instance_id
stringlengths 10
57
| patch
stringlengths 261
37.7k
| repo
stringlengths 7
53
| base_commit
stringlengths 40
40
| hints_text
stringclasses 301
values | test_patch
stringlengths 212
2.22M
| problem_statement
stringlengths 23
37.7k
| version
stringclasses 1
value | environment_setup_commit
stringlengths 40
40
| FAIL_TO_PASS
listlengths 1
4.94k
| PASS_TO_PASS
listlengths 0
7.82k
| meta
dict | created_at
stringlengths 25
25
| license
stringclasses 8
values | __index_level_0__
int64 0
6.41k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
globus__globus-cli-929
|
diff --git a/changelog.d/20240103_182435_sirosen_handle_non_dict_gcs_detail.md b/changelog.d/20240103_182435_sirosen_handle_non_dict_gcs_detail.md
new file mode 100644
index 0000000..75b9aba
--- /dev/null
+++ b/changelog.d/20240103_182435_sirosen_handle_non_dict_gcs_detail.md
@@ -0,0 +1,4 @@
+### Bugfixes
+
+* Fix the error handling when `globus gcs collection create guest` encounters a
+ non-session error.
diff --git a/src/globus_cli/commands/collection/create/guest.py b/src/globus_cli/commands/collection/create/guest.py
index d270c84..e89b864 100644
--- a/src/globus_cli/commands/collection/create/guest.py
+++ b/src/globus_cli/commands/collection/create/guest.py
@@ -197,7 +197,11 @@ def _is_session_timeout_error(e: globus_sdk.GCSAPIError) -> bool:
Detect session timeouts related to HA collections.
This is a hacky workaround until we have better GARE support across the CLI.
"""
- detail_type = getattr(e, "detail", {}).get("DATA_TYPE")
+ detail = getattr(e, "detail", {})
+ if not isinstance(detail, dict):
+ return False
+
+ detail_type = detail.get("DATA_TYPE")
return (
e.http_status == 403
and isinstance(detail_type, str)
|
globus/globus-cli
|
48f3fbae7eec36f32e606e7d65f7f2ce18648b95
|
diff --git a/tests/functional/collection/test_collection_create_guest.py b/tests/functional/collection/test_collection_create_guest.py
index d295755..e57392f 100644
--- a/tests/functional/collection/test_collection_create_guest.py
+++ b/tests/functional/collection/test_collection_create_guest.py
@@ -228,3 +228,44 @@ def test_guest_collection_create__when_session_times_out_against_ha_mapped_colle
assert "Session timeout detected; Re-authentication required." in result.stderr
assert f"globus login --gcs {endpoint_id} --force" in result.stderr
+
+
+def test_guest_collection_create__when_gcs_emits_unrecognized_error(
+ run_line,
+ mock_user_data,
+ add_gcs_login,
+):
+ meta = load_response_set("cli.collection_operations").metadata
+ mapped_collection_id = meta["mapped_collection_id"]
+ display_name = meta["guest_display_name"]
+ gcs_hostname = meta["gcs_hostname"]
+ endpoint_id = meta["endpoint_id"]
+ add_gcs_login(endpoint_id)
+
+ create_guest_collection_route = f"https://{gcs_hostname}/api/collections"
+ responses.replace(
+ "POST",
+ create_guest_collection_route,
+ status=403,
+ json={
+ "DATA_TYPE": "result#1.0.0",
+ "code": "permission_denied",
+ "detail": "oh noez!",
+ "has_next_page": False,
+ "http_response_code": 403,
+ "message": "Oh noez! You must authenticate much better!",
+ },
+ )
+
+ get_endpoint_route = (
+ f"{get_service_url('transfer')}v0.10/endpoint/{mapped_collection_id}"
+ )
+ get_endpoint_resp = requests.get(get_endpoint_route).json()
+ get_endpoint_resp["high_assurance"] = True
+ responses.replace("GET", get_endpoint_route, json=get_endpoint_resp)
+
+ params = f"{mapped_collection_id} /home/ '{display_name}'"
+ result = run_line(f"globus collection create guest {params}", assert_exit_code=1)
+
+ assert "Session timeout detected" not in result.stderr
+ assert "Oh noez! You must authenticate much better!" in result.stderr
|
Error with command: globus gcs collection create guest
Command generates error without much additional info.
Command:
globus gcs collection create guest --user-credential-id <credential ID> <collection ID> /path/to/shared_dir test
Error:
AttributeError: 'str' object has no attribute 'get'
|
0.0
|
48f3fbae7eec36f32e606e7d65f7f2ce18648b95
|
[
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_gcs_emits_unrecognized_error"
] |
[
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_missing_login",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_missing_consent",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_multiple_matching_user_credentials[True]",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_multiple_matching_user_credentials[False]",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_no_matching_user_credentials",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_mapped_collection_type_is_unsupported[EntityType.GCP_MAPPED]",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_mapped_collection_type_is_unsupported[EntityType.GCP_GUEST]",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_mapped_collection_type_is_unsupported[EntityType.GCSV5_ENDPOINT]",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_mapped_collection_type_is_unsupported[EntityType.GCSV5_GUEST]",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_mapped_collection_type_is_unsupported[EntityType.GCSV4_HOST]",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_mapped_collection_type_is_unsupported[EntityType.GCSV4_SHARE]",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_mapped_collection_type_is_unsupported[EntityType.UNRECOGNIZED]",
"tests/functional/collection/test_collection_create_guest.py::test_guest_collection_create__when_session_times_out_against_ha_mapped_collection"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-01-04 00:25:50+00:00
|
apache-2.0
| 2,535 |
|
globus__globus-sdk-python-143
|
diff --git a/globus_sdk/auth/client_types/native_client.py b/globus_sdk/auth/client_types/native_client.py
index 0f8da1d3..e2ab435e 100644
--- a/globus_sdk/auth/client_types/native_client.py
+++ b/globus_sdk/auth/client_types/native_client.py
@@ -46,7 +46,8 @@ class NativeAppAuthClient(AuthClient):
def oauth2_start_flow(
self, requested_scopes=None, redirect_uri=None,
- state='_default', verifier=None, refresh_tokens=False):
+ state='_default', verifier=None, refresh_tokens=False,
+ prefill_named_grant=None):
"""
Starts a Native App OAuth2 flow by instantiating a
:class:`GlobusNativeAppFlowManager
@@ -61,7 +62,8 @@ class NativeAppAuthClient(AuthClient):
self.current_oauth2_flow_manager = GlobusNativeAppFlowManager(
self, requested_scopes=requested_scopes,
redirect_uri=redirect_uri, state=state, verifier=verifier,
- refresh_tokens=refresh_tokens)
+ refresh_tokens=refresh_tokens,
+ prefill_named_grant=prefill_named_grant)
return self.current_oauth2_flow_manager
def oauth2_refresh_token(self, refresh_token):
diff --git a/globus_sdk/auth/oauth2_native_app.py b/globus_sdk/auth/oauth2_native_app.py
index b53f77a7..daa8f4d7 100644
--- a/globus_sdk/auth/oauth2_native_app.py
+++ b/globus_sdk/auth/oauth2_native_app.py
@@ -77,11 +77,14 @@ class GlobusNativeAppFlowManager(GlobusOAuthFlowManager):
``refresh_tokens`` (*bool*)
When True, request refresh tokens in addition to access tokens
+
+ ``prefill_named_grant`` (*string*)
+ Optionally prefill the named grant label on the consent page
"""
def __init__(self, auth_client, requested_scopes=None,
redirect_uri=None, state='_default', verifier=None,
- refresh_tokens=False):
+ refresh_tokens=False, prefill_named_grant=None):
self.auth_client = auth_client
# set client_id, then check for validity
@@ -109,6 +112,7 @@ class GlobusNativeAppFlowManager(GlobusOAuthFlowManager):
# store the remaining parameters directly, with no transformation
self.refresh_tokens = refresh_tokens
self.state = state
+ self.prefill_named_grant = prefill_named_grant
logger.debug('Starting Native App Flow with params:')
logger.debug('auth_client.client_id={}'.format(auth_client.client_id))
@@ -118,6 +122,10 @@ class GlobusNativeAppFlowManager(GlobusOAuthFlowManager):
logger.debug('requested_scopes={}'.format(self.requested_scopes))
logger.debug('verifier=<REDACTED>,challenge={}'.format(self.challenge))
+ if prefill_named_grant is not None:
+ logger.debug('prefill_named_grant={}'.format(
+ self.prefill_named_grant))
+
def get_authorize_url(self, additional_params=None):
"""
Start a Native App flow by getting the authorization URL to which users
@@ -153,6 +161,8 @@ class GlobusNativeAppFlowManager(GlobusOAuthFlowManager):
'code_challenge_method': 'S256',
'access_type': (self.refresh_tokens and 'offline') or 'online'
}
+ if self.prefill_named_grant is not None:
+ params['prefill_named_grant'] = self.prefill_named_grant
if additional_params:
params.update(additional_params)
|
globus/globus-sdk-python
|
35e55d84064d5a5ca7589c9d326c0abf5b153f69
|
diff --git a/tests/unit/test_oauth2_native_app.py b/tests/unit/test_oauth2_native_app.py
index 1403795d..0826a81f 100644
--- a/tests/unit/test_oauth2_native_app.py
+++ b/tests/unit/test_oauth2_native_app.py
@@ -81,6 +81,27 @@ class GlobusNativeAppFlowManagerTests(CapturedIOTestCase):
for param, value in params.items():
self.assertIn(param + "=" + value, param_url)
+ def test_prefill_named_grant(self):
+ """
+ Should add the `prefill_named_grant` query string parameter
+ to the authorize url.
+ """
+ flow_with_prefill = globus_sdk.auth.GlobusNativeAppFlowManager(
+ self.ac, requested_scopes="scopes", redirect_uri="uri",
+ state="state", verifier="verifier", prefill_named_grant="test")
+
+ authorize_url = flow_with_prefill.get_authorize_url()
+
+ self.assertIn('prefill_named_grant=test', authorize_url)
+
+ flow_without_prefill = globus_sdk.auth.GlobusNativeAppFlowManager(
+ self.ac, requested_scopes="scopes", redirect_uri="uri",
+ state="state", verifier="verifier")
+
+ authorize_url = flow_without_prefill.get_authorize_url()
+
+ self.assertNotIn('prefill_named_grant=', authorize_url)
+
def test_exchange_code_for_tokens(self):
"""
Makes a token exchange with the mock AuthClient,
|
Add `prefill_named_grant` support to NativeApp grant flow
Per globus/globus-cli#176 , there's an option to prefill the named grant label, `prefill_named_grant`. It's probably a string.
We need to support this so that the CLI and similar applications can use it.
Not considering this blocked on documentation.
|
0.0
|
35e55d84064d5a5ca7589c9d326c0abf5b153f69
|
[
"tests/unit/test_oauth2_native_app.py::GlobusNativeAppFlowManagerTests::test_prefill_named_grant"
] |
[
"tests/unit/test_oauth2_native_app.py::GlobusNativeAppFlowManagerTests::test_exchange_code_for_tokens",
"tests/unit/test_oauth2_native_app.py::GlobusNativeAppFlowManagerTests::test_get_authorize_url",
"tests/unit/test_oauth2_native_app.py::GlobusNativeAppFlowManagerTests::test_make_native_app_challenge"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-02-25 03:59:36+00:00
|
apache-2.0
| 2,536 |
|
globus__globus-sdk-python-172
|
diff --git a/globus_sdk/auth/client_types/base.py b/globus_sdk/auth/client_types/base.py
index 23cb7668..a9785bfe 100644
--- a/globus_sdk/auth/client_types/base.py
+++ b/globus_sdk/auth/client_types/base.py
@@ -223,6 +223,72 @@ class AuthClient(BaseClient):
form_data.update(additional_params)
return self.oauth2_token(form_data)
+ def oauth2_validate_token(self, token, additional_params=None):
+ """
+ Validate a token. It can be an Access Token or a Refresh token.
+
+ This call can be used to check tokens issued to your client,
+ confirming that they are or are not still valid. The resulting response
+ has the form ``{"active": True}`` when the token is valid, and
+ ``{"active": False}`` when it is not.
+
+ It is not necessary to validate tokens immediately after receiving them
+ from the service -- any tokens which you are issued will be valid at
+ that time. This is more for the purpose of doing checks like
+
+ - confirm that ``oauth2_revoke_token`` succeeded
+ - at application boot, confirm no need to do fresh login
+
+ **Parameters**
+
+ ``token`` (*string*)
+ The token which should be validated. Can be a refresh token or an
+ access token
+
+ ``additional_params`` (*dict*)
+ A ``dict`` or ``None``, which specifies additional
+ parameters to include in the validation body. Primarily for
+ internal use
+
+ **Examples**
+
+ Revoke a token and confirm that it is no longer active:
+
+ >>> from globus_sdk import ConfidentialAppAuthClient
+ >>> ac = ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET)
+ >>> ac.oauth2_revoke_token('<token_string>')
+ >>> data = ac.oauth2_validate_token('<token_string>')
+ >>> assert not data['active']
+
+ During application boot, check if the user needs to do a login, even
+ if a token is present:
+
+ >>> from globus_sdk import ConfidentialAppAuthClient
+ >>> ac = ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET)
+ >>> # this is not an SDK function, but a hypothetical function which
+ >>> # you use to load a token out of configuration data
+ >>> tok = load_token_from_config(...)
+ >>>
+ >>> if not tok or not ac.oauth2_validate_token(tok)['active']:
+ >>> # do_new_login() is another hypothetical helper
+ >>> tok = do_new_login()
+ >>> # at this point, tok is expected to be a valid token
+ """
+ self.logger.info('Validating token')
+ body = {'token': token}
+
+ # if this client has no way of authenticating itself but
+ # it does have a client_id, we'll send that in the request
+ no_authentication = (self.authorizer is None or
+ isinstance(self.authorizer, NullAuthorizer))
+ if no_authentication and self.client_id:
+ self.logger.debug('Validating token with unauthenticated client')
+ body.update({'client_id': self.client_id})
+
+ if additional_params:
+ body.update(additional_params)
+ return self.post('/v2/oauth2/token/validate', text_body=body)
+
def oauth2_revoke_token(self, token, additional_params=None):
"""
Revoke a token. It can be an Access Token or a Refresh token.
diff --git a/globus_sdk/auth/oauth2_authorization_code.py b/globus_sdk/auth/oauth2_authorization_code.py
index 0a359e88..df5141a0 100644
--- a/globus_sdk/auth/oauth2_authorization_code.py
+++ b/globus_sdk/auth/oauth2_authorization_code.py
@@ -3,7 +3,7 @@ from six.moves.urllib.parse import urlencode
from globus_sdk.base import slash_join
from globus_sdk.auth.oauth2_constants import DEFAULT_REQUESTED_SCOPES
-from globus_sdk.auth.oauth_flow_manager import GlobusOAuthFlowManager
+from globus_sdk.auth.oauth2_flow_manager import GlobusOAuthFlowManager
logger = logging.getLogger(__name__)
diff --git a/globus_sdk/auth/oauth_flow_manager.py b/globus_sdk/auth/oauth2_flow_manager.py
similarity index 100%
rename from globus_sdk/auth/oauth_flow_manager.py
rename to globus_sdk/auth/oauth2_flow_manager.py
diff --git a/globus_sdk/auth/oauth2_native_app.py b/globus_sdk/auth/oauth2_native_app.py
index b32bad8e..af646d6d 100644
--- a/globus_sdk/auth/oauth2_native_app.py
+++ b/globus_sdk/auth/oauth2_native_app.py
@@ -7,7 +7,7 @@ from six.moves.urllib.parse import urlencode
from globus_sdk.base import slash_join
from globus_sdk.auth.oauth2_constants import DEFAULT_REQUESTED_SCOPES
-from globus_sdk.auth.oauth_flow_manager import GlobusOAuthFlowManager
+from globus_sdk.auth.oauth2_flow_manager import GlobusOAuthFlowManager
logger = logging.getLogger(__name__)
diff --git a/globus_sdk/authorizers/client_credentials.py b/globus_sdk/authorizers/client_credentials.py
index f087c675..225ea426 100644
--- a/globus_sdk/authorizers/client_credentials.py
+++ b/globus_sdk/authorizers/client_credentials.py
@@ -64,14 +64,18 @@ class ClientCredentialsAuthorizer(RenewingAuthorizer):
super(ClientCredentialsAuthorizer, self).__init__(
access_token, expires_at, on_refresh)
- def _get_token_data(self):
+ def _get_token_response(self):
"""
- Make a client credentials grant, get the tokens .by_resource_server,
- Ensure that only one token was gotten, and return that token.
+ Make a client credentials grant
"""
- res = self.confidential_client.oauth2_client_credentials_tokens(
+ return self.confidential_client.oauth2_client_credentials_tokens(
requested_scopes=self.scopes)
+ def _extract_token_data(self, res):
+ """
+ Get the tokens .by_resource_server,
+ Ensure that only one token was gotten, and return that token.
+ """
token_data = res.by_resource_server.values()
if len(token_data) != 1:
raise ValueError(
diff --git a/globus_sdk/authorizers/refresh_token.py b/globus_sdk/authorizers/refresh_token.py
index ab21b7c8..6ca6e458 100644
--- a/globus_sdk/authorizers/refresh_token.py
+++ b/globus_sdk/authorizers/refresh_token.py
@@ -59,13 +59,17 @@ class RefreshTokenAuthorizer(RenewingAuthorizer):
super(RefreshTokenAuthorizer, self).__init__(
access_token, expires_at, on_refresh)
- def _get_token_data(self):
+ def _get_token_response(self):
"""
- Make a refresh token grant, get the tokens .by_resource_server,
- Ensure that only one token was gotten, and return that token.
+ Make a refresh token grant
"""
- res = self.auth_client.oauth2_refresh_token(self.refresh_token)
+ return self.auth_client.oauth2_refresh_token(self.refresh_token)
+ def _extract_token_data(self, res):
+ """
+ Get the tokens .by_resource_server,
+ Ensure that only one token was gotten, and return that token.
+ """
token_data = res.by_resource_server.values()
if len(token_data) != 1:
raise ValueError(
diff --git a/globus_sdk/authorizers/renewing.py b/globus_sdk/authorizers/renewing.py
index 80f513c2..8a47f22e 100644
--- a/globus_sdk/authorizers/renewing.py
+++ b/globus_sdk/authorizers/renewing.py
@@ -25,7 +25,8 @@ class RenewingAuthorizer(GlobusAuthorizer):
expiration time, callbacks on renewal, and 401 handling.
To make an authorizer that implements this class implement
- the _get_token_data method for that authorization type.
+ the _get_token_response and _extract_token_data methods for that
+ authorization type,
"""
def __init__(self, access_token=None, expires_at=None, on_refresh=None):
@@ -61,11 +62,17 @@ class RenewingAuthorizer(GlobusAuthorizer):
self._get_new_access_token()
@abc.abstractmethod
- def _get_token_data(self):
+ def _get_token_response(self):
"""
- Get the first element of token_response.by_resource_server using
- whatever flow or client or credentials the specific authorizer
- implementing this class uses.
+ Using whatever method the specific authorizer implementing this class
+ does, get a new token response.
+ """
+
+ @abc.abstractmethod
+ def _extract_token_data(self, res):
+ """
+ Given a token response object, get the first element of
+ token_response.by_resource_server
This method is expected to enforce that by_resource_server is only
returning one access token, and return a ValueError otherwise.
"""
@@ -81,11 +88,12 @@ class RenewingAuthorizer(GlobusAuthorizer):
def _get_new_access_token(self):
"""
- Given token data from _get_token_data,
+ Given token data from _get_token_response and _extract_token_data,
set the access token and expiration time, and call on_refresh
"""
- # get the first (and only) item from this iterable
- token_data = self._get_token_data()
+ # get the first (and only) token
+ res = self._get_token_response()
+ token_data = self._extract_token_data(res)
self._set_expiration_time(token_data['expires_at_seconds'])
self.access_token = token_data['access_token']
@@ -95,7 +103,7 @@ class RenewingAuthorizer(GlobusAuthorizer):
.format(self.access_token[-5:]))
if callable(self.on_refresh):
- self.on_refresh(token_data)
+ self.on_refresh(res)
logger.debug("Invoked on_refresh callback")
def _check_expiration_time(self):
|
globus/globus-sdk-python
|
e8d18bbdd34cc80d4fb96aded70a53e96ca252c7
|
diff --git a/tests/unit/test_client_credentials_authorizer.py b/tests/unit/test_client_credentials_authorizer.py
index 498d1ccf..06212b1a 100644
--- a/tests/unit/test_client_credentials_authorizer.py
+++ b/tests/unit/test_client_credentials_authorizer.py
@@ -40,15 +40,15 @@ class ClientCredentialsAuthorizerTests(CapturedIOTestCase):
self.cac, self.scopes, access_token=self.access_token,
expires_at=self.expires_at)
- def test_get_token_data(self):
+ def test_get_token_response(self):
"""
- Calls _get_token_data, confirms that the mock
+ Calls _get_token_response, confirms that the mock
ConfidentialAppAuthClient is used and the known data was returned.
"""
# get new_access_token
- res = self.authorizer._get_token_data()
+ res = self.authorizer._get_token_response()
# confirm expected response
- self.assertEqual(res, self.rs_data)
+ self.assertEqual(res, self.response)
# confirm mock ConfidentailAppAuthClient was used as expected
self.cac.oauth2_client_credentials_tokens.assert_called_once_with(
requested_scopes=self.scopes)
@@ -56,7 +56,8 @@ class ClientCredentialsAuthorizerTests(CapturedIOTestCase):
def test_multiple_resource_servers(self):
"""
Sets the mock ConfidentialAppAuthClient to return multiple resource
- servers. Confirms GlobusError is raised when _get_token_data is called.
+ servers. Confirms GlobusError is raised when _extract_token_data is
+ called.
"""
self.response.by_resource_server = {
"rs1": {
@@ -69,7 +70,7 @@ class ClientCredentialsAuthorizerTests(CapturedIOTestCase):
}
}
with self.assertRaises(ValueError) as err:
- self.authorizer._get_token_data()
+ self.authorizer._extract_token_data(self.response)
self.assertIn("didn't return exactly one token", str(err.exception))
self.assertIn(self.scopes, str(err.exception))
diff --git a/tests/unit/test_refresh_token_authorizer.py b/tests/unit/test_refresh_token_authorizer.py
index e6978071..cbf720e5 100644
--- a/tests/unit/test_refresh_token_authorizer.py
+++ b/tests/unit/test_refresh_token_authorizer.py
@@ -38,15 +38,15 @@ class RefreshTokenAuthorizerTests(CapturedIOTestCase):
self.refresh_token, self.ac, access_token=self.access_token,
expires_at=self.expires_at)
- def test_get_token_data(self):
+ def test_get_token_response(self):
"""
- Calls _get_token_data, confirms that the mock
+ Calls _get_token_response, confirms that the mock
AuthClient is used and the known data was returned.
"""
# get new_access_token
- res = self.authorizer._get_token_data()
+ res = self.authorizer._get_token_response()
# confirm expected response
- self.assertEqual(res, self.rs_data)
+ self.assertEqual(res, self.response)
# confirm mock ConfidentailAppAuthClient was used as expected
self.ac.oauth2_refresh_token.assert_called_once_with(
self.refresh_token)
@@ -54,7 +54,8 @@ class RefreshTokenAuthorizerTests(CapturedIOTestCase):
def test_multiple_resource_servers(self):
"""
Sets the mock ConfidentialAppAuthClient to return multiple resource
- servers. Confirms GlobusError is raised when _get_token_data is called.
+ servers. Confirms GlobusError is raised when _extract_token_data is
+ called.
"""
self.response.by_resource_server = {
"rs1": {
@@ -67,5 +68,5 @@ class RefreshTokenAuthorizerTests(CapturedIOTestCase):
}
}
with self.assertRaises(ValueError) as err:
- self.authorizer._get_token_data()
+ self.authorizer._extract_token_data(self.response)
self.assertIn("didn't return exactly one token", str(err.exception))
diff --git a/tests/unit/test_renewing_authorizer.py b/tests/unit/test_renewing_authorizer.py
index 702165b2..c3146b93 100644
--- a/tests/unit/test_renewing_authorizer.py
+++ b/tests/unit/test_renewing_authorizer.py
@@ -11,14 +11,18 @@ from tests.framework import CapturedIOTestCase
class MockRenewer(RenewingAuthorizer):
"""
- Class that implements RenewingAuthorizer so that _get_token_data
- can return known values for testing
+ Class that implements RenewingAuthorizer so that _get_token_response and
+ _extract_token_data can return known values for testing
"""
def __init__(self, token_data, **kwargs):
self.token_data = token_data
+ self.token_response = mock.Mock()
super(MockRenewer, self).__init__(**kwargs)
- def _get_token_data(self):
+ def _get_token_response(self):
+ return self.token_response
+
+ def _extract_token_data(self, res):
return self.token_data
|
Add validate_token to AuthClient
As soon as this is added to the docs site, we should add this to either `AuthClient` or `ConfidentialAppAuthClient`.
We should wait for the docs to be updated so that we can put a proper `External Documentation` section into the docstring.
@mattias-lidman or @bjmc, can you confirm that this does or does not work for Native App clients?
I would assume that, like introspect, it requires an ID and secret.
If this is the superior call for basic validity checking, we should be sure to update the docstring on introspect to recommend using it instead where possible.
|
0.0
|
e8d18bbdd34cc80d4fb96aded70a53e96ca252c7
|
[
"tests/unit/test_client_credentials_authorizer.py::ClientCredentialsAuthorizerTests::test_get_token_response",
"tests/unit/test_client_credentials_authorizer.py::ClientCredentialsAuthorizerTests::test_multiple_resource_servers",
"tests/unit/test_refresh_token_authorizer.py::RefreshTokenAuthorizerTests::test_get_token_response",
"tests/unit/test_refresh_token_authorizer.py::RefreshTokenAuthorizerTests::test_multiple_resource_servers",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_check_expiration_time_expired",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_check_expiration_time_no_expiration",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_check_expiration_time_no_token",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_check_expiration_time_valid",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_get_new_access_token",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_handle_missing_authorization",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_init",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_authorization_header",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_authorization_header_existing",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_authorization_header_expired",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_authorization_header_no_expires",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_authorization_header_no_token",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_expiration_time"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-04-04 17:54:44+00:00
|
apache-2.0
| 2,537 |
|
globus__globus-sdk-python-185
|
diff --git a/docs/examples/native_app.rst b/docs/examples/native_app.rst
index 27b0b239..9f39b8ec 100644
--- a/docs/examples/native_app.rst
+++ b/docs/examples/native_app.rst
@@ -1,3 +1,5 @@
+.. _examples_native_app_login:
+
Native App Login
----------------
diff --git a/docs/examples/three_legged_oauth.rst b/docs/examples/three_legged_oauth.rst
index 5a98e408..ca36ef65 100644
--- a/docs/examples/three_legged_oauth.rst
+++ b/docs/examples/three_legged_oauth.rst
@@ -1,3 +1,5 @@
+.. _examples_three_legged_oauth_login:
+
Three Legged OAuth with Flask
-----------------------------
diff --git a/globus_sdk/auth/client_types/confidential_client.py b/globus_sdk/auth/client_types/confidential_client.py
index 6126ada7..fa920c42 100644
--- a/globus_sdk/auth/client_types/confidential_client.py
+++ b/globus_sdk/auth/client_types/confidential_client.py
@@ -1,4 +1,6 @@
import logging
+import six
+
from globus_sdk.base import merge_params
from globus_sdk.authorizers import BasicAuthorizer
from globus_sdk.auth.oauth2_constants import DEFAULT_REQUESTED_SCOPES
@@ -72,6 +74,9 @@ class ConfidentialAppAuthClient(AuthClient):
"""
self.logger.info('Fetching token(s) using client credentials')
requested_scopes = requested_scopes or DEFAULT_REQUESTED_SCOPES
+ # convert scopes iterable to string immediately on load
+ if not isinstance(requested_scopes, six.string_types):
+ requested_scopes = " ".join(requested_scopes)
return self.oauth2_token({
'grant_type': 'client_credentials',
@@ -81,12 +86,43 @@ class ConfidentialAppAuthClient(AuthClient):
self, redirect_uri, requested_scopes=None,
state='_default', refresh_tokens=False):
"""
- Starts an Authorization Code OAuth2 flow by instantiating a
+ Starts or resumes an Authorization Code OAuth2 flow.
+
+ Under the hood, this is done by instantiating a
:class:`GlobusAuthorizationCodeFlowManager
<globus_sdk.auth.GlobusAuthorizationCodeFlowManager>`
- All of the parameters to this method are passed to that class's
- initializer verbatim.
+ **Parameters**
+
+ ``redirect_uri`` (*string*)
+ The page that users should be directed to after authenticating at
+ the authorize URL. Required.
+
+ ``requested_scopes`` (*iterable* or *string*)
+ The scopes on the token(s) being requested, as a space-separated
+ string or an iterable of strings. Defaults to ``openid profile
+ email urn:globus:auth:scope:transfer.api.globus.org:all``
+
+ ``state`` (*string*)
+ This is a way of your application passing information back to
+ itself in the course of the OAuth flow. Because the user will
+ navigate away from your application to complete the flow, this
+ parameter lets you pass an arbitrary string from the starting
+ page to the ``redirect_uri``
+
+ ``refresh_tokens`` (*bool*)
+ When True, request refresh tokens in addition to access tokens
+
+ **Examples**
+
+ You can see an example of this flow :ref:`in the usage examples
+ <examples_three_legged_oauth_login>`
+
+ **External Documentation**
+
+ The Authorization Code Grant flow is described
+ `in the Globus Auth Specification \
+ <https://docs.globus.org/api/auth/developer-guide/#obtaining-authorization>`_
"""
self.logger.info('Starting OAuth2 Authorization Code Grant Flow')
self.current_oauth2_flow_manager = GlobusAuthorizationCodeFlowManager(
diff --git a/globus_sdk/auth/client_types/native_client.py b/globus_sdk/auth/client_types/native_client.py
index 818269ab..20f55c58 100644
--- a/globus_sdk/auth/client_types/native_client.py
+++ b/globus_sdk/auth/client_types/native_client.py
@@ -40,14 +40,59 @@ class NativeAppAuthClient(AuthClient):
state='_default', verifier=None, refresh_tokens=False,
prefill_named_grant=None):
"""
- Starts a Native App OAuth2 flow by instantiating a
+ Starts a Native App OAuth2 flow.
+
+ This is done internally by instantiating a
:class:`GlobusNativeAppFlowManager
<globus_sdk.auth.GlobusNativeAppFlowManager>`
- All of the parameters to this method are passed to that class's
- initializer verbatim.
+ While the flow is in progress, the ``NativeAppAuthClient`` becomes
+ non thread-safe as temporary state is stored during the flow.
+
+ **Parameters**
+
+ ``requested_scopes`` (*iterable* or *string*)
+ The scopes on the token(s) being requested, as a space-separated
+ string or iterable of strings. Defaults to ``openid profile email
+ urn:globus:auth:scope:transfer.api.globus.org:all``
+
+ ``redirect_uri`` (*string*)
+ The page that users should be directed to after authenticating at
+ the authorize URL. Defaults to
+ 'https://auth.globus.org/v2/web/auth-code', which displays the
+ resulting ``auth_code`` for users to copy-paste back into your
+ application (and thereby be passed back to the
+ ``GlobusNativeAppFlowManager``)
+
+ ``state`` (*string*)
+ Typically is not meaningful in the Native App Grant flow, but you
+ may have a specialized use case for it. The ``redirect_uri`` page
+ will have this included in a query parameter, so you can use it
+ to pass information to that page. It defaults to the string
+ '_default'
+
+ ``verifier`` (*string*)
+ A secret used for the Native App flow. It will by default be a
+ freshly generated random string, known only to this
+ ``GlobusNativeAppFlowManager`` instance
+
+ ``refresh_tokens`` (*bool*)
+ When True, request refresh tokens in addition to access tokens
+
+ ``prefill_named_grant`` (*string*)
+ Optionally prefill the named grant label on the consent page
+
+ **Examples**
+
+ You can see an example of this flow :ref:`in the usage examples
+ <examples_native_app_login>`
+
+ **External Documentation**
- #notthreadsafe
+ The Globus Auth specification for Native App grants details the
+ modifications to the Authorization Code grant flow as
+ `The PKCE Security Protocol \
+ <https://docs.globus.org/api/auth/developer-guide/#pkce>`_
"""
self.logger.info('Starting Native App Grant Flow')
self.current_oauth2_flow_manager = GlobusNativeAppFlowManager(
diff --git a/globus_sdk/auth/oauth2_authorization_code.py b/globus_sdk/auth/oauth2_authorization_code.py
index df5141a0..8a9b312b 100644
--- a/globus_sdk/auth/oauth2_authorization_code.py
+++ b/globus_sdk/auth/oauth2_authorization_code.py
@@ -1,4 +1,5 @@
import logging
+import six
from six.moves.urllib.parse import urlencode
from globus_sdk.base import slash_join
@@ -34,9 +35,9 @@ class GlobusAuthorizationCodeFlowManager(GlobusOAuthFlowManager):
The page that users should be directed to after authenticating at the
authorize URL. Required.
- ``requested_scopes`` (*string*)
+ ``requested_scopes`` (*iterable* or *string*)
The scopes on the token(s) being requested, as a space-separated
- string. Defaults to ``openid profile email
+ string or an iterable of strings. Defaults to ``openid profile email
urn:globus:auth:scope:transfer.api.globus.org:all``
``state`` (*string*)
@@ -55,6 +56,9 @@ class GlobusAuthorizationCodeFlowManager(GlobusOAuthFlowManager):
refresh_tokens=False):
# default to the default requested scopes
self.requested_scopes = requested_scopes or DEFAULT_REQUESTED_SCOPES
+ # convert scopes iterable to string immediately on load
+ if not isinstance(self.requested_scopes, six.string_types):
+ self.requested_scopes = " ".join(self.requested_scopes)
# store the remaining parameters directly, with no transformation
self.client_id = auth_client.client_id
diff --git a/globus_sdk/auth/oauth2_constants.py b/globus_sdk/auth/oauth2_constants.py
index e92902eb..fb3fce16 100644
--- a/globus_sdk/auth/oauth2_constants.py
+++ b/globus_sdk/auth/oauth2_constants.py
@@ -2,5 +2,5 @@ __all__ = ['DEFAULT_REQUESTED_SCOPES']
DEFAULT_REQUESTED_SCOPES = (
- 'openid profile email '
+ 'openid', 'profile', 'email',
'urn:globus:auth:scope:transfer.api.globus.org:all')
diff --git a/globus_sdk/auth/oauth2_native_app.py b/globus_sdk/auth/oauth2_native_app.py
index af646d6d..f42b38dc 100644
--- a/globus_sdk/auth/oauth2_native_app.py
+++ b/globus_sdk/auth/oauth2_native_app.py
@@ -3,6 +3,7 @@ import hashlib
import base64
import re
import os
+import six
from six.moves.urllib.parse import urlencode
from globus_sdk.base import slash_join
@@ -72,9 +73,9 @@ class GlobusNativeAppFlowManager(GlobusOAuthFlowManager):
used to extract default values for the flow, and also to make calls
to the Auth service. This SHOULD be a ``NativeAppAuthClient``
- ``requested_scopes`` (*string*)
+ ``requested_scopes`` (*iterable* or *string*)
The scopes on the token(s) being requested, as a space-separated
- string. Defaults to ``openid profile email
+ string or iterable of strings. Defaults to ``openid profile email
urn:globus:auth:scope:transfer.api.globus.org:all``
``redirect_uri`` (*string*)
@@ -99,7 +100,7 @@ class GlobusNativeAppFlowManager(GlobusOAuthFlowManager):
``refresh_tokens`` (*bool*)
When True, request refresh tokens in addition to access tokens
- ``prefill_named_grant`` (*string*)
+ ``prefill_named_grant`` (*string*)
Optionally prefill the named grant label on the consent page
"""
@@ -119,6 +120,9 @@ class GlobusNativeAppFlowManager(GlobusOAuthFlowManager):
# default to the default requested scopes
self.requested_scopes = requested_scopes or DEFAULT_REQUESTED_SCOPES
+ # convert scopes iterable to string immediately on load
+ if not isinstance(self.requested_scopes, six.string_types):
+ self.requested_scopes = " ".join(self.requested_scopes)
# default to `/v2/web/auth-code` on whatever environment we're looking
# at -- most typically it will be `https://auth.globus.org/`
|
globus/globus-sdk-python
|
4cf08b26180d62ecef6b605c9df10ede9ebef681
|
diff --git a/tests/integration/test_auth_client_flow.py b/tests/integration/test_auth_client_flow.py
index c6e8ffa3..4ca019d8 100644
--- a/tests/integration/test_auth_client_flow.py
+++ b/tests/integration/test_auth_client_flow.py
@@ -27,7 +27,8 @@ class AuthClientIntegrationTests(CapturedIOTestCase):
"client_id=" + ac.client_id,
"redirect_uri=" +
quote_plus(ac.base_url + "v2/web/auth-code"),
- "scope=" + quote_plus(DEFAULT_REQUESTED_SCOPES),
+ "scope=" + quote_plus(
+ " ".join(DEFAULT_REQUESTED_SCOPES)),
"state=" + "_default",
"response_type=" + "code",
"code_challenge=" +
@@ -76,7 +77,8 @@ class AuthClientIntegrationTests(CapturedIOTestCase):
expected_vals = [ac.base_url + "v2/oauth2/authorize?",
"client_id=" + ac.client_id,
"redirect_uri=" + "uri",
- "scope=" + quote_plus(DEFAULT_REQUESTED_SCOPES),
+ "scope=" + quote_plus(
+ " ".join(DEFAULT_REQUESTED_SCOPES)),
"state=" + "_default",
"response_type=" + "code",
"access_type=" + "online"]
diff --git a/tests/integration/test_confidential_client_flow.py b/tests/integration/test_confidential_client_flow.py
index e7039e44..d713c741 100644
--- a/tests/integration/test_confidential_client_flow.py
+++ b/tests/integration/test_confidential_client_flow.py
@@ -31,7 +31,8 @@ class ConfidentialAppAuthClientIntegrationTests(CapturedIOTestCase):
flow = self.cac.oauth2_start_flow("uri")
self.assertIsInstance(flow, GlobusAuthorizationCodeFlowManager)
self.assertEqual(flow.redirect_uri, "uri")
- self.assertEqual(flow.requested_scopes, DEFAULT_REQUESTED_SCOPES)
+ self.assertEqual(flow.requested_scopes,
+ " ".join(DEFAULT_REQUESTED_SCOPES))
self.assertEqual(flow.state, "_default")
self.assertFalse(flow.refresh_tokens)
@@ -40,7 +41,8 @@ class ConfidentialAppAuthClientIntegrationTests(CapturedIOTestCase):
expected_vals = [self.cac.base_url + "v2/oauth2/authorize?",
"client_id=" + self.cac.client_id,
"redirect_uri=" + "uri",
- "scope=" + quote_plus(DEFAULT_REQUESTED_SCOPES),
+ "scope=" + quote_plus(
+ " ".join(DEFAULT_REQUESTED_SCOPES)),
"state=" + "_default",
"access_type=" + "online"]
for val in expected_vals:
diff --git a/tests/integration/test_native_client_flow.py b/tests/integration/test_native_client_flow.py
index c07a8c40..6d7d42a2 100644
--- a/tests/integration/test_native_client_flow.py
+++ b/tests/integration/test_native_client_flow.py
@@ -31,7 +31,8 @@ class NativeAppAuthClientIntegrationTests(CapturedIOTestCase):
self.assertIsInstance(flow, GlobusNativeAppFlowManager)
self.assertEqual(flow.redirect_uri,
self.nac.base_url + "v2/web/auth-code")
- self.assertEqual(flow.requested_scopes, DEFAULT_REQUESTED_SCOPES)
+ self.assertEqual(flow.requested_scopes,
+ " ".join(DEFAULT_REQUESTED_SCOPES))
self.assertEqual(flow.state, "_default")
self.assertFalse(flow.refresh_tokens)
@@ -41,7 +42,8 @@ class NativeAppAuthClientIntegrationTests(CapturedIOTestCase):
"client_id=" + self.nac.client_id,
"redirect_uri=" +
quote_plus(self.nac.base_url + "v2/web/auth-code"),
- "scope=" + quote_plus(DEFAULT_REQUESTED_SCOPES),
+ "scope=" + quote_plus(
+ " ".join(DEFAULT_REQUESTED_SCOPES)),
"state=" + "_default",
"code_challenge=" + quote_plus(flow.challenge),
"access_type=" + "online"]
diff --git a/tests/unit/test_confidential_client.py b/tests/unit/test_confidential_client.py
index 3346ba96..a6b1059d 100644
--- a/tests/unit/test_confidential_client.py
+++ b/tests/unit/test_confidential_client.py
@@ -1,3 +1,8 @@
+try:
+ import mock
+except ImportError:
+ from unittest import mock
+
import globus_sdk
from tests.framework import CapturedIOTestCase, get_client_data
from globus_sdk.exc import GlobusAPIError
@@ -28,7 +33,14 @@ class ConfidentialAppAuthClientTests(CapturedIOTestCase):
Confirm tokens allow use of userinfo for the client
Returns access_token for testing
"""
- token_res = self.cac.oauth2_client_credentials_tokens()
+ with mock.patch.object(self.cac, 'oauth2_token',
+ side_effect=self.cac.oauth2_token) as m:
+ token_res = self.cac.oauth2_client_credentials_tokens(
+ requested_scopes="openid profile")
+ m.assert_called_once_with(
+ {"grant_type": "client_credentials",
+ "scope": "openid profile"})
+
# validate results
self.assertIn("access_token", token_res)
self.assertIn("expires_in", token_res)
diff --git a/tests/unit/test_oauth2_authorization_code.py b/tests/unit/test_oauth2_authorization_code.py
index 5c531719..5c634b91 100644
--- a/tests/unit/test_oauth2_authorization_code.py
+++ b/tests/unit/test_oauth2_authorization_code.py
@@ -18,10 +18,16 @@ class GlobusAuthorizationCodeFlowManagerTests(CapturedIOTestCase):
self.ac = mock.Mock()
self.ac.client_id = "client_id"
self.ac.base_url = "base_url/"
- self.flow_manager = globus_sdk.auth.GlobusNativeAppFlowManager(
+ self.flow_manager = globus_sdk.auth.GlobusAuthorizationCodeFlowManager(
self.ac, requested_scopes="scopes", redirect_uri="uri",
state="state")
+ def test_init_handles_iterable_scopes(self):
+ flow_manager = globus_sdk.auth.GlobusAuthorizationCodeFlowManager(
+ self.ac, requested_scopes=["scope1", "scope2"], redirect_uri="uri",
+ state="state")
+ self.assertEquals(flow_manager.requested_scopes, "scope1 scope2")
+
def test_get_authorize_url(self):
"""
Creates an authorize url, confirms results match object values
@@ -55,9 +61,7 @@ class GlobusAuthorizationCodeFlowManagerTests(CapturedIOTestCase):
auth_code = "code"
self.flow_manager.exchange_code_for_tokens(auth_code)
- expected = {"client_id": self.ac.client_id,
- "grant_type": "authorization_code",
+ expected = {"grant_type": "authorization_code",
"code": auth_code.encode("utf-8"),
- "code_verifier": self.flow_manager.verifier,
"redirect_uri": self.flow_manager.redirect_uri}
self.ac.oauth2_token.assert_called_with(expected)
diff --git a/tests/unit/test_oauth2_native_app.py b/tests/unit/test_oauth2_native_app.py
index fb060c90..0782c1ae 100644
--- a/tests/unit/test_oauth2_native_app.py
+++ b/tests/unit/test_oauth2_native_app.py
@@ -26,6 +26,13 @@ class GlobusNativeAppFlowManagerTests(CapturedIOTestCase):
self.ac, requested_scopes="scopes", redirect_uri="uri",
state="state")
+ def test_init_handles_iterable_scopes(self):
+ flow_manager = globus_sdk.auth.GlobusNativeAppFlowManager(
+ self.ac, requested_scopes=set(("scope1", "scope2")),
+ redirect_uri="uri", state="state")
+ self.assertIn(flow_manager.requested_scopes, ("scope1 scope2",
+ "scope2 scope1"))
+
def test_make_native_app_challenge(self):
"""
Makes native app challenge with and without verifier,
|
Make requested_scopes accept (in all contexts) an iterable of strings
Right now, we're requiring that people give us a space-delimited string.
Many people have pointed out that it's awkward / uncomfortable.
Wouldn't it be great if we could take tuples and lists? Yes, yes it would.
This shouldn't be too hard.
|
0.0
|
4cf08b26180d62ecef6b605c9df10ede9ebef681
|
[
"tests/integration/test_auth_client_flow.py::AuthClientIntegrationTests::test_oauth2_get_authorize_url_confidential",
"tests/integration/test_auth_client_flow.py::AuthClientIntegrationTests::test_oauth2_get_authorize_url_native",
"tests/unit/test_oauth2_authorization_code.py::GlobusAuthorizationCodeFlowManagerTests::test_init_handles_iterable_scopes",
"tests/unit/test_oauth2_native_app.py::GlobusNativeAppFlowManagerTests::test_init_handles_iterable_scopes"
] |
[
"tests/integration/test_auth_client_flow.py::AuthClientIntegrationTests::test_oauth2_exchange_code_for_tokens_confidential",
"tests/unit/test_confidential_client.py::ConfidentialAppAuthClientTests::test_oauth2_client_credentials_tokens",
"tests/unit/test_confidential_client.py::ConfidentialAppAuthClientTests::test_oauth2_get_dependent_tokens",
"tests/unit/test_confidential_client.py::ConfidentialAppAuthClientTests::test_oauth2_token_introspect",
"tests/unit/test_oauth2_authorization_code.py::GlobusAuthorizationCodeFlowManagerTests::test_exchange_code_for_tokens",
"tests/unit/test_oauth2_authorization_code.py::GlobusAuthorizationCodeFlowManagerTests::test_get_authorize_url",
"tests/unit/test_oauth2_native_app.py::GlobusNativeAppFlowManagerTests::test_exchange_code_for_tokens",
"tests/unit/test_oauth2_native_app.py::GlobusNativeAppFlowManagerTests::test_get_authorize_url",
"tests/unit/test_oauth2_native_app.py::GlobusNativeAppFlowManagerTests::test_make_native_app_challenge",
"tests/unit/test_oauth2_native_app.py::GlobusNativeAppFlowManagerTests::test_make_native_app_challenge_invalid_verifier",
"tests/unit/test_oauth2_native_app.py::GlobusNativeAppFlowManagerTests::test_prefill_named_grant"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-04-13 16:06:34+00:00
|
apache-2.0
| 2,538 |
|
globus__globus-sdk-python-251
|
diff --git a/globus_sdk/authorizers/basic.py b/globus_sdk/authorizers/basic.py
index 83b49204..23475f24 100644
--- a/globus_sdk/authorizers/basic.py
+++ b/globus_sdk/authorizers/basic.py
@@ -1,7 +1,7 @@
import logging
-import base64
from globus_sdk.authorizers.base import GlobusAuthorizer
+from globus_sdk.utils import safe_b64encode
logger = logging.getLogger(__name__)
@@ -27,9 +27,8 @@ class BasicAuthorizer(GlobusAuthorizer):
self.username = username
self.password = password
- encoded = base64.b64encode(
- bytes("{0}:{1}".format(username, password).encode("utf-8")))
- self.header_val = "Basic %s" % encoded.decode('utf-8')
+ to_b64 = '{0}:{1}'.format(username, password)
+ self.header_val = "Basic %s" % safe_b64encode(to_b64)
def set_authorization_header(self, header_dict):
"""
diff --git a/globus_sdk/utils/__init__.py b/globus_sdk/utils/__init__.py
new file mode 100644
index 00000000..52c09c7b
--- /dev/null
+++ b/globus_sdk/utils/__init__.py
@@ -0,0 +1,6 @@
+from globus_sdk.utils.string_handling import safe_b64encode
+
+
+__all__ = [
+ 'safe_b64encode'
+]
diff --git a/globus_sdk/utils/string_handling.py b/globus_sdk/utils/string_handling.py
new file mode 100644
index 00000000..c2a9648d
--- /dev/null
+++ b/globus_sdk/utils/string_handling.py
@@ -0,0 +1,10 @@
+from base64 import b64encode
+
+
+def safe_b64encode(s):
+ try:
+ encoded = b64encode(s.encode('utf-8'))
+ except UnicodeDecodeError:
+ encoded = b64encode(s)
+
+ return encoded.decode('utf-8')
|
globus/globus-sdk-python
|
fed7e9a31d4a3f2c3c9cb78794ee8e9b9a3b76a4
|
diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py
new file mode 100644
index 00000000..c459e6aa
--- /dev/null
+++ b/tests/unit/test_utils.py
@@ -0,0 +1,19 @@
+# coding=utf-8
+import unittest
+
+from globus_sdk import utils
+
+
+class TestUtils(unittest.TestCase):
+
+ def test_safe_b64encode_non_ascii(self):
+ test_string = 'ⓤⓢⓔⓡⓝⓐⓜⓔ'
+ expected_b64 = '4pOk4pOi4pOU4pOh4pOd4pOQ4pOc4pOU'
+
+ self.assertEqual(utils.safe_b64encode(test_string), expected_b64)
+
+ def test_safe_b64encode_ascii(self):
+ test_string = 'username'
+ expected_b64 = 'dXNlcm5hbWU='
+
+ self.assertEqual(utils.safe_b64encode(test_string), expected_b64)
|
BasicAuthorizer won't accept non-ascii username or password
Under Python 2.7.12:
```python
from globus_sdk.authorizers import BasicAuthorizer
nonascii = 'テ'
BasicAuthorizer('myusername', nonascii)
# UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 11: ordinal not in range(128)
```
|
0.0
|
fed7e9a31d4a3f2c3c9cb78794ee8e9b9a3b76a4
|
[
"tests/unit/test_utils.py::TestUtils::test_safe_b64encode_ascii",
"tests/unit/test_utils.py::TestUtils::test_safe_b64encode_non_ascii"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-11-27 22:37:18+00:00
|
apache-2.0
| 2,539 |
|
globus__globus-sdk-python-261
|
diff --git a/globus_sdk/auth/token_response.py b/globus_sdk/auth/token_response.py
index 8b50dba3..65c8688e 100644
--- a/globus_sdk/auth/token_response.py
+++ b/globus_sdk/auth/token_response.py
@@ -2,6 +2,7 @@ import logging
import json
import requests
import time
+import six
import jwt
@@ -24,10 +25,71 @@ def _convert_token_info_dict(source_dict):
'access_token': source_dict['access_token'],
'refresh_token': source_dict.get('refresh_token'),
'token_type': source_dict.get('token_type'),
- 'expires_at_seconds': int(time.time() + expires_in)
+ 'expires_at_seconds': int(time.time() + expires_in),
+ 'resource_server': source_dict['resource_server']
}
+class _ByScopesGetter(object):
+ """
+ A fancy dict-like object for looking up token data by scope name.
+ Allows usage like
+
+ >>> tokens = OAuthTokenResponse(...)
+ >>> tok = tokens.by_scopes['openid profile']['access_token']
+ """
+ def __init__(self, scope_map):
+ self.scope_map = scope_map
+
+ def __str__(self):
+ return json.dumps(self.scope_map)
+
+ def __iter__(self):
+ """iteration gets you every individual scope"""
+ return iter(self.scope_map.keys())
+
+ def __getitem__(self, scopename):
+ if not isinstance(scopename, six.string_types):
+ raise KeyError('by_scopes cannot contain non-string value "{}"'
+ .format(scopename))
+
+ # split on spaces
+ scopes = scopename.split()
+ # collect every matching token in a set to dedup
+ # but collect actual results (dicts) in a list
+ rs_names = set()
+ toks = []
+ for scope in scopes:
+ try:
+ rs_names.add(self.scope_map[scope]['resource_server'])
+ toks.append(self.scope_map[scope])
+ except KeyError:
+ raise KeyError(('Scope specifier "{}" contains scope "{}" '
+ "which was not found"
+ ).format(scopename, scope))
+ # if there isn't exactly 1 token, it's an error
+ if len(rs_names) != 1:
+ raise KeyError(
+ 'Scope specifier "{}" did not match exactly one token!'
+ .format(scopename))
+ # pop the only element in the set
+ return toks.pop()
+
+ def __contains__(self, item):
+ """
+ contains is driven by checking against getitem
+ that way, the definitions are always "in sync" if we update them in
+ the future
+ """
+ try:
+ self.__getitem__(item)
+ return True
+ except KeyError:
+ pass
+
+ return False
+
+
class OAuthTokenResponse(GlobusHTTPResponse):
"""
Class for responses from the OAuth2 code for tokens exchange used in
@@ -36,11 +98,20 @@ class OAuthTokenResponse(GlobusHTTPResponse):
def __init__(self, *args, **kwargs):
GlobusHTTPResponse.__init__(self, *args, **kwargs)
self._init_rs_dict()
+ self._init_scopes_getter()
+
+ def _init_scopes_getter(self):
+ scope_map = {}
+ for rs, tok_data in self._by_resource_server.items():
+ for s in tok_data["scope"].split():
+ scope_map[s] = tok_data
+ self._by_scopes = _ByScopesGetter(scope_map)
def _init_rs_dict(self):
# call the helper at the top level
self._by_resource_server = {
- self['resource_server']: _convert_token_info_dict(self)}
+ self['resource_server']: _convert_token_info_dict(self)
+ }
# call the helper on everything in 'other_tokens'
self._by_resource_server.update(dict(
(unprocessed_item['resource_server'],
@@ -59,6 +130,29 @@ class OAuthTokenResponse(GlobusHTTPResponse):
"""
return self._by_resource_server
+ @property
+ def by_scopes(self):
+ """
+ Representation of the token response in a dict-like object indexed by
+ scope name (or even space delimited scope names, so long as they match
+ the same token).
+
+ If you request scopes `scope1 scope2 scope3`, where `scope1` and
+ `scope2` are for the same service (and therefore map to the same
+ token), but `scope3` is for a different service, the following forms of
+ access are valid:
+
+ >>> tokens = ...
+ >>> # single scope
+ >>> token_data = tokens.by_scopes['scope1']
+ >>> token_data = tokens.by_scopes['scope2']
+ >>> token_data = tokens.by_scopes['scope3']
+ >>> # matching scopes
+ >>> token_data = tokens.by_scopes['scope1 scope2']
+ >>> token_data = tokens.by_scopes['scope2 scope1']
+ """
+ return self._by_scopes
+
def decode_id_token(self, auth_client=None):
"""
A parsed ID Token (OIDC) as a dict.
|
globus/globus-sdk-python
|
803aa674e145f5a386f6f032264656206b7e0dde
|
diff --git a/tests/unit/responses/test_token_response.py b/tests/unit/responses/test_token_response.py
index e9d0e9e6..fd9f993a 100644
--- a/tests/unit/responses/test_token_response.py
+++ b/tests/unit/responses/test_token_response.py
@@ -35,7 +35,8 @@ class OAuthTokenResponseTests(CapturedIOTestCase):
"id_token": "invalid_id_token",
"access_token": SDKTESTER1A_ID_ACCESS_TOKEN}
self.other_token2 = { # valid id_token with invalid access_token
- "resource_server": "server3", "expires_in": 30, "scope": "scope3",
+ "resource_server": "server3", "expires_in": 30,
+ "scope": "scope3 scope4",
"refresh_token": "RT3", "other_tokens": [], "token_type": "3",
"id_token": SDKTESTER1A_NATIVE1_ID_TOKEN,
"access_token": "invalid_access_token"}
@@ -114,6 +115,35 @@ class OAuthTokenResponseTests(CapturedIOTestCase):
self.assertIn(server_data["expires_at_seconds"],
(expected - 1, expected, expected + 1))
+ def test_by_scopes(self):
+ """
+ Gets by_scopes attribute from test response,
+ Confirms expected values found for top and other tokens
+ """
+ by_scopes = self.response.by_scopes
+
+ # confirm data by server matches known token values
+ for scope, token in [("scope1", self.top_token),
+ ("scope2", self.other_token1),
+ ("scope3", self.other_token2),
+ ("scope4", self.other_token2),
+ ("scope3 scope4", self.other_token2),
+ ("scope4 scope3", self.other_token2)]:
+ scope_data = by_scopes[scope]
+ for key in ["scope", "access_token",
+ "refresh_token", "token_type"]:
+ self.assertEqual(scope_data[key], token[key])
+ # assumes test runs within 1 second range
+ expected = int(time.time()) + token["expires_in"]
+ self.assertIn(scope_data["expires_at_seconds"],
+ (expected - 1, expected, expected + 1))
+
+ self.assertIn('scope1', by_scopes)
+ self.assertIn('scope3', by_scopes)
+ self.assertNotIn('scope1 scope2', by_scopes)
+ self.assertNotIn('scope1 scope3', by_scopes)
+ self.assertIn('scope4 scope3', by_scopes)
+
@retry_errors()
def test_decode_id_token_invalid_id(self):
"""
@@ -159,7 +189,8 @@ class OAuthDependentTokenResponseTests(CapturedIOTestCase):
"resource_server": "server2", "expires_in": 20, "scope": "scope2",
"access_token": "AT2", "refresh_token": "RT2", "token_type": "2"}
self.token3 = {
- "resource_server": "server3", "expires_in": 30, "scope": "scope3",
+ "resource_server": "server3", "expires_in": 30,
+ "scope": "scope3 scope4",
"access_token": "AT3", "refresh_token": "RT3", "token_type": "3"}
# create the response
@@ -188,3 +219,32 @@ class OAuthDependentTokenResponseTests(CapturedIOTestCase):
expected = int(time.time()) + token["expires_in"]
self.assertIn(server_data["expires_at_seconds"],
(expected - 1, expected, expected + 1))
+
+ def test_by_scopes(self):
+ """
+ Gets by_scopes attribute from test response,
+ Confirms expected values found for top and other tokens
+ """
+ by_scopes = self.response.by_scopes
+
+ # confirm data by server matches known token values
+ for scope, token in [("scope1", self.token1),
+ ("scope2", self.token2),
+ ("scope3", self.token3),
+ ("scope4", self.token3),
+ ("scope3 scope4", self.token3),
+ ("scope4 scope3", self.token3)]:
+ scope_data = by_scopes[scope]
+ for key in ["scope", "access_token",
+ "refresh_token", "token_type"]:
+ self.assertEqual(scope_data[key], token[key])
+ # assumes test runs within 1 second range
+ expected = int(time.time()) + token["expires_in"]
+ self.assertIn(scope_data["expires_at_seconds"],
+ (expected - 1, expected, expected + 1))
+
+ self.assertIn('scope1', by_scopes)
+ self.assertIn('scope3', by_scopes)
+ self.assertNotIn('scope1 scope2', by_scopes)
+ self.assertNotIn('scope1 scope3', by_scopes)
+ self.assertIn('scope4 scope3', by_scopes)
|
Add `by_scopes` form (or similar) to token response
This is pretty much just another presentation of the same data that we put into `OAuthTokenResponse.by_resource_server`.
Although instinctively I'd just generate this as a dict, I don't think that's right. IMO, `tokens.by_scopes['openid profile']` should do the same thing as `tokens.by_scopes['openid']`
So, `by_scopes` should really be a small class which has `__getitem__` defined as doing `.split(' ')`, getting all indexed values, `KeyError` if num values != 1
We _could_ do this with `tokens.get_by_scopes('openid profile')`, but I don't think this is in any way fundamentally easier than a dict-like with sophisticated access.
Is this too fancy?
|
0.0
|
803aa674e145f5a386f6f032264656206b7e0dde
|
[
"tests/unit/responses/test_token_response.py::OAuthTokenResponseTests::test_by_scopes",
"tests/unit/responses/test_token_response.py::OAuthDependentTokenResponseTests::test_by_scopes"
] |
[
"tests/unit/responses/test_token_response.py::OAuthTokenResponseTests::test_by_resource_server",
"tests/unit/responses/test_token_response.py::OAuthTokenResponseTests::test_convert_token_info_dict",
"tests/unit/responses/test_token_response.py::OAuthTokenResponseTests::test_decode_id_token_expired",
"tests/unit/responses/test_token_response.py::OAuthTokenResponseTests::test_decode_id_token_invalid_id",
"tests/unit/responses/test_token_response.py::OAuthDependentTokenResponseTests::test_by_resource_server"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-12-11 18:25:37+00:00
|
apache-2.0
| 2,540 |
|
globus__globus-sdk-python-307
|
diff --git a/globus_sdk/auth/client_types/base.py b/globus_sdk/auth/client_types/base.py
index 07f26d0a..4554ebb7 100644
--- a/globus_sdk/auth/client_types/base.py
+++ b/globus_sdk/auth/client_types/base.py
@@ -360,7 +360,7 @@ class AuthClient(BaseClient):
**Parameters**
- ``response_type``
+ ``response_class``
Defaults to :class:`OAuthTokenResponse \
<globus_sdk.auth.token_response.OAuthTokenResponse>`. This is
used by calls to the oauth2_token endpoint which need to
diff --git a/globus_sdk/auth/client_types/confidential_client.py b/globus_sdk/auth/client_types/confidential_client.py
index 2b00cc3c..573e9207 100644
--- a/globus_sdk/auth/client_types/confidential_client.py
+++ b/globus_sdk/auth/client_types/confidential_client.py
@@ -139,7 +139,7 @@ class ConfidentialAppAuthClient(AuthClient):
state=state, refresh_tokens=refresh_tokens)
return self.current_oauth2_flow_manager
- def oauth2_get_dependent_tokens(self, token):
+ def oauth2_get_dependent_tokens(self, token, additional_params=None):
"""
Does a `Dependent Token Grant
<https://docs.globus.org/api/auth/reference/#dependent_token_grant_post_v2_oauth2_token>`_
@@ -166,14 +166,23 @@ class ConfidentialAppAuthClient(AuthClient):
``token`` (*string*)
An Access Token as a raw string, being exchanged.
+ ``additional_params`` (*dict*)
+ A ``dict`` or ``None``, which specifies additional parameters
+ to include in the request body
+
:rtype: :class:`OAuthTokenResponse
<globus_sdk.auth.token_response.OAuthTokenResponse>`
"""
self.logger.info('Getting dependent tokens from access token')
- return self.oauth2_token({
+ self.logger.debug('additional_params={}'.format(additional_params))
+ form_data = {
'grant_type': 'urn:globus:auth:grant_type:dependent_token',
- 'token': token},
- response_class=OAuthDependentTokenResponse)
+ 'token': token}
+ if additional_params:
+ form_data.update(additional_params)
+
+ return self.oauth2_token(
+ form_data, response_class=OAuthDependentTokenResponse)
def oauth2_token_introspect(self, token, include=None):
"""
diff --git a/globus_sdk/authorizers/client_credentials.py b/globus_sdk/authorizers/client_credentials.py
index 6f82b4ee..d5649942 100644
--- a/globus_sdk/authorizers/client_credentials.py
+++ b/globus_sdk/authorizers/client_credentials.py
@@ -48,8 +48,16 @@ class ClientCredentialsAuthorizer(RenewingAuthorizer):
POSIX timestamp (i.e. seconds since the epoch)
``on_refresh`` (*callable*)
- Will be called as fn(token_data) any time this authorizer
- fetches a new access_token
+ A callback which is triggered any time this authorizer fetches a new
+ access_token. The ``on_refresh`` callable is invoked on the
+ :class:`OAuthTokenResponse \
+ <globus_sdk.auth.token_response.OAuthTokenResponse>`
+ object resulting from the token being refreshed.
+ It should take only one argument, the token response object.
+
+ This is useful for implementing storage for Access Tokens, as the
+ ``on_refresh`` callback can be used to update the Access Tokens and
+ their expiration times.
"""
def __init__(self, confidential_client, scopes,
access_token=None, expires_at=None, on_refresh=None):
diff --git a/globus_sdk/authorizers/refresh_token.py b/globus_sdk/authorizers/refresh_token.py
index 6ca6e458..1cd35305 100644
--- a/globus_sdk/authorizers/refresh_token.py
+++ b/globus_sdk/authorizers/refresh_token.py
@@ -43,8 +43,16 @@ class RefreshTokenAuthorizer(RenewingAuthorizer):
POSIX timestamp (i.e. seconds since the epoch)
``on_refresh`` (*callable*)
- Will be called as fn(token_data) any time this authorizer
- fetches a new access_token
+ A callback which is triggered any time this authorizer fetches a new
+ access_token. The ``on_refresh`` callable is invoked on the
+ :class:`OAuthTokenResponse \
+ <globus_sdk.auth.token_response.OAuthTokenResponse>`
+ object resulting from the token being refreshed.
+ It should take only one argument, the token response object.
+
+ This is useful for implementing storage for Access Tokens, as the
+ ``on_refresh`` callback can be used to update the Access Tokens and
+ their expiration times.
"""
def __init__(self, refresh_token, auth_client,
access_token=None, expires_at=None, on_refresh=None):
diff --git a/globus_sdk/authorizers/renewing.py b/globus_sdk/authorizers/renewing.py
index 07fe7cd5..e2d711e8 100644
--- a/globus_sdk/authorizers/renewing.py
+++ b/globus_sdk/authorizers/renewing.py
@@ -28,6 +28,28 @@ class RenewingAuthorizer(GlobusAuthorizer):
To make an authorizer that implements this class implement
the _get_token_response and _extract_token_data methods for that
authorization type,
+
+ **Parameters**
+
+ ``access_token`` (*string*)
+ Initial Access Token to use. Used only if ``expires_at`` is also set,
+ otherwise ignored.
+
+ ``expires_at`` (*int*)
+ Expiration time for the starting ``access_token`` expressed as a
+ POSIX timestamp (i.e. seconds since the epoch)
+
+ ``on_refresh`` (*callable*)
+ A callback which is triggered any time this authorizer fetches a new
+ access_token. The ``on_refresh`` callable is invoked on the
+ :class:`OAuthTokenResponse \
+ <globus_sdk.auth.token_response.OAuthTokenResponse>`
+ object resulting from the token being refreshed.
+ It should take only one argument, the token response object.
+
+ This is useful for implementing storage for Access Tokens, as the
+ ``on_refresh`` callback can be used to update the Access Tokens and
+ their expiration times.
"""
def __init__(self, access_token=None, expires_at=None, on_refresh=None):
@@ -109,9 +131,14 @@ class RenewingAuthorizer(GlobusAuthorizer):
self.on_refresh(res)
logger.debug("Invoked on_refresh callback")
- def _check_expiration_time(self):
+ def check_expiration_time(self):
"""
Check if the expiration timer is done, and renew the token if it is.
+
+ This is called implicitly by ``set_authorization_header``, but you can
+ call it explicitly if you want to ensure that a token gets refreshed.
+ This can be useful in order to get at a new, valid token via the
+ ``on_refresh`` handler.
"""
logger.debug("RenewingAuthorizer checking expiration time")
if self.access_token is None or (
@@ -129,7 +156,7 @@ class RenewingAuthorizer(GlobusAuthorizer):
Once that's done, sets the ``Authorization`` header to
"Bearer <access_token>"
"""
- self._check_expiration_time()
+ self.check_expiration_time()
logger.debug(("Setting RefreshToken Authorization Header:"
'Bearer token has hash "{}"')
.format(self.access_token_hash))
diff --git a/globus_sdk/base.py b/globus_sdk/base.py
index ec668bcd..8fd51190 100644
--- a/globus_sdk/base.py
+++ b/globus_sdk/base.py
@@ -80,16 +80,16 @@ class BaseClient(object):
type(self), self.allowed_authorizer_types,
type(authorizer)))
- # defer this default until instantiation time so that logging can
- # capture the execution of the config load
- if environment is None:
- environment = config.get_default_environ()
+ # if an environment was passed, it will be used, but otherwise lookup
+ # the env var -- and in the special case of `production` translate to
+ # `default`, regardless of the source of that value
+ # logs the environment when it isn't `default`
+ self.environment = config.get_globus_environ(inputenv=environment)
- self.environment = environment
self.authorizer = authorizer
if base_url is None:
- self.base_url = config.get_service_url(environment, service)
+ self.base_url = config.get_service_url(self.environment, service)
else:
self.base_url = base_url
if base_path is not None:
@@ -104,13 +104,13 @@ class BaseClient(object):
}
# verify SSL? Usually true
- self._verify = config.get_ssl_verify(environment)
+ self._verify = config.get_ssl_verify(self.environment)
# HTTP connection timeout
# this is passed verbatim to `requests`, and we therefore technically
# support a tuple for connect/read timeouts, but we don't need to
# advertise that... Just declare it as an float value
if http_timeout is None:
- http_timeout = config.get_http_timeout(environment)
+ http_timeout = config.get_http_timeout(self.environment)
self._http_timeout = http_timeout
# handle -1 by passing None to requests
if self._http_timeout == -1:
diff --git a/globus_sdk/config.py b/globus_sdk/config.py
index d1c7147f..1f5bc364 100644
--- a/globus_sdk/config.py
+++ b/globus_sdk/config.py
@@ -175,17 +175,25 @@ def _bool_cast(value):
raise ValueError("Invalid config bool")
-def get_default_environ():
+def get_globus_environ(inputenv=None):
"""
- Get the default environment to look for in the config, as a string.
+ Get the environment to look for in the config, as a string.
+
Typically just "default", but it can be overridden with
`GLOBUS_SDK_ENVIRONMENT` in the shell environment. In that case, any client
which does not explicitly specify its environment will use this value.
+
+ :param inputenv: An environment which was passed, e.g. to a client
+ instantiation
"""
- env = os.environ.get('GLOBUS_SDK_ENVIRONMENT', 'default')
+ if inputenv is None:
+ env = os.environ.get('GLOBUS_SDK_ENVIRONMENT', 'default')
+ else:
+ env = inputenv
+
if env == 'production':
env = 'default'
if env != 'default':
logger.info(('On lookup, non-default environment: '
- 'GLOBUS_SDK_ENVIRONMENT={}'.format(env)))
+ 'globus_environment={}'.format(env)))
return env
|
globus/globus-sdk-python
|
d761ba9a104ba2d8a70d2e064d12ea95101596df
|
diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py
index 7ed9106e..fee2929c 100644
--- a/tests/unit/test_config.py
+++ b/tests/unit/test_config.py
@@ -148,22 +148,35 @@ class ConfigParserTests(CapturedIOTestCase):
with self.assertRaises(ValueError):
globus_sdk.config._bool_cast("invalid")
- def test_get_default_environ(self):
+ def test_get_globus_environ(self):
"""
Confirms returns "default", or the value of GLOBUS_SDK_ENVIRONMENT
"""
- # default if no environ value exists
- prev_setting = None
- if "GLOBUS_SDK_ENVIRONMENT" in os.environ:
- prev_setting = os.environ["GLOBUS_SDK_ENVIRONMENT"]
+ # mock environ to ensure it gets reset
+ with mock.patch.dict(os.environ):
+ # set an environment value, ensure that it's returned
+ os.environ["GLOBUS_SDK_ENVIRONMENT"] = "beta"
+ self.assertEqual(globus_sdk.config.get_globus_environ(), "beta")
+
+ # clear that value, "default" should be returned
del os.environ["GLOBUS_SDK_ENVIRONMENT"]
- self.assertEqual(globus_sdk.config.get_default_environ(), "default")
- # otherwise environ value
- os.environ["GLOBUS_SDK_ENVIRONMENT"] = "beta"
- self.assertEqual(globus_sdk.config.get_default_environ(), "beta")
-
- # cleanup for other tests
- if prev_setting:
- os.environ["GLOBUS_SDK_ENVIRONMENT"] = prev_setting
- else:
+ self.assertEqual(globus_sdk.config.get_globus_environ(), "default")
+
+ # ensure that passing a value returns that value
+ self.assertEqual(
+ globus_sdk.config.get_globus_environ("beta"), "beta")
+
+ def test_get_globus_environ_production(self):
+ """
+ Confirms that get_globus_environ translates "production" to "default",
+ including when special values are passed
+ """
+ # mock environ to ensure it gets reset
+ with mock.patch.dict(os.environ):
+ os.environ["GLOBUS_SDK_ENVIRONMENT"] = "production"
+ self.assertEqual(globus_sdk.config.get_globus_environ(), "default")
+
del os.environ["GLOBUS_SDK_ENVIRONMENT"]
+ # ensure that passing a value returns that value
+ self.assertEqual(
+ globus_sdk.config.get_globus_environ("production"), "default")
diff --git a/tests/unit/test_renewing_authorizer.py b/tests/unit/test_renewing_authorizer.py
index ed227b92..ffda8551 100644
--- a/tests/unit/test_renewing_authorizer.py
+++ b/tests/unit/test_renewing_authorizer.py
@@ -105,7 +105,7 @@ class RenewingAuthorizerTests(CapturedIOTestCase):
"""
Confirms nothing is done before the access_token expires,
"""
- self.authorizer._check_expiration_time()
+ self.authorizer.check_expiration_time()
self.assertEqual(self.authorizer.access_token, self.access_token)
def test_check_expiration_time_expired(self):
@@ -113,7 +113,7 @@ class RenewingAuthorizerTests(CapturedIOTestCase):
Confirms a new access_token is gotten after waiting for expiration
"""
time.sleep(1)
- self.authorizer._check_expiration_time()
+ self.authorizer.check_expiration_time()
self.assertEqual(self.authorizer.access_token,
self.token_data["access_token"])
self.assertEqual(self.authorizer.expires_at,
@@ -125,7 +125,7 @@ class RenewingAuthorizerTests(CapturedIOTestCase):
Confirms a new access_token is gotten if the old one is set to None
"""
self.authorizer.access_token = None
- self.authorizer._check_expiration_time()
+ self.authorizer.check_expiration_time()
self.assertEqual(self.authorizer.access_token,
self.token_data["access_token"])
self.assertEqual(self.authorizer.expires_at,
@@ -137,7 +137,7 @@ class RenewingAuthorizerTests(CapturedIOTestCase):
Confirms a new access_token is gotten if expires_at is set to None
"""
self.authorizer.expires_at = None
- self.authorizer._check_expiration_time()
+ self.authorizer.check_expiration_time()
self.assertEqual(self.authorizer.access_token,
self.token_data["access_token"])
self.assertEqual(self.authorizer.expires_at,
|
Creating a client with `environment="production"` does not properly translate as it would with the environment variable
The default config section has the "production" environment values.
We have handling code for this in `globus_sdk.config_get_default_environ`, but that only runs if `environment` isn't passed to a client.
As a result, config lookups are done against the `production` section and fail.
There are several ways of handling this, but one option which is probably pretty foolproof is to update this:
https://github.com/globus/globus-sdk-python/blob/d761ba9a104ba2d8a70d2e064d12ea95101596df/globus_sdk/base.py#L85-L86
Instead of doing that, try
```python
environment = config.get_default_environ(environment)
```
and update `get_default_environ` to take an input.
|
0.0
|
d761ba9a104ba2d8a70d2e064d12ea95101596df
|
[
"tests/unit/test_config.py::ConfigParserTests::test_get_globus_environ",
"tests/unit/test_config.py::ConfigParserTests::test_get_globus_environ_production",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_check_expiration_time_expired",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_check_expiration_time_no_expiration",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_check_expiration_time_no_token",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_check_expiration_time_valid"
] |
[
"tests/unit/test_config.py::ConfigParserTests::test_bool_cast",
"tests/unit/test_config.py::ConfigParserTests::test_get",
"tests/unit/test_config.py::ConfigParserTests::test_get_lib_config_path",
"tests/unit/test_config.py::ConfigParserTests::test_get_parser",
"tests/unit/test_config.py::ConfigParserTests::test_get_service_url",
"tests/unit/test_config.py::ConfigParserTests::test_get_ssl_verify",
"tests/unit/test_config.py::ConfigParserTests::test_init_and_load_config",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_get_new_access_token",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_handle_missing_authorization",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_init",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_authorization_header",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_authorization_header_existing",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_authorization_header_expired",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_authorization_header_no_expires",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_authorization_header_no_token",
"tests/unit/test_renewing_authorizer.py::RenewingAuthorizerTests::test_set_expiration_time"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-08-24 15:33:56+00:00
|
apache-2.0
| 2,541 |
|
glotzerlab__rowan-10
|
diff --git a/rowan/functions.py b/rowan/functions.py
index 2f6a0c4..8a960dc 100644
--- a/rowan/functions.py
+++ b/rowan/functions.py
@@ -1031,8 +1031,8 @@ def to_axis_angle(q):
sines = np.sin(angles/2)
# Avoid divide by zero issues; these values will not be used
sines[sines == 0] = 1
- axes = np.where(angles != 0,
- q[..., 1:]/sines,
+ axes = np.where(angles[..., np.newaxis] != 0,
+ q[..., 1:]/sines[..., np.newaxis],
0)
return axes, angles
|
glotzerlab/rowan
|
a6b947397e1de6797cfac144b0fa9e410c75c683
|
diff --git a/tests/test_axis_angle.py b/tests/test_axis_angle.py
index 3387061..b81cfa0 100644
--- a/tests/test_axis_angle.py
+++ b/tests/test_axis_angle.py
@@ -85,8 +85,19 @@ class TestFromAxisAngle(unittest.TestCase):
class TestToAxisAngle(unittest.TestCase):
"""Test converting to axis angle representation"""
+ def test_div_zero(self):
+ q = (1, 0, 0, 0)
+ axes, angles = rowan.to_axis_angle(q)
+ self.assertTrue(np.allclose(axes, [0, 0, 0]))
+ self.assertEqual(angles, 0)
+
def test_to_axis_angle(self):
- axes, angles = rowan.to_axis_angle(
- np.array((np.sqrt(2)/2, np.sqrt(2)/2, 0, 0)))
+ q = (np.sqrt(2)/2, np.sqrt(2)/2, 0, 0)
+ axes, angles = rowan.to_axis_angle(q)
self.assertTrue(np.allclose(axes, np.array([1, 0, 0])))
self.assertTrue(np.allclose(angles, np.pi/2))
+
+ q2 = np.stack((q, q), axis=0)
+ axes, angles = rowan.to_axis_angle(q2)
+ self.assertTrue(np.allclose(axes, np.array([[1, 0, 0], [1, 0, 0]])))
+ self.assertTrue(np.allclose(angles, [np.pi/2, np.pi/2]))
|
to_axis_angle not working for multiple quaternions?
I have several quaternions and want to get axes/angles. This is a traceback of what happens. I'm using rowan v1.2.0.
```
>>> rowan.to_axis_angle(rowan.normalize([[0.707, 0, 0, 0.707], [0, 0, 0, 1]]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/bdice/anaconda3/envs/dice/lib/python3.6/site-packages/rowan/functions.py", line 1035, in to_axis_angle
q[..., 1:]/sines,
ValueError: operands could not be broadcast together with shapes (2,3) (2,)
```
|
0.0
|
a6b947397e1de6797cfac144b0fa9e410c75c683
|
[
"tests/test_axis_angle.py::TestToAxisAngle::test_to_axis_angle"
] |
[
"tests/test_axis_angle.py::TestFromAxisAngle::test_complex",
"tests/test_axis_angle.py::TestFromAxisAngle::test_multiple",
"tests/test_axis_angle.py::TestFromAxisAngle::test_multiple_vectors",
"tests/test_axis_angle.py::TestFromAxisAngle::test_single",
"tests/test_axis_angle.py::TestToAxisAngle::test_div_zero"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2019-03-05 22:11:19+00:00
|
bsd-3-clause
| 2,542 |
|
glotzerlab__rowan-18
|
diff --git a/doc/conf.py b/doc/conf.py
index d1a5f01..564930e 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -55,7 +55,7 @@ master_doc = 'index'
# General information about the project.
project = 'rowan'
-copyright = '2010-2019, Regents of the University of Michigan'
+copyright = '2010-2019, The Regents of the University of Michigan'
author = 'Vyas Ramasubramani'
# The version info for the project you're documenting, acts as replacement for
diff --git a/rowan/functions.py b/rowan/functions.py
index d97afc4..f466e35 100644
--- a/rowan/functions.py
+++ b/rowan/functions.py
@@ -697,7 +697,7 @@ def to_euler(q, convention='zyx', axis_type='intrinsic'):
R_y(\theta) =& \left(\begin{array}{ccc}
\cos \theta & 0 & \sin \theta \\
0 & 1 & 0 \\
- -\sin \theta & 1 & \cos \theta \\
+ -\sin \theta & 0 & \cos \theta \\
\end{array}\right)\\
R_z(\theta) =& \left(\begin{array}{ccc}
\cos \theta & -\sin \theta & 0 \\
@@ -722,6 +722,21 @@ def to_euler(q, convention='zyx', axis_type='intrinsic'):
`Euler angles <https://en.wikipedia.org/wiki/Euler_angles>`_
(specifically the section on converting between representations).
+ .. warning::
+
+ Euler angles are a highly problematic representation for a number of
+ reasons, not least of which is the large number of possible conventions
+ and their relative imprecision when compared to using quaternions (or
+ axis-angle representations). If possible, you should avoid Euler angles
+ and work with quaternions instead. If Euler angles are required, note
+ that they are susceptible to `gimbal lock
+ <https://en.wikipedia.org/wiki/Gimbal_lock>`_, which leads to ambiguity
+ in the representation of a given rotation. To address this issue, in
+ cases where gimbal lock arises, :func:`~.to_euler` adopts the
+ convention that :math:`\gamma=0` and represents the rotation entirely
+ in terms of :math:`\beta` and :math:`\alpha`.
+
+
Args:
q ((...,4) np.array): Quaternions to transform.
convention (str): One of the 6 valid conventions zxz,
@@ -746,128 +761,182 @@ def to_euler(q, convention='zyx', axis_type='intrinsic'):
"""
q = np.asarray(q)
_validate_unit(q)
+ atol = 1e-3
try:
- mats = to_matrix(q)
+ # Due to minor numerical imprecision, the to_matrix function could
+ # generate a (very slightly) nonorthogonal matrix (e.g. with a norm of
+ # 1 + 2e-8). That is sufficient to throw off the trigonometric
+ # functions, so it's worthwhile to explicitly clip for safety,
+ # especially since we've already checked the quaternion norm.
+ mats = np.clip(to_matrix(q), -1, 1)
except ValueError:
raise ValueError(
"Not all quaternions in q are unit quaternions.")
- if axis_type == 'intrinsic':
- # Have to hardcode the different possibilities.
- # Classical Euler angles
- if convention == 'xzx':
- alpha = np.arctan2(mats[..., 2, 0], mats[..., 1, 0])
- beta = np.arccos(mats[..., 0, 0])
- gamma = np.arctan2(mats[..., 0, 2], -mats[..., 0, 1])
- elif convention == 'xyx':
- alpha = np.arctan2(mats[..., 1, 0], -mats[..., 2, 0])
- beta = np.arccos(mats[..., 0, 0])
- gamma = np.arctan2(mats[..., 0, 1], mats[..., 0, 2])
- elif convention == 'yxy':
- alpha = np.arctan2(mats[..., 0, 1], mats[..., 2, 1])
- beta = np.arccos(mats[..., 1, 1])
- gamma = np.arctan2(mats[..., 1, 0], -mats[..., 1, 2])
- elif convention == 'yzy':
- alpha = np.arctan2(mats[..., 2, 1], -mats[..., 0, 1])
- beta = np.arccos(mats[..., 1, 1])
- gamma = np.arctan2(mats[..., 1, 2], mats[..., 1, 0])
- elif convention == 'zyz':
- alpha = np.arctan2(mats[..., 1, 2], mats[..., 0, 2])
- beta = np.arccos(mats[..., 2, 2])
- gamma = np.arctan2(mats[..., 2, 1], -mats[..., 2, 0])
- elif convention == 'zxz':
- alpha = np.arctan2(mats[..., 0, 2], -mats[..., 1, 2])
- beta = np.arccos(mats[..., 2, 2])
- gamma = np.arctan2(mats[..., 2, 0], mats[..., 2, 1])
- # Tait-Bryan angles
- elif convention == 'xzy':
- alpha = np.arctan2(mats[..., 2, 1], mats[..., 1, 1])
- beta = np.arcsin(-mats[..., 0, 1])
- gamma = np.arctan2(mats[..., 0, 2], mats[..., 0, 0])
- elif convention == 'xyz':
- alpha = np.arctan2(-mats[..., 1, 2], mats[..., 2, 2])
- beta = np.arcsin(mats[..., 0, 2])
- gamma = np.arctan2(-mats[..., 0, 1], mats[..., 0, 0])
- elif convention == 'yxz':
- alpha = np.arctan2(mats[..., 0, 2], mats[..., 2, 2])
- beta = np.arcsin(-mats[..., 1, 2])
- gamma = np.arctan2(mats[..., 1, 0], mats[..., 1, 1])
- elif convention == 'yzx':
- alpha = np.arctan2(-mats[..., 2, 0], mats[..., 0, 0])
- beta = np.arcsin(mats[..., 1, 0])
- gamma = np.arctan2(-mats[..., 1, 2], mats[..., 1, 1])
- elif convention == 'zyx':
- alpha = np.arctan2(mats[..., 1, 0], mats[..., 0, 0])
- beta = np.arcsin(-mats[..., 2, 0])
- gamma = np.arctan2(mats[..., 2, 1], mats[..., 2, 2])
- elif convention == 'zxy':
- alpha = np.arctan2(-mats[..., 0, 1], mats[..., 1, 1])
- beta = np.arcsin(mats[..., 2, 1])
- gamma = np.arctan2(-mats[..., 2, 0], mats[..., 2, 2])
- else:
- raise ValueError("Unknown convention selected!")
- elif axis_type == 'extrinsic':
- # For these, the matrix must be constructed in reverse order
- # e.g. Z(\alpha)Y'(\beta)Z''(\gamma) (where primes denote the
- # rotated frames) becomes the extrinsic rotation
- # Z(\gamma)Y(\beta)Z(\alpha).
-
- # Classical Euler angles
- if convention == 'xzx':
- alpha = np.arctan2(mats[..., 0, 2], -mats[..., 0, 1])
- beta = np.arccos(mats[..., 0, 0])
- gamma = np.arctan2(mats[..., 2, 0], mats[..., 1, 0])
- elif convention == 'xyx':
- alpha = np.arctan2(mats[..., 0, 1], mats[..., 0, 2])
- beta = np.arccos(mats[..., 0, 0])
- gamma = np.arctan2(mats[..., 1, 0], -mats[..., 2, 0])
- elif convention == 'yxy':
- alpha = np.arctan2(mats[..., 1, 0], -mats[..., 1, 2])
- beta = np.arccos(mats[..., 1, 1])
- gamma = np.arctan2(mats[..., 0, 1], mats[..., 2, 1])
- elif convention == 'yzy':
- alpha = np.arctan2(mats[..., 1, 2], mats[..., 1, 0])
- beta = np.arccos(mats[..., 1, 1])
- gamma = np.arctan2(mats[..., 2, 1], -mats[..., 0, 1])
- elif convention == 'zyz':
- alpha = np.arctan2(mats[..., 2, 1], -mats[..., 2, 0])
- beta = np.arccos(mats[..., 2, 2])
- gamma = np.arctan2(mats[..., 1, 2], mats[..., 0, 2])
- elif convention == 'zxz':
- alpha = np.arctan2(mats[..., 2, 0], mats[..., 2, 1])
- beta = np.arccos(mats[..., 2, 2])
- gamma = np.arctan2(mats[..., 0, 2], -mats[..., 1, 2])
- # Tait-Bryan angles
- elif convention == 'xzy':
- alpha = np.arctan2(-mats[..., 1, 2], mats[..., 1, 1])
- beta = np.arcsin(mats[..., 1, 0])
- gamma = np.arctan2(-mats[..., 2, 0], mats[..., 0, 0])
- elif convention == 'xyz':
- alpha = np.arctan2(mats[..., 2, 1], mats[..., 2, 2])
- beta = np.arcsin(-mats[..., 2, 0])
- gamma = np.arctan2(mats[..., 1, 0], mats[..., 0, 0])
- elif convention == 'yxz':
- alpha = np.arctan2(-mats[..., 2, 0], mats[..., 2, 2])
- beta = np.arcsin(mats[..., 2, 1])
- gamma = np.arctan2(-mats[..., 0, 1], mats[..., 1, 1])
- elif convention == 'yzx':
- alpha = np.arctan2(mats[..., 0, 2], mats[..., 0, 0])
- beta = np.arcsin(-mats[..., 0, 1])
- gamma = np.arctan2(mats[..., 2, 1], mats[..., 1, 1])
- elif convention == 'zyx':
- alpha = np.arctan2(-mats[..., 0, 1], mats[..., 0, 0])
- beta = np.arcsin(mats[..., 0, 2])
- gamma = np.arctan2(-mats[..., 1, 2], mats[..., 2, 2])
- elif convention == 'zxy':
- alpha = np.arctan2(mats[..., 1, 0], mats[..., 1, 1])
- beta = np.arcsin(-mats[..., 1, 2])
- gamma = np.arctan2(mats[..., 0, 2], mats[..., 2, 2])
- else:
- raise ValueError("Unknown convention selected!")
- else:
+ # For intrinsic angles, the matrix must be constructed in reverse order
+ # e.g. Z(\alpha)Y'(\beta)Z''(\gamma) (where primes denote the rotated
+ # frames) becomes the extrinsic rotation Z(\gamma)Y(\beta)Z(\alpha). Simply
+ # for easier readability of order, matrices are constructed for the
+ # intrinsic angle ordering and just reversed for extrinsic.
+ if axis_type == "extrinsic":
+ convention = convention[::-1]
+ elif not axis_type == "intrinsic":
raise ValueError("The axis type must be either extrinsic or intrinsic")
+ # We have to hardcode the different convention possibilities since they all
+ # result in different matrices according to the rotation order. In all
+ # possible compositions, there are cases where, given some 0 elements in
+ # the matrix, the simplest combination of matrix elements will give the
+ # wrong solution. In those cases, we have to use other parts of the
+ # matrix. In those cases, we have to be much more careful about signs,
+ # because there are multiple places where negatives can come into play. Due
+ # to gimbal lock, the alpha and gamma angles are no longer independent in
+ # that case. By convention, we set gamma to 0 and solve for alpha in those
+ # cases.
+
+ # Classical Euler angles
+ if convention == 'xzx':
+ beta = np.arccos(mats[..., 0, 0])
+ multiplier = mats[..., 0, 0] if axis_type == "extrinsic" else 1
+ where_zero = np.isclose(np.sin(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(mats[..., 0, 2], -mats[..., 0, 1]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(mats[..., 2, 0], mats[..., 1, 0]))
+ zero_terms = np.arctan2(-multiplier*mats[..., 1, 2], mats[..., 2, 2])
+ elif convention == 'xyx':
+ beta = np.arccos(mats[..., 0, 0])
+ multiplier = mats[..., 0, 0] if axis_type == "extrinsic" else 1
+ where_zero = np.isclose(np.sin(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(mats[..., 0, 1], mats[..., 0, 2]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(mats[..., 1, 0], -mats[..., 2, 0]))
+ zero_terms = np.arctan2(multiplier*mats[..., 2, 1], mats[..., 1, 1])
+ elif convention == 'yxy':
+ beta = np.arccos(mats[..., 1, 1])
+ multiplier = mats[..., 1, 1] if axis_type == "extrinsic" else 1
+ where_zero = np.isclose(np.sin(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(mats[..., 1, 0], -mats[..., 1, 2]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(mats[..., 0, 1], mats[..., 2, 1]))
+ zero_terms = np.arctan2(-multiplier*mats[..., 2, 0], mats[..., 0, 0])
+ elif convention == 'yzy':
+ beta = np.arccos(mats[..., 1, 1])
+ multiplier = mats[..., 1, 1] if axis_type == "extrinsic" else 1
+ where_zero = np.isclose(np.sin(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(mats[..., 1, 2], mats[..., 1, 0]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(mats[..., 2, 1], -mats[..., 0, 1]))
+ zero_terms = np.arctan2(multiplier*mats[..., 0, 2], mats[..., 2, 2])
+ elif convention == 'zyz':
+ beta = np.arccos(mats[..., 2, 2])
+ multiplier = mats[..., 2, 2] if axis_type == "extrinsic" else 1
+ where_zero = np.isclose(np.sin(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(mats[..., 2, 1], -mats[..., 2, 0]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(mats[..., 1, 2], mats[..., 0, 2]))
+ zero_terms = np.arctan2(-multiplier*mats[..., 0, 1], mats[..., 1, 1])
+ elif convention == 'zxz':
+ beta = np.arccos(mats[..., 2, 2])
+ multiplier = mats[..., 2, 2] if axis_type == "extrinsic" else 1
+ where_zero = np.isclose(np.sin(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(mats[..., 2, 0], mats[..., 2, 1]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(mats[..., 0, 2], -mats[..., 1, 2]))
+ zero_terms = np.arctan2(multiplier*mats[..., 1, 0], mats[..., 0, 0])
+ # Tait-Bryan angles
+ elif convention == 'xzy':
+ beta = np.arcsin(-mats[..., 0, 1])
+ where_zero = np.isclose(np.cos(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(mats[..., 0, 2], mats[..., 0, 0]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(mats[..., 2, 1], mats[..., 1, 1]))
+ zero_terms = np.arctan2(-mats[..., 1, 2], mats[..., 2, 2])
+ elif convention == 'xyz':
+ beta = np.arcsin(mats[..., 0, 2])
+ multiplier = mats[..., 0, 2] if axis_type == "extrinsic" else 1
+ where_zero = np.isclose(np.cos(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(-mats[..., 0, 1], mats[..., 0, 0]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(-mats[..., 1, 2], mats[..., 2, 2]))
+ zero_terms = np.arctan2(multiplier*mats[..., 2, 1], mats[..., 1, 1])
+ elif convention == 'yxz':
+ beta = np.arcsin(-mats[..., 1, 2])
+ multiplier = mats[..., 1, 2] if axis_type == "extrinsic" else 1
+ where_zero = np.isclose(np.cos(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(mats[..., 1, 0], mats[..., 1, 1]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(mats[..., 0, 2], mats[..., 2, 2]))
+ zero_terms = np.arctan2(-multiplier*mats[..., 2, 0], mats[..., 0, 0])
+ elif convention == 'yzx':
+ beta = np.arcsin(mats[..., 1, 0])
+ multiplier = mats[..., 1, 0] if axis_type == "extrinsic" else 1
+ where_zero = np.isclose(np.cos(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(-mats[..., 1, 2], mats[..., 1, 1]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(-mats[..., 2, 0], mats[..., 0, 0]))
+ zero_terms = np.arctan2(multiplier*mats[..., 0, 2], mats[..., 2, 2])
+ elif convention == 'zyx':
+ beta = np.arcsin(-mats[..., 2, 0])
+ where_zero = np.isclose(np.cos(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(mats[..., 2, 1], mats[..., 2, 2]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(mats[..., 1, 0], mats[..., 0, 0]))
+ zero_terms = np.arctan2(-mats[..., 0, 1], mats[..., 1, 1])
+ elif convention == 'zxy':
+ beta = np.arcsin(mats[..., 2, 1])
+ multiplier = mats[..., 2, 1] if axis_type == "extrinsic" else 1
+ where_zero = np.isclose(np.cos(beta), 0, atol=atol)
+
+ gamma = np.where(where_zero, 0,
+ np.arctan2(-mats[..., 2, 0], mats[..., 2, 2]))
+ alpha = np.where(where_zero, 0,
+ np.arctan2(-mats[..., 0, 1], mats[..., 1, 1]))
+ zero_terms = np.arctan2(multiplier*mats[..., 1, 0], mats[..., 0, 0])
+ else:
+ raise ValueError("Unknown convention selected!")
+
+ # For extrinsic, swap back alpha and gamma.
+ if axis_type == "extrinsic":
+ tmp = alpha
+ alpha = gamma
+ gamma = tmp
+
+ # By convention, the zero terms that we calculate are always based on
+ # setting gamma to zero and applying to alpha. We assign them after the
+ # fact to enable the memcopy-free swap of alpha and gamma for extrinsic
+ # angles. For Python 2 compatibility, we need to index appropriately.
+ try:
+ alpha[where_zero] = zero_terms[where_zero]
+ except IndexError:
+ # This is necessary for Python 2 compatibility and limitations with the
+ # indexing behavior. Since the only possible case is a single set of
+ # inputs, we can just skip any indexing and overwrite directly if
+ # needed.
+ if where_zero:
+ alpha = zero_terms
return np.stack((alpha, beta, gamma), axis=-1)
|
glotzerlab/rowan
|
98532c0a82631fbdcf9661533f1500021ddcaf43
|
diff --git a/tests/test_euler.py b/tests/test_euler.py
index f00c93f..bea72cd 100644
--- a/tests/test_euler.py
+++ b/tests/test_euler.py
@@ -181,3 +181,177 @@ class TestEuler(unittest.TestCase):
),
msg="Failed for convention {}, axis type {}".format(
convention, axis_type))
+
+ def test_zero_beta(self):
+ """Check cases where beta is 0."""
+ # Since the Euler calculations are all done using matrices, it's easier
+ # to construct the test cases by directly using matrices as well. We
+ # assume gamma is 0 since, due to gimbal lock, only either alpha+gamma
+ # or alpha-gamma is a relevant parameter, and we just scan the other
+ # possible values. The actual function is defined such that gamma will
+ # always be zero in those cases. We define the matrices using lambda
+ # functions to support sweeping a range of values for alpha and beta,
+ # specifically to test cases where signs flip e.g. cos(0) vs cos(pi).
+ # These sign flips lead to changes in the rotation angles that must be
+ # tested.
+ mats_euler_intrinsic = [
+ ('xzx', 'intrinsic',
+ lambda alpha, beta:
+ [[np.cos(beta), 0, 0],
+ [0, np.cos(beta)*np.cos(alpha), -np.sin(alpha)],
+ [0, np.cos(beta)*np.sin(alpha), np.cos(alpha)]]),
+ ('xyx', 'intrinsic',
+ lambda alpha, beta:
+ [[np.cos(beta), 0, 0],
+ [0, np.cos(alpha), -np.cos(beta)*np.sin(alpha)],
+ [0, np.sin(alpha), np.cos(beta)*np.cos(alpha)]]),
+ ('yxy', 'intrinsic',
+ lambda alpha, beta:
+ [[np.cos(alpha), 0, np.cos(beta)*np.sin(alpha)],
+ [0, np.cos(beta), 0],
+ [-np.sin(alpha), 0, np.cos(beta)*np.cos(alpha)]]),
+ ('yzy', 'intrinsic',
+ lambda alpha, beta:
+ [[np.cos(beta)*np.cos(alpha), 0, np.sin(alpha)],
+ [0, np.cos(beta), 0],
+ [-np.cos(beta)*np.sin(alpha), 0, np.cos(alpha)]]),
+ ('zyz', 'intrinsic',
+ lambda alpha, beta:
+ [[np.cos(beta)*np.cos(alpha), -np.sin(alpha), 0],
+ [np.cos(beta)*np.sin(alpha), np.cos(beta), 0],
+ [0, 0, np.cos(beta)]]),
+ ('zxz', 'intrinsic',
+ lambda alpha, beta:
+ [[np.cos(alpha), -np.cos(beta)*np.sin(alpha), 0],
+ [np.sin(alpha), np.cos(beta)*np.cos(beta), 0],
+ [0, 0, np.cos(beta)]]),
+ ]
+
+ mats_tb_intrinsic = [
+ ('xzy', 'intrinsic',
+ lambda alpha, beta:
+ [[0, -np.sin(beta), 0],
+ [np.sin(beta)*np.cos(alpha), 0, -np.sin(alpha)],
+ [np.sin(beta)*np.sin(alpha), 0, np.cos(alpha)]]),
+ ('xyz', 'intrinsic',
+ lambda alpha, beta:
+ [[0, 0, np.sin(beta)],
+ [np.sin(beta)*np.sin(alpha), np.cos(alpha), 0],
+ [-np.sin(beta)*np.cos(alpha), np.sin(alpha), 0]]),
+ ('yxz', 'intrinsic',
+ lambda alpha, beta:
+ [[np.cos(alpha), np.sin(beta)*np.sin(alpha), 0],
+ [0, 0, -np.sin(beta)],
+ [-np.sin(alpha), np.sin(beta)*np.cos(alpha), 0]]),
+ ('yzx', 'intrinsic',
+ lambda alpha, beta:
+ [[0, -np.sin(beta)*np.cos(alpha), np.sin(alpha)],
+ [np.sin(beta), 0, 0],
+ [0, np.sin(beta)*np.sin(alpha), np.cos(alpha)]]),
+ ('zyx', 'intrinsic',
+ lambda alpha, beta:
+ [[0, -np.sin(alpha), np.sin(beta)*np.cos(alpha)],
+ [0, np.cos(alpha), np.sin(beta)*np.sin(alpha)],
+ [-np.sin(beta), 0, 0]]),
+ ('zxy', 'intrinsic',
+ lambda alpha, beta:
+ [[np.cos(alpha), 0, np.sin(beta)*np.sin(alpha)],
+ [np.sin(alpha), 0, -np.sin(beta)*np.cos(alpha)],
+ [0, -1, 0]]),
+ ]
+
+ # Extrinsic rotations can be tested identically to intrinsic rotations
+ # in the case of proper Euler angles.
+ mats_euler_extrinsic = [
+ (m[0], 'extrinsic', m[2]) for m in mats_euler_intrinsic
+ ]
+
+ # For Tait-Bryan angles, extrinsic rotations axis order must be
+ # reversed (since axes 1 and 3 are not identical), but more
+ # importantly, due to the sum/difference of alpha and gamma that
+ # arises, we need to test the negative of alpha to catch the dangerous
+ # cases. In practice we get the same results since we're sweeping alpha
+ # values in the tests below, but it's useful to set this up precisely.
+ mats_tb_extrinsic = [
+ (m[0][::-1], 'extrinsic',
+ lambda alpha, beta: m[2](-alpha, beta)
+ ) for m in mats_tb_intrinsic
+ ]
+
+ # Since angle representations may not be unique, checking that
+ # quaternions are equal may not work. Instead we perform rotations and
+ # check that they are identical. For simplicity, we rotate the
+ # simplest vector with all 3 components (otherwise tests won't catch
+ # the problem because there's no component to rotate).
+ test_vector = [1, 1, 1]
+
+ mats_intrinsic = (mats_euler_intrinsic, mats_tb_intrinsic)
+ mats_extrinsic = (mats_euler_extrinsic, mats_tb_extrinsic)
+
+ # The beta angles are different for proper Euler angles and Tait-Bryan
+ # angles because the relevant beta terms will be sines and cosines,
+ # respectively.
+ all_betas = ((0, np.pi), (np.pi/2, -np.pi/2))
+ alphas = (0, np.pi/2, np.pi, 3*np.pi/2)
+
+ for mats in (mats_intrinsic, mats_extrinsic):
+ for betas, mat_set in zip(all_betas, mats):
+ for convention, axis_type, mat_func in mat_set:
+ quaternions = []
+ for beta in betas:
+ for alpha in alphas:
+ mat = mat_func(alpha, beta)
+ if np.linalg.det(mat) == -1:
+ # Some of these will be improper rotations.
+ continue
+ quat = rowan.from_matrix(mat)
+ quaternions.append(quat)
+ euler = rowan.to_euler(
+ quat,
+ convention, axis_type
+ )
+ converted = rowan.from_euler(
+ *euler,
+ convention=convention,
+ axis_type=axis_type
+ )
+ correct_rotation = rowan.rotate(quat,
+ test_vector)
+ test_rotation = rowan.rotate(converted,
+ test_vector)
+ self.assertTrue(
+ np.allclose(
+ correct_rotation,
+ test_rotation,
+ atol=1e-6
+ ),
+ msg="""
+ Failed for convention {},
+ axis type {},
+ alpha = {},
+ beta = {}.
+ Expected quaternion: {}.
+ Calculated: {}.
+ Expected vector: {}.
+ Calculated vector: {}.""".format(
+ convention, axis_type,
+ alpha, beta, quat,
+ converted, correct_rotation,
+ test_rotation))
+
+ # For completeness, also test with broadcasting.
+ quaternions = np.asarray(quaternions).reshape(-1, 4)
+ all_euler = rowan.to_euler(
+ quaternions,
+ convention, axis_type
+ )
+ converted = rowan.from_euler(
+ all_euler[..., 0], all_euler[..., 1], all_euler[..., 2],
+ convention, axis_type
+ )
+ self.assertTrue(
+ np.allclose(
+ rowan.rotate(quaternions, test_vector),
+ rowan.rotate(converted, test_vector),
+ atol=1e-6
+ ))
|
to_euler failing with some quaternions
It looks like `to_euler` may be failing in some cases with particularly clean orientations; I'd guess that some tolerances may need to be added to the calculation, at a glance. For example,
```rowan.to_euler((-.5, .5, -.5, .5), convention='xyz', axis_type='intrinsic')```
produces the following rotation matrix inside the function:
```
array([[ 0., 0., 1.],
[-1., 0., 0.],
[ 0., -1., 0.]])
```
which causes both sets of arguments for `arctan2` to compute `alpha` and `gamma` to be (0, 0), causing the resulting set of angles to be `(0, pi/2, 0)`.
|
0.0
|
98532c0a82631fbdcf9661533f1500021ddcaf43
|
[
"tests/test_euler.py::TestEuler::test_zero_beta"
] |
[
"tests/test_euler.py::TestEuler::test_from_euler",
"tests/test_euler.py::TestEuler::test_from_to_euler",
"tests/test_euler.py::TestEuler::test_to_euler",
"tests/test_euler.py::TestEuler::test_to_from_euler"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-07-13 02:48:38+00:00
|
bsd-3-clause
| 2,543 |
|
glotzerlab__signac-118
|
diff --git a/changelog.txt b/changelog.txt
index 3d171bac..7c598d41 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -25,6 +25,7 @@ Added
+++++
- Adds an ``H5Store`` class, useful for storing array-like data with an HDF5 backend. Accessible via ``with job.data:`` or ``with project.data:``.
+ - Adds the ``signac.get_job()`` and the ``signac.Project.get_job()`` functions which allow users to get a job handle by switching into or providing the job's workspace directory.
- Add automatic cast of numpy arrays to lists when storing them within a `JSONDict`, e.g., a `job.statepoint` or `job.document`.
- Enable `Collection` class to manage collections stored in gzip files.
- Enable deleting of `JSONDict` keys through the attribute interface, e.g., `del job.doc.foo`.
diff --git a/signac/__init__.py b/signac/__init__.py
index 1104dd20..ec64fe41 100644
--- a/signac/__init__.py
+++ b/signac/__init__.py
@@ -21,6 +21,7 @@ from .contrib import Project
from .contrib import TemporaryProject
from .contrib import get_project
from .contrib import init_project
+from .contrib import get_job
from .contrib import fetch
from .contrib import export_one
from .contrib import export
@@ -46,7 +47,7 @@ __version__ = '0.9.5'
__all__ = ['__version__', 'contrib', 'db', 'errors', 'warnings', 'sync',
'cite',
- 'Project', 'TemporaryProject', 'get_project', 'init_project',
+ 'Project', 'TemporaryProject', 'get_project', 'init_project', 'get_job',
'get_database', 'fetch', 'fetch_one',
'export_one', 'export', 'export_to_mirror',
'Collection',
diff --git a/signac/__main__.py b/signac/__main__.py
index 0dcd74f8..dcf5fa02 100644
--- a/signac/__main__.py
+++ b/signac/__main__.py
@@ -95,7 +95,7 @@ Total transfer volume: {stats.volume}
SHELL_BANNER = """Python {python_version}
signac {signac_version}
-Project:\t{project_id}
+Project:\t{project_id}{job_banner}
Root:\t\t{root_path}
Workspace:\t{workspace_path}
Size:\t\t{size}
@@ -558,6 +558,7 @@ def _main_import_interactive(project, origin, args):
python_version=sys.version,
signac_version=__version__,
project_id=project.get_id(),
+ job_banner='',
root_path=project.root_directory(),
workspace_path=project.workspace(),
size=len(project),
@@ -958,7 +959,13 @@ def main_shell(args):
for _id in _jobs:
yield project.open_job(id=_id)
- job = _open_job_by_id(project, list(_jobs)[0]) if len(_jobs) == 1 else None
+ if len(_jobs) == 1:
+ job = _open_job_by_id(project, list(_jobs)[0])
+ else:
+ try:
+ job = project.get_job()
+ except LookupError:
+ job = None
local_ns = dict(
project=project, pr=project,
@@ -988,6 +995,7 @@ def main_shell(args):
python_version=sys.version,
signac_version=__version__,
project_id=project.get_id(),
+ job_banner='\nJob:\t\t{job._id}'.format(job=job) if job is not None else '',
root_path=project.root_directory(),
workspace_path=project.workspace(),
size=len(project)))
diff --git a/signac/contrib/__init__.py b/signac/contrib/__init__.py
index 8db2b3a8..c886d89d 100644
--- a/signac/contrib/__init__.py
+++ b/signac/contrib/__init__.py
@@ -7,7 +7,7 @@ import logging
from . import indexing
from .project import Project
from .project import TemporaryProject
-from .project import get_project, init_project
+from .project import get_project, init_project, get_job
from .indexing import BaseCrawler
from .indexing import RegexFileCrawler
from .indexing import JSONCrawler
@@ -29,7 +29,7 @@ logger = logging.getLogger(__name__)
__all__ = [
'indexing',
- 'Project', 'TemporaryProject', 'get_project', 'init_project',
+ 'Project', 'TemporaryProject', 'get_project', 'init_project', 'get_job',
'BaseCrawler', 'RegexFileCrawler', 'JSONCrawler', 'SignacProjectCrawler',
'MasterCrawler', 'fetch', 'fetch_one', 'fetched',
'export_one', 'export', 'export_to_mirror', 'export_pymongo',
diff --git a/signac/contrib/job.py b/signac/contrib/job.py
index bebf23d1..beb986fa 100644
--- a/signac/contrib/job.py
+++ b/signac/contrib/job.py
@@ -92,7 +92,7 @@ class Job(object):
return self._id
def __hash__(self):
- return hash(self._wd)
+ return hash(os.path.realpath(self._wd))
def __str__(self):
"Returns the job's id."
diff --git a/signac/contrib/project.py b/signac/contrib/project.py
index 4c4bf49a..e68a52ff 100644
--- a/signac/contrib/project.py
+++ b/signac/contrib/project.py
@@ -1518,7 +1518,7 @@ class Project(object):
:param search:
If True, search for project configurations inside and above
the specified root directory, otherwise only return projects
- with a root directory identical to the specified root arugment.
+ with a root directory identical to the specified root argument.
:type search: bool
:returns: The project handle.
:raises LookupError: If no project configuration can be found.
@@ -1531,6 +1531,38 @@ class Project(object):
"Unable to determine project id for path '{}'.".format(os.path.abspath(root)))
return cls(config=config)
+ @classmethod
+ def get_job(cls, root=None):
+ """Find a Job in or above the current working directory (or provided path).
+
+ :param root: The job root directory.
+ If no root directory is given, the current working directory is
+ assumed to be the job directory.
+ :type root: str
+ :returns: The job handle.
+ :raises LookupError: If this job cannot be found."""
+ if root is None:
+ root = os.getcwd()
+ root = os.path.abspath(root)
+
+ # Ensure the root path exists, which is not guaranteed by the regex match
+ if not os.path.exists(root):
+ raise LookupError("Path does not exist: '{}'.".format(root))
+
+ # Find the last match instance of a job id
+ results = list(re.finditer(JOB_ID_REGEX, root))
+ if len(results) == 0:
+ raise LookupError("Could not find a job id in path '{}'.".format(root))
+ match = results[-1]
+ job_id = match.group(0)
+ job_root = root[:match.end()]
+
+ # Find a project *above* the root directory (avoid finding nested projects)
+ project = cls.get_project(os.path.join(job_root, os.pardir))
+
+ # Return the matched job id from the found project
+ return project.open_job(id=job_id)
+
@contextmanager
def TemporaryProject(name=None, cls=None, **kwargs):
@@ -1836,6 +1868,28 @@ def get_project(root=None, search=True):
with a root directory identical to the specified root arugment.
:type search: bool
:returns: The project handle.
+ :rtype: :py:class:`~.Project`
:raises LookupError: If no project configuration can be found.
"""
return Project.get_project(root=root, search=search)
+
+
+def get_job(root=None):
+ """Find a Job in or above the current working directory (or provided path).
+
+ :param root: The job root directory.
+ If no root directory is given, the current working directory is
+ assumed to be within the current job workspace directory.
+ :type root: str
+ :returns: The job handle.
+ :raises LookupError: If this job cannot be found.
+
+ For example, when the current directory is a job workspace directory:
+
+ .. code-block:: python
+
+ >>> signac.get_job()
+ signac.contrib.job.Job(project=..., statepoint={...})
+
+ """
+ return Project.get_job(root=root)
|
glotzerlab/signac
|
6493898dc145cc3438533c75ec2030c82f06fa3c
|
diff --git a/tests/test_project.py b/tests/test_project.py
index 6ef330b7..352f0218 100644
--- a/tests/test_project.py
+++ b/tests/test_project.py
@@ -1765,6 +1765,20 @@ class ProjectInitTest(unittest.TestCase):
self.assertEqual(project.workspace(), os.path.join(root, 'workspace'))
self.assertEqual(project.root_directory(), root)
+ def test_get_project_non_local(self):
+ root = self._tmp_dir.name
+ subdir = os.path.join(root, 'subdir')
+ os.mkdir(subdir)
+ project = signac.init_project(root=root, name='testproject')
+ self.assertEqual(project, project.get_project(root=root))
+ self.assertEqual(project, signac.get_project(root=root))
+ with self.assertRaises(LookupError):
+ self.assertEqual(project, project.get_project(root=subdir, search=False))
+ with self.assertRaises(LookupError):
+ self.assertEqual(project, signac.get_project(root=subdir, search=False))
+ self.assertEqual(project, project.get_project(root=subdir, search=True))
+ self.assertEqual(project, signac.get_project(root=subdir, search=True))
+
def test_init(self):
root = self._tmp_dir.name
with self.assertRaises(LookupError):
@@ -1827,19 +1841,94 @@ class ProjectInitTest(unittest.TestCase):
finally:
os.chdir(cwd)
- def test_get_project_non_local(self):
+ def test_get_job_valid_workspace(self):
+ # Test case: The root-path is the job workspace path.
root = self._tmp_dir.name
- subdir = os.path.join(root, 'subdir')
- os.mkdir(subdir)
- project = signac.init_project(root=root, name='testproject')
- self.assertEqual(project, project.get_project(root=root))
- self.assertEqual(project, signac.get_project(root=root))
- with self.assertRaises(LookupError):
- self.assertEqual(project, project.get_project(root=subdir, search=False))
- with self.assertRaises(LookupError):
- self.assertEqual(project, signac.get_project(root=subdir, search=False))
- self.assertEqual(project, project.get_project(root=subdir, search=True))
- self.assertEqual(project, signac.get_project(root=subdir, search=True))
+ project = signac.init_project(name='testproject', root=root)
+ job = project.open_job({'a': 1})
+ job.init()
+ with job:
+ # The context manager enters the working directory of the job
+ self.assertEqual(project.get_job(), job)
+ self.assertEqual(signac.get_job(), job)
+
+ def test_get_job_invalid_workspace(self):
+ # Test case: The root-path is not the job workspace path.
+ root = self._tmp_dir.name
+ project = signac.init_project(name='testproject', root=root)
+ job = project.open_job({'a': 1})
+ job.init()
+ # We shouldn't be able to find a job while in the workspace directory,
+ # since no signac_statepoint.json exists.
+ cwd = os.getcwd()
+ try:
+ os.chdir(project.workspace())
+ with self.assertRaises(LookupError):
+ project.get_job()
+ with self.assertRaises(LookupError):
+ signac.get_job()
+ finally:
+ os.chdir(cwd)
+
+ def test_get_job_nested_project(self):
+ # Test case: The job workspace dir is also a project root dir.
+ root = self._tmp_dir.name
+ project = signac.init_project(name='testproject', root=root)
+ job = project.open_job({'a': 1})
+ job.init()
+ with job:
+ nestedproject = signac.init_project('nestedproject')
+ nestedproject.open_job({'b': 2}).init()
+ self.assertEqual(project.get_job(), job)
+ self.assertEqual(signac.get_job(), job)
+
+ def test_get_job_subdir(self):
+ # Test case: Get a job from a sub-directory of the job workspace dir.
+ root = self._tmp_dir.name
+ project = signac.init_project(name='testproject', root=root)
+ job = project.open_job({'a': 1})
+ job.init()
+ with job:
+ os.mkdir('test_subdir')
+ self.assertEqual(project.get_job('test_subdir'), job)
+ self.assertEqual(signac.get_job('test_subdir'), job)
+ self.assertEqual(project.get_job(job.fn('test_subdir')), job)
+ self.assertEqual(signac.get_job(job.fn('test_subdir')), job)
+
+ def test_get_job_nested_project_subdir(self):
+ # Test case: Get a job from a sub-directory of the job workspace dir
+ # when the job workspace is also a project root dir
+ root = self._tmp_dir.name
+ project = signac.init_project(name='testproject', root=root)
+ job = project.open_job({'a': 1})
+ job.init()
+ with job:
+ nestedproject = signac.init_project('nestedproject')
+ nestedproject.open_job({'b': 2}).init()
+ os.mkdir('test_subdir')
+ self.assertEqual(project.get_job('test_subdir'), job)
+ self.assertEqual(signac.get_job('test_subdir'), job)
+ self.assertEqual(project.get_job(job.fn('test_subdir')), job)
+ self.assertEqual(signac.get_job(job.fn('test_subdir')), job)
+
+ def test_get_job_symlink_other_project(self):
+ # Test case: Get a job from a symlink in another project workspace
+ root = self._tmp_dir.name
+ project_a_dir = os.path.join(root, 'project_a')
+ project_b_dir = os.path.join(root, 'project_b')
+ os.mkdir(project_a_dir)
+ os.mkdir(project_b_dir)
+ project_a = signac.init_project(name='project_a', root=project_a_dir)
+ project_b = signac.init_project(name='project_b', root=project_b_dir)
+ job_a = project_a.open_job({'a': 1})
+ job_a.init()
+ job_b = project_b.open_job({'b': 1})
+ job_b.init()
+ symlink_path = os.path.join(project_b.workspace(), job_a._id)
+ os.symlink(job_a.ws, symlink_path)
+ self.assertEqual(project_a.get_job(symlink_path), job_a)
+ self.assertEqual(project_b.get_job(symlink_path), job_a)
+ self.assertEqual(signac.get_job(symlink_path), job_a)
class ProjectPicklingTest(BaseProjectTest):
|
Implement a `signac.get_job()` function
**[Original report](https://bitbucket.org/glotzer/signac/issue/108) by Carl Simon Adorf (Bitbucket: [csadorf](https://bitbucket.org/csadorf), GitHub: [csadorf](https://github.com/csadorf)).**
----------------------------------------
The idea is to be able to "get" a job from the local directory. Use cases for example when opening a `signac shell` from within a signac workspace directory.
The main challenge is that the current data model does not associate a job workspace directory with one specific project.
See also related pull request: https://bitbucket.org/glotzer/signac/pull-requests/62
|
0.0
|
6493898dc145cc3438533c75ec2030c82f06fa3c
|
[
"tests/test_project.py::ProjectInitTest::test_get_job_invalid_workspace",
"tests/test_project.py::ProjectInitTest::test_get_job_nested_project",
"tests/test_project.py::ProjectInitTest::test_get_job_nested_project_subdir",
"tests/test_project.py::ProjectInitTest::test_get_job_subdir",
"tests/test_project.py::ProjectInitTest::test_get_job_symlink_other_project",
"tests/test_project.py::ProjectInitTest::test_get_job_valid_workspace"
] |
[
"tests/test_project.py::ProjectTest::test_corrupted_statepoint_file",
"tests/test_project.py::ProjectTest::test_custom_job_class",
"tests/test_project.py::ProjectTest::test_custom_project",
"tests/test_project.py::ProjectTest::test_doc",
"tests/test_project.py::ProjectTest::test_document",
"tests/test_project.py::ProjectTest::test_find_job_documents",
"tests/test_project.py::ProjectTest::test_find_job_documents_illegal_key",
"tests/test_project.py::ProjectTest::test_find_job_ids",
"tests/test_project.py::ProjectTest::test_find_jobs",
"tests/test_project.py::ProjectTest::test_find_jobs_arithmetic_operators",
"tests/test_project.py::ProjectTest::test_find_jobs_logical_operators",
"tests/test_project.py::ProjectTest::test_find_jobs_next",
"tests/test_project.py::ProjectTest::test_find_statepoint_sequences",
"tests/test_project.py::ProjectTest::test_find_statepoints",
"tests/test_project.py::ProjectTest::test_fn",
"tests/test_project.py::ProjectTest::test_get",
"tests/test_project.py::ProjectTest::test_get_id",
"tests/test_project.py::ProjectTest::test_index",
"tests/test_project.py::ProjectTest::test_isfile",
"tests/test_project.py::ProjectTest::test_iteration",
"tests/test_project.py::ProjectTest::test_job_clone",
"tests/test_project.py::ProjectTest::test_job_move",
"tests/test_project.py::ProjectTest::test_jobs_groupby",
"tests/test_project.py::ProjectTest::test_jobs_groupbydoc",
"tests/test_project.py::ProjectTest::test_len_find_jobs",
"tests/test_project.py::ProjectTest::test_missing_statepoint_file",
"tests/test_project.py::ProjectTest::test_num_jobs",
"tests/test_project.py::ProjectTest::test_open_job_by_abbreviated_id",
"tests/test_project.py::ProjectTest::test_open_job_by_id",
"tests/test_project.py::ProjectTest::test_project_contains",
"tests/test_project.py::ProjectTest::test_rename_workspace",
"tests/test_project.py::ProjectTest::test_repair_corrupted_workspace",
"tests/test_project.py::ProjectTest::test_repr",
"tests/test_project.py::ProjectTest::test_root_directory",
"tests/test_project.py::ProjectTest::test_schema",
"tests/test_project.py::ProjectTest::test_schema_difference",
"tests/test_project.py::ProjectTest::test_schema_eval",
"tests/test_project.py::ProjectTest::test_schema_init",
"tests/test_project.py::ProjectTest::test_schema_subset",
"tests/test_project.py::ProjectTest::test_signac_project_crawler",
"tests/test_project.py::ProjectTest::test_str",
"tests/test_project.py::ProjectTest::test_temp_project",
"tests/test_project.py::ProjectTest::test_workspace_broken_link_error_on_find",
"tests/test_project.py::ProjectTest::test_workspace_directory",
"tests/test_project.py::ProjectTest::test_workspace_directory_with_env_variable",
"tests/test_project.py::ProjectTest::test_workspace_path_normalization",
"tests/test_project.py::ProjectTest::test_workspace_read_only_path",
"tests/test_project.py::ProjectTest::test_write_read_statepoint",
"tests/test_project.py::ProjectExportImportTest::test_export",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_function",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_function_move",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_flat_flat",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_flat_tree",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_tree_flat",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_tree_tree",
"tests/test_project.py::ProjectExportImportTest::test_export_import",
"tests/test_project.py::ProjectExportImportTest::test_export_import_complex_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_complex_path_nested_schema_from_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_conflict",
"tests/test_project.py::ProjectExportImportTest::test_export_import_conflict_synced",
"tests/test_project.py::ProjectExportImportTest::test_export_import_conflict_synced_with_args",
"tests/test_project.py::ProjectExportImportTest::test_export_import_schema_callable",
"tests/test_project.py::ProjectExportImportTest::test_export_import_schema_callable_non_unique",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_nested_with_schema",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_schema_from_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_schema_from_path_float",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_with_float",
"tests/test_project.py::ProjectExportImportTest::test_export_import_tarfile",
"tests/test_project.py::ProjectExportImportTest::test_export_import_tarfile_zipped",
"tests/test_project.py::ProjectExportImportTest::test_export_import_zipfile",
"tests/test_project.py::ProjectExportImportTest::test_export_move",
"tests/test_project.py::ProjectExportImportTest::test_export_single_job",
"tests/test_project.py::ProjectExportImportTest::test_import_own_project",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_disjoint_schema",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_disjoint_schema_nested",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_fizz_schema_flat",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_schema_nested",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_schema_nested_partial_homogenous_path_provide",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_schema_problematic",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_flat_flat",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_flat_tree",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_nested",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_nested_provide_partial_path",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_tree",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_tree_flat",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_tree_tree",
"tests/test_project.py::CachedProjectTest::test_corrupted_statepoint_file",
"tests/test_project.py::CachedProjectTest::test_custom_job_class",
"tests/test_project.py::CachedProjectTest::test_custom_project",
"tests/test_project.py::CachedProjectTest::test_doc",
"tests/test_project.py::CachedProjectTest::test_document",
"tests/test_project.py::CachedProjectTest::test_find_job_documents",
"tests/test_project.py::CachedProjectTest::test_find_job_documents_illegal_key",
"tests/test_project.py::CachedProjectTest::test_find_job_ids",
"tests/test_project.py::CachedProjectTest::test_find_jobs",
"tests/test_project.py::CachedProjectTest::test_find_jobs_arithmetic_operators",
"tests/test_project.py::CachedProjectTest::test_find_jobs_logical_operators",
"tests/test_project.py::CachedProjectTest::test_find_jobs_next",
"tests/test_project.py::CachedProjectTest::test_find_statepoint_sequences",
"tests/test_project.py::CachedProjectTest::test_find_statepoints",
"tests/test_project.py::CachedProjectTest::test_fn",
"tests/test_project.py::CachedProjectTest::test_get",
"tests/test_project.py::CachedProjectTest::test_get_id",
"tests/test_project.py::CachedProjectTest::test_index",
"tests/test_project.py::CachedProjectTest::test_isfile",
"tests/test_project.py::CachedProjectTest::test_iteration",
"tests/test_project.py::CachedProjectTest::test_job_clone",
"tests/test_project.py::CachedProjectTest::test_job_move",
"tests/test_project.py::CachedProjectTest::test_jobs_groupby",
"tests/test_project.py::CachedProjectTest::test_jobs_groupbydoc",
"tests/test_project.py::CachedProjectTest::test_len_find_jobs",
"tests/test_project.py::CachedProjectTest::test_missing_statepoint_file",
"tests/test_project.py::CachedProjectTest::test_num_jobs",
"tests/test_project.py::CachedProjectTest::test_open_job_by_abbreviated_id",
"tests/test_project.py::CachedProjectTest::test_open_job_by_id",
"tests/test_project.py::CachedProjectTest::test_project_contains",
"tests/test_project.py::CachedProjectTest::test_rename_workspace",
"tests/test_project.py::CachedProjectTest::test_repair_corrupted_workspace",
"tests/test_project.py::CachedProjectTest::test_repr",
"tests/test_project.py::CachedProjectTest::test_root_directory",
"tests/test_project.py::CachedProjectTest::test_schema",
"tests/test_project.py::CachedProjectTest::test_schema_difference",
"tests/test_project.py::CachedProjectTest::test_schema_eval",
"tests/test_project.py::CachedProjectTest::test_schema_init",
"tests/test_project.py::CachedProjectTest::test_schema_subset",
"tests/test_project.py::CachedProjectTest::test_signac_project_crawler",
"tests/test_project.py::CachedProjectTest::test_str",
"tests/test_project.py::CachedProjectTest::test_temp_project",
"tests/test_project.py::CachedProjectTest::test_workspace_broken_link_error_on_find",
"tests/test_project.py::CachedProjectTest::test_workspace_directory",
"tests/test_project.py::CachedProjectTest::test_workspace_directory_with_env_variable",
"tests/test_project.py::CachedProjectTest::test_workspace_path_normalization",
"tests/test_project.py::CachedProjectTest::test_workspace_read_only_path",
"tests/test_project.py::CachedProjectTest::test_write_read_statepoint",
"tests/test_project.py::ProjectInitTest::test_get_project",
"tests/test_project.py::ProjectInitTest::test_get_project_non_local",
"tests/test_project.py::ProjectInitTest::test_init",
"tests/test_project.py::ProjectInitTest::test_nested_project",
"tests/test_project.py::ProjectPicklingTest::test_pickle_jobs_directly",
"tests/test_project.py::ProjectPicklingTest::test_pickle_project_empty",
"tests/test_project.py::ProjectPicklingTest::test_pickle_project_with_jobs"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-02-09 05:32:21+00:00
|
bsd-3-clause
| 2,544 |
|
glotzerlab__signac-169
|
diff --git a/changelog.txt b/changelog.txt
index 5845ceaf..753203ee 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -20,6 +20,7 @@ next
----
- Add command line options ``--sp`` and ``--doc`` for ``signac find`` that allow users to display key-value pairs of the state point and document in combination with the job id (#97, #146).
+ - Fix: Searches for whole numbers will match all numerically matching integers regardless of whether they are stored as decimals or whole numbers (#169).
[1.0.0] -- 2019-02-28
diff --git a/contributors.txt b/contributors.txt
index 2428d45d..3d92714b 100644
--- a/contributors.txt
+++ b/contributors.txt
@@ -7,3 +7,4 @@ Bradley Dice
Tim Moore
Pengji Zhou
Eric Harper
+Kelly Wang
diff --git a/signac/contrib/collection.py b/signac/contrib/collection.py
index ab733539..23df2fde 100644
--- a/signac/contrib/collection.py
+++ b/signac/contrib/collection.py
@@ -12,13 +12,14 @@
# on files on the local file system instead of a MongoDB database.
#
# [1]: https://github.com/mongodb/mongo-python-driver
-import sys
+import argparse
import io
-import re
import logging
-import argparse
import operator
+import re
+import sys
from itertools import islice
+from numbers import Number
from ..core import json
from ..common import six
@@ -30,7 +31,6 @@ else:
from collections.abc import Mapping
if six.PY2 or (six.PY3 and sys.version_info.minor < 5):
-
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
else:
@@ -620,7 +620,21 @@ class Collection(object):
raise KeyError("Unknown expression-operator '{}'.".format(op))
else:
index = self.index(key, build=True)
- return index.get(value, set())
+ # Check to see if 'value' is a floating point type but an
+ # integer value (e.g., 4.0), and search for both the int and float
+ # values. This allows the user to find statepoints that have
+ # integer-valued keys that are stored as floating point types.
+ # Note that this both cases: 1) user searches for an int and hopes
+ # to find values that are stored as integer-valued floats and 2) user
+ # searches for a integer-valued float and hopes to find ints.
+ # This way, both `signac find x 4.0` and `signac find x 4` would
+ # return jobs where `sp.x` is stored as either 4.0 or 4.
+ if isinstance(value, Number) and float(value).is_integer():
+ result_float = index.get(_float(value), set())
+ result_int = index.get(int(value), set())
+ return result_int.union(result_float)
+ else:
+ return index.get(value, set())
def _find_result(self, expr):
if not len(expr):
|
glotzerlab/signac
|
8da87575a3499ec5db77bb78780a1d1bada66056
|
diff --git a/tests/test_collection.py b/tests/test_collection.py
index 9c3fa7d4..8431545c 100644
--- a/tests/test_collection.py
+++ b/tests/test_collection.py
@@ -135,12 +135,14 @@ class CollectionTest(unittest.TestCase):
def test_int_float_equality(self):
self.c.insert_one(dict(a=1))
self.c.insert_one(dict(a=1.0))
- self.assertEqual(len(self.c.find(dict(a=1))), 1)
- self.assertEqual(len(self.c.find(dict(a=1.0))), 1)
+ self.assertEqual(len(self.c.find(dict(a=1))), 2)
+ self.assertEqual(len(self.c.find(dict(a=1.0))), 2)
+ """
for doc in self.c.find(dict(a=1)):
self.assertEqual(type(doc['a']), int)
for doc in self.c.find(dict(a=1.0)):
self.assertEqual(type(doc['a']), float)
+ """
def test_copy(self):
docs = [dict(_id=str(i)) for i in range(10)]
@@ -259,7 +261,7 @@ class CollectionTest(unittest.TestCase):
self.c.update(docs)
self.assertEqual(len(self.c.find()), len(docs))
self.assertEqual(len(self.c.find({'a': 0})), 1)
- self.assertEqual(len(self.c.find({'a': 0.0})), 0)
+ self.assertEqual(len(self.c.find({'a': 0.0})), 1)
self.assertEqual(list(self.c.find({'a': 0}))[0], docs[0])
self.assertEqual(len(self.c.find({'a': -1})), 0)
self.assertEqual(len(self.c.find({'a.b': 0})), 0)
@@ -276,7 +278,7 @@ class CollectionTest(unittest.TestCase):
docs = [dict(a=float(i)) for i in range(10)]
self.c.update(docs)
self.assertEqual(len(self.c.find()), len(docs))
- self.assertEqual(len(self.c.find({'a': 0})), 0)
+ self.assertEqual(len(self.c.find({'a': 0})), 1)
self.assertEqual(len(self.c.find({'a': 0.0})), 1)
self.assertEqual(list(self.c.find({'a': 0.0}))[0], docs[0])
self.assertEqual(len(self.c.find({'a': -1})), 0)
|
Surprising type comparisons with $signac find
### Description
I have a statepoint parameter that has some `int` values and some `decimal` values. When I use `signac find` to find jobs filtering by this parameter, it only returns jobs where both the value and type of the jobs' statepoints match the search parameters. I would expect the behavior to match that of python's `==` operator, e.g., `$signac find x 10` would return jobs where `job.sp.x = 10` and `job.sp.x = 10.0`.
### To reproduce
```
$ signac init test
Initialized project 'test'.
$ python
>>> import signac
>>> project = signac.get_project()
>>> job = project.open_job({'x': 100**0.5})
>>> job.init()
>>> exit()
$ signac find x 10
Interpreted filter arguments as '{"x": 10}'.
$ signac find x 10.
Interpreted filter arguments as '{"x": 10.0}'.
13dd08001115e65c96a2eeda9ce3505b
```
### System configuration
Please complete the following information:
```
$ python -c 'import platform; print(platform.platform()); import sys; print(sys.version); import signac; print(signac.__version__)'
Darwin-17.7.0-x86_64-i386-64bit
3.5.5 | packaged by conda-forge | (default, Jul 23 2018, 23:45:11)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)]
0.9.5
```
|
0.0
|
8da87575a3499ec5db77bb78780a1d1bada66056
|
[
"tests/test_collection.py::CollectionTest::test_find_float",
"tests/test_collection.py::CollectionTest::test_find_integer",
"tests/test_collection.py::CollectionTest::test_int_float_equality",
"tests/test_collection.py::CompressedCollectionTest::test_find_float",
"tests/test_collection.py::CompressedCollectionTest::test_find_integer",
"tests/test_collection.py::CompressedCollectionTest::test_int_float_equality",
"tests/test_collection.py::FileCollectionTest::test_find_float",
"tests/test_collection.py::FileCollectionTest::test_find_integer",
"tests/test_collection.py::FileCollectionTest::test_int_float_equality",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_float",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_integer",
"tests/test_collection.py::BinaryFileCollectionTest::test_int_float_equality",
"tests/test_collection.py::FileCollectionAppendTest::test_find_float",
"tests/test_collection.py::FileCollectionAppendTest::test_find_integer",
"tests/test_collection.py::FileCollectionAppendTest::test_int_float_equality",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_float",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_integer",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_int_float_equality",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_float",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_integer",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_int_float_equality",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_float",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_integer",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_int_float_equality",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_float",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_integer",
"tests/test_collection.py::ZippedFileCollectionTest::test_int_float_equality",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_float",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_integer",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_int_float_equality",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_float",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_integer",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_int_float_equality"
] |
[
"tests/test_collection.py::CollectionTest::test_buffer_size",
"tests/test_collection.py::CollectionTest::test_clear",
"tests/test_collection.py::CollectionTest::test_contains",
"tests/test_collection.py::CollectionTest::test_copy",
"tests/test_collection.py::CollectionTest::test_delete",
"tests/test_collection.py::CollectionTest::test_delete_one",
"tests/test_collection.py::CollectionTest::test_find_arithmetic_operators",
"tests/test_collection.py::CollectionTest::test_find_array_operators",
"tests/test_collection.py::CollectionTest::test_find_exists_operator",
"tests/test_collection.py::CollectionTest::test_find_int_float",
"tests/test_collection.py::CollectionTest::test_find_logical_operators",
"tests/test_collection.py::CollectionTest::test_find_near",
"tests/test_collection.py::CollectionTest::test_find_nested",
"tests/test_collection.py::CollectionTest::test_find_one",
"tests/test_collection.py::CollectionTest::test_find_regular_expression",
"tests/test_collection.py::CollectionTest::test_find_type_expression",
"tests/test_collection.py::CollectionTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::CollectionTest::test_find_types",
"tests/test_collection.py::CollectionTest::test_find_where_expression",
"tests/test_collection.py::CollectionTest::test_index",
"tests/test_collection.py::CollectionTest::test_init",
"tests/test_collection.py::CollectionTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::CollectionTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::CollectionTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::CollectionTest::test_init_with_list_without_ids",
"tests/test_collection.py::CollectionTest::test_init_with_non_serializable",
"tests/test_collection.py::CollectionTest::test_insert",
"tests/test_collection.py::CollectionTest::test_insert_and_remove",
"tests/test_collection.py::CollectionTest::test_insert_docs_with_dots",
"tests/test_collection.py::CollectionTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::CollectionTest::test_insert_multiple",
"tests/test_collection.py::CollectionTest::test_insert_non_serializable",
"tests/test_collection.py::CollectionTest::test_iteration",
"tests/test_collection.py::CollectionTest::test_nested_lists",
"tests/test_collection.py::CollectionTest::test_reindex",
"tests/test_collection.py::CollectionTest::test_replace_docs_with_dots",
"tests/test_collection.py::CollectionTest::test_replace_one",
"tests/test_collection.py::CollectionTest::test_replace_one_simple",
"tests/test_collection.py::CollectionTest::test_update",
"tests/test_collection.py::CollectionTest::test_update_collision",
"tests/test_collection.py::CompressedCollectionTest::test_buffer_size",
"tests/test_collection.py::CompressedCollectionTest::test_clear",
"tests/test_collection.py::CompressedCollectionTest::test_compression",
"tests/test_collection.py::CompressedCollectionTest::test_contains",
"tests/test_collection.py::CompressedCollectionTest::test_copy",
"tests/test_collection.py::CompressedCollectionTest::test_delete",
"tests/test_collection.py::CompressedCollectionTest::test_delete_one",
"tests/test_collection.py::CompressedCollectionTest::test_find_arithmetic_operators",
"tests/test_collection.py::CompressedCollectionTest::test_find_array_operators",
"tests/test_collection.py::CompressedCollectionTest::test_find_exists_operator",
"tests/test_collection.py::CompressedCollectionTest::test_find_int_float",
"tests/test_collection.py::CompressedCollectionTest::test_find_logical_operators",
"tests/test_collection.py::CompressedCollectionTest::test_find_near",
"tests/test_collection.py::CompressedCollectionTest::test_find_nested",
"tests/test_collection.py::CompressedCollectionTest::test_find_one",
"tests/test_collection.py::CompressedCollectionTest::test_find_regular_expression",
"tests/test_collection.py::CompressedCollectionTest::test_find_type_expression",
"tests/test_collection.py::CompressedCollectionTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::CompressedCollectionTest::test_find_types",
"tests/test_collection.py::CompressedCollectionTest::test_find_where_expression",
"tests/test_collection.py::CompressedCollectionTest::test_index",
"tests/test_collection.py::CompressedCollectionTest::test_init",
"tests/test_collection.py::CompressedCollectionTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::CompressedCollectionTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::CompressedCollectionTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::CompressedCollectionTest::test_init_with_list_without_ids",
"tests/test_collection.py::CompressedCollectionTest::test_init_with_non_serializable",
"tests/test_collection.py::CompressedCollectionTest::test_insert",
"tests/test_collection.py::CompressedCollectionTest::test_insert_and_remove",
"tests/test_collection.py::CompressedCollectionTest::test_insert_docs_with_dots",
"tests/test_collection.py::CompressedCollectionTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::CompressedCollectionTest::test_insert_multiple",
"tests/test_collection.py::CompressedCollectionTest::test_insert_non_serializable",
"tests/test_collection.py::CompressedCollectionTest::test_iteration",
"tests/test_collection.py::CompressedCollectionTest::test_nested_lists",
"tests/test_collection.py::CompressedCollectionTest::test_reindex",
"tests/test_collection.py::CompressedCollectionTest::test_replace_docs_with_dots",
"tests/test_collection.py::CompressedCollectionTest::test_replace_one",
"tests/test_collection.py::CompressedCollectionTest::test_replace_one_simple",
"tests/test_collection.py::CompressedCollectionTest::test_update",
"tests/test_collection.py::CompressedCollectionTest::test_update_collision",
"tests/test_collection.py::FileCollectionTestBadJson::test_read",
"tests/test_collection.py::FileCollectionTestReadOnly::test_read",
"tests/test_collection.py::FileCollectionTestReadOnly::test_write_on_readonly",
"tests/test_collection.py::FileCollectionTest::test_buffer_size",
"tests/test_collection.py::FileCollectionTest::test_clear",
"tests/test_collection.py::FileCollectionTest::test_contains",
"tests/test_collection.py::FileCollectionTest::test_copy",
"tests/test_collection.py::FileCollectionTest::test_delete",
"tests/test_collection.py::FileCollectionTest::test_delete_one",
"tests/test_collection.py::FileCollectionTest::test_find_arithmetic_operators",
"tests/test_collection.py::FileCollectionTest::test_find_array_operators",
"tests/test_collection.py::FileCollectionTest::test_find_exists_operator",
"tests/test_collection.py::FileCollectionTest::test_find_int_float",
"tests/test_collection.py::FileCollectionTest::test_find_logical_operators",
"tests/test_collection.py::FileCollectionTest::test_find_near",
"tests/test_collection.py::FileCollectionTest::test_find_nested",
"tests/test_collection.py::FileCollectionTest::test_find_one",
"tests/test_collection.py::FileCollectionTest::test_find_regular_expression",
"tests/test_collection.py::FileCollectionTest::test_find_type_expression",
"tests/test_collection.py::FileCollectionTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::FileCollectionTest::test_find_types",
"tests/test_collection.py::FileCollectionTest::test_find_where_expression",
"tests/test_collection.py::FileCollectionTest::test_index",
"tests/test_collection.py::FileCollectionTest::test_init",
"tests/test_collection.py::FileCollectionTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::FileCollectionTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::FileCollectionTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::FileCollectionTest::test_init_with_list_without_ids",
"tests/test_collection.py::FileCollectionTest::test_init_with_non_serializable",
"tests/test_collection.py::FileCollectionTest::test_insert",
"tests/test_collection.py::FileCollectionTest::test_insert_and_remove",
"tests/test_collection.py::FileCollectionTest::test_insert_docs_with_dots",
"tests/test_collection.py::FileCollectionTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::FileCollectionTest::test_insert_multiple",
"tests/test_collection.py::FileCollectionTest::test_insert_non_serializable",
"tests/test_collection.py::FileCollectionTest::test_iteration",
"tests/test_collection.py::FileCollectionTest::test_nested_lists",
"tests/test_collection.py::FileCollectionTest::test_reindex",
"tests/test_collection.py::FileCollectionTest::test_replace_docs_with_dots",
"tests/test_collection.py::FileCollectionTest::test_replace_one",
"tests/test_collection.py::FileCollectionTest::test_replace_one_simple",
"tests/test_collection.py::FileCollectionTest::test_update",
"tests/test_collection.py::FileCollectionTest::test_update_collision",
"tests/test_collection.py::FileCollectionTest::test_write_and_flush",
"tests/test_collection.py::FileCollectionTest::test_write_flush_and_reopen",
"tests/test_collection.py::BinaryFileCollectionTest::test_buffer_size",
"tests/test_collection.py::BinaryFileCollectionTest::test_clear",
"tests/test_collection.py::BinaryFileCollectionTest::test_contains",
"tests/test_collection.py::BinaryFileCollectionTest::test_copy",
"tests/test_collection.py::BinaryFileCollectionTest::test_delete",
"tests/test_collection.py::BinaryFileCollectionTest::test_delete_one",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_arithmetic_operators",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_array_operators",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_exists_operator",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_int_float",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_logical_operators",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_near",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_nested",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_one",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_regular_expression",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_type_expression",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_types",
"tests/test_collection.py::BinaryFileCollectionTest::test_find_where_expression",
"tests/test_collection.py::BinaryFileCollectionTest::test_index",
"tests/test_collection.py::BinaryFileCollectionTest::test_init",
"tests/test_collection.py::BinaryFileCollectionTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::BinaryFileCollectionTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::BinaryFileCollectionTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::BinaryFileCollectionTest::test_init_with_list_without_ids",
"tests/test_collection.py::BinaryFileCollectionTest::test_init_with_non_serializable",
"tests/test_collection.py::BinaryFileCollectionTest::test_insert",
"tests/test_collection.py::BinaryFileCollectionTest::test_insert_and_remove",
"tests/test_collection.py::BinaryFileCollectionTest::test_insert_docs_with_dots",
"tests/test_collection.py::BinaryFileCollectionTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::BinaryFileCollectionTest::test_insert_multiple",
"tests/test_collection.py::BinaryFileCollectionTest::test_insert_non_serializable",
"tests/test_collection.py::BinaryFileCollectionTest::test_iteration",
"tests/test_collection.py::BinaryFileCollectionTest::test_nested_lists",
"tests/test_collection.py::BinaryFileCollectionTest::test_reindex",
"tests/test_collection.py::BinaryFileCollectionTest::test_replace_docs_with_dots",
"tests/test_collection.py::BinaryFileCollectionTest::test_replace_one",
"tests/test_collection.py::BinaryFileCollectionTest::test_replace_one_simple",
"tests/test_collection.py::BinaryFileCollectionTest::test_update",
"tests/test_collection.py::BinaryFileCollectionTest::test_update_collision",
"tests/test_collection.py::FileCollectionAppendTest::test_buffer_size",
"tests/test_collection.py::FileCollectionAppendTest::test_clear",
"tests/test_collection.py::FileCollectionAppendTest::test_contains",
"tests/test_collection.py::FileCollectionAppendTest::test_copy",
"tests/test_collection.py::FileCollectionAppendTest::test_delete",
"tests/test_collection.py::FileCollectionAppendTest::test_delete_one",
"tests/test_collection.py::FileCollectionAppendTest::test_file_size",
"tests/test_collection.py::FileCollectionAppendTest::test_find_arithmetic_operators",
"tests/test_collection.py::FileCollectionAppendTest::test_find_array_operators",
"tests/test_collection.py::FileCollectionAppendTest::test_find_exists_operator",
"tests/test_collection.py::FileCollectionAppendTest::test_find_int_float",
"tests/test_collection.py::FileCollectionAppendTest::test_find_logical_operators",
"tests/test_collection.py::FileCollectionAppendTest::test_find_near",
"tests/test_collection.py::FileCollectionAppendTest::test_find_nested",
"tests/test_collection.py::FileCollectionAppendTest::test_find_one",
"tests/test_collection.py::FileCollectionAppendTest::test_find_regular_expression",
"tests/test_collection.py::FileCollectionAppendTest::test_find_type_expression",
"tests/test_collection.py::FileCollectionAppendTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::FileCollectionAppendTest::test_find_types",
"tests/test_collection.py::FileCollectionAppendTest::test_find_where_expression",
"tests/test_collection.py::FileCollectionAppendTest::test_index",
"tests/test_collection.py::FileCollectionAppendTest::test_init",
"tests/test_collection.py::FileCollectionAppendTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::FileCollectionAppendTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::FileCollectionAppendTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::FileCollectionAppendTest::test_init_with_list_without_ids",
"tests/test_collection.py::FileCollectionAppendTest::test_init_with_non_serializable",
"tests/test_collection.py::FileCollectionAppendTest::test_insert",
"tests/test_collection.py::FileCollectionAppendTest::test_insert_and_remove",
"tests/test_collection.py::FileCollectionAppendTest::test_insert_docs_with_dots",
"tests/test_collection.py::FileCollectionAppendTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::FileCollectionAppendTest::test_insert_multiple",
"tests/test_collection.py::FileCollectionAppendTest::test_insert_non_serializable",
"tests/test_collection.py::FileCollectionAppendTest::test_iteration",
"tests/test_collection.py::FileCollectionAppendTest::test_nested_lists",
"tests/test_collection.py::FileCollectionAppendTest::test_reindex",
"tests/test_collection.py::FileCollectionAppendTest::test_replace_docs_with_dots",
"tests/test_collection.py::FileCollectionAppendTest::test_replace_one",
"tests/test_collection.py::FileCollectionAppendTest::test_replace_one_simple",
"tests/test_collection.py::FileCollectionAppendTest::test_update",
"tests/test_collection.py::FileCollectionAppendTest::test_update_collision",
"tests/test_collection.py::FileCollectionAppendTest::test_write_and_flush",
"tests/test_collection.py::FileCollectionAppendTest::test_write_flush_and_reopen",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_buffer_size",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_clear",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_contains",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_copy",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_delete",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_delete_one",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_file_size",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_arithmetic_operators",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_array_operators",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_exists_operator",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_int_float",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_logical_operators",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_near",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_nested",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_one",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_regular_expression",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_type_expression",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_types",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_find_where_expression",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_index",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_init",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_init_with_list_without_ids",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_init_with_non_serializable",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_insert",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_insert_and_remove",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_insert_docs_with_dots",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_insert_multiple",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_insert_non_serializable",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_iteration",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_nested_lists",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_reindex",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_replace_docs_with_dots",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_replace_one",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_replace_one_simple",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_update",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_update_collision",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_write_and_flush",
"tests/test_collection.py::BinaryFileCollectionAppendTest::test_write_flush_and_reopen",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_buffer_size",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_clear",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_contains",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_copy",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_delete",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_delete_one",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_file_size",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_arithmetic_operators",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_array_operators",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_exists_operator",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_int_float",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_logical_operators",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_near",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_nested",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_one",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_regular_expression",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_type_expression",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_types",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_find_where_expression",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_index",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_init",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_init_with_list_without_ids",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_init_with_non_serializable",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_insert",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_insert_and_remove",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_insert_docs_with_dots",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_insert_multiple",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_insert_non_serializable",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_iteration",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_nested_lists",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_reindex",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_replace_docs_with_dots",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_replace_one",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_replace_one_simple",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_update",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_update_collision",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_write_and_flush",
"tests/test_collection.py::FileCollectionAppendPlusTest::test_write_flush_and_reopen",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_buffer_size",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_clear",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_contains",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_copy",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_delete",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_delete_one",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_file_size",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_arithmetic_operators",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_array_operators",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_exists_operator",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_int_float",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_logical_operators",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_near",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_nested",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_one",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_regular_expression",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_type_expression",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_types",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_find_where_expression",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_index",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_init",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_init_with_list_without_ids",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_init_with_non_serializable",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_insert",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_insert_and_remove",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_insert_docs_with_dots",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_insert_multiple",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_insert_non_serializable",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_iteration",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_nested_lists",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_reindex",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_replace_docs_with_dots",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_replace_one",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_replace_one_simple",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_update",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_update_collision",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_write_and_flush",
"tests/test_collection.py::BinaryFileCollectionAppendPlusTest::test_write_flush_and_reopen",
"tests/test_collection.py::ZippedFileCollectionTest::test_buffer_size",
"tests/test_collection.py::ZippedFileCollectionTest::test_clear",
"tests/test_collection.py::ZippedFileCollectionTest::test_compression_level",
"tests/test_collection.py::ZippedFileCollectionTest::test_contains",
"tests/test_collection.py::ZippedFileCollectionTest::test_copy",
"tests/test_collection.py::ZippedFileCollectionTest::test_delete",
"tests/test_collection.py::ZippedFileCollectionTest::test_delete_one",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_arithmetic_operators",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_array_operators",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_exists_operator",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_int_float",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_logical_operators",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_near",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_nested",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_one",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_regular_expression",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_type_expression",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_types",
"tests/test_collection.py::ZippedFileCollectionTest::test_find_where_expression",
"tests/test_collection.py::ZippedFileCollectionTest::test_index",
"tests/test_collection.py::ZippedFileCollectionTest::test_init",
"tests/test_collection.py::ZippedFileCollectionTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::ZippedFileCollectionTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::ZippedFileCollectionTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::ZippedFileCollectionTest::test_init_with_list_without_ids",
"tests/test_collection.py::ZippedFileCollectionTest::test_init_with_non_serializable",
"tests/test_collection.py::ZippedFileCollectionTest::test_insert",
"tests/test_collection.py::ZippedFileCollectionTest::test_insert_and_remove",
"tests/test_collection.py::ZippedFileCollectionTest::test_insert_docs_with_dots",
"tests/test_collection.py::ZippedFileCollectionTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::ZippedFileCollectionTest::test_insert_multiple",
"tests/test_collection.py::ZippedFileCollectionTest::test_insert_non_serializable",
"tests/test_collection.py::ZippedFileCollectionTest::test_iteration",
"tests/test_collection.py::ZippedFileCollectionTest::test_nested_lists",
"tests/test_collection.py::ZippedFileCollectionTest::test_reindex",
"tests/test_collection.py::ZippedFileCollectionTest::test_replace_docs_with_dots",
"tests/test_collection.py::ZippedFileCollectionTest::test_replace_one",
"tests/test_collection.py::ZippedFileCollectionTest::test_replace_one_simple",
"tests/test_collection.py::ZippedFileCollectionTest::test_update",
"tests/test_collection.py::ZippedFileCollectionTest::test_update_collision",
"tests/test_collection.py::ZippedFileCollectionTest::test_write_and_flush",
"tests/test_collection.py::ZippedFileCollectionTest::test_write_flush_and_reopen",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_buffer_size",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_clear",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_compression_level",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_contains",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_copy",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_delete",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_delete_one",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_arithmetic_operators",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_array_operators",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_exists_operator",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_int_float",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_logical_operators",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_near",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_nested",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_one",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_regular_expression",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_type_expression",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_types",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_find_where_expression",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_index",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_init",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_init_with_list_without_ids",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_init_with_non_serializable",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_insert",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_insert_and_remove",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_insert_docs_with_dots",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_insert_multiple",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_insert_non_serializable",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_iteration",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_nested_lists",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_reindex",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_replace_docs_with_dots",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_replace_one",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_replace_one_simple",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_update",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_update_collision",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_write_and_flush",
"tests/test_collection.py::ZippedFileCollectionAppendTest::test_write_flush_and_reopen",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_buffer_size",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_clear",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_compression_level",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_contains",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_copy",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_delete",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_delete_one",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_arithmetic_operators",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_array_operators",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_exists_operator",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_int_float",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_logical_operators",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_near",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_nested",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_one",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_regular_expression",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_type_expression",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_type_integer_values_identical_keys",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_types",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_find_where_expression",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_index",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_init",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_init_with_list_with_and_without_ids",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_init_with_list_with_ids_non_sequential",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_init_with_list_with_ids_sequential",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_init_with_list_without_ids",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_init_with_non_serializable",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_insert",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_insert_and_remove",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_insert_docs_with_dots",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_insert_docs_with_dots_force",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_insert_multiple",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_insert_non_serializable",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_iteration",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_nested_lists",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_reindex",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_replace_docs_with_dots",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_replace_one",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_replace_one_simple",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_update",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_update_collision",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_write_and_flush",
"tests/test_collection.py::ZippedFileCollectionAppendPlusTest::test_write_flush_and_reopen"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-03-22 17:26:54+00:00
|
bsd-3-clause
| 2,545 |
|
glotzerlab__signac-199
|
diff --git a/.circleci/config.yml b/.circleci/config.yml
index 4c584fb7..3056353c 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -65,7 +65,7 @@ jobs:
command: |
. venv/bin/activate
coverage run -m unittest discover tests/ -v
- pip install python-rapidjson==0.7 && coverage run -m unittest discover tests/ -v
+ pip install python-rapidjson==0.7.1 && coverage run -m unittest discover tests/ -v
coverage report -i
codecov
diff --git a/signac/contrib/filterparse.py b/signac/contrib/filterparse.py
index af8f0529..1ec15bbe 100644
--- a/signac/contrib/filterparse.py
+++ b/signac/contrib/filterparse.py
@@ -33,7 +33,7 @@ def _is_regex(q):
def _parse_json(q):
try:
return json.loads(q)
- except json.decoder.JSONDecodeError:
+ except json.JSONDecodeError:
_print_err("Failed to parse query argument. "
"Ensure that '{}' is valid JSON!".format(q))
raise
diff --git a/signac/core/json.py b/signac/core/json.py
index fccdefd5..3de9943d 100644
--- a/signac/core/json.py
+++ b/signac/core/json.py
@@ -16,6 +16,12 @@ except ImportError:
try:
import rapidjson as json
from rapidjson import Encoder
+ try:
+ # Defined for rapidjson >= 0.7.1
+ from rapidjson import JSONDecodeError
+ except ImportError:
+ # rapidjson < 0.7.1 raises a ValueError
+ JSONDecodeError = ValueError
class JSONEncoder(Encoder):
encode = Encoder.__call__
@@ -24,6 +30,11 @@ try:
except ImportError:
import json
from json import JSONEncoder
+ try:
+ from json.decoder import JSONDecodeError
+ except ImportError:
+ # JSONDecodeError doesn't exist for Python 2
+ JSONDecodeError = ValueError
logger.debug(msg.format('json'))
@@ -63,4 +74,4 @@ def dumps(o, sort_keys=False, indent=None):
return CustomJSONEncoder(sort_keys=sort_keys, indent=indent).encode(o)
-__all__ = ['loads', 'dumps']
+__all__ = ['loads', 'dumps', 'JSONDecodeError']
|
glotzerlab/signac
|
01fc15576d130d721c4970184d537dec3b305287
|
diff --git a/tests/test_find_command_line_interface.py b/tests/test_find_command_line_interface.py
index a2db94a1..19f35eea 100644
--- a/tests/test_find_command_line_interface.py
+++ b/tests/test_find_command_line_interface.py
@@ -1,12 +1,17 @@
-# Copyright (c) 2017 The Regents of the University of Michigan
+# Copyright (c) 2019 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
+import io
import os
+import sys
import json
import unittest
from itertools import chain
+from contextlib import contextmanager
+from signac.common import six
from signac.contrib.filterparse import parse_filter_arg
+from signac.core.json import JSONDecodeError
FILTERS = [
{'a': 0},
@@ -65,6 +70,29 @@ ARRAY_EXPRESSIONS = [
]
+class StringIO(io.StringIO):
+ "PY27 compatibility layer."
+
+ def write(self, s):
+ if six.PY2:
+ super(StringIO, self).write(unicode(s)) # noqa
+ else:
+ super(StringIO, self).write(s)
+
+
+@contextmanager
+def redirect_stderr(new_target=None):
+ "Temporarily redirect all output to stderr to new_target."
+ if new_target is None:
+ new_target = StringIO()
+ old_target = sys.stderr
+ try:
+ sys.stderr = new_target
+ yield
+ finally:
+ sys.stderr = old_target
+
+
class FindCommandLineInterfaceTest(unittest.TestCase):
@staticmethod
@@ -92,6 +120,11 @@ class FindCommandLineInterfaceTest(unittest.TestCase):
for expr in chain(ARITHMETIC_EXPRESSIONS, ARRAY_EXPRESSIONS):
self.assertEqual(self._parse(['a', json.dumps(expr)]), {'a': expr})
+ def test_invalid_json(self):
+ with redirect_stderr():
+ with self.assertRaises(JSONDecodeError):
+ parse_filter_arg(['{"x": True}'])
+
if __name__ == '__main__':
unittest.main()
|
Bug in JSON error checking
<!-- Please replace the text in the individual sections below. -->
### Description
The rapidjson package does not have a `decoder` submodule. Since we don't have a corresponding compatibility layer, things like `json.decoder.JSONDecodeError` fail.
### To reproduce
```
$ signac init json_decoder
$ signac find '{"x": True}'
27958648a9e57fcd66ae5e31ff3359e9
$ signac find '{"x": True}' # This is invalid JSON, the expected behavior is to raise an error indicating that the JSON is invalid
Error: module 'signac.core.json' has no attribute 'decoder' # The actual output
```
|
0.0
|
01fc15576d130d721c4970184d537dec3b305287
|
[
"tests/test_find_command_line_interface.py::FindCommandLineInterfaceTest::test_interpret_json",
"tests/test_find_command_line_interface.py::FindCommandLineInterfaceTest::test_interpret_mixed_key_value",
"tests/test_find_command_line_interface.py::FindCommandLineInterfaceTest::test_interpret_simple",
"tests/test_find_command_line_interface.py::FindCommandLineInterfaceTest::test_invalid_json"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-05-26 19:26:38+00:00
|
bsd-3-clause
| 2,546 |
|
glotzerlab__signac-211
|
diff --git a/changelog.txt b/changelog.txt
index daf2b1c6..145174d3 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -27,6 +27,7 @@ next
- Fix issue causing a failure of the automatic conversion of valid key types (#168, #205).
- Improve the 'dots in keys' error message to make it easier to fix related issues (#170, #205).
- Update the ``__repr__`` and ``__repr_html__`` implementations of the ``Project`, ``Job``, and ``JobsCursor`` classes (#193).
+ - Fix issue with rendering views from the command line for single job project (#208).
- Fix issue with heterogeneous types in state point values that are lists (#209).
[1.1.0] -- 2019-05-19
diff --git a/signac/contrib/import_export.py b/signac/contrib/import_export.py
index 8a5a6053..b63d9a08 100644
--- a/signac/contrib/import_export.py
+++ b/signac/contrib/import_export.py
@@ -44,7 +44,9 @@ def _make_schema_based_path_function(jobs, exclude_keys=None, delimiter_nested='
"Generate schema based paths as a function of the given jobs."
from .schema import _build_job_statepoint_index
if len(jobs) <= 1:
- return lambda job: ''
+ # The lambda must (optionally) take a format spec argument to match the
+ # signature of the path function below.
+ return lambda job, sep=None: ''
index = [{'_id': job._id, 'statepoint': job.sp()} for job in jobs]
jsi = _build_job_statepoint_index(jobs=jobs, exclude_const=True, index=index)
|
glotzerlab/signac
|
f83f86d7436ad7c362deeb541230c7d1e3ac5cff
|
diff --git a/tests/test_shell.py b/tests/test_shell.py
index 0b33d92c..a7a9dd5c 100644
--- a/tests/test_shell.py
+++ b/tests/test_shell.py
@@ -142,6 +142,21 @@ class BasicShellTest(unittest.TestCase):
self.assertIn('b', doc)
self.assertEqual(doc['b'], 0)
+ def test_view_single(self):
+ """Check whether command line views work for single job workspaces."""
+ self.call('python -m signac init my_project'.split())
+ project = signac.Project()
+ sps = [{'a': i} for i in range(1)]
+ for sp in sps:
+ project.open_job(sp).init()
+ os.mkdir('view')
+ self.call('python -m signac view'.split())
+ for sp in sps:
+ self.assertTrue(os.path.isdir('view/job'))
+ self.assertEqual(
+ os.path.realpath('view/job'),
+ os.path.realpath(project.open_job(sp).workspace()))
+
def test_view(self):
self.call('python -m signac init my_project'.split())
project = signac.Project()
|
view function regression in latest version
<!-- Please replace the text in the individual sections below. -->
### Description
"...there appears to be a regression affecting the view function in the latest version." per @csadorf in the Gitter signac lobby
### To reproduce
```
# init.py
import signac
project = signac.init('fmria_project')
sp = {'monomer':'nfa'}
job = project.open_job(sp)
job.init()
```
`$ python3 init.py`
`$ signac view`
### Error output
`Error: <lambda>() takes 1 positional argument but 2 were given`
### System configuration
Please complete the following information:
- Operating System [e.g. macOS]: CentOS `6.10 (final)`
- Version of Python [e.g. 3.7]: `3.7.3`
- Version of signac [e.g. 1.0]: `1.1.0`
|
0.0
|
f83f86d7436ad7c362deeb541230c7d1e3ac5cff
|
[
"tests/test_shell.py::BasicShellTest::test_view_single"
] |
[
"tests/test_shell.py::BasicShellTest::test_find",
"tests/test_shell.py::BasicShellTest::test_index",
"tests/test_shell.py::BasicShellTest::test_init_project",
"tests/test_shell.py::BasicShellTest::test_init_project_in_project_root",
"tests/test_shell.py::BasicShellTest::test_job_with_argument",
"tests/test_shell.py::BasicShellTest::test_job_with_argument_create_workspace",
"tests/test_shell.py::BasicShellTest::test_job_with_argument_workspace",
"tests/test_shell.py::BasicShellTest::test_project_id",
"tests/test_shell.py::BasicShellTest::test_project_workspace",
"tests/test_shell.py::BasicShellTest::test_remove",
"tests/test_shell.py::BasicShellTest::test_shell",
"tests/test_shell.py::BasicShellTest::test_shell_with_jobs",
"tests/test_shell.py::BasicShellTest::test_shell_with_jobs_and_selection",
"tests/test_shell.py::BasicShellTest::test_shell_with_jobs_and_selection_only_one_job",
"tests/test_shell.py::BasicShellTest::test_statepoint",
"tests/test_shell.py::BasicShellTest::test_view"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-07-19 16:47:56+00:00
|
bsd-3-clause
| 2,547 |
|
glotzerlab__signac-252
|
diff --git a/changelog.txt b/changelog.txt
index ee46ffa0..e3dfe099 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -34,6 +34,7 @@ Fixed
+++++
- Attempting to create a linked view for a Project on Windows now raises an informative error message.
+ - Project configuration is initialized using ConfigObj, allowing the configuration to include commas and special characters (#251, #252).
Deprecated
++++++++++
diff --git a/signac/contrib/project.py b/signac/contrib/project.py
index 96b7ce8f..c8804173 100644
--- a/signac/contrib/project.py
+++ b/signac/contrib/project.py
@@ -24,7 +24,7 @@ from ..core import json
from ..core.jsondict import JSONDict
from ..core.h5store import H5StoreManager
from .collection import Collection
-from ..common.config import load_config, Config
+from ..common.config import get_config, load_config, Config
from ..sync import sync_projects
from .job import Job
from .hashing import calc_id
@@ -1461,10 +1461,11 @@ class Project(object):
fn_config = os.path.join(root, 'signac.rc')
if make_dir:
_mkdir_p(os.path.dirname(fn_config))
- with open(fn_config, 'a') as config_file:
- config_file.write('project={}\n'.format(name))
- if workspace is not None:
- config_file.write('workspace_dir={}\n'.format(workspace))
+ config = get_config(fn_config)
+ config['project'] = name
+ if workspace is not None:
+ config['workspace_dir'] = workspace
+ config.write()
project = cls.get_project(root=root)
assert project.get_id() == str(name)
return project
|
glotzerlab/signac
|
51381aba9f18837ab29f8565964dc4acc5fc1c77
|
diff --git a/tests/test_project.py b/tests/test_project.py
index e34b1b24..2870e2d7 100644
--- a/tests/test_project.py
+++ b/tests/test_project.py
@@ -9,6 +9,7 @@ import logging
import itertools
import json
import pickle
+import string
from tarfile import TarFile
from zipfile import ZipFile
from tempfile import TemporaryDirectory
@@ -1794,6 +1795,14 @@ class ProjectInitTest(unittest.TestCase):
self.assertEqual(project.workspace(), os.path.join(root, 'workspace'))
self.assertEqual(project.root_directory(), root)
+ def test_get_project_all_printable_characters(self):
+ root = self._tmp_dir.name
+ with self.assertRaises(LookupError):
+ signac.get_project(root=root)
+ project_name = 'testproject' + string.printable
+ project = signac.init_project(name=project_name, root=root)
+ self.assertEqual(project.get_id(), project_name)
+
def test_get_project_non_local(self):
root = self._tmp_dir.name
subdir = os.path.join(root, 'subdir')
|
Commas in project names cause unexpected errors
### Description
I was creating a signac project named `oP6-As2(Co,Ni,Fe)_r`. This is problematic because the commas are not understood by the configuration parser.
### To reproduce
```python
>>> import signac
>>> signac.init_project('oP6-As2(Co,Ni,Fe)_r')
Traceback (most recent call last):
File ".../signac/contrib/project.py", line 1462, in init_project
project = cls.get_project(root=root, search=False)
File ".../signac/contrib/project.py", line 1509, in get_project
"Unable to determine project id for path '{}'.".format(os.path.abspath(root)))
LookupError: Unable to determine project id for path '/tmp_signac'.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../signac/contrib/project.py", line 1867, in init_project
return Project.init_project(name=name, root=root, workspace=workspace, make_dir=make_dir)
File ".../signac/contrib/project.py", line 1472, in init_project
assert project.get_id() == str(name)
AssertionError
```
or
```bash
$ signac init "oP6-As2(Co,Ni,Fe)_r"
Error:
```
In both cases, a file `signac.rc` is created with the contents:
```ini
project=oP6-As2(Co,Ni,Fe)_r
```
The project name is misinterpreted as a list:
```python
>>> project.get_id()
"['oP6-As2(Co', 'Ni', 'Fe)_r']"
```
### System configuration
- Operating System: macOS
- Version of Python: 3.7.3
- Version of signac [e.g. 1.0]: 1.2.0 (running on latest `master`)
|
0.0
|
51381aba9f18837ab29f8565964dc4acc5fc1c77
|
[
"tests/test_project.py::ProjectInitTest::test_get_project_all_printable_characters"
] |
[
"tests/test_project.py::ProjectTest::test_config_modification",
"tests/test_project.py::ProjectTest::test_corrupted_statepoint_file",
"tests/test_project.py::ProjectTest::test_custom_job_class",
"tests/test_project.py::ProjectTest::test_custom_project",
"tests/test_project.py::ProjectTest::test_doc",
"tests/test_project.py::ProjectTest::test_document",
"tests/test_project.py::ProjectTest::test_find_job_ids",
"tests/test_project.py::ProjectTest::test_find_jobs",
"tests/test_project.py::ProjectTest::test_find_jobs_arithmetic_operators",
"tests/test_project.py::ProjectTest::test_find_jobs_logical_operators",
"tests/test_project.py::ProjectTest::test_find_jobs_next",
"tests/test_project.py::ProjectTest::test_fn",
"tests/test_project.py::ProjectTest::test_get",
"tests/test_project.py::ProjectTest::test_get_id",
"tests/test_project.py::ProjectTest::test_index",
"tests/test_project.py::ProjectTest::test_isfile",
"tests/test_project.py::ProjectTest::test_iteration",
"tests/test_project.py::ProjectTest::test_job_clone",
"tests/test_project.py::ProjectTest::test_job_move",
"tests/test_project.py::ProjectTest::test_jobs_groupby",
"tests/test_project.py::ProjectTest::test_jobs_groupbydoc",
"tests/test_project.py::ProjectTest::test_len_find_jobs",
"tests/test_project.py::ProjectTest::test_missing_statepoint_file",
"tests/test_project.py::ProjectTest::test_num_jobs",
"tests/test_project.py::ProjectTest::test_open_job_by_abbreviated_id",
"tests/test_project.py::ProjectTest::test_open_job_by_id",
"tests/test_project.py::ProjectTest::test_project_contains",
"tests/test_project.py::ProjectTest::test_rename_workspace",
"tests/test_project.py::ProjectTest::test_repair_corrupted_workspace",
"tests/test_project.py::ProjectTest::test_repr",
"tests/test_project.py::ProjectTest::test_root_directory",
"tests/test_project.py::ProjectTest::test_schema",
"tests/test_project.py::ProjectTest::test_schema_difference",
"tests/test_project.py::ProjectTest::test_schema_eval",
"tests/test_project.py::ProjectTest::test_schema_init",
"tests/test_project.py::ProjectTest::test_schema_subset",
"tests/test_project.py::ProjectTest::test_signac_project_crawler",
"tests/test_project.py::ProjectTest::test_str",
"tests/test_project.py::ProjectTest::test_temp_project",
"tests/test_project.py::ProjectTest::test_workspace_broken_link_error_on_find",
"tests/test_project.py::ProjectTest::test_workspace_directory",
"tests/test_project.py::ProjectTest::test_workspace_directory_with_env_variable",
"tests/test_project.py::ProjectTest::test_workspace_path_normalization",
"tests/test_project.py::ProjectTest::test_workspace_read_only_path",
"tests/test_project.py::ProjectTest::test_write_read_statepoint",
"tests/test_project.py::ProjectExportImportTest::test_export",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_function",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_function_move",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_flat_flat",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_flat_tree",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_tree_flat",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_tree_tree",
"tests/test_project.py::ProjectExportImportTest::test_export_import",
"tests/test_project.py::ProjectExportImportTest::test_export_import_complex_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_complex_path_nested_schema_from_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_conflict",
"tests/test_project.py::ProjectExportImportTest::test_export_import_conflict_synced",
"tests/test_project.py::ProjectExportImportTest::test_export_import_conflict_synced_with_args",
"tests/test_project.py::ProjectExportImportTest::test_export_import_schema_callable",
"tests/test_project.py::ProjectExportImportTest::test_export_import_schema_callable_non_unique",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_nested_with_schema",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_schema_from_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_schema_from_path_float",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_with_float",
"tests/test_project.py::ProjectExportImportTest::test_export_import_tarfile",
"tests/test_project.py::ProjectExportImportTest::test_export_import_tarfile_zipped",
"tests/test_project.py::ProjectExportImportTest::test_export_import_zipfile",
"tests/test_project.py::ProjectExportImportTest::test_export_move",
"tests/test_project.py::ProjectExportImportTest::test_export_single_job",
"tests/test_project.py::ProjectExportImportTest::test_import_own_project",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_disjoint_schema",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_disjoint_schema_nested",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_fizz_schema_flat",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_schema_nested",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_schema_nested_partial_homogenous_path_provide",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_schema_problematic",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_flat_flat",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_flat_tree",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_nested",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_nested_provide_partial_path",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_tree",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_tree_flat",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_tree_tree",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_with_slash_raises_error",
"tests/test_project.py::CachedProjectTest::test_config_modification",
"tests/test_project.py::CachedProjectTest::test_corrupted_statepoint_file",
"tests/test_project.py::CachedProjectTest::test_custom_job_class",
"tests/test_project.py::CachedProjectTest::test_custom_project",
"tests/test_project.py::CachedProjectTest::test_doc",
"tests/test_project.py::CachedProjectTest::test_document",
"tests/test_project.py::CachedProjectTest::test_find_job_ids",
"tests/test_project.py::CachedProjectTest::test_find_jobs",
"tests/test_project.py::CachedProjectTest::test_find_jobs_arithmetic_operators",
"tests/test_project.py::CachedProjectTest::test_find_jobs_logical_operators",
"tests/test_project.py::CachedProjectTest::test_find_jobs_next",
"tests/test_project.py::CachedProjectTest::test_fn",
"tests/test_project.py::CachedProjectTest::test_get",
"tests/test_project.py::CachedProjectTest::test_get_id",
"tests/test_project.py::CachedProjectTest::test_index",
"tests/test_project.py::CachedProjectTest::test_isfile",
"tests/test_project.py::CachedProjectTest::test_iteration",
"tests/test_project.py::CachedProjectTest::test_job_clone",
"tests/test_project.py::CachedProjectTest::test_job_move",
"tests/test_project.py::CachedProjectTest::test_jobs_groupby",
"tests/test_project.py::CachedProjectTest::test_jobs_groupbydoc",
"tests/test_project.py::CachedProjectTest::test_len_find_jobs",
"tests/test_project.py::CachedProjectTest::test_missing_statepoint_file",
"tests/test_project.py::CachedProjectTest::test_num_jobs",
"tests/test_project.py::CachedProjectTest::test_open_job_by_abbreviated_id",
"tests/test_project.py::CachedProjectTest::test_open_job_by_id",
"tests/test_project.py::CachedProjectTest::test_project_contains",
"tests/test_project.py::CachedProjectTest::test_rename_workspace",
"tests/test_project.py::CachedProjectTest::test_repair_corrupted_workspace",
"tests/test_project.py::CachedProjectTest::test_repr",
"tests/test_project.py::CachedProjectTest::test_root_directory",
"tests/test_project.py::CachedProjectTest::test_schema",
"tests/test_project.py::CachedProjectTest::test_schema_difference",
"tests/test_project.py::CachedProjectTest::test_schema_eval",
"tests/test_project.py::CachedProjectTest::test_schema_init",
"tests/test_project.py::CachedProjectTest::test_schema_subset",
"tests/test_project.py::CachedProjectTest::test_signac_project_crawler",
"tests/test_project.py::CachedProjectTest::test_str",
"tests/test_project.py::CachedProjectTest::test_temp_project",
"tests/test_project.py::CachedProjectTest::test_workspace_broken_link_error_on_find",
"tests/test_project.py::CachedProjectTest::test_workspace_directory",
"tests/test_project.py::CachedProjectTest::test_workspace_directory_with_env_variable",
"tests/test_project.py::CachedProjectTest::test_workspace_path_normalization",
"tests/test_project.py::CachedProjectTest::test_workspace_read_only_path",
"tests/test_project.py::CachedProjectTest::test_write_read_statepoint",
"tests/test_project.py::ProjectInitTest::test_get_job_invalid_workspace",
"tests/test_project.py::ProjectInitTest::test_get_job_nested_project",
"tests/test_project.py::ProjectInitTest::test_get_job_nested_project_subdir",
"tests/test_project.py::ProjectInitTest::test_get_job_subdir",
"tests/test_project.py::ProjectInitTest::test_get_job_symlink_other_project",
"tests/test_project.py::ProjectInitTest::test_get_job_valid_workspace",
"tests/test_project.py::ProjectInitTest::test_get_project",
"tests/test_project.py::ProjectInitTest::test_get_project_non_local",
"tests/test_project.py::ProjectInitTest::test_init",
"tests/test_project.py::ProjectInitTest::test_nested_project",
"tests/test_project.py::ProjectPicklingTest::test_pickle_jobs_directly",
"tests/test_project.py::ProjectPicklingTest::test_pickle_project_empty",
"tests/test_project.py::ProjectPicklingTest::test_pickle_project_with_jobs",
"tests/test_project.py::TestTestingProjectInitialization::test_input_args"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-12-03 23:21:04+00:00
|
bsd-3-clause
| 2,548 |
|
glotzerlab__signac-269
|
diff --git a/changelog.txt b/changelog.txt
index d099ad1a..bbd04bb9 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -19,6 +19,7 @@ Fixed
+++++
- Fixed issues on Windows with ``H5Store``, project import/export, and operations that move files (#264, #266).
+ - Calling ``items`` or ``values`` on _SyncedDict objects does not mutate nested dictionaries (#234, #269).
[1.3.0] -- 2019-12-20
diff --git a/signac/core/synceddict.py b/signac/core/synceddict.py
index e3eb1393..48c74555 100644
--- a/signac/core/synceddict.py
+++ b/signac/core/synceddict.py
@@ -265,11 +265,11 @@ class _SyncedDict(MutableMapping):
def values(self):
self._synced_load()
- return self._convert_to_dict(self._data).values()
+ return self._convert_to_dict(self).values()
def items(self):
self._synced_load()
- return self._convert_to_dict(self._data).items()
+ return self._convert_to_dict(self).items()
def __repr__(self):
return repr(self())
@@ -279,7 +279,7 @@ class _SyncedDict(MutableMapping):
def _as_dict(self):
with self._suspend_sync():
- return self._convert_to_dict(self._data.copy())
+ return self._convert_to_dict(self)
def __call__(self):
self._synced_load()
|
glotzerlab/signac
|
dc870ac06159cae97e1475894913d1def567555e
|
diff --git a/tests/test_synced_attrdict.py b/tests/test_synced_attrdict.py
index 503c758d..6509e363 100644
--- a/tests/test_synced_attrdict.py
+++ b/tests/test_synced_attrdict.py
@@ -508,6 +508,18 @@ class SyncedAttrDictTest(unittest.TestCase):
self.assertEqual(len(sad), 1)
self.assert_only_read()
+ def test_nested_types_dict_conversion(self):
+ """Ensure that calling methods like items and values does not
+ change the type of nested dictionaries."""
+ sad = self.get_sad({'a': {'b': 1}})
+ assert type(sad['a']) is SAD
+ sad.items()
+ assert type(sad['a']) is SAD
+ sad.values()
+ assert type(sad['a']) is SAD
+ sad._as_dict()
+ assert type(sad['a']) is SAD
+
if __name__ == '__main__':
unittest.main()
|
Calling `_SyncedDict.values()` gives `dict` objects
<!-- Please replace the text in the individual sections below. -->
### Description
Calling standard `MutableMapping` methods (`keys`, `values`, etc) on `_SyncedAttrDict` objects modifies the underlying dictionary in place. This behavior is unexpected, such an operation should only affect the returned value.
### To reproduce
```
>> import signac
>> project = signac.init_project('test')
>> job = project.open_job({'a': {'b': 'c'}}).init()
>> print(type(job.sp.a))
<class 'signac.core.attrdict.SyncedAttrDict'>
>> job.sp.values()
>> print(type(job.sp.a))
<class 'dict'>
```
There is an open question of whether `job.sp.values()` should return nested dictionaries as `SyncedDict` objects or normal `dict` objects. I prefer that `SyncedDict` objects be what it returns so that it's still going to sync, as does @bdice, but that is a separate question. Either way, calling values in the manner in this PR should not modify the object in place.
### System configuration
Linux-4.19.61-1-lts-x86_64-with-arch
3.7.4 (default, Oct 4 2019, 06:57:26)
[GCC 9.2.0]
1.2.0
|
0.0
|
dc870ac06159cae97e1475894913d1def567555e
|
[
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_nested_types_dict_conversion"
] |
[
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_attr_reference_modification",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_call",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_clear",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_clear_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_copy",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_copy_as_dict",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_copy_as_dict_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_copy_value",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_delete",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_delete_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_init",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_is_object_and_mapping",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_iter",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_iter_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_list_modification",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_repr",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_set_get",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_set_get_attr_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_set_get_explicit_nested",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_set_get_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_str",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_suspend_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_update",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_update_sync"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-10 18:15:59+00:00
|
bsd-3-clause
| 2,549 |
|
glotzerlab__signac-271
|
diff --git a/changelog.txt b/changelog.txt
index d099ad1a..ac6d84a9 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -14,11 +14,19 @@ Added
+++++
- Added Windows to platforms tested with continuous integration (#264, #266).
+
+Changed
++++++++
+
+ - Workspace directory is created when ``Project`` is initialized (#267, #271).
+
Fixed
+++++
- Fixed issues on Windows with ``H5Store``, project import/export, and operations that move files (#264, #266).
+ - Calling ``items`` or ``values`` on _SyncedDict objects does not mutate nested dictionaries (#234, #269).
+
[1.3.0] -- 2019-12-20
diff --git a/contributors.yaml b/contributors.yaml
index 0838169e..150fa054 100644
--- a/contributors.yaml
+++ b/contributors.yaml
@@ -76,4 +76,8 @@ contributors:
given-names: Brandon
affiliation: "University of Michigan"
orcid: "https://orcid.org/0000-0001-7739-7796"
+ -
+ family-names: Sharma
+ given-names: Vishav
+ affiliation: "National Institute of Technology, Hamirpur"
...
diff --git a/signac/contrib/project.py b/signac/contrib/project.py
index 6864be88..208f23a9 100644
--- a/signac/contrib/project.py
+++ b/signac/contrib/project.py
@@ -156,6 +156,16 @@ class Project(object):
self._fn_doc = os.path.join(self._rd, self.FN_DOCUMENT)
self._document = None
+ # Prepare Workspace Directory
+ if not os.path.isdir(self._wd):
+ try:
+ _mkdir_p(self._wd)
+ except OSError:
+ logger.error(
+ "Error occurred while trying to create "
+ "workspace directory for project {}.".format(self.id))
+ raise
+
# Internal caches
self._index_cache = dict()
self._sp_cache = dict()
diff --git a/signac/core/synceddict.py b/signac/core/synceddict.py
index e3eb1393..48c74555 100644
--- a/signac/core/synceddict.py
+++ b/signac/core/synceddict.py
@@ -265,11 +265,11 @@ class _SyncedDict(MutableMapping):
def values(self):
self._synced_load()
- return self._convert_to_dict(self._data).values()
+ return self._convert_to_dict(self).values()
def items(self):
self._synced_load()
- return self._convert_to_dict(self._data).items()
+ return self._convert_to_dict(self).items()
def __repr__(self):
return repr(self())
@@ -279,7 +279,7 @@ class _SyncedDict(MutableMapping):
def _as_dict(self):
with self._suspend_sync():
- return self._convert_to_dict(self._data.copy())
+ return self._convert_to_dict(self)
def __call__(self):
self._synced_load()
|
glotzerlab/signac
|
dc870ac06159cae97e1475894913d1def567555e
|
diff --git a/tests/test_project.py b/tests/test_project.py
index 32147f77..f3680f40 100644
--- a/tests/test_project.py
+++ b/tests/test_project.py
@@ -98,6 +98,9 @@ class ProjectTest(BaseProjectTest):
self.project.config['workspace_dir'] = '${SIGNAC_ENV_DIR_TEST}'
self.assertEqual(self._tmp_wd, self.project.workspace())
+ def test_workspace_directory_exists(self):
+ self.assertTrue(os.path.exists(self.project.workspace()))
+
def test_fn(self):
self.assertEqual(
self.project.fn('test/abc'),
@@ -214,7 +217,8 @@ class ProjectTest(BaseProjectTest):
norm_path(os.path.join(self.project.root_directory(), self.project.workspace())))
def test_no_workspace_warn_on_find(self):
- self.assertFalse(os.path.exists(self.project.workspace()))
+ if os.path.exists(self.project.workspace()):
+ os.rmdir(self.project.workspace())
with self.assertLogs(level='INFO') as cm:
list(self.project.find_jobs())
# Python < 3.8 will return 2 messages.
@@ -234,6 +238,8 @@ class ProjectTest(BaseProjectTest):
def test_workspace_read_only_path(self):
# Create file where workspace would be, thus preventing the creation
# of the workspace directory.
+ if os.path.exists(self.project.workspace()):
+ os.rmdir(self.project.workspace())
with open(os.path.join(self.project.workspace()), 'w'):
pass
diff --git a/tests/test_synced_attrdict.py b/tests/test_synced_attrdict.py
index 503c758d..6509e363 100644
--- a/tests/test_synced_attrdict.py
+++ b/tests/test_synced_attrdict.py
@@ -508,6 +508,18 @@ class SyncedAttrDictTest(unittest.TestCase):
self.assertEqual(len(sad), 1)
self.assert_only_read()
+ def test_nested_types_dict_conversion(self):
+ """Ensure that calling methods like items and values does not
+ change the type of nested dictionaries."""
+ sad = self.get_sad({'a': {'b': 1}})
+ assert type(sad['a']) is SAD
+ sad.items()
+ assert type(sad['a']) is SAD
+ sad.values()
+ assert type(sad['a']) is SAD
+ sad._as_dict()
+ assert type(sad['a']) is SAD
+
if __name__ == '__main__':
unittest.main()
|
Fix race condition when workspace is created
### Description
In MPI parallel jobs, where every rank (or every `n` ranks) may initialize a statepoint on the fly, a race condition leads to the job crashing when no `workspace` directory is present. The explanation is that this directory is created on the fly simultaneously by all `job.init()`s of the same ensemble.
A detailed look identifies the `mkdir -p` in https://github.com/glotzerlab/signac/blob/2c0d9e4710bf9a758c53e74a9ad117acc20d43ae/signac/contrib/job.py#L337
as a culprit. The `mkdir` should not include the `-p` option, instead operate only on the target directory. Job workspaces should be created by default upon `signac init`.
Optionally, when they are deleted (for whatever reason), they could be recreated by an explicit `init` call, which would be properly guarded by MPI barriers. For now, the workaround is to create the workspace dir manually.
### To reproduce
```python
sp = {'just': 'a statepoint'}
project = signac.get_project()
# When initializing jobs on the fly in MPI setting:
job = project.open_job(sp)
device.comm.barrier_all() # HOOMD next
if device.comm.partition == 0 and device.comm.rank == 0:
job.init() # this is the problematic line
device.comm.barrier_all()
```
This would be the suggested way to do it (pending changes to signac):
```python
sp = {'just': 'a statepoint'}
project = signac.get_project()
device.comm.barrier_all()
if device.comm.partition == 0 and device.comm.rank == 0:
project.init()
device.comm.barrier_all()
# When initializing jobs on the fly in MPI setting:
job = project.open_job(sp)
device.comm.barrier_all()
if device.comm.partition == 0 and device.comm.rank == 0:
job.init() # this is the problematic line
device.comm.barrier_all()
```
### Error output
If possible, copy any terminal outputs or attach screenshots that provide additional information on the problem.
```
Error occured while trying to create workspace directory for job '42e1468f85f2b689659f23bae00de995'.
State point manifest file of job '42e1468f85f2b689659f23bae00de995' appears to be corrupted.
Traceback (most recent call last):
File "1brf_umbrella.py", line 125, in <module>
job.init()
File "/ccs/home/glaser/.conda/envs/myenv/lib/python3.7/site-packages/signac/contrib/job.py", line 427, in init
self._init(force=force)
File "/ccs/home/glaser/.conda/envs/myenv/lib/python3.7/site-packages/signac/contrib/job.py", line 354, in _init
_mkdir_p(self._wd)
File "/ccs/home/glaser/.conda/envs/myenv/lib/python3.7/site-packages/signac/contrib/utility.py", line 171, in _mkdir_p
os.makedirs(path)
File "/ccs/home/glaser/.conda/envs/myenv/lib/python3.7/os.py", line 221, in makedirs
mkdir(name, mode)
...
```
### System configuration
Please complete the following information:
- Operating System [e.g. macOS]: Linux login2 4.14.0-115.8.1.el7a.ppc64le #1 SMP Thu May 9 14:45:13 UTC 2019 ppc64le ppc64le ppc64le GNU/Linux (really, any OS)
- Version of Python [e.g. 3.7]: Python 3.7.4 (really, any python3 version)
- Version of signac [e.g. 1.0]: signac 1.0.0 (but looking at the code the problem may also be present in newer versions)
|
0.0
|
dc870ac06159cae97e1475894913d1def567555e
|
[
"tests/test_project.py::ProjectTest::test_workspace_directory_exists",
"tests/test_project.py::CachedProjectTest::test_workspace_directory_exists",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_nested_types_dict_conversion"
] |
[
"tests/test_project.py::ProjectTest::test_config_modification",
"tests/test_project.py::ProjectTest::test_corrupted_statepoint_file",
"tests/test_project.py::ProjectTest::test_custom_job_class",
"tests/test_project.py::ProjectTest::test_custom_project",
"tests/test_project.py::ProjectTest::test_doc",
"tests/test_project.py::ProjectTest::test_document",
"tests/test_project.py::ProjectTest::test_find_job_ids",
"tests/test_project.py::ProjectTest::test_find_jobs",
"tests/test_project.py::ProjectTest::test_find_jobs_arithmetic_operators",
"tests/test_project.py::ProjectTest::test_find_jobs_logical_operators",
"tests/test_project.py::ProjectTest::test_find_jobs_next",
"tests/test_project.py::ProjectTest::test_fn",
"tests/test_project.py::ProjectTest::test_get",
"tests/test_project.py::ProjectTest::test_get_id",
"tests/test_project.py::ProjectTest::test_index",
"tests/test_project.py::ProjectTest::test_isfile",
"tests/test_project.py::ProjectTest::test_iteration",
"tests/test_project.py::ProjectTest::test_job_clone",
"tests/test_project.py::ProjectTest::test_job_move",
"tests/test_project.py::ProjectTest::test_jobs_groupby",
"tests/test_project.py::ProjectTest::test_jobs_groupbydoc",
"tests/test_project.py::ProjectTest::test_len_find_jobs",
"tests/test_project.py::ProjectTest::test_missing_statepoint_file",
"tests/test_project.py::ProjectTest::test_no_workspace_warn_on_find",
"tests/test_project.py::ProjectTest::test_num_jobs",
"tests/test_project.py::ProjectTest::test_open_job_by_abbreviated_id",
"tests/test_project.py::ProjectTest::test_open_job_by_id",
"tests/test_project.py::ProjectTest::test_project_contains",
"tests/test_project.py::ProjectTest::test_property_id",
"tests/test_project.py::ProjectTest::test_rename_workspace",
"tests/test_project.py::ProjectTest::test_repair_corrupted_workspace",
"tests/test_project.py::ProjectTest::test_repr",
"tests/test_project.py::ProjectTest::test_root_directory",
"tests/test_project.py::ProjectTest::test_schema",
"tests/test_project.py::ProjectTest::test_schema_difference",
"tests/test_project.py::ProjectTest::test_schema_eval",
"tests/test_project.py::ProjectTest::test_schema_init",
"tests/test_project.py::ProjectTest::test_schema_subset",
"tests/test_project.py::ProjectTest::test_signac_project_crawler",
"tests/test_project.py::ProjectTest::test_str",
"tests/test_project.py::ProjectTest::test_temp_project",
"tests/test_project.py::ProjectTest::test_workspace_broken_link_error_on_find",
"tests/test_project.py::ProjectTest::test_workspace_directory",
"tests/test_project.py::ProjectTest::test_workspace_directory_with_env_variable",
"tests/test_project.py::ProjectTest::test_workspace_path_normalization",
"tests/test_project.py::ProjectTest::test_workspace_read_only_path",
"tests/test_project.py::ProjectTest::test_write_read_statepoint",
"tests/test_project.py::ProjectExportImportTest::test_export",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_function",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_function_move",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_flat_flat",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_flat_tree",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_tree_flat",
"tests/test_project.py::ProjectExportImportTest::test_export_custom_path_string_modify_tree_tree",
"tests/test_project.py::ProjectExportImportTest::test_export_import",
"tests/test_project.py::ProjectExportImportTest::test_export_import_complex_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_complex_path_nested_schema_from_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_conflict",
"tests/test_project.py::ProjectExportImportTest::test_export_import_conflict_synced",
"tests/test_project.py::ProjectExportImportTest::test_export_import_conflict_synced_with_args",
"tests/test_project.py::ProjectExportImportTest::test_export_import_schema_callable",
"tests/test_project.py::ProjectExportImportTest::test_export_import_schema_callable_non_unique",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_nested_with_schema",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_schema_from_path",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_schema_from_path_float",
"tests/test_project.py::ProjectExportImportTest::test_export_import_simple_path_with_float",
"tests/test_project.py::ProjectExportImportTest::test_export_import_tarfile",
"tests/test_project.py::ProjectExportImportTest::test_export_import_tarfile_zipped",
"tests/test_project.py::ProjectExportImportTest::test_export_import_tarfile_zipped_longname",
"tests/test_project.py::ProjectExportImportTest::test_export_import_zipfile",
"tests/test_project.py::ProjectExportImportTest::test_export_move",
"tests/test_project.py::ProjectExportImportTest::test_export_single_job",
"tests/test_project.py::ProjectExportImportTest::test_import_own_project",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_disjoint_schema",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_disjoint_schema_nested",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_fizz_schema_flat",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_schema_nested",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_schema_nested_partial_homogenous_path_provide",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_heterogeneous_schema_problematic",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_flat_flat",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_flat_tree",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_nested",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_nested_provide_partial_path",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_tree",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_tree_flat",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_homogeneous_schema_tree_tree",
"tests/test_project.py::LinkedViewProjectTest::test_create_linked_view_with_slash_raises_error",
"tests/test_project.py::CachedProjectTest::test_config_modification",
"tests/test_project.py::CachedProjectTest::test_corrupted_statepoint_file",
"tests/test_project.py::CachedProjectTest::test_custom_job_class",
"tests/test_project.py::CachedProjectTest::test_custom_project",
"tests/test_project.py::CachedProjectTest::test_doc",
"tests/test_project.py::CachedProjectTest::test_document",
"tests/test_project.py::CachedProjectTest::test_find_job_ids",
"tests/test_project.py::CachedProjectTest::test_find_jobs",
"tests/test_project.py::CachedProjectTest::test_find_jobs_arithmetic_operators",
"tests/test_project.py::CachedProjectTest::test_find_jobs_logical_operators",
"tests/test_project.py::CachedProjectTest::test_find_jobs_next",
"tests/test_project.py::CachedProjectTest::test_fn",
"tests/test_project.py::CachedProjectTest::test_get",
"tests/test_project.py::CachedProjectTest::test_get_id",
"tests/test_project.py::CachedProjectTest::test_index",
"tests/test_project.py::CachedProjectTest::test_isfile",
"tests/test_project.py::CachedProjectTest::test_iteration",
"tests/test_project.py::CachedProjectTest::test_job_clone",
"tests/test_project.py::CachedProjectTest::test_job_move",
"tests/test_project.py::CachedProjectTest::test_jobs_groupby",
"tests/test_project.py::CachedProjectTest::test_jobs_groupbydoc",
"tests/test_project.py::CachedProjectTest::test_len_find_jobs",
"tests/test_project.py::CachedProjectTest::test_missing_statepoint_file",
"tests/test_project.py::CachedProjectTest::test_no_workspace_warn_on_find",
"tests/test_project.py::CachedProjectTest::test_num_jobs",
"tests/test_project.py::CachedProjectTest::test_open_job_by_abbreviated_id",
"tests/test_project.py::CachedProjectTest::test_open_job_by_id",
"tests/test_project.py::CachedProjectTest::test_project_contains",
"tests/test_project.py::CachedProjectTest::test_property_id",
"tests/test_project.py::CachedProjectTest::test_rename_workspace",
"tests/test_project.py::CachedProjectTest::test_repair_corrupted_workspace",
"tests/test_project.py::CachedProjectTest::test_repr",
"tests/test_project.py::CachedProjectTest::test_root_directory",
"tests/test_project.py::CachedProjectTest::test_schema",
"tests/test_project.py::CachedProjectTest::test_schema_difference",
"tests/test_project.py::CachedProjectTest::test_schema_eval",
"tests/test_project.py::CachedProjectTest::test_schema_init",
"tests/test_project.py::CachedProjectTest::test_schema_subset",
"tests/test_project.py::CachedProjectTest::test_signac_project_crawler",
"tests/test_project.py::CachedProjectTest::test_str",
"tests/test_project.py::CachedProjectTest::test_temp_project",
"tests/test_project.py::CachedProjectTest::test_workspace_broken_link_error_on_find",
"tests/test_project.py::CachedProjectTest::test_workspace_directory",
"tests/test_project.py::CachedProjectTest::test_workspace_directory_with_env_variable",
"tests/test_project.py::CachedProjectTest::test_workspace_path_normalization",
"tests/test_project.py::CachedProjectTest::test_workspace_read_only_path",
"tests/test_project.py::CachedProjectTest::test_write_read_statepoint",
"tests/test_project.py::ProjectInitTest::test_get_job_invalid_workspace",
"tests/test_project.py::ProjectInitTest::test_get_job_nested_project",
"tests/test_project.py::ProjectInitTest::test_get_job_nested_project_subdir",
"tests/test_project.py::ProjectInitTest::test_get_job_subdir",
"tests/test_project.py::ProjectInitTest::test_get_job_symlink_other_project",
"tests/test_project.py::ProjectInitTest::test_get_job_valid_workspace",
"tests/test_project.py::ProjectInitTest::test_get_project",
"tests/test_project.py::ProjectInitTest::test_get_project_all_printable_characters",
"tests/test_project.py::ProjectInitTest::test_get_project_non_local",
"tests/test_project.py::ProjectInitTest::test_init",
"tests/test_project.py::ProjectInitTest::test_nested_project",
"tests/test_project.py::ProjectSchemaTest::test_no_migration",
"tests/test_project.py::ProjectSchemaTest::test_project_schema_version_migration",
"tests/test_project.py::ProjectSchemaTest::test_project_schema_versions",
"tests/test_project.py::ProjectPicklingTest::test_pickle_jobs_directly",
"tests/test_project.py::ProjectPicklingTest::test_pickle_project_empty",
"tests/test_project.py::ProjectPicklingTest::test_pickle_project_with_jobs",
"tests/test_project.py::TestTestingProjectInitialization::test_input_args",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_attr_reference_modification",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_call",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_clear",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_clear_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_copy",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_copy_as_dict",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_copy_as_dict_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_copy_value",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_delete",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_delete_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_init",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_is_object_and_mapping",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_iter",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_iter_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_list_modification",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_repr",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_set_get",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_set_get_attr_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_set_get_explicit_nested",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_set_get_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_str",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_suspend_sync",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_update",
"tests/test_synced_attrdict.py::SyncedAttrDictTest::test_update_sync"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-15 12:45:03+00:00
|
bsd-3-clause
| 2,550 |
|
glotzerlab__signac-296
|
diff --git a/changelog.txt b/changelog.txt
index 4bd9fb26..942b0a14 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -36,6 +36,7 @@ Removed
- Removed vendored ``tqdm`` module and replaced it with a requirement (#289).
- Removed support for ``rapidjson`` as an alternative JSON library (#285, #287).
+ - Removed tuple of keys implementation of Nested Dict (#272, #296).
[1.3.0] -- 2019-12-20
diff --git a/signac/contrib/collection.py b/signac/contrib/collection.py
index f5d03fd9..876f2dc7 100644
--- a/signac/contrib/collection.py
+++ b/signac/contrib/collection.py
@@ -20,10 +20,11 @@ import re
import sys
from itertools import islice
from numbers import Number
-from collections.abc import Mapping
from math import isclose
from ..core import json
+from .utility import _nested_dicts_to_dotted_keys
+from .utility import _to_hashable
from .filterparse import parse_filter_arg
@@ -56,51 +57,10 @@ def _flatten(container):
yield i
-class _hashable_dict(dict):
- def __hash__(self):
- return hash(tuple(sorted(self.items())))
-
-
-def _to_hashable(l):
- if type(l) is list:
- return tuple(_to_hashable(_) for _ in l)
- elif type(l) is dict:
- return _hashable_dict(l)
- else:
- return l
-
-
class _DictPlaceholder(object):
pass
-def _encode_tree(x):
- if type(x) is list:
- return _to_hashable(x)
- else:
- return x
-
-
-def _traverse_tree(t, encode=None, key=None):
- if encode is not None:
- t = encode(t)
- if isinstance(t, Mapping):
- if t:
- for k in t:
- k_ = k if key is None else '.'.join((key, k))
- for k__, v in _traverse_tree(t[k], key=k_, encode=encode):
- yield k__, v
- elif key is not None:
- yield key, t
- else:
- yield key, t
-
-
-def _traverse_filter(t):
- for key, value in _traverse_tree(t, encode=_encode_tree):
- yield key, value
-
-
def _valid_filter(f, top=True):
if f is None:
return True
@@ -653,7 +613,7 @@ class Collection(object):
not_expression = expr.pop('$not', None)
# Reduce the result based on the remaining non-logical expression:
- for key, value in _traverse_filter(expr):
+ for key, value in _nested_dicts_to_dotted_keys(expr):
reduce_results(self._find_expression(key, value))
if not result_ids: # No match, no need to continue...
return set()
diff --git a/signac/contrib/import_export.py b/signac/contrib/import_export.py
index 05c439ac..9c20b6f6 100644
--- a/signac/contrib/import_export.py
+++ b/signac/contrib/import_export.py
@@ -18,6 +18,7 @@ from ..core import json
from .errors import StatepointParsingError
from .errors import DestinationExistsError
from .utility import _mkdir_p
+from .utility import _dotted_dict_to_nested_dicts
import logging
@@ -53,7 +54,7 @@ def _make_schema_based_path_function(jobs, exclude_keys=None, delimiter_nested='
paths = dict()
for key_tokens, values in sp_index.items():
- key = delimiter_nested.join(map(str, key_tokens))
+ key = key_tokens.replace('.', delimiter_nested)
if exclude_keys and key in exclude_keys:
continue
for value, group in values.items():
@@ -335,26 +336,11 @@ def _make_path_based_schema_function(schema_path):
for key in types:
if key in sp:
sp[key] = types[key](sp[key])
- return _convert_to_nested(sp)
+ return _dotted_dict_to_nested_dicts(sp, delimiter_nested=_DOT_MAGIC_WORD)
return parse_path
-def _convert_to_nested(sp):
- """Convert a flat state point dict to a nested dict."""
- ret = dict()
- for key, value in sp.items():
- tokens = key.split(_DOT_MAGIC_WORD)
- if len(tokens) > 1:
- tmp = ret.setdefault(tokens[0], dict())
- for token in tokens[1:-1]:
- tmp = tmp.setdefault(token, dict())
- tmp[tokens[-1]] = value
- else:
- ret[tokens[0]] = value
- return ret
-
-
def _with_consistency_check(schema_function, read_sp_manifest_file):
"Check whether the state point detected from the schema function matches the manifest file."
diff --git a/signac/contrib/project.py b/signac/contrib/project.py
index 2e19da04..105c0cc0 100644
--- a/signac/contrib/project.py
+++ b/signac/contrib/project.py
@@ -551,8 +551,9 @@ class Project(object):
from .schema import _build_job_statepoint_index
if index is None:
index = [{'_id': job._id, 'statepoint': job.sp()} for job in self]
- for x in _build_job_statepoint_index(jobs=self, exclude_const=exclude_const, index=index):
- yield x
+ for x, y in _build_job_statepoint_index(
+ jobs=self, exclude_const=exclude_const, index=index):
+ yield tuple(x.split('.')), y
def detect_schema(self, exclude_const=False, subset=None, index=None):
"""Detect the project's state point schema.
@@ -571,12 +572,14 @@ class Project(object):
:rtype:
`signac.contrib.schema.ProjectSchema`
"""
+ from .schema import _build_job_statepoint_index
if index is None:
index = self.index(include_job_document=False)
if subset is not None:
subset = {str(s) for s in subset}
index = [doc for doc in index if doc['_id'] in subset]
- statepoint_index = self.build_job_statepoint_index(exclude_const=exclude_const, index=index)
+ statepoint_index = _build_job_statepoint_index(
+ jobs=self, exclude_const=exclude_const, index=index)
return ProjectSchema.detect(statepoint_index)
@deprecated(deprecated_in="1.3", removed_in="2.0", current_version=__version__,
diff --git a/signac/contrib/schema.py b/signac/contrib/schema.py
index f25c5edb..ced941d7 100644
--- a/signac/contrib/schema.py
+++ b/signac/contrib/schema.py
@@ -23,11 +23,11 @@ def _collect_by_type(values):
def _build_job_statepoint_index(jobs, exclude_const, index):
from .collection import Collection
- from .collection import _traverse_filter
from .collection import _DictPlaceholder
+ from .utility import _nested_dicts_to_dotted_keys
collection = Collection(index, _trust=True)
for doc in collection.find():
- for key, _ in _traverse_filter(doc):
+ for key, _ in _nested_dicts_to_dotted_keys(doc):
if key == '_id' or key.split('.')[0] != 'statepoint':
continue
collection.index(key, build=True)
@@ -42,7 +42,7 @@ def _build_job_statepoint_index(jobs, exclude_const, index):
if exclude_const and len(tmp[k]) == 1 \
and len(tmp[k][list(tmp[k].keys())[0]]) == len(collection):
continue
- yield tuple(strip_prefix(k).split('.')), remove_dict_placeholder(tmp[k])
+ yield strip_prefix(k), remove_dict_placeholder(tmp[k])
class ProjectSchema(object):
@@ -109,19 +109,21 @@ class ProjectSchema(object):
if depth > 0:
schema_dict = _Vividict()
for key, values in self._schema.items():
- if len(key) > 1:
- for k in key[:-1]:
- x = schema_dict[k]
- x[key[-1]] = _fmt_values(values)
+ keys = key.split('.')
+ if len(keys) > 1:
+ x = schema_dict[keys[0]]
+ for k in keys[1:-1]:
+ x = x[k]
+ x[keys[-1]] = _fmt_values(values)
else:
- schema_dict[key[0]] = _fmt_values(values)
+ schema_dict[keys[0]] = _fmt_values(values)
return pformat(schema_dict, depth=depth)
else:
ret = ['{']
for key in sorted(self._schema):
values = self._schema[key]
if values:
- ret.append(" '{}': '{}',".format('.'.join(key), _fmt_values(values)))
+ ret.append(" '{}': '{}',".format(key, _fmt_values(values)))
ret.append('}')
return '\n'.join(ret)
@@ -136,13 +138,14 @@ class ProjectSchema(object):
def __contains__(self, key_or_keys):
if isinstance(key_or_keys, str):
- key_or_keys = key_or_keys.split('.')
- return tuple(key_or_keys) in self._schema
+ return key_or_keys in self._schema
+ key_or_keys = '.'.join(key_or_keys)
+ return key_or_keys in self._schema
def __getitem__(self, key_or_keys):
if isinstance(key_or_keys, str):
- key_or_keys = key_or_keys.split('.')
- return self._schema.__getitem__(tuple(key_or_keys))
+ return self._schema[key_or_keys]
+ return self._schema['.'.join(key_or_keys)]
def __iter__(self):
return iter(self._schema)
@@ -181,11 +184,12 @@ class ProjectSchema(object):
iterators = itertools.tee(jobs_or_statepoints, len(self))
for key, it in zip(self, iterators):
values = []
+ keys = key.split('.')
for sp in it:
if not isinstance(sp, Mapping):
sp = sp.statepoint
- v = sp[key[0]]
- for k in key[1:]:
+ v = sp[keys[0]]
+ for k in keys[1:]:
v = v[k]
values.append(v)
s[key] = _collect_by_type(values)
diff --git a/signac/contrib/utility.py b/signac/contrib/utility.py
index f7b633c4..a318fd06 100644
--- a/signac/contrib/utility.py
+++ b/signac/contrib/utility.py
@@ -14,6 +14,7 @@ from datetime import timedelta
from contextlib import contextmanager
from deprecation import deprecated
from tempfile import TemporaryDirectory
+from collections.abc import Mapping
from ..version import __version__
@@ -227,3 +228,65 @@ def _extract(filename):
yield tmpdir
else:
raise RuntimeError("Unknown file type: '{}'.".format(filename))
+
+
+def _dotted_dict_to_nested_dicts(dotted_dict, delimiter_nested='.'):
+ """Convert dotted keys in the state point dict to a nested dict.
+
+ :param dotted_dict: A mapping with dots/delimiter_nested in its keys, e.g. {'a.b': 'c'}.
+ :param delimiter_nested: A string delimiter between keys, defaults to '.'.
+ :returns: A mapping instance with nested dicts, e.g. {'a': {'b': 'c'}}.
+ """
+ nested_dict = dict()
+ for key, value in dotted_dict.items():
+ tokens = key.split(delimiter_nested)
+ if len(tokens) > 1:
+ tmp = nested_dict.setdefault(tokens[0], dict())
+ for token in tokens[1:-1]:
+ tmp = tmp.setdefault(token, dict())
+ tmp[tokens[-1]] = value
+ else:
+ nested_dict[tokens[0]] = value
+ return nested_dict
+
+
+class _hashable_dict(dict):
+ def __hash__(self):
+ return hash(tuple(sorted(self.items())))
+
+
+def _to_hashable(l):
+ if type(l) is list:
+ return tuple(_to_hashable(_) for _ in l)
+ elif type(l) is dict:
+ return _hashable_dict(l)
+ else:
+ return l
+
+
+def _encode_tree(x):
+ if type(x) is list:
+ return _to_hashable(x)
+ else:
+ return x
+
+
+def _nested_dicts_to_dotted_keys(t, encode=_encode_tree, key=None):
+ """Generate tuples of key in dotted string format and value from nested dict.
+
+ :param t: A mapping instance with nested dicts, e.g. {'a': {'b': 'c'}}.
+ :param encode: By default, values are encoded to be hashable. Use ``None`` to skip encoding.
+ :yields: Tuples of dotted key and value e.g. ('a.b', 'c').
+ """
+ if encode is not None:
+ t = encode(t)
+ if isinstance(t, Mapping):
+ if t:
+ for k in t:
+ k_ = k if key is None else '.'.join((key, k))
+ for k__, v in _nested_dicts_to_dotted_keys(t[k], encode=encode, key=k_):
+ yield k__, v
+ elif key is not None:
+ yield key, t
+ else:
+ yield key, t
diff --git a/signac/diff.py b/signac/diff.py
index 4b608f1d..b29b1b58 100644
--- a/signac/diff.py
+++ b/signac/diff.py
@@ -1,31 +1,8 @@
# Copyright (c) 2019 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
-from .contrib.collection import _traverse_filter
-
-
-def _dotted_keys_to_nested_dicts(mapping):
- """Converts dictionaries with dot-separated keys into nested dictionaries.
-
- :param mapping: A mapping with dots in its keys, e.g. {'a.b': 'c'}
- :returns: A mapping with nested keys, e.g. {'a': {'b': 'c'}}
- :rtype: dict
- """
- result = {}
-
- def make_nested_dict(d, keys):
- item = d
- for key in keys[:-1]:
- if key not in item:
- item[key] = {}
- item = item[key]
- return item
-
- for dotted_key, value in mapping.items():
- keys = dotted_key.split('.')
- make_nested_dict(result, keys)[keys[-1]] = value
-
- return result
+from .contrib.utility import _dotted_dict_to_nested_dicts
+from .contrib.utility import _nested_dicts_to_dotted_keys
def diff_jobs(*jobs):
@@ -72,13 +49,13 @@ def diff_jobs(*jobs):
else:
sps = {}
for job in jobs:
- sps[job] = set(_traverse_filter(job.sp()))
+ sps[job] = set(_nested_dicts_to_dotted_keys(job.sp()))
intersection = set.intersection(*sps.values())
diffs = {}
for job in jobs:
unique_sps = sps[job]-intersection
- diffs[job.id] = _dotted_keys_to_nested_dicts(dict(unique_sps))
+ diffs[job.id] = _dotted_dict_to_nested_dicts(dict(unique_sps))
return diffs
|
glotzerlab/signac
|
55e6ab88e99b655760c7ba79b39b90b1df19c910
|
diff --git a/tests/test_project.py b/tests/test_project.py
index 4de4044a..dbd1dfbc 100644
--- a/tests/test_project.py
+++ b/tests/test_project.py
@@ -63,6 +63,22 @@ WINDOWS = (sys.platform == 'win32')
test_token = {'test_token': str(uuid.uuid4())}
+S_FORMAT1 = \
+'''{
+ 'a': 'int([0, 1, 2, ..., 8, 9], 10)',
+ 'b.b2': 'int([0, 1, 2, ..., 8, 9], 10)',
+ 'c.c2.c3.c4.c5': 'tuple([((0, 0, 0),), ((1, 0, 0),), ((2, 0, 0),), ..., ((8, 0, 0),), ((9, 0, 0),)], 10)',
+ 'const': 'int([0], 1)',
+}'''
+
+
+S_FORMAT2 = \
+'''{'a': 'int([0, 1, 2, ..., 8, 9], 10)',
+ 'b': {'b2': 'int([0, 1, 2, ..., 8, 9], 10)'},
+ 'c': {'c2': {...}},
+ 'const': 'int([0], 1)'}'''
+
+
class TestProjectBase(TestJobBase):
pass
@@ -786,6 +802,22 @@ class TestProject(TestProjectBase):
assert len(s.difference(s_, ignore_values=True)) == 0
assert len(s3.difference(s3_, ignore_values=True)) == 0
+ def test_schema_format(self):
+ for i in range(10):
+ self.project.open_job({
+ 'const': 0,
+ 'a': i,
+ 'b': {'b2': i},
+ 'c': {'c2': {'c3': {'c4': {'c5': [[i, 0, 0]]}}}}
+ }).init()
+
+ s = self.project.detect_schema()
+ s_format1 = s.format()
+ s_format2 = s.format(depth=2)
+
+ assert S_FORMAT1 == s_format1
+ assert S_FORMAT2 == s_format2
+
def test_jobs_groupby(self):
def get_sp(i):
return {
|
Simplify redundancies in nested dict representations
### Feature description
Currently nested dicts within signac can be represented as (1) nested dicts, (2) tuples as dict keys, and (3) strings with dot notation.
### Proposed solution
We've had some conversation, about whether it's a good idea to keep all three representations, or to simplify to (1) and (2) or (1) and (3) only. Related topic is issue #64
Current thoughts are:
- Keeping tuples as dict keys notation means more readable and simpler to iterate over, but requires more refactoring.
- Keeping strings with dot notation is more consistent with our current usage in Collections, but means slightly (very slightly) slower performance because indexing requires splitting the string and less readable code because we'd be iterating over split strings.
|
0.0
|
55e6ab88e99b655760c7ba79b39b90b1df19c910
|
[
"tests/test_project.py::TestProject::test_schema_format",
"tests/test_project.py::TestCachedProject::test_schema_format"
] |
[
"tests/test_project.py::TestProject::test_get",
"tests/test_project.py::TestProject::test_get_id",
"tests/test_project.py::TestProject::test_property_id",
"tests/test_project.py::TestProject::test_repr",
"tests/test_project.py::TestProject::test_str",
"tests/test_project.py::TestProject::test_root_directory",
"tests/test_project.py::TestProject::test_workspace_directory",
"tests/test_project.py::TestProject::test_config_modification",
"tests/test_project.py::TestProject::test_workspace_directory_with_env_variable",
"tests/test_project.py::TestProject::test_workspace_directory_exists",
"tests/test_project.py::TestProject::test_fn",
"tests/test_project.py::TestProject::test_isfile",
"tests/test_project.py::TestProject::test_document",
"tests/test_project.py::TestProject::test_doc",
"tests/test_project.py::TestProject::test_write_read_statepoint",
"tests/test_project.py::TestProject::test_workspace_path_normalization",
"tests/test_project.py::TestProject::test_no_workspace_warn_on_find",
"tests/test_project.py::TestProject::test_workspace_broken_link_error_on_find",
"tests/test_project.py::TestProject::test_workspace_read_only_path",
"tests/test_project.py::TestProject::test_find_job_ids",
"tests/test_project.py::TestProject::test_find_jobs",
"tests/test_project.py::TestProject::test_find_jobs_next",
"tests/test_project.py::TestProject::test_find_jobs_arithmetic_operators",
"tests/test_project.py::TestProject::test_find_jobs_logical_operators",
"tests/test_project.py::TestProject::test_num_jobs",
"tests/test_project.py::TestProject::test_len_find_jobs",
"tests/test_project.py::TestProject::test_iteration",
"tests/test_project.py::TestProject::test_open_job_by_id",
"tests/test_project.py::TestProject::test_open_job_by_abbreviated_id",
"tests/test_project.py::TestProject::test_missing_statepoint_file",
"tests/test_project.py::TestProject::test_corrupted_statepoint_file",
"tests/test_project.py::TestProject::test_rename_workspace",
"tests/test_project.py::TestProject::test_repair_corrupted_workspace",
"tests/test_project.py::TestProject::test_index",
"tests/test_project.py::TestProject::test_signac_project_crawler",
"tests/test_project.py::TestProject::test_custom_project",
"tests/test_project.py::TestProject::test_custom_job_class",
"tests/test_project.py::TestProject::test_project_contains",
"tests/test_project.py::TestProject::test_job_move",
"tests/test_project.py::TestProject::test_job_clone",
"tests/test_project.py::TestProject::test_schema_init",
"tests/test_project.py::TestProject::test_schema",
"tests/test_project.py::TestProject::test_schema_subset",
"tests/test_project.py::TestProject::test_schema_eval",
"tests/test_project.py::TestProject::test_schema_difference",
"tests/test_project.py::TestProject::test_jobs_groupby",
"tests/test_project.py::TestProject::test_jobs_groupbydoc",
"tests/test_project.py::TestProject::test_temp_project",
"tests/test_project.py::TestProjectExportImport::test_export",
"tests/test_project.py::TestProjectExportImport::test_export_single_job",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_function",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_tree_flat",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_tree_tree",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_flat_flat",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_flat_tree",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string",
"tests/test_project.py::TestProjectExportImport::test_export_move",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_function_move",
"tests/test_project.py::TestProjectExportImport::test_export_import_tarfile",
"tests/test_project.py::TestProjectExportImport::test_export_import_tarfile_zipped_longname",
"tests/test_project.py::TestProjectExportImport::test_export_import_tarfile_zipped",
"tests/test_project.py::TestProjectExportImport::test_export_import_zipfile",
"tests/test_project.py::TestProjectExportImport::test_export_import",
"tests/test_project.py::TestProjectExportImport::test_export_import_conflict",
"tests/test_project.py::TestProjectExportImport::test_export_import_conflict_synced",
"tests/test_project.py::TestProjectExportImport::test_export_import_conflict_synced_with_args",
"tests/test_project.py::TestProjectExportImport::test_export_import_schema_callable",
"tests/test_project.py::TestProjectExportImport::test_export_import_schema_callable_non_unique",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_nested_with_schema",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_with_float",
"tests/test_project.py::TestProjectExportImport::test_export_import_complex_path",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_schema_from_path",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_schema_from_path_float",
"tests/test_project.py::TestProjectExportImport::test_export_import_complex_path_nested_schema_from_path",
"tests/test_project.py::TestProjectExportImport::test_import_own_project",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_tree",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_tree_tree",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_tree_flat",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_flat_flat",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_flat_tree",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_nested",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_nested_provide_partial_path",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_disjoint_schema",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_disjoint_schema_nested",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_fizz_schema_flat",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_schema_nested",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_schema_nested_partial_homogenous_path_provide",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_schema_problematic",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_with_slash_raises_error",
"tests/test_project.py::TestCachedProject::test_get",
"tests/test_project.py::TestCachedProject::test_get_id",
"tests/test_project.py::TestCachedProject::test_property_id",
"tests/test_project.py::TestCachedProject::test_str",
"tests/test_project.py::TestCachedProject::test_root_directory",
"tests/test_project.py::TestCachedProject::test_workspace_directory",
"tests/test_project.py::TestCachedProject::test_config_modification",
"tests/test_project.py::TestCachedProject::test_workspace_directory_with_env_variable",
"tests/test_project.py::TestCachedProject::test_workspace_directory_exists",
"tests/test_project.py::TestCachedProject::test_fn",
"tests/test_project.py::TestCachedProject::test_isfile",
"tests/test_project.py::TestCachedProject::test_document",
"tests/test_project.py::TestCachedProject::test_doc",
"tests/test_project.py::TestCachedProject::test_write_read_statepoint",
"tests/test_project.py::TestCachedProject::test_workspace_path_normalization",
"tests/test_project.py::TestCachedProject::test_no_workspace_warn_on_find",
"tests/test_project.py::TestCachedProject::test_workspace_broken_link_error_on_find",
"tests/test_project.py::TestCachedProject::test_workspace_read_only_path",
"tests/test_project.py::TestCachedProject::test_find_job_ids",
"tests/test_project.py::TestCachedProject::test_find_jobs",
"tests/test_project.py::TestCachedProject::test_find_jobs_next",
"tests/test_project.py::TestCachedProject::test_find_jobs_arithmetic_operators",
"tests/test_project.py::TestCachedProject::test_find_jobs_logical_operators",
"tests/test_project.py::TestCachedProject::test_num_jobs",
"tests/test_project.py::TestCachedProject::test_len_find_jobs",
"tests/test_project.py::TestCachedProject::test_iteration",
"tests/test_project.py::TestCachedProject::test_open_job_by_id",
"tests/test_project.py::TestCachedProject::test_open_job_by_abbreviated_id",
"tests/test_project.py::TestCachedProject::test_missing_statepoint_file",
"tests/test_project.py::TestCachedProject::test_corrupted_statepoint_file",
"tests/test_project.py::TestCachedProject::test_rename_workspace",
"tests/test_project.py::TestCachedProject::test_repair_corrupted_workspace",
"tests/test_project.py::TestCachedProject::test_index",
"tests/test_project.py::TestCachedProject::test_signac_project_crawler",
"tests/test_project.py::TestCachedProject::test_custom_project",
"tests/test_project.py::TestCachedProject::test_custom_job_class",
"tests/test_project.py::TestCachedProject::test_project_contains",
"tests/test_project.py::TestCachedProject::test_job_move",
"tests/test_project.py::TestCachedProject::test_job_clone",
"tests/test_project.py::TestCachedProject::test_schema_init",
"tests/test_project.py::TestCachedProject::test_schema",
"tests/test_project.py::TestCachedProject::test_schema_subset",
"tests/test_project.py::TestCachedProject::test_schema_eval",
"tests/test_project.py::TestCachedProject::test_schema_difference",
"tests/test_project.py::TestCachedProject::test_jobs_groupby",
"tests/test_project.py::TestCachedProject::test_jobs_groupbydoc",
"tests/test_project.py::TestCachedProject::test_temp_project",
"tests/test_project.py::TestCachedProject::test_repr",
"tests/test_project.py::TestProjectInit::test_get_project",
"tests/test_project.py::TestProjectInit::test_get_project_all_printable_characters",
"tests/test_project.py::TestProjectInit::test_get_project_non_local",
"tests/test_project.py::TestProjectInit::test_init",
"tests/test_project.py::TestProjectInit::test_nested_project",
"tests/test_project.py::TestProjectInit::test_get_job_valid_workspace",
"tests/test_project.py::TestProjectInit::test_get_job_invalid_workspace",
"tests/test_project.py::TestProjectInit::test_get_job_nested_project",
"tests/test_project.py::TestProjectInit::test_get_job_subdir",
"tests/test_project.py::TestProjectInit::test_get_job_nested_project_subdir",
"tests/test_project.py::TestProjectInit::test_get_job_symlink_other_project",
"tests/test_project.py::TestProjectSchema::test_project_schema_versions",
"tests/test_project.py::TestProjectSchema::test_project_schema_version_migration",
"tests/test_project.py::TestProjectSchema::test_no_migration",
"tests/test_project.py::TestProjectPickling::test_pickle_project_empty",
"tests/test_project.py::TestProjectPickling::test_pickle_project_with_jobs",
"tests/test_project.py::TestProjectPickling::test_pickle_jobs_directly",
"tests/test_project.py::TestTestingProjectInitialization::test_input_args"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-19 20:59:31+00:00
|
bsd-3-clause
| 2,551 |
|
glotzerlab__signac-323
|
diff --git a/changelog.txt b/changelog.txt
index 91e497f3..69cf687c 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -15,9 +15,11 @@ Added
- Type annotations are validated during continuous integration (#313).
- Added ``_repr_html_`` method in ``ProjectSchema`` class (#314, #324).
+ - Allow grouping by variables that are not present in all jobs in the project in ``JobsCursor.groupby`` (#321, #323).
Fixed
+++++
+
- Fix the ``signac config verify`` command (previously broken) (#301, #302).
- Warnings now appear when raised by the ``signac`` CLI (#317, #308).
diff --git a/signac/contrib/project.py b/signac/contrib/project.py
index c536c40a..9d85724d 100644
--- a/signac/contrib/project.py
+++ b/signac/contrib/project.py
@@ -1776,8 +1776,14 @@ class JobsCursor(object):
A default value to be used when a given state point key is not present (must
be sortable).
"""
+ _filter = self._filter
if isinstance(key, str):
if default is None:
+ if _filter is None:
+ _filter = {key: {"$exists": True}}
+ else:
+ _filter = {'$and': [{key: {"$exists": True}}, _filter]}
+
def keyfunction(job):
return job.sp[key]
else:
@@ -1786,6 +1792,11 @@ class JobsCursor(object):
elif isinstance(key, Iterable):
if default is None:
+ if _filter is None:
+ _filter = {k: {"$exists": True} for k in key}
+ else:
+ _filter = {'$and': [{k: {"$exists": True} for k in key}, _filter]}
+
def keyfunction(job):
return tuple(job.sp[k] for k in key)
else:
@@ -1800,7 +1811,8 @@ class JobsCursor(object):
else:
keyfunction = key
- return groupby(sorted(iter(self), key=keyfunction), key=keyfunction)
+ return groupby(sorted(iter(JobsCursor(self._project, _filter, self._doc_filter)),
+ key=keyfunction), key=keyfunction)
def groupbydoc(self, key=None, default=None):
"""Groups jobs according to one or more document values.
|
glotzerlab/signac
|
5ae402c9d956a98478ddec660d4b63f37eaae30a
|
diff --git a/tests/test_project.py b/tests/test_project.py
index a128dfd9..100617bc 100644
--- a/tests/test_project.py
+++ b/tests/test_project.py
@@ -836,9 +836,7 @@ class TestProject(TestProjectBase):
assert len(list(g)) == 6
for job in list(g):
assert job.sp['b'] == k
- with pytest.raises(KeyError):
- for k, g in self.project.groupby('d'):
- pass
+ assert len(list(self.project.groupby('d'))) == 0
for k, g in self.project.groupby('d', default=-1):
assert k == -1
assert len(list(g)) == len(self.project)
@@ -863,6 +861,17 @@ class TestProject(TestProjectBase):
assert str(job) == k
assert group_count == len(list(self.project.find_jobs()))
+ self.project.open_job({'a': 20}).init()
+ for k, g in self.project.groupby('b'):
+ assert len(list(g)) == 6
+ for job in list(g):
+ assert job.sp['b'] == k
+ for k, g in self.project.groupby(('b', 'c')):
+ assert len(list(g)) == 2
+ for job in list(g):
+ assert job.sp['b'] == k[0]
+ assert job.sp['c'] == k[1]
+
def test_jobs_groupbydoc(self):
def get_doc(i):
return {
|
groupby() by variables that not present in the entire data space
### Feature description
I am interested in obtaining all the jobs that contain a variable `b` which does not necessarily have to be present in all the jobs.
### Proposed solution
From @bdice in the slack group:
> Bradley Dice 10:43 AM
@Miguel This behavior could be improved, but what would you expect the behavior to be? A group where b is None isn't really an option because b could be set to None in the statepoint. ***We could return only groups where the value is set (and ignore jobs where the key is missing).***
### Additional context
Example of the current problem. First `groupby()` works, second does not.
```python
import signac
project = signac.init_project('test')
sp = { 'a' : 1.0,
'c' : 2.0
}
job = project.open_job(sp)
job.init()
sp = { 'a' : 2.0,
'b' : 1.0,
}
job = project.open_job(sp)
job.init()
sp = { 'a' : 1.0,
'b' : 3.0,
}
job = project.open_job(sp)
job.init()
for a, group in project.groupby('a'):
print(a, list(group))
for b, group in project.groupby('b'):
print(b, list(group))
```
|
0.0
|
5ae402c9d956a98478ddec660d4b63f37eaae30a
|
[
"tests/test_project.py::TestProject::test_jobs_groupby",
"tests/test_project.py::TestCachedProject::test_jobs_groupby"
] |
[
"tests/test_project.py::TestProject::test_get",
"tests/test_project.py::TestProject::test_get_id",
"tests/test_project.py::TestProject::test_property_id",
"tests/test_project.py::TestProject::test_repr",
"tests/test_project.py::TestProject::test_str",
"tests/test_project.py::TestProject::test_root_directory",
"tests/test_project.py::TestProject::test_workspace_directory",
"tests/test_project.py::TestProject::test_config_modification",
"tests/test_project.py::TestProject::test_workspace_directory_with_env_variable",
"tests/test_project.py::TestProject::test_workspace_directory_exists",
"tests/test_project.py::TestProject::test_fn",
"tests/test_project.py::TestProject::test_isfile",
"tests/test_project.py::TestProject::test_document",
"tests/test_project.py::TestProject::test_doc",
"tests/test_project.py::TestProject::test_write_read_statepoint",
"tests/test_project.py::TestProject::test_workspace_path_normalization",
"tests/test_project.py::TestProject::test_no_workspace_warn_on_find",
"tests/test_project.py::TestProject::test_workspace_broken_link_error_on_find",
"tests/test_project.py::TestProject::test_workspace_read_only_path",
"tests/test_project.py::TestProject::test_find_job_ids",
"tests/test_project.py::TestProject::test_find_jobs",
"tests/test_project.py::TestProject::test_find_jobs_next",
"tests/test_project.py::TestProject::test_find_jobs_arithmetic_operators",
"tests/test_project.py::TestProject::test_find_jobs_logical_operators",
"tests/test_project.py::TestProject::test_num_jobs",
"tests/test_project.py::TestProject::test_len_find_jobs",
"tests/test_project.py::TestProject::test_iteration",
"tests/test_project.py::TestProject::test_open_job_by_id",
"tests/test_project.py::TestProject::test_open_job_by_abbreviated_id",
"tests/test_project.py::TestProject::test_missing_statepoint_file",
"tests/test_project.py::TestProject::test_corrupted_statepoint_file",
"tests/test_project.py::TestProject::test_rename_workspace",
"tests/test_project.py::TestProject::test_repair_corrupted_workspace",
"tests/test_project.py::TestProject::test_index",
"tests/test_project.py::TestProject::test_signac_project_crawler",
"tests/test_project.py::TestProject::test_custom_project",
"tests/test_project.py::TestProject::test_custom_job_class",
"tests/test_project.py::TestProject::test_project_contains",
"tests/test_project.py::TestProject::test_job_move",
"tests/test_project.py::TestProject::test_job_clone",
"tests/test_project.py::TestProject::test_schema_init",
"tests/test_project.py::TestProject::test_schema",
"tests/test_project.py::TestProject::test_schema_subset",
"tests/test_project.py::TestProject::test_schema_eval",
"tests/test_project.py::TestProject::test_schema_difference",
"tests/test_project.py::TestProject::test_schema_format",
"tests/test_project.py::TestProject::test_jobs_groupbydoc",
"tests/test_project.py::TestProject::test_temp_project",
"tests/test_project.py::TestProject::test_access_module",
"tests/test_project.py::TestProjectExportImport::test_export",
"tests/test_project.py::TestProjectExportImport::test_export_single_job",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_function",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_tree_flat",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_tree_tree",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_flat_flat",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_flat_tree",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string",
"tests/test_project.py::TestProjectExportImport::test_export_move",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_function_move",
"tests/test_project.py::TestProjectExportImport::test_export_import_tarfile",
"tests/test_project.py::TestProjectExportImport::test_export_import_tarfile_zipped_longname",
"tests/test_project.py::TestProjectExportImport::test_export_import_tarfile_zipped",
"tests/test_project.py::TestProjectExportImport::test_export_import_zipfile",
"tests/test_project.py::TestProjectExportImport::test_export_import",
"tests/test_project.py::TestProjectExportImport::test_export_import_conflict",
"tests/test_project.py::TestProjectExportImport::test_export_import_conflict_synced",
"tests/test_project.py::TestProjectExportImport::test_export_import_conflict_synced_with_args",
"tests/test_project.py::TestProjectExportImport::test_export_import_schema_callable",
"tests/test_project.py::TestProjectExportImport::test_export_import_schema_callable_non_unique",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_nested_with_schema",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_with_float",
"tests/test_project.py::TestProjectExportImport::test_export_import_complex_path",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_schema_from_path",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_schema_from_path_float",
"tests/test_project.py::TestProjectExportImport::test_export_import_complex_path_nested_schema_from_path",
"tests/test_project.py::TestProjectExportImport::test_import_own_project",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_tree",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_tree_tree",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_tree_flat",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_flat_flat",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_flat_tree",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_nested",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_nested_provide_partial_path",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_disjoint_schema",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_disjoint_schema_nested",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_fizz_schema_flat",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_schema_nested",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_schema_nested_partial_homogenous_path_provide",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_schema_problematic",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_with_slash_raises_error",
"tests/test_project.py::TestCachedProject::test_get",
"tests/test_project.py::TestCachedProject::test_get_id",
"tests/test_project.py::TestCachedProject::test_property_id",
"tests/test_project.py::TestCachedProject::test_str",
"tests/test_project.py::TestCachedProject::test_root_directory",
"tests/test_project.py::TestCachedProject::test_workspace_directory",
"tests/test_project.py::TestCachedProject::test_config_modification",
"tests/test_project.py::TestCachedProject::test_workspace_directory_with_env_variable",
"tests/test_project.py::TestCachedProject::test_workspace_directory_exists",
"tests/test_project.py::TestCachedProject::test_fn",
"tests/test_project.py::TestCachedProject::test_isfile",
"tests/test_project.py::TestCachedProject::test_document",
"tests/test_project.py::TestCachedProject::test_doc",
"tests/test_project.py::TestCachedProject::test_write_read_statepoint",
"tests/test_project.py::TestCachedProject::test_workspace_path_normalization",
"tests/test_project.py::TestCachedProject::test_no_workspace_warn_on_find",
"tests/test_project.py::TestCachedProject::test_workspace_broken_link_error_on_find",
"tests/test_project.py::TestCachedProject::test_workspace_read_only_path",
"tests/test_project.py::TestCachedProject::test_find_job_ids",
"tests/test_project.py::TestCachedProject::test_find_jobs",
"tests/test_project.py::TestCachedProject::test_find_jobs_next",
"tests/test_project.py::TestCachedProject::test_find_jobs_arithmetic_operators",
"tests/test_project.py::TestCachedProject::test_find_jobs_logical_operators",
"tests/test_project.py::TestCachedProject::test_num_jobs",
"tests/test_project.py::TestCachedProject::test_len_find_jobs",
"tests/test_project.py::TestCachedProject::test_iteration",
"tests/test_project.py::TestCachedProject::test_open_job_by_id",
"tests/test_project.py::TestCachedProject::test_open_job_by_abbreviated_id",
"tests/test_project.py::TestCachedProject::test_missing_statepoint_file",
"tests/test_project.py::TestCachedProject::test_corrupted_statepoint_file",
"tests/test_project.py::TestCachedProject::test_rename_workspace",
"tests/test_project.py::TestCachedProject::test_repair_corrupted_workspace",
"tests/test_project.py::TestCachedProject::test_index",
"tests/test_project.py::TestCachedProject::test_signac_project_crawler",
"tests/test_project.py::TestCachedProject::test_custom_project",
"tests/test_project.py::TestCachedProject::test_custom_job_class",
"tests/test_project.py::TestCachedProject::test_project_contains",
"tests/test_project.py::TestCachedProject::test_job_move",
"tests/test_project.py::TestCachedProject::test_job_clone",
"tests/test_project.py::TestCachedProject::test_schema_init",
"tests/test_project.py::TestCachedProject::test_schema",
"tests/test_project.py::TestCachedProject::test_schema_subset",
"tests/test_project.py::TestCachedProject::test_schema_eval",
"tests/test_project.py::TestCachedProject::test_schema_difference",
"tests/test_project.py::TestCachedProject::test_schema_format",
"tests/test_project.py::TestCachedProject::test_jobs_groupbydoc",
"tests/test_project.py::TestCachedProject::test_temp_project",
"tests/test_project.py::TestCachedProject::test_access_module",
"tests/test_project.py::TestCachedProject::test_repr",
"tests/test_project.py::TestProjectInit::test_get_project",
"tests/test_project.py::TestProjectInit::test_get_project_all_printable_characters",
"tests/test_project.py::TestProjectInit::test_get_project_non_local",
"tests/test_project.py::TestProjectInit::test_init",
"tests/test_project.py::TestProjectInit::test_nested_project",
"tests/test_project.py::TestProjectInit::test_get_job_valid_workspace",
"tests/test_project.py::TestProjectInit::test_get_job_invalid_workspace",
"tests/test_project.py::TestProjectInit::test_get_job_nested_project",
"tests/test_project.py::TestProjectInit::test_get_job_subdir",
"tests/test_project.py::TestProjectInit::test_get_job_nested_project_subdir",
"tests/test_project.py::TestProjectInit::test_get_job_symlink_other_project",
"tests/test_project.py::TestProjectSchema::test_project_schema_versions",
"tests/test_project.py::TestProjectSchema::test_project_schema_version_migration",
"tests/test_project.py::TestProjectSchema::test_no_migration",
"tests/test_project.py::TestProjectPickling::test_pickle_project_empty",
"tests/test_project.py::TestProjectPickling::test_pickle_project_with_jobs",
"tests/test_project.py::TestProjectPickling::test_pickle_jobs_directly",
"tests/test_project.py::TestTestingProjectInitialization::test_input_args"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-04-08 19:47:53+00:00
|
bsd-3-clause
| 2,552 |
|
glotzerlab__signac-622
|
diff --git a/signac/contrib/filterparse.py b/signac/contrib/filterparse.py
index 0fe52b75..9868fb8d 100644
--- a/signac/contrib/filterparse.py
+++ b/signac/contrib/filterparse.py
@@ -62,8 +62,8 @@ def _read_index(project, fn_index=None):
return (json.loads(line) for line in fd)
-def _is_json(q):
- """Check if q is JSON.
+def _is_json_like(q):
+ """Check if q is JSON like.
Parameters
----------
@@ -76,7 +76,7 @@ def _is_json(q):
True if q starts with "{" and ends with "}".
"""
- return q.strip().startswith("{") and q.strip().endswith("}")
+ return (q[0] == "{" and q[-1] == "}") or (q[0] == "[" and q[-1] == "]")
def _is_regex(q):
@@ -179,19 +179,18 @@ def _parse_single(key, value=None):
------
ValueError
If filter arguments have an invalid key.
-
"""
- if value is None or value == "!":
+ if _is_json_like(key):
+ raise ValueError(
+ "Please check your filter arguments. "
+ f"Using a JSON expression as a key is not allowed: '{key}'."
+ )
+ elif value is None or value == "!":
return key, {"$exists": True}
- elif _is_json(value):
+ elif _is_json_like(value):
return key, _parse_json(value)
elif _is_regex(value):
return key, {"$regex": value[1:-1]}
- elif _is_json(key):
- raise ValueError(
- "Please check your filter arguments. "
- "Using a JSON expression as a key is not allowed: '{}'.".format(key)
- )
else:
return key, _cast(value)
@@ -238,14 +237,13 @@ def parse_filter_arg(args, file=sys.stderr):
if args is None or len(args) == 0:
return None
elif len(args) == 1:
- if _is_json(args[0]):
+ if _is_json_like(args[0]):
return _parse_json(args[0])
else:
key, value = _parse_single(args[0])
return _with_message({key: value}, file)
else:
q = dict(parse_simple(args))
-
return _with_message(q, file)
|
glotzerlab/signac
|
42986037f07766ac1278716d4256da17690747e8
|
diff --git a/tests/test_shell.py b/tests/test_shell.py
index 6ea63bd4..1c5f62de 100644
--- a/tests/test_shell.py
+++ b/tests/test_shell.py
@@ -239,6 +239,7 @@ class TestBasicShell:
self.call("python -m signac init my_project".split())
project = signac.Project()
sps = [{"a": i} for i in range(3)]
+ sps.append({"a": [0, 1, 0]})
for sp in sps:
project.open_job(sp).init()
out = self.call("python -m signac find".split())
@@ -269,8 +270,15 @@ class TestBasicShell:
assert '{"a": 0}' in out
assert '{"a": 2}' in out
+ job = project.open_job({"a": [0, 1, 0]})
+ msg = [*"python -m signac find a".split(), "[0, 1, 0]", "--sp"]
+ out = self.call(msg).strip()
+ assert out.strip().split(os.linesep) == [str(job.id), str(job.statepoint)]
+
# Test the doc_filter
for job in project.find_jobs():
+ if job.statepoint()["a"] == [0, 1, 0]:
+ continue
job.document["a"] = job.statepoint()["a"]
job.document["b"] = job.statepoint()["a"] + 1
|
Using signac find on the CLI for tuples
<!-- Please replace the text in the individual sections below. -->
### Description
Finding jobs for which a given statepoint parameter, x, is equal to a particular list cannot be as easily done with the `signac find` CLI option as it can with other statepoint parameters. For example, `signac find x '[0, 1, 0]'` is currently interpreted as `'{"x": "[0, 1, 0]"}'` . The user has to explicitly specify `signac find '{"x": [0, 1, 0]}'` to get around this.
### To reproduce
`signac find x '[0, 1, 0]'` will return no jobs, even if x = [0, 1, 0] for some of them
### Error output
No error is thrown. The command is only misinterpreted.
### System configuration
Please complete the following information:
- Operating System [e.g. macOS]: macOS
- Version of Python [e.g. 3.7]: 3.9.6
- Version of signac [e.g. 1.0]: 1.7.0
Or copy & paste the output of: `python -c 'import platform; print(platform.platform()); import sys; print(sys.version); import signac; print(signac.__version__)'`
|
0.0
|
42986037f07766ac1278716d4256da17690747e8
|
[
"tests/test_shell.py::TestBasicShell::test_find"
] |
[
"tests/test_shell.py::TestBasicShell::test_print_usage",
"tests/test_shell.py::TestBasicShell::test_version",
"tests/test_shell.py::TestBasicShell::test_help",
"tests/test_shell.py::TestBasicShell::test_init_project",
"tests/test_shell.py::TestBasicShell::test_init_project_in_project_root",
"tests/test_shell.py::TestBasicShell::test_project_id",
"tests/test_shell.py::TestBasicShell::test_project_workspace",
"tests/test_shell.py::TestBasicShell::test_job_with_argument",
"tests/test_shell.py::TestBasicShell::test_job_with_argument_workspace",
"tests/test_shell.py::TestBasicShell::test_job_with_argument_create_workspace",
"tests/test_shell.py::TestBasicShell::test_statepoint",
"tests/test_shell.py::TestBasicShell::test_document",
"tests/test_shell.py::TestBasicShell::test_view_single",
"tests/test_shell.py::TestBasicShell::test_view",
"tests/test_shell.py::TestBasicShell::test_diff",
"tests/test_shell.py::TestBasicShell::test_clone",
"tests/test_shell.py::TestBasicShell::test_move",
"tests/test_shell.py::TestBasicShell::test_remove",
"tests/test_shell.py::TestBasicShell::test_schema",
"tests/test_shell.py::TestBasicShell::test_sync",
"tests/test_shell.py::TestBasicShell::test_sync_merge",
"tests/test_shell.py::TestBasicShell::test_sync_document",
"tests/test_shell.py::TestBasicShell::test_sync_file",
"tests/test_shell.py::TestBasicShell::test_export",
"tests/test_shell.py::TestBasicShell::test_import",
"tests/test_shell.py::TestBasicShell::test_import_sync",
"tests/test_shell.py::TestBasicShell::test_shell",
"tests/test_shell.py::TestBasicShell::test_shell_with_jobs",
"tests/test_shell.py::TestBasicShell::test_shell_with_jobs_and_selection",
"tests/test_shell.py::TestBasicShell::test_shell_with_jobs_and_selection_only_one_job",
"tests/test_shell.py::TestBasicShell::test_config_show",
"tests/test_shell.py::TestBasicShell::test_config_set",
"tests/test_shell.py::TestBasicShell::test_update_cache"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-16 20:00:59+00:00
|
bsd-3-clause
| 2,553 |
|
glotzerlab__signac-877
|
diff --git a/changelog.txt b/changelog.txt
index 9baa08f3..24e74b2b 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -54,7 +54,7 @@ Removed
- The ability to pass indexes to various ``Project`` methods (#599).
- The following ``JobsCursor`` methods: ``groupbydoc``, ``next`` (#601, #604).
- The ``Project.config`` property is no longer mutable. Use the command line ``$ signac config`` to modify configuration (#608, #246, #244).
- - The following config related functions: ``get_config``, ``load_config``, ``read_config_file``, ``search_standard_dirs`` (#674, #753, #789, #847).
+ - The config module and all its functions, all of which have been made private (#674, #753, #789, #847, #877).
- ``Project`` subclasses can no longer define a ``Job`` subclass to use (#588, #693).
- The ``Collection`` class (#664, #667, #683).
- The ``project`` CLI subcommand (#752).
diff --git a/signac/__main__.py b/signac/__main__.py
index b18f54c8..7211be8e 100644
--- a/signac/__main__.py
+++ b/signac/__main__.py
@@ -29,7 +29,15 @@ except ImportError:
else:
READLINE = True
-from . import config, get_project, init_project
+from . import get_project, init_project
+from ._config import (
+ PROJECT_CONFIG_FN,
+ USER_CONFIG_FN,
+ _Config,
+ _load_config,
+ _locate_config_dir,
+ _read_config_file,
+)
from ._utility import _add_verbosity_argument, _print_err, _query_yes_no, _safe_relpath
from ._vendor.configobj import Section, flatten_errors
from .diff import diff_jobs
@@ -663,12 +671,12 @@ def main_config_show(args):
if args.local and args.globalcfg:
raise ValueError("You can specify either -l/--local or -g/--global, not both.")
elif args.local:
- if os.path.isfile(config.PROJECT_CONFIG_FN):
- cfg = config._read_config_file(config.PROJECT_CONFIG_FN)
+ if os.path.isfile(PROJECT_CONFIG_FN):
+ cfg = _read_config_file(PROJECT_CONFIG_FN)
elif args.globalcfg:
- cfg = config._read_config_file(config.USER_CONFIG_FN)
+ cfg = _read_config_file(USER_CONFIG_FN)
else:
- cfg = config._load_config(config._locate_config_dir(os.getcwd()))
+ cfg = _load_config(_locate_config_dir(os.getcwd()))
if not cfg:
if args.local:
mode = "local"
@@ -686,7 +694,7 @@ def main_config_show(args):
if not isinstance(cfg, Section):
print(cfg)
else:
- for line in config._Config(cfg).write():
+ for line in _Config(cfg).write():
print(line)
@@ -717,12 +725,12 @@ def main_config_verify(args):
if args.local and args.globalcfg:
raise ValueError("You can specify either -l/--local or -g/--global, not both.")
elif args.local:
- if os.path.isfile(config.PROJECT_CONFIG_FN):
- cfg = config._read_config_file(config.PROJECT_CONFIG_FN)
+ if os.path.isfile(PROJECT_CONFIG_FN):
+ cfg = _read_config_file(PROJECT_CONFIG_FN)
elif args.globalcfg:
- cfg = config._read_config_file(config.USER_CONFIG_FN)
+ cfg = _read_config_file(USER_CONFIG_FN)
else:
- cfg = config._load_config(config._locate_config_dir(os.getcwd()))
+ cfg = _load_config(_locate_config_dir(os.getcwd()))
if not cfg:
if args.local:
mode = "local"
@@ -746,16 +754,16 @@ def main_config_set(args):
if args.local and args.globalcfg:
raise ValueError("You can specify either -l/--local or -g/--global, not both.")
elif args.local:
- if os.path.isfile(config.PROJECT_CONFIG_FN):
- fn_config = config.PROJECT_CONFIG_FN
+ if os.path.isfile(PROJECT_CONFIG_FN):
+ fn_config = PROJECT_CONFIG_FN
elif args.globalcfg:
- fn_config = config.USER_CONFIG_FN
+ fn_config = USER_CONFIG_FN
else:
raise ValueError(
"You need to specify either -l/--local or -g/--global "
"to specify which configuration to modify."
)
- cfg = config._read_config_file(fn_config)
+ cfg = _read_config_file(fn_config)
keys = args.key.split(".")
if len(args.value) == 0:
raise ValueError("No value argument provided!")
diff --git a/signac/config.py b/signac/_config.py
similarity index 100%
rename from signac/config.py
rename to signac/_config.py
diff --git a/signac/migration/v1_to_v2.py b/signac/migration/v1_to_v2.py
index e2da1e52..224c1d58 100644
--- a/signac/migration/v1_to_v2.py
+++ b/signac/migration/v1_to_v2.py
@@ -15,11 +15,10 @@ This migration involves the following changes:
import os
-from signac._synced_collections.backends.collection_json import BufferedJSONAttrDict
-from signac._vendor import configobj
-from signac.config import _get_project_config_fn
-from signac.project import Project
-
+from .._config import _get_project_config_fn
+from .._synced_collections.backends.collection_json import BufferedJSONAttrDict
+from .._vendor import configobj
+from ..project import Project
from .v0_to_v1 import _load_config_v1
# A minimal v2 config.
diff --git a/signac/project.py b/signac/project.py
index fe43f5cb..54c76bf9 100644
--- a/signac/project.py
+++ b/signac/project.py
@@ -20,10 +20,7 @@ from multiprocessing.pool import ThreadPool
from tempfile import TemporaryDirectory
from threading import RLock
-from ._search_indexer import _SearchIndexer
-from ._synced_collections.backends.collection_json import BufferedJSONAttrDict
-from ._utility import _mkdir_p, _nested_dicts_to_dotted_keys, _split_and_print_progress
-from .config import (
+from ._config import (
_Config,
_get_project_config_fn,
_load_config,
@@ -31,6 +28,9 @@ from .config import (
_raise_if_older_schema,
_read_config_file,
)
+from ._search_indexer import _SearchIndexer
+from ._synced_collections.backends.collection_json import BufferedJSONAttrDict
+from ._utility import _mkdir_p, _nested_dicts_to_dotted_keys, _split_and_print_progress
from .errors import (
DestinationExistsError,
IncompatibleSchemaVersion,
|
glotzerlab/signac
|
16a33c7ba5097447f552774bf02832eeac96a7b3
|
diff --git a/tests/test_job.py b/tests/test_job.py
index 3979461f..85df7de8 100644
--- a/tests/test_job.py
+++ b/tests/test_job.py
@@ -12,7 +12,8 @@ from tempfile import TemporaryDirectory
import pytest
-import signac.config
+import signac
+from signac._config import _load_config
from signac.errors import (
DestinationExistsError,
InvalidKeyError,
@@ -64,7 +65,7 @@ class TestJobBase:
request.addfinalizer(self._tmp_dir.cleanup)
self._tmp_pr = os.path.join(self._tmp_dir.name, "pr")
os.mkdir(self._tmp_pr)
- self.config = signac.config._load_config()
+ self.config = _load_config()
self.project = self.project_class.init_project(path=self._tmp_pr)
def tearDown(self):
diff --git a/tests/test_project.py b/tests/test_project.py
index e5c9cca6..42b860b3 100644
--- a/tests/test_project.py
+++ b/tests/test_project.py
@@ -22,7 +22,7 @@ from packaging import version
from test_job import TestJobBase
import signac
-from signac.config import (
+from signac._config import (
PROJECT_CONFIG_FN,
_get_project_config_fn,
_load_config,
diff --git a/tests/test_shell.py b/tests/test_shell.py
index 83fd1d37..073223e7 100644
--- a/tests/test_shell.py
+++ b/tests/test_shell.py
@@ -12,7 +12,7 @@ import pytest
from test_project import _initialize_v1_project
import signac
-from signac import config
+from signac._config import USER_CONFIG_FN, _Config, _load_config, _read_config_file
# Skip linked view tests on Windows
WINDOWS = sys.platform == "win32"
@@ -743,18 +743,18 @@ class TestBasicShell:
self.call("python -m signac init".split())
out = self.call("python -m signac config --local show".split()).strip()
- cfg = config._read_config_file(".signac/config")
- expected = config._Config(cfg).write()
+ cfg = _read_config_file(".signac/config")
+ expected = _Config(cfg).write()
assert out.split(os.linesep) == expected
out = self.call("python -m signac config show".split()).strip()
- cfg = config._load_config()
- expected = config._Config(cfg).write()
+ cfg = _load_config()
+ expected = _Config(cfg).write()
assert out.split(os.linesep) == expected
out = self.call("python -m signac config --global show".split()).strip()
- cfg = config._read_config_file(config.USER_CONFIG_FN)
- expected = config._Config(cfg).write()
+ cfg = _read_config_file(USER_CONFIG_FN)
+ expected = _Config(cfg).write()
assert out.split(os.linesep) == expected
def test_config_set(self):
@@ -769,12 +769,12 @@ class TestBasicShell:
assert "[x]" in cfg
assert "y = z" in cfg
- backup_config = os.path.exists(config.USER_CONFIG_FN)
- global_config_path_backup = config.USER_CONFIG_FN + ".tmp"
+ backup_config = os.path.exists(USER_CONFIG_FN)
+ global_config_path_backup = USER_CONFIG_FN + ".tmp"
try:
# Make a backup of the global config if it exists
if backup_config:
- shutil.copy2(config.USER_CONFIG_FN, global_config_path_backup)
+ shutil.copy2(USER_CONFIG_FN, global_config_path_backup)
# Test the global config CLI
self.call("python -m signac config --global set b c".split())
@@ -785,9 +785,9 @@ class TestBasicShell:
# Revert the global config to its previous state (or remove it if
# it did not exist)
if backup_config:
- shutil.move(global_config_path_backup, config.USER_CONFIG_FN)
+ shutil.move(global_config_path_backup, USER_CONFIG_FN)
else:
- os.remove(config.USER_CONFIG_FN)
+ os.remove(USER_CONFIG_FN)
def test_config_verify(self):
# no config file
|
Make config module internal
The config.py module no longer contains any public APIs. The only publicly visible items are the constants `PROJECT_CONFIG_FN` and `USER_CONFIG_FN`. Should we change this module to `_config`? If so, do we want to keep those two variables public so that users can easily and programmatically see where to expect signac's config files to be stored? To do so I would suggest importing those into `signac/__init__.py` and adding them to `__all__` in that package.
|
0.0
|
16a33c7ba5097447f552774bf02832eeac96a7b3
|
[
"tests/test_job.py::TestJobID::test_builtins",
"tests/test_job.py::TestJobID::test_shuffle",
"tests/test_job.py::TestJobID::test_nested",
"tests/test_job.py::TestJobID::test_sequences_identity",
"tests/test_job.py::TestJob::test_repr",
"tests/test_job.py::TestJob::test_str",
"tests/test_job.py::TestJob::test_eq",
"tests/test_job.py::TestJob::test_isfile",
"tests/test_job.py::TestJob::test_copy",
"tests/test_job.py::TestJob::test_deepcopy",
"tests/test_job.py::TestJob::test_project_access_from_job",
"tests/test_job.py::TestJob::test_custom_project_access_from_job",
"tests/test_job.py::TestJobSpInterface::test_interface_read_only",
"tests/test_job.py::TestJobSpInterface::test_interface_contains",
"tests/test_job.py::TestJobSpInterface::test_interface_read_write",
"tests/test_job.py::TestJobSpInterface::test_interface_job_identity_change",
"tests/test_job.py::TestJobSpInterface::test_interface_nested_kws",
"tests/test_job.py::TestJobSpInterface::test_interface_lists",
"tests/test_job.py::TestJobSpInterface::test_interface_reserved_keywords",
"tests/test_job.py::TestJobSpInterface::test_interface_illegal_type",
"tests/test_job.py::TestJobSpInterface::test_interface_rename",
"tests/test_job.py::TestJobSpInterface::test_interface_copy",
"tests/test_job.py::TestJobSpInterface::test_interface_deepcopy",
"tests/test_job.py::TestJobSpInterface::test_interface_add",
"tests/test_job.py::TestJobSpInterface::test_interface_delete",
"tests/test_job.py::TestJobSpInterface::test_interface_destination_conflict",
"tests/test_job.py::TestJobSpInterface::test_interface_multiple_changes",
"tests/test_job.py::TestJobSpInterface::test_valid_sp_key_types",
"tests/test_job.py::TestJobSpInterface::test_invalid_sp_key_types",
"tests/test_job.py::TestJobSpInterface::test_valid_doc_key_types",
"tests/test_job.py::TestJobSpInterface::test_invalid_doc_key_types",
"tests/test_job.py::TestConfig::test_config_str",
"tests/test_job.py::TestJobOpenAndClosing::test_init",
"tests/test_job.py::TestJobOpenAndClosing::test_chained_init",
"tests/test_job.py::TestJobOpenAndClosing::test_construction",
"tests/test_job.py::TestJobOpenAndClosing::test_open_job_close",
"tests/test_job.py::TestJobOpenAndClosing::test_open_job_close_manual",
"tests/test_job.py::TestJobOpenAndClosing::test_open_job_close_with_error",
"tests/test_job.py::TestJobOpenAndClosing::test_reopen_job",
"tests/test_job.py::TestJobOpenAndClosing::test_close_nonopen_job",
"tests/test_job.py::TestJobOpenAndClosing::test_close_job_while_open",
"tests/test_job.py::TestJobOpenAndClosing::test_open_job_recursive",
"tests/test_job.py::TestJobOpenAndClosing::test_corrupt_workspace",
"tests/test_job.py::TestJobDocument::test_get_set",
"tests/test_job.py::TestJobDocument::test_del",
"tests/test_job.py::TestJobDocument::test_get_set_doc",
"tests/test_job.py::TestJobDocument::test_set_set_doc",
"tests/test_job.py::TestJobDocument::test_get_set_nested",
"tests/test_job.py::TestJobDocument::test_get_set_nested_doc",
"tests/test_job.py::TestJobDocument::test_assign",
"tests/test_job.py::TestJobDocument::test_assign_doc",
"tests/test_job.py::TestJobDocument::test_copy_document",
"tests/test_job.py::TestJobDocument::test_update",
"tests/test_job.py::TestJobDocument::test_clear_document",
"tests/test_job.py::TestJobDocument::test_reopen",
"tests/test_job.py::TestJobDocument::test_concurrency",
"tests/test_job.py::TestJobDocument::test_remove",
"tests/test_job.py::TestJobDocument::test_clear_job",
"tests/test_job.py::TestJobDocument::test_reset",
"tests/test_job.py::TestJobDocument::test_doc",
"tests/test_job.py::TestJobDocument::test_sp_formatting",
"tests/test_job.py::TestJobDocument::test_doc_formatting",
"tests/test_project.py::TestProject::test_repr",
"tests/test_project.py::TestProject::test_str",
"tests/test_project.py::TestProject::test_path",
"tests/test_project.py::TestProject::test_workspace_directory",
"tests/test_project.py::TestProject::test_config_modification",
"tests/test_project.py::TestProject::test_workspace_directory_exists",
"tests/test_project.py::TestProject::test_fn",
"tests/test_project.py::TestProject::test_isfile",
"tests/test_project.py::TestProject::test_document",
"tests/test_project.py::TestProject::test_doc",
"tests/test_project.py::TestProject::test_no_workspace_warn_on_find",
"tests/test_project.py::TestProject::test_workspace_broken_link_error_on_find",
"tests/test_project.py::TestProject::test_workspace_read_only_path",
"tests/test_project.py::TestProject::test_find_jobs",
"tests/test_project.py::TestProject::test_find_jobs_JobsCursor_contains",
"tests/test_project.py::TestProject::test_find_jobs_arithmetic_operators",
"tests/test_project.py::TestProject::test_find_jobs_logical_operators",
"tests/test_project.py::TestProject::test_len_project",
"tests/test_project.py::TestProject::test_len_find_jobs",
"tests/test_project.py::TestProject::test_iteration",
"tests/test_project.py::TestProject::test_open_job_by_id",
"tests/test_project.py::TestProject::test_open_job_no_id_or_statepoint",
"tests/test_project.py::TestProject::test_open_job_by_abbreviated_id",
"tests/test_project.py::TestProject::test_missing_statepoint_file",
"tests/test_project.py::TestProject::test_corrupted_statepoint_file",
"tests/test_project.py::TestProject::test_rename_workspace",
"tests/test_project.py::TestProject::test_repair_corrupted_workspace",
"tests/test_project.py::TestProject::test_index",
"tests/test_project.py::TestProject::test_custom_project",
"tests/test_project.py::TestProject::test_project_contains",
"tests/test_project.py::TestProject::test_JobsCursor_contains",
"tests/test_project.py::TestProject::test_job_move",
"tests/test_project.py::TestProject::test_job_clone",
"tests/test_project.py::TestProject::test_schema_init",
"tests/test_project.py::TestProject::test_schema",
"tests/test_project.py::TestProject::test_schema_subset",
"tests/test_project.py::TestProject::test_schema_difference",
"tests/test_project.py::TestProject::test_schema_format",
"tests/test_project.py::TestProject::test_jobs_groupby",
"tests/test_project.py::TestProject::test_temp_project",
"tests/test_project.py::TestProjectExportImport::test_export",
"tests/test_project.py::TestProjectExportImport::test_export_single_job",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_function",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_tree_flat",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_tree_tree",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_flat_flat",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string_modify_flat_tree",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_string",
"tests/test_project.py::TestProjectExportImport::test_export_move",
"tests/test_project.py::TestProjectExportImport::test_export_custom_path_function_move",
"tests/test_project.py::TestProjectExportImport::test_export_import_tarfile",
"tests/test_project.py::TestProjectExportImport::test_export_import_tarfile_zipped_longname",
"tests/test_project.py::TestProjectExportImport::test_export_import_tarfile_zipped",
"tests/test_project.py::TestProjectExportImport::test_export_import_zipfile",
"tests/test_project.py::TestProjectExportImport::test_export_import",
"tests/test_project.py::TestProjectExportImport::test_export_import_conflict",
"tests/test_project.py::TestProjectExportImport::test_export_import_conflict_synced",
"tests/test_project.py::TestProjectExportImport::test_export_import_conflict_synced_with_args",
"tests/test_project.py::TestProjectExportImport::test_export_import_schema_callable",
"tests/test_project.py::TestProjectExportImport::test_export_import_schema_callable_non_unique",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_nested_with_schema",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_with_float",
"tests/test_project.py::TestProjectExportImport::test_export_import_complex_path",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_schema_from_path",
"tests/test_project.py::TestProjectExportImport::test_export_import_simple_path_schema_from_path_float",
"tests/test_project.py::TestProjectExportImport::test_export_import_complex_path_nested_schema_from_path",
"tests/test_project.py::TestProjectExportImport::test_import_own_project",
"tests/test_project.py::TestProjectRepresentation::test_Schema_repr_methods[add_jobs_homogeneous-0]",
"tests/test_project.py::TestProjectRepresentation::test_Schema_repr_methods[add_jobs_homogeneous-10]",
"tests/test_project.py::TestProjectRepresentation::test_Schema_repr_methods[add_jobs_homogeneous-200]",
"tests/test_project.py::TestProjectRepresentation::test_Schema_repr_methods[add_jobs_heterogeneous-0]",
"tests/test_project.py::TestProjectRepresentation::test_Schema_repr_methods[add_jobs_heterogeneous-10]",
"tests/test_project.py::TestProjectRepresentation::test_Schema_repr_methods[add_jobs_heterogeneous-200]",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_tree",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_tree_tree",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_tree_flat",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_flat_flat",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_flat_tree",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_nested",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_homogeneous_schema_nested_provide_partial_path",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_disjoint_schema",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_disjoint_schema_nested",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_fizz_schema_flat",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_schema_nested",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_schema_nested_partial_homogenous_path_provide",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_heterogeneous_schema_problematic",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_with_slash_raises_error",
"tests/test_project.py::TestLinkedViewProject::test_create_linked_view_duplicate_paths",
"tests/test_project.py::TestCachedProject::test_str",
"tests/test_project.py::TestCachedProject::test_path",
"tests/test_project.py::TestCachedProject::test_workspace_directory",
"tests/test_project.py::TestCachedProject::test_config_modification",
"tests/test_project.py::TestCachedProject::test_workspace_directory_exists",
"tests/test_project.py::TestCachedProject::test_fn",
"tests/test_project.py::TestCachedProject::test_isfile",
"tests/test_project.py::TestCachedProject::test_document",
"tests/test_project.py::TestCachedProject::test_doc",
"tests/test_project.py::TestCachedProject::test_no_workspace_warn_on_find",
"tests/test_project.py::TestCachedProject::test_workspace_broken_link_error_on_find",
"tests/test_project.py::TestCachedProject::test_workspace_read_only_path",
"tests/test_project.py::TestCachedProject::test_find_jobs",
"tests/test_project.py::TestCachedProject::test_find_jobs_JobsCursor_contains",
"tests/test_project.py::TestCachedProject::test_find_jobs_arithmetic_operators",
"tests/test_project.py::TestCachedProject::test_find_jobs_logical_operators",
"tests/test_project.py::TestCachedProject::test_len_project",
"tests/test_project.py::TestCachedProject::test_len_find_jobs",
"tests/test_project.py::TestCachedProject::test_iteration",
"tests/test_project.py::TestCachedProject::test_open_job_by_id",
"tests/test_project.py::TestCachedProject::test_open_job_no_id_or_statepoint",
"tests/test_project.py::TestCachedProject::test_open_job_by_abbreviated_id",
"tests/test_project.py::TestCachedProject::test_missing_statepoint_file",
"tests/test_project.py::TestCachedProject::test_corrupted_statepoint_file",
"tests/test_project.py::TestCachedProject::test_rename_workspace",
"tests/test_project.py::TestCachedProject::test_repair_corrupted_workspace",
"tests/test_project.py::TestCachedProject::test_index",
"tests/test_project.py::TestCachedProject::test_custom_project",
"tests/test_project.py::TestCachedProject::test_project_contains",
"tests/test_project.py::TestCachedProject::test_JobsCursor_contains",
"tests/test_project.py::TestCachedProject::test_job_move",
"tests/test_project.py::TestCachedProject::test_job_clone",
"tests/test_project.py::TestCachedProject::test_schema_init",
"tests/test_project.py::TestCachedProject::test_schema",
"tests/test_project.py::TestCachedProject::test_schema_subset",
"tests/test_project.py::TestCachedProject::test_schema_difference",
"tests/test_project.py::TestCachedProject::test_schema_format",
"tests/test_project.py::TestCachedProject::test_jobs_groupby",
"tests/test_project.py::TestCachedProject::test_temp_project",
"tests/test_project.py::TestCachedProject::test_repr",
"tests/test_project.py::TestProjectInit::test_get_project",
"tests/test_project.py::TestProjectInit::test_get_project_non_local",
"tests/test_project.py::TestProjectInit::test_init",
"tests/test_project.py::TestProjectInit::test_nested_project",
"tests/test_project.py::TestProjectInit::test_get_job_valid_workspace",
"tests/test_project.py::TestProjectInit::test_get_job_invalid_workspace",
"tests/test_project.py::TestProjectInit::test_get_job_nested_project",
"tests/test_project.py::TestProjectInit::test_get_job_subdir",
"tests/test_project.py::TestProjectInit::test_get_job_nested_project_subdir",
"tests/test_project.py::TestProjectInit::test_get_job_symlink_other_project",
"tests/test_project.py::TestProjectSchema::test_project_schema_versions",
"tests/test_project.py::TestSchemaMigration::test_project_schema_version_migration[True-True-True]",
"tests/test_project.py::TestSchemaMigration::test_project_schema_version_migration[True-True-False]",
"tests/test_project.py::TestSchemaMigration::test_project_schema_version_migration[True-False-True]",
"tests/test_project.py::TestSchemaMigration::test_project_schema_version_migration[True-False-False]",
"tests/test_project.py::TestSchemaMigration::test_project_schema_version_migration[False-True-True]",
"tests/test_project.py::TestSchemaMigration::test_project_schema_version_migration[False-True-False]",
"tests/test_project.py::TestSchemaMigration::test_project_schema_version_migration[False-False-True]",
"tests/test_project.py::TestSchemaMigration::test_project_schema_version_migration[False-False-False]",
"tests/test_project.py::TestSchemaMigration::test_project_init_old_schema",
"tests/test_project.py::TestProjectPickling::test_pickle_project_empty",
"tests/test_project.py::TestProjectPickling::test_pickle_project_with_jobs",
"tests/test_project.py::TestProjectPickling::test_pickle_jobs_directly",
"tests/test_shell.py::TestBasicShell::test_print_usage",
"tests/test_shell.py::TestBasicShell::test_version",
"tests/test_shell.py::TestBasicShell::test_help",
"tests/test_shell.py::TestBasicShell::test_init_project",
"tests/test_shell.py::TestBasicShell::test_job_with_argument",
"tests/test_shell.py::TestBasicShell::test_job_with_argument_workspace",
"tests/test_shell.py::TestBasicShell::test_job_with_argument_create_workspace",
"tests/test_shell.py::TestBasicShell::test_statepoint",
"tests/test_shell.py::TestBasicShell::test_document",
"tests/test_shell.py::TestBasicShell::test_view_single",
"tests/test_shell.py::TestBasicShell::test_view",
"tests/test_shell.py::TestBasicShell::test_view_prefix",
"tests/test_shell.py::TestBasicShell::test_view_incomplete_path_spec",
"tests/test_shell.py::TestBasicShell::test_find",
"tests/test_shell.py::TestBasicShell::test_diff",
"tests/test_shell.py::TestBasicShell::test_clone",
"tests/test_shell.py::TestBasicShell::test_move",
"tests/test_shell.py::TestBasicShell::test_remove",
"tests/test_shell.py::TestBasicShell::test_schema",
"tests/test_shell.py::TestBasicShell::test_sync",
"tests/test_shell.py::TestBasicShell::test_sync_merge",
"tests/test_shell.py::TestBasicShell::test_sync_document",
"tests/test_shell.py::TestBasicShell::test_sync_file",
"tests/test_shell.py::TestBasicShell::test_export",
"tests/test_shell.py::TestBasicShell::test_import",
"tests/test_shell.py::TestBasicShell::test_import_sync",
"tests/test_shell.py::TestBasicShell::test_shell",
"tests/test_shell.py::TestBasicShell::test_shell_with_jobs",
"tests/test_shell.py::TestBasicShell::test_shell_with_jobs_and_selection",
"tests/test_shell.py::TestBasicShell::test_shell_with_jobs_and_selection_only_one_job",
"tests/test_shell.py::TestBasicShell::test_config_show",
"tests/test_shell.py::TestBasicShell::test_config_set",
"tests/test_shell.py::TestBasicShell::test_config_verify",
"tests/test_shell.py::TestBasicShell::test_update_cache",
"tests/test_shell.py::TestBasicShell::test_migrate_v1_to_v2"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-08 04:20:46+00:00
|
bsd-3-clause
| 2,554 |
|
glotzerlab__signac-flow-738
|
diff --git a/changelog.txt b/changelog.txt
index a002f4d..1657aef 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -8,6 +8,19 @@ The numbers in brackets denote the related GitHub issue and/or pull request.
Version 0.25
============
+[0.25.1] -- 2023-XX-XX
+----------------------
+
+Fixed
++++++
+
+- Fix filter argument (#737, #738).
+
+Removed
++++++++
+
+- ``--doc-filter`` argument (#738).
+
[0.25.0] -- 2023-03-30
----------------------
diff --git a/flow/project.py b/flow/project.py
index 8fdd92f..8bd2970 100644
--- a/flow/project.py
+++ b/flow/project.py
@@ -4223,12 +4223,6 @@ class FlowProject(signac.Project, metaclass=_FlowProjectClass):
nargs="+",
help="Only select jobs that match the given state point filter.",
)
- parser.add_argument(
- "--doc-filter",
- type=str,
- nargs="+",
- help="Only select jobs that match the given document filter.",
- )
@classmethod
def _add_operation_selection_arg_group(cls, parser):
@@ -4757,7 +4751,6 @@ class FlowProject(signac.Project, metaclass=_FlowProjectClass):
"debug",
"job_id",
"filter",
- "doc_filter",
]
}
if args.pop("full"):
@@ -4876,14 +4869,10 @@ class FlowProject(signac.Project, metaclass=_FlowProjectClass):
operation_function(*aggregate)
def _select_jobs_from_args(self, args):
- """Select jobs with the given command line arguments ('-j/-f/--doc-filter/--job-id')."""
- if (
- not args.func == self._main_exec
- and args.job_id
- and (args.filter or args.doc_filter)
- ):
+ """Select jobs with the given command line arguments ('-j/-f/--job-id')."""
+ if not args.func == self._main_exec and args.job_id and (args.filter):
raise ValueError(
- "Cannot provide both -j/--job-id and -f/--filter or --doc-filter in combination."
+ "Cannot provide both -j/--job-id and -f/--filter in combination."
)
if args.job_id:
@@ -4900,12 +4889,11 @@ class FlowProject(signac.Project, metaclass=_FlowProjectClass):
elif args.func == self._main_exec:
# exec command does not support filters, so we must exit early.
return _AggregateStoresCursor(self)
- elif args.filter or args.doc_filter:
- # filter or doc_filter provided. Filters can only be used to select
+ elif args.filter:
+ # filter, including doc_filter provided. Filters can only be used to select
# single jobs and not aggregates of multiple jobs.
filter_ = parse_filter_arg(args.filter)
- doc_filter = parse_filter_arg(args.doc_filter)
- return _JobAggregateCursor(self, filter_, doc_filter)
+ return _JobAggregateCursor(self, filter_)
else:
# Use all aggregates
return _AggregateStoresCursor(self)
|
glotzerlab/signac-flow
|
4590e4258942512d24b281d34a0205e1e5bf3c69
|
diff --git a/tests/test_project.py b/tests/test_project.py
index a8b9940..7d06273 100644
--- a/tests/test_project.py
+++ b/tests/test_project.py
@@ -1307,6 +1307,18 @@ class TestProjectMainInterface(TestProjectBase):
else:
assert not job.isfile("world.txt")
+ def test_main_run_filter(self):
+ assert len(self.project)
+ for job in self.project:
+ assert not job.isfile("world.txt")
+ self.call_subcmd("run -o op1 -f b 2")
+ even_jobs = [job for job in self.project if job.sp.b == 2]
+ for job in self.project:
+ if job in even_jobs:
+ assert job.isfile("world.txt")
+ else:
+ assert not job.isfile("world.txt")
+
def test_main_run_invalid_op(self):
assert len(self.project)
run_output = self.call_subcmd(
|
Error when running jobs using -f on command line
### Description
When I use `python project.py run -f ...` on the command line, flow errors internally.
### To reproduce
```python
import signac
from flow import FlowProject
from pathlib import Path
project = signac.get_project(Path(__file__).parent / "SignacProject")
job_sps = [{'a': 1, 'b': 2},
{'a': 1, 'b': 3}]
for job_sp in job_sps:
job = project.open_job(job_sp)
job.init()
class SignacProject(FlowProject):
pass
@SignacProject.operation
def print_statepoint(job):
print(job.sp)
if __name__ == "__main__":
SignacProject.get_project(project.path).main()
```
Try to run the only job on the command line with
```bash
python script.py run -f b 2
```
### Error output
```bash
$ python script.py run -f b 2
Using environment configuration: StandardEnvironment
Interpreted filter arguments as '{"b": 2}'.
Traceback (most recent call last):
File "/Users/tomwalt/scripts/signac/flow-2.0-bug/script.py", line 26, in <module>
SignacProject.get_project(project.path).main()
File "/Users/tomwalt/miniconda3/envs/py310/lib/python3.10/site-packages/flow/project.py", line 5132, in main
args.func(args)
File "/Users/tomwalt/miniconda3/envs/py310/lib/python3.10/site-packages/flow/project.py", line 4820, in _main_run
aggregates = self._select_jobs_from_args(args)
File "/Users/tomwalt/miniconda3/envs/py310/lib/python3.10/site-packages/flow/project.py", line 4908, in _select_jobs_from_args
return _JobAggregateCursor(self, filter_, doc_filter)
TypeError: _JobAggregateCursor.__init__() takes from 2 to 3 positional arguments but 4 were given
```
### System configuration
Please complete the following information:
- Operating System [e.g. macOS]: macOS, linux
- Version of Python [e.g. 3.7]: 3.10.10
- Version of signac [e.g. 1.0]: 2.0.0
- Version of signac-flow: 0.25.0
|
0.0
|
4590e4258942512d24b281d34a0205e1e5bf3c69
|
[
"tests/test_project.py::TestProjectMainInterface::test_main_run_filter",
"tests/test_project.py::TestDynamicProjectMainInterface::test_main_run_filter",
"tests/test_project.py::TestGroupDynamicProjectMainInterface::test_main_run_filter"
] |
[
"tests/test_project.py::TestProjectStatusPerformance::test_status_performance",
"tests/test_project.py::TestProjectStatusNoEligibleOperations::test_status_no_eligible_operations",
"tests/test_project.py::TestProjectClass::test_operation_definition",
"tests/test_project.py::TestProjectClass::test_repeat_operation_definition",
"tests/test_project.py::TestProjectClass::test_repeat_anonymous_operation_definition",
"tests/test_project.py::TestProjectClass::test_repeat_operation_name",
"tests/test_project.py::TestProjectClass::test_condition_as_operation",
"tests/test_project.py::TestProjectClass::test_operation_as_condition",
"tests/test_project.py::TestProjectClass::test_repeat_operation_definition_with_inheritance",
"tests/test_project.py::TestProjectClass::test_label_definition",
"tests/test_project.py::TestProjectClass::test_conditions_with_inheritance",
"tests/test_project.py::TestProjectClass::test_with_job_argument",
"tests/test_project.py::TestProjectClass::test_cmd_operation_argument",
"tests/test_project.py::TestProjectClass::test_with_job_works_with_cmd",
"tests/test_project.py::TestProjectClass::test_operations_user_error_handling",
"tests/test_project.py::TestProjectClass::test_with_job_user_error_handling",
"tests/test_project.py::TestProjectClass::test_cmd_with_job_user_error_handling",
"tests/test_project.py::TestProjectClass::test_function_in_directives",
"tests/test_project.py::TestProjectClass::test_invalid_memory_directive",
"tests/test_project.py::TestProjectClass::test_memory_directive",
"tests/test_project.py::TestProjectClass::test_walltime_directive",
"tests/test_project.py::TestProjectClass::test_invalid_walltime_directive",
"tests/test_project.py::TestProjectClass::test_callable_directives",
"tests/test_project.py::TestProjectClass::test_callable_directives_with_groups",
"tests/test_project.py::TestProjectClass::test_copy_conditions",
"tests/test_project.py::TestProjectClass::test_preconditions_and_postconditions",
"tests/test_project.py::TestProjectClass::test_condition_using_functools",
"tests/test_project.py::TestProject::test_instance",
"tests/test_project.py::TestProject::test_labels",
"tests/test_project.py::TestProject::test_next_operations",
"tests/test_project.py::TestProject::test_get_job_status",
"tests/test_project.py::TestProject::test_project_status_homogeneous_schema",
"tests/test_project.py::TestProject::test_serial_project_status_homogeneous_schema",
"tests/test_project.py::TestProject::test_thread_parallelized_project_status_homogeneous_schema",
"tests/test_project.py::TestProject::test_process_parallelized_project_status_homogeneous_schema",
"tests/test_project.py::TestProject::test_project_status_invalid_parallelization_config",
"tests/test_project.py::TestProject::test_project_status_heterogeneous_schema",
"tests/test_project.py::TestProject::test_init",
"tests/test_project.py::TestProject::test_graph_detection_error_raising",
"tests/test_project.py::TestExecutionProject::test_next_operations_order",
"tests/test_project.py::TestExecutionProject::test_run_invalid_order",
"tests/test_project.py::TestExecutionProject::test_run_order[None]",
"tests/test_project.py::TestExecutionProject::test_run_order[none]",
"tests/test_project.py::TestExecutionProject::test_run_order[cyclic]",
"tests/test_project.py::TestExecutionProject::test_run_order[by-job]",
"tests/test_project.py::TestExecutionProject::test_run_order[random]",
"tests/test_project.py::TestExecutionProject::test_run_order[<lambda>]",
"tests/test_project.py::TestExecutionProject::test_run_with_selection",
"tests/test_project.py::TestExecutionProject::test_run_with_operation_selection",
"tests/test_project.py::TestExecutionProject::test_run_parallel",
"tests/test_project.py::TestExecutionProject::test_run_condition_inheritance",
"tests/test_project.py::TestExecutionProject::test_run_fork",
"tests/test_project.py::TestExecutionProject::test_run_invalid_ops",
"tests/test_project.py::TestExecutionProject::test_submit_operations",
"tests/test_project.py::TestExecutionProject::test_submit",
"tests/test_project.py::TestExecutionProject::test_submit_bad_names_argument",
"tests/test_project.py::TestExecutionProject::test_submit_limited",
"tests/test_project.py::TestExecutionProject::test_submit_error",
"tests/test_project.py::TestExecutionProject::test_resubmit",
"tests/test_project.py::TestExecutionProject::test_bundles",
"tests/test_project.py::TestExecutionProject::test_submit_status",
"tests/test_project.py::TestExecutionProject::test_submit_operations_bad_directive",
"tests/test_project.py::TestExecutionProject::test_condition_evaluation",
"tests/test_project.py::TestExecutionDynamicProject::test_next_operations_order",
"tests/test_project.py::TestExecutionDynamicProject::test_run_invalid_order",
"tests/test_project.py::TestExecutionDynamicProject::test_run_order[None]",
"tests/test_project.py::TestExecutionDynamicProject::test_run_order[none]",
"tests/test_project.py::TestExecutionDynamicProject::test_run_order[cyclic]",
"tests/test_project.py::TestExecutionDynamicProject::test_run_order[by-job]",
"tests/test_project.py::TestExecutionDynamicProject::test_run_order[random]",
"tests/test_project.py::TestExecutionDynamicProject::test_run_order[<lambda>]",
"tests/test_project.py::TestExecutionDynamicProject::test_run_with_selection",
"tests/test_project.py::TestExecutionDynamicProject::test_run_with_operation_selection",
"tests/test_project.py::TestExecutionDynamicProject::test_run_parallel",
"tests/test_project.py::TestExecutionDynamicProject::test_run_condition_inheritance",
"tests/test_project.py::TestExecutionDynamicProject::test_run_fork",
"tests/test_project.py::TestExecutionDynamicProject::test_run_invalid_ops",
"tests/test_project.py::TestExecutionDynamicProject::test_submit_operations",
"tests/test_project.py::TestExecutionDynamicProject::test_submit",
"tests/test_project.py::TestExecutionDynamicProject::test_submit_bad_names_argument",
"tests/test_project.py::TestExecutionDynamicProject::test_submit_limited",
"tests/test_project.py::TestExecutionDynamicProject::test_submit_error",
"tests/test_project.py::TestExecutionDynamicProject::test_resubmit",
"tests/test_project.py::TestExecutionDynamicProject::test_bundles",
"tests/test_project.py::TestExecutionDynamicProject::test_submit_status",
"tests/test_project.py::TestExecutionDynamicProject::test_submit_operations_bad_directive",
"tests/test_project.py::TestExecutionDynamicProject::test_condition_evaluation",
"tests/test_project.py::TestProjectMainInterface::test_main_help",
"tests/test_project.py::TestProjectMainInterface::test_main_exec",
"tests/test_project.py::TestProjectMainInterface::test_main_run",
"tests/test_project.py::TestProjectMainInterface::test_main_run_invalid_op",
"tests/test_project.py::TestProjectMainInterface::test_main_run_invalid_job",
"tests/test_project.py::TestProjectMainInterface::test_main_run_invalid_aggregate",
"tests/test_project.py::TestProjectMainInterface::test_main_next",
"tests/test_project.py::TestProjectMainInterface::test_main_next_invalid_op",
"tests/test_project.py::TestProjectMainInterface::test_main_status",
"tests/test_project.py::TestDynamicProjectMainInterface::test_main_help",
"tests/test_project.py::TestDynamicProjectMainInterface::test_main_exec",
"tests/test_project.py::TestDynamicProjectMainInterface::test_main_run",
"tests/test_project.py::TestDynamicProjectMainInterface::test_main_run_invalid_op",
"tests/test_project.py::TestDynamicProjectMainInterface::test_main_run_invalid_job",
"tests/test_project.py::TestDynamicProjectMainInterface::test_main_run_invalid_aggregate",
"tests/test_project.py::TestDynamicProjectMainInterface::test_main_next",
"tests/test_project.py::TestDynamicProjectMainInterface::test_main_next_invalid_op",
"tests/test_project.py::TestDynamicProjectMainInterface::test_main_status",
"tests/test_project.py::TestDirectivesProjectMainInterface::test_main_submit_walltime_with_directive",
"tests/test_project.py::TestDirectivesProjectMainInterface::test_main_submit_walltime_no_directive",
"tests/test_project.py::TestDirectivesProjectMainInterface::test_main_submit_walltime_with_groups",
"tests/test_project.py::TestDirectivesProjectMainInterface::test_main_submit_walltime_serial",
"tests/test_project.py::TestDirectivesProjectMainInterface::test_main_submit_walltime_parallel",
"tests/test_project.py::TestProjectDagDetection::test_dag",
"tests/test_project.py::TestProjectSubmitOptions::test_main_submit_after[DefaultSlurmEnvironment-sbatch",
"tests/test_project.py::TestProjectSubmitOptions::test_main_submit_after[DefaultPBSEnvironment-qsub",
"tests/test_project.py::TestProjectSubmitOptions::test_main_submit_after[DefaultLSFEnvironment-bsub",
"tests/test_project.py::TestProjectSubmitOptions::test_main_submit_hold[DefaultSlurmEnvironment-sbatch",
"tests/test_project.py::TestProjectSubmitOptions::test_main_submit_hold[DefaultPBSEnvironment-qsub",
"tests/test_project.py::TestProjectSubmitOptions::test_main_submit_hold[DefaultLSFEnvironment-bsub",
"tests/test_project.py::TestProjectSubmitOptions::test_main_submit_job_output[DefaultSlurmEnvironment-job_output_flags0]",
"tests/test_project.py::TestProjectSubmitOptions::test_main_submit_job_output[DefaultPBSEnvironment-job_output_flags1]",
"tests/test_project.py::TestProjectSubmitOptions::test_main_submit_job_output[DefaultLSFEnvironment-job_output_flags2]",
"tests/test_project.py::TestGroupProject::test_instance",
"tests/test_project.py::TestGroupProject::test_directives_hierarchy",
"tests/test_project.py::TestGroupProject::test_unique_group_operation_names",
"tests/test_project.py::TestGroupProject::test_group_operation_without_operation_definition",
"tests/test_project.py::TestGroupProject::test_group_operation_without_operation_definition_anonymous",
"tests/test_project.py::TestGroupProject::test_repeat_group_definition",
"tests/test_project.py::TestGroupProject::test_repeat_operation_group_definition",
"tests/test_project.py::TestGroupProject::test_submission_combine_directives",
"tests/test_project.py::TestGroupProject::test_flowgroup_repr",
"tests/test_project.py::TestGroupProject::test_submit_options",
"tests/test_project.py::TestGroupProject::test_run_options",
"tests/test_project.py::TestGroupExecutionProject::test_run_with_operation_selection",
"tests/test_project.py::TestGroupExecutionProject::test_run_parallel",
"tests/test_project.py::TestGroupExecutionProject::test_submit_groups",
"tests/test_project.py::TestGroupExecutionProject::test_submit_groups_invalid_char_with_error",
"tests/test_project.py::TestGroupExecutionProject::test_submit_groups_invalid_char_avoid_error",
"tests/test_project.py::TestGroupExecutionProject::test_submit",
"tests/test_project.py::TestGroupExecutionProject::test_submit_invalid_char_with_error",
"tests/test_project.py::TestGroupExecutionProject::test_submit_invalid_char_avoid_error",
"tests/test_project.py::TestGroupExecutionProject::test_group_resubmit",
"tests/test_project.py::TestGroupExecutionProject::test_operation_resubmit",
"tests/test_project.py::TestGroupExecutionDynamicProject::test_run_with_operation_selection",
"tests/test_project.py::TestGroupExecutionDynamicProject::test_run_parallel",
"tests/test_project.py::TestGroupExecutionDynamicProject::test_submit_groups",
"tests/test_project.py::TestGroupExecutionDynamicProject::test_submit_groups_invalid_char_with_error",
"tests/test_project.py::TestGroupExecutionDynamicProject::test_submit_groups_invalid_char_avoid_error",
"tests/test_project.py::TestGroupExecutionDynamicProject::test_submit",
"tests/test_project.py::TestGroupExecutionDynamicProject::test_submit_invalid_char_with_error",
"tests/test_project.py::TestGroupExecutionDynamicProject::test_submit_invalid_char_avoid_error",
"tests/test_project.py::TestGroupExecutionDynamicProject::test_group_resubmit",
"tests/test_project.py::TestGroupExecutionDynamicProject::test_operation_resubmit",
"tests/test_project.py::TestGroupProjectMainInterface::test_main_run",
"tests/test_project.py::TestGroupProjectMainInterface::test_main_submit",
"tests/test_project.py::TestGroupDynamicProjectMainInterface::test_main_help",
"tests/test_project.py::TestGroupDynamicProjectMainInterface::test_main_exec",
"tests/test_project.py::TestGroupDynamicProjectMainInterface::test_main_run",
"tests/test_project.py::TestGroupDynamicProjectMainInterface::test_main_run_invalid_op",
"tests/test_project.py::TestGroupDynamicProjectMainInterface::test_main_run_invalid_job",
"tests/test_project.py::TestGroupDynamicProjectMainInterface::test_main_run_invalid_aggregate",
"tests/test_project.py::TestGroupDynamicProjectMainInterface::test_main_next",
"tests/test_project.py::TestGroupDynamicProjectMainInterface::test_main_next_invalid_op",
"tests/test_project.py::TestGroupDynamicProjectMainInterface::test_main_status",
"tests/test_project.py::TestAggregatesProjectBase::test_aggregator_with_job",
"tests/test_project.py::TestAggregationProjectMainInterface::test_aggregator_with_job",
"tests/test_project.py::TestAggregationProjectMainInterface::test_main_run",
"tests/test_project.py::TestAggregationProjectMainInterface::test_main_run_abbreviated",
"tests/test_project.py::TestAggregationProjectMainInterface::test_main_run_cmd",
"tests/test_project.py::TestAggregationProjectMainInterface::test_main_run_parallel",
"tests/test_project.py::TestAggregationProjectMainInterface::test_main_submit",
"tests/test_project.py::TestAggregationGroupProjectMainInterface::test_aggregator_with_job",
"tests/test_project.py::TestAggregationGroupProjectMainInterface::test_main_run",
"tests/test_project.py::TestAggregationGroupProjectMainInterface::test_main_run_abbreviated",
"tests/test_project.py::TestAggregationGroupProjectMainInterface::test_main_run_abbreviated_duplicate",
"tests/test_project.py::TestAggregationGroupProjectMainInterface::test_main_submit",
"tests/test_project.py::TestHooksBase::test_start_and_finish[raise_exception-base]",
"tests/test_project.py::TestHooksBase::test_start_and_finish[no_exception-base]",
"tests/test_project.py::TestHooksBase::test_success[raise_exception-base]",
"tests/test_project.py::TestHooksBase::test_success[no_exception-base]",
"tests/test_project.py::TestHooksBase::test_fail[raise_exception-base]",
"tests/test_project.py::TestHooksBase::test_fail[no_exception-base]",
"tests/test_project.py::TestHooksCmd::test_start_and_finish[raise_exception-base_cmd]",
"tests/test_project.py::TestHooksCmd::test_start_and_finish[no_exception-base_cmd]",
"tests/test_project.py::TestHooksCmd::test_success[raise_exception-base_cmd]",
"tests/test_project.py::TestHooksCmd::test_success[no_exception-base_cmd]",
"tests/test_project.py::TestHooksCmd::test_fail[raise_exception-base_cmd]",
"tests/test_project.py::TestHooksCmd::test_fail[no_exception-base_cmd]",
"tests/test_project.py::TestHooksInstallBase::test_start_and_finish[raise_exception-base]",
"tests/test_project.py::TestHooksInstallBase::test_start_and_finish[raise_exception-base_no_decorators]",
"tests/test_project.py::TestHooksInstallBase::test_start_and_finish[no_exception-base]",
"tests/test_project.py::TestHooksInstallBase::test_start_and_finish[no_exception-base_no_decorators]",
"tests/test_project.py::TestHooksInstallBase::test_success[raise_exception-base]",
"tests/test_project.py::TestHooksInstallBase::test_success[raise_exception-base_no_decorators]",
"tests/test_project.py::TestHooksInstallBase::test_success[no_exception-base]",
"tests/test_project.py::TestHooksInstallBase::test_success[no_exception-base_no_decorators]",
"tests/test_project.py::TestHooksInstallBase::test_fail[raise_exception-base]",
"tests/test_project.py::TestHooksInstallBase::test_fail[raise_exception-base_no_decorators]",
"tests/test_project.py::TestHooksInstallBase::test_fail[no_exception-base]",
"tests/test_project.py::TestHooksInstallBase::test_fail[no_exception-base_no_decorators]",
"tests/test_project.py::TestHooksInstallCmd::test_start_and_finish[raise_exception-base_cmd]",
"tests/test_project.py::TestHooksInstallCmd::test_start_and_finish[raise_exception-base_cmd_no_decorators]",
"tests/test_project.py::TestHooksInstallCmd::test_start_and_finish[no_exception-base_cmd]",
"tests/test_project.py::TestHooksInstallCmd::test_start_and_finish[no_exception-base_cmd_no_decorators]",
"tests/test_project.py::TestHooksInstallCmd::test_success[raise_exception-base_cmd]",
"tests/test_project.py::TestHooksInstallCmd::test_success[raise_exception-base_cmd_no_decorators]",
"tests/test_project.py::TestHooksInstallCmd::test_success[no_exception-base_cmd]",
"tests/test_project.py::TestHooksInstallCmd::test_success[no_exception-base_cmd_no_decorators]",
"tests/test_project.py::TestHooksInstallCmd::test_fail[raise_exception-base_cmd]",
"tests/test_project.py::TestHooksInstallCmd::test_fail[raise_exception-base_cmd_no_decorators]",
"tests/test_project.py::TestHooksInstallCmd::test_fail[no_exception-base_cmd]",
"tests/test_project.py::TestHooksInstallCmd::test_fail[no_exception-base_cmd_no_decorators]",
"tests/test_project.py::TestHooksInstallWithDecorators::test_start_and_finish[raise_exception-base]",
"tests/test_project.py::TestHooksInstallWithDecorators::test_start_and_finish[no_exception-base]",
"tests/test_project.py::TestHooksInstallWithDecorators::test_success[raise_exception-base]",
"tests/test_project.py::TestHooksInstallWithDecorators::test_success[no_exception-base]",
"tests/test_project.py::TestHooksInstallWithDecorators::test_fail[raise_exception-base]",
"tests/test_project.py::TestHooksInstallWithDecorators::test_fail[no_exception-base]",
"tests/test_project.py::TestHooksInstallCmdWithDecorators::test_start_and_finish[raise_exception]",
"tests/test_project.py::TestHooksInstallCmdWithDecorators::test_start_and_finish[no_exception]",
"tests/test_project.py::TestHooksInstallCmdWithDecorators::test_success[raise_exception]",
"tests/test_project.py::TestHooksInstallCmdWithDecorators::test_success[no_exception]",
"tests/test_project.py::TestHooksInstallCmdWithDecorators::test_fail[raise_exception]",
"tests/test_project.py::TestHooksInstallCmdWithDecorators::test_fail[no_exception]",
"tests/test_project.py::TestHooksInstallNoDecorators::test_no_decorator_keys[base_no_decorators]",
"tests/test_project.py::TestHooksInstallNoDecorators::test_no_decorator_keys[base_cmd_no_decorators]",
"tests/test_project.py::TestHooksInvalidOption::test_invalid_hook",
"tests/test_project.py::TestHooksInvalidOption::test_install_invalid_hook",
"tests/test_project.py::TestHooksInvalidOption::test_raise_exception_in_hook",
"tests/test_project.py::TestHooksInvalidOption::test_raise_exception_in_hook_cmd",
"tests/test_project.py::TestIgnoreConditions::test_str",
"tests/test_project.py::TestIgnoreConditions::test_invert"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-14 18:51:25+00:00
|
bsd-3-clause
| 2,555 |
|
glue-viz__glue-astronomy-25
|
diff --git a/glue_astronomy/translators/ccddata.py b/glue_astronomy/translators/ccddata.py
index c862c6a..52a7d78 100644
--- a/glue_astronomy/translators/ccddata.py
+++ b/glue_astronomy/translators/ccddata.py
@@ -1,6 +1,5 @@
-import numpy as np
-
from astropy.wcs import WCS
+from astropy.nddata import CCDData
from glue.config import data_translator
from glue.core import Data, Subset
diff --git a/glue_astronomy/translators/spectral_cube.py b/glue_astronomy/translators/spectral_cube.py
index 8fa161f..c0baff7 100644
--- a/glue_astronomy/translators/spectral_cube.py
+++ b/glue_astronomy/translators/spectral_cube.py
@@ -1,5 +1,3 @@
-import numpy as np
-
from astropy.wcs.wcsapi import BaseLowLevelWCS
from glue.config import data_translator
diff --git a/glue_astronomy/translators/spectrum1d.py b/glue_astronomy/translators/spectrum1d.py
index db64c40..42c22a9 100644
--- a/glue_astronomy/translators/spectrum1d.py
+++ b/glue_astronomy/translators/spectrum1d.py
@@ -29,7 +29,7 @@ class Specutils1DHandler:
# Include uncertainties if they exist
if obj.uncertainty is not None:
data['uncertainty'] = obj.uncertainty.quantity
- data.get_component('uncertainty').units = str(obj.unit)
+ data.get_component('uncertainty').units = str(obj.uncertainty.unit)
data.meta.update({'uncertainty_type': obj.uncertainty.uncertainty_type})
# Include mask if it exists
|
glue-viz/glue-astronomy
|
b518b0d56840f7ee7b825f15f7621514f6afa465
|
diff --git a/glue_astronomy/translators/tests/test_spectrum1d.py b/glue_astronomy/translators/tests/test_spectrum1d.py
index c5d894d..4ccfc61 100644
--- a/glue_astronomy/translators/tests/test_spectrum1d.py
+++ b/glue_astronomy/translators/tests/test_spectrum1d.py
@@ -7,7 +7,7 @@ from specutils import Spectrum1D
from astropy import units as u
from astropy.wcs import WCS
from astropy.tests.helper import assert_quantity_allclose
-from astropy.nddata import StdDevUncertainty
+from astropy.nddata import VarianceUncertainty
from glue.core import Data, DataCollection
from glue.core.component import Component
@@ -136,8 +136,8 @@ def test_from_spectrum1d(mode):
kwargs = {'spectral_axis': [1, 2, 3, 4] * u.Hz}
spec = Spectrum1D([2, 3, 4, 5] * u.Jy,
- uncertainty=StdDevUncertainty(
- [0.1, 0.1, 0.1, 0.1] * u.Jy),
+ uncertainty=VarianceUncertainty(
+ [0.1, 0.1, 0.1, 0.1] * u.Jy**2),
mask=[False, False, False, False],
**kwargs)
@@ -158,7 +158,7 @@ def test_from_spectrum1d(mode):
assert data.main_components[1].label == 'uncertainty'
assert_allclose(data['uncertainty'], [0.1, 0.1, 0.1, 0.1])
component = data.get_component('uncertainty')
- assert component.units == 'Jy'
+ assert component.units == 'Jy2'
# Check round-tripping via single attribute reference
spec_new = data.get_object(attribute='flux')
@@ -173,4 +173,4 @@ def test_from_spectrum1d(mode):
assert_quantity_allclose(spec_new.spectral_axis, [1, 2, 3, 4] * u.Hz)
assert_quantity_allclose(spec_new.flux, [2, 3, 4, 5] * u.Jy)
assert spec_new.uncertainty is not None
- assert_quantity_allclose(spec_new.uncertainty.quantity, [0.1, 0.1, 0.1, 0.1] * u.Jy)
+ assert_quantity_allclose(spec_new.uncertainty.quantity, [0.1, 0.1, 0.1, 0.1] * u.Jy**2)
|
Uncertainties failing to round-trip properly from Spectrum1D
Using the latest version throws an error when retrieving a Spectrum1D in `jdaviz` (the file is https://data.sdss.org/sas/dr14/sdss/spectro/redux/26/spectra/0751/spec-0751-52251-0160.fits):
```
---------------------------------------------------------------------------
UnitConversionError Traceback (most recent call last)
~/opt/anaconda3/envs/viz_dev/lib/python3.8/site-packages/astropy/nddata/nduncertainty.py in parent_nddata(self, value)
232 try:
--> 233 unit_from_data.to(self.unit)
234 except UnitConversionError:
~/opt/anaconda3/envs/viz_dev/lib/python3.8/site-packages/astropy/units/quantity.py in to(self, unit, equivalencies)
688 unit = Unit(unit)
--> 689 return self._new_view(self._to_value(unit, equivalencies), unit)
690
~/opt/anaconda3/envs/viz_dev/lib/python3.8/site-packages/astropy/units/quantity.py in _to_value(self, unit, equivalencies)
659 equivalencies = self._equivalencies
--> 660 return self.unit.to(unit, self.view(np.ndarray),
661 equivalencies=equivalencies)
~/opt/anaconda3/envs/viz_dev/lib/python3.8/site-packages/astropy/units/core.py in to(self, other, value, equivalencies)
986 else:
--> 987 return self._get_converter(other, equivalencies=equivalencies)(value)
988
~/opt/anaconda3/envs/viz_dev/lib/python3.8/site-packages/astropy/units/core.py in _get_converter(self, other, equivalencies)
917
--> 918 raise exc
919
~/opt/anaconda3/envs/viz_dev/lib/python3.8/site-packages/astropy/units/core.py in _get_converter(self, other, equivalencies)
902 try:
--> 903 return self._apply_equivalencies(
904 self, other, self._normalize_equivalencies(equivalencies))
~/opt/anaconda3/envs/viz_dev/lib/python3.8/site-packages/astropy/units/core.py in _apply_equivalencies(self, unit, other, equivalencies)
885
--> 886 raise UnitConversionError(
887 "{} and {} are not convertible".format(
UnitConversionError: 'Angstrom2 cm4 s2 / erg2' and 'erg / (Angstrom cm2 s)' (spectral flux density wav) are not convertible
During handling of the above exception, another exception occurred:
UnitConversionError Traceback (most recent call last)
<ipython-input-2-a4b364c1fa48> in <module>
1 from astropy.utils.data import download_file
2 fn = download_file('https://data.sdss.org/sas/dr14/sdss/spectro/redux/26/spectra/0751/spec-0751-52251-0160.fits', cache=True)
----> 3 specviz.load_spectrum(fn, "myfile", format="SDSS-III/IV spec")
~/projects/jdaviz/jdaviz/configs/specviz/helper.py in load_spectrum(self, data, data_label, format, show_in_viewer)
67 self.app.add_data(data, data_label)
68 if show_in_viewer:
---> 69 self.app.add_data_to_viewer("spectrum-viewer", data_label)
70
71 def get_spectra(self, data_label=None):
~/projects/jdaviz/jdaviz/app.py in add_data_to_viewer(self, viewer_reference, data_label, clear_other_data)
563 if data_id is not None:
564 data_ids.append(data_id)
--> 565 self._update_selected_data_items(viewer_item['id'], data_ids)
566 else:
567 raise ValueError(
~/projects/jdaviz/jdaviz/app.py in _update_selected_data_items(self, viewer_id, selected_items)
833 viewer_id=viewer_id,
834 sender=self)
--> 835 self.hub.broadcast(add_data_message)
836
837 # Remove any deselected data objects from viewer
~/projects/glue/glue/core/hub.py in broadcast(self, message)
213 logging.getLogger(__name__).info("Broadcasting %s", message)
214 for subscriber, handler in self._find_handlers(message):
--> 215 handler(message)
216
217 def __getstate__(self):
~/projects/jdaviz/jdaviz/configs/specviz/plugins/unit_conversion/unit_conversion.py in _on_viewer_data_changed(self, msg)
72 viewer = self.app.get_viewer('spectrum-viewer')
73
---> 74 self._viewer_data = self.app.get_data_from_viewer('spectrum-viewer')
75
76 self.dc_items = [layer_state.layer.label
~/projects/jdaviz/jdaviz/app.py in get_data_from_viewer(self, viewer_reference, data_label, cls, include_subsets)
372
373 if cls is not None:
--> 374 layer_data = layer_data.get_object(cls=cls,
375 statistic=statistic)
376 # If the shape of the data is 2d, then use CCDData as the
~/projects/glue/glue/core/data.py in get_object(self, cls, **kwargs)
287 handler, _ = data_translator.get_handler_for(cls)
288
--> 289 return handler.to_object(self, **kwargs)
290
291 @property
~/projects/glue-astronomy/glue_astronomy/translators/spectrum1d.py in to_object(self, data_or_subset, attribute, statistic)
145 [attribute] if not hasattr(attribute, '__len__') else attribute)
146
--> 147 return Spectrum1D(**data_kwargs, **kwargs)
~/projects/specutils/specutils/spectra/spectrum1d.py in __init__(self, flux, spectral_axis, wcs, velocity_convention, rest_value, redshift, radial_velocity, bin_specification, **kwargs)
187 wcs = gwcs_from_array(np.arange(size) * u.Unit(""))
188
--> 189 super(Spectrum1D, self).__init__(
190 data=flux.value if isinstance(flux, u.Quantity) else flux,
191 wcs=wcs, **kwargs)
~/opt/anaconda3/envs/viz_dev/lib/python3.8/site-packages/astropy/nddata/nddata.py in __init__(self, data, uncertainty, mask, wcs, meta, unit, copy)
232 self._unit = unit
233 # Call the setter for uncertainty to further check the uncertainty
--> 234 self.uncertainty = uncertainty
235
236 def __str__(self):
~/opt/anaconda3/envs/viz_dev/lib/python3.8/site-packages/astropy/nddata/nddata.py in uncertainty(self, value)
324 # to be saved as weakref but that's done by NDUncertainty
325 # setter).
--> 326 value.parent_nddata = self
327 self._uncertainty = value
~/opt/anaconda3/envs/viz_dev/lib/python3.8/site-packages/astropy/nddata/nduncertainty.py in parent_nddata(self, value)
233 unit_from_data.to(self.unit)
234 except UnitConversionError:
--> 235 raise UnitConversionError("Unit {} of uncertainty "
236 "incompatible with unit {} of "
237 "data".format(self.unit,
UnitConversionError: Unit 1e-17 erg / (Angstrom cm2 s) of uncertainty incompatible with unit 1e-17 erg / (Angstrom cm2 s) of data
```
|
0.0
|
b518b0d56840f7ee7b825f15f7621514f6afa465
|
[
"glue_astronomy/translators/tests/test_spectrum1d.py::test_from_spectrum1d[wcs]",
"glue_astronomy/translators/tests/test_spectrum1d.py::test_from_spectrum1d[lookup]"
] |
[
"glue_astronomy/translators/tests/test_spectrum1d.py::test_to_spectrum1d",
"glue_astronomy/translators/tests/test_spectrum1d.py::test_to_spectrum1d_unitless",
"glue_astronomy/translators/tests/test_spectrum1d.py::test_to_spectrum1d_invalid",
"glue_astronomy/translators/tests/test_spectrum1d.py::test_to_spectrum1d_from_3d_cube",
"glue_astronomy/translators/tests/test_spectrum1d.py::test_to_spectrum1d_with_spectral_coordinates",
"glue_astronomy/translators/tests/test_spectrum1d.py::test_to_spectrum1d_default_attribute"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-08-17 16:11:41+00:00
|
bsd-3-clause
| 2,556 |
|
godatadriven__evol-164
|
diff --git a/evol/__init__.py b/evol/__init__.py
index 6746f75..9f44276 100644
--- a/evol/__init__.py
+++ b/evol/__init__.py
@@ -119,4 +119,4 @@ from .population import Population, ContestPopulation
from .evolution import Evolution
from .logger import BaseLogger
-__version__ = "0.5.2"
+__version__ = "0.5.3"
diff --git a/evol/population.py b/evol/population.py
index 9a7aedd..8e989f5 100644
--- a/evol/population.py
+++ b/evol/population.py
@@ -207,7 +207,7 @@ class BasePopulation(metaclass=ABCMeta):
:param kwargs: Arguments to pass to the mutation function.
:return: self
"""
- elite_fitness = self.current_best if elitist else None
+ elite_fitness: Optional[float] = self.current_best.fitness if elitist else None
for individual in self.individuals:
if elite_fitness is None or individual.fitness != elite_fitness:
individual.mutate(mutate_function, probability=probability, **kwargs)
|
godatadriven/evol
|
b092a309f5fd4091b76b7bfd773ff9daa8ae9b2f
|
diff --git a/tests/test_population.py b/tests/test_population.py
index 0e441b9..a9b772c 100644
--- a/tests/test_population.py
+++ b/tests/test_population.py
@@ -244,7 +244,7 @@ class TestPopulationMutate:
def test_mutate_elitist(self):
pop = Population([1, 1, 3], eval_function=lambda x: x).evaluate().mutate(lambda x: x + 1, elitist=True)
for chromosome in pop.chromosomes:
- assert chromosome > 1
+ assert 1 < chromosome <= 3
assert len(pop) == 3
|
Not sure if elitism works
I put elitist to True in my mutation step, but it did not work when looking at the source code it looks like it will not work.
`
elite_fitness = self.current_best if elitist else None
for individual in self.individuals:
if elite_fitness is None or individual.fitness != elite_fitness:
individual.mutate(mutate_function, probability=probability, **kwargs)
return self
`
elite_fitness is set as an 'individual' object, then in the if statement it is compared to the floating point fitness instead of the actual object. Therefore individual.fitness will never equal elite_fitness and the current_best is not skipped over like it should be.
|
0.0
|
b092a309f5fd4091b76b7bfd773ff9daa8ae9b2f
|
[
"tests/test_population.py::TestPopulationMutate::test_mutate_elitist"
] |
[
"tests/test_population.py::TestPopulationSimple::test_filter_works",
"tests/test_population.py::TestPopulationSimple::test_population_init",
"tests/test_population.py::TestPopulationSimple::test_population_generate",
"tests/test_population.py::TestPopulationSimple::test_is_evaluated[0]",
"tests/test_population.py::TestPopulationSimple::test_is_evaluated[1]",
"tests/test_population.py::TestPopulationCopy::test_population_copy[0]",
"tests/test_population.py::TestPopulationCopy::test_population_copy[1]",
"tests/test_population.py::TestPopulationCopy::test_population_is_evaluated[0]",
"tests/test_population.py::TestPopulationCopy::test_population_is_evaluated[1]",
"tests/test_population.py::TestPopulationEvaluate::test_individuals_are_not_initially_evaluated[0]",
"tests/test_population.py::TestPopulationEvaluate::test_individuals_are_not_initially_evaluated[1]",
"tests/test_population.py::TestPopulationEvaluate::test_evaluate_lambda",
"tests/test_population.py::TestPopulationEvaluate::test_evaluate_func",
"tests/test_population.py::TestPopulationEvaluate::test_evaluate_lazy[0]",
"tests/test_population.py::TestPopulationEvaluate::test_evaluate_lazy[1]",
"tests/test_population.py::TestPopulationSurvive::test_survive_n_works",
"tests/test_population.py::TestPopulationSurvive::test_survive_p_works",
"tests/test_population.py::TestPopulationSurvive::test_survive_n_and_p_works",
"tests/test_population.py::TestPopulationSurvive::test_breed_increases_generation[0]",
"tests/test_population.py::TestPopulationSurvive::test_breed_increases_generation[1]",
"tests/test_population.py::TestPopulationSurvive::test_survive_throws_correct_errors[0]",
"tests/test_population.py::TestPopulationSurvive::test_survive_throws_correct_errors[1]",
"tests/test_population.py::TestPopulationBreed::test_breed_amount_works",
"tests/test_population.py::TestPopulationBreed::test_breed_works_with_kwargs",
"tests/test_population.py::TestPopulationBreed::test_breed_raises_with_multiple_values_for_kwarg",
"tests/test_population.py::TestPopulationMutate::test_mutate_lambda",
"tests/test_population.py::TestPopulationMutate::test_mutate_inplace",
"tests/test_population.py::TestPopulationMutate::test_mutate_func",
"tests/test_population.py::TestPopulationMutate::test_mutate_probability",
"tests/test_population.py::TestPopulationMutate::test_mutate_zero_probability",
"tests/test_population.py::TestPopulationMutate::test_mutate_func_kwargs",
"tests/test_population.py::TestPopulationWeights::test_weights",
"tests/test_population.py::TestPopulationBest::test_current_best",
"tests/test_population.py::TestPopulationBest::test_current_worst",
"tests/test_population.py::TestPopulationBest::test_mutate_resets",
"tests/test_population.py::TestPopulationBest::test_documented_best",
"tests/test_population.py::TestPopulationIslands::test_groups[1]",
"tests/test_population.py::TestPopulationIslands::test_groups[2]",
"tests/test_population.py::TestPopulationIslands::test_groups[3]",
"tests/test_population.py::TestPopulationIslands::test_groups[4]",
"tests/test_population.py::TestPopulationIslands::test_no_groups",
"tests/test_population.py::TestPopulationIslands::test_empty_group",
"tests/test_population.py::TestPopulationIslands::test_invalid_group[result0-TypeError]",
"tests/test_population.py::TestPopulationIslands::test_invalid_group[result1-TypeError]",
"tests/test_population.py::TestPopulationIslands::test_invalid_group[result2-IndexError]",
"tests/test_population.py::TestPopulationIslands::test_not_evaluated",
"tests/test_population.py::TestPopulationIslands::test_combine",
"tests/test_population.py::TestPopulationIslands::test_combine_nothing",
"tests/test_population.py::TestContest::test_assign_score",
"tests/test_population.py::TestContest::test_generate_n_contests[2-1]",
"tests/test_population.py::TestContest::test_generate_n_contests[5-1]",
"tests/test_population.py::TestContest::test_generate_n_contests[7-1]",
"tests/test_population.py::TestContest::test_generate_n_contests[2-5]",
"tests/test_population.py::TestContest::test_generate_n_contests[5-4]",
"tests/test_population.py::TestContest::test_generate_n_contests[3-3]",
"tests/test_population.py::TestContestPopulation::test_init",
"tests/test_population.py::TestContestPopulationBest::test_no_documented"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-04-07 17:01:19+00:00
|
mit
| 2,557 |
|
goerz__zip_files-5
|
diff --git a/src/zip_files/backend.py b/src/zip_files/backend.py
index 36c0d44..b1c4999 100644
--- a/src/zip_files/backend.py
+++ b/src/zip_files/backend.py
@@ -9,7 +9,7 @@ import random
import re
from pathlib import Path
from string import ascii_letters
-from zipfile import ZipFile
+from zipfile import ZipFile, ZipInfo
import click
@@ -257,12 +257,19 @@ def zip_files(
exclude,
exclude_dotfiles,
relative_to=file.parent,
+ compression=compression,
)
logger.debug("Done")
def _add_to_zip(
- zipfile, file, root_folder, exclude, exclude_dotfiles, relative_to
+ zipfile,
+ file,
+ root_folder,
+ exclude,
+ exclude_dotfiles,
+ relative_to,
+ compression,
):
"""Recursively add the `file` to the (open) `zipfile`."""
logger = logging.getLogger(__name__)
@@ -293,7 +300,9 @@ def _add_to_zip(
else:
raise TypeError("Invalid type for pattern %r" % pattern)
logger.debug("Adding %s to zip as %s", file, filename)
- zipfile.writestr(str(filename), data)
+ zinfo = ZipInfo.from_file(file, arcname=str(filename))
+ zinfo.compress_type = compression
+ zipfile.writestr(zinfo, data)
elif file.is_dir():
directory = file
for file_in_dir in directory.iterdir():
@@ -304,4 +313,5 @@ def _add_to_zip(
exclude,
exclude_dotfiles,
relative_to,
+ compression,
)
|
goerz/zip_files
|
8eda31078c4dc1274b2acb0354942741313f311b
|
diff --git a/tests/test_zip_files.py b/tests/test_zip_files.py
index 82e9744..f204848 100644
--- a/tests/test_zip_files.py
+++ b/tests/test_zip_files.py
@@ -1,9 +1,14 @@
"""Tests for `zip-files` executable."""
import io
+import os
+import stat
+import sys
+import time
from pathlib import Path
from zipfile import ZipFile
+import pytest
from click.testing import CliRunner
from pkg_resources import parse_version
@@ -273,3 +278,31 @@ def test_zip_files_default_include_dotfiles(tmp_path):
zipfile.debug = 3
assert zipfile.testzip() is None
assert set(zipfile.namelist()) == set(expected_files)
+
+
[email protected](
+ sys.platform == 'win32',
+ reason="Windows does not have Unix file permissions",
+)
+def test_zip_files_preserve_executable(tmp_path):
+ """Test that an executable file permission is preserved."""
+ runner = CliRunner()
+ outfile = tmp_path / 'archive.zip'
+ executable = tmp_path / 'executable.sh'
+ with open(executable, "w") as fh:
+ fh.write("#!/usr/bin/bash\n")
+ fh.write('echo "Hello World"\n')
+ os.chmod(executable, stat.S_IXUSR | stat.S_IRUSR)
+ result = runner.invoke(
+ zip_files, ['--debug', '-o', str(outfile), str(executable)]
+ )
+ _check_exit_code(result)
+ with ZipFile(outfile) as zipfile:
+ zipfile.debug = 3
+ assert zipfile.testzip() is None
+ assert set(zipfile.namelist()) == set(["executable.sh"])
+ zip_info = zipfile.getinfo("executable.sh")
+ today = time.localtime()
+ today_ymd = (today.tm_year, today.tm_mon, today.tm_mday)
+ assert zip_info.date_time >= today_ymd
+ assert stat.filemode(zip_info.external_attr >> 16) == '-r-x------'
|
Permissions are not preserved
File permissions, like the "executable" flag are not preserved in the zip file.
|
0.0
|
8eda31078c4dc1274b2acb0354942741313f311b
|
[
"tests/test_zip_files.py::test_zip_files_preserve_executable"
] |
[
"tests/test_zip_files.py::test_valid_version",
"tests/test_zip_files.py::test_zip_files_simple",
"tests/test_zip_files.py::test_zip_files_with_root_folder",
"tests/test_zip_files.py::test_zip_files_to_stdout",
"tests/test_zip_files.py::test_zip_files_auto_root",
"tests/test_zip_files.py::test_zip_files_exclude",
"tests/test_zip_files.py::test_zip_files_excludes",
"tests/test_zip_files.py::test_zip_files_exclude_options",
"tests/test_zip_files.py::test_zip_files_default_include_dotfiles"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-21 05:34:34+00:00
|
bsd-3-clause
| 2,558 |
|
goodmami__wn-173
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31499b6..4a066dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,7 +13,9 @@
* `wn.download()` no longer uses Python features unavailable in 3.7
when recovering from download errors
* `Sense.synset()` now creates a `Synset` properly linked to the same
- `Wordnet` object ([#168])
+ `Wordnet` object ([#157], [#168])
+* `Sense.word()` now creates a `Word` properly linked to the same
+ `Wordnet` object ([#157])
## [v0.9.1]
@@ -585,4 +587,5 @@ abandoned, but this is an entirely new codebase.
[#154]: https://github.com/goodmami/wn/issues/154
[#155]: https://github.com/goodmami/wn/issues/155
[#156]: https://github.com/goodmami/wn/issues/156
+[#157]: https://github.com/goodmami/wn/issues/157
[#168]: https://github.com/goodmami/wn/issues/168
diff --git a/wn/_core.py b/wn/_core.py
index e74b928..0d89f42 100644
--- a/wn/_core.py
+++ b/wn/_core.py
@@ -891,7 +891,7 @@ class Sense(_Relatable):
Word('pwn-spigot-n')
"""
- return word(id=self._entry_id)
+ return self._wordnet.word(id=self._entry_id)
def synset(self) -> Synset:
"""Return the synset of the sense.
|
goodmami/wn
|
ea450b2353aea8249998bcb376eef308ea151f0a
|
diff --git a/tests/secondary_query_test.py b/tests/secondary_query_test.py
index 9b97187..56d91b0 100644
--- a/tests/secondary_query_test.py
+++ b/tests/secondary_query_test.py
@@ -38,6 +38,16 @@ def test_sense_synset():
== wn.synset('test-es-0001-n'))
[email protected]('mini_db')
+def test_sense_issue_157():
+ # https://github.com/goodmami/wn/issues/157
+ sense = wn.sense('test-en-information-n-0001-01')
+ # This test uses non-public members, which is not ideal, but there
+ # is currently no better alternative.
+ assert sense._wordnet is sense.word()._wordnet
+ assert sense._wordnet is sense.synset()._wordnet
+
+
@pytest.mark.usefixtures('mini_db')
def test_sense_examples():
assert wn.sense('test-en-information-n-0001-01').examples() == []
|
If you try to loop through senses first, hypernym_paths() hangs
Hi,
if you try to loop through senses, then try to find hypernym paths, the code hangs. Looping through synsets is fine!
For example, the code below will print the path for the synset in the first loop, but hang in the second loop.
```
##
## MWP
##
import wn
en = wn.Wordnet('omw-en:1.4')
organism = en.synsets(ili='i35563')[0] #beast
for ss in en.synsets(pos='n'):
if ss == organism:
print(ss.hypernym_paths())
for s in en.senses(pos='n'):
ss == s.synset()
if ss == organism:
print(ss.hypernym_paths())
```
|
0.0
|
ea450b2353aea8249998bcb376eef308ea151f0a
|
[
"tests/secondary_query_test.py::test_sense_issue_157"
] |
[
"tests/secondary_query_test.py::test_word_senses",
"tests/secondary_query_test.py::test_word_synsets",
"tests/secondary_query_test.py::test_word_translate",
"tests/secondary_query_test.py::test_sense_word",
"tests/secondary_query_test.py::test_sense_synset",
"tests/secondary_query_test.py::test_sense_examples",
"tests/secondary_query_test.py::test_sense_lexicalized",
"tests/secondary_query_test.py::test_sense_frames",
"tests/secondary_query_test.py::test_sense_frames_issue_156",
"tests/secondary_query_test.py::test_sense_translate",
"tests/secondary_query_test.py::test_synset_senses",
"tests/secondary_query_test.py::test_synset_words",
"tests/secondary_query_test.py::test_synset_lemmas",
"tests/secondary_query_test.py::test_synset_ili",
"tests/secondary_query_test.py::test_synset_definition",
"tests/secondary_query_test.py::test_synset_examples",
"tests/secondary_query_test.py::test_synset_lexicalized",
"tests/secondary_query_test.py::test_synset_translate"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-09-22 04:29:06+00:00
|
mit
| 2,559 |
|
goodmami__wn-174
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4a066dc..e61eab7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@
`Wordnet` object ([#157], [#168])
* `Sense.word()` now creates a `Word` properly linked to the same
`Wordnet` object ([#157])
+* `Synset.relations()` uses the correct relation type for those
+ obtained from expand lexicons ([#169])
## [v0.9.1]
@@ -589,3 +591,4 @@ abandoned, but this is an entirely new codebase.
[#156]: https://github.com/goodmami/wn/issues/156
[#157]: https://github.com/goodmami/wn/issues/157
[#168]: https://github.com/goodmami/wn/issues/168
+[#169]: https://github.com/goodmami/wn/issues/169
diff --git a/wn/_core.py b/wn/_core.py
index 0d89f42..b5c8246 100644
--- a/wn/_core.py
+++ b/wn/_core.py
@@ -693,10 +693,11 @@ class Synset(_Relatable):
# first get relations from the current lexicon(s)
if self._id != NON_ROWID:
- relations = list(get_synset_relations({self._id}, args, lexids))
- targets.extend((row[0], Synset(*row[2:], self._wordnet))
- for row in relations
- if row[5] in lexids)
+ targets.extend(
+ (row[0], Synset(*row[2:], self._wordnet))
+ for row in get_synset_relations({self._id}, args, lexids)
+ if row[5] in lexids
+ )
# then attempt to expand via ILI
if self._ili is not None and self._wordnet and self._wordnet._expanded_ids:
@@ -705,26 +706,31 @@ class Synset(_Relatable):
# get expanded relation
expss = find_synsets(ili=self._ili, lexicon_rowids=expids)
rowids = {rowid for _, _, _, _, rowid in expss} - {self._id, NON_ROWID}
- relations = list(get_synset_relations(rowids, args, expids))
- ilis = {row[4] for row in relations} - {None}
+ relations: Dict[str, Set[str]] = {reltype: set() for reltype in args}
+ for rel_row in get_synset_relations(rowids, args, expids):
+ rel_type, ili = rel_row[0], rel_row[4]
+ if ili is not None:
+ relations[rel_type].add(ili)
# map back to target lexicons
seen = {ss._id for _, ss in targets}
- for row in get_synsets_for_ilis(ilis, lexicon_rowids=lexids):
- if row[-1] not in seen:
- targets.append((row[0], Synset(*row, self._wordnet)))
+ for rel_type, ilis in relations.items():
+ for row in get_synsets_for_ilis(ilis, lexicon_rowids=lexids):
+ if row[-1] not in seen:
+ targets.append((rel_type, Synset(*row, self._wordnet)))
# add empty synsets for ILIs without a target in lexids
- unseen_ilis = ilis - {tgt._ili for _, tgt in targets}
- for rel_row in relations:
- if rel_row[4] in unseen_ilis:
+ seen_ilis = {tgt._ili for _, tgt in targets}
+ for rel_type, ilis in relations.items():
+ unseen_ilis = ilis - seen_ilis
+ for ili in unseen_ilis:
ss = Synset.empty(
id=_INFERRED_SYNSET,
- ili=rel_row[4],
+ ili=ili,
_lexid=self._lexid,
_wordnet=self._wordnet
)
- targets.append((rel_row[0], ss))
+ targets.append((rel_type, ss))
return targets
|
goodmami/wn
|
4d9100f2d94fa71f3224414527aaaf66f65b8c7c
|
diff --git a/tests/relations_test.py b/tests/relations_test.py
index 8a335d3..1295075 100644
--- a/tests/relations_test.py
+++ b/tests/relations_test.py
@@ -109,6 +109,16 @@ def test_extension_relations():
@pytest.mark.usefixtures('mini_db_1_1')
def test_sense_synset_issue_168():
+ # https://github.com/goodmami/wn/issues/168
ja = wn.Wordnet(lexicon='test-ja', expand='')
assert ja.synset('test-ja-0001-n').get_related() == []
assert ja.sense('test-ja-情報-n-0001-01').synset().get_related() == []
+
+
[email protected]('mini_db')
+def test_synset_relations_issue_169():
+ # https://github.com/goodmami/wn/issues/169
+ en = wn.Wordnet('test-en')
+ assert list(en.synset("test-en-0001-n").relations('hyponym')) == ['hyponym']
+ es = wn.Wordnet('test-es', expand='test-en')
+ assert list(es.synset("test-es-0001-n").relations('hyponym')) == ['hyponym']
|
Synset.relations() for some lexicons uses synset id as relation name
Compare the difference in the relation name for the `oewn` versus the `omw-fr` lexicons:
```pycon
>>> import wn
>>> wn.synsets('dog', pos='n', lexicon='oewn')[0].relations('hypernym')
{'hypernym': [Synset('oewn-02085998-n'), Synset('oewn-01320032-n')]}
>>> wn.synsets('chien', pos='n', lexicon='omw-fr')[0].relations('hypernym')
{'omw-fr-10753546-n': [Synset('omw-fr-10753546-n')]}
```
For OEWN, the relation name is `hypernym` while for `omw-fr` it is `omw-fr-10753546-n`. I suspect this is the case for relations obtained from expand lexicons.
|
0.0
|
4d9100f2d94fa71f3224414527aaaf66f65b8c7c
|
[
"tests/relations_test.py::test_synset_relations_issue_169"
] |
[
"tests/relations_test.py::test_word_derived_words",
"tests/relations_test.py::test_synset_hypernyms",
"tests/relations_test.py::test_synset_hypernyms_expand_default",
"tests/relations_test.py::test_synset_hypernyms_expand_empty",
"tests/relations_test.py::test_synset_hypernyms_expand_specified",
"tests/relations_test.py::test_synset_relations",
"tests/relations_test.py::test_sense_get_related",
"tests/relations_test.py::test_sense_relations",
"tests/relations_test.py::test_extension_relations",
"tests/relations_test.py::test_sense_synset_issue_168"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-09-29 17:26:59+00:00
|
mit
| 2,560 |
|
google-research__arxiv-latex-cleaner-29
|
diff --git a/arxiv_latex_cleaner/arxiv_latex_cleaner.py b/arxiv_latex_cleaner/arxiv_latex_cleaner.py
index 96dcd0c..bc12ddc 100644
--- a/arxiv_latex_cleaner/arxiv_latex_cleaner.py
+++ b/arxiv_latex_cleaner/arxiv_latex_cleaner.py
@@ -111,6 +111,36 @@ def _remove_environment(text, environment):
text)
+def _remove_iffalse_block(text):
+ """Removes possibly nested r'\iffalse*\fi' blocks from 'text'."""
+ p = re.compile(r'\\if(\w+)|\\fi')
+ level = -1
+ positions_to_del = []
+ start, end = 0, 0
+ for m in p.finditer(text):
+ if m.group() == r'\iffalse' and level == -1:
+ level += 1
+ start = m.start()
+ elif m.group().startswith(r'\if') and level >= 0:
+ level += 1
+ elif m.group() == r'\fi' and level >= 0:
+ if level == 0:
+ end = m.end()
+ positions_to_del.append((start, end))
+ level -= 1
+ else:
+ pass
+
+ for (start, end) in reversed(positions_to_del):
+ if end < len(text) and text[end].isspace():
+ end_to_del = end + 1
+ else:
+ end_to_del = end
+ text = text[:start] + text[end_to_del:]
+
+ return text
+
+
def _remove_comments_inline(text):
"""Removes the comments from the string 'text'."""
if 'auto-ignore' in text:
@@ -147,6 +177,7 @@ def _remove_comments(content, parameters):
"""Erases all LaTeX comments in the content, and writes it."""
content = [_remove_comments_inline(line) for line in content]
content = _remove_environment(''.join(content), 'comment')
+ content = _remove_iffalse_block(content)
for command in parameters['commands_to_delete']:
content = _remove_command(content, command)
return content
diff --git a/tex/main.tex b/tex/main.tex
index 2e434d5..0a9abac 100644
--- a/tex/main.tex
+++ b/tex/main.tex
@@ -15,6 +15,16 @@ This is a todo command\mytodo{Do this later}
\mytodo{This is a todo command with a nested \textit{command}.
Please remember that up to \texttt{2 levels} of \textit{nesting} are supported.}
+\newif\ifvar
+
+\ifvar
+\iffalse
+\ifvar
+Text
+\fi
+\fi
+\fi
+
\input{figures/figure_included.tex}
% \input{figures/figure_not_included.tex}
diff --git a/tex_arXiv_true/main.tex b/tex_arXiv_true/main.tex
index c3b203f..2df5b95 100644
--- a/tex_arXiv_true/main.tex
+++ b/tex_arXiv_true/main.tex
@@ -9,6 +9,11 @@ This is a percent \%.
This is a todo command
+\newif\ifvar
+
+\ifvar
+\fi
+
\input{figures/figure_included.tex}
\includegraphics{ext_tikz/test1.pdf}
|
google-research/arxiv-latex-cleaner
|
2045634c0b52bad482c9b3a0b507a7add84450e2
|
diff --git a/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py b/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py
index 0a34693..60258f1 100644
--- a/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py
+++ b/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py
@@ -88,6 +88,41 @@ class UnitTests(parameterized.TestCase):
arxiv_latex_cleaner._remove_environment(text_in, 'comment'),
true_output)
+ @parameterized.named_parameters(
+ {
+ 'testcase_name': 'no_iffalse',
+ 'text_in': 'Foo\n',
+ 'true_output': 'Foo\n'
+ }, {
+ 'testcase_name': 'if_not_removed',
+ 'text_in': '\\ifvar\n\\ifvar\nFoo\n\\fi\n\\fi\n',
+ 'true_output': '\\ifvar\n\\ifvar\nFoo\n\\fi\n\\fi\n'
+ }, {
+ 'testcase_name': 'if_removed_with_nested_ifvar',
+ 'text_in': '\\ifvar\n\\iffalse\n\\ifvar\nFoo\n\\fi\n\\fi\n\\fi\n',
+ 'true_output': '\\ifvar\n\\fi\n'
+ }, {
+ 'testcase_name': 'if_removed_with_nested_iffalse',
+ 'text_in': '\\ifvar\n\\iffalse\n\\iffalse\nFoo\n\\fi\n\\fi\n\\fi\n',
+ 'true_output': '\\ifvar\n\\fi\n'
+ }, {
+ 'testcase_name': 'if_removed_eof',
+ 'text_in': '\\iffalse\nFoo\n\\fi',
+ 'true_output': ''
+ }, {
+ 'testcase_name': 'if_removed_space',
+ 'text_in': '\\iffalse\nFoo\n\\fi ',
+ 'true_output': ''
+ }, {
+ 'testcase_name': 'if_removed_backslash',
+ 'text_in': '\\iffalse\nFoo\n\\fi\\end{document}',
+ 'true_output': '\\end{document}'
+ })
+ def test_remove_iffalse_block(self, text_in, true_output):
+ self.assertEqual(
+ arxiv_latex_cleaner._remove_iffalse_block(text_in),
+ true_output)
+
@parameterized.named_parameters(
{
'testcase_name': 'all_pass',
|
Nested \iffalse \fi block comments.
I used \iffalse ... \fi to block comment in my latex document, and used this modification of the _remove_environment command:
```
def _remove_iffalse(text):
"""Removes '\\iffalse *\\fi' from 'text'."""
"""This has problems with nested \\iffalse \\fi statements"""
return re.sub(
r'\\iffalse[\s\S]*?\\fi',
'', text)
```
However, this runs incorrectly on:
```
\iffalse
A
\iffalse
B
\fi
C
\fi
```
Which in latex outputs nothing, but with the _remove_iffalse code above outputs:
```
C
\fi
```
(I had one such nested comment in my document, because of commenting out a subsection of a section that was later commented out in its entirety.)
A similar problem does not exist for \begin{comment} \end{comment}, because
```
\begin{comment}
A
\begin{comment}
B
\end{comment}
C
\end{comment}
```
Does not compile in Latex.
|
0.0
|
2045634c0b52bad482c9b3a0b507a7add84450e2
|
[
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_not_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_backslash",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_eof",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_space",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_with_nested_iffalse",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_with_nested_ifvar",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_no_iffalse"
] |
[
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_keep_pattern_all_pass",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_keep_pattern_not_all_pass",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_not_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_no_command",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_auto_ignore",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_comment",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_comment_inline",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_no_comment",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_percent",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_environment_environment_not_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_environment_environment_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_environment_no_environment",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_pattern_all_pass",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_pattern_not_all_pass",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_tikzpictures_no_tikz",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_tikzpictures_tikz_match",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_tikzpictures_tikz_no_match"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-08-01 11:02:07+00:00
|
apache-2.0
| 2,561 |
|
google-research__arxiv-latex-cleaner-96
|
diff --git a/arxiv_latex_cleaner/arxiv_latex_cleaner.py b/arxiv_latex_cleaner/arxiv_latex_cleaner.py
index 2b83c54..296e698 100644
--- a/arxiv_latex_cleaner/arxiv_latex_cleaner.py
+++ b/arxiv_latex_cleaner/arxiv_latex_cleaner.py
@@ -212,8 +212,10 @@ def _remove_iffalse_block(text):
def _remove_comments_inline(text):
"""Removes the comments from the string 'text' and ignores % inside \\url{}."""
- if 'auto-ignore' in text:
- return text
+ auto_ignore_pattern = r'(%\s*auto-ignore).*'
+ if regex.search(auto_ignore_pattern, text):
+ return regex.sub(auto_ignore_pattern, r'\1', text)
+
if text.lstrip(' ').lstrip('\t').startswith('%'):
return ''
|
google-research/arxiv-latex-cleaner
|
b7a0b3c3d5fe488ac02ab2e745a059d1ab641d7d
|
diff --git a/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py b/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py
index 8540e75..34e9488 100644
--- a/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py
+++ b/arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py
@@ -278,6 +278,16 @@ class UnitTests(parameterized.TestCase):
'line_in': '%auto-ignore\n',
'true_output': '%auto-ignore\n',
},
+ {
+ 'testcase_name': 'auto_ignore_middle',
+ 'line_in': 'Foo % auto-ignore Comment\n',
+ 'true_output': 'Foo % auto-ignore\n',
+ },
+ {
+ 'testcase_name': 'auto_ignore_text_with_comment',
+ 'line_in': 'Foo auto-ignore % Comment\n',
+ 'true_output': 'Foo auto-ignore %\n',
+ },
{
'testcase_name': 'percent',
'line_in': r'100\% accurate\n',
|
[Unexpected Behavior] Comments Not Removed on Lines with "auto-ignore"
While fixing issue #91, I discovered that comments in lines containing the word `auto-ignore` are not being removed as expected. This behavior is not documented in either the README or the help message, which may lead to unexpected outcomes for users.
I suppose there is a specific reason for this behavior as it is also being tested 🤔
## Example
### Input:
```latex
Foo auto-ignore Bar ... % Top Secret Comment
```
### Output:
```latex
Foo auto-ignore Bar ... % Top Secret Comment
```
### Expected Output:
```latex
Foo auto-ignore Bar ... %
```
|
0.0
|
b7a0b3c3d5fe488ac02ab2e745a059d1ab641d7d
|
[
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_auto_ignore_middle",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_auto_ignore_text_with_comment"
] |
[
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_find_and_replace_patterns_replace_contents",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_keep_pattern_all_pass",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_keep_pattern_not_all_pass",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_merge_args_into_config_args",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_merge_args_into_config_empty",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_no_end_line_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_no_end_line_removed_keep_text",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_not_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_not_removed_keep_text",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_with_end_line_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_with_end_line_removed_keep_text",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_with_optional_arguments_end",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_with_optional_arguments_end_keep_text",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_with_optional_arguments_start",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_command_with_optional_arguments_start_keep_text",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_deeply_nested_command_keep_text",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_nested_command_keep_text",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_no_command",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_command_no_command_keep_text",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_auto_ignore",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_comment",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_comment_inline",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_comment_with_url",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_no_comment",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_percent",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_comments_inline_url_with_percent",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_environment_environment_not_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_environment_environment_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_environment_no_environment",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_commands_not_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_not_removed",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_backslash",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_eof",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_space",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_with_nested_iffalse",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_if_removed_with_nested_ifvar",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_iffalse_block_no_iffalse",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_pattern_all_pass",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_remove_pattern_not_all_pass",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_includesvg_includesvg_match",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_includesvg_includesvg_match_with_options",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_includesvg_includesvg_no_match",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_includesvg_no_includesvg",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_tikzpictures_no_tikz",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_tikzpictures_tikz_match",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_replace_tikzpictures_tikz_no_match",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_filewise_one_parent",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_filewise_three_parent",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_filewise_two_parent",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_filewise_two_parent_strict",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_diffext",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_diffext2",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_nested_diffpath",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_nested_less_specific",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_nested_more_specific",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_nested_substring",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_path_starting_with_dot",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_prefix1",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_prefix2",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_strict_diffext",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_strict_nested_diffpath",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_strict_nested_less_specific",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_strict_nested_more_specific",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_strict_nested_substring1",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_strict_nested_substring2",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_strict_prefix1",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_strong_strict_prefix2",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_diffext",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_diffext2",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_nested_diffpath",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_nested_less_specific",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_nested_more_specific",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_nested_substring",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_path_starting_with_dot",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_prefix1",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_prefix2",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_strict_diffext",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_strict_nested_diffpath",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_strict_nested_less_specific",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_strict_nested_more_specific",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_strict_nested_substring1",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_strict_nested_substring2",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_strict_prefix1",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::UnitTests::test_search_reference_weak_strict_prefix2",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::IntegrationTests::test_complete_from_dir",
"arxiv_latex_cleaner/tests/arxiv_latex_cleaner_test.py::IntegrationTests::test_complete_from_zip"
] |
{
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-03-25 05:45:28+00:00
|
apache-2.0
| 2,562 |
|
google__GiftStick-137
|
diff --git a/auto_forensicate/recipes/disk.py b/auto_forensicate/recipes/disk.py
index 1e09f3f..79d47e4 100644
--- a/auto_forensicate/recipes/disk.py
+++ b/auto_forensicate/recipes/disk.py
@@ -133,7 +133,9 @@ class DiskArtifact(base.BaseArtifact):
code = self._ddprocess.returncode
error = self._ddprocess.stderr.read()
if code > 0:
- raise errors.RecipeException('Command dcfldd returned non-zero exit status {0:d}, with error: "{1:s}"'.format(code, error.decode()))
+ raise errors.RecipeException(
+ 'Command dcfldd returned non-zero exit status {0:d}, '
+ 'with error: "{1:s}"'.format(code, error.decode()))
return error
def GetDescription(self):
@@ -142,7 +144,7 @@ class DiskArtifact(base.BaseArtifact):
Returns:
str: the description
"""
- return 'Name: {0:s} (Size: {1:d})'.format(self.name, self.size)
+ description = 'Name: {0:s} (Size: {1:d})'.format(self.name, self.size)
if self.mounted:
description = '(WARNING: disk has a mounted partition) ' + description
return description
@@ -281,7 +283,7 @@ class DiskRecipe(base.BaseRecipe):
"""
def __init__(self, name, options=None):
- """TODO"""
+ """Class for a disks acquisition Recipe"""
self.use_dcfldd = True
super().__init__(name, options=options)
@@ -306,7 +308,9 @@ class DiskRecipe(base.BaseRecipe):
for mac_disk in macdisk.WholeDisks():
disk_name = mac_disk.deviceidentifier
disk_size = mac_disk.totalsize
- disk = MacDiskArtifact(os.path.join('/dev', disk_name), disk_size, use_dcfldd=self.use_dcfldd)
+ disk = MacDiskArtifact(
+ os.path.join('/dev', disk_name), disk_size,
+ use_dcfldd=self.use_dcfldd)
disk_list.append(disk)
return disk_list
@@ -352,8 +356,7 @@ class DiskRecipe(base.BaseRecipe):
return disk_list
def _ListDisks(self, all_devices=False, names=None):
- """Between all disks connected to the machine, selects the one we want to
- acquire.
+ """Builds a list of DiskArtifact object to acquire.
Args:
all_devices(bool): whether to also list devices that aren't internal to
@@ -395,8 +398,7 @@ class DiskRecipe(base.BaseRecipe):
return lsblk_artifact
def _GetDiskInfoArtifact(self, disk):
- """Returns an StringArtifact containing information about a disk being
- copied.
+ """Returns an StringArtifact containing info about a disk being copied.
Args:
disk(DiskArtifact): the disk object to get info from.
@@ -443,13 +445,12 @@ class DiskRecipe(base.BaseRecipe):
else:
disks_to_collect = self._ListDisks()
-
- if not disks_to_collect:
- raise errors.RecipeException('No disk to collect')
-
disk_list_artifact = self._GetListDisksArtifact()
artifacts.append(disk_list_artifact)
+ if not disks_to_collect:
+ self._logger.warn('No disk to collect')
+
for disk in disks_to_collect:
disk_info_artifact = self._GetDiskInfoArtifact(disk)
|
google/GiftStick
|
342b0e2b09b88e8cf9e5b6b3b551535bf227a7e8
|
diff --git a/tests/disk_tests.py b/tests/disk_tests.py
index 2e1acd0..ad5d274 100644
--- a/tests/disk_tests.py
+++ b/tests/disk_tests.py
@@ -199,8 +199,11 @@ class DiskRecipeTests(unittest.TestCase):
patched_listdisk.return_value = []
recipe = disk.DiskRecipe('Disk')
recipe._platform = 'linux'
- with self.assertRaises(errors.RecipeException):
- recipe.GetArtifacts()
+ artifacts = recipe.GetArtifacts()
+ self.assertEqual(len(artifacts), 1)
+
+ artifact = artifacts[0]
+ self.assertEqual(artifact.name, 'lsblk.txt')
def testGetArtifacts(self):
disk_name = 'sdx'
|
Try to upload the "disk list" artifact before failing if no disk is detected
In https://github.com/google/GiftStick/blob/main/auto_forensicate/recipes/disk.py we raise if no "acquire-able" disk is detected, before trying to upload the list of all disks
|
0.0
|
342b0e2b09b88e8cf9e5b6b3b551535bf227a7e8
|
[
"tests/disk_tests.py::DiskRecipeTests::testGetArtifactsZeroDisk"
] |
[
"tests/disk_tests.py::DiskArtifactTests::testGenerateDDCommand",
"tests/disk_tests.py::DiskArtifactTests::testInstantiate",
"tests/disk_tests.py::LinuxDiskArtifactTests::testGetDescription",
"tests/disk_tests.py::LinuxDiskArtifactTests::testIsFloppy",
"tests/disk_tests.py::LinuxDiskArtifactTests::testIsUsb",
"tests/disk_tests.py::LinuxDiskArtifactTests::testProbablyADisk",
"tests/disk_tests.py::DiskRecipeTests::testGetArtifacts",
"tests/disk_tests.py::DiskRecipeTests::testIsMounted",
"tests/disk_tests.py::DiskRecipeTests::testListAllDisks",
"tests/disk_tests.py::DiskRecipeTests::testListDisksWithNames",
"tests/disk_tests.py::DiskRecipeTests::testListDisksZero",
"tests/disk_tests.py::MacDiskArtifactTests::testGetDescription",
"tests/disk_tests.py::MacDiskArtifactTests::testProbablyADisk"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-16 15:36:38+00:00
|
apache-2.0
| 2,563 |
|
google__capirca-266
|
diff --git a/capirca/lib/juniper.py b/capirca/lib/juniper.py
index c0a36ad..875f782 100644
--- a/capirca/lib/juniper.py
+++ b/capirca/lib/juniper.py
@@ -163,7 +163,8 @@ class Term(aclgenerator.Term):
'daddr': 'ip-destination-address',
'protocol': 'ip-protocol',
'protocol-except': 'ip-protocol-except',
- 'tcp-est': 'tcp-flags "(ack|rst)"'}}
+ 'tcp-est': 'tcp-flags "(ack|rst)"'}
+ }
def __init__(self, term, term_type, enable_dsmo, noverbose):
super().__init__(term)
@@ -857,7 +858,7 @@ class Juniper(aclgenerator.ACLGenerator):
_PLATFORM = 'juniper'
_DEFAULT_PROTOCOL = 'ip'
- _SUPPORTED_AF = set(('inet', 'inet6', 'bridge'))
+ _SUPPORTED_AF = frozenset(('inet', 'inet6', 'bridge', 'mixed'))
_TERM = Term
SUFFIX = '.jcl'
@@ -942,42 +943,57 @@ class Juniper(aclgenerator.ACLGenerator):
if len(filter_options) > 1:
filter_type = filter_options[1]
- term_names = set()
- new_terms = []
- for term in terms:
+ if filter_type == 'mixed':
+ filter_types_to_process = ['inet', 'inet6']
+ else:
+ filter_types_to_process = [filter_type]
- # if inactive is set, deactivate the term and remove the option.
- if 'inactive' in term.option:
- term.inactive = True
- term.option.remove('inactive')
-
- term.name = self.FixTermLength(term.name)
-
- if term.name in term_names:
- raise JuniperDuplicateTermError('You have multiple terms named: %s' %
- term.name)
- term_names.add(term.name)
-
- term = self.FixHighPorts(term, af=filter_type)
- if not term:
- continue
-
- if term.expiration:
- if term.expiration <= exp_info_date:
- logging.info('INFO: Term %s in policy %s expires '
- 'in less than two weeks.', term.name, filter_name)
- if term.expiration <= current_date:
- logging.warning('WARNING: Term %s in policy %s is expired and '
- 'will not be rendered.', term.name, filter_name)
- continue
- if 'is-fragment' in term.option and filter_type == 'inet6':
- raise JuniperFragmentInV6Error('The term %s uses "is-fragment" but '
- 'is a v6 policy.' % term.name)
+ for filter_type in filter_types_to_process:
+
+ filter_name_suffix = ''
+ # If mixed filter_type, will append 4 or 6 to the filter name
+ if len(filter_types_to_process) > 1:
+ if filter_type == 'inet':
+ filter_name_suffix = '4'
+ if filter_type == 'inet6':
+ filter_name_suffix = '6'
+
+ term_names = set()
+ new_terms = []
+ for term in terms:
- new_terms.append(self._TERM(term, filter_type, enable_dsmo, noverbose))
+ # if inactive is set, deactivate the term and remove the option.
+ if 'inactive' in term.option:
+ term.inactive = True
+ term.option.remove('inactive')
+
+ term.name = self.FixTermLength(term.name)
+
+ if term.name in term_names:
+ raise JuniperDuplicateTermError('You have multiple terms named: %s' %
+ term.name)
+ term_names.add(term.name)
+
+ term = self.FixHighPorts(term, af=filter_type)
+ if not term:
+ continue
- self.juniper_policies.append((header, filter_name, filter_type,
- interface_specific, new_terms))
+ if term.expiration:
+ if term.expiration <= exp_info_date:
+ logging.info('INFO: Term %s in policy %s expires '
+ 'in less than two weeks.', term.name, filter_name)
+ if term.expiration <= current_date:
+ logging.warning('WARNING: Term %s in policy %s is expired and '
+ 'will not be rendered.', term.name, filter_name)
+ continue
+ if 'is-fragment' in term.option and filter_type == 'inet6':
+ raise JuniperFragmentInV6Error('The term %s uses "is-fragment" but '
+ 'is a v6 policy.' % term.name)
+
+ new_terms.append(self._TERM(term, filter_type, enable_dsmo, noverbose))
+
+ self.juniper_policies.append((header, filter_name + filter_name_suffix, filter_type,
+ interface_specific, new_terms))
def __str__(self):
config = Config()
|
google/capirca
|
2b1c3519255fa0940a464521197d80187b355570
|
diff --git a/tests/lib/juniper_test.py b/tests/lib/juniper_test.py
index 2846360..95557c3 100644
--- a/tests/lib/juniper_test.py
+++ b/tests/lib/juniper_test.py
@@ -20,6 +20,7 @@ from absl.testing import absltest
from unittest import mock
from absl import logging
+from absl.testing import parameterized
from capirca.lib import aclgenerator
from capirca.lib import juniper
from capirca.lib import nacaddr
@@ -42,6 +43,11 @@ header {
target:: juniper test-filter inet6
}
"""
+GOOD_HEADER_MIXED = """
+header {
+ target:: juniper test-filter mixed
+}
+"""
GOOD_HEADER_BRIDGE = """
header {
target:: juniper test-filter bridge
@@ -533,6 +539,16 @@ term flex-match-term-1 {
}
"""
+MIXED_TESTING_TERM = """
+term good-term {
+ protocol:: tcp
+ source-address:: SOME_HOST
+ destination-port:: SMTP
+ destination-address:: SOME_OTHER_HOST
+ action:: accept
+}
+"""
+
SUPPORTED_TOKENS = frozenset([
'action',
'address',
@@ -645,7 +661,7 @@ SUPPORTED_SUB_TOKENS = {
EXP_INFO = 2
-class JuniperTest(absltest.TestCase):
+class JuniperTest(parameterized.TestCase):
def setUp(self):
super().setUp()
@@ -1533,6 +1549,136 @@ class JuniperTest(absltest.TestCase):
GOOD_HEADER_V6 + BAD_FLEX_MATCH_TERM_4,
self.naming)
+ @parameterized.named_parameters(
+ ('MIXED_TO_V4',
+ [[nacaddr.IPv4('0.0.0.0/1'),
+ nacaddr.IPv6('2001::/33')], [nacaddr.IPv4('192.168.0.0/24')]], [
+ ' term good-term {\n' +
+ ' from {\n' +
+ ' source-address {\n' +
+ ' 0.0.0.0/1;\n' +
+ ' }\n' +
+ ' destination-address {\n' +
+ ' 192.168.0.0/24;\n' +
+ ' }'
+ ], ['2001::/33']),
+ ('V4_TO_MIXED', [
+ [nacaddr.IPv4('192.168.0.0/24')],
+ [nacaddr.IPv4('0.0.0.0/1'),
+ nacaddr.IPv6('2001::/33')],
+ ], [
+ ' term good-term {\n' +
+ ' from {\n' +
+ ' source-address {\n' +
+ ' 192.168.0.0/24;\n' +
+ ' }\n' +
+ ' destination-address {\n' +
+ ' 0.0.0.0/1;\n' +
+ ' }'
+ ], ['2001::/33']),
+ ('MIXED_TO_V6',
+ [[nacaddr.IPv4('0.0.0.0/1'),
+ nacaddr.IPv6('2001::/33')], [nacaddr.IPv6('2201::/48')]], [
+ ' term good-term {\n' +
+ ' from {\n' +
+ ' source-address {\n' +
+ ' 2001::/33;\n' +
+ ' }\n' +
+ ' destination-address {\n' +
+ ' 2201::/48;\n' +
+ ' }'
+ ], ['0.0.0.0/1']),
+ ('V6_TO_MIXED', [[
+ nacaddr.IPv6('2201::/48')
+ ], [nacaddr.IPv4('0.0.0.0/1'),
+ nacaddr.IPv6('2001::/33')]], [
+ ' term good-term {\n' +
+ ' from {\n' +
+ ' source-address {\n' +
+ ' 2201::/48;\n' +
+ ' }\n' +
+ ' destination-address {\n' +
+ ' 2001::/33;\n' +
+ ' }'
+ ], ['0.0.0.0/1']),
+ ('MIXED_TO_MIXED', [[
+ nacaddr.IPv4('0.0.0.0/1'),
+ nacaddr.IPv6('2001::/33')
+ ], [nacaddr.IPv4('192.168.0.0/24'),
+ nacaddr.IPv6('2201::/48')]], [
+ ' term good-term {\n' +
+ ' from {\n' +
+ ' source-address {\n' +
+ ' 0.0.0.0/1;\n' +
+ ' }\n' +
+ ' destination-address {\n' +
+ ' 192.168.0.0/24;\n' +
+ ' }',
+ ' term good-term {\n' +
+ ' from {\n' +
+ ' source-address {\n' +
+ ' 2001::/33;\n' +
+ ' }\n' +
+ ' destination-address {\n' +
+ ' 2201::/48;\n' +
+ ' }'
+ ], []),
+ ('V4_TO_V4', [[nacaddr.IPv4('0.0.0.0/1')],
+ [nacaddr.IPv4('192.168.0.0/24')]], [
+ ' term good-term {\n' +
+ ' from {\n' +
+ ' source-address {\n' +
+ ' 0.0.0.0/1;\n' +
+ ' }\n' +
+ ' destination-address {\n' +
+ ' 192.168.0.0/24;\n' +
+ ' }'
+ ], []),
+ ('V6_TO_V6', [[nacaddr.IPv6('2001::/33')], [nacaddr.IPv6('2201::/48')]], [
+ ' term good-term {\n' +
+ ' from {\n' +
+ ' source-address {\n' +
+ ' 2001::/33;\n' +
+ ' }\n' +
+ ' destination-address {\n' +
+ ' 2201::/48;\n' +
+ ' }'
+ ], []),
+ (
+ 'V4_TO_V6',
+ [[nacaddr.IPv4('0.0.0.0/1')], [nacaddr.IPv6('2201::/48')]],
+ [],
+ ['0.0.0.0/1', '192.168.0.0/24', '2001::/33', '2201::/48'],
+ ),
+ (
+ 'V6_TO_V4',
+ [[nacaddr.IPv6('2001::/33')], [nacaddr.IPv4('192.168.0.0/24')]],
+ [],
+ ['0.0.0.0/1', '192.168.0.0/24', '2001::/33', '2201::/48'],
+ ),
+ (
+ 'PARTLY_UNSPECIFIED',
+ [[nacaddr.IPv6('2001::/33')], [nacaddr.IPv4('192.168.0.0/24')]],
+ ['term good_term_25 '],
+ [
+ '0.0.0.0/1', '192.168.0.0/24', '2001::/33', '2201::/48',
+ 'term good-term-both-icmp-and-icmpv6-'
+ ],
+ ),
+ )
+ def testMixed(self, addresses, expected, notexpected):
+ self.naming.GetNetAddr.side_effect = addresses
+ self.naming.GetServiceByProto.return_value = ['25']
+ jcl = juniper.Juniper(
+ policy.ParsePolicy(
+ GOOD_HEADER_MIXED + MIXED_TESTING_TERM + GOOD_TERM_25, self.naming),
+ EXP_INFO)
+ output = str(jcl)
+ for expect in expected:
+ self.assertIn(expect, output, output)
+ for notexpect in notexpected:
+ self.assertNotIn(notexpect, output, output)
+
if __name__ == '__main__':
absltest.main()
|
Support multiple targets per header
Based on https://github.com/google/capirca/wiki/Policy-format#header-section I was under the impression that a header could have multiple targets, for example:
```
header {
target:: juniper testpol4 inet
target:: juniper testpol6 inet6
}
term default {
comment:: "test"
action:: deny
}
```
But running that only outputs:
```
firewall {
family inet {
/*
** $Id:$
** $Date:$
** $Revision:$
**
*/
replace: filter testpol4 {
interface-specific;
/*
** test
*/
term default {
then {
discard;
}
}
}
}
}
```
While I would have expected both inet and inet6 filters to be generated.
I'm wondering if it's a regression, bug or was just never supported, but it would be nice to keep policy files as lean as possible.
The workaround is to do:
```
header {
target:: juniper testpol4 inet
}
#include 'testpol.inc'
header {
target:: juniper testpol6 inet6
}
#include 'testpol.inc'
```
Which is more complex and creates clutter.
What do you think?
Thanks.
|
0.0
|
2b1c3519255fa0940a464521197d80187b355570
|
[
"tests/lib/juniper_test.py::JuniperTest::testMixedMIXED_TO_MIXED",
"tests/lib/juniper_test.py::JuniperTest::testMixedMIXED_TO_V4",
"tests/lib/juniper_test.py::JuniperTest::testMixedMIXED_TO_V6",
"tests/lib/juniper_test.py::JuniperTest::testMixedPARTLY_UNSPECIFIED",
"tests/lib/juniper_test.py::JuniperTest::testMixedV4_TO_MIXED",
"tests/lib/juniper_test.py::JuniperTest::testMixedV4_TO_V4",
"tests/lib/juniper_test.py::JuniperTest::testMixedV4_TO_V6",
"tests/lib/juniper_test.py::JuniperTest::testMixedV6_TO_MIXED",
"tests/lib/juniper_test.py::JuniperTest::testMixedV6_TO_V4",
"tests/lib/juniper_test.py::JuniperTest::testMixedV6_TO_V6"
] |
[
"tests/lib/juniper_test.py::JuniperTest::testAddressExclude",
"tests/lib/juniper_test.py::JuniperTest::testArbitraryOptions",
"tests/lib/juniper_test.py::JuniperTest::testBadFilterType",
"tests/lib/juniper_test.py::JuniperTest::testBridgeFilterInetType",
"tests/lib/juniper_test.py::JuniperTest::testBridgeFilterType",
"tests/lib/juniper_test.py::JuniperTest::testBuildTokens",
"tests/lib/juniper_test.py::JuniperTest::testBuildWarningTokens",
"tests/lib/juniper_test.py::JuniperTest::testCommentShrinking",
"tests/lib/juniper_test.py::JuniperTest::testConfigHelper",
"tests/lib/juniper_test.py::JuniperTest::testDefaultDeny",
"tests/lib/juniper_test.py::JuniperTest::testDscpByte",
"tests/lib/juniper_test.py::JuniperTest::testDscpClass",
"tests/lib/juniper_test.py::JuniperTest::testDscpIPv6",
"tests/lib/juniper_test.py::JuniperTest::testDsmo",
"tests/lib/juniper_test.py::JuniperTest::testDsmoExclude",
"tests/lib/juniper_test.py::JuniperTest::testDsmoJuniperFriendly",
"tests/lib/juniper_test.py::JuniperTest::testEncapsulate",
"tests/lib/juniper_test.py::JuniperTest::testEtherType",
"tests/lib/juniper_test.py::JuniperTest::testExpiredTerm",
"tests/lib/juniper_test.py::JuniperTest::testExpiringTerm",
"tests/lib/juniper_test.py::JuniperTest::testFailEncapsulate",
"tests/lib/juniper_test.py::JuniperTest::testFailFlexibleMatch",
"tests/lib/juniper_test.py::JuniperTest::testFailIsFragmentInV6",
"tests/lib/juniper_test.py::JuniperTest::testFailNextIpMultipleIP",
"tests/lib/juniper_test.py::JuniperTest::testFailNextIpNetworkIP",
"tests/lib/juniper_test.py::JuniperTest::testFlexibleMatch",
"tests/lib/juniper_test.py::JuniperTest::testFlexibleMatchIPv6",
"tests/lib/juniper_test.py::JuniperTest::testForwardingClass",
"tests/lib/juniper_test.py::JuniperTest::testForwardingClassExcept",
"tests/lib/juniper_test.py::JuniperTest::testFragmentOffset",
"tests/lib/juniper_test.py::JuniperTest::testHopLimit",
"tests/lib/juniper_test.py::JuniperTest::testHopLimitInet",
"tests/lib/juniper_test.py::JuniperTest::testHopOptProtocol",
"tests/lib/juniper_test.py::JuniperTest::testIcmpCode",
"tests/lib/juniper_test.py::JuniperTest::testIcmpInet6Mismatch",
"tests/lib/juniper_test.py::JuniperTest::testIcmpType",
"tests/lib/juniper_test.py::JuniperTest::testIcmpv6Except",
"tests/lib/juniper_test.py::JuniperTest::testIcmpv6InetMismatch",
"tests/lib/juniper_test.py::JuniperTest::testInactiveTerm",
"tests/lib/juniper_test.py::JuniperTest::testInet6",
"tests/lib/juniper_test.py::JuniperTest::testInterfaceSpecificHeader",
"tests/lib/juniper_test.py::JuniperTest::testLongPolicer",
"tests/lib/juniper_test.py::JuniperTest::testLossPriority",
"tests/lib/juniper_test.py::JuniperTest::testMinimizePrefixes",
"tests/lib/juniper_test.py::JuniperTest::testMultipleForwardingClass",
"tests/lib/juniper_test.py::JuniperTest::testMultipleForwardingClassExcept",
"tests/lib/juniper_test.py::JuniperTest::testMultiplePrecedence",
"tests/lib/juniper_test.py::JuniperTest::testNextIp",
"tests/lib/juniper_test.py::JuniperTest::testNextIpFormat",
"tests/lib/juniper_test.py::JuniperTest::testNextIpv6",
"tests/lib/juniper_test.py::JuniperTest::testNoMatchReversal",
"tests/lib/juniper_test.py::JuniperTest::testNoVerboseV4",
"tests/lib/juniper_test.py::JuniperTest::testNoVerboseV6",
"tests/lib/juniper_test.py::JuniperTest::testNonTcpWithTcpEstablished",
"tests/lib/juniper_test.py::JuniperTest::testNotInterfaceSpecificHeader",
"tests/lib/juniper_test.py::JuniperTest::testOptions",
"tests/lib/juniper_test.py::JuniperTest::testOwnerTerm",
"tests/lib/juniper_test.py::JuniperTest::testPrecedence",
"tests/lib/juniper_test.py::JuniperTest::testPrefixList",
"tests/lib/juniper_test.py::JuniperTest::testPrefixListExcept",
"tests/lib/juniper_test.py::JuniperTest::testPrefixListMixed",
"tests/lib/juniper_test.py::JuniperTest::testProtocolCase",
"tests/lib/juniper_test.py::JuniperTest::testProtocolExcept",
"tests/lib/juniper_test.py::JuniperTest::testRoutingInstance",
"tests/lib/juniper_test.py::JuniperTest::testSimplifiedThenStatement",
"tests/lib/juniper_test.py::JuniperTest::testSimplifiedThenStatementWithSingleAction",
"tests/lib/juniper_test.py::JuniperTest::testSimplifiedThenStatementWithSingleActionDiscardIPv4",
"tests/lib/juniper_test.py::JuniperTest::testSimplifiedThenStatementWithSingleActionDiscardIPv6",
"tests/lib/juniper_test.py::JuniperTest::testSimplifiedThenStatementWithSingleActionRejectIPv6",
"tests/lib/juniper_test.py::JuniperTest::testTTL",
"tests/lib/juniper_test.py::JuniperTest::testTTLInet6",
"tests/lib/juniper_test.py::JuniperTest::testTcpEstablished",
"tests/lib/juniper_test.py::JuniperTest::testTermAndFilterName",
"tests/lib/juniper_test.py::JuniperTest::testTermTypeIndexKeys",
"tests/lib/juniper_test.py::JuniperTest::testTrafficClassCount",
"tests/lib/juniper_test.py::JuniperTest::testTrafficType",
"tests/lib/juniper_test.py::JuniperTest::testVerbatimTerm"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-04-21 13:15:37+00:00
|
apache-2.0
| 2,564 |
|
google__cyanobyte-128
|
diff --git a/cloudbuild-deploy.yaml b/cloudbuild-deploy.yaml
index 83f0570..dbb30dd 100644
--- a/cloudbuild-deploy.yaml
+++ b/cloudbuild-deploy.yaml
@@ -16,6 +16,28 @@ steps:
args: ['-c', 'wget -O- https://github.com/gohugoio/hugo/releases/download/v${_HUGO}/hugo_extended_${_HUGO}_Linux-64bit.tar.gz | tar zx']
id: Install Hugo manually
+- name: docker.io/library/python:3.7
+ entrypoint: python3
+ id: Generate Hugo-compatible Markdown for our peripherals
+ args:
+ - 'src/codegen.py'
+ - '-t'
+ - 'templates/doc.md'
+ - '-o'
+ - './docs/content/docs/Reference/Peripheral Docs'
+ - '-i'
+ - 'peripherals/ADS1015.yaml'
+ - '-i'
+ - 'peripherals/BMP280.yaml'
+ - '-i'
+ - 'peripherals/LSM303D.yaml'
+ - '-i'
+ - 'peripherals/MCP4725.yaml'
+ - '-i'
+ - 'peripherals/MCP9808.yaml'
+ - '-i'
+ - 'peripherals/TCS3472.yaml'
+
- name: gcr.io/cloud-builders/git
entrypoint: bash
id: Move up content directory
diff --git a/docs/content/docs/Reference/Peripheral Docs/_index.md b/docs/content/docs/Reference/Peripheral Docs/_index.md
new file mode 100644
index 0000000..b1d2fe4
--- /dev/null
+++ b/docs/content/docs/Reference/Peripheral Docs/_index.md
@@ -0,0 +1,7 @@
+---
+title: "Auto-generated reference docs"
+linkTitle: "Auto-generated reference docs"
+weight: 1
+description: >
+ Hosted peripherals
+---
diff --git a/templates/doc.md b/templates/doc.md
index b27738e..4c880b6 100644
--- a/templates/doc.md
+++ b/templates/doc.md
@@ -1,5 +1,10 @@
-# {{ info.title }}
-{{ info.description }}
+---
+title: "{{info.title}}"
+linkTitle: "{{info.title}}"
+weight: 4
+description: >
+ {{info.description}}
+---
## Registers
{% for register in registers %}
@@ -17,4 +22,4 @@ _{{ info.title }} version {{ info.version }}_
_Based on Cyanobyte spec version {{cyanobyte}}_
-_Generated from Cyanobyte Codegen version {{ version }}_
\ No newline at end of file
+_Generated from Cyanobyte Codegen version {{ version }}_
|
google/cyanobyte
|
429e255bc41341c9993ca4d9bd7d46a283f05202
|
diff --git a/test/sampleData/markdown/ADS1015.md b/test/sampleData/markdown/ADS1015.md
index b188fd7..eb84995 100644
--- a/test/sampleData/markdown/ADS1015.md
+++ b/test/sampleData/markdown/ADS1015.md
@@ -1,5 +1,10 @@
-# ADS1015
-Texas Instruments Analog-Digital Converter
+---
+title: "ADS1015"
+linkTitle: "ADS1015"
+weight: 4
+description: >
+ Texas Instruments Analog-Digital Converter
+---
## Registers
diff --git a/test/sampleData/markdown/BMP280.md b/test/sampleData/markdown/BMP280.md
index 000fa87..85b7389 100644
--- a/test/sampleData/markdown/BMP280.md
+++ b/test/sampleData/markdown/BMP280.md
@@ -1,5 +1,10 @@
-# BMP280
-Bosch Digital Pressure Sensor
+---
+title: "BMP280"
+linkTitle: "BMP280"
+weight: 4
+description: >
+ Bosch Digital Pressure Sensor
+---
## Registers
diff --git a/test/sampleData/markdown/LSM303D.md b/test/sampleData/markdown/LSM303D.md
index 8f7b201..67711b9 100644
--- a/test/sampleData/markdown/LSM303D.md
+++ b/test/sampleData/markdown/LSM303D.md
@@ -1,5 +1,10 @@
-# LSM303D
-STMicroelectronics accelerometer and magnetometer
+---
+title: "LSM303D"
+linkTitle: "LSM303D"
+weight: 4
+description: >
+ STMicroelectronics accelerometer and magnetometer
+---
## Registers
diff --git a/test/sampleData/markdown/MCP4725.md b/test/sampleData/markdown/MCP4725.md
index d4bbc26..2c9f700 100644
--- a/test/sampleData/markdown/MCP4725.md
+++ b/test/sampleData/markdown/MCP4725.md
@@ -1,5 +1,10 @@
-# MCP4725
-Microchip 4725 Digital-to-Analog Converter
+---
+title: "MCP4725"
+linkTitle: "MCP4725"
+weight: 4
+description: >
+ Microchip 4725 Digital-to-Analog Converter
+---
## Registers
diff --git a/test/sampleData/markdown/MCP9808.md b/test/sampleData/markdown/MCP9808.md
index f923450..6d879e1 100644
--- a/test/sampleData/markdown/MCP9808.md
+++ b/test/sampleData/markdown/MCP9808.md
@@ -1,5 +1,10 @@
-# MCP9808
-This is a test description
+---
+title: "MCP9808"
+linkTitle: "MCP9808"
+weight: 4
+description: >
+ This is a test description
+---
## Registers
diff --git a/test/sampleData/markdown/TCS3472.md b/test/sampleData/markdown/TCS3472.md
index 26907e5..1d80532 100644
--- a/test/sampleData/markdown/TCS3472.md
+++ b/test/sampleData/markdown/TCS3472.md
@@ -1,5 +1,10 @@
-# TCS3472
-Color Light-to-Digital Converter with IR Filter
+---
+title: "TCS3472"
+linkTitle: "TCS3472"
+weight: 4
+description: >
+ Color Light-to-Digital Converter with IR Filter
+---
## Registers
|
Add doc generation from markdown template
|
0.0
|
429e255bc41341c9993ca4d9bd7d46a283f05202
|
[
"test/test_codegen.py::TestCodegen::test_Markdown"
] |
[
"test/test_codegen.py::TestCodegen::test_Arduino",
"test/test_codegen.py::TestCodegen::test_Kubos",
"test/test_codegen.py::TestCodegen::test_RaspberryPi"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-03-04 21:42:32+00:00
|
apache-2.0
| 2,565 |
|
google__docker-explorer-42
|
diff --git a/docker_explorer/de.py b/docker_explorer/de.py
index 705287a..4817867 100644
--- a/docker_explorer/de.py
+++ b/docker_explorer/de.py
@@ -52,11 +52,8 @@ class DockerExplorer(object):
"""
self.docker_directory = docker_path
if not os.path.isdir(self.docker_directory):
- err_message = (
- '{0:s} is not a Docker directory\n'
- 'Please specify the Docker\'s directory path.\n'
- 'hint: de.py -r /var/lib/docker').format(self.docker_directory)
- raise errors.BadStorageException(err_message)
+ msg = '{0:s} is not a Docker directory'.format(self.docker_directory)
+ raise errors.BadStorageException(msg)
self.containers_directory = os.path.join(
self.docker_directory, 'containers')
@@ -156,14 +153,23 @@ class DockerExplorer(object):
Returns:
list(Container): the list of Container objects.
+
+ Raises:
+ errors.BadStorageException: If required files or directories are not found
+ in the provided Docker directory.
"""
+ if not os.path.isdir(self.containers_directory):
+ raise errors.BadStorageException(
+ 'Containers directory {0} does not exist'.format(
+ self.containers_directory))
container_ids_list = os.listdir(self.containers_directory)
if not container_ids_list:
- print('Couldn\'t find any container configuration file (\'{0:s}\'). '
- 'Make sure the docker repository ({1:s}) is correct. '
+ print('Could not find container configuration files ({0:s}) in {1:s}.\n'
+ 'Make sure the docker directory ({2:s}) is correct.\n'
'If it is correct, you might want to run this script'
- ' with higher privileges.').format(
- self.container_config_filename, self.docker_directory)
+ ' with higher privileges.'.format(
+ self.container_config_filename, self.containers_directory,
+ self.docker_directory))
return [self.GetContainer(cid) for cid in container_ids_list]
def GetContainersList(self, only_running=False):
@@ -246,6 +252,10 @@ class DockerExplorer(object):
Returns:
str: human readable list of images in local Docker repositories.
+
+ Raises:
+ errors.BadStorageException: If required files or directories are not found
+ in the provided Docker directory.
"""
result_string = ''
repositories = []
@@ -253,6 +263,9 @@ class DockerExplorer(object):
repositories = [os.path.join(self.docker_directory, 'repositories-aufs')]
else:
image_path = os.path.join(self.docker_directory, 'image')
+ if not os.path.isdir(image_path):
+ raise errors.BadStorageException(
+ 'Expected image directory {0} does not exist.'.format(image_path))
for storage_method in os.listdir(image_path):
repositories_file_path = os.path.join(
image_path, storage_method, 'repositories.json')
@@ -301,4 +314,9 @@ class DockerExplorer(object):
if __name__ == '__main__':
- DockerExplorer().Main()
+ try:
+ DockerExplorer().Main()
+ except errors.BadStorageException as exc:
+ print('ERROR: {0}\n'.format(exc.message))
+ print('Please specify a proper Docker directory path.\n'
+ ' hint: de.py -r /var/lib/docker')
diff --git a/docker_explorer/lib/container.py b/docker_explorer/lib/container.py
index 5f926e1..4d97bc7 100644
--- a/docker_explorer/lib/container.py
+++ b/docker_explorer/lib/container.py
@@ -81,9 +81,17 @@ class Container(object):
container_info_json_path = os.path.join(
self.docker_directory, 'containers', container_id,
self.container_config_filename)
+
+ if not os.path.isfile(container_info_json_path):
+ raise errors.BadContainerException(
+ 'Unable to find container configuration file {0}. \n'
+ 'Make sure you are providing a Docker directory (hint: -r).'.format(
+ container_info_json_path)
+ )
with open(container_info_json_path) as container_info_json_file:
container_info_dict = json.load(container_info_json_file)
+
if container_info_dict is None:
raise errors.BadContainerException(
'Could not load container configuration file {0}'.format(
|
google/docker-explorer
|
9a1de78c80d260a3cc55b01e318696cd682826a5
|
diff --git a/tests.py b/tests.py
index 6ce7522..c3689d9 100644
--- a/tests.py
+++ b/tests.py
@@ -80,10 +80,7 @@ class TestDEMain(unittest.TestCase):
de_object.docker_directory = 'this_dir_shouldnt_exist'
expected_error_message = (
- 'this_dir_shouldnt_exist is not a Docker directory\n'
- 'Please specify the Docker\'s directory path.\n'
- 'hint: de.py -r /var/lib/docker')
-
+ 'this_dir_shouldnt_exist is not a Docker directory')
with self.assertRaises(errors.BadStorageException) as err:
de_object._SetDockerDirectory('this_dir_shouldnt_exist')
self.assertEqual(expected_error_message, err.exception.message)
|
Raise something more explicit when wrong Docker folder is passed
Something along the lines:
```
diff --git a/docker_explorer/lib/container.py b/docker_explorer/lib/container.py
index 5f926e1..5a7df25 100644
--- a/docker_explorer/lib/container.py
+++ b/docker_explorer/lib/container.py
@@ -81,8 +81,14 @@ class Container(object):
container_info_json_path = os.path.join(
self.docker_directory, 'containers', container_id,
self.container_config_filename)
- with open(container_info_json_path) as container_info_json_file:
- container_info_dict = json.load(container_info_json_file)
+ try:
+ with open(container_info_json_path) as container_info_json_file:
+ container_info_dict = json.load(container_info_json_file)
+ except IOError as exception:
+ raise errors.BadContainerException(
+ 'Unable to open configuration file {0} make sure you use the proper docker dir'.format(
+ container_info_json_path)
+ )
if container_info_dict is None:
raise errors.BadContainerException(
```
|
0.0
|
9a1de78c80d260a3cc55b01e318696cd682826a5
|
[
"tests.py::TestDEMain::testDetectStorageFail"
] |
[
"tests.py::UtilsTests::testFormatDatetime",
"tests.py::UtilsTests::testPrettyPrintJSON",
"tests.py::TestDEMain::testParseArguments",
"tests.py::TestAufsStorage::testDetectStorage",
"tests.py::TestAufsStorage::testGetAllContainers",
"tests.py::TestAufsStorage::testGetContainersString",
"tests.py::TestAufsStorage::testGetHistory",
"tests.py::TestAufsStorage::testGetLayerInfo",
"tests.py::TestAufsStorage::testGetOrderedLayers",
"tests.py::TestAufsStorage::testGetRepositoriesString",
"tests.py::TestAufsStorage::testGetRunningContainersList",
"tests.py::TestAufsStorage::testMakeMountCommands",
"tests.py::TestOverlayStorage::testDetectStorage",
"tests.py::TestOverlayStorage::testGetAllContainers",
"tests.py::TestOverlayStorage::testGetContainersString",
"tests.py::TestOverlayStorage::testGetHistory",
"tests.py::TestOverlayStorage::testGetLayerInfo",
"tests.py::TestOverlayStorage::testGetOrderedLayers",
"tests.py::TestOverlayStorage::testGetRepositoriesString",
"tests.py::TestOverlayStorage::testGetRunningContainersList",
"tests.py::TestOverlayStorage::testMakeMountCommands",
"tests.py::TestOverlay2Storage::testDetectStorage",
"tests.py::TestOverlay2Storage::testGetAllContainers",
"tests.py::TestOverlay2Storage::testGetContainersString",
"tests.py::TestOverlay2Storage::testGetHistory",
"tests.py::TestOverlay2Storage::testGetLayerInfo",
"tests.py::TestOverlay2Storage::testGetOrderedLayers",
"tests.py::TestOverlay2Storage::testGetRepositoriesString",
"tests.py::TestOverlay2Storage::testGetRunningContainersList",
"tests.py::TestOverlay2Storage::testMakeMountCommands"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-06-28 15:39:14+00:00
|
apache-2.0
| 2,566 |
|
google__docker-explorer-57
|
diff --git a/docker_explorer/de.py b/docker_explorer/de.py
index d558e9c..286966f 100644
--- a/docker_explorer/de.py
+++ b/docker_explorer/de.py
@@ -257,6 +257,9 @@ class DockerExplorer(object):
container_object.start_timestamp)
container_json['image_name'] = container_object.config_image_name
+ if container_object.mount_id:
+ container_json['mount_id'] = container_object.mount_id
+
result.append(container_json)
return result
|
google/docker-explorer
|
21f304f33e1300d4dd60dff7f52dc734d0c780f9
|
diff --git a/tests.py b/tests.py
index 48fef64..70363c4 100644
--- a/tests.py
+++ b/tests.py
@@ -176,6 +176,8 @@ class TestAufsStorage(DockerTestCase):
'7968321274dc6b6171697c33df7815310468e694ac5be0ec03ff053bb135e768',
'container_id':
'7b02fb3e8a665a63e32b909af5babb7d6ba0b64e10003b2d9534c7d5f2af8966',
+ 'mount_id':
+ 'b16a494082bba0091e572b58ff80af1b7b5d28737a3eedbe01e73cd7f4e01d23',
'start_date': '2017-02-13T16:45:05.785658',
'image_name': 'busybox'}
]
@@ -339,6 +341,8 @@ class TestOverlayStorage(DockerTestCase):
'5b0d59026729b68570d99bc4f3f7c31a2e4f2a5736435641565d93e7c25bd2c3',
'container_id':
'5dc287aa80b460652a5584e80a5c8c1233b0c0691972d75424cf5250b917600a',
+ 'mount_id':
+ '974e2b994f9db74e1ddd6fc546843bc65920e786612a388f25685acf84b3fed1',
'start_date': '2018-01-26T14:55:56.574924',
'image_name': 'busybox:latest'}
]
@@ -494,6 +498,8 @@ class TestOverlay2Storage(DockerTestCase):
'8ac48589692a53a9b8c2d1ceaa6b402665aa7fe667ba51ccc03002300856d8c7',
'container_id':
'8e8b7f23eb7cbd4dfe7e91646ddd0e0f524218e25d50113559f078dfb2690206',
+ 'mount_id':
+ '92fd3b3e7d6101bb701743c9518c45b0d036b898c8a3d7cae84e1a06e6829b53',
'start_date': '2018-05-16T10:51:39.625989',
'image_name': 'busybox'}
]
|
Go from overlayFS ID to container ID
It would be useful to find a way to map an overlayFS ID to the container that actually used it.
e.g. given this path on a server running Docker:
`/mnt/docker/var/lib/docker/overlay2/6688ce711806faead06aae3ff534ab21183a087241d3a890741f0c3b437b179c/diff/var/tmp/malware`
Find out in which container 6688ce711806faead06aae3ff534ab21183a087241d3a890741f0c3b437b179c is being used.
|
0.0
|
21f304f33e1300d4dd60dff7f52dc734d0c780f9
|
[
"tests.py::TestAufsStorage::testGetContainersJson",
"tests.py::TestOverlayStorage::testGetContainersJson",
"tests.py::TestOverlay2Storage::testGetContainersJson"
] |
[
"tests.py::UtilsTests::testFormatDatetime",
"tests.py::UtilsTests::testPrettyPrintJSON",
"tests.py::TestDEMain::testDetectStorageFail",
"tests.py::TestDEMain::testParseArguments",
"tests.py::TestAufsStorage::testDetectStorage",
"tests.py::TestAufsStorage::testGetAllContainers",
"tests.py::TestAufsStorage::testGetFullContainerID",
"tests.py::TestAufsStorage::testGetHistory",
"tests.py::TestAufsStorage::testGetLayerInfo",
"tests.py::TestAufsStorage::testGetOrderedLayers",
"tests.py::TestAufsStorage::testGetRepositoriesString",
"tests.py::TestAufsStorage::testGetRunningContainersList",
"tests.py::TestAufsStorage::testMakeMountCommands",
"tests.py::TestOverlayStorage::testDetectStorage",
"tests.py::TestOverlayStorage::testGetAllContainers",
"tests.py::TestOverlayStorage::testGetFullContainerID",
"tests.py::TestOverlayStorage::testGetHistory",
"tests.py::TestOverlayStorage::testGetLayerInfo",
"tests.py::TestOverlayStorage::testGetOrderedLayers",
"tests.py::TestOverlayStorage::testGetRepositoriesString",
"tests.py::TestOverlayStorage::testGetRunningContainersList",
"tests.py::TestOverlayStorage::testMakeMountCommands",
"tests.py::TestOverlay2Storage::testDetectStorage",
"tests.py::TestOverlay2Storage::testGetAllContainers",
"tests.py::TestOverlay2Storage::testGetFullContainerID",
"tests.py::TestOverlay2Storage::testGetHistory",
"tests.py::TestOverlay2Storage::testGetLayerInfo",
"tests.py::TestOverlay2Storage::testGetOrderedLayers",
"tests.py::TestOverlay2Storage::testGetRepositoriesString",
"tests.py::TestOverlay2Storage::testGetRunningContainersList",
"tests.py::TestOverlay2Storage::testMakeMountCommands"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2018-12-21 15:56:49+00:00
|
apache-2.0
| 2,567 |
|
google__docker-explorer-64
|
diff --git a/docker_explorer/storage.py b/docker_explorer/storage.py
index 390a212..9e84a68 100644
--- a/docker_explorer/storage.py
+++ b/docker_explorer/storage.py
@@ -211,7 +211,7 @@ class OverlayStorage(BaseStorage):
cmd = [
'/bin/mount', '-t', 'overlay', 'overlay', '-o',
- 'ro,lowerdir="{0:s}:{1:s}"'.format(upper_dir, lower_dir), mount_dir]
+ 'ro,lowerdir={0:s}:{1:s}'.format(upper_dir, lower_dir), mount_dir]
return [cmd]
|
google/docker-explorer
|
e6612da9a4db2fb79711343712350099185de098
|
diff --git a/tests.py b/tests.py
index 0b3a425..952778e 100644
--- a/tests.py
+++ b/tests.py
@@ -547,10 +547,10 @@ class TestOverlayStorage(DockerTestCase):
commands = [' '.join(cmd) for cmd in commands]
expected_commands = [(
'/bin/mount -t overlay overlay -o ro,lowerdir='
- '"test_data/docker/overlay/974e2b994f9db74e1ddd6fc546843bc65920e786612'
+ 'test_data/docker/overlay/974e2b994f9db74e1ddd6fc546843bc65920e786612'
'a388f25685acf84b3fed1/upper:'
'test_data/docker/overlay/a94d714512251b0d8a9bfaacb832e0c6cb70f71cb71'
- '976cca7a528a429336aae/root" '
+ '976cca7a528a429336aae/root '
'/mnt')]
self.assertEqual(expected_commands, commands)
@@ -704,10 +704,10 @@ class TestOverlay2Storage(DockerTestCase):
commands = [' '.join(cmd) for cmd in commands]
expected_commands = [(
'/bin/mount -t overlay overlay -o ro,lowerdir='
- '"test_data/docker/overlay2/'
+ 'test_data/docker/overlay2/'
'92fd3b3e7d6101bb701743c9518c45b0d036b898c8a3d7cae84e1a06e6829b53/diff:'
'test_data/docker/overlay2/l/OTFSLJCXWCECIG6FVNGRTWUZ7D:'
- 'test_data/docker/overlay2/l/CH5A7XWSBP2DUPV7V47B7DOOGY" /mnt'
+ 'test_data/docker/overlay2/l/CH5A7XWSBP2DUPV7V47B7DOOGY /mnt'
)]
self.assertEqual(expected_commands, commands)
|
overlay mount error: mount: special device overlay does not exist
> de.py mount 6f51d96cdd2c /root/docker/docker-explorer/mnt
/bin/mount -t overlay overlay -o ro,lowerdir="/var/lib/docker/overlay2/44bbbf57e9be5c160d9addac59b51a83c35d90955b4179ca4d893ae2942ef8e1/diff:/var/lib/docker/overlay2/l/F74KTIZFM3OJPZ44L4Y5OMLQRY:/var/lib/docker/overlay2/l/MULY352PDKNLWPYT22DFGHCJXA:/var/lib/docker/overlay2/l/ZH325HA5PVVFXEPQCWG6VTKIZ3:/var/lib/docker/overlay2/l/HFQVPV3GII75YHNJBJAJBMOMIZ:/var/lib/docker/overlay2/l/BXKFWQ4WPHOZMZHHD6TFT3ITZ7:/var/lib/docker/overlay2/l/KABGVLKHDM2RBUJKGPGWN3X7RU" /root/docker/docker-explorer/mnt
Do you want to mount this container ID: 6f51d96cdd2cff0601c5922917d4a62e593917cd5358d710a344111db1c1e354 on /root/docker/docker-explorer/mnt ?
(ie: run these commands) [Y/n]
Y
**mount: special device overlay does not exist**
OS: CentOS 7.5.1804
Kernel: 3.10.0-862.14.4.el7.x86_64
Docker: 1.13.1
> docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6f51d96cdd2c atmoz/sftp "/entrypoint foo:p..." 4 days ago Up 4 days 0.0.0.0:4444->22/tcp sftp
|
0.0
|
e6612da9a4db2fb79711343712350099185de098
|
[
"tests.py::TestOverlayStorage::testMakeMountCommands",
"tests.py::TestOverlay2Storage::testMakeMountCommands"
] |
[
"tests.py::UtilsTests::testFormatDatetime",
"tests.py::UtilsTests::testPrettyPrintJSON",
"tests.py::TestDEMain::testDetectStorageFail",
"tests.py::TestDEMain::testParseArguments",
"tests.py::TestAufsStorage::testDetectStorage",
"tests.py::TestAufsStorage::testGetAllContainers",
"tests.py::TestAufsStorage::testGetContainersJson",
"tests.py::TestAufsStorage::testGetFullContainerID",
"tests.py::TestAufsStorage::testGetHistory",
"tests.py::TestAufsStorage::testGetLayerInfo",
"tests.py::TestAufsStorage::testGetOrderedLayers",
"tests.py::TestAufsStorage::testGetRepositoriesString",
"tests.py::TestAufsStorage::testGetRunningContainersList",
"tests.py::TestAufsStorage::testMakeMountCommands",
"tests.py::TestAufsV1Storage::testDetectStorage",
"tests.py::TestAufsV1Storage::testGetAllContainers",
"tests.py::TestAufsV1Storage::testGetContainersJson",
"tests.py::TestAufsV1Storage::testGetFullContainerID",
"tests.py::TestAufsV1Storage::testGetHistory",
"tests.py::TestAufsV1Storage::testGetLayerInfo",
"tests.py::TestAufsV1Storage::testGetOrderedLayers",
"tests.py::TestAufsV1Storage::testGetRepositoriesString",
"tests.py::TestAufsV1Storage::testGetRunningContainersList",
"tests.py::TestAufsV1Storage::testMakeMountCommands",
"tests.py::TestOverlayStorage::testDetectStorage",
"tests.py::TestOverlayStorage::testGetAllContainers",
"tests.py::TestOverlayStorage::testGetContainersJson",
"tests.py::TestOverlayStorage::testGetFullContainerID",
"tests.py::TestOverlayStorage::testGetHistory",
"tests.py::TestOverlayStorage::testGetLayerInfo",
"tests.py::TestOverlayStorage::testGetOrderedLayers",
"tests.py::TestOverlayStorage::testGetRepositoriesString",
"tests.py::TestOverlayStorage::testGetRunningContainersList",
"tests.py::TestOverlay2Storage::testDetectStorage",
"tests.py::TestOverlay2Storage::testGetAllContainers",
"tests.py::TestOverlay2Storage::testGetContainersJson",
"tests.py::TestOverlay2Storage::testGetFullContainerID",
"tests.py::TestOverlay2Storage::testGetHistory",
"tests.py::TestOverlay2Storage::testGetLayerInfo",
"tests.py::TestOverlay2Storage::testGetOrderedLayers",
"tests.py::TestOverlay2Storage::testGetRepositoriesString",
"tests.py::TestOverlay2Storage::testGetRunningContainersList"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2019-03-21 15:25:43+00:00
|
apache-2.0
| 2,568 |
|
google__gae-secure-scaffold-python3-14
|
diff --git a/src/securescaffold/views.py b/src/securescaffold/views.py
index b53c0aa..5de1852 100644
--- a/src/securescaffold/views.py
+++ b/src/securescaffold/views.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import urllib.parse
from typing import Optional
import flask
@@ -44,6 +45,17 @@ def best_match(requested_langs: LanguageAccept, supported_langs: list) -> Option
return result
+def add_query_to_url(path: str, qs: str) -> str:
+ """Add query params to a URL path, preserving existing path params."""
+ parsed = urllib.parse.urlsplit(path)
+ old_params = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
+ new_params = urllib.parse.parse_qsl(qs, keep_blank_values=True)
+ query = urllib.parse.urlencode(old_params + new_params)
+ parsed = parsed._replace(query=query)
+
+ return urllib.parse.urlunsplit(parsed)
+
+
def lang_redirect():
"""Redirects the user depending on the Accept-Language header.
@@ -63,4 +75,8 @@ def lang_redirect():
redirect_to = locales_redirect_to.format(locale=locale)
+ if flask.request.query_string:
+ # Preserve query parameters on redirect.
+ redirect_to = add_query_to_url(redirect_to, flask.request.query_string)
+
return flask.redirect(redirect_to)
|
google/gae-secure-scaffold-python3
|
8ec9ffb6895eeb9c99aaa0975231436e86b7abfd
|
diff --git a/src/securescaffold/tests/test_views.py b/src/securescaffold/tests/test_views.py
index 96ab8e0..92b5d4c 100644
--- a/src/securescaffold/tests/test_views.py
+++ b/src/securescaffold/tests/test_views.py
@@ -75,3 +75,18 @@ class RedirectTestCase(unittest.TestCase):
self.assertEqual(response.status_code, 302)
self.assertEqual(response.location, "/intl/en/")
+
+ def test_redirect_with_query(self):
+ client = demo_app.test_client()
+ response = client.get("/", query_string={"foo": "bar"})
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.location, "/intl/en/?foo=bar")
+
+ def test_redirect_with_query_preserves_original_query(self):
+ client = demo_app.test_client()
+ demo_app.config["LOCALES_REDIRECT_TO"] = "/test?baz=qux"
+ response = client.get("/", query_string={"foo": "bar"})
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(response.location, "/test?baz=qux&foo=bar")
|
Preserve query params on redirect
## Issue
Currently, any query string set on the redirect path is not preserved when redirected.
## Behaviour
**Current**: `/?foo=bar` -> `/intl/en/`
**Expected**: `/?foo=bar` -> `/intl/en/?foo=bar`
## Setup
```py
# Follows github.com/google/gae-secure-scaffold-python3/blob/master/examples/language-redirect/main.py
app = securescaffold.create_app(__name__)
app.add_url_rule("/", "lang_redirect", securescaffold.views.lang_redirect)
app.config["LOCALES"] = ["en"]
app.config["LOCALES_REDIRECT_TO"] = "/intl/{locale}/"
```
|
0.0
|
8ec9ffb6895eeb9c99aaa0975231436e86b7abfd
|
[
"src/securescaffold/tests/test_views.py::RedirectTestCase::test_redirect_with_query",
"src/securescaffold/tests/test_views.py::RedirectTestCase::test_redirect_with_query_preserves_original_query"
] |
[
"src/securescaffold/tests/test_views.py::RedirectTestCase::test_default_config_locales",
"src/securescaffold/tests/test_views.py::RedirectTestCase::test_default_config_locales_redirect_to",
"src/securescaffold/tests/test_views.py::RedirectTestCase::test_negotiates_valid_locale"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-02-20 11:38:42+00:00
|
apache-2.0
| 2,569 |
|
google__github-release-retry-15
|
diff --git a/ci/check_headers.py b/ci/check_headers.py
index 4fa435e..507f057 100755
--- a/ci/check_headers.py
+++ b/ci/check_headers.py
@@ -88,7 +88,7 @@ def exclude_filename(f: str):
def go():
fail = False
copyright_pattern = re.compile(
- r"Copyright 20(18|19|20) The github-release-retry Project Authors"
+ r"Copyright 20(18|19|20|21) The github-release-retry Project Authors"
)
for (dirpath, dirnames, filenames) in os.walk(os.curdir):
diff --git a/dictionary.dic b/dictionary.dic
index 82c52d7..4784640 100644
--- a/dictionary.dic
+++ b/dictionary.dic
@@ -24,3 +24,5 @@ dirname
testcase
unprocessable
S106
+endian
+exc
diff --git a/github_release_retry/github_release_retry.py b/github_release_retry/github_release_retry.py
index c54a7a9..22a7dd9 100755
--- a/github_release_retry/github_release_retry.py
+++ b/github_release_retry/github_release_retry.py
@@ -23,6 +23,7 @@ import json
import os
import sys
import time
+import traceback
import typing
from dataclasses import dataclass
from pathlib import Path
@@ -48,6 +49,61 @@ def log(message: str) -> None:
print(message, file=sys.stderr) # noqa: T001
+def log_exception(message: str) -> None:
+ log(message)
+ traceback.print_exc(file=sys.stderr)
+ log("")
+
+
+def log_response(response: requests.Response) -> None:
+ log(f"status_code: {response.status_code}")
+ if response.content:
+ try:
+ content = response.content.decode(encoding="utf-8", errors="ignore")
+ log(f"content: {content}")
+ except Exception: # pylint: disable=broad-except;
+ log(f"content: {response.content!r}")
+ log("")
+
+
+def release_asset_node_id_to_asset_id(node_id: str) -> str:
+ """
+ Extracts and returns the asset id from the given Release Asset |node_id|.
+
+ The "id" returned from the GraphQL v4 API is called the "node_id" in the REST API v3.
+ We can get back to the REST "id" by decoding the "node_id" (it is base64 encoded)
+ and extracting the id number at the end, but this is undocumented and may change.
+
+ :param node_id: The Release Asset node_id.
+ :return: The extracted REST API v3 asset id.
+ """
+ # There is a new format and an old format.
+
+ if node_id.startswith("RA_"):
+ # New format: "RA_[base64 encoded bytes]".
+ # The last four bytes (big-endian, unsigned) of the base64 encoded bytes are the node id.
+
+ # Strip off the "RA_".
+ base64_string = node_id[3:]
+
+ asset_id = str(int.from_bytes(base64.b64decode(base64_string)[-4:], "big"))
+ else:
+ # Old format: just a base64 encoded string.
+ # Once decoded, the format is similar to "012:ReleaseAsset18381577". # noqa: SC100
+ # The asset id part is 18381577.
+ node_id_decoded: str = base64.b64decode(node_id).decode(
+ encoding="utf-8", errors="ignore"
+ )
+ if "ReleaseAsset" not in node_id_decoded:
+ raise AssertionError(
+ f"Unrecognized node_id format: {node_id}. Decoded (base64) string: {node_id_decoded}."
+ )
+
+ asset_id = node_id_decoded.split("ReleaseAsset")[1]
+
+ return asset_id
+
+
@dataclass
class GithubResourceError(DataClassJsonMixin):
resource: Optional[str] = None
@@ -144,7 +200,6 @@ class GithubApi(DataClassJsonMixin):
)
def upload_asset(self, file_path: Path, release: Release) -> requests.Response:
-
if not release.upload_url:
raise AssertionError("Need release object with upload_url.")
@@ -180,12 +235,17 @@ class GithubApi(DataClassJsonMixin):
"""
Returns the asset id.
- :returns the asset id or 0 if the asset was not found.
+ This relies on undocumented behavior; see release_asset_node_id_to_asset_id.
+
+ :returns the asset id or None if the asset was not found.
"""
+ if not release.tag_name:
+ raise AssertionError("Expected tag_name")
+
# We get the asset id via GitHub's v4 GraphQL API, as this seems to be more reliable.
# But most other operations still require using the REST v3 API.
- log(f"Finding asset id of {file_name}.")
+ log(f"Finding asset id using v4 API of {file_name}.")
query = f"""
query {{
@@ -240,23 +300,36 @@ query {{
return None
try:
- node_id = assets[0]["id"]
+ node_id: str = assets[0]["id"]
except KeyError:
raise UnexpectedResponseError(response)
- # The id we get from the GraphQL API is called the "node_id" in the REST API v3.
- # We can get back to the REST id by decoding the node_id (it is base64 encoded)
- # and extracting the number at the end.
- # Once decoded, the node_id is similar to "012:ReleaseAsset18381577". # noqa: SC100
- # The id part is 18381577.
+ return release_asset_node_id_to_asset_id(node_id)
- node_id_decoded: str = base64.b64decode(node_id).decode(
- encoding="utf-8", errors="ignore"
- )
-
- asset_id = node_id_decoded.split("ReleaseAsset")[1]
+ def verify_asset_size_and_state_via_v3_api(
+ self, file_name: str, file_size: int, tag_name: str, release: Optional[Release]
+ ) -> bool:
+ if not release:
+ log("Getting the current release again to check asset status.")
+ response = self.get_release_by_tag(tag_name)
+ if response.status_code != requests.codes.ok:
+ raise UnexpectedResponseError(response)
+ log("Decoding release info.")
+ try:
+ release = Release.from_json(response.content)
+ except json.JSONDecodeError:
+ raise UnexpectedResponseError(response)
- return asset_id
+ if release.assets:
+ for asset in release.assets:
+ if (
+ asset.name == file_name
+ and asset.size == file_size
+ and asset.state == "uploaded"
+ ):
+ log("The asset has the correct size and state. Asset done.\n")
+ return True
+ return False
class MissingTokenError(Exception):
@@ -281,7 +354,7 @@ class ReachedRetryLimitError(Exception):
pass
-def upload_file( # pylint: disable=too-many-branches;
+def upload_file( # pylint: disable=too-many-branches,too-many-nested-blocks,too-many-statements;
g: GithubApi, release: Release, file_path: Path # noqa: VNE001
) -> None:
@@ -292,53 +365,92 @@ def upload_file( # pylint: disable=too-many-branches;
retry_count = 0
wait_time = 2
+ if not release.tag_name:
+ raise AssertionError("Expected tag_name")
+
# Optimization:
- # We don't trust the |release| object; assets that exist on the releases web page might be missing from this object.
- # However, if the asset *does* exist in the |release| object, and has the correct size and state, then we can assume
- # it has already been uploaded without making any further remote API calls.
- if release.assets:
- for asset in release.assets:
- if (
- asset.name == file_path.name
- and asset.size == file_size
- and asset.state == "uploaded"
- ):
- log("The asset has the correct size and state. Asset done.\n")
- return
+ # The v3 API does not always show assets that are in a bad state, but if the asset *does* exist with the correct
+ # size and state, then we can assume the asset was successfully uploaded.
+ # We use the existing |release| object, which means we might be able to skip making any further remote API calls.
+ try:
+ if g.verify_asset_size_and_state_via_v3_api(
+ file_name=file_path.name,
+ file_size=file_size,
+ tag_name=release.tag_name,
+ release=release,
+ ):
+ return
+ except Exception: # pylint: disable=broad-except;
+ log_exception(
+ "Ignoring exception that occurred when trying to check asset status with the v3 API."
+ )
# Only exit the loop if we manage to verify that the asset has the expected size and state, or if we reach the retry
# limit.
while True:
-
- existing_asset_id = g.find_asset_id_by_file_name(file_path.name, release)
- if existing_asset_id:
- log("Asset exists.")
- log("Getting asset info.")
- response = g.get_asset_by_id(existing_asset_id)
- if response.status_code != requests.codes.ok:
- raise UnexpectedResponseError(response)
-
- log("Decoding asset info.")
- try:
- existing_asset = Asset.from_json(response.content)
- except json.JSONDecodeError:
- raise UnexpectedResponseError(response)
-
- if existing_asset.size == file_size and existing_asset.state == "uploaded":
- log("The asset has the correct size and state. Asset done.\n")
+ # We use try-except liberally so that we always at least try to blindly upload the asset (towards the end of the
+ # loop), because this may well succeed and then the asset checking code may also be more likely to succeed on
+ # subsequent iterations.
+
+ # Optimization:
+ # The v3 API does not always show assets that are in a bad state, but if the asset *does* exist with the
+ # correct size and state, then we can assume the asset was successfully uploaded, without relying on
+ # undocumented behavior.
+ # We pass release=None, which forces a fresh fetch of the Release object.
+ try:
+ if g.verify_asset_size_and_state_via_v3_api(
+ file_name=file_path.name,
+ file_size=file_size,
+ tag_name=release.tag_name,
+ release=None,
+ ):
return
+ except Exception: # pylint: disable=broad-except;
+ log_exception(
+ "Ignoring exception that occurred when trying to check asset status with the v3 API."
+ )
- log('The asset looks bad (wrong size or state was not "uploaded").')
+ # We now try to get the asset details via the v4 API.
+ # This allows us to delete the asset if it is in a bad state, but relies on undocumented behavior.
+ try:
+ existing_asset_id = g.find_asset_id_by_file_name(file_path.name, release)
+ if existing_asset_id:
+ log("Asset exists.")
+ log("Getting asset info.")
+ response = g.get_asset_by_id(existing_asset_id)
+ if response.status_code != requests.codes.ok:
+ raise UnexpectedResponseError(response)
- log("Deleting asset.")
+ log("Decoding asset info.")
+ try:
+ existing_asset = Asset.from_json(response.content)
+ except json.JSONDecodeError:
+ raise UnexpectedResponseError(response)
- response = g.delete_asset(existing_asset_id)
- if response.status_code != requests.codes.no_content:
- log(f"Ignoring failed deletion: {response}")
- else:
- log("Asset does not exist.")
+ if (
+ existing_asset.size == file_size
+ and existing_asset.state == "uploaded"
+ ):
+ log("The asset has the correct size and state. Asset done.\n")
+ return
+
+ log('The asset looks bad (wrong size or state was not "uploaded").')
+
+ log("Deleting asset.")
+
+ response = g.delete_asset(existing_asset_id)
+ if response.status_code != requests.codes.no_content:
+ log("Ignoring failed deletion.")
+ log_response(response)
+ else:
+ log("Asset does not exist.")
+ except Exception: # pylint: disable=broad-except;
+ log_exception(
+ "Ignoring exception that occurred when trying to check asset status with the v4 API."
+ )
- # Asset does not exist or has now been deleted.
+ # Asset does not exist, has been deleted, or an error occurred.
+ # Upload the asset, regardless.
if retry_count >= g.retry_limit:
raise ReachedRetryLimitError("Reached upload retry limit.")
@@ -354,9 +466,10 @@ def upload_file( # pylint: disable=too-many-branches;
try:
response = g.upload_asset(file_path, release)
if response.status_code != requests.codes.created:
- log(f"Ignoring failed upload: {response}")
- except Exception as ex: # pylint: disable=broad-except;
- log(f"Ignoring upload exception: {ex}")
+ log("Ignoring failed upload.")
+ log_response(response)
+ except Exception: # pylint: disable=broad-except;
+ log_exception("Ignoring upload exception.")
# And now we loop.
@@ -406,9 +519,9 @@ def make_release(
if response.status_code != requests.codes.ok:
raise UnexpectedResponseError(response)
- except UnexpectedResponseError as ex:
- log(
- f"Unexpected response when creating the release or getting the existing release info:\n{ex}..."
+ except UnexpectedResponseError:
+ log_exception(
+ "Unexpected response when creating the release or getting the existing release info."
)
# Note: GitHub will sometimes return a custom error for the Release resource with a message:
# "Published releases must have a valid tag".
|
google/github-release-retry
|
426300ff66b25191b4bfb17d101342235749ad4f
|
diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml
index f7cdd58..0e58106 100644
--- a/.github/workflows/build_and_test.yml
+++ b/.github/workflows/build_and_test.yml
@@ -24,33 +24,18 @@ jobs:
fail-fast: false
matrix:
os:
- - ubuntu-16.04
+ - ubuntu-18.04
- windows-latest
python-version:
- 3.6
runs-on: ${{ matrix.os }}
steps:
- - name: get_actions
- run: |
- mkdir -p ./../.github/actions/
- pushd ./../.github/actions/
- git clone https://github.com/actions/setup-python.git
- pushd setup-python/
- git checkout v2
- popd
- git clone https://github.com/actions/checkout.git
- pushd checkout/
- git checkout v2
- popd
- popd
- shell: bash
-
- name: checkout
- uses: ./../.github/actions/checkout
+ uses: actions/checkout@v2
- name: setup_python
- uses: ./../.github/actions/setup-python
+ uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
architecture: x64
diff --git a/github_release_retry_tests/test_node_id_extraction.py b/github_release_retry_tests/test_node_id_extraction.py
new file mode 100644
index 0000000..2247475
--- /dev/null
+++ b/github_release_retry_tests/test_node_id_extraction.py
@@ -0,0 +1,57 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2021 The github-release-retry Project Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import base64
+
+from github_release_retry import github_release_retry
+
+
+def test_release_asset_node_id_to_asset_id() -> None:
+
+ old_format_node_id = "MDEyOlJlbGVhc2VBc3NldDQyMTY0NTg2"
+ old_format_expected_asset_id = "42164586"
+
+ old_format_actual_asset_id = github_release_retry.release_asset_node_id_to_asset_id(
+ old_format_node_id
+ )
+
+ assert old_format_actual_asset_id == old_format_expected_asset_id
+
+ new_format_node_id = "RA_kwDODNhc0c4CrJ0q"
+ new_format_expected_asset_id = "44866858"
+
+ new_format_actual_asset_id = github_release_retry.release_asset_node_id_to_asset_id(
+ new_format_node_id
+ )
+
+ assert new_format_actual_asset_id == new_format_expected_asset_id
+
+
+def test_release_asset_node_id_to_asset_id_exception() -> None:
+ # The release_asset_node_id_to_asset_id(...) function expects a node id with "ReleaseAsset", not "ReleaseBadAsset".
+ node_id_decoded = b"012:ReleaseBadAsset18381577"
+ node_id_encoded = base64.b64encode(node_id_decoded).decode(
+ encoding="utf-8", errors="none"
+ )
+
+ try:
+ github_release_retry.release_asset_node_id_to_asset_id(node_id_encoded)
+ except AssertionError as error:
+ message = str(error)
+ assert "format" in message
+ return
+
+ raise AssertionError("Expected an exception")
|
New GitHub node id format is not supported
It seems that GitHub recently introduced a new format for their node ids. Specifically, release asset node ids used to just be a base64 encoded string. Newer node ids look like this: `"RA_[base64 encoded bytes]"`. It looks like the asset id is still encoded within the node id, but the format is different.
We use the ability to extract the REST v3 API "id" from the GraphQL v4 API "node id", even though this is undocumented.
|
0.0
|
426300ff66b25191b4bfb17d101342235749ad4f
|
[
"github_release_retry_tests/test_node_id_extraction.py::test_release_asset_node_id_to_asset_id",
"github_release_retry_tests/test_node_id_extraction.py::test_release_asset_node_id_to_asset_id_exception"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-23 20:22:33+00:00
|
apache-2.0
| 2,570 |
|
google__importlab-13
|
diff --git a/importlab/import_finder.py b/importlab/import_finder.py
index 35e11ff..47687d3 100644
--- a/importlab/import_finder.py
+++ b/importlab/import_finder.py
@@ -64,7 +64,10 @@ def _resolve_import_2(name):
path = None
for part in parts[i:]:
try:
- spec = imp.find_module(part, path)
+ if path:
+ spec = imp.find_module(part, [path])
+ else:
+ spec = imp.find_module(part)
except ImportError:
return None
path = spec[1]
diff --git a/importlab/resolve.py b/importlab/resolve.py
index c4c1a9c..23314bc 100644
--- a/importlab/resolve.py
+++ b/importlab/resolve.py
@@ -183,8 +183,8 @@ class Resolver:
short_filename = os.path.dirname(filename)
files.append((short_name, short_filename))
- for fs in self.fs_path:
- for module_name, path in files:
+ for module_name, path in files:
+ for fs in self.fs_path:
f = self._find_file(fs, path)
if not f:
continue
@@ -214,6 +214,10 @@ class Resolver:
pyfile = prefix + '.py'
if os.path.exists(pyfile):
return System(pyfile, mod_name)
+ elif not ext:
+ pyfile = os.path.join(prefix, "__init__.py")
+ if os.path.exists(pyfile):
+ return System(pyfile, mod_name)
return System(item.source, mod_name)
raise ImportException(name)
|
google/importlab
|
17edb0b8aae61e7dc2089fbafbd78504d975c221
|
diff --git a/tests/test_resolve.py b/tests/test_resolve.py
index 0d00214..df9e8a0 100644
--- a/tests/test_resolve.py
+++ b/tests/test_resolve.py
@@ -176,6 +176,18 @@ class TestResolver(unittest.TestCase):
self.assertTrue(isinstance(f, resolve.System))
self.assertEqual(f.module_name, "foo.bar")
+ def testResolveSystemPackageDir(self):
+ with utils.Tempdir() as d:
+ py_file = d.create_file("foo/__init__.py")
+ imp = parsepy.ImportStatement("foo",
+ source=d["foo"],
+ is_from=True)
+ r = self.make_resolver("x.py", "x")
+ f = r.resolve_import(imp)
+ self.assertTrue(isinstance(f, resolve.System))
+ self.assertEqual(f.module_name, "foo")
+ self.assertEqual(f.path, d["foo/__init__.py"])
+
def testGetPyFromPycSource(self):
# Override a source pyc file with the corresponding py file if it exists
# in the native filesystem.
|
Importlab running under Python 3.6 and analyzing Python 2.7 can't find networkx
Steps I took:
sudo apt-get install python-pip
pip install networkx # puts networkx in ~/.local/lib/python2.7/site-packages/
virtualenv --python=python3.6 .venv3
source .venv3/bin/activate
pip install importlab
echo "import networkx" > foo.py
importlab -V2.7 foo.py --tree
`foo.py` shows up as the only file in the tree. On the other hand, if I install importlab under Python 2.7 and analyze Python 3.5 code (I didn't try 3.6 because pip3 is 3.5 on my machine), the last command (correctly) causes a bunch of networkx files to be printed as part of the tree.
|
0.0
|
17edb0b8aae61e7dc2089fbafbd78504d975c221
|
[
"tests/test_resolve.py::TestResolver::testResolveSystemPackageDir"
] |
[
"tests/test_resolve.py::TestResolver::testFallBackToSource",
"tests/test_resolve.py::TestResolver::testGetPyFromPycSource",
"tests/test_resolve.py::TestResolver::testOverrideSource",
"tests/test_resolve.py::TestResolver::testPycSourceWithoutPy",
"tests/test_resolve.py::TestResolver::testResolveBuiltin",
"tests/test_resolve.py::TestResolver::testResolveInitFile",
"tests/test_resolve.py::TestResolver::testResolveInitFileRelative",
"tests/test_resolve.py::TestResolver::testResolveModuleFromFile",
"tests/test_resolve.py::TestResolver::testResolvePackageFile",
"tests/test_resolve.py::TestResolver::testResolveParentPackageFile",
"tests/test_resolve.py::TestResolver::testResolveParentPackageFileWithModule",
"tests/test_resolve.py::TestResolver::testResolvePyiFile",
"tests/test_resolve.py::TestResolver::testResolveRelativeFromInitFileWithModule",
"tests/test_resolve.py::TestResolver::testResolveRelativeInNonPackage",
"tests/test_resolve.py::TestResolver::testResolveSamePackageFile",
"tests/test_resolve.py::TestResolver::testResolveSiblingPackageFile",
"tests/test_resolve.py::TestResolver::testResolveStarImport",
"tests/test_resolve.py::TestResolver::testResolveStarImportBuiltin",
"tests/test_resolve.py::TestResolver::testResolveStarImportSystem",
"tests/test_resolve.py::TestResolver::testResolveSymbolFromFile",
"tests/test_resolve.py::TestResolver::testResolveSystemInitFile",
"tests/test_resolve.py::TestResolver::testResolveSystemRelative",
"tests/test_resolve.py::TestResolver::testResolveSystemSymbol",
"tests/test_resolve.py::TestResolver::testResolveSystemSymbolNameClash",
"tests/test_resolve.py::TestResolver::testResolveTopLevel",
"tests/test_resolve.py::TestResolver::testResolveWithFilesystem",
"tests/test_resolve.py::TestResolverUtils::testGetAbsoluteName",
"tests/test_resolve.py::TestResolverUtils::testInferModuleName"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-08-16 21:22:53+00:00
|
apache-2.0
| 2,571 |
|
google__importlab-23
|
diff --git a/importlab/resolve.py b/importlab/resolve.py
index 23314bc..d55f34d 100644
--- a/importlab/resolve.py
+++ b/importlab/resolve.py
@@ -102,6 +102,9 @@ def infer_module_name(filename, fspath):
for f in fspath:
short_name = f.relative_path(filename)
if short_name:
+ # The module name for __init__.py files is the directory.
+ if short_name.endswith(os.path.sep + "__init__"):
+ short_name = short_name[:short_name.rfind(os.path.sep)]
return short_name.replace(os.path.sep, '.')
# We have not found filename relative to anywhere in pythonpath.
return ''
|
google/importlab
|
77f04151272440dacea197b8c4f74aa26fdbe950
|
diff --git a/tests/test_resolve.py b/tests/test_resolve.py
index 2a217d3..9891764 100644
--- a/tests/test_resolve.py
+++ b/tests/test_resolve.py
@@ -293,6 +293,15 @@ class TestResolverUtils(unittest.TestCase):
resolve.infer_module_name("/some/random/file", fspath),
"")
+ def testInferInitModuleName(self):
+ with utils.Tempdir() as d:
+ os_fs = fs.OSFileSystem(d.path)
+ fspath = [os_fs]
+ py_file = d.create_file("foo/__init__.py")
+ self.assertEqual(
+ resolve.infer_module_name(py_file, fspath),
+ "foo")
+
def testGetAbsoluteName(self):
test_cases = [
("x.y", "a.b", "x.y.a.b"),
|
Incorrect inferred module name for __init__.py files
See google/pytype#154 for more detail.
`resolve.infer_module_name` calculates the wrong name for `__init__.py` files. For example, for `foo/bar/__init__.py`, it will return `foo.bar.__init__`. The module name should be `foo.bar`.
|
0.0
|
77f04151272440dacea197b8c4f74aa26fdbe950
|
[
"tests/test_resolve.py::TestResolverUtils::testInferInitModuleName"
] |
[
"tests/test_resolve.py::TestResolver::testFallBackToSource",
"tests/test_resolve.py::TestResolver::testGetPyFromPycSource",
"tests/test_resolve.py::TestResolver::testOverrideSource",
"tests/test_resolve.py::TestResolver::testPycSourceWithoutPy",
"tests/test_resolve.py::TestResolver::testResolveBuiltin",
"tests/test_resolve.py::TestResolver::testResolveInitFile",
"tests/test_resolve.py::TestResolver::testResolveInitFileRelative",
"tests/test_resolve.py::TestResolver::testResolveModuleFromFile",
"tests/test_resolve.py::TestResolver::testResolvePackageFile",
"tests/test_resolve.py::TestResolver::testResolveParentPackageFile",
"tests/test_resolve.py::TestResolver::testResolveParentPackageFileWithModule",
"tests/test_resolve.py::TestResolver::testResolvePyiFile",
"tests/test_resolve.py::TestResolver::testResolveRelativeFromInitFileWithModule",
"tests/test_resolve.py::TestResolver::testResolveRelativeInNonPackage",
"tests/test_resolve.py::TestResolver::testResolveSamePackageFile",
"tests/test_resolve.py::TestResolver::testResolveSiblingPackageFile",
"tests/test_resolve.py::TestResolver::testResolveStarImport",
"tests/test_resolve.py::TestResolver::testResolveStarImportBuiltin",
"tests/test_resolve.py::TestResolver::testResolveStarImportSystem",
"tests/test_resolve.py::TestResolver::testResolveSymbolFromFile",
"tests/test_resolve.py::TestResolver::testResolveSystemInitFile",
"tests/test_resolve.py::TestResolver::testResolveSystemPackageDir",
"tests/test_resolve.py::TestResolver::testResolveSystemRelative",
"tests/test_resolve.py::TestResolver::testResolveSystemSymbol",
"tests/test_resolve.py::TestResolver::testResolveSystemSymbolNameClash",
"tests/test_resolve.py::TestResolver::testResolveTopLevel",
"tests/test_resolve.py::TestResolver::testResolveWithFilesystem",
"tests/test_resolve.py::TestResolverUtils::testGetAbsoluteName",
"tests/test_resolve.py::TestResolverUtils::testInferModuleName"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-09-12 22:25:03+00:00
|
apache-2.0
| 2,572 |
|
google__latexify_py-143
|
diff --git a/src/latexify/codegen/function_codegen.py b/src/latexify/codegen/function_codegen.py
index 9ef24a0..cf83122 100644
--- a/src/latexify/codegen/function_codegen.py
+++ b/src/latexify/codegen/function_codegen.py
@@ -334,18 +334,84 @@ class FunctionCodegen(ast.NodeVisitor):
wrapped = [r"\mathopen{}\left( " + s + r" \mathclose{}\right)" for s in conds]
return r" \land ".join(wrapped)
+ def _generate_sum_prod(self, node: ast.Call) -> str | None:
+ """Generates sum/prod expression.
+
+ Args:
+ node: ast.Call node containing the sum/prod invocation.
+
+ Returns:
+ Generated LaTeX, or None if the node has unsupported syntax.
+ """
+ if not isinstance(node.args[0], ast.GeneratorExp):
+ return None
+
+ name = ast_utils.extract_function_name_or_none(node)
+ assert name is not None
+
+ elt, scripts = self._get_sum_prod_info(node.args[0])
+ scripts_str = [rf"\{name}_{{{lo}}}^{{{up}}}" for lo, up in scripts]
+ return (
+ " ".join(scripts_str)
+ + rf" \mathopen{{}}\left({{{elt}}}\mathclose{{}}\right)"
+ )
+
+ def _generate_matrix(self, node: ast.Call) -> str | None:
+ """Generates matrix expression.
+
+ Args:
+ node: ast.Call node containing the ndarray invocation.
+
+ Returns:
+ Generated LaTeX, or None if the node has unsupported syntax.
+ """
+
+ def generate_matrix_from_array(data: list[list[str]]) -> str:
+ """Helper to generate a bmatrix environment."""
+ contents = r" \\ ".join(" & ".join(row) for row in data)
+ return r"\begin{bmatrix} " + contents + r" \end{bmatrix}"
+
+ arg = node.args[0]
+ if not isinstance(arg, ast.List) or not arg.elts:
+ # Not an array or no rows
+ return None
+
+ row0 = arg.elts[0]
+
+ if not isinstance(row0, ast.List):
+ # Maybe 1 x N array
+ return generate_matrix_from_array([[self.visit(x) for x in arg.elts]])
+
+ if not row0.elts:
+ # No columns
+ return None
+
+ ncols = len(row0.elts)
+
+ if not all(
+ isinstance(row, ast.List) and len(row.elts) == ncols for row in arg.elts
+ ):
+ # Length mismatch
+ return None
+
+ return generate_matrix_from_array(
+ [[self.visit(x) for x in row.elts] for row in arg.elts]
+ )
+
def visit_Call(self, node: ast.Call) -> str:
"""Visit a call node."""
func_name = ast_utils.extract_function_name_or_none(node)
- # Special processing for sum and prod.
- if func_name in ("sum", "prod") and isinstance(node.args[0], ast.GeneratorExp):
- elt, scripts = self._get_sum_prod_info(node.args[0])
- scripts_str = [rf"\{func_name}_{{{lo}}}^{{{up}}}" for lo, up in scripts]
- return (
- " ".join(scripts_str)
- + rf" \mathopen{{}}\left({{{elt}}}\mathclose{{}}\right)"
- )
+ # Special treatments for some functions.
+ if func_name in ("sum", "prod"):
+ special_latex = self._generate_sum_prod(node)
+ elif func_name in ("array", "ndarray"):
+ special_latex = self._generate_matrix(node)
+ else:
+ special_latex = None
+
+ if special_latex is not None:
+ return special_latex
# Function signature (possibly an expression).
default_func_str = self.visit(node.func)
|
google/latexify_py
|
7f13cb6aa7346084617d84a6b51b417c9ed6e49c
|
diff --git a/src/latexify/codegen/function_codegen_test.py b/src/latexify/codegen/function_codegen_test.py
index 2dc880a..d7628be 100644
--- a/src/latexify/codegen/function_codegen_test.py
+++ b/src/latexify/codegen/function_codegen_test.py
@@ -744,3 +744,46 @@ def test_use_set_symbols_compare(code: str, latex: str) -> None:
tree = ast.parse(code).body[0].value
assert isinstance(tree, ast.Compare)
assert function_codegen.FunctionCodegen(use_set_symbols=True).visit(tree) == latex
+
+
[email protected](
+ "code,latex",
+ [
+ ("array(1)", r"\mathrm{array}\mathopen{}\left({1}\mathclose{}\right)"),
+ (
+ "array([])",
+ r"\mathrm{array}\mathopen{}\left(\left[ \right] \mathclose{}\right)",
+ ),
+ ("array([1])", r"\begin{bmatrix} {1} \end{bmatrix}"),
+ ("array([1, 2, 3])", r"\begin{bmatrix} {1} & {2} & {3} \end{bmatrix}"),
+ (
+ "array([[]])",
+ r"\mathrm{array}\mathopen{}\left("
+ r"\left[ \left[ \right] \right] "
+ r"\mathclose{}\right)",
+ ),
+ ("array([[1]])", r"\begin{bmatrix} {1} \end{bmatrix}"),
+ ("array([[1], [2], [3]])", r"\begin{bmatrix} {1} \\ {2} \\ {3} \end{bmatrix}"),
+ (
+ "array([[1], [2], [3, 4]])",
+ r"\mathrm{array}\mathopen{}\left("
+ r"\left[ "
+ r"\left[ {1}\right] \space,\space "
+ r"\left[ {2}\right] \space,\space "
+ r"\left[ {3}\space,\space {4}\right] "
+ r"\right] "
+ r"\mathclose{}\right)",
+ ),
+ (
+ "array([[1, 2], [3, 4], [5, 6]])",
+ r"\begin{bmatrix} {1} & {2} \\ {3} & {4} \\ {5} & {6} \end{bmatrix}",
+ ),
+ # Only checks two cases for ndarray.
+ ("ndarray(1)", r"\mathrm{ndarray}\mathopen{}\left({1}\mathclose{}\right)"),
+ ("ndarray([1])", r"\begin{bmatrix} {1} \end{bmatrix}"),
+ ],
+)
+def test_numpy_array(code: str, latex: str) -> None:
+ tree = ast.parse(code).body[0].value
+ assert isinstance(tree, ast.Call)
+ assert function_codegen.FunctionCodegen().visit(tree) == latex
|
NDArray support
Sometimes users want to support NDArrays in this library, e.g., `np.array([[a, b], [c, d]])` to
$$\left( \begin{array}{cc}a&b \\\\ c&d\end{array} \right)$$
This is definitely useful, but often it is not possible to compile:
- Large arrays.
- Arrays with more than 2 dimensions.
I think we could start implementing it with reasonable restrictions (e.g., only NDArrays with <= 2 dimensions with small lengths), but it would be also good to keep discussion.
Refs:
- #38
- #53
- #75
|
0.0
|
7f13cb6aa7346084617d84a6b51b417c9ed6e49c
|
[
"src/latexify/codegen/function_codegen_test.py::test_numpy_array[array([1])-\\\\begin{bmatrix}",
"src/latexify/codegen/function_codegen_test.py::test_numpy_array[array([1,",
"src/latexify/codegen/function_codegen_test.py::test_numpy_array[array([[1]])-\\\\begin{bmatrix}",
"src/latexify/codegen/function_codegen_test.py::test_numpy_array[array([[1],",
"src/latexify/codegen/function_codegen_test.py::test_numpy_array[array([[1,",
"src/latexify/codegen/function_codegen_test.py::test_numpy_array[ndarray([1])-\\\\begin{bmatrix}"
] |
[
"src/latexify/codegen/function_codegen_test.py::test_generic_visit",
"src/latexify/codegen/function_codegen_test.py::test_visit_functiondef_use_signature",
"src/latexify/codegen/function_codegen_test.py::test_visit_functiondef_ignore_docstring",
"src/latexify/codegen/function_codegen_test.py::test_visit_functiondef_ignore_multiple_constants",
"src/latexify/codegen/function_codegen_test.py::test_visit_listcomp[[i",
"src/latexify/codegen/function_codegen_test.py::test_visit_setcomp[{i",
"src/latexify/codegen/function_codegen_test.py::test_visit_call_sum_prod[(x)-",
"src/latexify/codegen/function_codegen_test.py::test_visit_call_sum_prod[([1,",
"src/latexify/codegen/function_codegen_test.py::test_visit_call_sum_prod[({1,",
"src/latexify/codegen/function_codegen_test.py::test_visit_call_sum_prod[(f(x))-",
"src/latexify/codegen/function_codegen_test.py::test_visit_call_sum_prod[(i",
"src/latexify/codegen/function_codegen_test.py::test_visit_call_sum_prod_multiple_comprehension[sum(i",
"src/latexify/codegen/function_codegen_test.py::test_visit_call_sum_prod_multiple_comprehension[prod(i",
"src/latexify/codegen/function_codegen_test.py::test_visit_call_sum_prod_with_if[(i",
"src/latexify/codegen/function_codegen_test.py::test_if_then_else[x",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[x**y-x^{y}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[x",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[(x**y)**z-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[(x",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[x**(y**z)-x^{y^{z}}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[x**y",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[x**(y",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[x**f(y)-x^{f\\\\mathopen{}\\\\left(y\\\\mathclose{}\\\\right)}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[f(x)**y-f\\\\mathopen{}\\\\left(x\\\\mathclose{}\\\\right)^{y}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[f(x)",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[x**-y-x^{-y}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[(-x)**y-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/function_codegen_test.py::test_visit_binop[-x",
"src/latexify/codegen/function_codegen_test.py::test_visit_unaryop[+x-+x]",
"src/latexify/codegen/function_codegen_test.py::test_visit_unaryop[-x--x]",
"src/latexify/codegen/function_codegen_test.py::test_visit_unaryop[~x-\\\\mathord{\\\\sim}",
"src/latexify/codegen/function_codegen_test.py::test_visit_unaryop[not",
"src/latexify/codegen/function_codegen_test.py::test_visit_unaryop[+f(x)-+f\\\\mathopen{}\\\\left(x\\\\mathclose{}\\\\right)]",
"src/latexify/codegen/function_codegen_test.py::test_visit_unaryop[-f(x)--f\\\\mathopen{}\\\\left(x\\\\mathclose{}\\\\right)]",
"src/latexify/codegen/function_codegen_test.py::test_visit_unaryop[~f(x)-\\\\mathord{\\\\sim}",
"src/latexify/codegen/function_codegen_test.py::test_visit_unaryop[+(x",
"src/latexify/codegen/function_codegen_test.py::test_visit_unaryop[-(x",
"src/latexify/codegen/function_codegen_test.py::test_visit_unaryop[~(x",
"src/latexify/codegen/function_codegen_test.py::test_visit_compare[a",
"src/latexify/codegen/function_codegen_test.py::test_visit_compare[f(a)",
"src/latexify/codegen/function_codegen_test.py::test_visit_compare[-a",
"src/latexify/codegen/function_codegen_test.py::test_visit_compare[(not",
"src/latexify/codegen/function_codegen_test.py::test_visit_compare[(a",
"src/latexify/codegen/function_codegen_test.py::test_visit_boolop[a",
"src/latexify/codegen/function_codegen_test.py::test_visit_boolop[(a",
"src/latexify/codegen/function_codegen_test.py::test_visit_boolop[f(a)",
"src/latexify/codegen/function_codegen_test.py::test_visit_boolop[not",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[0-Num-{0}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[1-Num-{1}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[0.0-Num-{0.0}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[1.5-Num-{1.5}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[0.0j-Num-{0j}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[1.0j-Num-{1j}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[1.5j-Num-{1.5j}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[\"abc\"-Str-\\\\textrm{\"abc\"}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[b\"abc\"-Bytes-\\\\textrm{b'abc'}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[None-NameConstant-\\\\mathrm{None}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[False-NameConstant-\\\\mathrm{False}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[True-NameConstant-\\\\mathrm{True}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant_lagacy[...-Ellipsis-{\\\\cdots}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[0-{0}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[1-{1}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[0.0-{0.0}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[1.5-{1.5}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[0.0j-{0j}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[1.0j-{1j}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[1.5j-{1.5j}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[\"abc\"-\\\\textrm{\"abc\"}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[b\"abc\"-\\\\textrm{b'abc'}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[None-\\\\mathrm{None}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[False-\\\\mathrm{False}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[True-\\\\mathrm{True}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_constant[...-{\\\\cdots}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_subscript[x[0]-{x_{{0}}}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_subscript[x[0][1]-{x_{{0},",
"src/latexify/codegen/function_codegen_test.py::test_visit_subscript[x[0][1][2]-{x_{{0},",
"src/latexify/codegen/function_codegen_test.py::test_visit_subscript[x[foo]-{x_{\\\\mathrm{foo}}}]",
"src/latexify/codegen/function_codegen_test.py::test_visit_subscript[x[floor(x)]-{x_{\\\\left\\\\lfloor{x}\\\\right\\\\rfloor}}]",
"src/latexify/codegen/function_codegen_test.py::test_use_set_symbols_binop[a",
"src/latexify/codegen/function_codegen_test.py::test_use_set_symbols_compare[a",
"src/latexify/codegen/function_codegen_test.py::test_numpy_array[array(1)-\\\\mathrm{array}\\\\mathopen{}\\\\left({1}\\\\mathclose{}\\\\right)]",
"src/latexify/codegen/function_codegen_test.py::test_numpy_array[array([])-\\\\mathrm{array}\\\\mathopen{}\\\\left(\\\\left[",
"src/latexify/codegen/function_codegen_test.py::test_numpy_array[array([[]])-\\\\mathrm{array}\\\\mathopen{}\\\\left(\\\\left[",
"src/latexify/codegen/function_codegen_test.py::test_numpy_array[ndarray(1)-\\\\mathrm{ndarray}\\\\mathopen{}\\\\left({1}\\\\mathclose{}\\\\right)]"
] |
{
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-03 11:49:41+00:00
|
apache-2.0
| 2,573 |
|
google__latexify_py-182
|
diff --git a/src/latexify/codegen/expression_codegen.py b/src/latexify/codegen/expression_codegen.py
index 9706e74..3c72219 100644
--- a/src/latexify/codegen/expression_codegen.py
+++ b/src/latexify/codegen/expression_codegen.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import ast
+import re
from latexify import analyzers, ast_utils, exceptions
from latexify.codegen import codegen_utils, expression_rules, identifier_converter
@@ -406,12 +407,94 @@ class ExpressionCodegen(ast.NodeVisitor):
return rf"\mathopen{{}}\left( {latex} \mathclose{{}}\right)"
+ _l_bracket_pattern = re.compile(r"^\\mathopen.*")
+ _r_bracket_pattern = re.compile(r".*\\mathclose[^ ]+$")
+ _r_word_pattern = re.compile(r"\\mathrm\{[^ ]+\}$")
+
+ def _should_remove_multiply_op(
+ self, l_latex: str, r_latex: str, l_expr: ast.expr, r_expr: ast.expr
+ ):
+ """Determine whether the multiply operator should be removed or not.
+
+ See also:
+ https://github.com/google/latexify_py/issues/89#issuecomment-1344967636
+
+ This is an ad-hoc implementation.
+ This function doesn't fully implements the above requirements, but only
+ essential ones necessary to release v0.3.
+ """
+
+ # NOTE(odashi): For compatibility with Python 3.7, we compare the generated
+ # caracter type directly to determine the "numeric" type.
+
+ if isinstance(l_expr, ast.Call):
+ l_type = "f"
+ elif self._r_bracket_pattern.match(l_latex):
+ l_type = "b"
+ elif self._r_word_pattern.match(l_latex):
+ l_type = "w"
+ elif l_latex[-1].isnumeric():
+ l_type = "n"
+ else:
+ le = l_expr
+ while True:
+ if isinstance(le, ast.UnaryOp):
+ le = le.operand
+ elif isinstance(le, ast.BinOp):
+ le = le.right
+ elif isinstance(le, ast.Compare):
+ le = le.comparators[-1]
+ elif isinstance(le, ast.BoolOp):
+ le = le.values[-1]
+ else:
+ break
+ l_type = "a" if isinstance(le, ast.Name) and len(le.id) == 1 else "m"
+
+ if isinstance(r_expr, ast.Call):
+ r_type = "f"
+ elif self._l_bracket_pattern.match(r_latex):
+ r_type = "b"
+ elif r_latex.startswith("\\mathrm"):
+ r_type = "w"
+ elif r_latex[0].isnumeric():
+ r_type = "n"
+ else:
+ re = r_expr
+ while True:
+ if isinstance(re, ast.UnaryOp):
+ if isinstance(re.op, ast.USub):
+ # NOTE(odashi): Unary "-" always require \cdot.
+ return False
+ re = re.operand
+ elif isinstance(re, ast.BinOp):
+ re = re.left
+ elif isinstance(re, ast.Compare):
+ re = re.left
+ elif isinstance(re, ast.BoolOp):
+ re = re.values[0]
+ else:
+ break
+ r_type = "a" if isinstance(re, ast.Name) and len(re.id) == 1 else "m"
+
+ if r_type == "n":
+ return False
+ if l_type in "bn":
+ return True
+ if l_type in "am" and r_type in "am":
+ return True
+ return False
+
def visit_BinOp(self, node: ast.BinOp) -> str:
"""Visit a BinOp node."""
prec = expression_rules.get_precedence(node)
rule = self._bin_op_rules[type(node.op)]
lhs = self._wrap_binop_operand(node.left, prec, rule.operand_left)
rhs = self._wrap_binop_operand(node.right, prec, rule.operand_right)
+
+ if type(node.op) in [ast.Mult, ast.MatMult]:
+ if self._should_remove_multiply_op(lhs, rhs, node.left, node.right):
+ return f"{rule.latex_left}{lhs} {rhs}{rule.latex_right}"
+
return f"{rule.latex_left}{lhs}{rule.latex_middle}{rhs}{rule.latex_right}"
def visit_UnaryOp(self, node: ast.UnaryOp) -> str:
|
google/latexify_py
|
37d47c98b044135fa0e7d33c18774b7e6b816763
|
diff --git a/src/integration_tests/algorithmic_style_test.py b/src/integration_tests/algorithmic_style_test.py
index 8cbe68e..96665cb 100644
--- a/src/integration_tests/algorithmic_style_test.py
+++ b/src/integration_tests/algorithmic_style_test.py
@@ -63,7 +63,7 @@ def test_collatz() -> None:
\If{$n \mathbin{\%} 2 = 0$}
\State $n \gets \left\lfloor\frac{n}{2}\right\rfloor$
\Else
- \State $n \gets 3 \cdot n + 1$
+ \State $n \gets 3 n + 1$
\EndIf
\State $\mathrm{iterations} \gets \mathrm{iterations} + 1$
\EndWhile
@@ -80,7 +80,7 @@ def test_collatz() -> None:
r" \hspace{2em} \mathbf{if} \ n \mathbin{\%} 2 = 0 \\"
r" \hspace{3em} n \gets \left\lfloor\frac{n}{2}\right\rfloor \\"
r" \hspace{2em} \mathbf{else} \\"
- r" \hspace{3em} n \gets 3 \cdot n + 1 \\"
+ r" \hspace{3em} n \gets 3 n + 1 \\"
r" \hspace{2em} \mathbf{end \ if} \\"
r" \hspace{2em}"
r" \mathrm{iterations} \gets \mathrm{iterations} + 1 \\"
diff --git a/src/integration_tests/regression_test.py b/src/integration_tests/regression_test.py
index 17b5d3c..7cb063d 100644
--- a/src/integration_tests/regression_test.py
+++ b/src/integration_tests/regression_test.py
@@ -11,10 +11,7 @@ def test_quadratic_solution() -> None:
def solve(a, b, c):
return (-b + math.sqrt(b**2 - 4 * a * c)) / (2 * a)
- latex = (
- r"\mathrm{solve}(a, b, c) ="
- r" \frac{-b + \sqrt{ b^{2} - 4 \cdot a \cdot c }}{2 \cdot a}"
- )
+ latex = r"\mathrm{solve}(a, b, c) =" r" \frac{-b + \sqrt{ b^{2} - 4 a c }}{2 a}"
integration_utils.check_function(solve, latex)
@@ -47,7 +44,7 @@ def test_x_times_beta() -> None:
xtimesbeta, latex_without_symbols, use_math_symbols=False
)
- latex_with_symbols = r"\mathrm{xtimesbeta}(x, \beta) = x \cdot \beta"
+ latex_with_symbols = r"\mathrm{xtimesbeta}(x, \beta) = x \beta"
integration_utils.check_function(
xtimesbeta, latex_with_symbols, use_math_symbols=True
)
@@ -145,7 +142,7 @@ def test_nested_function() -> None:
def nested(x):
return 3 * x
- integration_utils.check_function(nested, r"\mathrm{nested}(x) = 3 \cdot x")
+ integration_utils.check_function(nested, r"\mathrm{nested}(x) = 3 x")
def test_double_nested_function() -> None:
@@ -155,7 +152,7 @@ def test_double_nested_function() -> None:
return inner
- integration_utils.check_function(nested(3), r"\mathrm{inner}(y) = x \cdot y")
+ integration_utils.check_function(nested(3), r"\mathrm{inner}(y) = x y")
def test_reduce_assignments() -> None:
@@ -165,11 +162,11 @@ def test_reduce_assignments() -> None:
integration_utils.check_function(
f,
- r"\begin{array}{l} a = x + x \\ f(x) = 3 \cdot a \end{array}",
+ r"\begin{array}{l} a = x + x \\ f(x) = 3 a \end{array}",
)
integration_utils.check_function(
f,
- r"f(x) = 3 \cdot \mathopen{}\left( x + x \mathclose{}\right)",
+ r"f(x) = 3 \mathopen{}\left( x + x \mathclose{}\right)",
reduce_assignments=True,
)
@@ -184,7 +181,7 @@ def test_reduce_assignments_double() -> None:
r"\begin{array}{l}"
r" a = x^{2} \\"
r" b = a + a \\"
- r" f(x) = 3 \cdot b"
+ r" f(x) = 3 b"
r" \end{array}"
)
@@ -192,7 +189,7 @@ def test_reduce_assignments_double() -> None:
integration_utils.check_function(f, latex_without_option, reduce_assignments=False)
integration_utils.check_function(
f,
- r"f(x) = 3 \cdot \mathopen{}\left( x^{2} + x^{2} \mathclose{}\right)",
+ r"f(x) = 3 \mathopen{}\left( x^{2} + x^{2} \mathclose{}\right)",
reduce_assignments=True,
)
@@ -228,7 +225,7 @@ def test_sub_bracket() -> None:
r"\mathrm{solve}(a, b) ="
r" \frac{a + b - b}{a - b} - \mathopen{}\left("
r" a + b \mathclose{}\right) - \mathopen{}\left("
- r" a - b \mathclose{}\right) - a \cdot b"
+ r" a - b \mathclose{}\right) - a b"
)
integration_utils.check_function(solve, latex)
diff --git a/src/latexify/codegen/expression_codegen_test.py b/src/latexify/codegen/expression_codegen_test.py
index 0b90915..5eb999b 100644
--- a/src/latexify/codegen/expression_codegen_test.py
+++ b/src/latexify/codegen/expression_codegen_test.py
@@ -454,8 +454,8 @@ def test_if_then_else(code: str, latex: str) -> None:
[
# x op y
("x**y", r"x^{y}"),
- ("x * y", r"x \cdot y"),
- ("x @ y", r"x \cdot y"),
+ ("x * y", r"x y"),
+ ("x @ y", r"x y"),
("x / y", r"\frac{x}{y}"),
("x // y", r"\left\lfloor\frac{x}{y}\right\rfloor"),
("x % y", r"x \mathbin{\%} y"),
@@ -468,8 +468,8 @@ def test_if_then_else(code: str, latex: str) -> None:
("x | y", R"x \mathbin{|} y"),
# (x op y) op z
("(x**y)**z", r"\mathopen{}\left( x^{y} \mathclose{}\right)^{z}"),
- ("(x * y) * z", r"x \cdot y \cdot z"),
- ("(x @ y) @ z", r"x \cdot y \cdot z"),
+ ("(x * y) * z", r"x y z"),
+ ("(x @ y) @ z", r"x y z"),
("(x / y) / z", r"\frac{\frac{x}{y}}{z}"),
(
"(x // y) // z",
@@ -485,8 +485,8 @@ def test_if_then_else(code: str, latex: str) -> None:
("(x | y) | z", r"x \mathbin{|} y \mathbin{|} z"),
# x op (y op z)
("x**(y**z)", r"x^{y^{z}}"),
- ("x * (y * z)", r"x \cdot y \cdot z"),
- ("x @ (y @ z)", r"x \cdot y \cdot z"),
+ ("x * (y * z)", r"x y z"),
+ ("x @ (y @ z)", r"x y z"),
("x / (y / z)", r"\frac{x}{\frac{y}{z}}"),
(
"x // (y // z)",
@@ -504,9 +504,9 @@ def test_if_then_else(code: str, latex: str) -> None:
("x ^ (y ^ z)", r"x \oplus y \oplus z"),
("x | (y | z)", r"x \mathbin{|} y \mathbin{|} z"),
# x OP y op z
- ("x**y * z", r"x^{y} \cdot z"),
- ("x * y + z", r"x \cdot y + z"),
- ("x @ y + z", r"x \cdot y + z"),
+ ("x**y * z", r"x^{y} z"),
+ ("x * y + z", r"x y + z"),
+ ("x @ y + z", r"x y + z"),
("x / y + z", r"\frac{x}{y} + z"),
("x // y + z", r"\left\lfloor\frac{x}{y}\right\rfloor + z"),
("x % y + z", r"x \mathbin{\%} y + z"),
@@ -517,7 +517,7 @@ def test_if_then_else(code: str, latex: str) -> None:
("x & y ^ z", r"x \mathbin{\&} y \oplus z"),
("x ^ y | z", r"x \oplus y \mathbin{|} z"),
# x OP (y op z)
- ("x**(y * z)", r"x^{y \cdot z}"),
+ ("x**(y * z)", r"x^{y z}"),
("x * (y + z)", r"x \cdot \mathopen{}\left( y + z \mathclose{}\right)"),
("x @ (y + z)", r"x \cdot \mathopen{}\left( y + z \mathclose{}\right)"),
("x / (y + z)", r"\frac{x}{y + z}"),
@@ -542,9 +542,9 @@ def test_if_then_else(code: str, latex: str) -> None:
r"x \oplus \mathopen{}\left( y \mathbin{|} z \mathclose{}\right)",
),
# x op y OP z
- ("x * y**z", r"x \cdot y^{z}"),
- ("x + y * z", r"x + y \cdot z"),
- ("x + y @ z", r"x + y \cdot z"),
+ ("x * y**z", r"x y^{z}"),
+ ("x + y * z", r"x + y z"),
+ ("x + y @ z", r"x + y z"),
("x + y / z", r"x + \frac{y}{z}"),
("x + y // z", r"x + \left\lfloor\frac{y}{z}\right\rfloor"),
("x + y % z", r"x + y \mathbin{\%} z"),
@@ -555,9 +555,9 @@ def test_if_then_else(code: str, latex: str) -> None:
("x ^ y & z", r"x \oplus y \mathbin{\&} z"),
("x | y ^ z", r"x \mathbin{|} y \oplus z"),
# (x op y) OP z
- ("(x * y)**z", r"\mathopen{}\left( x \cdot y \mathclose{}\right)^{z}"),
- ("(x + y) * z", r"\mathopen{}\left( x + y \mathclose{}\right) \cdot z"),
- ("(x + y) @ z", r"\mathopen{}\left( x + y \mathclose{}\right) \cdot z"),
+ ("(x * y)**z", r"\mathopen{}\left( x y \mathclose{}\right)^{z}"),
+ ("(x + y) * z", r"\mathopen{}\left( x + y \mathclose{}\right) z"),
+ ("(x + y) @ z", r"\mathopen{}\left( x + y \mathclose{}\right) z"),
("(x + y) / z", r"\frac{x + y}{z}"),
("(x + y) // z", r"\left\lfloor\frac{x + y}{z}\right\rfloor"),
("(x + y) % z", r"\mathopen{}\left( x + y \mathclose{}\right) \mathbin{\%} z"),
@@ -600,8 +600,8 @@ def test_if_then_else(code: str, latex: str) -> None:
# With UnaryOp
("x**-y", r"x^{-y}"),
("(-x)**y", r"\mathopen{}\left( -x \mathclose{}\right)^{y}"),
- ("x * -y", r"x \cdot -y"), # TODO(odashi): google/latexify_py#89
- ("-x * y", r"-x \cdot y"),
+ ("x * -y", r"x \cdot -y"),
+ ("-x * y", r"-x y"),
("x / -y", r"\frac{x}{-y}"),
("-x / y", r"\frac{-x}{y}"),
("x + -y", r"x + -y"),
@@ -610,7 +610,7 @@ def test_if_then_else(code: str, latex: str) -> None:
("x**(y == z)", r"x^{y = z}"),
("(x == y)**z", r"\mathopen{}\left( x = y \mathclose{}\right)^{z}"),
("x * (y == z)", r"x \cdot \mathopen{}\left( y = z \mathclose{}\right)"),
- ("(x == y) * z", r"\mathopen{}\left( x = y \mathclose{}\right) \cdot z"),
+ ("(x == y) * z", r"\mathopen{}\left( x = y \mathclose{}\right) z"),
("x / (y == z)", r"\frac{x}{y = z}"),
("(x == y) / z", r"\frac{x = y}{z}"),
("x + (y == z)", r"x + \mathopen{}\left( y = z \mathclose{}\right)"),
@@ -619,7 +619,7 @@ def test_if_then_else(code: str, latex: str) -> None:
("x**(y and z)", r"x^{y \land z}"),
("(x and y)**z", r"\mathopen{}\left( x \land y \mathclose{}\right)^{z}"),
("x * (y and z)", r"x \cdot \mathopen{}\left( y \land z \mathclose{}\right)"),
- ("(x and y) * z", r"\mathopen{}\left( x \land y \mathclose{}\right) \cdot z"),
+ ("(x and y) * z", r"\mathopen{}\left( x \land y \mathclose{}\right) z"),
("x / (y and z)", r"\frac{x}{y \land z}"),
("(x and y) / z", r"\frac{x \land y}{z}"),
("x + (y and z)", r"x + \mathopen{}\left( y \land z \mathclose{}\right)"),
@@ -991,3 +991,96 @@ def test_transpose(code: str, latex: str) -> None:
tree = ast_utils.parse_expr(code)
assert isinstance(tree, ast.Call)
assert expression_codegen.ExpressionCodegen().visit(tree) == latex
+
+
+# Check list for #89.
+# https://github.com/google/latexify_py/issues/89#issuecomment-1344967636
[email protected](
+ "left,right,latex",
+ [
+ ("2", "3", r"2 \cdot 3"),
+ ("2", "y", "2 y"),
+ ("2", "beta", r"2 \beta"),
+ ("2", "bar", r"2 \mathrm{bar}"),
+ ("2", "g(y)", r"2 g \mathopen{}\left( y \mathclose{}\right)"),
+ ("2", "(u + v)", r"2 \mathopen{}\left( u + v \mathclose{}\right)"),
+ ("x", "3", r"x \cdot 3"),
+ ("x", "y", "x y"),
+ ("x", "beta", r"x \beta"),
+ ("x", "bar", r"x \cdot \mathrm{bar}"),
+ ("x", "g(y)", r"x \cdot g \mathopen{}\left( y \mathclose{}\right)"),
+ ("x", "(u + v)", r"x \cdot \mathopen{}\left( u + v \mathclose{}\right)"),
+ ("alpha", "3", r"\alpha \cdot 3"),
+ ("alpha", "y", r"\alpha y"),
+ ("alpha", "beta", r"\alpha \beta"),
+ ("alpha", "bar", r"\alpha \cdot \mathrm{bar}"),
+ ("alpha", "g(y)", r"\alpha \cdot g \mathopen{}\left( y \mathclose{}\right)"),
+ (
+ "alpha",
+ "(u + v)",
+ r"\alpha \cdot \mathopen{}\left( u + v \mathclose{}\right)",
+ ),
+ ("foo", "3", r"\mathrm{foo} \cdot 3"),
+ ("foo", "y", r"\mathrm{foo} \cdot y"),
+ ("foo", "beta", r"\mathrm{foo} \cdot \beta"),
+ ("foo", "bar", r"\mathrm{foo} \cdot \mathrm{bar}"),
+ (
+ "foo",
+ "g(y)",
+ r"\mathrm{foo} \cdot g \mathopen{}\left( y \mathclose{}\right)",
+ ),
+ (
+ "foo",
+ "(u + v)",
+ r"\mathrm{foo} \cdot \mathopen{}\left( u + v \mathclose{}\right)",
+ ),
+ ("f(x)", "3", r"f \mathopen{}\left( x \mathclose{}\right) \cdot 3"),
+ ("f(x)", "y", r"f \mathopen{}\left( x \mathclose{}\right) \cdot y"),
+ ("f(x)", "beta", r"f \mathopen{}\left( x \mathclose{}\right) \cdot \beta"),
+ (
+ "f(x)",
+ "bar",
+ r"f \mathopen{}\left( x \mathclose{}\right) \cdot \mathrm{bar}",
+ ),
+ (
+ "f(x)",
+ "g(y)",
+ r"f \mathopen{}\left( x \mathclose{}\right)"
+ r" \cdot g \mathopen{}\left( y \mathclose{}\right)",
+ ),
+ (
+ "f(x)",
+ "(u + v)",
+ r"f \mathopen{}\left( x \mathclose{}\right)"
+ r" \cdot \mathopen{}\left( u + v \mathclose{}\right)",
+ ),
+ ("(s + t)", "3", r"\mathopen{}\left( s + t \mathclose{}\right) \cdot 3"),
+ ("(s + t)", "y", r"\mathopen{}\left( s + t \mathclose{}\right) y"),
+ ("(s + t)", "beta", r"\mathopen{}\left( s + t \mathclose{}\right) \beta"),
+ (
+ "(s + t)",
+ "bar",
+ r"\mathopen{}\left( s + t \mathclose{}\right) \mathrm{bar}",
+ ),
+ (
+ "(s + t)",
+ "g(y)",
+ r"\mathopen{}\left( s + t \mathclose{}\right)"
+ r" g \mathopen{}\left( y \mathclose{}\right)",
+ ),
+ (
+ "(s + t)",
+ "(u + v)",
+ r"\mathopen{}\left( s + t \mathclose{}\right)"
+ r" \mathopen{}\left( u + v \mathclose{}\right)",
+ ),
+ ],
+)
+def test_remove_multiply(left: str, right: str, latex: str) -> None:
+ for op in ["*", "@"]:
+ tree = ast_utils.parse_expr(f"{left} {op} {right}")
+ assert isinstance(tree, ast.BinOp)
+ assert (
+ expression_codegen.ExpressionCodegen(use_math_symbols=True).visit(tree)
+ == latex
+ )
diff --git a/src/latexify/codegen/function_codegen_match_test.py b/src/latexify/codegen/function_codegen_match_test.py
index 2467f94..87594ec 100644
--- a/src/latexify/codegen/function_codegen_match_test.py
+++ b/src/latexify/codegen/function_codegen_match_test.py
@@ -29,7 +29,7 @@ def test_functiondef_match() -> None:
r"f(x) ="
r" \left\{ \begin{array}{ll}"
r" 1, & \mathrm{if} \ x = 0 \\"
- r" 3 \cdot x, & \mathrm{otherwise}"
+ r" 3 x, & \mathrm{otherwise}"
r" \end{array} \right."
)
assert function_codegen.FunctionCodegen().visit(tree) == expected
diff --git a/src/latexify/generate_latex_test.py b/src/latexify/generate_latex_test.py
index e9df79e..6f128b0 100644
--- a/src/latexify/generate_latex_test.py
+++ b/src/latexify/generate_latex_test.py
@@ -11,8 +11,8 @@ def test_get_latex_identifiers() -> None:
identifiers = {"myfn": "f", "myvar": "x"}
- latex_without_flag = r"\mathrm{myfn}(\mathrm{myvar}) = 3 \cdot \mathrm{myvar}"
- latex_with_flag = r"f(x) = 3 \cdot x"
+ latex_without_flag = r"\mathrm{myfn}(\mathrm{myvar}) = 3 \mathrm{myvar}"
+ latex_with_flag = r"f(x) = 3 x"
assert generate_latex.get_latex(myfn) == latex_without_flag
assert generate_latex.get_latex(myfn, identifiers=identifiers) == latex_with_flag
@@ -46,8 +46,8 @@ def test_get_latex_reduce_assignments() -> None:
y = 3 * x
return y
- latex_without_flag = r"\begin{array}{l} y = 3 \cdot x \\ f(x) = y \end{array}"
- latex_with_flag = r"f(x) = 3 \cdot x"
+ latex_without_flag = r"\begin{array}{l} y = 3 x \\ f(x) = y \end{array}"
+ latex_with_flag = r"f(x) = 3 x"
assert generate_latex.get_latex(f) == latex_without_flag
assert generate_latex.get_latex(f, reduce_assignments=False) == latex_without_flag
|
Wrong behavior around multiplication
The current implementation converts `a * b` into $ab$. This only works if the variables have only 1 character and doesn't generate a correct syntax for other cases:
* Long names: `abc * def` --> $abcdef$, which is hard to distinguish from other combination of variables.
* Unary operators: `x * -y` --> $x - y$, which is definitely wrong.
These cases require explicit multiply operator ( $\cdot$ or $\times$ ) between the operands.
I think the `Mult(left, right)` subtree should be converted to $left \cdot right$ *by default*, and try to avoid the operator only in the following cases:
- The left-hand side operand is a single character or a bracket (with or without unary operators and/or super/subscripts)
- The right-hand side operand is a single character or a bracket (with or without super/subscripts, *without* unary operators)
This requires fine-graind name processing, and may be applied after #82.
|
0.0
|
37d47c98b044135fa0e7d33c18774b7e6b816763
|
[
"src/integration_tests/algorithmic_style_test.py::test_collatz",
"src/integration_tests/regression_test.py::test_quadratic_solution",
"src/integration_tests/regression_test.py::test_x_times_beta",
"src/integration_tests/regression_test.py::test_nested_function",
"src/integration_tests/regression_test.py::test_double_nested_function",
"src/integration_tests/regression_test.py::test_reduce_assignments",
"src/integration_tests/regression_test.py::test_reduce_assignments_double",
"src/integration_tests/regression_test.py::test_sub_bracket",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**y",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**(y",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-y-2",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-beta-2",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-bar-2",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-g(y)-2",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-(u",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-y-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-beta-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-y-\\\\alpha",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-beta-\\\\alpha",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[(s",
"src/latexify/generate_latex_test.py::test_get_latex_identifiers",
"src/latexify/generate_latex_test.py::test_get_latex_reduce_assignments"
] |
[
"src/integration_tests/algorithmic_style_test.py::test_factorial",
"src/integration_tests/regression_test.py::test_sinc",
"src/integration_tests/regression_test.py::test_sum_with_limit_1arg",
"src/integration_tests/regression_test.py::test_sum_with_limit_2args",
"src/integration_tests/regression_test.py::test_sum_with_reducible_limit",
"src/integration_tests/regression_test.py::test_sum_with_irreducible_limit",
"src/integration_tests/regression_test.py::test_prod_with_limit_1arg",
"src/integration_tests/regression_test.py::test_prod_with_limit_2args",
"src/integration_tests/regression_test.py::test_prod_with_reducible_limits",
"src/integration_tests/regression_test.py::test_prod_with_irreducible_limit",
"src/integration_tests/regression_test.py::test_reduce_assignments_with_if",
"src/integration_tests/regression_test.py::test_docstring_allowed",
"src/integration_tests/regression_test.py::test_multiple_constants_allowed",
"src/latexify/codegen/expression_codegen_test.py::test_generic_visit",
"src/latexify/codegen/expression_codegen_test.py::test_visit_tuple[()-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_tuple[(x,)-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_tuple[(x,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_list[[]-\\\\mathopen{}\\\\left[",
"src/latexify/codegen/expression_codegen_test.py::test_visit_list[[x]-\\\\mathopen{}\\\\left[",
"src/latexify/codegen/expression_codegen_test.py::test_visit_list[[x,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_set[{x}-\\\\mathopen{}\\\\left\\\\{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_set[{x,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_listcomp[[i",
"src/latexify/codegen/expression_codegen_test.py::test_visit_setcomp[{i",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[foo(x)-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(x)-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(-x)-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(f(x))-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(sqrt(x))-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(sin(x))-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(factorial(x))-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(x,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(x)-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(-x)-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(f(x))-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(sqrt(x))-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(sin(x))-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(factorial(x))-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(x)-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(-x)-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(f(x))-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(sqrt(x))-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(sin(x))-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(factorial(x))-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(x)-x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(-x)-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(f(x))-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(sqrt(x))-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(sin(x))-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(factorial(x))-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[(x)-",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[([1,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[({1,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[(f(x))-",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[(i",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod_multiple_comprehension[sum(i",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod_multiple_comprehension[prod(i",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod_with_if[(i",
"src/latexify/codegen/expression_codegen_test.py::test_if_then_else[x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**y-x^{y}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[(x**y)**z-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**(y**z)-x^{y^{z}}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**f(y)-x^{f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[f(x)**y-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[f(x)",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[sqrt(x)",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**-y-x^{-y}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[(-x)**y-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[+x-+x]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[-x--x]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[~x-\\\\mathord{\\\\sim}",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[not",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[+f(x)-+f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[-f(x)--f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[~f(x)-\\\\mathord{\\\\sim}",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[+(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[-(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[~(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare[a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare[f(a)",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare[-a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare[(not",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare[(a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_boolop[a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_boolop[(a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_boolop[f(a)",
"src/latexify/codegen/expression_codegen_test.py::test_visit_boolop[not",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[0-Num-0]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[1-Num-1]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[0.0-Num-0.0]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[1.5-Num-1.5]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[0.0j-Num-0j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[1.0j-Num-1j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[1.5j-Num-1.5j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[\"abc\"-Str-\\\\textrm{\"abc\"}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[b\"abc\"-Bytes-\\\\textrm{b'abc'}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[None-NameConstant-\\\\mathrm{None}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[False-NameConstant-\\\\mathrm{False}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[True-NameConstant-\\\\mathrm{True}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[...-Ellipsis-\\\\cdots]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[0-0]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[1-1]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[0.0-0.0]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[1.5-1.5]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[0.0j-0j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[1.0j-1j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[1.5j-1.5j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[\"abc\"-\\\\textrm{\"abc\"}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[b\"abc\"-\\\\textrm{b'abc'}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[None-\\\\mathrm{None}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[False-\\\\mathrm{False}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[True-\\\\mathrm{True}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[...-\\\\cdots]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_subscript[x[0]-x_{0}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_subscript[x[0][1]-x_{0,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_subscript[x[0][1][2]-x_{0,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_subscript[x[foo]-x_{\\\\mathrm{foo}}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_subscript[x[floor(x)]-x_{\\\\mathopen{}\\\\left\\\\lfloor",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop_use_set_symbols[a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare_use_set_symbols[a",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array(1)-\\\\mathrm{array}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([])-\\\\mathrm{array}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([1])-\\\\begin{bmatrix}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([1,",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([[]])-\\\\mathrm{array}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([[1]])-\\\\begin{bmatrix}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([[1],",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([[1,",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[ndarray(1)-\\\\mathrm{ndarray}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[ndarray([1])-\\\\begin{bmatrix}",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(0)-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(1)-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(2)-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(())-0]",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((0,))-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((1,))-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((2,))-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((0,",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((1,",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((2,",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros()-\\\\mathrm{zeros}",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(x)-\\\\mathrm{zeros}",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(0,",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((x,))-\\\\mathrm{zeros}",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity(0)-\\\\mathbf{I}_{0}]",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity(1)-\\\\mathbf{I}_{1}]",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity(2)-\\\\mathbf{I}_{2}]",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity()-\\\\mathrm{identity}",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity(x)-\\\\mathrm{identity}",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity(0,",
"src/latexify/codegen/expression_codegen_test.py::test_transpose[transpose(A)-\\\\mathbf{A}^\\\\intercal]",
"src/latexify/codegen/expression_codegen_test.py::test_transpose[transpose(b)-\\\\mathbf{b}^\\\\intercal]",
"src/latexify/codegen/expression_codegen_test.py::test_transpose[transpose()-\\\\mathrm{transpose}",
"src/latexify/codegen/expression_codegen_test.py::test_transpose[transpose(2)-\\\\mathrm{transpose}",
"src/latexify/codegen/expression_codegen_test.py::test_transpose[transpose(a,",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-3-2",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-3-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-bar-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-g(y)-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-(u",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-3-\\\\alpha",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-bar-\\\\alpha",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-g(y)-\\\\alpha",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-(u",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-3-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-y-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-beta-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-bar-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-g(y)-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-(u",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-3-f",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-y-f",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-beta-f",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-bar-f",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-g(y)-f",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-(u",
"src/latexify/codegen/function_codegen_match_test.py::test_functiondef_match",
"src/latexify/codegen/function_codegen_match_test.py::test_matchvalue",
"src/latexify/codegen/function_codegen_match_test.py::test_multiple_matchvalue",
"src/latexify/codegen/function_codegen_match_test.py::test_single_matchvalue_no_wildcards",
"src/latexify/codegen/function_codegen_match_test.py::test_multiple_matchvalue_no_wildcards",
"src/latexify/codegen/function_codegen_match_test.py::test_matchas_nonempty",
"src/latexify/codegen/function_codegen_match_test.py::test_matchvalue_no_return",
"src/latexify/codegen/function_codegen_match_test.py::test_matchvalue_mutliple_statements",
"src/latexify/generate_latex_test.py::test_get_latex_prefixes",
"src/latexify/generate_latex_test.py::test_get_latex_use_math_symbols",
"src/latexify/generate_latex_test.py::test_get_latex_use_signature",
"src/latexify/generate_latex_test.py::test_get_latex_use_set_symbols"
] |
{
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-15 20:10:19+00:00
|
apache-2.0
| 2,574 |
|
google__latexify_py-195
|
diff --git a/src/latexify/codegen/expression_codegen.py b/src/latexify/codegen/expression_codegen.py
index f88869c..9239d72 100644
--- a/src/latexify/codegen/expression_codegen.py
+++ b/src/latexify/codegen/expression_codegen.py
@@ -408,16 +408,22 @@ class ExpressionCodegen(ast.NodeVisitor):
if rule.is_unary and len(node.args) == 1:
# Unary function. Applies the same wrapping policy with the unary operators.
+ precedence = expression_rules.get_precedence(node)
+ arg = node.args[0]
# NOTE(odashi):
# Factorial "x!" is treated as a special case: it requires both inner/outer
# parentheses for correct interpretation.
- precedence = expression_rules.get_precedence(node)
- arg = node.args[0]
- force_wrap = isinstance(arg, ast.Call) and (
+ force_wrap_factorial = isinstance(arg, ast.Call) and (
func_name == "factorial"
or ast_utils.extract_function_name_or_none(arg) == "factorial"
)
- arg_latex = self._wrap_operand(arg, precedence, force_wrap)
+ # Note(odashi):
+ # Wrapping is also required if the argument is pow.
+ # https://github.com/google/latexify_py/issues/189
+ force_wrap_pow = isinstance(arg, ast.BinOp) and isinstance(arg.op, ast.Pow)
+ arg_latex = self._wrap_operand(
+ arg, precedence, force_wrap_factorial or force_wrap_pow
+ )
elements = [rule.left, arg_latex, rule.right]
else:
arg_latex = ", ".join(self.visit(arg) for arg in node.args)
@@ -490,7 +496,7 @@ class ExpressionCodegen(ast.NodeVisitor):
latex = self.visit(child)
child_prec = expression_rules.get_precedence(child)
- if child_prec < parent_prec or force_wrap and child_prec == parent_prec:
+ if force_wrap or child_prec < parent_prec:
return rf"\mathopen{{}}\left( {latex} \mathclose{{}}\right)"
return latex
|
google/latexify_py
|
1cfb8e78527cb8e13dc647e9c8d91f789a427402
|
diff --git a/src/latexify/codegen/expression_codegen_test.py b/src/latexify/codegen/expression_codegen_test.py
index 8ed960b..e869777 100644
--- a/src/latexify/codegen/expression_codegen_test.py
+++ b/src/latexify/codegen/expression_codegen_test.py
@@ -218,6 +218,25 @@ def test_visit_call(code: str, latex: str) -> None:
assert expression_codegen.ExpressionCodegen().visit(node) == latex
[email protected](
+ "code,latex",
+ [
+ ("log(x)**2", r"\mathopen{}\left( \log x \mathclose{}\right)^{2}"),
+ ("log(x**2)", r"\log \mathopen{}\left( x^{2} \mathclose{}\right)"),
+ (
+ "log(x**2)**3",
+ r"\mathopen{}\left("
+ r" \log \mathopen{}\left( x^{2} \mathclose{}\right)"
+ r" \mathclose{}\right)^{3}",
+ ),
+ ],
+)
+def test_visit_call_with_pow(code: str, latex: str) -> None:
+ node = ast_utils.parse_expr(code)
+ assert isinstance(node, (ast.Call, ast.BinOp))
+ assert expression_codegen.ExpressionCodegen().visit(node) == latex
+
+
@pytest.mark.parametrize(
"src_suffix,dest_suffix",
[
|
Counterintuitive (wrong?) parenthesis when combining exp() and powers
## Description
When you latexify something like log((x/c)^2), the rendering you get looks (to me at least) like it's log(x/c)^2:
<img width="333" alt="image" src="https://github.com/google/latexify_py/assets/889526/c4c7a979-d5f1-459c-9957-daecbf6fd405">
In contrast, Wolfram Alpha for example will insert extra parens to disambiguate this case.
<img width="292" alt="image" src="https://github.com/google/latexify_py/assets/889526/28311362-6ed8-4911-a572-48cdee621280">
## Reproduction
Describe how to reproduce the issue by other people.
```
@latexify.function()
def f(x, c):
return np.log((x/c)**2)
f
```
|
0.0
|
1cfb8e78527cb8e13dc647e9c8d91f789a427402
|
[
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_with_pow[log(x**2)-\\\\log",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_with_pow[log(x**2)**3-\\\\mathopen{}\\\\left("
] |
[
"src/latexify/codegen/expression_codegen_test.py::test_generic_visit",
"src/latexify/codegen/expression_codegen_test.py::test_visit_tuple[()-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_tuple[(x,)-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_tuple[(x,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_list[[]-\\\\mathopen{}\\\\left[",
"src/latexify/codegen/expression_codegen_test.py::test_visit_list[[x]-\\\\mathopen{}\\\\left[",
"src/latexify/codegen/expression_codegen_test.py::test_visit_list[[x,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_set[{x}-\\\\mathopen{}\\\\left\\\\{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_set[{x,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_listcomp[[i",
"src/latexify/codegen/expression_codegen_test.py::test_visit_setcomp[{i",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[foo(x)-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(x)-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(-x)-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(f(x))-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(sqrt(x))-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(sin(x))-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(factorial(x))-f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[f(x,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(x)-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(-x)-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(f(x))-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(sqrt(x))-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(sin(x))-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sqrt(factorial(x))-\\\\sqrt{",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(x)-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(-x)-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(f(x))-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(sqrt(x))-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(sin(x))-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[sin(factorial(x))-\\\\sin",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(x)-x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(-x)-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(f(x))-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(sqrt(x))-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(sin(x))-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call[factorial(factorial(x))-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_with_pow[log(x)**2-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[()-",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[(x)-",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[([1,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[({1,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[(f(x))-",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod[(i",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod_multiple_comprehension[sum(i",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod_multiple_comprehension[prod(i",
"src/latexify/codegen/expression_codegen_test.py::test_visit_call_sum_prod_with_if[(i",
"src/latexify/codegen/expression_codegen_test.py::test_if_then_else[x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**y-x^{y}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[(x**y)**z-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**(y**z)-x^{y^{z}}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**y",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**(y",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**f(y)-x^{f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[f(x)**y-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[f(x)",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[sqrt(x)",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[x**-y-x^{-y}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[(-x)**y-\\\\mathopen{}\\\\left(",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop[-x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[+x-+x]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[-x--x]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[~x-\\\\mathord{\\\\sim}",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[not",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[+f(x)-+f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[-f(x)--f",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[~f(x)-\\\\mathord{\\\\sim}",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[+(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[-(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_unaryop[~(x",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare[a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare[f(a)",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare[-a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare[(not",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare[(a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_boolop[a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_boolop[(a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_boolop[f(a)",
"src/latexify/codegen/expression_codegen_test.py::test_visit_boolop[not",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[0-Num-0]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[1-Num-1]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[0.0-Num-0.0]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[1.5-Num-1.5]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[0.0j-Num-0j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[1.0j-Num-1j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[1.5j-Num-1.5j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[\"abc\"-Str-\\\\textrm{\"abc\"}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[b\"abc\"-Bytes-\\\\textrm{b'abc'}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[None-NameConstant-\\\\mathrm{None}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[False-NameConstant-\\\\mathrm{False}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[True-NameConstant-\\\\mathrm{True}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant_lagacy[...-Ellipsis-\\\\cdots]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[0-0]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[1-1]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[0.0-0.0]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[1.5-1.5]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[0.0j-0j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[1.0j-1j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[1.5j-1.5j]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[\"abc\"-\\\\textrm{\"abc\"}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[b\"abc\"-\\\\textrm{b'abc'}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[None-\\\\mathrm{None}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[False-\\\\mathrm{False}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[True-\\\\mathrm{True}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_constant[...-\\\\cdots]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_subscript[x[0]-x_{0}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_subscript[x[0][1]-x_{0,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_subscript[x[0][1][2]-x_{0,",
"src/latexify/codegen/expression_codegen_test.py::test_visit_subscript[x[foo]-x_{\\\\mathrm{foo}}]",
"src/latexify/codegen/expression_codegen_test.py::test_visit_subscript[x[floor(x)]-x_{\\\\mathopen{}\\\\left\\\\lfloor",
"src/latexify/codegen/expression_codegen_test.py::test_visit_binop_use_set_symbols[a",
"src/latexify/codegen/expression_codegen_test.py::test_visit_compare_use_set_symbols[a",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array(1)-\\\\mathrm{array}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([])-\\\\mathrm{array}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([1])-\\\\begin{bmatrix}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([1,",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([[]])-\\\\mathrm{array}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([[1]])-\\\\begin{bmatrix}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([[1],",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[array([[1,",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[ndarray(1)-\\\\mathrm{ndarray}",
"src/latexify/codegen/expression_codegen_test.py::test_numpy_array[ndarray([1])-\\\\begin{bmatrix}",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(0)-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(1)-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(2)-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(())-0]",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((0,))-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((1,))-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((2,))-\\\\mathbf{0}^{1",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((0,",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((1,",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((2,",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros()-\\\\mathrm{zeros}",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(x)-\\\\mathrm{zeros}",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros(0,",
"src/latexify/codegen/expression_codegen_test.py::test_zeros[zeros((x,))-\\\\mathrm{zeros}",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity(0)-\\\\mathbf{I}_{0}]",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity(1)-\\\\mathbf{I}_{1}]",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity(2)-\\\\mathbf{I}_{2}]",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity()-\\\\mathrm{identity}",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity(x)-\\\\mathrm{identity}",
"src/latexify/codegen/expression_codegen_test.py::test_identity[identity(0,",
"src/latexify/codegen/expression_codegen_test.py::test_transpose[transpose(A)-\\\\mathbf{A}^\\\\intercal]",
"src/latexify/codegen/expression_codegen_test.py::test_transpose[transpose(b)-\\\\mathbf{b}^\\\\intercal]",
"src/latexify/codegen/expression_codegen_test.py::test_transpose[transpose()-\\\\mathrm{transpose}",
"src/latexify/codegen/expression_codegen_test.py::test_transpose[transpose(2)-\\\\mathrm{transpose}",
"src/latexify/codegen/expression_codegen_test.py::test_transpose[transpose(a,",
"src/latexify/codegen/expression_codegen_test.py::test_determinant[det(A)-\\\\det",
"src/latexify/codegen/expression_codegen_test.py::test_determinant[det(b)-\\\\det",
"src/latexify/codegen/expression_codegen_test.py::test_determinant[det([[1,",
"src/latexify/codegen/expression_codegen_test.py::test_determinant[det()-\\\\mathrm{det}",
"src/latexify/codegen/expression_codegen_test.py::test_determinant[det(2)-\\\\mathrm{det}",
"src/latexify/codegen/expression_codegen_test.py::test_determinant[det(a,",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_rank[matrix_rank(A)-\\\\mathrm{rank}",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_rank[matrix_rank(b)-\\\\mathrm{rank}",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_rank[matrix_rank([[1,",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_rank[matrix_rank()-\\\\mathrm{matrix\\\\_rank}",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_rank[matrix_rank(2)-\\\\mathrm{matrix\\\\_rank}",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_rank[matrix_rank(a,",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_power[matrix_power(A,",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_power[matrix_power(b,",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_power[matrix_power([[1,",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_power[matrix_power()-\\\\mathrm{matrix\\\\_power}",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_power[matrix_power(2)-\\\\mathrm{matrix\\\\_power}",
"src/latexify/codegen/expression_codegen_test.py::test_matrix_power[matrix_power(a,",
"src/latexify/codegen/expression_codegen_test.py::test_inv[inv(A)-\\\\mathbf{A}^{-1}]",
"src/latexify/codegen/expression_codegen_test.py::test_inv[inv(b)-\\\\mathbf{b}^{-1}]",
"src/latexify/codegen/expression_codegen_test.py::test_inv[inv([[1,",
"src/latexify/codegen/expression_codegen_test.py::test_inv[inv()-\\\\mathrm{inv}",
"src/latexify/codegen/expression_codegen_test.py::test_inv[inv(2)-\\\\mathrm{inv}",
"src/latexify/codegen/expression_codegen_test.py::test_inv[inv(a,",
"src/latexify/codegen/expression_codegen_test.py::test_pinv[pinv(A)-\\\\mathbf{A}^{+}]",
"src/latexify/codegen/expression_codegen_test.py::test_pinv[pinv(b)-\\\\mathbf{b}^{+}]",
"src/latexify/codegen/expression_codegen_test.py::test_pinv[pinv([[1,",
"src/latexify/codegen/expression_codegen_test.py::test_pinv[pinv()-\\\\mathrm{pinv}",
"src/latexify/codegen/expression_codegen_test.py::test_pinv[pinv(2)-\\\\mathrm{pinv}",
"src/latexify/codegen/expression_codegen_test.py::test_pinv[pinv(a,",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-3-2",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-y-2",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-beta-2",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-bar-2",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-g(y)-2",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[2-(u",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-3-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-y-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-beta-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-bar-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-g(y)-x",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[x-(u",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-3-\\\\alpha",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-y-\\\\alpha",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-beta-\\\\alpha",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-bar-\\\\alpha",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-g(y)-\\\\alpha",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[alpha-(u",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-3-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-y-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-beta-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-bar-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-g(y)-\\\\mathrm{foo}",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[foo-(u",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-3-f",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-y-f",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-beta-f",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-bar-f",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-g(y)-f",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[f(x)-(u",
"src/latexify/codegen/expression_codegen_test.py::test_remove_multiply[(s"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-11-18 21:31:54+00:00
|
apache-2.0
| 2,575 |
|
google__latexify_py-47
|
diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml
index 1e6ed35..ed4cc7c 100644
--- a/.github/workflows/python-package.yml
+++ b/.github/workflows/python-package.yml
@@ -24,7 +24,7 @@ jobs:
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"
- name: Test
- run: python -m pytest tests
+ run: python -m pytest src
black:
runs-on: ubuntu-latest
@@ -39,7 +39,7 @@ jobs:
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"
- name: Check
- run: python -m black src tests
+ run: python -m black src
flake8:
runs-on: ubuntu-latest
@@ -54,4 +54,4 @@ jobs:
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"
- name: Check
- run: python -m pflake8 src tests
+ run: python -m pflake8 src
diff --git a/checks.sh b/checks.sh
new file mode 100755
index 0000000..205bf86
--- /dev/null
+++ b/checks.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+set -eoux pipefail
+
+python -m pytest src
+python -m black src
+python -m pflake8 src
diff --git a/src/latexify/core.py b/src/latexify/core.py
index bc50596..8a9f0d1 100644
--- a/src/latexify/core.py
+++ b/src/latexify/core.py
@@ -17,6 +17,7 @@
import ast
import inspect
+import textwrap
import dill
@@ -307,6 +308,8 @@ def get_latex(fn, *args, **kwargs):
# Maybe running on console.
source = dill.source.getsource(fn)
+ source = textwrap.dedent(source)
+
return LatexifyVisitor(*args, **kwargs).visit(ast.parse(source))
|
google/latexify_py
|
7870485ace214d937be1a8c8138a6b36dc2f2ca7
|
diff --git a/src/integration_tests/regression_test.py b/src/integration_tests/regression_test.py
index 9ff8b8d..7a2f432 100644
--- a/src/integration_tests/regression_test.py
+++ b/src/integration_tests/regression_test.py
@@ -16,7 +16,7 @@
import math
import pytest
-from latexify import with_latex
+from latexify import get_latex, with_latex
def solve(a, b, c):
@@ -91,3 +91,20 @@ def test_with_latex_to_str(func, expected_latex, math_symbol):
assert str(latexified_function) == expected_latex
expected_repr = r"$$ \displaystyle %s $$" % expected_latex
assert latexified_function._repr_latex_() == expected_repr
+
+
+def test_nested_function():
+ def nested(x):
+ return 3 * x
+
+ assert get_latex(nested) == r"\mathrm{nested}(x) \triangleq 3x"
+
+
+def test_double_nested_function():
+ def nested(x):
+ def inner(y):
+ return x * y
+
+ return inner
+
+ assert get_latex(nested(3)) == r"\mathrm{inner}(y) \triangleq xy"
|
Support for nested functions
As an example use case, I have a function that takes in a dataset and returns a closure based on that dataset.
```python
def gen_normalizer(df):
def normalize_row_based_on_dataset(row):
return (row - df.mean()) / df.std()
return normalize_row_based_on_dataset
```
I would love to be able to apply the decorator to the nested function so that later in my experiment I can display a set of different Normalizers in LaTeX. However, currently adding the decorator to the nested function results in the following error:
```python
File <unknown>:1
@latexify.with_latex
^
IndentationError: unexpected indent
```
|
0.0
|
7870485ace214d937be1a8c8138a6b36dc2f2ca7
|
[
"src/integration_tests/regression_test.py::test_nested_function",
"src/integration_tests/regression_test.py::test_double_nested_function"
] |
[
"src/integration_tests/regression_test.py::test_with_latex_to_str[solve-\\\\mathrm{solve}(a,",
"src/integration_tests/regression_test.py::test_with_latex_to_str[sinc-\\\\mathrm{sinc}(x)",
"src/integration_tests/regression_test.py::test_with_latex_to_str[xtimesbeta-\\\\mathrm{xtimesbeta}(x,",
"src/integration_tests/regression_test.py::test_with_latex_to_str[sum_with_limit-\\\\mathrm{sum_with_limit}(n)",
"src/integration_tests/regression_test.py::test_with_latex_to_str[sum_with_limit_two_args-\\\\mathrm{sum_with_limit_two_args}(a,"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-09 11:54:29+00:00
|
apache-2.0
| 2,576 |
|
google__latexify_py-64
|
diff --git a/src/latexify/frontend.py b/src/latexify/frontend.py
index 380a200..5894b82 100644
--- a/src/latexify/frontend.py
+++ b/src/latexify/frontend.py
@@ -11,25 +11,32 @@ from typing import Any
import dill
from latexify import latexify_visitor
+from latexify.transformers.identifier_replacer import IdentifierReplacer
def get_latex(
fn: Callable[..., Any],
*,
+ identifiers: dict[str, str] | None = None,
+ reduce_assignments: bool = False,
use_math_symbols: bool = False,
use_raw_function_name: bool = False,
- reduce_assignments: bool = False,
) -> str:
"""Obtains LaTeX description from the function's source.
Args:
fn: Reference to a function to analyze.
+ identifiers: If set, the mapping to replace identifier names in the function.
+ Keys are the original names of the identifiers, and corresponding values are
+ the replacements.
+ Both keys and values have to represent valid Python identifiers:
+ ^[A-Za-z_][A-Za-z0-9_]*$
+ reduce_assignments: If True, assignment statements are used to synthesize
+ the final expression.
use_math_symbols: Whether to convert identifiers with a math symbol surface
(e.g., "alpha") to the LaTeX symbol (e.g., "\\alpha").
use_raw_function_name: Whether to keep underscores "_" in the function name,
or convert it to subscript.
- reduce_assignments: If True, assignment statements are used to synthesize
- the final expression.
Returns:
Generatee LaTeX description.
@@ -45,6 +52,9 @@ def get_latex(
tree = ast.parse(source)
+ if identifiers is not None:
+ tree = IdentifierReplacer(identifiers).visit(tree)
+
visitor = latexify_visitor.LatexifyVisitor(
use_math_symbols=use_math_symbols,
use_raw_function_name=use_raw_function_name,
diff --git a/src/latexify/latexify_visitor.py b/src/latexify/latexify_visitor.py
index d271457..476d1ef 100644
--- a/src/latexify/latexify_visitor.py
+++ b/src/latexify/latexify_visitor.py
@@ -23,19 +23,19 @@ class LatexifyVisitor(node_visitor_base.NodeVisitorBase):
def __init__(
self,
*,
+ reduce_assignments: bool = True,
use_math_symbols: bool = False,
use_raw_function_name: bool = False,
- reduce_assignments: bool = True,
):
"""Initializer.
Args:
+ reduce_assignments: If True, assignment statements are used to synthesize
+ the final expression.
use_math_symbols: Whether to convert identifiers with a math symbol surface
(e.g., "alpha") to the LaTeX symbol (e.g., "\\alpha").
use_raw_function_name: Whether to keep underscores "_" in the function name,
or convert it to subscript.
- reduce_assignments: If True, assignment statements are used to synthesize
- the final expression.
"""
self._math_symbol_converter = math_symbols.MathSymbolConverter(
enabled=use_math_symbols
diff --git a/src/latexify/transformers/__init__.py b/src/latexify/transformers/__init__.py
new file mode 100644
index 0000000..005a0d2
--- /dev/null
+++ b/src/latexify/transformers/__init__.py
@@ -0,0 +1,1 @@
+"""Package latexify.transformers."""
diff --git a/src/latexify/transformers/identifier_replacer.py b/src/latexify/transformers/identifier_replacer.py
new file mode 100644
index 0000000..3e7f903
--- /dev/null
+++ b/src/latexify/transformers/identifier_replacer.py
@@ -0,0 +1,84 @@
+"""Transformer to replace user symbols."""
+
+from __future__ import annotations
+
+import ast
+import re
+import sys
+from typing import ClassVar
+
+
+class IdentifierReplacer(ast.NodeTransformer):
+ """NodeTransformer to replace identifier names.
+
+ This class defines a rule to replace identifiers in AST with specified names.
+
+ Example:
+ def foo(bar):
+ return baz
+
+ IdentifierReplacer({"foo": "x", "bar": "y", "baz": "z"}) will modify the AST of
+ the function above to below:
+
+ def x(y):
+ return z
+ """
+
+ _IDENTIFIER_PATTERN: ClassVar[re.Pattern] = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+
+ def __init__(self, mapping: dict[str, str]):
+ """Initializer.
+
+ Args:
+ mapping: User defined mapping of names. Keys are the original names of the
+ identifiers, and corresponding values are the replacements.
+ Both keys and values have to represent valid Python identifiers:
+ ^[A-Za-z_][A-Za-z0-9_]*$
+ """
+ self._mapping = mapping
+
+ for k, v in self._mapping.items():
+ if not self._IDENTIFIER_PATTERN.match(k):
+ raise ValueError(f"'{k}' is not an identifier name.")
+ if not self._IDENTIFIER_PATTERN.match(v):
+ raise ValueError(f"'{v}' is not an identifier name.")
+
+ def _replace_args(self, args: list[ast.arg]) -> list[ast.arg]:
+ """Helper function to replace arg names."""
+ return [ast.arg(arg=self._mapping.get(a.arg, a.arg)) for a in args]
+
+ def _visit_children(self, children: list[ast.AST]) -> list[ast.AST]:
+ """Helper function to visit all children."""
+ return [self.visit(child) for child in children]
+
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
+ """Visitor of FunctionDef."""
+ if sys.version_info.minor < 8:
+ args = ast.arguments(
+ args=self._replace_args(node.args.args),
+ kwonlyargs=self._replace_args(node.args.kwonlyargs),
+ kw_defaults=self._visit_children(node.args.kw_defaults),
+ defaults=self._visit_children(node.args.defaults),
+ )
+ else:
+ args = ast.arguments(
+ posonlyargs=self._replace_args(node.args.posonlyargs), # from 3.8
+ args=self._replace_args(node.args.args),
+ kwonlyargs=self._replace_args(node.args.kwonlyargs),
+ kw_defaults=self._visit_children(node.args.kw_defaults),
+ defaults=self._visit_children(node.args.defaults),
+ )
+
+ return ast.FunctionDef(
+ name=self._mapping.get(node.name, node.name),
+ args=args,
+ body=self._visit_children(node.body),
+ decorator_list=self._visit_children(node.decorator_list),
+ )
+
+ def visit_Name(self, node: ast.Name) -> ast.Name:
+ """Visitor of Name."""
+ return ast.Name(
+ id=self._mapping.get(node.id, node.id),
+ ctx=node.ctx,
+ )
|
google/latexify_py
|
4ff77b4e0939a458201f082133b3f3cb8cfba5fe
|
diff --git a/src/latexify/frontend_test.py b/src/latexify/frontend_test.py
new file mode 100644
index 0000000..91a9d30
--- /dev/null
+++ b/src/latexify/frontend_test.py
@@ -0,0 +1,19 @@
+"""Tests for latexify.frontend."""
+
+from __future__ import annotations
+
+from latexify import frontend
+
+
+def test_identifiers() -> None:
+ def very_long_name_function(very_long_name_variable):
+ return 3 * very_long_name_variable
+
+ identifiers = {
+ "very_long_name_function": "f",
+ "very_long_name_variable": "x",
+ }
+
+ assert frontend.get_latex(very_long_name_function, identifiers=identifiers) == (
+ r"\mathrm{f}(x) \triangleq 3x"
+ )
diff --git a/src/latexify/test_utils.py b/src/latexify/test_utils.py
new file mode 100644
index 0000000..b45da9b
--- /dev/null
+++ b/src/latexify/test_utils.py
@@ -0,0 +1,59 @@
+"""Test utilities."""
+
+from __future__ import annotations
+
+import ast
+from typing import cast
+
+
+def ast_equal(tree1: ast.AST, tree2: ast.AST) -> bool:
+ """Checks the equality between two ASTs.
+
+ Args:
+ tree1: An AST to compare.
+ tree2: Another AST.
+
+ Returns:
+ True if tree1 and tree2 represent the same AST, False otherwise.
+ """
+ try:
+ assert type(tree1) is type(tree2)
+
+ for k, v1 in vars(tree1).items():
+ v2 = getattr(tree2, k)
+
+ if isinstance(v1, ast.AST):
+ assert ast_equal(v1, cast(ast.AST, v2))
+ elif isinstance(v1, list):
+ v2 = cast(list, v2)
+ assert len(v1) == len(v2)
+ assert all(
+ ast_equal(cast(ast.AST, c1), cast(ast.AST, c2))
+ for c1, c2 in zip(v1, v2)
+ )
+ else:
+ assert v1 == v2
+
+ except AssertionError:
+ return False
+
+ return True
+
+
+def assert_ast_equal(tree1: ast.AST, tree2: ast.AST) -> None:
+ """Asserts the equality between two ASTs.
+
+ Args:
+ tree1: An AST to compare.
+ tree2: Another AST.
+
+ Raises:
+ AssertionError: tree1 and tree2 represent different ASTs.
+ """
+ assert ast_equal(
+ tree1, tree2
+ ), f"""\
+AST does not match.
+tree1={ast.dump(tree1, indent=4)}
+tree2={ast.dump(tree2, indent=4)}
+"""
diff --git a/src/latexify/transformers/identifier_replacer_test.py b/src/latexify/transformers/identifier_replacer_test.py
new file mode 100644
index 0000000..f555b92
--- /dev/null
+++ b/src/latexify/transformers/identifier_replacer_test.py
@@ -0,0 +1,101 @@
+"""Tests for latexify.transformer.identifier_replacer."""
+
+import ast
+
+import pytest
+
+from latexify import test_utils
+from latexify.transformers.identifier_replacer import IdentifierReplacer
+
+
+def test_invalid_mapping() -> None:
+ with pytest.raises(ValueError, match=r"'123' is not an identifier name."):
+ IdentifierReplacer({"123": "foo"})
+ with pytest.raises(ValueError, match=r"'456' is not an identifier name."):
+ IdentifierReplacer({"foo": "456"})
+
+
+def test_name_replaced() -> None:
+ source = ast.Name(id="foo", ctx=ast.Load())
+ expected = ast.Name(id="bar", ctx=ast.Load())
+ transformed = IdentifierReplacer({"foo": "bar"}).visit(source)
+ test_utils.assert_ast_equal(transformed, expected)
+
+
+def test_name_not_replaced() -> None:
+ source = ast.Name(id="foo", ctx=ast.Load())
+ expected = ast.Name(id="foo", ctx=ast.Load())
+ transformed = IdentifierReplacer({"fo": "bar"}).visit(source)
+ test_utils.assert_ast_equal(transformed, expected)
+ transformed = IdentifierReplacer({"fooo": "bar"}).visit(source)
+ test_utils.assert_ast_equal(transformed, expected)
+
+
+def test_functiondef() -> None:
+ # Subtree of:
+ # @d
+ # def f(x=a, /, y=b, *, z=c):
+ # ...
+ source = ast.FunctionDef(
+ name="f",
+ args=ast.arguments(
+ posonlyargs=[ast.arg(arg="x")],
+ args=[ast.arg(arg="y")],
+ kwonlyargs=[ast.arg(arg="z")],
+ kw_defaults=[ast.Name(id="c", ctx=ast.Load())],
+ defaults=[
+ ast.Name(id="a", ctx=ast.Load()),
+ ast.Name(id="b", ctx=ast.Load()),
+ ],
+ ),
+ body=[ast.Ellipsis()],
+ decorator_list=[ast.Name(id="d", ctx=ast.Load())],
+ )
+
+ expected = ast.FunctionDef(
+ name="F",
+ args=ast.arguments(
+ posonlyargs=[ast.arg(arg="X")],
+ args=[ast.arg(arg="Y")],
+ kwonlyargs=[ast.arg(arg="Z")],
+ kw_defaults=[ast.Name(id="C", ctx=ast.Load())],
+ defaults=[
+ ast.Name(id="A", ctx=ast.Load()),
+ ast.Name(id="B", ctx=ast.Load()),
+ ],
+ ),
+ body=[ast.Ellipsis()],
+ decorator_list=[ast.Name(id="D", ctx=ast.Load())],
+ )
+
+ mapping = {x: x.upper() for x in "abcdfxyz"}
+ transformed = IdentifierReplacer(mapping).visit(source)
+ test_utils.assert_ast_equal(transformed, expected)
+
+
+def test_expr() -> None:
+ # Subtree of:
+ # (x + y) * z
+ source = ast.BinOp(
+ left=ast.BinOp(
+ left=ast.Name(id="x", ctx=ast.Load()),
+ op=ast.Add(),
+ right=ast.Name(id="y", ctx=ast.Load()),
+ ),
+ op=ast.Mult(),
+ right=ast.Name(id="z", ctx=ast.Load()),
+ )
+
+ expected = ast.BinOp(
+ left=ast.BinOp(
+ left=ast.Name(id="X", ctx=ast.Load()),
+ op=ast.Add(),
+ right=ast.Name(id="Y", ctx=ast.Load()),
+ ),
+ op=ast.Mult(),
+ right=ast.Name(id="Z", ctx=ast.Load()),
+ )
+
+ mapping = {x: x.upper() for x in "xyz"}
+ transformed = IdentifierReplacer(mapping).visit(source)
+ test_utils.assert_ast_equal(transformed, expected)
|
Support substitutions of names
According to: https://github.com/google/latexify_py/issues/46#issuecomment-1278292646
Currently, latexify uses only the syntax information of the functions wrapped by `with_latex` and the decorator does not know any bound values outside the function. Some people want to substitute identifiers in the function into its actual value. For example:
```python
# Values bound by literals
t = 42
@with_latex
def diff(y):
return y - t
# Values bound by given variables
def wrapper(t):
@with_latex
def diff(y):
return y - t
mydiff = wrapper(42)
```
In both cases the user may want to see [ $diff(y) \triangleq y - 42$ ], not [ $diff(y) \triangleq y - t$ ].
I think implementing additional parameter to `with_latex` to specify substitutions, for example:
```python
@with_latex(substitutions={"t": t})
def diff(y):
...
```
is a handy solution at this moment, though users are required to write some additional stuff. To implement it, we need to define a substitution rule in the AST visitor that replaces matched identifiers to given strings (or any values that can be converted into a string).
|
0.0
|
4ff77b4e0939a458201f082133b3f3cb8cfba5fe
|
[
"src/latexify/frontend_test.py::test_identifiers",
"src/latexify/transformers/identifier_replacer_test.py::test_invalid_mapping",
"src/latexify/transformers/identifier_replacer_test.py::test_name_replaced",
"src/latexify/transformers/identifier_replacer_test.py::test_name_not_replaced",
"src/latexify/transformers/identifier_replacer_test.py::test_functiondef",
"src/latexify/transformers/identifier_replacer_test.py::test_expr"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-24 16:46:58+00:00
|
apache-2.0
| 2,577 |
|
google__latexify_py-67
|
diff --git a/.gitignore b/.gitignore
index 42812b2..564c52f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -90,7 +90,7 @@ ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
-# .python-version
+.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
diff --git a/pyproject.toml b/pyproject.toml
index a262297..bffd249 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -42,6 +42,7 @@ dev = [
"build>=0.8",
"black>=22.10",
"flake8>=5.0",
+ "notebook>=6.5.1",
"pyproject-flake8>=5.0",
"pytest>=7.1",
"twine>=4.0",
diff --git a/src/latexify/latexify_visitor.py b/src/latexify/latexify_visitor.py
index 476d1ef..19764f3 100644
--- a/src/latexify/latexify_visitor.py
+++ b/src/latexify/latexify_visitor.py
@@ -305,6 +305,43 @@ class LatexifyVisitor(node_visitor_base.NodeVisitorBase):
"but {} were given".format(len(comprehensions))
)
+ # Until 3.8
+ def visit_Index(self, node: ast.Index, action) -> str:
+ """Visitor for the Index nodes."""
+ return self.visit(node.value)
+
+ def convert_nested_subscripts(self, node: ast.Subscript) -> tuple[str, list[str]]:
+ """Helper function to convert nested subscription.
+
+ This function converts x[i][j][...] to "x" and ["i", "j", ...]
+
+ Args:
+ node: ast.Subscript node to be converted.
+
+ Returns:
+ Tuple of following strings:
+ - The root value of the subscription.
+ - Sequence of incices.
+ """
+ if isinstance(node.value, ast.Subscript):
+ value, indices = self.convert_nested_subscripts(node.value)
+ else:
+ value = self.visit(node.value)
+ indices = []
+
+ indices.append(self.visit(node.slice))
+ return value, indices
+
+ def visit_Subscript(self, node: ast.Subscript, action) -> str:
+ """Visitor of the Subscript nodes."""
+ value, indices = self.convert_nested_subscripts(node)
+
+ # TODO(odashi):
+ # "[i][j][...]" may be a possible representation as well as "i, j. ..."
+ indices_str = "{" + ", ".join(indices) + "}"
+
+ return f"{{{value}_{indices_str}}}"
+
def visit_comprehension_set_bounds(self, node): # pylint: disable=invalid-name
"""Visit a comprehension node, which represents a for clause"""
var = self.visit(node.target)
|
google/latexify_py
|
363ffae12ba75930b8100333ecf59ff6d4a42324
|
diff --git a/src/latexify/latexify_visitor_test.py b/src/latexify/latexify_visitor_test.py
index 22a4784..1214333 100644
--- a/src/latexify/latexify_visitor_test.py
+++ b/src/latexify/latexify_visitor_test.py
@@ -65,3 +65,19 @@ def test_visit_boolop(code: str, latex: str) -> None:
tree = ast.parse(code).body[0].value
assert isinstance(tree, ast.BoolOp)
assert LatexifyVisitor().visit(tree) == latex
+
+
[email protected](
+ "code,latex",
+ [
+ ("x[0]", "{x_{0}}"),
+ ("x[0][1]", "{x_{0, 1}}"),
+ ("x[0][1][2]", "{x_{0, 1, 2}}"),
+ ("x[foo]", "{x_{foo}}"),
+ ("x[math.floor(x)]", r"{x_{\left\lfloor{x}\right\rfloor}}"),
+ ],
+)
+def test_visit_subscript(code: str, latex: str) -> None:
+ tree = ast.parse(code).body[0].value
+ assert isinstance(tree, ast.Subscript)
+ assert LatexifyVisitor().visit(tree) == latex
|
support indicies
Add suppot for indicies
```
import math
import latexify
@latexify.with_latex
def solve(a):
return a[0]
print(solve)
```
to be something like `\mathrm{solve}(a) \triangleq a_0`
|
0.0
|
363ffae12ba75930b8100333ecf59ff6d4a42324
|
[
"src/latexify/latexify_visitor_test.py::test_visit_subscript[x[0]-{x_{0}}]",
"src/latexify/latexify_visitor_test.py::test_visit_subscript[x[0][1]-{x_{0,",
"src/latexify/latexify_visitor_test.py::test_visit_subscript[x[0][1][2]-{x_{0,",
"src/latexify/latexify_visitor_test.py::test_visit_subscript[x[foo]-{x_{foo}}]",
"src/latexify/latexify_visitor_test.py::test_visit_subscript[x[math.floor(x)]-{x_{\\\\left\\\\lfloor{x}\\\\right\\\\rfloor}}]"
] |
[
"src/latexify/latexify_visitor_test.py::test_visit_compare[a",
"src/latexify/latexify_visitor_test.py::test_visit_boolop[a"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-29 16:53:17+00:00
|
apache-2.0
| 2,578 |
|
google__mobly-134
|
diff --git a/mobly/controllers/android_device_lib/callback_handler.py b/mobly/controllers/android_device_lib/callback_handler.py
index 93b13e2..d86bf9e 100644
--- a/mobly/controllers/android_device_lib/callback_handler.py
+++ b/mobly/controllers/android_device_lib/callback_handler.py
@@ -17,6 +17,8 @@
import logging
import time
+from mobly.controllers.android_device_lib import snippet_event
+
class Error(Exception):
pass
@@ -30,16 +32,23 @@ class CallbackHandler(object):
"""The class used to handle a specific group of callback events.
All the events handled by a CallbackHandler are originally triggered by one
- async Rpc call. All the events are tagged with a callback_id specific to a call
- to an AsyncRpc method defined on the server side.
+ async Rpc call. All the events are tagged with a callback_id specific to a
+ call to an AsyncRpc method defined on the server side.
- The callback events are dictionaries that follow this schema:
+ The raw message representing an event looks like:
{
'callbackId': <string, callbackId>,
'name': <string, name of the event>,
- 'time': <long, epoch time of when the event was created on the server side>,
+ 'time': <long, epoch time of when the event was created on the server
+ side>,
'data': <dict, extra data from the callback on the server side>
}
+
+ Each message is then used to create a SnippetEvent object on the client
+ side.
+
+ Attributes:
+ ret_value: The direct return value of the async Rpc call.
"""
def __init__(self, callback_id, event_client, ret_value, method_name):
@@ -57,7 +66,7 @@ class CallbackHandler(object):
timeout: float, the number of seconds to wait before giving up.
Returns:
- The oldest entry of the specified event.
+ SnippetEvent, the oldest entry of the specified event.
Raises:
TimeoutError: The expected event does not occur within time limit.
@@ -65,25 +74,27 @@ class CallbackHandler(object):
if timeout:
timeout *= 1000 # convert to milliseconds for java side
try:
- event = self._event_client.eventWaitAndGet(self._id, event_name,
- timeout)
+ raw_event = self._event_client.eventWaitAndGet(self._id,
+ event_name, timeout)
except Exception as e:
if "EventSnippetException: timeout." in str(e):
raise TimeoutError(
'Timeout waiting for event "%s" triggered by %s (%s).'
% (event_name, self._method_name, self._id))
raise
- return event
+ return snippet_event.from_dict(raw_event)
def getAll(self, event_name):
- """Gets all the events of a certain name that have been received so far.
- This is a non-blocking call.
+ """Gets all the events of a certain name that have been received so
+ far. This is a non-blocking call.
Args:
callback_id: The id of the callback.
event_name: string, the name of the event to get.
Returns:
- A list of dicts, each dict representing an event from the Java side.
+ A list of SnippetEvent, each representing an event from the Java
+ side.
"""
- return self._event_client.eventGetAll(self._id, event_name)
+ raw_events = self._event_client.eventGetAll(self._id, event_name)
+ return [snippet_event.from_dict(msg) for msg in raw_events]
diff --git a/mobly/controllers/android_device_lib/snippet_event.py b/mobly/controllers/android_device_lib/snippet_event.py
new file mode 100644
index 0000000..0947a55
--- /dev/null
+++ b/mobly/controllers/android_device_lib/snippet_event.py
@@ -0,0 +1,50 @@
+# Copyright 2017 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import logging
+import time
+
+
+def from_dict(event_dict):
+ """Create a SnippetEvent object from a dictionary.
+
+ Args:
+ event_dict: a dictionary representing an event.
+
+ Returns:
+ A SnippetEvent object.
+ """
+ return SnippetEvent(
+ callback_id=event_dict['callbackId'],
+ name=event_dict['name'],
+ creation_time=event_dict['time'],
+ data=event_dict['data'])
+
+
+class SnippetEvent(object):
+ """The class that represents callback events for mobly snippet library.
+
+ Attributes:
+ callback_id: string, the callback ID associated with the event.
+ name: string, the name of the event.
+ creation_time: int, the epoch time when the event is created on the
+ Rpc server side.
+ data: dictionary, the data held by the event. Can be None.
+ """
+
+ def __init__(self, callback_id, name, creation_time, data):
+ self.callback_id = callback_id
+ self.name = name
+ self.creation_time = creation_time
+ self.data = data
|
google/mobly
|
061ed277ec8af0b67e607ad7b12a5de80912c590
|
diff --git a/tests/mobly/controllers/android_device_lib/callback_handler_test.py b/tests/mobly/controllers/android_device_lib/callback_handler_test.py
index dbbb692..d121fe8 100755
--- a/tests/mobly/controllers/android_device_lib/callback_handler_test.py
+++ b/tests/mobly/controllers/android_device_lib/callback_handler_test.py
@@ -21,19 +21,47 @@ from mobly.controllers.android_device_lib import callback_handler
from mobly.controllers.android_device_lib import jsonrpc_client_base
MOCK_CALLBACK_ID = "1-0"
+MOCK_RAW_EVENT = {
+ 'callbackId': '2-1',
+ 'name': 'AsyncTaskResult',
+ 'time': 20460228696,
+ 'data': {
+ 'exampleData': "Here's a simple event.",
+ 'successful': True,
+ 'secretNumber': 12
+ }
+}
class CallbackHandlerTest(unittest.TestCase):
"""Unit tests for mobly.controllers.android_device_lib.callback_handler.
"""
+ def test_event_dict_to_snippet_event(self):
+ mock_event_client = mock.Mock()
+ mock_event_client.eventWaitAndGet = mock.Mock(
+ return_value=MOCK_RAW_EVENT)
+ handler = callback_handler.CallbackHandler(
+ callback_id=MOCK_CALLBACK_ID,
+ event_client=mock_event_client,
+ ret_value=None,
+ method_name=None)
+ event = handler.waitAndGet('ha')
+ self.assertEqual(event.name, MOCK_RAW_EVENT['name'])
+ self.assertEqual(event.creation_time, MOCK_RAW_EVENT['time'])
+ self.assertEqual(event.data, MOCK_RAW_EVENT['data'])
+ self.assertEqual(event.callback_id, MOCK_RAW_EVENT['callbackId'])
+
def test_wait_and_get_timeout(self):
mock_event_client = mock.Mock()
java_timeout_msg = 'com.google.android.mobly.snippet.event.EventSnippet$EventSnippetException: timeout.'
mock_event_client.eventWaitAndGet = mock.Mock(
side_effect=jsonrpc_client_base.ApiError(java_timeout_msg))
- handler = callback_handler.CallbackHandler(MOCK_CALLBACK_ID,
- mock_event_client, None, None)
+ handler = callback_handler.CallbackHandler(
+ callback_id=MOCK_CALLBACK_ID,
+ event_client=mock_event_client,
+ ret_value=None,
+ method_name=None)
expected_msg = 'Timeout waiting for event "ha" .*'
with self.assertRaisesRegexp(callback_handler.TimeoutError,
expected_msg):
|
Create an `event` type on the client side
So instead of dealing with the dict and key access:
```
{u'callbackId': u'2-2', u'data': {u'isSuccess': True}, u'name': u'status', u'time': 1487989424790}
```
We could have some sort of structure:
```
event.data -> {'isSuccess': True}
event.name -> 'status'
event.creation_time -> 1487989424790
```
|
0.0
|
061ed277ec8af0b67e607ad7b12a5de80912c590
|
[
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_event_dict_to_snippet_event"
] |
[
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_wait_and_get_timeout"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-02-28 16:35:44+00:00
|
apache-2.0
| 2,579 |
|
google__mobly-135
|
diff --git a/mobly/controllers/android_device_lib/callback_handler.py b/mobly/controllers/android_device_lib/callback_handler.py
index 399e999..93b13e2 100644
--- a/mobly/controllers/android_device_lib/callback_handler.py
+++ b/mobly/controllers/android_device_lib/callback_handler.py
@@ -42,10 +42,11 @@ class CallbackHandler(object):
}
"""
- def __init__(self, callback_id, event_client, ret_value):
+ def __init__(self, callback_id, event_client, ret_value, method_name):
self._id = callback_id
self._event_client = event_client
self.ret_value = ret_value
+ self._method_name = method_name
def waitAndGet(self, event_name, timeout=None):
"""Blocks until an event of the specified name has been received and
@@ -69,8 +70,8 @@ class CallbackHandler(object):
except Exception as e:
if "EventSnippetException: timeout." in str(e):
raise TimeoutError(
- 'Timeout waiting for event "%s" of callback %s'
- % (event_name, self._id))
+ 'Timeout waiting for event "%s" triggered by %s (%s).'
+ % (event_name, self._method_name, self._id))
raise
return event
diff --git a/mobly/controllers/android_device_lib/jsonrpc_client_base.py b/mobly/controllers/android_device_lib/jsonrpc_client_base.py
index 84cf480..eed3aca 100644
--- a/mobly/controllers/android_device_lib/jsonrpc_client_base.py
+++ b/mobly/controllers/android_device_lib/jsonrpc_client_base.py
@@ -292,7 +292,10 @@ class JsonRpcClientBase(object):
if self._event_client is None:
self._event_client = self._start_event_client()
return callback_handler.CallbackHandler(
- result['callback'], self._event_client, result['result'])
+ callback_id=result['callback'],
+ event_client=self._event_client,
+ ret_value=result['result'],
+ method_name=method)
return result['result']
def _is_app_running(self):
diff --git a/mobly/controllers/android_device_lib/snippet_client.py b/mobly/controllers/android_device_lib/snippet_client.py
index a053303..c3f2ac9 100644
--- a/mobly/controllers/android_device_lib/snippet_client.py
+++ b/mobly/controllers/android_device_lib/snippet_client.py
@@ -64,13 +64,13 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
# Use info here so people know exactly what's happening here, which is
# helpful since they need to create their own instrumentations and
# manifest.
- logging.info('Launching snippet apk with: %s', cmd)
+ logging.debug('Launching snippet apk %s', self.package)
self._adb.shell(cmd)
def stop_app(self):
"""Overrides superclass."""
cmd = _STOP_CMD % self.package
- logging.info('Stopping snippet apk with: %s', cmd)
+ logging.debug('Stopping snippet apk %s', self.package)
out = self._adb.shell(_STOP_CMD % self.package).decode('utf-8')
if 'OK (0 tests)' not in out:
raise Error('Failed to stop existing apk. Unexpected output: %s' %
|
google/mobly
|
81f4c8854fdc7b07607efdb7f0da91b9e1b22d12
|
diff --git a/tests/mobly/controllers/android_device_lib/callback_handler_test.py b/tests/mobly/controllers/android_device_lib/callback_handler_test.py
index ffe3ad7..dbbb692 100755
--- a/tests/mobly/controllers/android_device_lib/callback_handler_test.py
+++ b/tests/mobly/controllers/android_device_lib/callback_handler_test.py
@@ -33,7 +33,7 @@ class CallbackHandlerTest(unittest.TestCase):
mock_event_client.eventWaitAndGet = mock.Mock(
side_effect=jsonrpc_client_base.ApiError(java_timeout_msg))
handler = callback_handler.CallbackHandler(MOCK_CALLBACK_ID,
- mock_event_client, None)
+ mock_event_client, None, None)
expected_msg = 'Timeout waiting for event "ha" .*'
with self.assertRaisesRegexp(callback_handler.TimeoutError,
expected_msg):
|
Better timeout message in CallbackHandler
Right now the `CallbackHandler`'s timeout msg only includes the `callback_id`, which is an implementation detail that doesn't make too much sense for the user. We should add the name of the call where the event was supposed to originate from.
|
0.0
|
81f4c8854fdc7b07607efdb7f0da91b9e1b22d12
|
[
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_wait_and_get_timeout"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-02-28 17:06:35+00:00
|
apache-2.0
| 2,580 |
|
google__mobly-140
|
diff --git a/mobly/controllers/android_device_lib/callback_handler.py b/mobly/controllers/android_device_lib/callback_handler.py
index 7c648c2..ddcf029 100644
--- a/mobly/controllers/android_device_lib/callback_handler.py
+++ b/mobly/controllers/android_device_lib/callback_handler.py
@@ -18,6 +18,11 @@ import time
from mobly.controllers.android_device_lib import snippet_event
+# The max timeout cannot be larger than the max time the socket waits for a
+# response message. Otherwise, the socket would timeout before the Rpc call
+# does, leaving both server and client in unknown states.
+MAX_TIMEOUT = 60 * 10
+
class Error(Exception):
pass
@@ -68,9 +73,15 @@ class CallbackHandler(object):
SnippetEvent, the oldest entry of the specified event.
Raises:
+ Error: If the specified timeout is longer than the max timeout
+ supported.
TimeoutError: The expected event does not occur within time limit.
"""
if timeout:
+ if timeout > MAX_TIMEOUT:
+ raise Error(
+ 'Specified timeout %s is longer than max timeout %s.' %
+ (timeout, MAX_TIMEOUT))
timeout *= 1000 # convert to milliseconds for java side
try:
raw_event = self._event_client.eventWaitAndGet(self._id,
@@ -78,8 +89,8 @@ class CallbackHandler(object):
except Exception as e:
if 'EventSnippetException: timeout.' in str(e):
raise TimeoutError(
- 'Timeout waiting for event "%s" triggered by %s (%s).'
- % (event_name, self._method_name, self._id))
+ 'Timeout waiting for event "%s" triggered by %s (%s).' %
+ (event_name, self._method_name, self._id))
raise
return snippet_event.from_dict(raw_event)
diff --git a/mobly/controllers/android_device_lib/jsonrpc_client_base.py b/mobly/controllers/android_device_lib/jsonrpc_client_base.py
index bb4b5ed..5b661a3 100644
--- a/mobly/controllers/android_device_lib/jsonrpc_client_base.py
+++ b/mobly/controllers/android_device_lib/jsonrpc_client_base.py
@@ -53,7 +53,10 @@ APP_START_WAIT_TIME = 15
UNKNOWN_UID = -1
# Maximum time to wait for the socket to open on the device.
-_SOCKET_TIMEOUT = 60
+_SOCKET_CONNECTION_TIMEOUT = 60
+
+# Maximum time to wait for a response message on the socket.
+_SOCKET_READ_TIMEOUT = callback_handler.MAX_TIMEOUT
class Error(Exception):
@@ -70,9 +73,9 @@ class ApiError(Error):
class ProtocolError(Error):
"""Raised when there is some error in exchanging data with server."""
- NO_RESPONSE_FROM_HANDSHAKE = "No response from handshake."
- NO_RESPONSE_FROM_SERVER = "No response from server."
- MISMATCHED_API_ID = "Mismatched API id."
+ NO_RESPONSE_FROM_HANDSHAKE = 'No response from handshake.'
+ NO_RESPONSE_FROM_SERVER = 'No response from server.'
+ MISMATCHED_API_ID = 'Mismatched API id.'
class JsonRpcCommand(object):
@@ -186,9 +189,9 @@ class JsonRpcClientBase(object):
"""Opens a connection to a JSON RPC server.
Opens a connection to a remote client. The connection attempt will time
- out if it takes longer than _SOCKET_TIMEOUT seconds. Each subsequent
- operation over this socket will time out after _SOCKET_TIMEOUT seconds
- as well.
+ out if it takes longer than _SOCKET_CONNECTION_TIMEOUT seconds. Each
+ subsequent operation over this socket will time out after
+ _SOCKET_READ_TIMEOUT seconds as well.
Args:
uid: int, The uid of the session to join, or UNKNOWN_UID to start a
@@ -202,8 +205,8 @@ class JsonRpcClientBase(object):
"""
self._counter = self._id_counter()
self._conn = socket.create_connection(('127.0.0.1', self.host_port),
- _SOCKET_TIMEOUT)
- self._conn.settimeout(_SOCKET_TIMEOUT)
+ _SOCKET_CONNECTION_TIMEOUT)
+ self._conn.settimeout(_SOCKET_READ_TIMEOUT)
self._client = self._conn.makefile(mode='brw')
resp = self._cmd(cmd, uid)
diff --git a/mobly/controllers/android_device_lib/sl4a_client.py b/mobly/controllers/android_device_lib/sl4a_client.py
index ef5583e..ba31e0f 100644
--- a/mobly/controllers/android_device_lib/sl4a_client.py
+++ b/mobly/controllers/android_device_lib/sl4a_client.py
@@ -57,4 +57,4 @@ class Sl4aClient(jsonrpc_client_base.JsonRpcClientBase):
"pm list package | grep com.googlecode.android_scripting"):
raise jsonrpc_client_base.AppStartError(
'%s is not installed on %s' % (
- self.app_name, self._adb.getprop('ro.boot.serialno')))
+ self.app_name, self._adb.serial))
diff --git a/mobly/controllers/android_device_lib/snippet_client.py b/mobly/controllers/android_device_lib/snippet_client.py
index 7c3ca01..793e3ae 100644
--- a/mobly/controllers/android_device_lib/snippet_client.py
+++ b/mobly/controllers/android_device_lib/snippet_client.py
@@ -56,8 +56,8 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
app_name=package,
adb_proxy=adb_proxy)
self.package = package
- self._serial = self._adb.getprop('ro.boot.serialno')
self.log = log
+ self._serial = self._adb.serial
def _do_start_app(self):
"""Overrides superclass."""
|
google/mobly
|
b4362eda0c8148644812849cdb9c741e35d5750d
|
diff --git a/tests/mobly/controllers/android_device_lib/callback_handler_test.py b/tests/mobly/controllers/android_device_lib/callback_handler_test.py
index d121fe8..1a3afc0 100755
--- a/tests/mobly/controllers/android_device_lib/callback_handler_test.py
+++ b/tests/mobly/controllers/android_device_lib/callback_handler_test.py
@@ -37,6 +37,10 @@ class CallbackHandlerTest(unittest.TestCase):
"""Unit tests for mobly.controllers.android_device_lib.callback_handler.
"""
+ def test_timeout_value(self):
+ self.assertGreaterEqual(jsonrpc_client_base._SOCKET_READ_TIMEOUT,
+ callback_handler.MAX_TIMEOUT)
+
def test_event_dict_to_snippet_event(self):
mock_event_client = mock.Mock()
mock_event_client.eventWaitAndGet = mock.Mock(
|
Rpc socket times out before EventHandler.waitAndGet
`json_rpc_base._SOCKET_TIMEOUT` is 60s. Yet `EventHandler.waitAndGet` can take an arbitrary timeout length.
`EventHandler.waitAndGet` makes a call to `EventSnippet.eventWaitAndGet` through the socket, which doesn't return until the event is received or the method itself times out.
So if somebody calls `EventHandler.waitAndGet` with a timeout longer than `json_rpc_base._SOCKET_TIMEOUT`, we'd get a socket timeout error.
We should:
1. Make socket timeout longer
2. Add a guard in `EventHandler.waitAndGet` for a max timeout value.
|
0.0
|
b4362eda0c8148644812849cdb9c741e35d5750d
|
[
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_timeout_value"
] |
[
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_event_dict_to_snippet_event",
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_wait_and_get_timeout"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-03-09 06:28:28+00:00
|
apache-2.0
| 2,581 |
|
google__mobly-146
|
diff --git a/mobly/controllers/android_device.py b/mobly/controllers/android_device.py
index 79d3f16..5675e34 100644
--- a/mobly/controllers/android_device.py
+++ b/mobly/controllers/android_device.py
@@ -16,6 +16,7 @@
from builtins import str
from builtins import open
+from past.builtins import basestring
import contextlib
import logging
@@ -78,17 +79,19 @@ def create(configs):
ads = get_all_instances()
elif not isinstance(configs, list):
raise Error(ANDROID_DEVICE_NOT_LIST_CONFIG_MSG)
- elif isinstance(configs[0], str):
- # Configs is a list of serials.
- ads = get_instances(configs)
- else:
+ elif isinstance(configs[0], dict):
# Configs is a list of dicts.
ads = get_instances_with_configs(configs)
+ elif isinstance(configs[0], basestring):
+ # Configs is a list of strings representing serials.
+ ads = get_instances(configs)
+ else:
+ raise Error("No valid config found in: %s" % configs)
connected_ads = list_adb_devices()
for ad in ads:
if ad.serial not in connected_ads:
- raise DeviceError(ad, 'Android device is specified in config but '
+ raise DeviceError(ad, 'Android device is specified in config but'
' is not attached.')
_start_services_on_ads(ads)
return ads
diff --git a/mobly/controllers/android_device_lib/jsonrpc_client_base.py b/mobly/controllers/android_device_lib/jsonrpc_client_base.py
index 187ec1c..08237fb 100644
--- a/mobly/controllers/android_device_lib/jsonrpc_client_base.py
+++ b/mobly/controllers/android_device_lib/jsonrpc_client_base.py
@@ -188,7 +188,7 @@ class JsonRpcClientBase(object):
for _ in range(wait_time):
time.sleep(1)
if self._is_app_running():
- self.log.debug('Successfully started %s', self.app_name)
+ self._log.debug('Successfully started %s', self.app_name)
return
raise AppStartError('%s failed to start on %s.' %
(self.app_name, self._adb.serial))
|
google/mobly
|
3bf63583dae310bd2a7a147bbff01b6aa917f72e
|
diff --git a/tests/lib/mock_android_device.py b/tests/lib/mock_android_device.py
index 5fd6fac..03b62a1 100755
--- a/tests/lib/mock_android_device.py
+++ b/tests/lib/mock_android_device.py
@@ -33,7 +33,7 @@ def get_mock_ads(num):
"""
ads = []
for i in range(num):
- ad = mock.MagicMock(name="AndroidDevice", serial=i, h_port=None)
+ ad = mock.MagicMock(name="AndroidDevice", serial=str(i), h_port=None)
ads.append(ad)
return ads
@@ -42,6 +42,18 @@ def get_all_instances():
return get_mock_ads(5)
+def get_instances(serials):
+ ads = []
+ for serial in serials:
+ ad = mock.MagicMock(name="AndroidDevice", serial=serial, h_port=None)
+ ads.append(ad)
+ return ads
+
+
+def get_instances_with_configs(dicts):
+ return get_instances([d['serial'] for d in dicts])
+
+
def list_adb_devices():
return [ad.serial for ad in get_mock_ads(5)]
diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py
index 38247cb..c5b3733 100755
--- a/tests/mobly/controllers/android_device_test.py
+++ b/tests/mobly/controllers/android_device_test.py
@@ -79,6 +79,29 @@ class AndroidDeviceTest(unittest.TestCase):
for actual, expected in zip(actual_ads, mock_android_device.get_mock_ads(5)):
self.assertEqual(actual.serial, expected.serial)
+ @mock.patch.object(android_device,
+ "get_instances",
+ new=mock_android_device.get_instances)
+ @mock.patch.object(android_device,
+ "list_adb_devices",
+ new=mock_android_device.list_adb_devices)
+ def test_create_with_string_list(self):
+ string_list = [u'1', '2']
+ actual_ads = android_device.create(string_list)
+ for actual_ad, expected_serial in zip(actual_ads, ['1', '2']):
+ self.assertEqual(actual_ad.serial, expected_serial)
+
+ @mock.patch.object(android_device,
+ "get_instances_with_configs",
+ new=mock_android_device.get_instances_with_configs)
+ @mock.patch.object(android_device,
+ "list_adb_devices",
+ new=mock_android_device.list_adb_devices)
+ def test_create_with_dict_list(self):
+ string_list = [{'serial': '1'}, {'serial': '2'}]
+ actual_ads = android_device.create(string_list)
+ for actual_ad, expected_serial in zip(actual_ads, ['1', '2']):
+ self.assertEqual(actual_ad.serial, expected_serial)
def test_create_with_empty_config(self):
expected_msg = android_device.ANDROID_DEVICE_EMPTY_CONFIG_MSG
with self.assertRaisesRegexp(android_device.Error,
@@ -91,15 +114,21 @@ class AndroidDeviceTest(unittest.TestCase):
expected_msg):
android_device.create("HAHA")
+ def test_create_with_no_valid_config(self):
+ expected_msg = "No valid config found in: .*"
+ with self.assertRaisesRegexp(android_device.Error,
+ expected_msg):
+ android_device.create([1])
+
def test_get_device_success_with_serial(self):
ads = mock_android_device.get_mock_ads(5)
- expected_serial = 0
+ expected_serial = '0'
ad = android_device.get_device(ads, serial=expected_serial)
self.assertEqual(ad.serial, expected_serial)
def test_get_device_success_with_serial_and_extra_field(self):
ads = mock_android_device.get_mock_ads(5)
- expected_serial = 1
+ expected_serial = '1'
expected_h_port = 5555
ads[1].h_port = expected_h_port
ad = android_device.get_device(ads,
@@ -119,7 +148,7 @@ class AndroidDeviceTest(unittest.TestCase):
def test_get_device_too_many_matches(self):
ads = mock_android_device.get_mock_ads(5)
target_serial = ads[1].serial = ads[0].serial
- expected_msg = "More than one device matched: \[0, 0\]"
+ expected_msg = "More than one device matched: \['0', '0'\]"
with self.assertRaisesRegexp(android_device.Error,
expected_msg):
android_device.get_device(ads, serial=target_serial)
|
controllers/android_device.py throws an exception on android configuration with just string
Seems like an earlier checkin to switch to using base64 string to load configuration might have introduced a bug in mobly/controllers/android_device.create(configs). I was hitting an issue where I specified the android device serial in string format in my configuration file but was failing the isinstance check with str, so instead it tries to interpret my android config as a dict format and fails. Changing the isinstance check with basestring instead of str seems to have solved the problem.
Here is the snippet of the exception thrown.
mobly/controllers/android_device.py", line 81, in create
mobly/controllers/android_device.py", line 219, in get_instances_with_configs
MoblyTest [ln] serial = c.pop('serial')
MoblyTest [ln] AttributeError: 'str' object has no attribute 'pop'
|
0.0
|
3bf63583dae310bd2a7a147bbff01b6aa917f72e
|
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_no_valid_config"
] |
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_build_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_cat_adb_log",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_debug_tag",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_instantiation",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_attribute_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_package",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_snippet_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_snippet_cleanup",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fallback",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat_with_user_param",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_dict_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_empty_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_not_list_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_pickup_all",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_string_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial_and_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_too_many_matches",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-03-14 22:56:44+00:00
|
apache-2.0
| 2,582 |
|
google__mobly-164
|
diff --git a/mobly/controllers/sniffer_lib/local/local_base.py b/mobly/controllers/sniffer_lib/local/local_base.py
index 859c242..781e4b6 100644
--- a/mobly/controllers/sniffer_lib/local/local_base.py
+++ b/mobly/controllers/sniffer_lib/local/local_base.py
@@ -54,9 +54,10 @@ class SnifferLocalBase(sniffer.Sniffer):
self._base_configs = base_configs
try:
- utils.exe_cmd("ifconfig", self._interface, "down")
- utils.exe_cmd("iwconfig", self._interface, "mode", "monitor")
- utils.exe_cmd("ifconfig", self._interface, "up")
+ subprocess.check_call(['ifconfig', self._interface, 'down'])
+ subprocess.check_call(
+ ['iwconfig', self._interface, 'mode', 'monitor'])
+ subprocess.check_call(['ifconfig', self._interface, 'up'])
except Exception as err:
raise sniffer.ExecutionError(err)
@@ -87,8 +88,11 @@ class SnifferLocalBase(sniffer.Sniffer):
if sniffer.Sniffer.CONFIG_KEY_CHANNEL in final_configs:
try:
- utils.exe_cmd("iwconfig", self._interface, "channel",
- str(final_configs[sniffer.Sniffer.CONFIG_KEY_CHANNEL]))
+ subprocess.check_call([
+ 'iwconfig',
+ self._interface,
+ 'channel',
+ str(final_configs[sniffer.Sniffer.CONFIG_KEY_CHANNEL])])
except Exception as err:
raise sniffer.ExecutionError(err)
diff --git a/mobly/utils.py b/mobly/utils.py
index ba47c60..c9be01e 100644
--- a/mobly/utils.py
+++ b/mobly/utils.py
@@ -280,27 +280,6 @@ def concurrent_exec(func, param_list):
return return_vals
-def exe_cmd(*cmds):
- """Executes commands in a new shell.
-
- Args:
- cmds: A sequence of commands and arguments.
-
- Returns:
- The output of the command run.
-
- Raises:
- OSError is raised if an error occurred during the command execution.
- """
- cmd = ' '.join(cmds)
- proc = subprocess.Popen(
- cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
- (out, err) = proc.communicate()
- if not err:
- return out
- raise OSError(err)
-
-
def _assert_subprocess_running(proc):
"""Checks if a subprocess has terminated on its own.
@@ -368,14 +347,21 @@ def stop_standing_subprocess(proc, kill_signal=signal.SIGTERM):
_assert_subprocess_running(proc)
process = psutil.Process(pid)
success = True
- for child in process.children(recursive=True):
+ try:
+ children = process.children(recursive=True)
+ except AttributeError:
+ # Handle versions <3.0.0 of psutil.
+ children = process.get_children(recursive=True)
+ for child in children:
try:
child.kill()
+ child.wait(timeout=10)
except:
success = False
logging.exception('Failed to kill standing subprocess %d', child.pid)
try:
process.kill()
+ process.wait(timeout=10)
except:
success = False
logging.exception('Failed to kill standing subprocess %d', pid)
|
google/mobly
|
464a16aee403100025085846f0b6a5e29620e5b6
|
diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py
index c5b3733..3a0940e 100755
--- a/tests/mobly/controllers/android_device_test.py
+++ b/tests/mobly/controllers/android_device_test.py
@@ -209,8 +209,7 @@ class AndroidDeviceTest(unittest.TestCase):
@mock.patch('mobly.controllers.android_device_lib.fastboot.FastbootProxy',
return_value=mock_android_device.MockFastbootProxy(1))
@mock.patch('mobly.utils.create_dir')
- @mock.patch('mobly.utils.exe_cmd')
- def test_AndroidDevice_take_bug_report(self, exe_mock, create_dir_mock,
+ def test_AndroidDevice_take_bug_report(self, create_dir_mock,
FastbootProxy, MockAdbProxy):
"""Verifies AndroidDevice.take_bug_report calls the correct adb command
and writes the bugreport file to the correct path.
@@ -227,8 +226,7 @@ class AndroidDeviceTest(unittest.TestCase):
@mock.patch('mobly.controllers.android_device_lib.fastboot.FastbootProxy',
return_value=mock_android_device.MockFastbootProxy(1))
@mock.patch('mobly.utils.create_dir')
- @mock.patch('mobly.utils.exe_cmd')
- def test_AndroidDevice_take_bug_report_fail(self, exe_mock, create_dir_mock,
+ def test_AndroidDevice_take_bug_report_fail(self, create_dir_mock,
FastbootProxy, MockAdbProxy):
"""Verifies AndroidDevice.take_bug_report writes out the correct message
when taking bugreport fails.
@@ -245,8 +243,7 @@ class AndroidDeviceTest(unittest.TestCase):
@mock.patch('mobly.controllers.android_device_lib.fastboot.FastbootProxy',
return_value=mock_android_device.MockFastbootProxy(1))
@mock.patch('mobly.utils.create_dir')
- @mock.patch('mobly.utils.exe_cmd')
- def test_AndroidDevice_take_bug_report_fallback(self, exe_mock,
+ def test_AndroidDevice_take_bug_report_fallback(self,
create_dir_mock, FastbootProxy, MockAdbProxy):
"""Verifies AndroidDevice.take_bug_report falls back to traditional
bugreport on builds that do not have bugreportz.
diff --git a/tests/mobly/utils_test.py b/tests/mobly/utils_test.py
index fb2f519..de618a5 100755
--- a/tests/mobly/utils_test.py
+++ b/tests/mobly/utils_test.py
@@ -32,6 +32,11 @@ class UtilsTest(unittest.TestCase):
utils.start_standing_subprocess("sleep 0", check_health_delay=0.1)
def test_stop_standing_subproc(self):
+ p = utils.start_standing_subprocess('sleep 5')
+ utils.stop_standing_subprocess(p)
+ self.assertIsNotNone(p.poll())
+
+ def test_stop_standing_subproc_already_dead(self):
p = utils.start_standing_subprocess("sleep 0")
time.sleep(0.1)
with self.assertRaisesRegexp(utils.Error,
|
Flake in unit tests
Reported in #87
https://travis-ci.org/google/mobly/jobs/197104959
=================================== FAILURES ===================================
____________________ UtilsTest.test_start_standing_subproc _____________________
self = <tests.mobly.utils_test.UtilsTest testMethod=test_start_standing_subproc>
def test_start_standing_subproc(self):
with self.assertRaisesRegexp(utils.Error,
"Process .* has terminated"):
\> utils.start_standing_subprocess("sleep 0", check_health_delay=0.1)
E AssertionError: Error not raised
tests/mobly/utils_test.py:32: AssertionErro
|
0.0
|
464a16aee403100025085846f0b6a5e29620e5b6
|
[
"tests/mobly/utils_test.py::UtilsTest::test_stop_standing_subproc"
] |
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_build_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_cat_adb_log",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_debug_tag",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_instantiation",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_attribute_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_package",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_snippet_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_snippet_cleanup",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fallback",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat_with_user_param",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_dict_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_empty_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_no_valid_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_not_list_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_pickup_all",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_string_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial_and_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_too_many_matches",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads",
"tests/mobly/utils_test.py::UtilsTest::test_is_port_available_negative",
"tests/mobly/utils_test.py::UtilsTest::test_is_port_available_positive",
"tests/mobly/utils_test.py::UtilsTest::test_start_standing_subproc",
"tests/mobly/utils_test.py::UtilsTest::test_stop_standing_subproc_already_dead"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-03-23 02:48:42+00:00
|
apache-2.0
| 2,583 |
|
google__mobly-165
|
diff --git a/mobly/controllers/sniffer_lib/local/local_base.py b/mobly/controllers/sniffer_lib/local/local_base.py
index 859c242..781e4b6 100644
--- a/mobly/controllers/sniffer_lib/local/local_base.py
+++ b/mobly/controllers/sniffer_lib/local/local_base.py
@@ -54,9 +54,10 @@ class SnifferLocalBase(sniffer.Sniffer):
self._base_configs = base_configs
try:
- utils.exe_cmd("ifconfig", self._interface, "down")
- utils.exe_cmd("iwconfig", self._interface, "mode", "monitor")
- utils.exe_cmd("ifconfig", self._interface, "up")
+ subprocess.check_call(['ifconfig', self._interface, 'down'])
+ subprocess.check_call(
+ ['iwconfig', self._interface, 'mode', 'monitor'])
+ subprocess.check_call(['ifconfig', self._interface, 'up'])
except Exception as err:
raise sniffer.ExecutionError(err)
@@ -87,8 +88,11 @@ class SnifferLocalBase(sniffer.Sniffer):
if sniffer.Sniffer.CONFIG_KEY_CHANNEL in final_configs:
try:
- utils.exe_cmd("iwconfig", self._interface, "channel",
- str(final_configs[sniffer.Sniffer.CONFIG_KEY_CHANNEL]))
+ subprocess.check_call([
+ 'iwconfig',
+ self._interface,
+ 'channel',
+ str(final_configs[sniffer.Sniffer.CONFIG_KEY_CHANNEL])])
except Exception as err:
raise sniffer.ExecutionError(err)
diff --git a/mobly/utils.py b/mobly/utils.py
index ba47c60..338c4e8 100644
--- a/mobly/utils.py
+++ b/mobly/utils.py
@@ -280,27 +280,6 @@ def concurrent_exec(func, param_list):
return return_vals
-def exe_cmd(*cmds):
- """Executes commands in a new shell.
-
- Args:
- cmds: A sequence of commands and arguments.
-
- Returns:
- The output of the command run.
-
- Raises:
- OSError is raised if an error occurred during the command execution.
- """
- cmd = ' '.join(cmds)
- proc = subprocess.Popen(
- cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
- (out, err) = proc.communicate()
- if not err:
- return out
- raise OSError(err)
-
-
def _assert_subprocess_running(proc):
"""Checks if a subprocess has terminated on its own.
@@ -339,10 +318,16 @@ def start_standing_subprocess(cmd, check_health_delay=0):
"""
proc = subprocess.Popen(
cmd,
+ stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
logging.debug('Start standing subprocess with cmd: %s', cmd)
+ # Leaving stdin open causes problems for input, e.g. breaking the
+ # code.inspect() shell (http://stackoverflow.com/a/25512460/1612937), so
+ # explicitly close it assuming it is not needed for standing subprocesses.
+ proc.stdin.close()
+ proc.stdin = None
if check_health_delay > 0:
time.sleep(check_health_delay)
_assert_subprocess_running(proc)
@@ -368,14 +353,21 @@ def stop_standing_subprocess(proc, kill_signal=signal.SIGTERM):
_assert_subprocess_running(proc)
process = psutil.Process(pid)
success = True
- for child in process.children(recursive=True):
+ try:
+ children = process.children(recursive=True)
+ except AttributeError:
+ # Handle versions <3.0.0 of psutil.
+ children = process.get_children(recursive=True)
+ for child in children:
try:
child.kill()
+ child.wait(timeout=10)
except:
success = False
logging.exception('Failed to kill standing subprocess %d', child.pid)
try:
process.kill()
+ process.wait(timeout=10)
except:
success = False
logging.exception('Failed to kill standing subprocess %d', pid)
|
google/mobly
|
464a16aee403100025085846f0b6a5e29620e5b6
|
diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py
index c5b3733..3a0940e 100755
--- a/tests/mobly/controllers/android_device_test.py
+++ b/tests/mobly/controllers/android_device_test.py
@@ -209,8 +209,7 @@ class AndroidDeviceTest(unittest.TestCase):
@mock.patch('mobly.controllers.android_device_lib.fastboot.FastbootProxy',
return_value=mock_android_device.MockFastbootProxy(1))
@mock.patch('mobly.utils.create_dir')
- @mock.patch('mobly.utils.exe_cmd')
- def test_AndroidDevice_take_bug_report(self, exe_mock, create_dir_mock,
+ def test_AndroidDevice_take_bug_report(self, create_dir_mock,
FastbootProxy, MockAdbProxy):
"""Verifies AndroidDevice.take_bug_report calls the correct adb command
and writes the bugreport file to the correct path.
@@ -227,8 +226,7 @@ class AndroidDeviceTest(unittest.TestCase):
@mock.patch('mobly.controllers.android_device_lib.fastboot.FastbootProxy',
return_value=mock_android_device.MockFastbootProxy(1))
@mock.patch('mobly.utils.create_dir')
- @mock.patch('mobly.utils.exe_cmd')
- def test_AndroidDevice_take_bug_report_fail(self, exe_mock, create_dir_mock,
+ def test_AndroidDevice_take_bug_report_fail(self, create_dir_mock,
FastbootProxy, MockAdbProxy):
"""Verifies AndroidDevice.take_bug_report writes out the correct message
when taking bugreport fails.
@@ -245,8 +243,7 @@ class AndroidDeviceTest(unittest.TestCase):
@mock.patch('mobly.controllers.android_device_lib.fastboot.FastbootProxy',
return_value=mock_android_device.MockFastbootProxy(1))
@mock.patch('mobly.utils.create_dir')
- @mock.patch('mobly.utils.exe_cmd')
- def test_AndroidDevice_take_bug_report_fallback(self, exe_mock,
+ def test_AndroidDevice_take_bug_report_fallback(self,
create_dir_mock, FastbootProxy, MockAdbProxy):
"""Verifies AndroidDevice.take_bug_report falls back to traditional
bugreport on builds that do not have bugreportz.
diff --git a/tests/mobly/utils_test.py b/tests/mobly/utils_test.py
index fb2f519..73ea149 100755
--- a/tests/mobly/utils_test.py
+++ b/tests/mobly/utils_test.py
@@ -29,11 +29,16 @@ class UtilsTest(unittest.TestCase):
def test_start_standing_subproc(self):
with self.assertRaisesRegexp(utils.Error,
"Process .* has terminated"):
- utils.start_standing_subprocess("sleep 0", check_health_delay=0.1)
+ utils.start_standing_subprocess("sleep 0", check_health_delay=0.5)
def test_stop_standing_subproc(self):
+ p = utils.start_standing_subprocess('sleep 5')
+ utils.stop_standing_subprocess(p)
+ self.assertIsNotNone(p.poll())
+
+ def test_stop_standing_subproc_already_dead(self):
p = utils.start_standing_subprocess("sleep 0")
- time.sleep(0.1)
+ time.sleep(0.5)
with self.assertRaisesRegexp(utils.Error,
"Process .* has terminated"):
utils.stop_standing_subprocess(p)
|
Flake in unit tests
Reported in #87
https://travis-ci.org/google/mobly/jobs/197104959
=================================== FAILURES ===================================
____________________ UtilsTest.test_start_standing_subproc _____________________
self = <tests.mobly.utils_test.UtilsTest testMethod=test_start_standing_subproc>
def test_start_standing_subproc(self):
with self.assertRaisesRegexp(utils.Error,
"Process .* has terminated"):
\> utils.start_standing_subprocess("sleep 0", check_health_delay=0.1)
E AssertionError: Error not raised
tests/mobly/utils_test.py:32: AssertionErro
|
0.0
|
464a16aee403100025085846f0b6a5e29620e5b6
|
[
"tests/mobly/utils_test.py::UtilsTest::test_stop_standing_subproc"
] |
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_build_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_cat_adb_log",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_debug_tag",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_instantiation",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_attribute_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_package",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_snippet_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_snippet_cleanup",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fallback",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat_with_user_param",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_dict_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_empty_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_no_valid_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_not_list_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_pickup_all",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_string_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial_and_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_too_many_matches",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads",
"tests/mobly/utils_test.py::UtilsTest::test_is_port_available_negative",
"tests/mobly/utils_test.py::UtilsTest::test_is_port_available_positive",
"tests/mobly/utils_test.py::UtilsTest::test_start_standing_subproc",
"tests/mobly/utils_test.py::UtilsTest::test_stop_standing_subproc_already_dead"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-03-23 03:39:23+00:00
|
apache-2.0
| 2,584 |
|
google__mobly-17
|
diff --git a/mobly/controllers/android_device_lib/adb.py b/mobly/controllers/android_device_lib/adb.py
index 4a57cf0..a3e66ec 100644
--- a/mobly/controllers/android_device_lib/adb.py
+++ b/mobly/controllers/android_device_lib/adb.py
@@ -37,6 +37,28 @@ class AdbError(Exception):
) % (self.cmd, self.ret_code, self.stdout, self.stderr)
+def list_occupied_adb_ports():
+ """Lists all the host ports occupied by adb forward.
+
+ This is useful because adb will silently override the binding if an attempt
+ to bind to a port already used by adb was made, instead of throwing binding
+ error. So one should always check what ports adb is using before trying to
+ bind to a port with adb.
+
+ Returns:
+ A list of integers representing occupied host ports.
+ """
+ out = AdbProxy().forward("--list")
+ clean_lines = str(out, 'utf-8').strip().split('\n')
+ used_ports = []
+ for line in clean_lines:
+ tokens = line.split(" tcp:")
+ if len(tokens) != 3:
+ continue
+ used_ports.append(int(tokens[1]))
+ return used_ports
+
+
class AdbProxy():
"""Proxy class for ADB.
diff --git a/mobly/utils.py b/mobly/utils.py
index 0a68c2d..9c52fea 100644
--- a/mobly/utils.py
+++ b/mobly/utils.py
@@ -30,6 +30,7 @@ import subprocess
import time
import traceback
+from mobly.controllers.android_device_lib import adb
# File name length is limited to 255 chars on some OS, so we need to make sure
# the file names we output fits within the limit.
MAX_FILENAME_LEN = 255
@@ -429,21 +430,15 @@ def timeout(sec):
def get_available_host_port():
- """Finds a semi-random available port.
-
- A race condition is still possible after the port number is returned, if
- another process happens to bind it.
+ """Gets a host port number available for adb forward.
Returns:
- A port number that is unused on both TCP and UDP.
+ An integer representing a port number on the host available for adb
+ forward.
"""
- # On the 2.6 kernel, calling _try_bind() on UDP socket returns the
- # same port over and over. So always try TCP first.
while True:
- # Ask the OS for an unused port.
- port = _try_bind(0, socket.SOCK_STREAM, socket.IPPROTO_TCP)
- # Check if this port is unused on the other protocol.
- if port and _try_bind(port, socket.SOCK_DGRAM, socket.IPPROTO_UDP):
+ port = random.randint(1024, 9900)
+ if is_port_available(port):
return port
@@ -456,19 +451,18 @@ def is_port_available(port):
Returns:
True if the port is available; False otherwise.
"""
- return (_try_bind(port, socket.SOCK_STREAM, socket.IPPROTO_TCP) and
- _try_bind(port, socket.SOCK_DGRAM, socket.IPPROTO_UDP))
-
-
-def _try_bind(port, socket_type, socket_proto):
- s = socket.socket(socket.AF_INET, socket_type, socket_proto)
+ # Make sure adb is not using this port so we don't accidentally interrupt
+ # ongoing runs by trying to bind to the port.
+ if port in adb.list_occupied_adb_ports():
+ return False
+ s = None
try:
- try:
- s.bind(('', port))
- # The result of getsockname() is protocol dependent, but for both
- # IPv4 and IPv6 the second field is a port number.
- return s.getsockname()[1]
- except socket.error:
- return None
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind(('localhost', port))
+ return True
+ except socket.error:
+ return False
finally:
- s.close()
+ if s:
+ s.close()
|
google/mobly
|
213cd2f8b71c9c1699765bf6bcef4777dcacaafe
|
diff --git a/tests/mobly/utils_test.py b/tests/mobly/utils_test.py
index 31d776a..fb2f519 100755
--- a/tests/mobly/utils_test.py
+++ b/tests/mobly/utils_test.py
@@ -14,6 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import mock
import socket
import time
import unittest
@@ -37,29 +38,16 @@ class UtilsTest(unittest.TestCase):
"Process .* has terminated"):
utils.stop_standing_subprocess(p)
- def test_is_port_available_positive(self):
- # Unfortunately, we cannot do this test reliably for SOCK_STREAM
- # because the kernel allow this socket to linger about for some
- # small amount of time. We're not using SO_REUSEADDR because we
- # are working around behavior on darwin where binding to localhost
- # on some port and then binding again to the wildcard address
- # with SO_REUSEADDR seems to be allowed.
- test_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ @mock.patch('mobly.controllers.android_device_lib.adb.list_occupied_adb_ports')
+ def test_is_port_available_positive(self, mock_list_occupied_adb_ports):
+ test_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
test_s.bind(('localhost', 0))
port = test_s.getsockname()[1]
test_s.close()
self.assertTrue(utils.is_port_available(port))
- def test_detects_udp_port_in_use(self):
- test_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- test_s.bind(('localhost', 0))
- port = test_s.getsockname()[1]
- try:
- self.assertFalse(utils.is_port_available(port))
- finally:
- test_s.close()
-
- def test_detects_tcp_port_in_use(self):
+ @mock.patch('mobly.controllers.android_device_lib.adb.list_occupied_adb_ports')
+ def test_is_port_available_negative(self, mock_list_occupied_adb_ports):
test_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
test_s.bind(('localhost', 0))
port = test_s.getsockname()[1]
@@ -68,6 +56,5 @@ class UtilsTest(unittest.TestCase):
finally:
test_s.close()
-
if __name__ == "__main__":
- unittest.main()
\ No newline at end of file
+ unittest.main()
|
Mobly unit tests are flaky
Running the unit tests gives different results without code changes:
```
$ python setup.py test
running test
running egg_info
writing requirements to mobly.egg-info/requires.txt
writing mobly.egg-info/PKG-INFO
writing top-level names to mobly.egg-info/top_level.txt
writing dependency_links to mobly.egg-info/dependency_links.txt
reading manifest file 'mobly.egg-info/SOURCES.txt'
writing manifest file 'mobly.egg-info/SOURCES.txt'
running build_ext
==================================================================================================================== test session starts =====================================================================================================================
platform linux2 -- Python 2.7.6, pytest-3.0.5, py-1.4.31, pluggy-0.4.0
rootdir: /usr/local/google/home/adorokhine/work/mobly.git, inifile:
collected 114 items
tests/mobly_android_device_test.py ................
tests/mobly_asserts_test.py .
tests/mobly_base_class_test.py .....................................................
tests/mobly_logger_test.py .
tests/mobly_records_test.py ................
tests/mobly_sl4a_client_test.py ...........
tests/mobly_test_runner_test.py ...........
tests/mobly_utils_test.py ..F
========================================================================================================================== FAILURES ==========================================================================================================================
_______________________________________________________________________________________________________ MoblyUtilsTest.test_is_port_available_positive _______________________________________________________________________________________________________
self = <mobly_utils_test.MoblyUtilsTest testMethod=test_is_port_available_positive>
def test_is_port_available_positive(self):
# Unfortunately, we cannot do this test reliably for SOCK_STREAM
# because the kernel allow this socket to linger about for some
# small amount of time. We're not using SO_REUSEADDR because we
# are working around behavior on darwin where binding to localhost
# on some port and then binding again to the wildcard address
# with SO_REUSEADDR seems to be allowed.
test_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
test_s.bind(('localhost', 0))
port = test_s.getsockname()[1]
test_s.close()
> self.assertTrue(utils.is_port_available(port))
E AssertionError: None is not true
tests/mobly_utils_test.py:51: AssertionError
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================================================================ 1 failed, 111 passed in 0.48 seconds ============================================================================================================
```
Ran again:
```
$ python setup.py test
running test
running egg_info
writing requirements to mobly.egg-info/requires.txt
writing mobly.egg-info/PKG-INFO
writing top-level names to mobly.egg-info/top_level.txt
writing dependency_links to mobly.egg-info/dependency_links.txt
reading manifest file 'mobly.egg-info/SOURCES.txt'
writing manifest file 'mobly.egg-info/SOURCES.txt'
running build_ext
==================================================================================================================== test session starts =====================================================================================================================
platform linux2 -- Python 2.7.6, pytest-3.0.5, py-1.4.31, pluggy-0.4.0
rootdir: /usr/local/google/home/adorokhine/work/mobly.git, inifile:
collected 114 items
tests/mobly_android_device_test.py ................
tests/mobly_asserts_test.py .
tests/mobly_base_class_test.py .....................................................
tests/mobly_logger_test.py .
tests/mobly_records_test.py ................
tests/mobly_sl4a_client_test.py ...........
tests/mobly_test_runner_test.py ...........
tests/mobly_utils_test.py .....
================================================================================================================= 114 passed in 0.56 seconds =================================================================================================================
```
|
0.0
|
213cd2f8b71c9c1699765bf6bcef4777dcacaafe
|
[
"tests/mobly/utils_test.py::UtilsTest::test_is_port_available_negative",
"tests/mobly/utils_test.py::UtilsTest::test_is_port_available_positive"
] |
[
"tests/mobly/utils_test.py::UtilsTest::test_start_standing_subproc",
"tests/mobly/utils_test.py::UtilsTest::test_stop_standing_subproc"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-12-09 02:33:47+00:00
|
apache-2.0
| 2,585 |
|
google__mobly-194
|
diff --git a/docs/tutorial.md b/docs/tutorial.md
index 67f66b0..2c64dae 100644
--- a/docs/tutorial.md
+++ b/docs/tutorial.md
@@ -9,18 +9,13 @@ various devices and you can also use your own custom hardware/equipment.
* A computer with at least 2 USB ports.
* Mobly package and its system dependencies installed on the computer.
-* One or two Android devices with the app SL4A* installed.
+* One or two Android devices with the [Mobly Bundled Snippets]
+ (https://github.com/google/mobly-bundled-snippets) (MBS) installed. We will
+ use MBS to trigger actions on the Android devices.
* A working adb setup. To check, connect one Android device to the computer
and make sure it has "USB debugging" enabled. Make sure the device shows up
in the list printed by `adb devices`.
-\* You can get SL4A from the
-[Android repo](https://source.android.com/source/downloading.html), under
-project `<aosp>/external/sl4a`
-
-It can be built like a regular system app with `mm` commands. It needs to be
-signed with the build you use on your Android devices.
-
# Example 1: Hello World!
Let's start with the simple example of posting "Hello World" on the Android
@@ -51,10 +46,11 @@ class HelloWorldTest(base_test.BaseTestClass):
# object is created from this.
self.ads = self.register_controller(android_device)
self.dut = self.ads[0]
- self.dut.load_sl4a() # starts sl4a.
+ # Start Mobly Bundled Snippets (MBS).
+ self.dut.load_snippet('mbs', 'com.google.android.mobly.snippet.bundled')
def test_hello(self):
- self.dut.sl4a.makeToast('Hello World!')
+ self.dut.mbs.makeToast('Hello World!')
if __name__ == '__main__':
test_runner.main()
@@ -97,13 +93,13 @@ class HelloWorldTest(base_test.BaseTestClass):
def setup_class(self):
self.ads = self.register_controller(android_device)
self.dut = self.ads[0]
- self.dut.load_sl4a()
+ self.dut.load_snippet('mbs', 'com.google.android.mobly.snippet.bundled')
def test_hello(self):
- self.dut.sl4a.makeToast('Hello World!')
+ self.dut.mbs.makeToast('Hello World!')
def test_bye(self):
- self.dut.sl4a.makeToast('Goodbye!')
+ self.dut.mbs.makeToast('Goodbye!')
if __name__ == '__main__':
test_runner.main()
@@ -152,9 +148,9 @@ In the test script, you could access the user parameter:
def test_favorite_food(self):
food = self.user_params.get('favorite_food')
if food:
- self.dut.sl4a.makeToast("I'd like to eat %s." % food)
+ self.dut.mbs.makeToast("I'd like to eat %s." % food)
else:
- self.dut.sl4a.makeToast("I'm not hungry.")
+ self.dut.mbs.makeToast("I'm not hungry.")
```
# Example 4: Multiple Test Beds and Default Test Parameters
@@ -201,7 +197,7 @@ screen.
In this example, we use one Android device to discover another Android device
via bluetooth. This test demonstrates several essential elements in test
-writing, like logging and asserts.
+writing, like asserts, device debug tag, and general logging vs logging with device tag.
**sample_config.yml**
@@ -211,111 +207,90 @@ TestBeds:
Controllers:
AndroidDevice:
- serial: xyz,
- label: dut
+ label: target
- serial: abc,
label: discoverer
TestParams:
bluetooth_name: MagicBluetooth,
bluetooth_timeout: 5
-
-
+
```
**sample_test.py**
```python
+import logging
+import pprint
+
+from mobly import asserts
from mobly import base_test
from mobly import test_runner
-from mobly.controllerse import android_device
-
+from mobly.controllers import android_device
+
+# Number of seconds for the target to stay discoverable on Bluetooth.
+DISCOVERABLE_TIME = 60
+
+
class HelloWorldTest(base_test.BaseTestClass):
-
-
- def setup_class(self):
- # Registering android_device controller module, and declaring that the test
- # requires at least two Android devices.
- self.ads = self.register_controller(android_device, min_number=2)
- self.dut = android_device.get_device(self.ads, label='dut')
- self.dut.load_sl4a()
- self.discoverer = android_device.get_device(self.ads, label='discoverer')
- self.discoverer.load_sl4a()
- self.dut.ed.clear_all_events()
- self.discoverer.ed.clear_all_events()
-
- def setup_test(self):
- # Make sure bluetooth is on
- self.dut.sl4a.bluetoothToggleState(True)
- self.discoverer.sl4a.bluetoothToggleState(True)
- self.dut.ed.pop_event(event_name='BluetoothStateChangedOn',
- timeout=10)
- self.discoverer.ed.pop_event(event_name='BluetoothStateChangedOn',
- timeout=10)
- if (not self.dut.sl4a.bluetoothCheckState() or
- not self.discoverer.sl4a.bluetoothCheckState()):
- asserts.abort_class('Could not turn on Bluetooth on both devices.')
-
- # Set the name of device #1 and verify the name properly registered.
- self.dut.sl4a.bluetoothSetLocalName(self.bluetooth_name)
- asserts.assert_equal(self.dut.sl4a.bluetoothGetLocalName(),
- self.bluetooth_name,
- 'Failed to set bluetooth name to %s on %s' %
- (self.bluetooth_name, self.dut.serial))
-
- def test_bluetooth_discovery(self):
- # Make dut discoverable.
- self.dut.sl4a.bluetoothMakeDiscoverable()
- scan_mode = self.dut.sl4a.bluetoothGetScanMode()
- asserts.assert_equal(
- scan_mode, 3, # 3 signifies CONNECTABLE and DISCOVERABLE
- 'Android device %s failed to make blueooth discoverable.' %
- self.dut.serial)
-
- # Start the discovery process on #discoverer.
- self.discoverer.ed.clear_all_events()
- self.discoverer.sl4a.bluetoothStartDiscovery()
- self.discoverer.ed.pop_event(
- event_name='BluetoothDiscoveryFinished',
- timeout=self.bluetooth_timeout)
-
- # The following log entry demonstrates AndroidDevice log object, which
- # prefixes log entries with "[AndroidDevice|<serial>] "
- self.discoverer.log.info('Discovering other bluetooth devices.')
-
- # Get a list of discovered devices
- discovered_devices = self.discoverer.sl4a.bluetoothGetDiscoveredDevices()
- self.discoverer.log.info('Found devices: %s', discovered_devices)
- matching_devices = [d for d in discovered_devices
- if d.get('name') == self.bluetooth_name]
- if not matching_devices:
- asserts.fail('Android device %s did not discover %s.' %
- (self.discoverer.serial, self.dut.serial))
- self.discoverer.log.info('Discovered at least 1 device named '
- '%s: %s', self.bluetooth_name, matching_devices)
-
+ def setup_class(self):
+ # Registering android_device controller module, and declaring that the test
+ # requires at least two Android devices.
+ self.ads = self.register_controller(android_device, min_number=2)
+ # The device used to discover Bluetooth devices.
+ self.discoverer = android_device.get_device(
+ self.ads, label='discoverer')
+ # Sets the tag that represents this device in logs.
+ self.discoverer.debug_tag = 'discoverer'
+ # The device that is expected to be discovered
+ self.target = android_device.get_device(self.ads, label='target')
+ self.target.debug_tag = 'target'
+ self.target.load_snippet('mbs',
+ 'com.google.android.mobly.snippet.bundled')
+ self.discoverer.load_snippet(
+ 'mbs', 'com.google.android.mobly.snippet.bundled')
+
+ def setup_test(self):
+ # Make sure bluetooth is on.
+ self.target.mbs.btEnable()
+ self.discoverer.mbs.btEnable()
+ # Set Bluetooth name on target device.
+ self.target.mbs.btSetName('LookForMe!')
+
+ def test_bluetooth_discovery(self):
+ target_name = self.target.mbs.btGetName()
+ self.target.log.info('Become discoverable with name "%s" for %ds.',
+ target_name, DISCOVERABLE_TIME)
+ self.target.mbs.btBecomeDiscoverable(DISCOVERABLE_TIME)
+ self.discoverer.log.info('Looking for Bluetooth devices.')
+ discovered_devices = self.discoverer.mbs.btDiscoverAndGetResults()
+ self.discoverer.log.debug('Found Bluetooth devices: %s',
+ pprint.pformat(discovered_devices, indent=2))
+ discovered_names = [device['Name'] for device in discovered_devices]
+ logging.info('Verifying the target is discovered by the discoverer.')
+ asserts.assert_true(
+ target_name in discovered_names,
+ 'Failed to discover the target device %s over Bluetooth.' %
+ target_name)
+
+ def teardown_test(self):
+ # Turn Bluetooth off on both devices after test finishes.
+ self.target.mbs.btDisable()
+ self.discoverer.mbs.btDisable()
+
+
if __name__ == '__main__':
- test_runner.main()
+ test_runner.main()
+
```
-
-One will notice that this is not the most robust test (another nearby device
-could be using the same name), but in the interest of simplicity, we've limited
-the number of RPCs sent to each Android device to just two:
-
-* For `self.dut`, we asked it to make itself discoverable and checked that it
- did it.
-* For `self.discoverer`, we asked it to start scanning for nearby bluetooth
- devices, and then we pulled the list of devices seen.
-
-There's potentially a lot more we could do to write a thorough test (e.g., check
-the hardware address, see whether we can pair devices, transfer files, etc.).
-
-# Event Dispatcher
-
-You'll notice above that we've used `self.{device_alias}.ed.pop_event()`. The
-`ed` attribute of an Android device object is an EventDispatcher, which provides
-APIs to interact with async events.
-
-For example, `pop_event` is a function which will block until either a
-specified event is seen or the call times out, and by using it we avoid the use
-of busy loops that constantly check the device state. For more, see the APIs in
-`mobly.controllers.android_device_lib.event_dispatcher`.
+
+There's potentially a lot more we could do in this test, e.g. check
+the hardware address, see whether we can pair devices, transfer files, etc.
+
+To learn more about the features included in MBS, go to [MBS repo]
+(https://github.com/google/mobly-bundled-snippets) to see how to check its help
+menu.
+
+To learn more about Mobly Snippet Lib, including features like Espresso support
+and asynchronous calls, see the [snippet lib examples]
+(https://github.com/google/mobly-snippet-lib/tree/master/examples).
diff --git a/mobly/controllers/android_device.py b/mobly/controllers/android_device.py
index 159f587..a77e787 100644
--- a/mobly/controllers/android_device.py
+++ b/mobly/controllers/android_device.py
@@ -350,7 +350,7 @@ class AndroidDevice(object):
android device should be stored.
log: A logger adapted from root logger with an added prefix specific
to an AndroidDevice instance. The default prefix is
- [AndroidDevice|<serial>]. Use self.set_debug_tag to use a
+ [AndroidDevice|<serial>]. Use self.debug_tag = 'tag' to use a
different tag in the prefix.
adb_logcat_file_path: A string that's the full path to the adb logcat
file collected, if any.
@@ -408,6 +408,7 @@ class AndroidDevice(object):
The tag can be customized with `ad.debug_tag = 'Caller'`:
'INFO [AndroidDevice|Caller] One pending call ringing.'
"""
+ self.log.info('Logging debug tag set to "%s"', tag)
self._debug_tag = tag
self.log.extra['tag'] = tag
@@ -759,11 +760,11 @@ class AndroidDevice(object):
try:
extra_params = self.adb_logcat_param
except AttributeError:
- extra_params = '-b all'
+ extra_params = ''
cmd = 'adb -s %s logcat -v threadtime %s >> %s' % (
self.serial, extra_params, logcat_file_path)
- self._adb_logcat_process = utils.start_standing_subprocess(
- cmd, shell=True)
+ process = utils.start_standing_subprocess(cmd, shell=True)
+ self._adb_logcat_process = process
self.adb_logcat_file_path = logcat_file_path
def stop_adb_logcat(self):
|
google/mobly
|
5960e218c4006d8b7681ffe9698cbef160ad112f
|
diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py
index 136bbba..b1cd7fe 100755
--- a/tests/mobly/controllers/android_device_test.py
+++ b/tests/mobly/controllers/android_device_test.py
@@ -280,7 +280,7 @@ class AndroidDeviceTest(unittest.TestCase):
"AndroidDevice%s" % ad.serial,
"adblog,fakemodel,%s.txt" % ad.serial)
creat_dir_mock.assert_called_with(os.path.dirname(expected_log_path))
- adb_cmd = 'adb -s %s logcat -v threadtime -b all >> %s'
+ adb_cmd = 'adb -s %s logcat -v threadtime >> %s'
start_proc_mock.assert_called_with(
adb_cmd % (ad.serial, expected_log_path), shell=True)
self.assertEqual(ad.adb_logcat_file_path, expected_log_path)
|
logcat is empty for some NBU devices
When starting adb logcat, we use `-b all` to catch all buffers.
But some NBU devices (like HTC Desire 526g+) don't have the buffer option "all", and their adb logcat would only have one line saying "Unable to open log device '/dev/log/all': No such file or directory".
We need to handle this properly so we get the logs from the buffers the device does have, like 'main', 'system', 'radio', and 'events'.
|
0.0
|
5960e218c4006d8b7681ffe9698cbef160ad112f
|
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat"
] |
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_build_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_cat_adb_log",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_debug_tag",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_instantiation",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_attribute_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_package",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_snippet_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_snippet_cleanup",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fallback",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat_with_user_param",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_dict_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_empty_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_no_valid_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_not_list_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_pickup_all",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_string_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial_and_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_too_many_matches",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-04-28 05:46:23+00:00
|
apache-2.0
| 2,586 |
|
google__mobly-227
|
diff --git a/mobly/controllers/android_device_lib/snippet_client.py b/mobly/controllers/android_device_lib/snippet_client.py
index 4eb15e8..769140f 100644
--- a/mobly/controllers/android_device_lib/snippet_client.py
+++ b/mobly/controllers/android_device_lib/snippet_client.py
@@ -1,11 +1,11 @@
# Copyright 2016 Google Inc.
-#
+#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
-#
+#
# http://www.apache.org/licenses/LICENSE-2.0
-#
+#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -42,7 +42,7 @@ class Error(Exception):
pass
-class ProtocolVersionError(Error):
+class ProtocolVersionError(jsonrpc_client_base.AppStartError):
"""Raised when the protocol reported by the snippet is unknown."""
@@ -92,7 +92,7 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
# just warn and retry as v0.
# TODO(adorokhine): delete this in Mobly 1.6 when snippet v0 support is
# removed.
- line = self._read_line()
+ line = self._read_protocol_line()
if line in ('INSTRUMENTATION_RESULT: shortMsg=Process crashed.',
'INSTRUMENTATION_RESULT: shortMsg='
'java.lang.IllegalArgumentException'):
@@ -185,7 +185,8 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
def _connect_to_v0(self):
self.device_port = self.host_port
self._adb.forward(
- ['tcp:%d' % self.host_port, 'tcp:%d' % self.device_port])
+ ['tcp:%d' % self.host_port,
+ 'tcp:%d' % self.device_port])
start_time = time.time()
expiration_time = start_time + _APP_START_WAIT_TIME_V0
while time.time() < expiration_time:
@@ -203,19 +204,46 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
'%s failed to start on %s.' % (self.package, self._adb.serial))
def _connect_to_v1(self):
- line = self._read_line()
+ line = self._read_protocol_line()
match = re.match('^SNIPPET SERVING, PORT ([0-9]+)$', line)
if not match:
- raise ProtocolVersionError(line)
+ raise jsonrpc_client_base.AppStartError(line)
self.device_port = int(match.group(1))
# Forward the device port to a new host port, and connect to that port
self.host_port = utils.get_available_host_port()
self._adb.forward(
- ['tcp:%d' % self.host_port, 'tcp:%d' % self.device_port])
+ ['tcp:%d' % self.host_port,
+ 'tcp:%d' % self.device_port])
self.connect()
- def _read_line(self):
- line = self._proc.stdout.readline().rstrip()
- self.log.debug('Read line from instrumentation output: "%s"', line)
- return line
+ def _read_protocol_line(self):
+ """Reads the next line of instrumentation output relevant to snippets.
+
+ This method will skip over lines that don't start with 'SNIPPET' or
+ 'INSTRUMENTATION_RESULT'.
+
+ Returns:
+ (str) Next line of snippet-related instrumentation output, stripped.
+
+ Raises:
+ jsonrpc_client_base.AppStartError: If EOF is reached without any
+ protocol lines being read.
+ """
+ while True:
+ line = self._proc.stdout.readline().decode('utf-8')
+ if not line:
+ raise jsonrpc_client_base.AppStartError(
+ 'Unexpected EOF waiting for app to start')
+ # readline() uses an empty string to mark EOF, and a single newline
+ # to mark regular empty lines in the output. Don't move the strip()
+ # call above the truthiness check, or this method will start
+ # considering any blank output line to be EOF.
+ line = line.strip()
+ if (line.startswith('INSTRUMENTATION_RESULT:') or
+ line.startswith('SNIPPET ')):
+ self.log.debug(
+ 'Accepted line from instrumentation output: "%s"', line)
+ return line
+ self.log.debug('Discarded line from instrumentation output: "%s"',
+ line)
|
google/mobly
|
caffb80efb51ec19f73fcb334ada67bdeac1d390
|
diff --git a/tests/mobly/controllers/android_device_lib/snippet_client_test.py b/tests/mobly/controllers/android_device_lib/snippet_client_test.py
index 911f53e..244be5f 100755
--- a/tests/mobly/controllers/android_device_lib/snippet_client_test.py
+++ b/tests/mobly/controllers/android_device_lib/snippet_client_test.py
@@ -1,11 +1,11 @@
# Copyright 2017 Google Inc.
-#
+#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
-#
+#
# http://www.apache.org/licenses/LICENSE-2.0
-#
+#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -120,10 +120,129 @@ class SnippetClientTest(jsonrpc_client_test_base.JsonRpcClientTestBase):
with self.assertRaisesRegexp(jsonrpc_client_base.ApiError, '1'):
callback.getAll('eventName')
+ @mock.patch('socket.create_connection')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.start_standing_subprocess')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.get_available_host_port')
+ def test_snippet_start_app_and_connect_v1(self, mock_get_port,
+ mock_start_standing_subprocess,
+ mock_create_connection):
+ self.setup_mock_socket_file(mock_create_connection)
+ self._setup_mock_instrumentation_cmd(
+ mock_start_standing_subprocess,
+ resp_lines=[
+ b'SNIPPET START, PROTOCOL 1 0\n',
+ b'SNIPPET SERVING, PORT 123\n',
+ ])
+ client = self._make_client()
+ client.start_app_and_connect()
+ self.assertEqual(123, client.device_port)
+
+ @mock.patch('socket.create_connection')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.start_standing_subprocess')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.get_available_host_port')
+ def test_snippet_start_app_and_connect_v0(self, mock_get_port,
+ mock_start_standing_subprocess,
+ mock_create_connection):
+ mock_get_port.return_value = 456
+ self.setup_mock_socket_file(mock_create_connection)
+ self._setup_mock_instrumentation_cmd(
+ mock_start_standing_subprocess,
+ resp_lines=[b'INSTRUMENTATION_RESULT: shortMsg=Process crashed.\n'])
+ client = self._make_client()
+ client.start_app_and_connect()
+ self.assertEqual(456, client.device_port)
+
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.start_standing_subprocess')
+ def test_snippet_start_app_and_connect_unknown_protocol(
+ self, mock_start_standing_subprocess):
+ self._setup_mock_instrumentation_cmd(
+ mock_start_standing_subprocess,
+ resp_lines=[b'SNIPPET START, PROTOCOL 99 0\n'])
+ client = self._make_client()
+ with self.assertRaises(snippet_client.ProtocolVersionError):
+ client.start_app_and_connect()
+
+ @mock.patch('socket.create_connection')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.start_standing_subprocess')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.get_available_host_port')
+ def test_snippet_start_app_and_connect_v1_header_junk(
+ self, mock_get_port, mock_start_standing_subprocess,
+ mock_create_connection):
+ self.setup_mock_socket_file(mock_create_connection)
+ self._setup_mock_instrumentation_cmd(
+ mock_start_standing_subprocess,
+ resp_lines=[
+ b'This is some header junk\n',
+ b'Some phones print arbitrary output\n',
+ b'SNIPPET START, PROTOCOL 1 0\n',
+ b'Maybe in the middle too\n',
+ b'SNIPPET SERVING, PORT 123\n',
+ ])
+ client = self._make_client()
+ client.start_app_and_connect()
+ self.assertEqual(123, client.device_port)
+
+ @mock.patch('socket.create_connection')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.start_standing_subprocess')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.get_available_host_port')
+ def test_snippet_start_app_and_connect_v0_header_junk(
+ self, mock_get_port, mock_start_standing_subprocess,
+ mock_create_connection):
+ mock_get_port.return_value = 456
+ self.setup_mock_socket_file(mock_create_connection)
+ self._setup_mock_instrumentation_cmd(
+ mock_start_standing_subprocess,
+ resp_lines=[
+ b'This is some header junk\n',
+ b'Some phones print arbitrary output\n',
+ b'\n',
+ b'INSTRUMENTATION_RESULT: shortMsg=Process crashed.\n',
+ ])
+ client = self._make_client()
+ client.start_app_and_connect()
+ self.assertEqual(456, client.device_port)
+
+ @mock.patch('socket.create_connection')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.start_standing_subprocess')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.get_available_host_port')
+ def test_snippet_start_app_and_connect_no_valid_line(
+ self, mock_get_port, mock_start_standing_subprocess,
+ mock_create_connection):
+ mock_get_port.return_value = 456
+ self.setup_mock_socket_file(mock_create_connection)
+ self._setup_mock_instrumentation_cmd(
+ mock_start_standing_subprocess,
+ resp_lines=[
+ b'This is some header junk\n',
+ b'Some phones print arbitrary output\n',
+ b'', # readline uses '' to mark EOF
+ ])
+ client = self._make_client()
+ with self.assertRaisesRegexp(
+ jsonrpc_client_base.AppStartError,
+ 'Unexpected EOF waiting for app to start'):
+ client.start_app_and_connect()
+
def _make_client(self, adb_proxy=MockAdbProxy()):
return snippet_client.SnippetClient(
package=MOCK_PACKAGE_NAME, adb_proxy=adb_proxy)
+ def _setup_mock_instrumentation_cmd(self, mock_start_standing_subprocess,
+ resp_lines):
+ mock_proc = mock_start_standing_subprocess()
+ mock_proc.stdout.readline.side_effect = resp_lines
+
if __name__ == "__main__":
unittest.main()
|
Snippet crashes on phones that print extra instrumentation output.
Some phones print extra information prior to instrumentation output. On such phones, the snippet crashes.
|
0.0
|
caffb80efb51ec19f73fcb334ada67bdeac1d390
|
[
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_no_valid_line",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_unknown_protocol",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v0",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v0_header_junk",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v1",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v1_header_junk"
] |
[
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_app_not_installed",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_not_instrumented",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_target_not_installed",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_normal",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_event_client"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-06-02 07:17:53+00:00
|
apache-2.0
| 2,587 |
|
google__mobly-238
|
diff --git a/mobly/records.py b/mobly/records.py
index ae550d9..6c5efe2 100644
--- a/mobly/records.py
+++ b/mobly/records.py
@@ -262,11 +262,12 @@ class TestResult(object):
Args:
record: A test record object to add.
"""
+ if record.result == TestResultEnums.TEST_RESULT_SKIP:
+ self.skipped.append(record)
+ return
self.executed.append(record)
if record.result == TestResultEnums.TEST_RESULT_FAIL:
self.failed.append(record)
- elif record.result == TestResultEnums.TEST_RESULT_SKIP:
- self.skipped.append(record)
elif record.result == TestResultEnums.TEST_RESULT_PASS:
self.passed.append(record)
else:
@@ -283,14 +284,32 @@ class TestResult(object):
self.controller_info[name] = info
def fail_class(self, test_record):
- """Add a record to indicate a test class setup has failed and no test
- in the class was executed.
+ """Add a record to indicate a test class has failed before any test
+ could execute.
+
+ This is only called before any test is actually executed. So it only
+ adds an error entry that describes why the class failed to the tally
+ and does not affect the total number of tests requrested or exedcuted.
Args:
test_record: A TestResultRecord object for the test class.
"""
- self.executed.append(test_record)
- self.failed.append(test_record)
+ self.error.append(test_record)
+
+ def is_test_executed(self, test_name):
+ """Checks if a specific test has been executed.
+
+ Args:
+ test_name: string, the name of the test to check.
+
+ Returns:
+ True if the test has been executed according to the test result,
+ False otherwise.
+ """
+ for record in self.executed:
+ if record.test_name == test_name:
+ return True
+ return False
@property
def is_all_pass(self):
|
google/mobly
|
310791d8d2faa9f554fddb0a5ce11ae249156bb4
|
diff --git a/mobly/base_test.py b/mobly/base_test.py
index a83334d..b5176a4 100644
--- a/mobly/base_test.py
+++ b/mobly/base_test.py
@@ -344,6 +344,12 @@ class BaseTestClass(object):
test_method(*args, **kwargs)
else:
test_method()
+ except signals.TestPass as e:
+ raise e
+ except Exception as e:
+ logging.exception('Exception occurred in %s.',
+ self.current_test_name)
+ raise e
finally:
try:
self._teardown_test(test_name)
@@ -354,7 +360,6 @@ class BaseTestClass(object):
tr_record.add_error('teardown_test', e)
self._exec_procedure_func(self._on_fail, tr_record)
except (signals.TestFailure, AssertionError) as e:
- logging.exception(e)
tr_record.test_fail(e)
self._exec_procedure_func(self._on_fail, tr_record)
except signals.TestSkip as e:
@@ -374,7 +379,6 @@ class BaseTestClass(object):
is_generate_trigger = True
self.results.requested.remove(test_name)
except Exception as e:
- logging.exception(e)
# Exception happened during test.
tr_record.test_error(e)
self._exec_procedure_func(self._on_fail, tr_record)
@@ -547,6 +551,22 @@ class BaseTestClass(object):
test_methods.append((test_name, test_method))
return test_methods
+ def _skip_remaining_tests(self, exception):
+ """Marks any requested test that has not been executed in a class as
+ skipped.
+
+ This is useful for handling abort class signal.
+
+ Args:
+ exception: The exception object that was thrown to trigger the
+ skip.
+ """
+ for test_name in self.results.requested:
+ if not self.results.is_test_executed(test_name):
+ test_record = records.TestResultRecord(test_name, self.TAG)
+ test_record.test_skip(exception)
+ self.results.add_record(test_record)
+
def run(self, test_names=None):
"""Runs tests within a test class.
@@ -591,21 +611,33 @@ class BaseTestClass(object):
# Setup for the class.
try:
self._setup_class()
+ except signals.TestAbortClass as e:
+ # The test class is intentionally aborted.
+ # Skip all tests peacefully.
+ e.details = 'Test class aborted due to: %s' % e.details
+ self._skip_remaining_tests(e)
+ return self.results
except Exception as e:
+ # Setup class failed for unknown reasons.
+ # Fail the class and skip all tests.
logging.exception('Failed to setup %s.', self.TAG)
class_record = records.TestResultRecord('setup_class', self.TAG)
class_record.test_begin()
class_record.test_fail(e)
self._exec_procedure_func(self._on_fail, class_record)
self.results.fail_class(class_record)
- self._safe_exec_func(self.teardown_class)
+ self._skip_remaining_tests(e)
return self.results
+ finally:
+ self._safe_exec_func(self.teardown_class)
# Run tests in order.
try:
for test_name, test_method in tests:
self.exec_one_test(test_name, test_method)
return self.results
- except signals.TestAbortClass:
+ except signals.TestAbortClass as e:
+ e.details = 'Test class aborted due to: %s' % e.details
+ self._skip_remaining_tests(e)
return self.results
except signals.TestAbortAll as e:
# Piggy-back test results on this exception object so we don't lose
diff --git a/tests/mobly/base_test_test.py b/tests/mobly/base_test_test.py
index 0ed05f7..c9d517b 100755
--- a/tests/mobly/base_test_test.py
+++ b/tests/mobly/base_test_test.py
@@ -168,6 +168,10 @@ class BaseTestTest(unittest.TestCase):
# This should not execute because setup_class failed.
never_call()
+ def test_something2(self):
+ # This should not execute because setup_class failed.
+ never_call()
+
def teardown_class(self):
# This should execute because the setup_class failure should
# have already been recorded.
@@ -179,12 +183,12 @@ class BaseTestTest(unittest.TestCase):
bt_cls = MockBaseTest(self.mock_test_cls_configs)
bt_cls.run()
- actual_record = bt_cls.results.failed[0]
+ actual_record = bt_cls.results.error[0]
self.assertEqual(actual_record.test_name, "setup_class")
self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
self.assertIsNone(actual_record.extras)
- expected_summary = ("Error 0, Executed 1, Failed 1, Passed 0, "
- "Requested 1, Skipped 0")
+ expected_summary = ("Error 1, Executed 0, Failed 0, Passed 0, "
+ "Requested 2, Skipped 2")
self.assertEqual(bt_cls.results.summary_str(), expected_summary)
teardown_class_call_check.assert_called_once_with("heehee")
on_fail_call_check.assert_called_once_with("haha")
@@ -526,7 +530,33 @@ class BaseTestTest(unittest.TestCase):
"Requested 1, Skipped 0")
self.assertEqual(bt_cls.results.summary_str(), expected_summary)
- def test_abort_class(self):
+ def test_abort_setup_class(self):
+ """A class was intentionally aborted by the test.
+
+ This is not considered an error as the abort class is used as a skip
+ signal for the entire class, which is different from raising other
+ exceptions in `setup_class`.
+ """
+ class MockBaseTest(base_test.BaseTestClass):
+ def setup_class(self):
+ asserts.abort_class(MSG_EXPECTED_EXCEPTION)
+
+ def test_1(self):
+ never_call()
+
+ def test_2(self):
+ never_call()
+
+ def test_3(self):
+ never_call()
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.run(test_names=["test_1", "test_2", "test_3"])
+ self.assertEqual(bt_cls.results.summary_str(),
+ ("Error 0, Executed 0, Failed 0, Passed 0, "
+ "Requested 3, Skipped 3"))
+
+ def test_abort_class_in_test(self):
class MockBaseTest(base_test.BaseTestClass):
def test_1(self):
pass
@@ -545,7 +575,7 @@ class BaseTestTest(unittest.TestCase):
MSG_EXPECTED_EXCEPTION)
self.assertEqual(bt_cls.results.summary_str(),
("Error 0, Executed 2, Failed 1, Passed 1, "
- "Requested 3, Skipped 0"))
+ "Requested 3, Skipped 1"))
def test_uncaught_exception(self):
class MockBaseTest(base_test.BaseTestClass):
@@ -958,12 +988,12 @@ class BaseTestTest(unittest.TestCase):
bt_cls = MockBaseTest(self.mock_test_cls_configs)
bt_cls.run()
- actual_record = bt_cls.results.failed[0]
+ actual_record = bt_cls.results.error[0]
self.assertEqual(actual_record.test_name, "setup_generated_tests")
self.assertEqual(
actual_record.details,
'Test name "ha" already exists, cannot be duplicated!')
- expected_summary = ("Error 0, Executed 1, Failed 1, Passed 0, "
+ expected_summary = ("Error 1, Executed 0, Failed 0, Passed 0, "
"Requested 0, Skipped 0")
self.assertEqual(bt_cls.results.summary_str(), expected_summary)
diff --git a/tests/mobly/records_test.py b/tests/mobly/records_test.py
index d74c00b..9500d1d 100755
--- a/tests/mobly/records_test.py
+++ b/tests/mobly/records_test.py
@@ -219,8 +219,8 @@ class RecordsTest(unittest.TestCase):
record2 = records.TestResultRecord("SomeTest", s)
tr.fail_class(record2)
self.assertEqual(len(tr.passed), 1)
- self.assertEqual(len(tr.failed), 1)
- self.assertEqual(len(tr.executed), 2)
+ self.assertEqual(len(tr.error), 1)
+ self.assertEqual(len(tr.executed), 1)
def test_result_fail_class_with_special_error(self):
"""Call TestResult.fail_class with an error class that requires more
@@ -241,8 +241,8 @@ class RecordsTest(unittest.TestCase):
record2 = records.TestResultRecord("SomeTest", se)
tr.fail_class(record2)
self.assertEqual(len(tr.passed), 1)
- self.assertEqual(len(tr.failed), 1)
- self.assertEqual(len(tr.executed), 2)
+ self.assertEqual(len(tr.error), 1)
+ self.assertEqual(len(tr.executed), 1)
def test_is_all_pass(self):
s = signals.TestPass(self.details, self.float_extra)
@@ -284,6 +284,15 @@ class RecordsTest(unittest.TestCase):
tr.fail_class(record1)
self.assertFalse(tr.is_all_pass)
+ def test_is_test_executed(self):
+ record1 = records.TestResultRecord(self.tn)
+ record1.test_begin()
+ record1.test_fail(Exception("haha"))
+ tr = records.TestResult()
+ tr.add_record(record1)
+ self.assertTrue(tr.is_test_executed(record1.test_name))
+ self.assertFalse(tr.is_test_executed(self.tn + 'ha'))
+
if __name__ == "__main__":
unittest.main()
|
Properly report skipped test classes
Now that we have a way to reliably get all the tests in a class, including the generated tests, the test report for an aborted class should include entries for all the tests requested, instead of only one entry for the class.
|
0.0
|
310791d8d2faa9f554fddb0a5ce11ae249156bb4
|
[
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_dup_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_class_fail_by_exception",
"tests/mobly/records_test.py::RecordsTest::test_is_test_executed",
"tests/mobly/records_test.py::RecordsTest::test_result_fail_class_with_special_error",
"tests/mobly/records_test.py::RecordsTest::test_result_fail_class_with_test_signal"
] |
[
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail_with_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_regex",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_both_teardown_and_test_body_raise_exceptions",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_override_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_default_execution_of_all_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass_but_teardown_test_raises_an_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_in_procedure_functions_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_to_call_procedure_function_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_call_outside_of_setup_generated_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_selected_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_generated_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_implicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_missing_requested_test_func",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_setup_fails_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_test_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_if",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_assert_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_setup_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_uncaught_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_basic",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_None",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_optional_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_required_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_missing",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_with_default",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required_missing",
"tests/mobly/records_test.py::RecordsTest::test_is_all_pass",
"tests/mobly/records_test.py::RecordsTest::test_is_all_pass_negative",
"tests/mobly/records_test.py::RecordsTest::test_is_all_pass_with_fail_class",
"tests/mobly/records_test.py::RecordsTest::test_result_add_operator_success",
"tests/mobly/records_test.py::RecordsTest::test_result_add_operator_type_mismatch",
"tests/mobly/records_test.py::RecordsTest::test_result_record_fail_none",
"tests/mobly/records_test.py::RecordsTest::test_result_record_fail_stacktrace",
"tests/mobly/records_test.py::RecordsTest::test_result_record_fail_with_float_extra",
"tests/mobly/records_test.py::RecordsTest::test_result_record_fail_with_json_extra",
"tests/mobly/records_test.py::RecordsTest::test_result_record_pass_none",
"tests/mobly/records_test.py::RecordsTest::test_result_record_pass_with_float_extra",
"tests/mobly/records_test.py::RecordsTest::test_result_record_pass_with_json_extra",
"tests/mobly/records_test.py::RecordsTest::test_result_record_skip_none",
"tests/mobly/records_test.py::RecordsTest::test_result_record_skip_with_float_extra",
"tests/mobly/records_test.py::RecordsTest::test_result_record_skip_with_json_extra"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2017-06-30 19:50:04+00:00
|
apache-2.0
| 2,588 |
|
google__mobly-248
|
diff --git a/mobly/records.py b/mobly/records.py
index 6c5efe2..0b67c9d 100644
--- a/mobly/records.py
+++ b/mobly/records.py
@@ -14,6 +14,7 @@
"""This module is where all the record definitions and record containers live.
"""
+import itertools
import json
import logging
import pprint
@@ -283,7 +284,7 @@ class TestResult(object):
return
self.controller_info[name] = info
- def fail_class(self, test_record):
+ def add_class_error(self, test_record):
"""Add a record to indicate a test class has failed before any test
could execute.
@@ -337,7 +338,9 @@ class TestResult(object):
"""
d = {}
d['ControllerInfo'] = self.controller_info
- d['Results'] = [record.to_dict() for record in self.executed]
+ records_to_write = itertools.chain(self.passed, self.failed,
+ self.skipped, self.error)
+ d['Results'] = [record.to_dict() for record in records_to_write]
d['Summary'] = self.summary_dict()
json_str = json.dumps(d, indent=4, sort_keys=True)
return json_str
|
google/mobly
|
31dcff279d4808e011f6af8ab0661b9750357cda
|
diff --git a/mobly/base_test.py b/mobly/base_test.py
index 355603e..e85551a 100644
--- a/mobly/base_test.py
+++ b/mobly/base_test.py
@@ -343,12 +343,12 @@ class BaseTestClass(object):
test_method(*args, **kwargs)
else:
test_method()
- except signals.TestPass as e:
- raise e
- except Exception as e:
+ except signals.TestPass:
+ raise
+ except Exception:
logging.exception('Exception occurred in %s.',
self.current_test_name)
- raise e
+ raise
finally:
try:
self._teardown_test(test_name)
@@ -531,8 +531,8 @@ class BaseTestClass(object):
class_record = records.TestResultRecord('setup_generated_tests',
self.TAG)
class_record.test_begin()
- class_record.test_fail(e)
- self.results.fail_class(class_record)
+ class_record.test_error(e)
+ self.results.add_class_error(class_record)
return self.results
logging.info('==========> %s <==========', self.TAG)
# Devise the actual test methods to run in the test class.
@@ -551,18 +551,18 @@ class BaseTestClass(object):
except signals.TestAbortClass as e:
# The test class is intentionally aborted.
# Skip all tests peacefully.
- e.details = 'Test class aborted due to: %s' % e.details
+ e.details = 'setup_class aborted due to: %s' % e.details
self._skip_remaining_tests(e)
return self.results
except Exception as e:
# Setup class failed for unknown reasons.
# Fail the class and skip all tests.
- logging.exception('Failed to setup %s.', self.TAG)
+ logging.exception('Error in setup_class %s.', self.TAG)
class_record = records.TestResultRecord('setup_class', self.TAG)
class_record.test_begin()
- class_record.test_fail(e)
+ class_record.test_error(e)
self._exec_procedure_func(self._on_fail, class_record)
- self.results.fail_class(class_record)
+ self.results.add_class_error(class_record)
self._skip_remaining_tests(e)
return self.results
finally:
diff --git a/tests/mobly/base_test_test.py b/tests/mobly/base_test_test.py
index 65caf6f..da036ea 100755
--- a/tests/mobly/base_test_test.py
+++ b/tests/mobly/base_test_test.py
@@ -20,6 +20,10 @@ from mobly import base_test
from mobly import config_parser
from mobly import signals
+from tests.mobly import records_test
+
+validate_test_result = records_test.validate_test_result
+
MSG_EXPECTED_EXCEPTION = "This is an expected exception."
MSG_EXPECTED_TEST_FAILURE = "This is an expected test failure."
MSG_UNEXPECTED_EXCEPTION = "Unexpected exception!"
@@ -187,7 +191,9 @@ class BaseTestTest(unittest.TestCase):
bt_cls = MockBaseTest(self.mock_test_cls_configs)
bt_cls.run()
actual_record = bt_cls.results.error[0]
+ validate_test_result(bt_cls.results)
self.assertEqual(actual_record.test_name, "setup_class")
+
self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
self.assertIsNone(actual_record.extras)
expected_summary = ("Error 1, Executed 0, Failed 0, Passed 0, "
@@ -540,6 +546,7 @@ class BaseTestTest(unittest.TestCase):
signal for the entire class, which is different from raising other
exceptions in `setup_class`.
"""
+
class MockBaseTest(base_test.BaseTestClass):
def setup_class(self):
asserts.abort_class(MSG_EXPECTED_EXCEPTION)
@@ -555,6 +562,7 @@ class BaseTestTest(unittest.TestCase):
bt_cls = MockBaseTest(self.mock_test_cls_configs)
bt_cls.run(test_names=["test_1", "test_2", "test_3"])
+ self.assertEqual(len(bt_cls.results.skipped), 3)
self.assertEqual(bt_cls.results.summary_str(),
("Error 0, Executed 0, Failed 0, Passed 0, "
"Requested 3, Skipped 3"))
@@ -966,6 +974,7 @@ class BaseTestTest(unittest.TestCase):
bt_cls = MockBaseTest(self.mock_test_cls_configs)
bt_cls.run()
actual_record = bt_cls.results.error[0]
+ validate_test_result(bt_cls.results)
self.assertEqual(actual_record.test_name, "test_ha")
self.assertEqual(
actual_record.details,
diff --git a/tests/mobly/records_test.py b/tests/mobly/records_test.py
index 9500d1d..f1ee1ed 100755
--- a/tests/mobly/records_test.py
+++ b/tests/mobly/records_test.py
@@ -18,6 +18,26 @@ from mobly import records
from mobly import signals
+def validate_test_result(result):
+ """Validate basic properties of a test result.
+
+ The records in each bucket of the test result should have the corresponding
+ result enum.
+
+ Args:
+ result: The TestResult object to validate.
+ """
+ buckets = [
+ (result.passed, records.TestResultEnums.TEST_RESULT_PASS),
+ (result.failed, records.TestResultEnums.TEST_RESULT_FAIL),
+ (result.error, records.TestResultEnums.TEST_RESULT_ERROR),
+ (result.skipped, records.TestResultEnums.TEST_RESULT_SKIP),
+ ]
+ for bucket_list, expected_enum in buckets:
+ for record in bucket_list:
+ assert record.result == expected_enum
+
+
class RecordsTest(unittest.TestCase):
"""This test class tests the implementation of classes in mobly.records.
"""
@@ -208,7 +228,7 @@ class RecordsTest(unittest.TestCase):
with self.assertRaisesRegexp(TypeError, expected_msg):
tr1 += "haha"
- def test_result_fail_class_with_test_signal(self):
+ def test_result_add_class_error_with_test_signal(self):
record1 = records.TestResultRecord(self.tn)
record1.test_begin()
s = signals.TestPass(self.details, self.float_extra)
@@ -217,13 +237,13 @@ class RecordsTest(unittest.TestCase):
tr.add_record(record1)
s = signals.TestFailure(self.details, self.float_extra)
record2 = records.TestResultRecord("SomeTest", s)
- tr.fail_class(record2)
+ tr.add_class_error(record2)
self.assertEqual(len(tr.passed), 1)
self.assertEqual(len(tr.error), 1)
self.assertEqual(len(tr.executed), 1)
- def test_result_fail_class_with_special_error(self):
- """Call TestResult.fail_class with an error class that requires more
+ def test_result_add_class_error_with_special_error(self):
+ """Call TestResult.add_class_error with an error class that requires more
than one arg to instantiate.
"""
record1 = records.TestResultRecord(self.tn)
@@ -239,7 +259,7 @@ class RecordsTest(unittest.TestCase):
se = SpecialError("haha", 42)
record2 = records.TestResultRecord("SomeTest", se)
- tr.fail_class(record2)
+ tr.add_class_error(record2)
self.assertEqual(len(tr.passed), 1)
self.assertEqual(len(tr.error), 1)
self.assertEqual(len(tr.executed), 1)
@@ -271,17 +291,18 @@ class RecordsTest(unittest.TestCase):
tr = records.TestResult()
tr.add_record(record1)
tr.add_record(record2)
+ validate_test_result(tr)
self.assertFalse(tr.is_all_pass)
- def test_is_all_pass_with_fail_class(self):
- """Verifies that is_all_pass yields correct value when fail_class is
+ def test_is_all_pass_with_add_class_error(self):
+ """Verifies that is_all_pass yields correct value when add_class_error is
used.
"""
record1 = records.TestResultRecord(self.tn)
record1.test_begin()
record1.test_fail(Exception("haha"))
tr = records.TestResult()
- tr.fail_class(record1)
+ tr.add_class_error(record1)
self.assertFalse(tr.is_all_pass)
def test_is_test_executed(self):
|
Stacktrace is lost in test_summary.json
The reraise in base_test.py in 349-352 here loses the stacktrace:
https://github.com/google/mobly/pull/241
|
0.0
|
31dcff279d4808e011f6af8ab0661b9750357cda
|
[
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_dup_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_class_fail_by_exception",
"tests/mobly/records_test.py::RecordsTest::test_is_all_pass_with_add_class_error",
"tests/mobly/records_test.py::RecordsTest::test_result_add_class_error_with_special_error",
"tests/mobly/records_test.py::RecordsTest::test_result_add_class_error_with_test_signal"
] |
[
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail_with_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_regex",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_both_teardown_and_test_body_raise_exceptions",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_override_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_default_execution_of_all_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass_but_teardown_test_raises_an_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_in_procedure_functions_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_to_call_procedure_function_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_call_outside_of_setup_generated_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_selected_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_implicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_missing_requested_test_func",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_setup_fails_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_test_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_if",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_assert_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_setup_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_uncaught_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_basic",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_None",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_optional_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_required_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_missing",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_with_default",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required_missing",
"tests/mobly/records_test.py::RecordsTest::test_is_all_pass",
"tests/mobly/records_test.py::RecordsTest::test_is_all_pass_negative",
"tests/mobly/records_test.py::RecordsTest::test_is_test_executed",
"tests/mobly/records_test.py::RecordsTest::test_result_add_operator_success",
"tests/mobly/records_test.py::RecordsTest::test_result_add_operator_type_mismatch",
"tests/mobly/records_test.py::RecordsTest::test_result_record_fail_none",
"tests/mobly/records_test.py::RecordsTest::test_result_record_fail_stacktrace",
"tests/mobly/records_test.py::RecordsTest::test_result_record_fail_with_float_extra",
"tests/mobly/records_test.py::RecordsTest::test_result_record_fail_with_json_extra",
"tests/mobly/records_test.py::RecordsTest::test_result_record_pass_none",
"tests/mobly/records_test.py::RecordsTest::test_result_record_pass_with_float_extra",
"tests/mobly/records_test.py::RecordsTest::test_result_record_pass_with_json_extra",
"tests/mobly/records_test.py::RecordsTest::test_result_record_skip_none",
"tests/mobly/records_test.py::RecordsTest::test_result_record_skip_with_float_extra",
"tests/mobly/records_test.py::RecordsTest::test_result_record_skip_with_json_extra"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-07-11 11:28:03+00:00
|
apache-2.0
| 2,589 |
|
google__mobly-258
|
diff --git a/mobly/controllers/android_device_lib/callback_handler.py b/mobly/controllers/android_device_lib/callback_handler.py
index 4207f47..1ab67d8 100644
--- a/mobly/controllers/android_device_lib/callback_handler.py
+++ b/mobly/controllers/android_device_lib/callback_handler.py
@@ -83,13 +83,14 @@ class CallbackHandler(object):
(timeout, MAX_TIMEOUT))
timeout *= 1000 # convert to milliseconds for java side
try:
- raw_event = self._event_client.eventWaitAndGet(self._id,
- event_name, timeout)
+ raw_event = self._event_client.eventWaitAndGet(
+ self._id, event_name, timeout)
except Exception as e:
if 'EventSnippetException: timeout.' in str(e):
raise TimeoutError(
- 'Timeout waiting for event "%s" triggered by %s (%s).' %
- (event_name, self._method_name, self._id))
+ 'Timed out after waiting %ss for event "%s" triggered by'
+ ' %s (%s).' % (timeout, event_name, self._method_name,
+ self._id))
raise
return snippet_event.from_dict(raw_event)
diff --git a/mobly/controllers/android_device_lib/snippet_client.py b/mobly/controllers/android_device_lib/snippet_client.py
index 3d85e40..f7f473b 100644
--- a/mobly/controllers/android_device_lib/snippet_client.py
+++ b/mobly/controllers/android_device_lib/snippet_client.py
@@ -24,15 +24,27 @@ _INSTRUMENTATION_RUNNER_PACKAGE = (
'com.google.android.mobly.snippet.SnippetRunner')
# TODO(adorokhine): delete this in Mobly 1.6 when snippet v0 support is removed.
-_LAUNCH_CMD_V0 = ('am instrument -w -e action start -e port %s %s/' +
+_LAUNCH_CMD_V0 = ('%s am instrument -w -e action start -e port %s %s/' +
_INSTRUMENTATION_RUNNER_PACKAGE)
_LAUNCH_CMD_V1 = (
- 'am instrument -w -e action start %s/' + _INSTRUMENTATION_RUNNER_PACKAGE)
+ '%s am instrument -w -e action start %s/' + _INSTRUMENTATION_RUNNER_PACKAGE)
_STOP_CMD = (
'am instrument -w -e action stop %s/' + _INSTRUMENTATION_RUNNER_PACKAGE)
+# Test that uses UiAutomation requires the shell session to be maintained while
+# test is in progress. However, this requirement does not hold for the test that
+# deals with device USB disconnection (Once device disconnects, the shell
+# session that started the instrument ends, and UiAutomation fails with error:
+# "UiAutomation not connected"). To keep the shell session and redirect
+# stdin/stdout/stderr, use "setsid" or "nohup" while launching the
+# instrumentation test. Because these commands may not be available in every
+# android system, try to use them only if exists.
+_SETSID_COMMAND = 'setsid'
+
+_NOHUP_COMMAND = 'nohup'
+
# Maximum time to wait for a v0 snippet to start on the device (10 minutes).
# TODO(adorokhine): delete this in Mobly 1.6 when snippet v0 support is removed.
_APP_START_WAIT_TIME_V0 = 10 * 60
@@ -60,7 +72,7 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
def __init__(self, package, adb_proxy, log=logging.getLogger()):
"""Initializes a SnippetClient.
-
+
Args:
package: (str) The package name of the apk where the snippets are
defined.
@@ -77,13 +89,14 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
"""Overrides superclass. Launches a snippet app and connects to it."""
self._check_app_installed()
+ persists_shell_cmd = self._get_persist_command()
# Try launching the app with the v1 protocol. If that fails, fall back
# to v0 for compatibility. Use info here so people know exactly what's
# happening here, which is helpful since they need to create their own
# instrumentations and manifest.
self.log.info('Launching snippet apk %s with protocol v1',
self.package)
- cmd = _LAUNCH_CMD_V1 % self.package
+ cmd = _LAUNCH_CMD_V1 % (persists_shell_cmd, self.package)
start_time = time.time()
self._proc = self._do_start_app(cmd)
@@ -106,7 +119,7 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
# Reuse the host port as the device port in v0 snippet. This isn't
# safe in general, but the protocol is deprecated.
self.device_port = self.host_port
- cmd = _LAUNCH_CMD_V0 % (self.device_port, self.package)
+ cmd = _LAUNCH_CMD_V0 % (persists_shell_cmd, self.device_port, self.package)
self._proc = self._do_start_app(cmd)
self._connect_to_v0()
self._launch_version = 'v0'
@@ -291,3 +304,17 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
return line
self.log.debug('Discarded line from instrumentation output: "%s"',
line)
+
+ def _get_persist_command(self):
+ """Check availability and return path of command if available."""
+ for command in [_SETSID_COMMAND, _NOHUP_COMMAND]:
+ try:
+ if command in self._adb.shell('which %s' % command):
+ return command
+ except adb.AdbError:
+ continue
+ self.log.warning('No %s and %s commands available to launch instrument '
+ 'persistently, tests that depend on UiAutomator and '
+ 'at the same time performs USB disconnection may fail',
+ _SETSID_COMMAND, _NOHUP_COMMAND)
+ return ''
|
google/mobly
|
c9ba28477626c6f7d5365bec019646f915a5bd2d
|
diff --git a/mobly/base_test.py b/mobly/base_test.py
index e85551a..b3ccf43 100644
--- a/mobly/base_test.py
+++ b/mobly/base_test.py
@@ -553,6 +553,7 @@ class BaseTestClass(object):
# Skip all tests peacefully.
e.details = 'setup_class aborted due to: %s' % e.details
self._skip_remaining_tests(e)
+ self._safe_exec_func(self.teardown_class)
return self.results
except Exception as e:
# Setup class failed for unknown reasons.
@@ -564,9 +565,8 @@ class BaseTestClass(object):
self._exec_procedure_func(self._on_fail, class_record)
self.results.add_class_error(class_record)
self._skip_remaining_tests(e)
- return self.results
- finally:
self._safe_exec_func(self.teardown_class)
+ return self.results
# Run tests in order.
try:
for test_name, test_method in tests:
diff --git a/tests/mobly/base_test_test.py b/tests/mobly/base_test_test.py
index 725dcda..db615dd 100755
--- a/tests/mobly/base_test_test.py
+++ b/tests/mobly/base_test_test.py
@@ -38,7 +38,6 @@ class SomeError(Exception):
class BaseTestTest(unittest.TestCase):
-
def setUp(self):
self.mock_test_cls_configs = config_parser.TestRunConfig()
self.mock_test_cls_configs.log_path = '/tmp'
@@ -566,6 +565,25 @@ class BaseTestTest(unittest.TestCase):
("Error 0, Executed 0, Failed 0, Passed 0, "
"Requested 3, Skipped 3"))
+ def test_setup_and_teardown_execution_count(self):
+ class MockBaseTest(base_test.BaseTestClass):
+ def test_func(self):
+ pass
+
+ def test_func2(self):
+ pass
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.setup_class = mock.Mock()
+ bt_cls.teardown_class = mock.Mock()
+ bt_cls.setup_test = mock.Mock()
+ bt_cls.teardown_test = mock.Mock()
+ bt_cls.run()
+ self.assertEqual(bt_cls.setup_class.call_count, 1)
+ self.assertEqual(bt_cls.teardown_class.call_count, 1)
+ self.assertEqual(bt_cls.setup_test.call_count, 2)
+ self.assertEqual(bt_cls.teardown_test.call_count, 2)
+
def test_abort_class_in_test(self):
class MockBaseTest(base_test.BaseTestClass):
def test_1(self):
diff --git a/tests/mobly/controllers/android_device_lib/callback_handler_test.py b/tests/mobly/controllers/android_device_lib/callback_handler_test.py
index a701d51..f288ef3 100755
--- a/tests/mobly/controllers/android_device_lib/callback_handler_test.py
+++ b/tests/mobly/controllers/android_device_lib/callback_handler_test.py
@@ -34,6 +34,7 @@ MOCK_RAW_EVENT = {
class CallbackHandlerTest(unittest.TestCase):
"""Unit tests for mobly.controllers.android_device_lib.callback_handler.
"""
+
def test_timeout_value(self):
self.assertGreaterEqual(jsonrpc_client_base._SOCKET_READ_TIMEOUT,
callback_handler.MAX_TIMEOUT)
@@ -64,9 +65,9 @@ class CallbackHandlerTest(unittest.TestCase):
event_client=mock_event_client,
ret_value=None,
method_name=None)
- expected_msg = 'Timeout waiting for event "ha" .*'
+ expected_msg = 'Timed out after waiting .*s for event "ha" .*'
with self.assertRaisesRegex(callback_handler.TimeoutError,
- expected_msg):
+ expected_msg):
handler.waitAndGet('ha')
def test_wait_for_event(self):
@@ -101,7 +102,7 @@ class CallbackHandlerTest(unittest.TestCase):
return False
with self.assertRaisesRegex(callback_handler.TimeoutError,
- expected_msg):
+ expected_msg):
handler.waitForEvent('AsyncTaskResult', some_condition, 0.01)
diff --git a/tests/mobly/controllers/android_device_lib/snippet_client_test.py b/tests/mobly/controllers/android_device_lib/snippet_client_test.py
index 010064c..beb9262 100755
--- a/tests/mobly/controllers/android_device_lib/snippet_client_test.py
+++ b/tests/mobly/controllers/android_device_lib/snippet_client_test.py
@@ -18,6 +18,7 @@ from builtins import bytes
import mock
from future.tests.base import unittest
+from mobly.controllers.android_device_lib import adb
from mobly.controllers.android_device_lib import jsonrpc_client_base
from mobly.controllers.android_device_lib import snippet_client
from tests.lib import jsonrpc_client_test_base
@@ -51,6 +52,8 @@ class MockAdbProxy(object):
return bytes('instrumentation:{p}/{r} (target={p})'.format(
p=MOCK_PACKAGE_NAME,
r=snippet_client._INSTRUMENTATION_RUNNER_PACKAGE), 'utf-8')
+ elif 'which' in params:
+ return ''
def __getattr__(self, name):
"""All calls to the none-existent functions in adb proxy would
@@ -175,6 +178,73 @@ class SnippetClientTest(jsonrpc_client_test_base.JsonRpcClientTestBase):
client.start_app_and_connect()
self.assertEqual(123, client.device_port)
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'SnippetClient._do_start_app')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'SnippetClient._check_app_installed')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'SnippetClient._read_protocol_line')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'SnippetClient._connect_to_v1')
+ @mock.patch('mobly.controllers.android_device_lib.snippet_client.'
+ 'utils.get_available_host_port')
+ def test_snippet_start_app_and_connect_v1_persistent_session(
+ self, mock_get_port, mock_connect_to_v1, mock_read_protocol_line,
+ mock_check_app_installed, mock_do_start_app):
+
+ def _mocked_shell(arg):
+ if 'setsid' in arg:
+ raise adb.AdbError('cmd', 'stdout', 'stderr', 'ret_code')
+ else:
+ return 'nohup'
+
+ mock_get_port.return_value = 123
+ mock_read_protocol_line.side_effect = [
+ 'SNIPPET START, PROTOCOL 1 234',
+ 'SNIPPET SERVING, PORT 1234',
+ 'SNIPPET START, PROTOCOL 1 234',
+ 'SNIPPET SERVING, PORT 1234',
+ 'SNIPPET START, PROTOCOL 1 234',
+ 'SNIPPET SERVING, PORT 1234',
+ ]
+
+ # Test 'setsid' exists
+ client = self._make_client()
+ client._adb.shell = mock.Mock(return_value='setsid')
+ client.start_app_and_connect()
+ cmd_setsid = '%s am instrument -w -e action start %s/%s' % (
+ snippet_client._SETSID_COMMAND,
+ MOCK_PACKAGE_NAME,
+ snippet_client._INSTRUMENTATION_RUNNER_PACKAGE)
+ mock_do_start_app.assert_has_calls(mock.call(cmd_setsid))
+
+ # Test 'setsid' does not exist, but 'nohup' exsits
+ client = self._make_client()
+ client._adb.shell = _mocked_shell
+ client.start_app_and_connect()
+ cmd_nohup = '%s am instrument -w -e action start %s/%s' % (
+ snippet_client._NOHUP_COMMAND,
+ MOCK_PACKAGE_NAME,
+ snippet_client._INSTRUMENTATION_RUNNER_PACKAGE)
+ mock_do_start_app.assert_has_calls([
+ mock.call(cmd_setsid),
+ mock.call(cmd_nohup)
+ ])
+
+ # Test both 'setsid' and 'nohup' do not exist
+ client._adb.shell = mock.Mock(
+ side_effect=adb.AdbError('cmd', 'stdout', 'stderr', 'ret_code'))
+ client = self._make_client()
+ client.start_app_and_connect()
+ cmd_not_persist = ' am instrument -w -e action start %s/%s' % (
+ MOCK_PACKAGE_NAME,
+ snippet_client._INSTRUMENTATION_RUNNER_PACKAGE)
+ mock_do_start_app.assert_has_calls([
+ mock.call(cmd_setsid),
+ mock.call(cmd_nohup),
+ mock.call(cmd_not_persist)
+ ])
+
@mock.patch('socket.create_connection')
@mock.patch('mobly.controllers.android_device_lib.snippet_client.'
'utils.start_standing_subprocess')
|
Exceptions from `CallbackHandler` should include timeout value
Right now some timeout exceptions thrown by `CallbackHandler` do not include how long the timeout was, making debugging more difficult.
|
0.0
|
c9ba28477626c6f7d5365bec019646f915a5bd2d
|
[
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_wait_and_get_timeout",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v1_persistent_session"
] |
[
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail_with_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_regex",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_both_teardown_and_test_body_raise_exceptions",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_override_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_default_execution_of_all_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass_but_teardown_test_raises_an_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_in_procedure_functions_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_to_call_procedure_function_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_call_outside_of_setup_generated_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_dup_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_selected_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_implicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_missing_requested_test_func",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_setup_fails_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_and_teardown_execution_count",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_test_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_if",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_assert_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_setup_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_uncaught_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_basic",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_None",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_optional_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_required_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_missing",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_with_default",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required_missing",
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_event_dict_to_snippet_event",
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_timeout_value",
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_wait_for_event",
"tests/mobly/controllers/android_device_lib/callback_handler_test.py::CallbackHandlerTest::test_wait_for_event_negative",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_app_not_installed",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_not_instrumented",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_target_not_installed",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_normal",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_restore_event_client",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_no_valid_line",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_unknown_protocol",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v0",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v0_header_junk",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v1",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v1_header_junk",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_event_client"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-07-12 18:30:24+00:00
|
apache-2.0
| 2,590 |
|
google__mobly-276
|
diff --git a/mobly/controllers/android_device_lib/snippet_client.py b/mobly/controllers/android_device_lib/snippet_client.py
index f7f473b..6d656a4 100644
--- a/mobly/controllers/android_device_lib/snippet_client.py
+++ b/mobly/controllers/android_device_lib/snippet_client.py
@@ -27,8 +27,8 @@ _INSTRUMENTATION_RUNNER_PACKAGE = (
_LAUNCH_CMD_V0 = ('%s am instrument -w -e action start -e port %s %s/' +
_INSTRUMENTATION_RUNNER_PACKAGE)
-_LAUNCH_CMD_V1 = (
- '%s am instrument -w -e action start %s/' + _INSTRUMENTATION_RUNNER_PACKAGE)
+_LAUNCH_CMD_V1 = ('%s am instrument -w -e action start %s/' +
+ _INSTRUMENTATION_RUNNER_PACKAGE)
_STOP_CMD = (
'am instrument -w -e action stop %s/' + _INSTRUMENTATION_RUNNER_PACKAGE)
@@ -119,7 +119,8 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
# Reuse the host port as the device port in v0 snippet. This isn't
# safe in general, but the protocol is deprecated.
self.device_port = self.host_port
- cmd = _LAUNCH_CMD_V0 % (persists_shell_cmd, self.device_port, self.package)
+ cmd = _LAUNCH_CMD_V0 % (persists_shell_cmd, self.device_port,
+ self.package)
self._proc = self._do_start_app(cmd)
self._connect_to_v0()
self._launch_version = 'v0'
@@ -165,8 +166,8 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
# Failed to connect to app, something went wrong.
raise jsonrpc_client_base.AppRestoreConnectionError(
('Failed to restore app connection for %s at host port %s, '
- 'device port %s'),
- self.package, self.host_port, self.device_port)
+ 'device port %s'), self.package, self.host_port,
+ self.device_port)
# Because the previous connection was lost, update self._proc
self._proc = None
@@ -250,8 +251,7 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
# removed.
def _connect_to_v0(self):
self._adb.forward(
- ['tcp:%d' % self.host_port,
- 'tcp:%d' % self.device_port])
+ ['tcp:%d' % self.host_port, 'tcp:%d' % self.device_port])
start_time = time.time()
expiration_time = start_time + _APP_START_WAIT_TIME_V0
while time.time() < expiration_time:
@@ -270,8 +270,7 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
def _connect_to_v1(self):
self._adb.forward(
- ['tcp:%d' % self.host_port,
- 'tcp:%d' % self.device_port])
+ ['tcp:%d' % self.host_port, 'tcp:%d' % self.device_port])
self.connect()
def _read_protocol_line(self):
@@ -309,12 +308,14 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
"""Check availability and return path of command if available."""
for command in [_SETSID_COMMAND, _NOHUP_COMMAND]:
try:
- if command in self._adb.shell('which %s' % command):
+ if command in self._adb.shell(['which',
+ command]).decode('utf-8'):
return command
except adb.AdbError:
continue
- self.log.warning('No %s and %s commands available to launch instrument '
- 'persistently, tests that depend on UiAutomator and '
- 'at the same time performs USB disconnection may fail',
- _SETSID_COMMAND, _NOHUP_COMMAND)
+ self.log.warning(
+ 'No %s and %s commands available to launch instrument '
+ 'persistently, tests that depend on UiAutomator and '
+ 'at the same time performs USB disconnection may fail',
+ _SETSID_COMMAND, _NOHUP_COMMAND)
return ''
|
google/mobly
|
2172facbb0ad8d1795a63e7b777d5938914cf758
|
diff --git a/tests/mobly/controllers/android_device_lib/snippet_client_test.py b/tests/mobly/controllers/android_device_lib/snippet_client_test.py
index beb9262..7e127c9 100755
--- a/tests/mobly/controllers/android_device_lib/snippet_client_test.py
+++ b/tests/mobly/controllers/android_device_lib/snippet_client_test.py
@@ -53,7 +53,7 @@ class MockAdbProxy(object):
p=MOCK_PACKAGE_NAME,
r=snippet_client._INSTRUMENTATION_RUNNER_PACKAGE), 'utf-8')
elif 'which' in params:
- return ''
+ return b''
def __getattr__(self, name):
"""All calls to the none-existent functions in adb proxy would
@@ -196,7 +196,7 @@ class SnippetClientTest(jsonrpc_client_test_base.JsonRpcClientTestBase):
if 'setsid' in arg:
raise adb.AdbError('cmd', 'stdout', 'stderr', 'ret_code')
else:
- return 'nohup'
+ return b'nohup'
mock_get_port.return_value = 123
mock_read_protocol_line.side_effect = [
@@ -210,7 +210,7 @@ class SnippetClientTest(jsonrpc_client_test_base.JsonRpcClientTestBase):
# Test 'setsid' exists
client = self._make_client()
- client._adb.shell = mock.Mock(return_value='setsid')
+ client._adb.shell = mock.Mock(return_value=b'setsid')
client.start_app_and_connect()
cmd_setsid = '%s am instrument -w -e action start %s/%s' % (
snippet_client._SETSID_COMMAND,
|
snippet launching is broken in py3
When trying to launch snippet, it fails with:
```
File "/Users/angli/Developer/mobly/tools/snippet_shell.py", line 43, in _start_services
self._ad.load_snippet(name='snippet', package=self._package)
File "/Users/angli/Developer/mobly/mobly/controllers/android_device.py", line 727, in load_snippet
client.start_app_and_connect()
File "/Users/angli/Developer/mobly/mobly/controllers/android_device_lib/snippet_client.py", line 92, in start_app_and_connect
persists_shell_cmd = self._get_persist_command()
File "/Users/angli/Developer/mobly/mobly/controllers/android_device_lib/snippet_client.py", line 312, in _get_persist_command
if command in self._adb.shell('which %s' % command):
TypeError: a bytes-like object is required, not 'str'
```
Looks like this is related to recent change #251
|
0.0
|
2172facbb0ad8d1795a63e7b777d5938914cf758
|
[
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_no_valid_line",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_unknown_protocol",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v0",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v0_header_junk",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v1",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v1_header_junk",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_v1_persistent_session"
] |
[
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_app_not_installed",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_not_instrumented",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_target_not_installed",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_normal",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_restore_event_client",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_event_client"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-07-28 01:36:53+00:00
|
apache-2.0
| 2,591 |
|
google__mobly-279
|
diff --git a/mobly/records.py b/mobly/records.py
index 54be008..b6175cd 100644
--- a/mobly/records.py
+++ b/mobly/records.py
@@ -43,8 +43,16 @@ class TestSummaryEntryType(enum.Enum):
The idea is similar to how `TestResult.json_str` categorizes different
sections of a `TestResult` object in the serialized format.
"""
+ # A list of all the tests requested for a test run.
+ # This is dumped at the beginning of a summary file so we know what was
+ # requested in case the test is interrupted and the final summary is not.
+ # created.
+ TEST_NAME_LIST = 'TestNameList'
+ # Records of test results.
RECORD = 'Record'
+ # A summary of the test run stats, like how many test failed.
SUMMARY = 'Summary'
+ # Information on the controllers used in the test.
CONTROLLER_INFO = 'ControllerInfo'
@@ -418,6 +426,17 @@ class TestResult(object):
json_str = json.dumps(d, indent=4, sort_keys=True)
return json_str
+ def requested_test_names_dict(self):
+ """Gets the requested test names of a test run in a dict format.
+
+ Note a test can be requested multiple times, so there can be duplicated
+ values
+
+ Returns:
+ A dict with a key and the list of strings.
+ """
+ return {'Requested Tests': copy.deepcopy(self.requested)}
+
def summary_str(self):
"""Gets a string that summarizes the stats of this test result.
|
google/mobly
|
49db9368415e40a3bf0512bddf6c0e3170513a41
|
diff --git a/mobly/base_test.py b/mobly/base_test.py
index ece150a..5deaf5e 100644
--- a/mobly/base_test.py
+++ b/mobly/base_test.py
@@ -552,6 +552,8 @@ class BaseTestClass(object):
# No test method specified by user, execute all in test class.
test_names = self._get_all_test_names()
self.results.requested = test_names
+ self.summary_writer.dump(self.results.requested_test_names_dict(),
+ records.TestSummaryEntryType.TEST_NAME_LIST)
tests = self._get_test_methods(test_names)
# Setup for the class.
try:
diff --git a/tests/mobly/test_runner_test.py b/tests/mobly/test_runner_test.py
index e57a91f..7690c22 100755
--- a/tests/mobly/test_runner_test.py
+++ b/tests/mobly/test_runner_test.py
@@ -13,11 +13,14 @@
# limitations under the License.
import mock
+import os
import shutil
import tempfile
+import yaml
from future.tests.base import unittest
from mobly import config_parser
+from mobly import records
from mobly import signals
from mobly import test_runner
@@ -31,6 +34,7 @@ class TestRunnerTest(unittest.TestCase):
"""This test class has unit tests for the implementation of everything
under mobly.test_runner.
"""
+
def setUp(self):
self.tmp_dir = tempfile.mkdtemp()
self.base_mock_test_config = config_parser.TestRunConfig()
@@ -50,7 +54,7 @@ class TestRunnerTest(unittest.TestCase):
def test_register_controller_no_config(self):
tr = test_runner.TestRunner(self.log_dir, self.test_bed_name)
with self.assertRaisesRegex(signals.ControllerError,
- 'No corresponding config found for'):
+ 'No corresponding config found for'):
tr._register_controller(self.base_mock_test_config,
mock_controller)
@@ -177,6 +181,37 @@ class TestRunnerTest(unittest.TestCase):
}
self.assertEqual(tr.results.controller_info, expected_info)
+ def test_summary_file_entries(self):
+ """Verifies the output summary's file format.
+
+ This focuses on the format of the file instead of the content of
+ entries, which is covered in base_test_test.
+ """
+ mock_test_config = self.base_mock_test_config.copy()
+ mock_ctrlr_config_name = mock_controller.MOBLY_CONTROLLER_CONFIG_NAME
+ my_config = [{
+ 'serial': 'xxxx',
+ 'magic': 'Magic1'
+ }, {
+ 'serial': 'xxxx',
+ 'magic': 'Magic2'
+ }]
+ mock_test_config.controller_configs[mock_ctrlr_config_name] = my_config
+ tr = test_runner.TestRunner(self.log_dir, self.test_bed_name)
+ tr.add_test_class(mock_test_config, integration_test.IntegrationTest)
+ tr.run()
+ summary_path = os.path.join(mock_test_config.log_path,
+ mock_test_config.test_bed_name, 'latest',
+ records.OUTPUT_FILE_SUMMARY)
+ with open(summary_path, 'r') as f:
+ summary_entries = list(yaml.load_all(f))
+ self.assertEqual(len(summary_entries), 4)
+ # Verify the first entry is the list of test names.
+ self.assertEqual(summary_entries[0]['Type'],
+ records.TestSummaryEntryType.TEST_NAME_LIST.value)
+ self.assertEqual(summary_entries[1]['Type'],
+ records.TestSummaryEntryType.RECORD.value)
+
@mock.patch(
'mobly.controllers.android_device_lib.adb.AdbProxy',
return_value=mock_android_device.MockAdbProxy(1))
@@ -265,8 +300,7 @@ class TestRunnerTest(unittest.TestCase):
def test_run_no_tests(self):
tr = test_runner.TestRunner(self.log_dir, self.test_bed_name)
- with self.assertRaisesRegex(test_runner.Error,
- 'No tests to execute.'):
+ with self.assertRaisesRegex(test_runner.Error, 'No tests to execute.'):
tr.run()
def test_verify_controller_module(self):
|
add a prefix document to test_summary.yaml with requested tests
This could be dumped before any test cases are run
|
0.0
|
49db9368415e40a3bf0512bddf6c0e3170513a41
|
[
"tests/mobly/test_runner_test.py::TestRunnerTest::test_run_twice",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_run_two_test_classes",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_run_two_test_classes_different_configs"
] |
[
"tests/mobly/test_runner_test.py::TestRunnerTest::test_add_test_class_mismatched_log_path",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_add_test_class_mismatched_test_bed_name",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_register_controller_change_return_value",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_register_controller_dup_register",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_register_controller_less_than_min_number",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_register_controller_no_config",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_register_controller_no_config_no_register",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_register_controller_no_get_info",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_register_controller_return_value",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_run_no_tests",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_verify_controller_module",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_verify_controller_module_missing_attr",
"tests/mobly/test_runner_test.py::TestRunnerTest::test_verify_controller_module_null_attr"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-07-28 18:54:44+00:00
|
apache-2.0
| 2,592 |
|
google__mobly-311
|
diff --git a/mobly/signals.py b/mobly/signals.py
index 8899065..85bdc30 100644
--- a/mobly/signals.py
+++ b/mobly/signals.py
@@ -46,6 +46,10 @@ class TestSignal(Exception):
return 'Details=%s, Extras=%s' % (self.details, self.extras)
+class TestError(TestSignal):
+ """Raised when a test has an unexpected error."""
+
+
class TestFailure(TestSignal):
"""Raised when a test has failed."""
|
google/mobly
|
25b676a196403ef3e1d2f7516008d58d3649d888
|
diff --git a/mobly/base_test.py b/mobly/base_test.py
index 5233aa5..649f6d5 100644
--- a/mobly/base_test.py
+++ b/mobly/base_test.py
@@ -17,6 +17,7 @@ import copy
import functools
import inspect
import logging
+import sys
from mobly import logger
from mobly import records
@@ -175,6 +176,19 @@ class BaseTestClass(object):
Implementation is optional.
"""
+ def _teardown_class(self):
+ """Proxy function to guarantee the base implementation of
+ teardown_class is called.
+ """
+ record = records.TestResultRecord('teardown_class', self.TAG)
+ record.test_begin()
+ try:
+ self.teardown_class()
+ except Exception as e:
+ record.test_error(e)
+ record.update_record()
+ self.results.add_class_error(record)
+
def teardown_class(self):
"""Teardown function that will be called after all the selected tests in
the test class have been executed.
@@ -316,7 +330,7 @@ class BaseTestClass(object):
Executes setup_test, the test method, and teardown_test; then creates a
records.TestResultRecord object with the execution information and adds
- the record to the test class's test results.
+ the record to the test class's test result s.
Args:
test_name: Name of the test.
@@ -330,7 +344,12 @@ class BaseTestClass(object):
teardown_test_failed = False
try:
try:
- self._setup_test(test_name)
+ try:
+ self._setup_test(test_name)
+ except signals.TestFailure as e:
+ new_e = signals.TestError(e.details, e.extras)
+ _, _, new_e.__traceback__ = sys.exc_info()
+ raise new_e
if args or kwargs:
test_method(*args, **kwargs)
else:
@@ -563,7 +582,7 @@ class BaseTestClass(object):
# Skip all tests peacefully.
e.details = 'setup_class aborted due to: %s' % e.details
self._skip_remaining_tests(e)
- self._safe_exec_func(self.teardown_class)
+ self._teardown_class()
return self.results
except Exception as e:
# Setup class failed for unknown reasons.
@@ -577,7 +596,7 @@ class BaseTestClass(object):
self.summary_writer.dump(class_record.to_dict(),
records.TestSummaryEntryType.RECORD)
self._skip_remaining_tests(e)
- self._safe_exec_func(self.teardown_class)
+ self._teardown_class()
return self.results
# Run tests in order.
try:
@@ -594,7 +613,7 @@ class BaseTestClass(object):
setattr(e, 'results', self.results)
raise e
finally:
- self._safe_exec_func(self.teardown_class)
+ self._teardown_class()
logging.info('Summary for test class %s: %s', self.TAG,
self.results.summary_str())
diff --git a/tests/mobly/base_test_test.py b/tests/mobly/base_test_test.py
index bd7dce9..d615f3f 100755
--- a/tests/mobly/base_test_test.py
+++ b/tests/mobly/base_test_test.py
@@ -203,6 +203,28 @@ class BaseTestTest(unittest.TestCase):
teardown_class_call_check.assert_called_once_with("heehee")
on_fail_call_check.assert_called_once_with("haha")
+ def test_teardown_class_fail_by_exception(self):
+ class MockBaseTest(base_test.BaseTestClass):
+ def test_something(self):
+ pass
+
+ def teardown_class(self):
+ raise Exception(MSG_EXPECTED_EXCEPTION)
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.run()
+ test_record = bt_cls.results.passed[0]
+ class_record = bt_cls.results.error[0]
+ self.assertFalse(bt_cls.results.is_all_pass)
+ self.assertEqual(class_record.test_name, 'teardown_class')
+ self.assertEqual(class_record.details, MSG_EXPECTED_EXCEPTION)
+ self.assertIsNotNone(class_record.begin_time)
+ self.assertIsNotNone(class_record.end_time)
+ self.assertIsNone(class_record.extras)
+ expected_summary = ('Error 1, Executed 1, Failed 0, Passed 1, '
+ 'Requested 1, Skipped 0')
+ self.assertEqual(bt_cls.results.summary_str(), expected_summary)
+
def test_setup_test_fail_by_exception(self):
mock_on_fail = mock.Mock()
@@ -223,6 +245,10 @@ class BaseTestTest(unittest.TestCase):
actual_record = bt_cls.results.error[0]
self.assertEqual(actual_record.test_name, self.mock_test_name)
self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
+ self.assertTrue('in setup_test\n '
+ 'raise Exception(MSG_EXPECTED_EXCEPTION)\n'
+ 'Exception: This is an expected exception.\n' in
+ actual_record.stacktrace)
self.assertIsNone(actual_record.extras)
expected_summary = ("Error 1, Executed 1, Failed 0, Passed 0, "
"Requested 1, Skipped 0")
@@ -239,11 +265,13 @@ class BaseTestTest(unittest.TestCase):
bt_cls = MockBaseTest(self.mock_test_cls_configs)
bt_cls.run(test_names=["test_something"])
- actual_record = bt_cls.results.failed[0]
+ actual_record = bt_cls.results.error[0]
self.assertEqual(actual_record.test_name, self.mock_test_name)
self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
+ # Make sure the full stacktrace of `setup_test` is preserved.
+ self.assertTrue('self.setup_test()' in actual_record.stacktrace)
self.assertIsNone(actual_record.extras)
- expected_summary = ("Error 0, Executed 1, Failed 1, Passed 0, "
+ expected_summary = ("Error 1, Executed 1, Failed 0, Passed 0, "
"Requested 1, Skipped 0")
self.assertEqual(bt_cls.results.summary_str(), expected_summary)
@@ -407,6 +435,7 @@ class BaseTestTest(unittest.TestCase):
def test_procedure_function_gets_correct_record(self):
on_fail_mock = mock.MagicMock()
+
class MockBaseTest(base_test.BaseTestClass):
def on_fail(self, record):
on_fail_mock.record = record
@@ -418,12 +447,16 @@ class BaseTestTest(unittest.TestCase):
bt_cls.run()
actual_record = bt_cls.results.failed[0]
self.assertEqual(actual_record.test_name, 'test_something')
- self.assertEqual(on_fail_mock.record.test_name, actual_record.test_name)
- self.assertEqual(on_fail_mock.record.begin_time, actual_record.begin_time)
+ self.assertEqual(on_fail_mock.record.test_name,
+ actual_record.test_name)
+ self.assertEqual(on_fail_mock.record.begin_time,
+ actual_record.begin_time)
self.assertEqual(on_fail_mock.record.end_time, actual_record.end_time)
- self.assertEqual(on_fail_mock.record.stacktrace, actual_record.stacktrace)
+ self.assertEqual(on_fail_mock.record.stacktrace,
+ actual_record.stacktrace)
self.assertEqual(on_fail_mock.record.extras, actual_record.extras)
- self.assertEqual(on_fail_mock.record.extra_errors, actual_record.extra_errors)
+ self.assertEqual(on_fail_mock.record.extra_errors,
+ actual_record.extra_errors)
# But they are not the same object.
self.assertIsNot(on_fail_mock.record, actual_record)
@@ -989,6 +1022,23 @@ class BaseTestTest(unittest.TestCase):
self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
self.assertEqual(actual_record.extras, MOCK_EXTRA)
+ def test_skip_in_setup_test(self):
+ class MockBaseTest(base_test.BaseTestClass):
+ def setup_test(self):
+ asserts.skip(MSG_EXPECTED_EXCEPTION, extras=MOCK_EXTRA)
+
+ def test_func(self):
+ never_call()
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.run(test_names=["test_func"])
+ actual_record = bt_cls.results.skipped[0]
+ self.assertIsNotNone(actual_record.begin_time)
+ self.assertIsNotNone(actual_record.end_time)
+ self.assertEqual(actual_record.test_name, "test_func")
+ self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
+ self.assertEqual(actual_record.extras, MOCK_EXTRA)
+
def test_unpack_userparams_required(self):
"""Missing a required param should raise an error."""
required = ["some_param"]
|
Exceptions in `setup_test` should leave the test in `ERROR` status
Regardless of the type of the exception, `setup_test` error should cause `ERROR` status.
This is different from a test method.
In a test method, an exception based on signals.TestFailure should cause the test to exit with `FAILED` status.
This is to be consistent with pyunit's behavior.
|
0.0
|
25b676a196403ef3e1d2f7516008d58d3649d888
|
[
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_test_signal"
] |
[
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail_with_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_regex",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_both_teardown_and_test_body_raise_exceptions",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_override_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_default_execution_of_all_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_exception_objects_in_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass_but_teardown_test_raises_an_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_in_procedure_functions_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_to_call_procedure_function_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_call_outside_of_setup_generated_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_dup_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_selected_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_implicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_missing_requested_test_func",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_cannot_modify_original_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_both_test_and_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_setup_fails_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_cannot_modify_original_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_procedure_function_gets_correct_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_promote_extra_errors_to_termination_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_and_teardown_execution_count",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_if",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_assert_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_setup_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_uncaught_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_basic",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_None",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_optional_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_required_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_missing",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_with_default",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required_missing"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2017-08-16 00:27:44+00:00
|
apache-2.0
| 2,593 |
|
google__mobly-323
|
diff --git a/mobly/controllers/android_device.py b/mobly/controllers/android_device.py
index 2be180b..5d7027e 100644
--- a/mobly/controllers/android_device.py
+++ b/mobly/controllers/android_device.py
@@ -725,7 +725,17 @@ class AndroidDevice(object):
' "%s".' % (package, client_name))
client = snippet_client.SnippetClient(
package=package, adb_proxy=self.adb, log=self.log)
- client.start_app_and_connect()
+ try:
+ client.start_app_and_connect()
+ except Exception as e:
+ # If errors happen, make sure we clean up before raising.
+ try:
+ client.stop_app()
+ except:
+ self.log.exception(
+ 'Failed to stop app after failure to launch.')
+ # Raise the error from start app failure.
+ raise e
self._snippet_clients[name] = client
setattr(self, name, client)
diff --git a/mobly/signals.py b/mobly/signals.py
index 85bdc30..e367a8f 100644
--- a/mobly/signals.py
+++ b/mobly/signals.py
@@ -62,13 +62,18 @@ class TestSkip(TestSignal):
"""Raised when a test has been skipped."""
-class TestAbortClass(TestSignal):
+class TestAbortSignal(TestSignal):
+ """Base class for abort signals.
+ """
+
+
+class TestAbortClass(TestAbortSignal):
"""Raised when all subsequent tests within the same test class should
be aborted.
"""
-class TestAbortAll(TestSignal):
+class TestAbortAll(TestAbortSignal):
"""Raised when all subsequent tests should be aborted."""
|
google/mobly
|
1493710b2fa167349303bc6710dda042dae0b895
|
diff --git a/mobly/base_test.py b/mobly/base_test.py
index 0c540a5..24290de 100644
--- a/mobly/base_test.py
+++ b/mobly/base_test.py
@@ -318,7 +318,7 @@ class BaseTestClass(object):
# Pass a copy of the record instead of the actual object so that it
# will not be modified.
func(copy.deepcopy(tr_record))
- except signals.TestAbortAll:
+ except signals.TestAbortSignal:
raise
except Exception as e:
logging.exception('Exception happened when executing %s for %s.',
@@ -363,7 +363,7 @@ class BaseTestClass(object):
finally:
try:
self._teardown_test(test_name)
- except signals.TestAbortAll:
+ except signals.TestAbortSignal:
raise
except Exception as e:
logging.exception(e)
@@ -374,7 +374,7 @@ class BaseTestClass(object):
except signals.TestSkip as e:
# Test skipped.
tr_record.test_skip(e)
- except (signals.TestAbortClass, signals.TestAbortAll) as e:
+ except signals.TestAbortSignal as e:
# Abort signals, pass along.
tr_record.test_fail(e)
raise e
@@ -389,17 +389,20 @@ class BaseTestClass(object):
tr_record.test_pass()
finally:
tr_record.update_record()
- if tr_record.result in (records.TestResultEnums.TEST_RESULT_ERROR,
- records.TestResultEnums.TEST_RESULT_FAIL):
- self._exec_procedure_func(self._on_fail, tr_record)
- elif tr_record.result == records.TestResultEnums.TEST_RESULT_PASS:
- self._exec_procedure_func(self._on_pass, tr_record)
- elif tr_record.result == records.TestResultEnums.TEST_RESULT_SKIP:
- self._exec_procedure_func(self._on_skip, tr_record)
- self.results.add_record(tr_record)
- self.summary_writer.dump(tr_record.to_dict(),
- records.TestSummaryEntryType.RECORD)
- self.current_test_name = None
+ try:
+ if tr_record.result in (
+ records.TestResultEnums.TEST_RESULT_ERROR,
+ records.TestResultEnums.TEST_RESULT_FAIL):
+ self._exec_procedure_func(self._on_fail, tr_record)
+ elif tr_record.result == records.TestResultEnums.TEST_RESULT_PASS:
+ self._exec_procedure_func(self._on_pass, tr_record)
+ elif tr_record.result == records.TestResultEnums.TEST_RESULT_SKIP:
+ self._exec_procedure_func(self._on_skip, tr_record)
+ finally:
+ self.results.add_record(tr_record)
+ self.summary_writer.dump(tr_record.to_dict(),
+ records.TestSummaryEntryType.RECORD)
+ self.current_test_name = None
def _assert_function_name_in_stack(self, expected_func_name):
"""Asserts that the current stack contains the given function name."""
@@ -577,7 +580,7 @@ class BaseTestClass(object):
# Setup for the class.
try:
self._setup_class()
- except signals.TestAbortClass as e:
+ except signals.TestAbortSignal as e:
# The test class is intentionally aborted.
# Skip all tests peacefully.
e.details = 'setup_class aborted due to: %s' % e.details
diff --git a/tests/mobly/base_test_test.py b/tests/mobly/base_test_test.py
index d615f3f..29781af 100755
--- a/tests/mobly/base_test_test.py
+++ b/tests/mobly/base_test_test.py
@@ -739,6 +739,48 @@ class BaseTestTest(unittest.TestCase):
("Error 0, Executed 0, Failed 0, Passed 0, "
"Requested 3, Skipped 3"))
+ def test_abort_class_in_setup_test(self):
+ class MockBaseTest(base_test.BaseTestClass):
+ def setup_test(self):
+ asserts.abort_class(MSG_EXPECTED_EXCEPTION)
+
+ def test_1(self):
+ never_call()
+
+ def test_2(self):
+ never_call()
+
+ def test_3(self):
+ never_call()
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.run(test_names=["test_1", "test_2", "test_3"])
+ self.assertEqual(len(bt_cls.results.skipped), 2)
+ self.assertEqual(bt_cls.results.summary_str(),
+ ("Error 0, Executed 1, Failed 1, Passed 0, "
+ "Requested 3, Skipped 2"))
+
+ def test_abort_class_in_on_fail(self):
+ class MockBaseTest(base_test.BaseTestClass):
+ def test_1(self):
+ asserts.fail(MSG_EXPECTED_EXCEPTION)
+
+ def test_2(self):
+ never_call()
+
+ def test_3(self):
+ never_call()
+
+ def on_fail(self, record):
+ asserts.abort_class(MSG_EXPECTED_EXCEPTION)
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.run(test_names=["test_1", "test_2", "test_3"])
+ self.assertEqual(len(bt_cls.results.skipped), 2)
+ self.assertEqual(bt_cls.results.summary_str(),
+ ("Error 0, Executed 1, Failed 1, Passed 0, "
+ "Requested 3, Skipped 2"))
+
def test_setup_and_teardown_execution_count(self):
class MockBaseTest(base_test.BaseTestClass):
def test_func(self):
|
`signals.TestAbortClass` does not work in `setup_test` and `on_xxxx` methods
It is valid to abort the class at any stage of a test.
E.g. If we find out in `on_fail` that a test failed due to a fatal error like snippet_client losing socket connection, it is reasonable for the test to abort all subsequent tests in the class instead of continue running and failing more tests when we know they will fail.
|
0.0
|
1493710b2fa167349303bc6710dda042dae0b895
|
[
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_on_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_both_teardown_and_test_body_raise_exceptions",
"tests/mobly/base_test_test.py::BaseTestTest::test_exception_objects_in_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass_but_teardown_test_raises_an_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_in_procedure_functions_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_to_call_procedure_function_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_call_outside_of_setup_generated_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_both_test_and_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_setup_fails_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_cannot_modify_original_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_promote_extra_errors_to_termination_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_test_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_assert_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_setup_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_uncaught_exception"
] |
[
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail_with_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_regex",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_override_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_default_execution_of_all_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_dup_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_selected_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_implicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_missing_requested_test_func",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_cannot_modify_original_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_procedure_function_gets_correct_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_and_teardown_execution_count",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_if",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_basic",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_None",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_optional_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_required_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_missing",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_with_default",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required_missing"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-08-24 20:07:58+00:00
|
apache-2.0
| 2,594 |
|
google__mobly-328
|
diff --git a/mobly/controllers/android_device.py b/mobly/controllers/android_device.py
index 5d7027e..e52e5fd 100644
--- a/mobly/controllers/android_device.py
+++ b/mobly/controllers/android_device.py
@@ -836,10 +836,8 @@ class AndroidDevice(object):
extra_params = self.adb_logcat_param
except AttributeError:
extra_params = ''
- cmd = '"%s" -s %s logcat -v threadtime %s >> %s' % (adb.ADB,
- self.serial,
- extra_params,
- logcat_file_path)
+ cmd = '"%s" -s %s logcat -v threadtime %s >> "%s"' % (
+ adb.ADB, self.serial, extra_params, logcat_file_path)
process = utils.start_standing_subprocess(cmd, shell=True)
self._adb_logcat_process = process
self.adb_logcat_file_path = logcat_file_path
|
google/mobly
|
51c912d1a8ffd5ace4a9a744a46498515cf5c145
|
diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py
index 1849496..59c5529 100755
--- a/tests/mobly/controllers/android_device_test.py
+++ b/tests/mobly/controllers/android_device_test.py
@@ -326,7 +326,7 @@ class AndroidDeviceTest(unittest.TestCase):
creat_dir_mock.assert_called_with(os.path.dirname(expected_log_path))
adb_cmd = '"adb" -s %s logcat -v threadtime >> %s'
start_proc_mock.assert_called_with(
- adb_cmd % (ad.serial, expected_log_path), shell=True)
+ adb_cmd % (ad.serial, '"%s"' % expected_log_path), shell=True)
self.assertEqual(ad.adb_logcat_file_path, expected_log_path)
expected_msg = (
'Logcat thread is already running, cannot start another'
@@ -373,7 +373,7 @@ class AndroidDeviceTest(unittest.TestCase):
creat_dir_mock.assert_called_with(os.path.dirname(expected_log_path))
adb_cmd = '"adb" -s %s logcat -v threadtime -b radio >> %s'
start_proc_mock.assert_called_with(
- adb_cmd % (ad.serial, expected_log_path), shell=True)
+ adb_cmd % (ad.serial, '"%s"' % expected_log_path), shell=True)
self.assertEqual(ad.adb_logcat_file_path, expected_log_path)
@mock.patch(
|
`AndroidDevice` adb logcat file name gets truncated
If device model name includes space, the output file name of adb logcat is incorrect.
For example, for model "aqua power hd-4g", we expect `adblog,aqua power hd-4g,usb:3-5.2.3.txt`, but we actually get `adblog,aqua`.
|
0.0
|
51c912d1a8ffd5ace4a9a744a46498515cf5c145
|
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat_with_user_param"
] |
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_build_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_cat_adb_log",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_debug_tag",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_instantiation",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_attribute_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_package",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_snippet_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_snippet_cleanup",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fallback",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_dict_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_empty_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_no_valid_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_not_list_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_pickup_all",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_string_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_usb_id",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial_and_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_too_many_matches",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-09-01 21:02:53+00:00
|
apache-2.0
| 2,595 |
|
google__mobly-433
|
diff --git a/mobly/controllers/android_device.py b/mobly/controllers/android_device.py
index f1a4636..14828a4 100644
--- a/mobly/controllers/android_device.py
+++ b/mobly/controllers/android_device.py
@@ -436,9 +436,8 @@ class AndroidDevice(object):
self._log_path = os.path.join(self._log_path_base,
'AndroidDevice%s' % self._serial)
self._debug_tag = self._serial
- self.log = AndroidDeviceLoggerAdapter(logging.getLogger(), {
- 'tag': self.debug_tag
- })
+ self.log = AndroidDeviceLoggerAdapter(logging.getLogger(),
+ {'tag': self.debug_tag})
self.sl4a = None
self.ed = None
self._adb_logcat_process = None
@@ -937,6 +936,7 @@ class AndroidDevice(object):
f_name = os.path.basename(self.adb_logcat_file_path)
out_name = f_name.replace('adblog,', '').replace('.txt', '')
out_name = ',%s,%s.txt' % (begin_time, out_name)
+ out_name = out_name.replace(':', '-')
tag_len = utils.MAX_FILENAME_LEN - len(out_name)
tag = tag[:tag_len]
out_name = tag + out_name
|
google/mobly
|
02b9d84acfe775a6fe73e2b960ba7e47765184d6
|
diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py
index b1428ec..f175f17 100755
--- a/tests/mobly/controllers/android_device_test.py
+++ b/tests/mobly/controllers/android_device_test.py
@@ -630,7 +630,7 @@ class AndroidDeviceTest(unittest.TestCase):
ad.cat_adb_log('some_test', MOCK_ADB_LOGCAT_BEGIN_TIME)
cat_file_path = os.path.join(
ad.log_path, 'AdbLogExcerpts',
- ('some_test,02-29 14:02:20.123,%s,%s.txt') % (ad.model, ad.serial))
+ ('some_test,02-29 14-02-20.123,%s,%s.txt') % (ad.model, ad.serial))
with open(cat_file_path, 'r') as f:
actual_cat = f.read()
self.assertEqual(actual_cat, ''.join(MOCK_ADB_LOGCAT_CAT_RESULT))
diff --git a/tests/mobly/logger_test.py b/tests/mobly/logger_test.py
index b1cf839..1ac9f1d 100755
--- a/tests/mobly/logger_test.py
+++ b/tests/mobly/logger_test.py
@@ -1,11 +1,11 @@
# Copyright 2016 Google Inc.
-#
+#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
-#
+#
# http://www.apache.org/licenses/LICENSE-2.0
-#
+#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
AdbLogExcerpts filename is invalid on Windows
Windows filenames should not have colons in them:
https://support.microsoft.com/en-us/help/905231/information-about-the-characters-that-you-cannot-use-in-site-names-fol
|
0.0
|
02b9d84acfe775a6fe73e2b960ba7e47765184d6
|
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_cat_adb_log"
] |
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice__enable_logpersist_with_logpersist",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice__enable_logpersist_with_missing_all_logpersist",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice__enable_logpersist_with_missing_logpersist_start",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice__enable_logpersist_with_missing_logpersist_stop",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_build_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_change_log_path",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_change_log_path_no_log_exists",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_change_log_path_with_existing_file",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_change_log_path_with_service",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_debug_tag",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_device_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_instantiation",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_attribute_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_package",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_snippet_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_fail_cleanup_also_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_failure",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_precheck_failure",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_start_app_fails",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_serial_is_valid",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_snippet_cleanup",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fallback",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_with_destination",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat_with_user_param",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_update_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_update_serial_with_service_running",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_dict_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_empty_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_no_valid_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_not_list_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_pickup_all",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_string_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_usb_id",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial_and_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_too_many_matches",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_devices_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_devices_success_with_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads_skip_logcat",
"tests/mobly/logger_test.py::LoggerTest::test_epoch_to_log_line_timestamp"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-04-11 23:35:44+00:00
|
apache-2.0
| 2,596 |
|
google__mobly-444
|
diff --git a/mobly/controllers/android_device_lib/adb.py b/mobly/controllers/android_device_lib/adb.py
index 12c14bd..cb5b6b6 100644
--- a/mobly/controllers/android_device_lib/adb.py
+++ b/mobly/controllers/android_device_lib/adb.py
@@ -237,7 +237,8 @@ class AdbProxy(object):
def forward(self, args=None, shell=False):
with ADB_PORT_LOCK:
- return self._exec_adb_cmd('forward', args, shell, timeout=None)
+ return self._exec_adb_cmd(
+ 'forward', args, shell, timeout=None, stderr=None)
def instrument(self, package, options=None, runner=None):
"""Runs an instrumentation command on the device.
|
google/mobly
|
8caa5c387b2df47a180e0349fbebe7838b099b83
|
diff --git a/mobly/base_test.py b/mobly/base_test.py
index e4e047b..13a79b0 100644
--- a/mobly/base_test.py
+++ b/mobly/base_test.py
@@ -624,6 +624,10 @@ class BaseTestClass(object):
tests = self._get_test_methods(test_names)
try:
# Setup for the class.
+ class_record = records.TestResultRecord('setup_class', self.TAG)
+ class_record.test_begin()
+ self.current_test_info = runtime_test_info.RuntimeTestInfo(
+ 'setup_class', self.log_path, class_record)
try:
self._setup_class()
except signals.TestAbortSignal:
@@ -633,9 +637,6 @@ class BaseTestClass(object):
# Setup class failed for unknown reasons.
# Fail the class and skip all tests.
logging.exception('Error in setup_class %s.', self.TAG)
- class_record = records.TestResultRecord(
- 'setup_class', self.TAG)
- class_record.test_begin()
class_record.test_error(e)
self._exec_procedure_func(self._on_fail, class_record)
self.results.add_class_error(class_record)
diff --git a/mobly/runtime_test_info.py b/mobly/runtime_test_info.py
index f4eea99..57b0742 100644
--- a/mobly/runtime_test_info.py
+++ b/mobly/runtime_test_info.py
@@ -19,10 +19,13 @@ from mobly import utils
class RuntimeTestInfo(object):
- """Container class for runtime information of a test.
+ """Container class for runtime information of a test or test stage.
One object corresponds to one test. This is meant to be a read-only class.
+ This also applies to test stages like `setup_class`, which has its own
+ runtime info but is not part of any single test.
+
Attributes:
name: string, name of the test.
signature: string, an identifier of the test, a combination of test
diff --git a/tests/mobly/base_test_test.py b/tests/mobly/base_test_test.py
index d78a640..a38b532 100755
--- a/tests/mobly/base_test_test.py
+++ b/tests/mobly/base_test_test.py
@@ -91,6 +91,25 @@ class BaseTestTest(unittest.TestCase):
self.assertIsNone(actual_record.details)
self.assertIsNone(actual_record.extras)
+ def test_current_test_info_in_setup_class(self):
+ class MockBaseTest(base_test.BaseTestClass):
+ def setup_class(self):
+ asserts.assert_true(
+ self.current_test_info.name == 'setup_class',
+ 'Got unexpected test name %s.' %
+ self.current_test_info.name)
+ output_path = self.current_test_info.output_path
+ asserts.assert_true(
+ os.path.exists(output_path), 'test output path missing')
+ raise Exception(MSG_EXPECTED_EXCEPTION)
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.run()
+ actual_record = bt_cls.results.error[0]
+ self.assertEqual(actual_record.test_name, 'setup_class')
+ self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
+ self.assertIsNone(actual_record.extras)
+
def test_self_tests_list(self):
class MockBaseTest(base_test.BaseTestClass):
def __init__(self, controllers):
diff --git a/tests/mobly/controllers/android_device_lib/adb_test.py b/tests/mobly/controllers/android_device_lib/adb_test.py
index 7bf61ab..cf699ce 100755
--- a/tests/mobly/controllers/android_device_lib/adb_test.py
+++ b/tests/mobly/controllers/android_device_lib/adb_test.py
@@ -173,6 +173,10 @@ class AdbTest(unittest.TestCase):
self.assertEqual(MOCK_DEFAULT_STDERR,
stderr_redirect.getvalue().decode('utf-8'))
+ def test_forward(self):
+ with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
+ adb.AdbProxy().forward(MOCK_SHELL_COMMAND)
+
def test_instrument_without_parameters(self):
"""Verifies the AndroidDevice object's instrument command is correct in
the basic case.
|
`current_test_info` should exist between `setup_class` and `setup_test`
Right now `current_test_info` is None between `setup_class` and `setup_test`, which makes it difficult to use this field consistently.
E.g. if a test relies on this field in `on_fail`, if `setup_class` fails, the logic in `on_fail` would raise an exception for any call to `current_test_info`.
|
0.0
|
8caa5c387b2df47a180e0349fbebe7838b099b83
|
[
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_forward"
] |
[
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_on_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_on_fail_from_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_on_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail_with_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_regex",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_both_teardown_and_test_body_raise_exceptions",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_override_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_info",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_info_in_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_default_execution_of_all_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_exception_objects_in_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_equal",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_false",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_in_teardown_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_multiple_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_no_op",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_no_raises_custom_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_no_raises_default_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_true_and_assert_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_two_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass_but_teardown_test_raises_an_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_in_procedure_functions_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_to_call_procedure_function_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_call_outside_of_setup_generated_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_dup_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_selected_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_implicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_missing_requested_test_func",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_cannot_modify_original_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_both_test_and_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_setup_fails_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_cannot_modify_original_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_procedure_function_gets_correct_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_promote_extra_errors_to_termination_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_and_teardown_execution_count",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_test_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_if",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_assert_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_setup_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_uncaught_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_basic",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_None",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_optional_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_required_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_missing",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_with_default",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required_missing",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_cli_cmd_to_string",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_serial",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_shell_true",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_shell_true_with_serial",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_stderr_pipe",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_error_no_timeout",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_no_timeout_success",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_timed_out",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_with_negative_timeout_value",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_with_timeout_success",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_called_correctly",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_existing_command",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_missing_command_on_newer_devices",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_missing_command_on_older_devices",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_options",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_runner",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_without_parameters"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2018-05-11 15:02:16+00:00
|
apache-2.0
| 2,597 |
|
google__mobly-445
|
diff --git a/docs/mobly.rst b/docs/mobly.rst
index ee4b412..91ecb1b 100644
--- a/docs/mobly.rst
+++ b/docs/mobly.rst
@@ -35,6 +35,14 @@ mobly.config_parser module
:undoc-members:
:show-inheritance:
+mobly.expects module
+--------------------------
+
+.. automodule:: mobly.expects
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
mobly.keys module
-----------------
@@ -59,6 +67,14 @@ mobly.records module
:undoc-members:
:show-inheritance:
+mobly.runtime_test_info module
+------------------------------
+
+.. automodule:: mobly.runtime_test_info
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
mobly.signals module
--------------------
@@ -67,6 +83,14 @@ mobly.signals module
:undoc-members:
:show-inheritance:
+mobly.suite_runner module
+-------------------------
+
+.. automodule:: mobly.suite_runner
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
mobly.test_runner module
------------------------
diff --git a/mobly/controllers/android_device.py b/mobly/controllers/android_device.py
index 14828a4..746f819 100644
--- a/mobly/controllers/android_device.py
+++ b/mobly/controllers/android_device.py
@@ -436,8 +436,9 @@ class AndroidDevice(object):
self._log_path = os.path.join(self._log_path_base,
'AndroidDevice%s' % self._serial)
self._debug_tag = self._serial
- self.log = AndroidDeviceLoggerAdapter(logging.getLogger(),
- {'tag': self.debug_tag})
+ self.log = AndroidDeviceLoggerAdapter(logging.getLogger(), {
+ 'tag': self.debug_tag
+ })
self.sl4a = None
self.ed = None
self._adb_logcat_process = None
@@ -680,6 +681,9 @@ class AndroidDevice(object):
execution result after device got reconnected.
Example Usage:
+
+ .. code-block:: python
+
with ad.handle_usb_disconnect():
try:
# User action that triggers USB disconnect, could throw
@@ -842,9 +846,12 @@ class AndroidDevice(object):
"""Starts the snippet apk with the given package name and connects.
Examples:
- >>> ad.load_snippet(
+
+ .. code-block:: python
+
+ ad.load_snippet(
name='maps', package='com.google.maps.snippets')
- >>> ad.maps.activateZoom('3')
+ ad.maps.activateZoom('3')
Args:
name: The attribute name to which to attach the snippet server.
diff --git a/mobly/controllers/android_device_lib/adb.py b/mobly/controllers/android_device_lib/adb.py
index 12c14bd..db705e7 100644
--- a/mobly/controllers/android_device_lib/adb.py
+++ b/mobly/controllers/android_device_lib/adb.py
@@ -237,7 +237,8 @@ class AdbProxy(object):
def forward(self, args=None, shell=False):
with ADB_PORT_LOCK:
- return self._exec_adb_cmd('forward', args, shell, timeout=None)
+ return self._exec_adb_cmd(
+ 'forward', args, shell, timeout=None, stderr=None)
def instrument(self, package, options=None, runner=None):
"""Runs an instrumentation command on the device.
@@ -245,6 +246,9 @@ class AdbProxy(object):
This is a convenience wrapper to avoid parameter formatting.
Example:
+
+ .. code-block:: python
+
device.instrument(
'com.my.package.test',
options = {
diff --git a/mobly/suite_runner.py b/mobly/suite_runner.py
index a7e5f16..468b7e7 100644
--- a/mobly/suite_runner.py
+++ b/mobly/suite_runner.py
@@ -16,6 +16,8 @@
To create a test suite, call suite_runner.run_suite() with one or more
individual test classes. For example:
+.. code-block:: python
+
from mobly import suite_runner
from my.test.lib import foo_test
@@ -103,7 +105,7 @@ def run_suite(test_classes, argv=None):
sys.exit(1)
-def _compute_selected_tests(test_classes, selected_tests):
+def compute_selected_tests(test_classes, selected_tests):
"""Computes tests to run for each class from selector strings.
This function transforms a list of selector strings (such as FooTest or
@@ -112,24 +114,34 @@ def _compute_selected_tests(test_classes, selected_tests):
that class are selected.
Args:
- test_classes: (list of class) all classes that are part of this suite.
- selected_tests: (list of string) list of tests to execute, eg:
- [
- 'FooTest',
- 'BarTest',
- 'BazTest.test_method_a',
- 'BazTest.test_method_b'
- ].
- May be empty, in which case all tests in the class are selected.
+ test_classes: list of strings, names of all the classes that are part
+ of a suite.
+ selected_tests: list of strings, list of tests to execute. If empty,
+ all classes `test_classes` are selected. E.g.
+
+ .. code-block:: python
+
+ [
+ 'FooTest',
+ 'BarTest',
+ 'BazTest.test_method_a',
+ 'BazTest.test_method_b'
+ ]
Returns:
- dict: test_name class -> list(test_name name):
- identifiers for TestRunner. For the above example:
- {
- FooTest: None,
- BarTest: None,
- BazTest: ['test_method_a', 'test_method_b'],
- }
+ dict: Identifiers for TestRunner. Keys are test class names; valures
+ are lists of test names within class. E.g. the example in
+ `selected_tests` would translate to:
+
+ .. code-block:: python
+
+ {
+ FooTest: None,
+ BarTest: None,
+ BazTest: ['test_method_a', 'test_method_b']
+ }
+
+ This dict is easy to consume for `TestRunner`.
"""
class_to_tests = collections.OrderedDict()
if not selected_tests:
|
google/mobly
|
8caa5c387b2df47a180e0349fbebe7838b099b83
|
diff --git a/mobly/base_test.py b/mobly/base_test.py
index e4e047b..13a79b0 100644
--- a/mobly/base_test.py
+++ b/mobly/base_test.py
@@ -624,6 +624,10 @@ class BaseTestClass(object):
tests = self._get_test_methods(test_names)
try:
# Setup for the class.
+ class_record = records.TestResultRecord('setup_class', self.TAG)
+ class_record.test_begin()
+ self.current_test_info = runtime_test_info.RuntimeTestInfo(
+ 'setup_class', self.log_path, class_record)
try:
self._setup_class()
except signals.TestAbortSignal:
@@ -633,9 +637,6 @@ class BaseTestClass(object):
# Setup class failed for unknown reasons.
# Fail the class and skip all tests.
logging.exception('Error in setup_class %s.', self.TAG)
- class_record = records.TestResultRecord(
- 'setup_class', self.TAG)
- class_record.test_begin()
class_record.test_error(e)
self._exec_procedure_func(self._on_fail, class_record)
self.results.add_class_error(class_record)
diff --git a/mobly/runtime_test_info.py b/mobly/runtime_test_info.py
index f4eea99..57b0742 100644
--- a/mobly/runtime_test_info.py
+++ b/mobly/runtime_test_info.py
@@ -19,10 +19,13 @@ from mobly import utils
class RuntimeTestInfo(object):
- """Container class for runtime information of a test.
+ """Container class for runtime information of a test or test stage.
One object corresponds to one test. This is meant to be a read-only class.
+ This also applies to test stages like `setup_class`, which has its own
+ runtime info but is not part of any single test.
+
Attributes:
name: string, name of the test.
signature: string, an identifier of the test, a combination of test
diff --git a/tests/mobly/base_test_test.py b/tests/mobly/base_test_test.py
index d78a640..a38b532 100755
--- a/tests/mobly/base_test_test.py
+++ b/tests/mobly/base_test_test.py
@@ -91,6 +91,25 @@ class BaseTestTest(unittest.TestCase):
self.assertIsNone(actual_record.details)
self.assertIsNone(actual_record.extras)
+ def test_current_test_info_in_setup_class(self):
+ class MockBaseTest(base_test.BaseTestClass):
+ def setup_class(self):
+ asserts.assert_true(
+ self.current_test_info.name == 'setup_class',
+ 'Got unexpected test name %s.' %
+ self.current_test_info.name)
+ output_path = self.current_test_info.output_path
+ asserts.assert_true(
+ os.path.exists(output_path), 'test output path missing')
+ raise Exception(MSG_EXPECTED_EXCEPTION)
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.run()
+ actual_record = bt_cls.results.error[0]
+ self.assertEqual(actual_record.test_name, 'setup_class')
+ self.assertEqual(actual_record.details, MSG_EXPECTED_EXCEPTION)
+ self.assertIsNone(actual_record.extras)
+
def test_self_tests_list(self):
class MockBaseTest(base_test.BaseTestClass):
def __init__(self, controllers):
diff --git a/tests/mobly/controllers/android_device_lib/adb_test.py b/tests/mobly/controllers/android_device_lib/adb_test.py
index 7bf61ab..cf699ce 100755
--- a/tests/mobly/controllers/android_device_lib/adb_test.py
+++ b/tests/mobly/controllers/android_device_lib/adb_test.py
@@ -173,6 +173,10 @@ class AdbTest(unittest.TestCase):
self.assertEqual(MOCK_DEFAULT_STDERR,
stderr_redirect.getvalue().decode('utf-8'))
+ def test_forward(self):
+ with mock.patch.object(adb.AdbProxy, '_exec_cmd') as mock_exec_cmd:
+ adb.AdbProxy().forward(MOCK_SHELL_COMMAND)
+
def test_instrument_without_parameters(self):
"""Verifies the AndroidDevice object's instrument command is correct in
the basic case.
diff --git a/tests/mobly/suite_runner_test.py b/tests/mobly/suite_runner_test.py
index dacd754..d0a9be4 100755
--- a/tests/mobly/suite_runner_test.py
+++ b/tests/mobly/suite_runner_test.py
@@ -21,7 +21,7 @@ from tests.lib import integration2_test
class SuiteRunnerTest(unittest.TestCase):
def test_select_no_args(self):
- identifiers = suite_runner._compute_selected_tests(
+ identifiers = suite_runner.compute_selected_tests(
test_classes=[
integration_test.IntegrationTest,
integration2_test.Integration2Test
@@ -33,7 +33,7 @@ class SuiteRunnerTest(unittest.TestCase):
}, identifiers)
def test_select_by_class(self):
- identifiers = suite_runner._compute_selected_tests(
+ identifiers = suite_runner.compute_selected_tests(
test_classes=[
integration_test.IntegrationTest,
integration2_test.Integration2Test
@@ -42,7 +42,7 @@ class SuiteRunnerTest(unittest.TestCase):
self.assertEqual({integration_test.IntegrationTest: None}, identifiers)
def test_select_by_method(self):
- identifiers = suite_runner._compute_selected_tests(
+ identifiers = suite_runner.compute_selected_tests(
test_classes=[
integration_test.IntegrationTest,
integration2_test.Integration2Test
@@ -55,7 +55,7 @@ class SuiteRunnerTest(unittest.TestCase):
}, identifiers)
def test_select_all_clobbers_method(self):
- identifiers = suite_runner._compute_selected_tests(
+ identifiers = suite_runner.compute_selected_tests(
test_classes=[
integration_test.IntegrationTest,
integration2_test.Integration2Test
@@ -63,7 +63,7 @@ class SuiteRunnerTest(unittest.TestCase):
selected_tests=['IntegrationTest.test_a', 'IntegrationTest'])
self.assertEqual({integration_test.IntegrationTest: None}, identifiers)
- identifiers = suite_runner._compute_selected_tests(
+ identifiers = suite_runner.compute_selected_tests(
test_classes=[
integration_test.IntegrationTest,
integration2_test.Integration2Test
|
Modules missing from API docs
Our [API docs](http://mobly.readthedocs.io/en/stable/)
Is missing some modules like `mobly.runtime_test_info`
|
0.0
|
8caa5c387b2df47a180e0349fbebe7838b099b83
|
[
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_forward",
"tests/mobly/suite_runner_test.py::SuiteRunnerTest::test_select_all_clobbers_method",
"tests/mobly/suite_runner_test.py::SuiteRunnerTest::test_select_by_class",
"tests/mobly/suite_runner_test.py::SuiteRunnerTest::test_select_by_method",
"tests/mobly/suite_runner_test.py::SuiteRunnerTest::test_select_no_args"
] |
[
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_on_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_on_fail_from_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_in_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_all_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_on_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail_with_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_regex",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_both_teardown_and_test_body_raise_exceptions",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_override_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_info",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_info_in_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_default_execution_of_all_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_exception_objects_in_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_equal",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_false",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_in_teardown_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_multiple_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_no_op",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_no_raises_custom_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_no_raises_default_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_true_and_assert_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_expect_two_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass_but_teardown_test_raises_an_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_in_procedure_functions_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_to_call_procedure_function_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_call_outside_of_setup_generated_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_dup_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_selected_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_implicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_missing_requested_test_func",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_cannot_modify_original_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_both_test_and_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_setup_fails_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_cannot_modify_original_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_procedure_function_gets_correct_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_promote_extra_errors_to_termination_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_and_teardown_execution_count",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_test_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_if",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_assert_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_setup_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_uncaught_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_basic",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_None",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_optional_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_required_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_missing",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_with_default",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required_missing",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_cli_cmd_to_string",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_serial",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_shell_true",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_shell_true_with_serial",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_stderr_pipe",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_error_no_timeout",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_no_timeout_success",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_timed_out",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_with_negative_timeout_value",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_with_timeout_success",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_called_correctly",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_existing_command",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_missing_command_on_newer_devices",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_missing_command_on_older_devices",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_options",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_runner",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_without_parameters"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-11 15:20:50+00:00
|
apache-2.0
| 2,598 |
|
google__mobly-453
|
diff --git a/mobly/controllers/android_device_lib/adb.py b/mobly/controllers/android_device_lib/adb.py
index 90dcd0b..95d1261 100644
--- a/mobly/controllers/android_device_lib/adb.py
+++ b/mobly/controllers/android_device_lib/adb.py
@@ -203,6 +203,7 @@ class AdbProxy(object):
stderr=subprocess.PIPE,
shell=shell,
bufsize=1)
+ out = '[elided, processed via handler]'
try:
while proc.poll() is None:
line = proc.stdout.readline()
@@ -211,16 +212,19 @@ class AdbProxy(object):
else:
break
finally:
- (_, err) = proc.communicate()
+ (unexpected_out, err) = proc.communicate()
+ if unexpected_out:
+ out = '[unexpected stdout] %s' % unexpected_out
+ for line in unexpected_out.splitlines():
+ handler(line)
+
ret = proc.returncode
+ logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s',
+ cli_cmd_to_string(args), out, err, ret)
if ret == 0:
return err
else:
- raise AdbError(
- cmd=args,
- stdout='[elided, processed via handler]',
- stderr=err,
- ret_code=ret)
+ raise AdbError(cmd=args, stdout=out, stderr=err, ret_code=ret)
def _construct_adb_cmd(self, raw_name, args, shell):
"""Constructs an adb command with arguments for a subprocess call.
diff --git a/mobly/controllers/android_device_lib/snippet_client.py b/mobly/controllers/android_device_lib/snippet_client.py
index e3e835d..03674ff 100644
--- a/mobly/controllers/android_device_lib/snippet_client.py
+++ b/mobly/controllers/android_device_lib/snippet_client.py
@@ -125,8 +125,7 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
# Yaaay! We're done!
self.log.debug('Snippet %s started after %.1fs on host port %s',
- self.package,
- time.time() - start_time, self.host_port)
+ self.package, time.time() - start_time, self.host_port)
def restore_app_connection(self, port=None):
"""Restores the app after device got reconnected.
@@ -151,12 +150,13 @@ class SnippetClient(jsonrpc_client_base.JsonRpcClientBase):
try:
self.connect()
except:
- # Failed to connect to app, something went wrong.
+ # Log the original error and raise AppRestoreConnectionError.
+ self.log.exception('Failed to re-connect to app.')
raise jsonrpc_client_base.AppRestoreConnectionError(
- self._ad(
- 'Failed to restore app connection for %s at host port %s, '
- 'device port %s'), self.package, self.host_port,
- self.device_port)
+ self._ad,
+ ('Failed to restore app connection for %s at host port %s, '
+ 'device port %s') % (self.package, self.host_port,
+ self.device_port))
# Because the previous connection was lost, update self._proc
self._proc = None
|
google/mobly
|
f1aff6a7f06887424759e3c192b1bf6e13d2a6bf
|
diff --git a/tests/mobly/controllers/android_device_lib/adb_test.py b/tests/mobly/controllers/android_device_lib/adb_test.py
index 1c75a9d..8dec8aa 100755
--- a/tests/mobly/controllers/android_device_lib/adb_test.py
+++ b/tests/mobly/controllers/android_device_lib/adb_test.py
@@ -76,8 +76,7 @@ class AdbTest(unittest.TestCase):
mock_popen.return_value.stdout.readline.side_effect = ['']
mock_proc.communicate = mock.Mock(
- return_value=(MOCK_DEFAULT_STDOUT.encode('utf-8'),
- MOCK_DEFAULT_STDERR.encode('utf-8')))
+ return_value=('', MOCK_DEFAULT_STDERR.encode('utf-8')))
mock_proc.returncode = 0
return mock_popen
@@ -150,6 +149,57 @@ class AdbTest(unittest.TestCase):
mock_handler.assert_any_call('1')
mock_handler.assert_any_call('2')
+ @mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
+ def test_execute_and_process_stdout_reads_unexpected_stdout(
+ self, mock_popen):
+ unexpected_stdout = MOCK_DEFAULT_STDOUT.encode('utf-8')
+
+ self._mock_execute_and_process_stdout_process(mock_popen)
+ mock_handler = mock.MagicMock()
+ mock_popen.return_value.communicate = mock.Mock(
+ return_value=(unexpected_stdout, MOCK_DEFAULT_STDERR.encode(
+ 'utf-8')))
+
+ err = adb.AdbProxy()._execute_and_process_stdout(
+ ['fake_cmd'], shell=False, handler=mock_handler)
+ self.assertEqual(mock_handler.call_count, 1)
+ mock_handler.assert_called_with(unexpected_stdout)
+
+ @mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
+ @mock.patch('logging.debug')
+ def test_execute_and_process_stdout_logs_cmd(self, mock_debug_logger,
+ mock_popen):
+ raw_expected_stdout = ''
+ expected_stdout = '[elided, processed via handler]'
+ expected_stderr = MOCK_DEFAULT_STDERR.encode('utf-8')
+ self._mock_execute_and_process_stdout_process(mock_popen)
+ mock_popen.return_value.communicate = mock.Mock(
+ return_value=(raw_expected_stdout, expected_stderr))
+
+ err = adb.AdbProxy()._execute_and_process_stdout(
+ ['fake_cmd'], shell=False, handler=mock.MagicMock())
+ mock_debug_logger.assert_called_with(
+ 'cmd: %s, stdout: %s, stderr: %s, ret: %s', 'fake_cmd',
+ expected_stdout, expected_stderr, 0)
+
+ @mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
+ @mock.patch('logging.debug')
+ def test_execute_and_process_stdout_logs_cmd_with_unexpected_stdout(
+ self, mock_debug_logger, mock_popen):
+ raw_expected_stdout = MOCK_DEFAULT_STDOUT.encode('utf-8')
+ expected_stdout = '[unexpected stdout] %s' % raw_expected_stdout
+ expected_stderr = MOCK_DEFAULT_STDERR.encode('utf-8')
+
+ self._mock_execute_and_process_stdout_process(mock_popen)
+ mock_popen.return_value.communicate = mock.Mock(
+ return_value=(raw_expected_stdout, expected_stderr))
+
+ err = adb.AdbProxy()._execute_and_process_stdout(
+ ['fake_cmd'], shell=False, handler=mock.MagicMock())
+ mock_debug_logger.assert_called_with(
+ 'cmd: %s, stdout: %s, stderr: %s, ret: %s', 'fake_cmd',
+ expected_stdout, expected_stderr, 0)
+
@mock.patch('mobly.controllers.android_device_lib.adb.subprocess.Popen')
def test_execute_and_process_stdout_when_cmd_exits(self, mock_popen):
self._mock_execute_and_process_stdout_process(mock_popen)
diff --git a/tests/mobly/controllers/android_device_lib/snippet_client_test.py b/tests/mobly/controllers/android_device_lib/snippet_client_test.py
index 2c875d8..d964ae3 100755
--- a/tests/mobly/controllers/android_device_lib/snippet_client_test.py
+++ b/tests/mobly/controllers/android_device_lib/snippet_client_test.py
@@ -166,6 +166,15 @@ class SnippetClientTest(jsonrpc_client_test_base.JsonRpcClientTestBase):
self.assertEqual(789, callback._event_client.host_port)
self.assertEqual(456, callback._event_client.device_port)
+ # if unable to reconnect for any reason, a
+ # jsonrpc_client_base.AppRestoreConnectionError is raised.
+ mock_create_connection.side_effect = IOError('socket timed out')
+ with self.assertRaisesRegex(
+ jsonrpc_client_base.AppRestoreConnectionError,
+ ('Failed to restore app connection for %s at host port %s, '
+ 'device port %s') % (MOCK_PACKAGE_NAME, 789, 456)):
+ client.restore_app_connection()
+
@mock.patch('socket.create_connection')
@mock.patch('mobly.controllers.android_device_lib.snippet_client.'
'utils.start_standing_subprocess')
|
`_execute_and_process_stdout` should log cmd
|
0.0
|
f1aff6a7f06887424759e3c192b1bf6e13d2a6bf
|
[
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_logs_cmd",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_logs_cmd_with_unexpected_stdout",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_reads_unexpected_stdout",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_restore_event_client"
] |
[
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_cli_cmd_to_string",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_list",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_one_arg_command",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_one_arg_command_list",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_one_command",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_serial",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_serial_with_list",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_auto_quotes",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_list",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_one_arg_command",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_one_arg_command_list",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_one_command",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_serial",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_shell_true_with_serial_with_list",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_construct_adb_cmd_with_special_characters",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_formats_command",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_formats_command_with_shell_true",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_shell_true",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_adb_cmd_with_stderr_pipe",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_error_no_timeout",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_no_timeout_success",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_timed_out",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_with_negative_timeout_value",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_exec_cmd_with_timeout_success",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_adb_and_process_stdout_formats_command",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_raises_adb_error",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_reads_stdout",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_returns_stderr",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_when_cmd_eof",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_when_cmd_exits",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_execute_and_process_stdout_when_handler_crash",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_forward",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_called_correctly",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_existing_command",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_missing_command_on_newer_devices",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_has_shell_command_with_missing_command_on_older_devices",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_handler",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_handler_with_options",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_handler_with_runner",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_options",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_with_runner",
"tests/mobly/controllers/android_device_lib/adb_test.py::AdbTest::test_instrument_without_parameters",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_app_not_installed",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_not_instrumented",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_fail_target_not_installed",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_check_app_installed_normal",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_header_junk",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_no_valid_line",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_persistent_session",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_and_connect_unknown_protocol",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_app_crash",
"tests/mobly/controllers/android_device_lib/snippet_client_test.py::SnippetClientTest::test_snippet_start_event_client"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-05-24 19:50:41+00:00
|
apache-2.0
| 2,599 |
|
google__mobly-472
|
diff --git a/mobly/config_parser.py b/mobly/config_parser.py
index aa43c03..b873af0 100644
--- a/mobly/config_parser.py
+++ b/mobly/config_parser.py
@@ -16,6 +16,7 @@ from builtins import str
import copy
import io
+import pprint
import os
import yaml
@@ -189,4 +190,7 @@ class TestRunConfig(object):
return copy.deepcopy(self)
def __str__(self):
- return str(self.__dict__)
+ content = dict(self.__dict__)
+ content.pop('summary_writer')
+ content.pop('register_controller')
+ return pprint.pformat(content)
diff --git a/mobly/controllers/android_device.py b/mobly/controllers/android_device.py
index 504f671..4d89af8 100644
--- a/mobly/controllers/android_device.py
+++ b/mobly/controllers/android_device.py
@@ -436,8 +436,9 @@ class AndroidDevice(object):
self._log_path = os.path.join(self._log_path_base,
'AndroidDevice%s' % self._serial)
self._debug_tag = self._serial
- self.log = AndroidDeviceLoggerAdapter(logging.getLogger(),
- {'tag': self.debug_tag})
+ self.log = AndroidDeviceLoggerAdapter(logging.getLogger(), {
+ 'tag': self.debug_tag
+ })
self.sl4a = None
self.ed = None
self._adb_logcat_process = None
@@ -783,15 +784,7 @@ class AndroidDevice(object):
@property
def is_rootable(self):
- """If the build type is 'user', the device is not rootable.
-
- Other possible build types are 'userdebug' and 'eng', both are rootable.
- We are checking the last four chars of the clean stdout because the
- stdout of the adb command could be polluted with other info like adb
- server startup message.
- """
- build_type_output = self.adb.getprop('ro.build.type').lower()
- return build_type_output[-4:] != 'user'
+ return self.adb.getprop('ro.debuggable') == '1'
@property
def model(self):
diff --git a/mobly/controllers/android_device_lib/jsonrpc_client_base.py b/mobly/controllers/android_device_lib/jsonrpc_client_base.py
index 279360d..498434d 100644
--- a/mobly/controllers/android_device_lib/jsonrpc_client_base.py
+++ b/mobly/controllers/android_device_lib/jsonrpc_client_base.py
@@ -19,7 +19,7 @@ The JSON protocol expected by this module is:
Request:
{
- "id": <monotonically increasing integer containing the ID of
+ "id": <monotonically increasing integer containing the ID of
this request>
"method": <string containing the name of the method to execute>
"params": <JSON array containing the arguments to the method>
@@ -239,6 +239,7 @@ class JsonRpcClientBase(object):
try:
self._client.write(msg.encode("utf8") + b'\n')
self._client.flush()
+ self.log.debug('Snippet sent %s.', msg)
except socket.error as e:
raise Error(
self._ad,
@@ -255,7 +256,9 @@ class JsonRpcClientBase(object):
Error: a socket error occurred during the read.
"""
try:
- return self._client.readline()
+ response = self._client.readline()
+ self.log.debug('Snippet received: %s', response)
+ return response
except socket.error as e:
raise Error(
self._ad,
@@ -299,7 +302,7 @@ class JsonRpcClientBase(object):
if not response:
raise ProtocolError(self._ad,
ProtocolError.NO_RESPONSE_FROM_SERVER)
- result = json.loads(str(response, encoding="utf8"))
+ result = json.loads(str(response, encoding='utf8'))
if result['error']:
raise ApiError(self._ad, result['error'])
if result['id'] != apiid:
|
google/mobly
|
9c5b19e1b932888d3e347fa529b82f5417b28a5e
|
diff --git a/mobly/test_runner.py b/mobly/test_runner.py
index af834e8..e4fa9d8 100644
--- a/mobly/test_runner.py
+++ b/mobly/test_runner.py
@@ -381,8 +381,9 @@ class TestRunner(object):
test_class: class, test class to execute.
tests: Optional list of test names within the class to execute.
"""
-
with test_class(config) as test_instance:
+ logging.debug('Executing test class "%s" with config: %s',
+ test_class.__name__, config)
try:
cls_result = test_instance.run(tests)
self.results += cls_result
diff --git a/tests/mobly/config_parser_test.py b/tests/mobly/config_parser_test.py
index ea16668..44dfbdc 100644
--- a/tests/mobly/config_parser_test.py
+++ b/tests/mobly/config_parser_test.py
@@ -56,6 +56,11 @@ class OutputTest(unittest.TestCase):
config = config_parser._load_config_file(tmp_file_path)
self.assertEqual(config['TestBeds'][0]['Name'], u'\u901a')
+ def test_run_config_type(self):
+ config = config_parser.TestRunConfig()
+ self.assertNotIn('summary_writer', str(config))
+ self.assertNotIn('register_controller', str(config))
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py
index e12e511..eb5129a 100755
--- a/tests/mobly/controllers/android_device_test.py
+++ b/tests/mobly/controllers/android_device_test.py
@@ -706,7 +706,8 @@ class AndroidDeviceTest(unittest.TestCase):
self, MockFastboot, MockAdbProxy):
mock_serial = '1'
mock_adb_proxy = MockAdbProxy.return_value
- mock_adb_proxy.getprop.return_value = 'userdebug'
+ # Set getprop to return '1' to indicate the device is rootable.
+ mock_adb_proxy.getprop.return_value = '1'
mock_adb_proxy.has_shell_command.side_effect = lambda command: {
'logpersist.start': True,
'logpersist.stop': True, }[command]
|
Log the contents of config file at the debug level early
This helps in debugging remote user's malformed json/yaml or configs that don't adhere to schema.
|
0.0
|
9c5b19e1b932888d3e347fa529b82f5417b28a5e
|
[
"tests/mobly/config_parser_test.py::OutputTest::test_run_config_type"
] |
[
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice__enable_logpersist_with_logpersist",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice__enable_logpersist_with_missing_all_logpersist",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice__enable_logpersist_with_missing_logpersist_start",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice__enable_logpersist_with_missing_logpersist_stop",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_build_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_cat_adb_log",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_cat_adb_log_with_unicode",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_change_log_path",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_change_log_path_no_log_exists",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_change_log_path_with_existing_file",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_change_log_path_with_service",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_debug_tag",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_device_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_instantiation",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_attribute_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_package",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_snippet_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_fail_cleanup_also_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_failure",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_precheck_failure",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_start_app_fails",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_serial_is_valid",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_snippet_cleanup",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fallback",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_with_destination",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat_with_user_param",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_unload_snippet",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_update_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_update_serial_with_service_running",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_dict_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_empty_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_no_valid_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_not_list_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_pickup_all",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_string_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_usb_id",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial_and_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_too_many_matches",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_devices_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_devices_success_with_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads_skip_logcat"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-07-19 00:05:12+00:00
|
apache-2.0
| 2,600 |
|
google__sre_yield-21
|
diff --git a/README.rst b/README.rst
index 06ca7b0..f2a7f90 100644
--- a/README.rst
+++ b/README.rst
@@ -110,6 +110,42 @@ This even works for simplistic backreferences, in this case to have matching quo
'000'
+Anchors and Lookaround
+======================
+
+Some very simple anchors are supported out of the box, to enable parsing
+patterns where the anchors are actually redundant with it being fullmatch, such
+as ``^foo$``. More complex anchoring should raise an exception at parse time,
+as will any use of lookaround. (``\b`` is supported at beginning/end despite
+this being not quite correct.)
+
+.. code-block:: pycon
+
+ >>> list(sre_yield.AllStrings('foo$'))
+ ['foo']
+ >>> list(sre_yield.AllStrings('^$'))
+ ['']
+ >>> list(sre_yield.AllStrings('.\\b.')) # doctest: +IGNORE_EXCEPTION_DETAIL
+ Traceback (most recent call last):
+ ...
+ ParseError: Non-end-anchor None found at END state
+
+Supporting these in a limited way is possible, but I haven't found the time in
+6+ years to implement it, because I don't have a need. Instead if you need
+these and don't mind (potentially many) extra matches, provide ``relaxed=True`` to
+pretend these don't exist, at which point the values returned by ``sre_yield``
+will be a superset of the true matches, and you can postprocess them yourself.
+
+.. code-block:: pycon
+
+ >>> pattern = '.\\b.'
+ >>> values = list(sre_yield.AllStrings(pattern, charset='a-', relaxed=True))
+ >>> values
+ ['aa', '-a', 'a-', '--']
+ >>> [v for v in values if re.fullmatch(pattern, v)]
+ ['-a', 'a-']
+
+
Reporting Bugs, etc.
====================
@@ -201,15 +237,3 @@ other exceptions:
yet this appears to work fine.
- Order does not depend on greediness.
- The regex is treated as fullmatch.
-- ``sre_yield`` is confused by complex uses of anchors, but support simple ones:
-
- .. code-block:: pycon
-
- >>> list(sre_yield.AllStrings('foo$'))
- ['foo']
- >>> list(sre_yield.AllStrings('^$'))
- ['']
- >>> list(sre_yield.AllStrings('.\\b.')) # doctest: +IGNORE_EXCEPTION_DETAIL
- Traceback (most recent call last):
- ...
- ParseError: Non-end-anchor None found at END state
diff --git a/sre_yield/__init__.py b/sre_yield/__init__.py
index 6cb16c4..4ccf2da 100644
--- a/sre_yield/__init__.py
+++ b/sre_yield/__init__.py
@@ -27,6 +27,7 @@ __all__ = ["Values", "AllStrings", "AllMatches", "ParseError"]
import bisect
import re
+import sre_compile
import sre_constants
import sre_parse
import string
@@ -402,6 +403,11 @@ class RegexMembershipSequence(WrappedSequence):
def nothing_added(self, *_):
return [""]
+ def lookaround_parse_error(self, *_):
+ raise ParseError(
+ "Lookarounds are not supported, try relaxed=True and postprocess"
+ )
+
def branch_values(self, _, items):
"""Converts SRE parser data into literals and merges those lists."""
return ConcatenatedSequence(*[self.sub_values(parsed) for parsed in items])
@@ -456,7 +462,8 @@ class RegexMembershipSequence(WrappedSequence):
if not isinstance(arguments, tuple):
arguments = (arguments,)
if matcher in self.backends:
- self.check_anchor_state(matcher, arguments)
+ if not self.relaxed:
+ self.check_anchor_state(matcher, arguments)
return self.backends[matcher](*arguments)
# No idea what to do here
raise ParseError(repr(parsed)) # pragma: no cover
@@ -524,12 +531,17 @@ class RegexMembershipSequence(WrappedSequence):
# All others (AT_END, AT_END_STRING, AT_BOUNDARY) advance to END.
self.state = STATE_END
- def __init__(self, pattern, flags=0, charset=CHARSET, max_count=None):
+ def __init__(
+ self, pattern, flags=0, charset=CHARSET, max_count=None, relaxed=False
+ ):
# If the RE module cannot compile it, we give up quickly
- self.matcher = re.compile(r"(?:%s)\Z" % pattern, flags)
+ if not isinstance(pattern, sre_parse.SubPattern):
+ pattern = sre_parse.parse(pattern, flags)
+ self.matcher = sre_compile.compile(pattern, flags)
if not flags & re.DOTALL:
charset = "".join(c for c in charset if c != "\n")
self.charset = charset
+ self.relaxed = relaxed
self.named_group_lookup = self.matcher.groupindex
@@ -563,23 +575,31 @@ class RegexMembershipSequence(WrappedSequence):
sre_constants.MIN_REPEAT: self.max_repeat_values,
sre_constants.MAX_REPEAT: self.max_repeat_values,
sre_constants.AT: self.nothing_added,
- sre_constants.ASSERT: self.empty_list,
- sre_constants.ASSERT_NOT: self.empty_list,
+ sre_constants.ASSERT: self.lookaround_parse_error,
+ sre_constants.ASSERT_NOT: self.lookaround_parse_error,
sre_constants.ANY: lambda _: self.in_values(((sre_constants.NEGATE,),)),
sre_constants.IN: self.in_values,
sre_constants.NOT_LITERAL: self.not_literal,
sre_constants.CATEGORY: self.category,
sre_constants.GROUPREF: self.groupref,
}
+ if self.relaxed:
+ self.backends.update(
+ {
+ sre_constants.ASSERT: self.nothing_added,
+ sre_constants.ASSERT_NOT: self.nothing_added,
+ }
+ )
+
self.state = STATE_START
# Now build a generator that knows all possible patterns
- self.raw = self.sub_values(sre_parse.parse(pattern, flags))
+ self.raw = self.sub_values(pattern)
# Configure this class instance to know about that result
self.length = self.raw.__len__()
def __contains__(self, item):
# Since we have a regex, we can search the list really cheaply
- return self.matcher.match(item) is not None
+ return self.matcher.fullmatch(item) is not None
class RegexMembershipSequenceMatches(RegexMembershipSequence):
@@ -596,9 +616,11 @@ class RegexMembershipSequenceMatches(RegexMembershipSequence):
return Match(s, d, self.named_group_lookup)
-def AllStrings(regex, flags=0, charset=CHARSET, max_count=None):
+def AllStrings(regex, flags=0, charset=CHARSET, max_count=None, relaxed=False):
"""Constructs an object that will generate all matching strings."""
- return RegexMembershipSequence(regex, flags, charset, max_count=max_count)
+ return RegexMembershipSequence(
+ regex, flags, charset, max_count=max_count, relaxed=relaxed
+ )
Values = AllStrings
@@ -632,9 +654,11 @@ class Match(object):
raise NotImplementedError()
-def AllMatches(regex, flags=0, charset=CHARSET, max_count=None):
+def AllMatches(regex, flags=0, charset=CHARSET, max_count=None, relaxed=False):
"""Constructs an object that will generate all matching strings."""
- return RegexMembershipSequenceMatches(regex, flags, charset, max_count=max_count)
+ return RegexMembershipSequenceMatches(
+ regex, flags, charset, max_count=max_count, relaxed=relaxed
+ )
def main(argv=None):
|
google/sre_yield
|
90a651accda89f798f6e88d8c62d08d809bf667d
|
diff --git a/sre_yield/tests/test_compatibility.py b/sre_yield/tests/test_compatibility.py
index 654b3c6..517c219 100644
--- a/sre_yield/tests/test_compatibility.py
+++ b/sre_yield/tests/test_compatibility.py
@@ -40,6 +40,7 @@ class CompatibilityTest(UnitTest):
pat: str,
max_length: int,
expected_failure: bool = False,
+ relaxed: bool = False,
m: Optional[List[str]] = None,
):
# If this changes, some examples will need to be updated, especially
@@ -55,12 +56,16 @@ class CompatibilityTest(UnitTest):
[
x
for x in sre_yield.AllStrings(
- pat, charset=charset, max_count=max_length
+ pat, charset=charset, max_count=max_length, relaxed=relaxed
)
if len(x) <= max_length
],
key=lambda i: (len(i), i),
)
+ if relaxed:
+ # This test has no guardrails against having way too many matches
+ # that the caller should filter.
+ actual = [x for x in actual if pat_re.fullmatch(x)]
# These document current behavior, even when it's wrong, and when they
# start passing we want to know.
@@ -113,6 +118,34 @@ class CompatibilityTest(UnitTest):
def test_anchors(self, pat: str, max_length: int) -> None:
self._verify(pat, max_length)
+ @data_provider(
+ (
+ {"pat": r"(?=a)a", "max_length": 2},
+ {"pat": r"(?=a)a.", "max_length": 2},
+ {"pat": r"(?=a)b", "max_length": 2},
+ {"pat": r"(?=a).{3}", "max_length": 3},
+ {"pat": r"(?!a)a", "max_length": 2},
+ {"pat": r"(?!a)a.", "max_length": 2},
+ {"pat": r"(?!a)b", "max_length": 2},
+ )
+ )
+ def test_lookahead(
+ self, pat: str, max_length: int, expected_failure: bool = False
+ ) -> None:
+ self._verify(pat, max_length, expected_failure, relaxed=True)
+
+ @data_provider(
+ (
+ {"pat": r"\b.", "max_length": 2},
+ {"pat": r"[a-]\b[a-]", "max_length": 2, "m": ["-a", "a-"]},
+ {"pat": r"^.", "max_length": 2, "m": ["-", "a", "b", "c"]},
+ # This only passes because _verify does filtering
+ {"pat": r"^\b.", "max_length": 2, "m": ["a", "b", "c"]},
+ )
+ )
+ def test_boundary(self, **kwargs) -> None:
+ self._verify(relaxed=True, **kwargs)
+
if __name__ == "__main__":
unittest.main()
diff --git a/sre_yield/tests/test_sre_yield.py b/sre_yield/tests/test_sre_yield.py
index 3027058..9d54183 100644
--- a/sre_yield/tests/test_sre_yield.py
+++ b/sre_yield/tests/test_sre_yield.py
@@ -18,6 +18,7 @@
import codecs
import io
import re
+import sre_parse
import sys
import unittest
@@ -113,6 +114,28 @@ class YieldTest(unittest.TestCase):
self.assertTrue("0101" in parsed)
self.assertFalse("0201" in parsed)
+ def testPreparsedInstantiation(self):
+ self.assertSequenceEqual(sre_yield.AllStrings(r"(?:[aeiou])\Z"), list("aeiou"))
+ preparsed = sre_parse.parse("[aeiou]")
+ self.assertSequenceEqual(sre_yield.AllStrings(preparsed), list("aeiou"))
+ preparsed = sre_parse.parse(r"(?:[aeiou])\Z")
+ self.assertSequenceEqual(sre_yield.AllStrings(preparsed), list("aeiou"))
+
+ preparsed = sre_parse.parse("[01]+")
+ parsed = sre_yield.AllStrings(preparsed)
+ self.assertTrue("0101" in parsed)
+ self.assertFalse("0201" in parsed)
+
+ preparsed = sre_parse.parse("[01]+")
+ parsed = sre_yield.AllStrings(preparsed)
+ self.assertTrue("0101" in parsed)
+ self.assertFalse("0201" in parsed)
+
+ preparsed = sre_parse.parse(r"(?:[01]+)\Z")
+ parsed = sre_yield.AllStrings(preparsed)
+ self.assertTrue("0101" in parsed)
+ self.assertFalse("0201" in parsed)
+
def testNaturalOrder(self):
parsed = sre_yield.AllStrings("[0-9]{2}")
self.assertEqual(parsed[0], "00")
|
Problem with lookaheads
Positive and negative lookaheads behave the same. This is as of [d997adf]
```
>>> x = sre_yield.AllStrings("(?!a)x?")
>>> len(x)
0
>>> x.raw.list_lengths
[([], 0), ({repeat base=1 low=0 high=1}, 2)]
```
|
0.0
|
90a651accda89f798f6e88d8c62d08d809bf667d
|
[
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_anchors_0",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_anchors_1",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_anchors_2",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_boundary_0",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_boundary_1",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_boundary_2",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_boundary_3",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_charclass_0",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_charclass_1",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_charclass_2",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_lookahead_0",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_lookahead_1",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_lookahead_2",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_lookahead_3",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_lookahead_4",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_lookahead_5",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_lookahead_6",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_repeat_0",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_repeat_1",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_repeat_2",
"sre_yield/tests/test_compatibility.py::CompatibilityTest::test_repeat_3",
"sre_yield/tests/test_sre_yield.py::YieldTest::testPreparsedInstantiation"
] |
[
"sre_yield/tests/test_compatibility.py::MatchListTest::test_match_list_0",
"sre_yield/tests/test_compatibility.py::MatchListTest::test_match_list_1",
"sre_yield/tests/test_compatibility.py::MatchListTest::test_match_list_2",
"sre_yield/tests/test_sre_yield.py::YieldTest::testAllStringsIsValues",
"sre_yield/tests/test_sre_yield.py::YieldTest::testAlternationWithEmptyElement",
"sre_yield/tests/test_sre_yield.py::YieldTest::testBackrefCounts",
"sre_yield/tests/test_sre_yield.py::YieldTest::testCanIterateGiantValues",
"sre_yield/tests/test_sre_yield.py::YieldTest::testCanSliceGiantValues",
"sre_yield/tests/test_sre_yield.py::YieldTest::testCategories",
"sre_yield/tests/test_sre_yield.py::YieldTest::testContains",
"sre_yield/tests/test_sre_yield.py::YieldTest::testDotallFlag",
"sre_yield/tests/test_sre_yield.py::YieldTest::testGetItemNegative",
"sre_yield/tests/test_sre_yield.py::YieldTest::testLargeSequenceSliceLength",
"sre_yield/tests/test_sre_yield.py::YieldTest::testMain",
"sre_yield/tests/test_sre_yield.py::YieldTest::testMaxCount",
"sre_yield/tests/test_sre_yield.py::YieldTest::testNaturalOrder",
"sre_yield/tests/test_sre_yield.py::YieldTest::testOffset",
"sre_yield/tests/test_sre_yield.py::YieldTest::testOtherCases",
"sre_yield/tests/test_sre_yield.py::YieldTest::testParseErrors",
"sre_yield/tests/test_sre_yield.py::YieldTest::testSavingGroups",
"sre_yield/tests/test_sre_yield.py::YieldTest::testSavingGroupsByName",
"sre_yield/tests/test_sre_yield.py::YieldTest::testSimpleCases",
"sre_yield/tests/test_sre_yield.py::YieldTest::testSlices",
"sre_yield/tests/test_sre_yield.py::YieldTest::testSlicesRepeated",
"sre_yield/tests/test_sre_yield.py::YieldTest::testSlicingMatches"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-16 23:41:27+00:00
|
apache-2.0
| 2,601 |
|
google__yapf-1089
|
diff --git a/.pre-commit-config.yml b/.pre-commit-config.yml
deleted file mode 100644
index 3bd65c2..0000000
--- a/.pre-commit-config.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-# File introduces automated checks triggered on git events
-# to enable run `pip install pre-commit && pre-commit install`
-
-repos:
- - repo: local
- hooks:
- - id: yapf
- name: yapf
- language: python
- entry: yapf
- args: [-i, -vv]
- types: [python]
- - repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v3.2.0
- hooks:
- - id: trailing-whitespace
- - id: check-docstring-first
- - id: check-json
- - id: check-added-large-files
- - id: check-yaml
- - id: debug-statements
- - id: requirements-txt-fixer
- - id: check-merge-conflict
- - id: double-quote-string-fixer
- - id: end-of-file-fixer
- - id: sort-simple-yaml
- - repo: meta
- hooks:
- - id: check-hooks-apply
- - id: check-useless-excludes
diff --git a/.pre-commit-hooks.yml b/.pre-commit-hooks.yml
deleted file mode 100644
index 3eba1f2..0000000
--- a/.pre-commit-hooks.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-# File configures YAPF to be used as a git hook with https://github.com/pre-commit/pre-commit
-
-- id: yapf
- name: yapf
- description: "A formatter for Python files."
- entry: yapf
- args: [-i] #inplace
- language: python
- types: [python]
diff --git a/yapf/__init__.py b/yapf/__init__.py
index 14c693d..39b15c9 100644
--- a/yapf/__init__.py
+++ b/yapf/__init__.py
@@ -27,19 +27,34 @@ If no filenames are specified, YAPF reads the code from stdin.
"""
import argparse
+import codecs
+import io
import logging
import os
import sys
from yapf.yapflib import errors
from yapf.yapflib import file_resources
-from yapf.yapflib import py3compat
from yapf.yapflib import style
from yapf.yapflib import yapf_api
__version__ = '0.33.0'
+def _raw_input():
+ wrapper = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
+ return wrapper.buffer.raw.readall().decode('utf-8')
+
+
+def _removeBOM(source):
+ """Remove any Byte-order-Mark bytes from the beginning of a file."""
+ bom = codecs.BOM_UTF8
+ bom = bom.decode('utf-8')
+ if source.startswith(bom):
+ return source[len(bom):]
+ return source
+
+
def main(argv):
"""Main program.
@@ -83,7 +98,7 @@ def main(argv):
# user will need to hit 'Ctrl-D' more than once if they're inputting
# the program by hand. 'raw_input' throws an EOFError exception if
# 'Ctrl-D' is pressed, which makes it easy to bail out of this loop.
- original_source.append(py3compat.raw_input())
+ original_source.append(_raw_input())
except EOFError:
break
except KeyboardInterrupt:
@@ -93,7 +108,7 @@ def main(argv):
style_config = file_resources.GetDefaultStyleForDir(os.getcwd())
source = [line.rstrip() for line in original_source]
- source[0] = py3compat.removeBOM(source[0])
+ source[0] = _removeBOM(source[0])
try:
reformatted_source, _ = yapf_api.FormatCode(
diff --git a/yapf/yapflib/py3compat.py b/yapf/yapflib/py3compat.py
deleted file mode 100644
index c95d4b5..0000000
--- a/yapf/yapflib/py3compat.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright 2015 Google Inc. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Utilities for Python2 / Python3 compatibility."""
-
-import codecs
-import io
-import sys
-
-PY38 = sys.version_info[0] >= 3 and sys.version_info[1] >= 8
-
-
-def raw_input():
- wrapper = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
- return wrapper.buffer.raw.readall().decode('utf-8')
-
-
-def removeBOM(source):
- """Remove any Byte-order-Mark bytes from the beginning of a file."""
- bom = codecs.BOM_UTF8
- bom = bom.decode('utf-8')
- if source.startswith(bom):
- return source[len(bom):]
- return source
|
google/yapf
|
a22db8379510f2a344a1b509e3819f3c6cad0de1
|
diff --git a/yapftests/main_test.py b/yapftests/main_test.py
index 5b73476..7241a02 100644
--- a/yapftests/main_test.py
+++ b/yapftests/main_test.py
@@ -20,8 +20,6 @@ import sys
import unittest
import yapf
-from yapf.yapflib import py3compat
-
from yapftests import yapf_test_helper
@@ -79,11 +77,11 @@ def patched_input(code):
return next(lines)
try:
- orig_raw_import = yapf.py3compat.raw_input
- yapf.py3compat.raw_input = patch_raw_input
+ orig_raw_import = yapf._raw_input
+ yapf._raw_input = patch_raw_input
yield
finally:
- yapf.py3compat.raw_input = orig_raw_import
+ yapf._raw_input = orig_raw_import
class RunMainTest(yapf_test_helper.YAPFTest):
diff --git a/yapftests/reformatter_basic_test.py b/yapftests/reformatter_basic_test.py
index a8b2fdd..2edbc31 100644
--- a/yapftests/reformatter_basic_test.py
+++ b/yapftests/reformatter_basic_test.py
@@ -13,15 +13,17 @@
# limitations under the License.
"""Basic tests for yapf.reformatter."""
+import sys
import textwrap
import unittest
-from yapf.yapflib import py3compat
from yapf.yapflib import reformatter
from yapf.yapflib import style
from yapftests import yapf_test_helper
+PY38 = sys.version_info[0] >= 3 and sys.version_info[1] >= 8
+
class BasicReformatterTest(yapf_test_helper.YAPFTest):
@@ -3162,7 +3164,7 @@ my_dict = {
finally:
style.SetGlobalStyle(style.CreateYapfStyle())
- @unittest.skipUnless(py3compat.PY38, 'Requires Python 3.8')
+ @unittest.skipUnless(PY38, 'Requires Python 3.8')
def testWalrus(self):
unformatted_code = textwrap.dedent("""\
if (x := len([1]*1000)>100):
|
Resolve duplicate pre-commit files?
Hi!
There are two pre-commit files in here that have identical copies as both `.yaml` and `.yml`:
```console
# ls -l .pre-commit-* | sed "s,${USER},user,g"
-rw-r--r-- 1 user user 803 Apr 19 00:29 .pre-commit-config.yaml
-rw-r--r-- 1 user user 803 Apr 19 00:29 .pre-commit-config.yml
-rw-r--r-- 1 user user 239 Apr 19 00:29 .pre-commit-hooks.yaml
-rw-r--r-- 1 user user 239 Apr 19 00:29 .pre-commit-hooks.yml
# diff -u .pre-commit-config.y{a,}ml && echo identical
identical
# diff -u .pre-commit-hooks.y{a,}ml && echo identical
identical
```
Is there a reason we need both of these still today? Also, does anyone know what it was that got us into this duplication back then?
Thanks and best, Sebastian
|
0.0
|
a22db8379510f2a344a1b509e3819f3c6cad0de1
|
[
"yapftests/main_test.py::MainTest::testEchoBadInput",
"yapftests/main_test.py::MainTest::testEchoInput",
"yapftests/main_test.py::MainTest::testEchoInputWithStyle"
] |
[
"yapftests/main_test.py::RunMainTest::testShouldHandleYapfError",
"yapftests/main_test.py::MainTest::testHelp",
"yapftests/main_test.py::MainTest::testNoPythonFilesMatched",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testArgsAndKwargsFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBinaryOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeClassDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeModuleDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesAtEndOfFile",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeFunctionsNotInColumnZero",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBetweenTopLevelImportsAndVariables",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketsInlinedInCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCoalesceBracketsOnDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBeforeFuncDef",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBetweenDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentColumnLimitOverflow",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithTrailingSpaces",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComprehensionForAndIf",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContiguousList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkerAfterStringWithContinuation",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationSpaceRetention",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDedentClosingBracketsWithTypeAnnotationExceedingLineLength",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictSetGenerator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryElementsOnOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryMakerFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryOnOwnLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryValuesOnOwnLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDisableEndingCommaHeuristic",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstrings",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontAddBlankLineAfterMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontSplitKeywordValueArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEllipses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEmptyContainers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingWhitespaceAfterSimpleStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessCharacters",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessLineCountWithDefaultKeywords",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExpressionPenalties",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testForceMultilineDict_False",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testForceMultilineDict_True",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFormattingListComprehensions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallContinuationLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInNestedDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18n",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nNonFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfConditionalParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfExpressionWithFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testImportAsList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentBlankLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInTuple",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsWithTypeAnnotationExceedingLineLength",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineDepthOfSingleLineStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineWrapInForExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehension",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferNoBreakForTrivialExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLineOverArithmeticSplit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferThreeLinesForLineWrap",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListWithFunctionCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMatchingParenSplittingMatching",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineCommentReformatted",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDictionaryKeys",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineLambdas",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineShebang",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleDictionariesInList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleUgliness",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNamedAssignNotAtEndOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedListsInDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoBreakOutsideOfBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoKeywordArgumentBreakage",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoPenaltySplitting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoQueueSeletionInMiddleOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpaceBetweenUnaryOpAndOpeningParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesAroundKeywordDefaultValues",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenOpeningBracketAndStartingOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenSubscriptsAndCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingAroundCompOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingAroundTermOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingBeforeEndingSubscriptBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingOnSingleArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWhenBinPacking",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWithinSubscriptList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotInParams",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotSplittingAfterSubscript",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOpeningAndClosingBrackets",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOverColumnLimit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testPseudoParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelativeImportStatements",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelaxArraySubscriptAffinity",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleFunctionsWithTrailingComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineCode",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineWithComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineFunctions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceAfterNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceBetweenStringAndParentheses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitAfterComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithInterspersedComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithTerminatingComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitStringsIfSurroundedByParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingAllArgs",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArgumentsTerminatedByComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArraysSensibly",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnCompoundStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionDefinition",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstElementListArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingOneArgumentList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingTopLevelAllArgs",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableInlinedDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSubscriptExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSubscriptExpressionTerminatedByComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailerOnSingleLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailingCommaAndBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCohesion",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCommaBeforeLastParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryOpInDictionaryValue",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnbreakableNot",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnformattedAfterMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testWalrus"
] |
{
"failed_lite_validators": [
"has_removed_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-05-02 20:36:57+00:00
|
apache-2.0
| 2,602 |
|
google__yapf-1173
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d8127cf..ca880fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,8 @@
### Fixed
- Fix SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED for one-item named argument lists
by taking precedence over SPLIT_BEFORE_NAMED_ASSIGNS.
+- Fix SPLIT_ALL_COMMA_SEPARATED_VALUES and SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES
+ being too agressive for lambdas and unpacking.
## [0.40.2] 2023-09-22
### Changes
diff --git a/yapf/pytree/subtype_assigner.py b/yapf/pytree/subtype_assigner.py
index 05d88b0..e3b3277 100644
--- a/yapf/pytree/subtype_assigner.py
+++ b/yapf/pytree/subtype_assigner.py
@@ -222,6 +222,11 @@ class _SubtypeAssigner(pytree_visitor.PyTreeVisitor):
if isinstance(child, pytree.Leaf) and child.value == '**':
_AppendTokenSubtype(child, subtypes.BINARY_OPERATOR)
+ def Visit_lambdef(self, node): # pylint: disable=invalid-name
+ # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
+ _AppendSubtypeRec(node, subtypes.LAMBDEF)
+ self.DefaultNodeVisit(node)
+
def Visit_trailer(self, node): # pylint: disable=invalid-name
for child in node.children:
self.Visit(child)
diff --git a/yapf/yapflib/format_decision_state.py b/yapf/yapflib/format_decision_state.py
index ce74313..06f3455 100644
--- a/yapf/yapflib/format_decision_state.py
+++ b/yapf/yapflib/format_decision_state.py
@@ -180,6 +180,10 @@ class FormatDecisionState(object):
return False
if style.Get('SPLIT_ALL_COMMA_SEPARATED_VALUES') and previous.value == ',':
+ if (subtypes.COMP_FOR in current.subtypes or
+ subtypes.LAMBDEF in current.subtypes):
+ return False
+
return True
if (style.Get('FORCE_MULTILINE_DICT') and
@@ -188,6 +192,11 @@ class FormatDecisionState(object):
if (style.Get('SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES') and
previous.value == ','):
+
+ if (subtypes.COMP_FOR in current.subtypes or
+ subtypes.LAMBDEF in current.subtypes):
+ return False
+
# Avoid breaking in a container that fits in the current line if possible
opening = _GetOpeningBracket(current)
diff --git a/yapf/yapflib/subtypes.py b/yapf/yapflib/subtypes.py
index b4b7efe..3c234fb 100644
--- a/yapf/yapflib/subtypes.py
+++ b/yapf/yapflib/subtypes.py
@@ -38,3 +38,4 @@ TYPED_NAME_ARG_LIST = 21
SIMPLE_EXPRESSION = 22
PARAMETER_START = 23
PARAMETER_STOP = 24
+LAMBDEF = 25
|
google/yapf
|
c1d7a213f83ac09e6ddedf9d07277b08d9a26880
|
diff --git a/yapftests/reformatter_basic_test.py b/yapftests/reformatter_basic_test.py
index 24f34a6..d58343e 100644
--- a/yapftests/reformatter_basic_test.py
+++ b/yapftests/reformatter_basic_test.py
@@ -91,6 +91,30 @@ class BasicReformatterTest(yapf_test_helper.YAPFTest):
""")
llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
+ unformatted_code = textwrap.dedent("""\
+ values = [ lambda arg1, arg2: arg1 + arg2 ]
+ """) # noqa
+ expected_formatted_code = textwrap.dedent("""\
+ values = [
+ lambda arg1, arg2: arg1 + arg2
+ ]
+ """)
+ llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
+ self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
+ unformatted_code = textwrap.dedent("""\
+ values = [
+ (some_arg1, some_arg2) for some_arg1, some_arg2 in values
+ ]
+ """) # noqa
+ expected_formatted_code = textwrap.dedent("""\
+ values = [
+ (some_arg1,
+ some_arg2)
+ for some_arg1, some_arg2 in values
+ ]
+ """)
+ llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
+ self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
# There is a test for split_all_top_level_comma_separated_values, with
# different expected value
unformatted_code = textwrap.dedent("""\
@@ -161,6 +185,32 @@ class BasicReformatterTest(yapf_test_helper.YAPFTest):
""")
llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
+ # Works the same way as split_all_comma_separated_values
+ unformatted_code = textwrap.dedent("""\
+ values = [ lambda arg1, arg2: arg1 + arg2 ]
+ """) # noqa
+ expected_formatted_code = textwrap.dedent("""\
+ values = [
+ lambda arg1, arg2: arg1 + arg2
+ ]
+ """)
+ llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
+ self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
+ # There is a test for split_all_comma_separated_values, with different
+ # expected value
+ unformatted_code = textwrap.dedent("""\
+ values = [
+ (some_arg1, some_arg2) for some_arg1, some_arg2 in values
+ ]
+ """) # noqa
+ expected_formatted_code = textwrap.dedent("""\
+ values = [
+ (some_arg1, some_arg2)
+ for some_arg1, some_arg2 in values
+ ]
+ """)
+ llines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
+ self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(llines))
# There is a test for split_all_comma_separated_values, with different
# expected value
unformatted_code = textwrap.dedent("""\
|
`SPLIT_ALL[_TOP_LEVEL]_COMMA_SEPARATED_VALUES` breaks on tuple unpacking
```python
values = [
('a', '1'),
('b', '2'),
]
values = [
really_quite_long_function(some_quite_long_arg, value)
for some_quite_long_arg, value in values
]
```
with `SPLIT_ALL_COMMA_SEPARATED_VALUES` enabled being reformatted to
```python
values = [
('a',
'1'),
('b',
'2'),
]
values = [
really_quite_long_function(some_quite_long_arg,
value) for some_quite_long_arg,
value in values
]
```
and with `SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES` enabled being reformatted to
```python
values = [
('a', '1'),
('b', '2'),
]
values = [
really_quite_long_function(some_quite_long_arg, value)
for some_quite_long_arg,
value in values
]
```
while replacing
```python
for some_quite_long_arg, value in values
```
with
```python
for (some_quite_long_arg, value) in values
```
yields to a different result.
Is this an intended behavior?
|
0.0
|
c1d7a213f83ac09e6ddedf9d07277b08d9a26880
|
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingAllArgs",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingTopLevelAllArgs"
] |
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testArgsAndKwargsFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBinaryOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeClassDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeModuleDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesAtEndOfFile",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeFunctionsNotInColumnZero",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBetweenTopLevelImportsAndVariables",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketsInlinedInCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCoalesceBracketsOnDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBeforeFuncDef",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBetweenDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentColumnLimitOverflow",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithTrailingSpaces",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComprehensionForAndIf",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContiguousList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkerAfterStringWithContinuation",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationSpaceRetention",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDedentClosingBracketsWithTypeAnnotationExceedingLineLength",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictSetGenerator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryElementsOnOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryMakerFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryOnOwnLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryValuesOnOwnLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDisableEndingCommaHeuristic",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstrings",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontAddBlankLineAfterMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontSplitKeywordValueArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEllipses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEmptyContainers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingWhitespaceAfterSimpleStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessCharacters",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessLineCountWithDefaultKeywords",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExpressionPenalties",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testForceMultilineDict_False",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testForceMultilineDict_True",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFormattingListComprehensions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallContinuationLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInNestedDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18n",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nNonFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfConditionalParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfExpressionWithFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testImportAsList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentBlankLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInTuple",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsWithTypeAnnotationExceedingLineLength",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineDepthOfSingleLineStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineWrapInForExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehension",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferNoBreakForTrivialExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLineOverArithmeticSplit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferThreeLinesForLineWrap",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListWithFunctionCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMatchingParenSplittingMatching",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineCommentReformatted",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDictionaryKeys",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineLambdas",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineShebang",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleDictionariesInList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleUgliness",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNamedAssignNotAtEndOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedListsInDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoBreakOutsideOfBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoKeywordArgumentBreakage",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoPenaltySplitting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoQueueSeletionInMiddleOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpaceBetweenUnaryOpAndOpeningParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesAroundKeywordDefaultValues",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenOpeningBracketAndStartingOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenSubscriptsAndCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingAroundCompOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingAroundTermOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingBeforeEndingSubscriptBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingOnSingleArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWhenBinPacking",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWithinSubscriptList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotInParams",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotSplittingAfterSubscript",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOpeningAndClosingBrackets",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOverColumnLimit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testParenthesizedContextManagers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testPseudoParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelativeImportStatements",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelaxArraySubscriptAffinity",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleFunctionsWithTrailingComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineCode",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineWithComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineFunctions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceAfterNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceBetweenStringAndParentheses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitAfterComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithInterspersedComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithTerminatingComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitStringsIfSurroundedByParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArgumentsTerminatedByComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArraysSensibly",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnCompoundStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionDefinition",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstElementListArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingOneArgumentList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableInlinedDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStructuredPatternMatching",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSubscriptExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSubscriptExpressionTerminatedByComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailerOnSingleLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailingCommaAndBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCohesion",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCommaBeforeLastParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryOpInDictionaryValue",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnbreakableNot",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnformattedAfterMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testWalrus"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-14 06:47:48+00:00
|
apache-2.0
| 2,603 |
|
google__yapf-286
|
diff --git a/CHANGELOG b/CHANGELOG
index d331f8d..bb3ffdc 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -8,6 +8,11 @@
- It's okay to split in the middle of a dotted name if the whole expression is
going to go over the column limit.
+### Changed
+- Issue #228: Return exit code 0 on success, regardless of whether files were
+ changed. (Previously, 0 meant success with no files
+ modified, and 2 meant success with at least one file modified.)
+
## [0.11.0] 2016-07-17
### Added
- The COALESCE_BRACKETS knob prevents splitting consecutive brackets when
diff --git a/yapf/__init__.py b/yapf/__init__.py
index dfbb8ee..145d8f4 100644
--- a/yapf/__init__.py
+++ b/yapf/__init__.py
@@ -161,7 +161,7 @@ def main(argv):
lines=lines,
verify=args.verify)
sys.stdout.write(reformatted_source)
- return 2 if changed else 0
+ return 0
files = file_resources.GetCommandLineFiles(args.files, args.recursive,
args.exclude)
@@ -175,7 +175,7 @@ def main(argv):
in_place=args.in_place,
print_diff=args.diff,
verify=args.verify)
- return 2 if changed else 0
+ return 0
def FormatFiles(filenames,
|
google/yapf
|
b8d20bd2d9d69fda6c1b102c0c07f97931e87132
|
diff --git a/yapftests/main_test.py b/yapftests/main_test.py
index e5a5a74..42e6f9b 100644
--- a/yapftests/main_test.py
+++ b/yapftests/main_test.py
@@ -91,7 +91,7 @@ class MainTest(unittest.TestCase):
with patched_input(code):
with captured_output() as (out, err):
ret = yapf.main(['-', '--style=chromium'])
- self.assertEqual(ret, 2)
+ self.assertEqual(ret, 0)
self.assertEqual(out.getvalue(), chromium_code)
def testEchoBadInput(self):
@@ -116,3 +116,4 @@ class MainTest(unittest.TestCase):
self.assertEqual(ret, 0)
version = 'yapf {}\n'.format(yapf.__version__)
self.assertEqual(version, out.getvalue())
+
|
yapf returns an exit code of 2 on unformatted but valid input.
Hello there and thanks for developing this much appreciated python formatter.
I’m opening this issue as I’m not sure to understand the logic behind yapf's exit code return when applying it on unformatted and valid input. Indeed, yapf returns an exit code of 2 in such case (which implies something went wrong), yet a valid formatted output is returned. I would consider the operation successful, hence expect an exit code of 0.
Consequently, this behavior tends to break scripts where flow execution rely on the format's success.
I saw a related issue: https://github.com/google/yapf/issues/186 but I don't see the need to inform output has been modified compared to input (i.e. formatted) by returning a status code other than 0 as formatting is the purpose of the tool. Otherwise, _--diff_ option seems the right fit if this information is needed (not to mention UNIX tools can also answer this).
Am I missing something or is this behavior indeed odd? Thanks!
|
0.0
|
b8d20bd2d9d69fda6c1b102c0c07f97931e87132
|
[
"yapftests/main_test.py::MainTest::testEchoInputWithStyle"
] |
[
"yapftests/main_test.py::RunMainTest::testShouldHandleYapfError",
"yapftests/main_test.py::MainTest::testEchoBadInput",
"yapftests/main_test.py::MainTest::testEchoInput",
"yapftests/main_test.py::MainTest::testHelp",
"yapftests/main_test.py::MainTest::testNoPythonFilesMatched",
"yapftests/main_test.py::MainTest::testVersion"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-07-28 04:51:31+00:00
|
apache-2.0
| 2,604 |
|
google__yapf-438
|
diff --git a/CHANGELOG b/CHANGELOG
index 270d30c..e90c25b 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -5,6 +5,8 @@
## [0.17.1] UNRELEASED
### Fixed
- Allow semicolons if the line is disabled.
+- Fix issue where subsequent comments at decreasing levels of indentation
+ were improperly aligned and/or caused output with invalid syntax.
## [0.17.0] 2017-08-20
### Added
diff --git a/plugins/README.rst b/plugins/README.rst
index b6a3e0c..56d3217 100644
--- a/plugins/README.rst
+++ b/plugins/README.rst
@@ -40,7 +40,23 @@ The plugin can be easily installed by using *Sublime Package Control*.
Check the project page of the plugin for more information:
https://github.com/jason-kane/PyYapf
+===================
+git Pre-Commit Hook
+===================
+The ``git`` pre-commit hook automatically formats your Python files before they
+are committed to your local repository. Any changes ``yapf`` makes to the files
+will stay unstaged so that you can diff them manually.
+
+To install, simply download the raw file and copy it into your git hooks directory:
+
+.. code-block:: bash
+
+ # From the root of your git project.
+ curl -o https://raw.githubusercontent.com/google/yapf/master/plugins/pre-commit.sh
+ mv pre-commit.sh .git/hooks/pre-commit
+
+==========
Textmate 2
==========
diff --git a/plugins/pre-commit.sh b/plugins/pre-commit.sh
new file mode 100644
index 0000000..24976b5
--- /dev/null
+++ b/plugins/pre-commit.sh
@@ -0,0 +1,58 @@
+#!/bin/bash
+
+# Git pre-commit hook to check staged Python files for formatting issues with yapf.
+#
+# INSTALLING: Copy this script into `.git/hooks/pre-commit`, and mark it as executable.
+#
+# This requires that yapf is installed and runnable in the environment running the pre-commit hook.
+#
+# When running, this first checks for unstaged changes to staged files, and if there are any, it
+# will exit with an error. Files with unstaged changes will be printed.
+#
+# If all staged files have no unstaged changes, it will run yapf against them, leaving the
+# formatting changes unstaged. Changed files will be printed.
+#
+# BUGS: This does not leave staged changes alone when used with the -a flag to git commit, due to
+# the fact that git stages ALL unstaged files when that flag is used.
+
+# Find all staged Python files, and exit early if there aren't any.
+PYTHON_FILES=(`git diff --name-only --cached --diff-filter=AM | grep --color=never '.py$'`)
+if [ ! "$PYTHON_FILES" ]; then
+ exit 0
+fi
+
+# Verify that yapf is installed; if not, warn and exit.
+if [ -z $(which yapf) ]; then
+ echo 'yapf not on path; can not format. Please install yapf:'
+ echo ' pip install yapf'
+ exit 2
+fi
+
+# Check for unstaged changes to files in the index.
+CHANGED_FILES=(`git diff --name-only ${PYTHON_FILES[@]}`)
+if [ "$CHANGED_FILES" ]; then
+ echo 'You have unstaged changes to some files in your commit; skipping auto-format.'
+ echo 'Please stage, stash, or revert these changes.'
+ echo 'You may find `git stash -k` helpful here.'
+ echo
+ echo 'Files with unstaged changes:'
+ for file in ${CHANGED_FILES[@]}; do
+ echo " $file"
+ done
+ exit 1
+fi
+# Format all staged files, then exit with an error code if any have uncommitted changes.
+echo 'Formatting staged Python files . . .'
+yapf -i -r ${PYTHON_FILES[@]}
+CHANGED_FILES=(`git diff --name-only ${PYTHON_FILES[@]}`)
+if [ "$CHANGED_FILES" ]; then
+ echo 'Some staged files were reformatted. Please review the changes and stage them.'
+ echo
+ echo 'Files updated:'
+ for file in ${CHANGED_FILES[@]}; do
+ echo " $file"
+ done
+ exit 1
+else
+ exit 0
+fi
diff --git a/yapf/yapflib/comment_splicer.py b/yapf/yapflib/comment_splicer.py
index 7c79e80..32997b7 100644
--- a/yapf/yapflib/comment_splicer.py
+++ b/yapf/yapflib/comment_splicer.py
@@ -71,8 +71,7 @@ def SpliceComments(tree):
# We can't just insert it before the NEWLINE node, because as a
# result of the way pytrees are organized, this node can be under
# an inappropriate parent.
- comment_column -= len(comment_prefix)
- comment_column += len(comment_prefix) - len(comment_prefix.lstrip())
+ comment_column -= len(comment_prefix.lstrip())
pytree_utils.InsertNodesAfter(
_CreateCommentsFromPrefix(
comment_prefix,
@@ -83,63 +82,53 @@ def SpliceComments(tree):
# Comment prefixes on DEDENT nodes also deserve special treatment,
# because their final placement depends on their prefix.
# We'll look for an ancestor of this child with a matching
- # indentation, and insert the comment after it.
- ancestor_at_indent = _FindAncestorAtIndent(child, prefix_indent)
- if ancestor_at_indent.type == token.DEDENT:
- comments = comment_prefix.split('\n')
-
- # lib2to3 places comments that should be separated into the same
- # DEDENT node. For example, "comment 1" and "comment 2" will be
- # combined.
- #
- # def _():
- # for x in y:
- # pass
- # # comment 1
- #
- # # comment 2
- # pass
- #
- # In this case, we need to split them up ourselves.
- before = []
- after = []
- after_lineno = comment_lineno
-
- index = 0
- while index < len(comments):
- cmt = comments[index]
- if not cmt.strip() or cmt.startswith(prefix_indent + '#'):
- before.append(cmt)
- else:
- after_lineno += index
- after.extend(comments[index:])
- break
- index += 1
-
- # Special case where the comment is inserted in the same
- # indentation level as the DEDENT it was originally attached to.
- pytree_utils.InsertNodesBefore(
- _CreateCommentsFromPrefix(
- '\n'.join(before) + '\n',
- comment_lineno,
- comment_column,
- standalone=True), ancestor_at_indent)
- if after:
- after_column = len(after[0]) - len(after[0].lstrip())
- comment_column -= comment_column - after_column
- pytree_utils.InsertNodesAfter(
- _CreateCommentsFromPrefix(
- '\n'.join(after) + '\n',
- after_lineno,
- comment_column,
- standalone=True), _FindNextAncestor(ancestor_at_indent))
- else:
- pytree_utils.InsertNodesAfter(
+ # indentation, and insert the comment before it if the ancestor is
+ # on a DEDENT node and after it otherwise.
+ #
+ # lib2to3 places comments that should be separated into the same
+ # DEDENT node. For example, "comment 1" and "comment 2" will be
+ # combined.
+ #
+ # def _():
+ # for x in y:
+ # pass
+ # # comment 1
+ #
+ # # comment 2
+ # pass
+ #
+ # In this case, we need to split them up ourselves.
+
+ # Split into groups of comments at decreasing levels of indentation
+ comment_groups = []
+ comment_column = None
+ for cmt in comment_prefix.split('\n'):
+ col = cmt.find('#')
+ if col < 0:
+ if comment_column is None:
+ # Skip empty lines at the top of the first comment group
+ comment_lineno += 1
+ continue
+ elif comment_column is None or col < comment_column:
+ comment_column = col
+ comment_indent = cmt[:comment_column]
+ comment_groups.append((comment_column, comment_indent, []))
+ comment_groups[-1][-1].append(cmt)
+
+ # Insert a node for each group
+ for comment_column, comment_indent, comment_group in comment_groups:
+ ancestor_at_indent = _FindAncestorAtIndent(child, comment_indent)
+ if ancestor_at_indent.type == token.DEDENT:
+ InsertNodes = pytree_utils.InsertNodesBefore
+ else:
+ InsertNodes = pytree_utils.InsertNodesAfter
+ InsertNodes(
_CreateCommentsFromPrefix(
- comment_prefix,
+ '\n'.join(comment_group) + '\n',
comment_lineno,
comment_column,
standalone=True), ancestor_at_indent)
+ comment_lineno += len(comment_group)
else:
# Otherwise there are two cases.
#
@@ -337,16 +326,6 @@ def _FindAncestorAtIndent(node, indent):
return _FindAncestorAtIndent(node.parent, indent)
-def _FindNextAncestor(node):
- if node.parent is None:
- return node
-
- if node.parent.next_sibling is not None:
- return node.parent.next_sibling
-
- return _FindNextAncestor(node.parent)
-
-
def _AnnotateIndents(tree):
"""Annotate the tree with child_indent annotations.
|
google/yapf
|
8012f595c04e2c9b213ce4fec461644d1f1c81f6
|
diff --git a/yapftests/comment_splicer_test.py b/yapftests/comment_splicer_test.py
index ee0527e..5abe450 100644
--- a/yapftests/comment_splicer_test.py
+++ b/yapftests/comment_splicer_test.py
@@ -206,6 +206,33 @@ class CommentSplicerTest(unittest.TestCase):
self._AssertNodeIsComment(if_suite.children[-2])
self._AssertNodeType('DEDENT', if_suite.children[-1])
+ def testCommentBeforeDedentThreeLevel(self):
+ code = textwrap.dedent(r'''
+ if foo:
+ if bar:
+ z = 1
+ # comment 2
+ # comment 1
+ # comment 0
+ j = 2
+ ''')
+ tree = pytree_utils.ParseCodeToTree(code)
+ comment_splicer.SpliceComments(tree)
+
+ # comment 0 should go under the tree root
+ self._AssertNodeIsComment(tree.children[1], '# comment 0')
+
+ # comment 1 is in the first if_suite, right before the DEDENT
+ if_suite_1 = self._FindNthChildNamed(tree, 'suite', n=1)
+ self._AssertNodeIsComment(if_suite_1.children[-2], '# comment 1')
+ self._AssertNodeType('DEDENT', if_suite_1.children[-1])
+
+ # comment 2 is in if_suite nested under the first if suite,
+ # right before the DEDENT
+ if_suite_2 = self._FindNthChildNamed(tree, 'suite', n=2)
+ self._AssertNodeIsComment(if_suite_2.children[-2], '# comment 2')
+ self._AssertNodeType('DEDENT', if_suite_2.children[-1])
+
def testCommentsInClass(self):
code = textwrap.dedent(r'''
class Foo:
diff --git a/yapftests/reformatter_buganizer_test.py b/yapftests/reformatter_buganizer_test.py
index 2d0cf9f..996a0a3 100644
--- a/yapftests/reformatter_buganizer_test.py
+++ b/yapftests/reformatter_buganizer_test.py
@@ -501,6 +501,18 @@ class BuganizerFixes(yapf_test_helper.YAPFTest):
uwlines = yapf_test_helper.ParseAndUnwrap(code)
self.assertCodeEqual(code, reformatter.Reformat(uwlines))
+ def testB30087363(self):
+ code = textwrap.dedent("""\
+ if False:
+ bar()
+ # This is a comment
+ # This is another comment
+ elif True:
+ foo()
+ """)
+ uwlines = yapf_test_helper.ParseAndUnwrap(code)
+ self.assertCodeEqual(code, reformatter.Reformat(uwlines))
+
def testB29093579(self):
unformatted_code = textwrap.dedent("""\
def _():
|
mistaken added indentation to comment when previous block ended in a comment
The specific issue is the final change, adding a level of indentation of the comment "attached" to the return statement, presumably because the previous block ended with a comment. While this is flipping where the comment was attached (eg: end of block, then before block), I think that it's worth preserving the original location of that final comment because of the explicit newline, outdent, code at outdent pattern.
``` diff
except Exception as ex:
self.logger.exception(
"Caught exception while fetching livehoststatus. "
- "Falling back to old API: %s",
- ex
+ "Falling back to old API: %s", ex
)
# @todo dpittman 2015-09-25: I feel like this is way too broad a
# catch statement for the failure mode assumption, but it matches
# the original. We should probably fix that.
- # ...guess we try the old fashioned way.
+ # ...guess we try the old fashioned way.
return self.get_bad_hosts_with_live_maint_status(maint, stage)
def get_bad_hosts_with_live_host_status(self, maint, stage):
```
|
0.0
|
8012f595c04e2c9b213ce4fec461644d1f1c81f6
|
[
"yapftests/comment_splicer_test.py::CommentSplicerTest::testCommentBeforeDedentThreeLevel",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30087363"
] |
[
"yapftests/comment_splicer_test.py::CommentSplicerTest::testCommentBeforeDedent",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testCommentBeforeDedentTwoLevel",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testCommentBeforeDedentTwoLevelImproperlyIndented",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testCommentIsFirstChildInCompound",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testCommentIsLastChildInCompound",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testCommentsInClass",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testCommentsOnDedents",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testExprComments",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testInlineAfterSeparateLine",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testMultipleBlockComments",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testMultipleCommentsInOneExpr",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testSeparateLineAfterInline",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testSimpleInline",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testSimpleSeparateLine",
"yapftests/comment_splicer_test.py::CommentSplicerTest::testTwoLineComment",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB13900309",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB14406499",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB14468247",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB15438132",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB15542157",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB15597568",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB15697268",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB15884241",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB16572361",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB16783631",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB17011869",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB17133019",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB17489866",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB17534869",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB18255697",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB18256666",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB18256826",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB18257115",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19073499",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19194420",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19287512",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19353268",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19372573",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19377034",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19547210",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19626808",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20016122",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20073838",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20127686",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20128830",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20551180",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20559654",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20562732",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20605036",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20813997",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20849933",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB22527411",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB23445244",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB23935890",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB23943842",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB23944849",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25131481",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25136704",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25136820",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25157123",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25165602",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25324261",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25505359",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB26034238",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB26382315",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB26868213",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB27266946",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB27590179",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB27616132",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB28414371",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB29093579",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB29908765",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30087362",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30173198",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30442148",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30536435",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30760569",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB31063453",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB31847238",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB31911533",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB31937033",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB32570937",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB32714745",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB32737279",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB32931780",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB33047408",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB33842726",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB34682902",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB35021894",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB35212469",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB36215507",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB36806207",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB37460004"
] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-08-03 20:15:32+00:00
|
apache-2.0
| 2,605 |
|
google__yapf-441
|
diff --git a/CHANGELOG b/CHANGELOG
index d7a465c..b05a6f4 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -13,6 +13,7 @@
- Corrected how `DEDENT_CLOSING_BRACKETS` and `COALESCE_BRACKETS` interacted.
- Fix return value to return a boolean.
- Correct vim plugin not to clobber edited code if yapf returns an error.
+- Ensured comma-terminated tuples with multiple elements are split onto separate lines.
## [0.16.3] 2017-07-13
### Changed
diff --git a/yapf/yapflib/pytree_unwrapper.py b/yapf/yapflib/pytree_unwrapper.py
index c67c1c6..8dbbfe0 100644
--- a/yapf/yapflib/pytree_unwrapper.py
+++ b/yapf/yapflib/pytree_unwrapper.py
@@ -258,8 +258,7 @@ class PyTreeUnwrapper(pytree_visitor.PyTreeVisitor):
self.DefaultNodeVisit(node)
def Visit_testlist_gexp(self, node): # pylint: disable=invalid-name
- if _ContainsComments(node):
- _DetermineMustSplitAnnotation(node)
+ _DetermineMustSplitAnnotation(node)
self.DefaultNodeVisit(node)
def Visit_arglist(self, node): # pylint: disable=invalid-name
@@ -336,6 +335,11 @@ def _AdjustSplitPenalty(uwline):
def _DetermineMustSplitAnnotation(node):
"""Enforce a split in the list if the list ends with a comma."""
if not _ContainsComments(node):
+ token = next(node.parent.leaves())
+ if token.value == '(':
+ if sum(1 for ch in node.children
+ if pytree_utils.NodeName(ch) == 'COMMA') < 2:
+ return
if (not isinstance(node.children[-1], pytree.Leaf) or
node.children[-1].value != ','):
return
|
google/yapf
|
2e7952b348f6444f7a9d781f96bf0e8cdfea7895
|
diff --git a/yapftests/reformatter_basic_test.py b/yapftests/reformatter_basic_test.py
index 0ce8da8..c205f47 100644
--- a/yapftests/reformatter_basic_test.py
+++ b/yapftests/reformatter_basic_test.py
@@ -459,10 +459,17 @@ class BasicReformatterTest(yapf_test_helper.YAPFTest):
def testOpeningAndClosingBrackets(self):
unformatted_code = textwrap.dedent("""\
+ foo( (1, ) )
+ foo( ( 1, 2, 3 ) )
foo( ( 1, 2, 3, ) )
""")
expected_formatted_code = textwrap.dedent("""\
- foo((1, 2, 3,))
+ foo((1,))
+ foo((1, 2, 3))
+ foo((
+ 1,
+ 2,
+ 3,))
""")
uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
diff --git a/yapftests/reformatter_facebook_test.py b/yapftests/reformatter_facebook_test.py
index 4706786..953d290 100644
--- a/yapftests/reformatter_facebook_test.py
+++ b/yapftests/reformatter_facebook_test.py
@@ -107,7 +107,7 @@ v, w, x, y, z
self.assertCodeEqual(code, reformatter.Reformat(uwlines))
def testDedentTestListGexp(self):
- code = textwrap.dedent("""\
+ unformatted_code = textwrap.dedent("""\
try:
pass
except (
@@ -122,8 +122,27 @@ v, w, x, y, z
) as exception:
pass
""")
- uwlines = yapf_test_helper.ParseAndUnwrap(code)
- self.assertCodeEqual(code, reformatter.Reformat(uwlines))
+ expected_formatted_code = textwrap.dedent("""\
+ try:
+ pass
+ except (
+ IOError, OSError, LookupError, RuntimeError, OverflowError
+ ) as exception:
+ pass
+
+ try:
+ pass
+ except (
+ IOError,
+ OSError,
+ LookupError,
+ RuntimeError,
+ OverflowError,
+ ) as exception:
+ pass
+ """)
+ uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
+ self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
def testBrokenIdempotency(self):
# TODO(ambv): The following behaviour should be fixed.
|
How to prevent YAPF from joining lines in dictionaries and lists?
YAPF converts
```
DJANGO_TEMPLATES_OPTIONS = {
"context_processors": []
}
```
to
```
DJANGO_TEMPLATES_OPTIONS = {"context_processors": []}
```
and I cannot find the option to disable such behavior.
Is it possible?
|
0.0
|
2e7952b348f6444f7a9d781f96bf0e8cdfea7895
|
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOpeningAndClosingBrackets",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testDedentTestListGexp"
] |
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testArgsAndKwargsFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBinaryOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeClassDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesAtEndOfFile",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeFunctionsNotInColumnZero",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketsInlinedInCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCoalesceBracketsOnDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBeforeFuncDef",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBetweenDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentColumnLimitOverflow",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithTrailingSpaces",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComprehensionForAndIf",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContiguousList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationSpaceRetention",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictSetGenerator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryElementsOnOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryMakerFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryOnOwnLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryValuesOnOwnLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstrings",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontAddBlankLineAfterMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontSplitKeywordValueArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEllipses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEmptyContainers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingWhitespaceAfterSimpleStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessCharacters",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessLineCountWithDefaultKeywords",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExpressionPenalties",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFormattingListComprehensions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallContinuationLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInNestedDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18n",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nNonFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfConditionalParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfExpressionWithFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testImportAsList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineDepthOfSingleLineStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineWrapInForExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehension",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListWithFunctionCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMatchingParenSplittingMatching",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineCommentReformatted",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDictionaryKeys",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineLambdas",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineShebang",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleUgliness",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNamedAssignNotAtEndOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedListsInDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoBreakOutsideOfBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoKeywordArgumentBreakage",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoPenaltySplitting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoQueueSeletionInMiddleOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpaceBetweenUnaryOpAndOpeningParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesAroundKeywordDefaultValues",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenOpeningBracketAndStartingOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenSubscriptsAndCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingAroundTermOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingBeforeEndingSubscriptBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingOnSingleArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWhenBinPacking",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWithinSubscriptList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotInParams",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotSplittingAfterSubscript",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOverColumnLimit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelativeImportStatements",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelaxArraySubscriptAffinity",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimple",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleFunctions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleFunctionsWithTrailingComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineCode",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineWithComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineFunctions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceAfterNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitAfterComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithInterspersedComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithTerminatingComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitStringsIfSurroundedByParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArgumentsTerminatedByComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArraysSensibly",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnCompoundStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionDefinition",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstElementListArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingOneArgumentList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableInlinedDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSubscriptExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailerOnSingleLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailingCommaAndBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCohesion",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCommaBeforeLastParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryOpInDictionaryValue",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnbreakableNot",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnformattedAfterMultilineString",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testBreakAfterOpeningBracketIfContentsTooBig",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testBrokenIdempotency",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testCommentWithNewlinesInPrefix",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testDedentClosingBracket",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testDedentClosingBracketWithComments",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testDedentIfConditional",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testDedentImportAsNames",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testDedentSet",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testDedentingCallsWithInnerLists",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testDedentingInnerScope",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testDedentingListComprehension",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testDedentingWithSubscripts",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testIfExprHangingIndent",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testMustSplitDedenting",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testNoNeedForLineBreaks",
"yapftests/reformatter_facebook_test.py::TestsForFacebookStyle::testSimpleDedenting"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-08-07 02:58:34+00:00
|
apache-2.0
| 2,606 |
|
google__yapf-485
|
diff --git a/yapf/yapflib/reformatter.py b/yapf/yapflib/reformatter.py
index 7ed7a62..299fef8 100644
--- a/yapf/yapflib/reformatter.py
+++ b/yapf/yapflib/reformatter.py
@@ -439,7 +439,7 @@ def _IsClassOrDef(uwline):
if uwline.first.value in {'class', 'def'}:
return True
- return (t.name for t in uwline.tokens[:2]) == ('async', 'def')
+ return [t.value for t in uwline.tokens[:2]] == ['async', 'def']
def _CalculateNumberOfNewlines(first_token, indent_depth, prev_uwline,
|
google/yapf
|
c67685c0f4bf04dc2d34f8d615fa256181913788
|
diff --git a/yapftests/reformatter_python3_test.py b/yapftests/reformatter_python3_test.py
index c6a3e99..6ed1bbb 100644
--- a/yapftests/reformatter_python3_test.py
+++ b/yapftests/reformatter_python3_test.py
@@ -209,6 +209,17 @@ class TestsForPython3Code(yapf_test_helper.YAPFTest):
uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
+ def testAsyncFunctionsNested(self):
+ if sys.version_info[1] < 5:
+ return
+ code = textwrap.dedent("""\
+ async def outer():
+ async def inner():
+ pass
+ """)
+ uwlines = yapf_test_helper.ParseAndUnwrap(code)
+ self.assertCodeEqual(code, reformatter.Reformat(uwlines))
+
def testKeepTypesIntact(self):
if sys.version_info[1] < 5:
return
|
Regression in formatting nested 'async def' functions
My style file has `blank_line_before_nested_class_or_def=False`.
Yapf 0.19.0 formats like:
```python
async def foo():
async def bar():
pass
```
Yapf 0.20.0 changes this to:
```python
async def foo():
async def bar():
pass
```
According to `git bisect`, this was introduced by 58e36945be8978deb7ab3ad3681f5feccb0405fc, which seems like it must be a bug, since that commit wasn't intended to change python 3 formatting at all.
|
0.0
|
c67685c0f4bf04dc2d34f8d615fa256181913788
|
[
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testAsyncFunctionsNested"
] |
[
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testAnnotations",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testAsyncFunctions",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testAsyncWithPrecedingComment",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testContinuationIndentWithAsync",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testExecAsNonKeyword",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testKeepTypesIntact",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testKeywordOnlyArgSpecifier",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testMatrixMultiplication",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testNoSpacesAroundPowerOparator",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testPEP448ParameterExpansion",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testSpacesAroundDefaultOrNamedAssign",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testSplittingArguments",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testTypeHint",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testTypedNames"
] |
{
"failed_lite_validators": [
"has_git_commit_hash"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-12-10 04:55:36+00:00
|
apache-2.0
| 2,607 |
|
google__yapf-542
|
diff --git a/CHANGELOG b/CHANGELOG
index 92806ad..e3cc518 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -2,6 +2,11 @@
# All notable changes to this project will be documented in this file.
# This project adheres to [Semantic Versioning](http://semver.org/).
+## Unreleased
+### Added
+- The `BLANK_LINE_BEFORE_MODULE_DOCSTRING` knob adds a blank line before a
+ module's docstring.
+
## [0.21.0] 2018-03-18
### Added
- Introduce a new option of formatting multiline literals. Add
diff --git a/README.rst b/README.rst
index 3b43d29..ccc74d9 100644
--- a/README.rst
+++ b/README.rst
@@ -322,6 +322,9 @@ Knobs
def method():
pass
+``BLANK_LINE_BEFORE_MODULE_DOCSTRING``
+ Insert a blank line before a module docstring.
+
``BLANK_LINE_BEFORE_CLASS_DOCSTRING``
Insert a blank line before a class-level docstring.
diff --git a/yapf/yapflib/reformatter.py b/yapf/yapflib/reformatter.py
index a4965ab..0485d7e 100644
--- a/yapf/yapflib/reformatter.py
+++ b/yapf/yapflib/reformatter.py
@@ -473,6 +473,10 @@ def _CalculateNumberOfNewlines(first_token, indent_depth, prev_uwline,
style.Get('BLANK_LINE_BEFORE_CLASS_DOCSTRING')):
# Enforce a blank line before a class's docstring.
return ONE_BLANK_LINE
+ elif (prev_uwline.first.value.startswith('#') and
+ style.Get('BLANK_LINE_BEFORE_MODULE_DOCSTRING')):
+ # Enforce a blank line before a module's docstring.
+ return ONE_BLANK_LINE
# The docstring shouldn't have a newline before it.
return NO_BLANK_LINES
diff --git a/yapf/yapflib/style.py b/yapf/yapflib/style.py
index 5f2fdac..7fd2177 100644
--- a/yapf/yapflib/style.py
+++ b/yapf/yapflib/style.py
@@ -71,6 +71,8 @@ _STYLE_HELP = dict(
..."""),
BLANK_LINE_BEFORE_CLASS_DOCSTRING=textwrap.dedent("""\
Insert a blank line before a class-level docstring."""),
+ BLANK_LINE_BEFORE_MODULE_DOCSTRING=textwrap.dedent("""\
+ Insert a blank line before a module docstring."""),
BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION=textwrap.dedent("""\
Number of blank lines surrounding top-level function and class
definitions."""),
@@ -261,6 +263,7 @@ def CreatePEP8Style():
ALLOW_SPLIT_BEFORE_DICT_VALUE=True,
BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF=False,
BLANK_LINE_BEFORE_CLASS_DOCSTRING=False,
+ BLANK_LINE_BEFORE_MODULE_DOCSTRING=False,
BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION=2,
COALESCE_BRACKETS=False,
COLUMN_LIMIT=79,
@@ -406,6 +409,7 @@ _STYLE_OPTION_VALUE_CONVERTER = dict(
ALLOW_SPLIT_BEFORE_DICT_VALUE=_BoolConverter,
BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF=_BoolConverter,
BLANK_LINE_BEFORE_CLASS_DOCSTRING=_BoolConverter,
+ BLANK_LINE_BEFORE_MODULE_DOCSTRING=_BoolConverter,
BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION=int,
COALESCE_BRACKETS=_BoolConverter,
COLUMN_LIMIT=int,
|
google/yapf
|
c873f37236c6fb962b6a181bae6a2f2cab23ba6a
|
diff --git a/yapftests/reformatter_basic_test.py b/yapftests/reformatter_basic_test.py
index a1ca779..01ed3d9 100644
--- a/yapftests/reformatter_basic_test.py
+++ b/yapftests/reformatter_basic_test.py
@@ -2218,6 +2218,59 @@ s = 'foo \\
finally:
style.SetGlobalStyle(style.CreateChromiumStyle())
+ def testBlankLineBeforeModuleDocstring(self):
+ unformatted_code = textwrap.dedent('''\
+ #!/usr/bin/env python
+ # -*- coding: utf-8 name> -*-
+
+ """Some module docstring."""
+
+
+ def foobar():
+ pass
+ ''')
+ expected_code = textwrap.dedent('''\
+ #!/usr/bin/env python
+ # -*- coding: utf-8 name> -*-
+ """Some module docstring."""
+
+
+ def foobar():
+ pass
+ ''')
+ uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
+ self.assertEqual(expected_code, reformatter.Reformat(uwlines))
+
+ try:
+ style.SetGlobalStyle(
+ style.CreateStyleFromConfig(
+ '{based_on_style: pep8, '
+ 'blank_line_before_module_docstring: True}'))
+ unformatted_code = textwrap.dedent('''\
+ #!/usr/bin/env python
+ # -*- coding: utf-8 name> -*-
+ """Some module docstring."""
+
+
+ def foobar():
+ pass
+ ''')
+ expected_formatted_code = textwrap.dedent('''\
+ #!/usr/bin/env python
+ # -*- coding: utf-8 name> -*-
+
+ """Some module docstring."""
+
+
+ def foobar():
+ pass
+ ''')
+ uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
+ self.assertCodeEqual(expected_formatted_code,
+ reformatter.Reformat(uwlines))
+ finally:
+ style.SetGlobalStyle(style.CreateChromiumStyle())
+
def testTupleCohesion(self):
unformatted_code = textwrap.dedent("""\
def f():
|
Space between modeline/shebang and module docstring
Imagine this file:
``` python
#!/usr/bin/env python
# -*- coding: utf-8 name> -*-
"""Some module docstring."""
def foobar():
pass
```
Running yapf on it produces this diff:
``` diff
--- yapf.py (original)
+++ yapf.py (reformatted)
@@ -1,6 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 name> -*-
-
"""Some module docstring."""
```
I would actually have expected yapf **not** to remove the blank line between the shebang/encoding and the module docstring (i.e. do nothing).
|
0.0
|
c873f37236c6fb962b6a181bae6a2f2cab23ba6a
|
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeModuleDocstring"
] |
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testArgsAndKwargsFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBinaryOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeClassDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesAtEndOfFile",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeFunctionsNotInColumnZero",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketsInlinedInCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCoalesceBracketsOnDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBeforeFuncDef",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBetweenDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentColumnLimitOverflow",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithTrailingSpaces",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComprehensionForAndIf",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContiguousList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkerAfterStringWithContinuation",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationSpaceRetention",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictSetGenerator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryElementsOnOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryMakerFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryOnOwnLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryValuesOnOwnLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstrings",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontAddBlankLineAfterMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontSplitKeywordValueArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEllipses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEmptyContainers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingWhitespaceAfterSimpleStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessCharacters",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessLineCountWithDefaultKeywords",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExpressionPenalties",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFormattingListComprehensions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallContinuationLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInNestedDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18n",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nNonFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfConditionalParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfExpressionWithFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testImportAsList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineDepthOfSingleLineStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineWrapInForExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehension",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferNoBreakForTrivialExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLineOverArithmeticSplit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferThreeLinesForLineWrap",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListWithFunctionCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMatchingParenSplittingMatching",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineCommentReformatted",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDictionaryKeys",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineLambdas",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineShebang",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleUgliness",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNamedAssignNotAtEndOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedListsInDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoBreakOutsideOfBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoKeywordArgumentBreakage",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoPenaltySplitting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoQueueSeletionInMiddleOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpaceBetweenUnaryOpAndOpeningParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesAroundKeywordDefaultValues",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenOpeningBracketAndStartingOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenSubscriptsAndCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingAroundTermOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingBeforeEndingSubscriptBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingOnSingleArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWhenBinPacking",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWithinSubscriptList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotInParams",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotSplittingAfterSubscript",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOpeningAndClosingBrackets",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOverColumnLimit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelativeImportStatements",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelaxArraySubscriptAffinity",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimple",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleFunctions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleFunctionsWithTrailingComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineCode",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineWithComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineFunctions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceAfterNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitAfterComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithInterspersedComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithTerminatingComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitStringsIfSurroundedByParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArgumentsTerminatedByComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArraysSensibly",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnCompoundStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionDefinition",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstElementListArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingOneArgumentList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableInlinedDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSubscriptExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailerOnSingleLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailingCommaAndBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCohesion",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCommaBeforeLastParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryOpInDictionaryValue",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnbreakableNot",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnformattedAfterMultilineString"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-03-22 13:11:52+00:00
|
apache-2.0
| 2,608 |
|
google__yapf-615
|
diff --git a/CHANGELOG b/CHANGELOG
index 83b26c9..698e6ea 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -6,6 +6,10 @@
### Added
- Added `INDENT_BLANK_LINES` knob to select whether the blank lines are empty
or indented consistently with the current block.
+### Fixed
+- Correctly determine if a scope is the last in line. It avoids a wrong
+ computation of the line end when determining if it must split after the
+ opening bracket with `DEDENT_CLOSING_BRACKETS` enabled.
## [0.24.0] 2018-09-07
### Added
diff --git a/yapf/yapflib/format_decision_state.py b/yapf/yapflib/format_decision_state.py
index cd6a729..40b4571 100644
--- a/yapf/yapflib/format_decision_state.py
+++ b/yapf/yapflib/format_decision_state.py
@@ -930,6 +930,7 @@ def _IsFunctionDefinition(current):
def _IsLastScopeInLine(current):
+ current = current.matching_bracket
while current:
current = current.next_token
if current and current.OpensScope():
|
google/yapf
|
841ad411adef77a38bf9e98f5ab843d65f3177d7
|
diff --git a/yapftests/reformatter_basic_test.py b/yapftests/reformatter_basic_test.py
index 57a45d6..3de71a8 100644
--- a/yapftests/reformatter_basic_test.py
+++ b/yapftests/reformatter_basic_test.py
@@ -2558,6 +2558,37 @@ x = [1, 2, 3, 4, 5, 6, 7,]
finally:
style.SetGlobalStyle(style.CreateChromiumStyle())
+ def testDedentClosingBracketsWithTypeAnnotationExceedingLineLength(self):
+ try:
+ style.SetGlobalStyle(
+ style.CreateStyleFromConfig('{based_on_style: chromium,'
+ ' dedent_closing_brackets: True}'))
+ unformatted_code = textwrap.dedent("""\
+ def function(first_argument_xxxxxxxxxxxxxxxx=(0,), second_argument=None) -> None:
+ pass
+
+
+ def function(first_argument_xxxxxxxxxxxxxxxxxxxxxxx=(0,), second_argument=None) -> None:
+ pass
+ """)
+ expected_formatted_code = textwrap.dedent("""\
+ def function(
+ first_argument_xxxxxxxxxxxxxxxx=(0,), second_argument=None
+ ) -> None:
+ pass
+
+
+ def function(
+ first_argument_xxxxxxxxxxxxxxxxxxxxxxx=(0,), second_argument=None
+ ) -> None:
+ pass
+ """)
+ uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
+ self.assertCodeEqual(expected_formatted_code,
+ reformatter.Reformat(uwlines))
+ finally:
+ style.SetGlobalStyle(style.CreateChromiumStyle())
+
if __name__ == '__main__':
unittest.main()
|
DEDENT_CLOSING_BRACKETS does not seem to work if arguments fit in line
I am getting somewhat inconsistent formatting on code like this:
```python
def long_function_name(argument1: Tuple[str, int], argument2: List[str]) -> Iterator[str]:
pass
def ever_longer_function_name(argument1: Tuple[str, int], argument2: List[str]) -> Iterator[str]:
pass
```
My `setup.cfg`:
```ini
[yapf]
based_on_style = pep8
coalesce_brackets = True
dedent_closing_brackets = True
split_penalty_after_opening_bracket = 0
split_before_first_argument = true
```
The result is this:
```python
def long_function_name(argument1: Tuple[str, int],
argument2: List[str]) -> Iterator[str]:
pass
def ever_longer_function_name(
argument1: Tuple[str, int], argument2: List[str]
) -> Iterator[str]:
pass
```
However, i would prefer the second style for the first example as well. I was expecting the `split_before_first_argument` option to have exactly that effect, but it does not seem to work.
With type annotations, the function signatures can get significant length other than their arguments. so this happens quite frequently in my code base. This issue seems to happen if the arguments fit in one line, but the full signature does not. If the arguments are longer than one line, it works fine.
I am using version 0.14.0.
|
0.0
|
841ad411adef77a38bf9e98f5ab843d65f3177d7
|
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDedentClosingBracketsWithTypeAnnotationExceedingLineLength"
] |
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testArgsAndKwargsFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBinaryOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeClassDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeModuleDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesAtEndOfFile",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeFunctionsNotInColumnZero",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketsInlinedInCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCoalesceBracketsOnDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBeforeFuncDef",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBetweenDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentColumnLimitOverflow",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithTrailingSpaces",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComprehensionForAndIf",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContiguousList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkerAfterStringWithContinuation",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationSpaceRetention",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictSetGenerator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryElementsOnOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryMakerFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryOnOwnLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryValuesOnOwnLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDisableEndingCommaHeuristic",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstrings",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontAddBlankLineAfterMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontSplitKeywordValueArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEllipses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEmptyContainers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingWhitespaceAfterSimpleStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessCharacters",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessLineCountWithDefaultKeywords",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExpressionPenalties",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFormattingListComprehensions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallContinuationLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInNestedDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18n",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nNonFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfConditionalParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfExpressionWithFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testImportAsList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentBlankLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineDepthOfSingleLineStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineWrapInForExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehension",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferNoBreakForTrivialExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLineOverArithmeticSplit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferThreeLinesForLineWrap",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListWithFunctionCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMatchingParenSplittingMatching",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineCommentReformatted",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDictionaryKeys",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineLambdas",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineShebang",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleUgliness",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNamedAssignNotAtEndOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedListsInDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoBreakOutsideOfBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoKeywordArgumentBreakage",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoPenaltySplitting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoQueueSeletionInMiddleOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpaceBetweenUnaryOpAndOpeningParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesAroundKeywordDefaultValues",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenOpeningBracketAndStartingOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenSubscriptsAndCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingAroundTermOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingBeforeEndingSubscriptBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingOnSingleArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWhenBinPacking",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWithinSubscriptList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotInParams",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotSplittingAfterSubscript",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOpeningAndClosingBrackets",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOverColumnLimit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testPseudoParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelativeImportStatements",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelaxArraySubscriptAffinity",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleFunctionsWithTrailingComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineCode",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineWithComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineFunctions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceAfterNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitAfterComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithInterspersedComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithTerminatingComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitStringsIfSurroundedByParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingAllArgs",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArgumentsTerminatedByComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArraysSensibly",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnCompoundStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionDefinition",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstElementListArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingOneArgumentList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableInlinedDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSubscriptExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailerOnSingleLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailingCommaAndBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCohesion",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCommaBeforeLastParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryOpInDictionaryValue",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnbreakableNot",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnformattedAfterMultilineString"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-09-07 10:13:16+00:00
|
apache-2.0
| 2,609 |
|
google__yapf-668
|
diff --git a/CHANGELOG b/CHANGELOG
index 214f013..d291200 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -6,6 +6,8 @@
### Added
- `ALLOW_SPLIT_BEFORE_DEFAULT_OR_NAMED_ASSIGNS` allows us to split before
default / named assignments.
+- `ARITHMETIC_PRECEDENCE_INDICATION` removes spacing around binary operators
+ if they have higher precedence than other operators in the same expression.
### Changed
- `SPACES_BEFORE_COMMENT` can now be assigned to a specific value (standard
behavior) or a list of column values. When assigned to a list, trailing
@@ -13,6 +15,8 @@
the list that is greater than the maximum line length in the block.
- Don't modify the vertical spacing of a line that has a comment "pylint:
disable=line-too-long". The line is expected to be too long.
+- improved `CONTINUATION_ALIGN_STYLE` to accept quoted or underline-separated
+ option value for passing option with command line arguments.
### Fixed
- When retrieving the opening bracket make sure that it's actually an opening
bracket.
@@ -26,6 +30,8 @@
multiple lines with the opening bracket on the same line as the key.
Therefore, we shouldn't enforce a split because of that.
- Increase split penalty around exponent operator.
+- Correct spacing when using binary operators on strings with the
+ `NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS` option enabled.
## [0.25.0] 2018-11-25
### Added
diff --git a/README.rst b/README.rst
index 2465ebc..388ddaa 100644
--- a/README.rst
+++ b/README.rst
@@ -333,6 +333,29 @@ Knobs
``ALLOW_SPLIT_BEFORE_DICT_VALUE``
Allow splits before the dictionary value.
+``ARITHMETIC_PRECEDENCE_INDICATION``
+ Let spacing indicate operator precedence. For example:
+
+ .. code-block:: python
+
+ a = 1 * 2 + 3 / 4
+ b = 1 / 2 - 3 * 4
+ c = (1 + 2) * (3 - 4)
+ d = (1 - 2) / (3 + 4)
+ e = 1 * 2 - 3
+ f = 1 + 2 + 3 + 4
+
+ will be formatted as follows to indicate precedence:
+
+ .. code-block:: python
+
+ a = 1*2 + 3/4
+ b = 1/2 - 3*4
+ c = (1+2) * (3-4)
+ d = (1-2) / (3+4)
+ e = 1*2 - 3
+ f = 1 + 2 + 3 + 4
+
``BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF``
Insert a blank line before a ``def`` or ``class`` immediately nested within
another ``def`` or ``class``. For example:
diff --git a/yapf/yapflib/format_token.py b/yapf/yapflib/format_token.py
index 9b428b3..8d41b90 100644
--- a/yapf/yapflib/format_token.py
+++ b/yapf/yapflib/format_token.py
@@ -36,6 +36,8 @@ class Subtype(object):
NONE = 0
UNARY_OPERATOR = 1
BINARY_OPERATOR = 2
+ A_EXPR_OPERATOR = 22
+ M_EXPR_OPERATOR = 23
SUBSCRIPT_COLON = 3
SUBSCRIPT_BRACKET = 4
DEFAULT_OR_NAMED_ASSIGN = 5
@@ -55,6 +57,7 @@ class Subtype(object):
DECORATOR = 18
TYPED_NAME = 19
TYPED_NAME_ARG_LIST = 20
+ SIMPLE_EXPRESSION = 24
def _TabbedContinuationAlignPadding(spaces, align_style, tab_width,
@@ -280,6 +283,30 @@ class FormatToken(object):
"""Token is a binary operator."""
return Subtype.BINARY_OPERATOR in self.subtypes
+ @property
+ @py3compat.lru_cache()
+ def is_a_expr_op(self):
+ """Token is an a_expr operator."""
+ return Subtype.A_EXPR_OPERATOR in self.subtypes
+
+ @property
+ @py3compat.lru_cache()
+ def is_m_expr_op(self):
+ """Token is an m_expr operator."""
+ return Subtype.M_EXPR_OPERATOR in self.subtypes
+
+ @property
+ @py3compat.lru_cache()
+ def is_arithmetic_op(self):
+ """Token is an arithmetic operator."""
+ return self.is_a_expr_op or self.is_m_expr_op
+
+ @property
+ @py3compat.lru_cache()
+ def is_simple_expr(self):
+ """Token is an operator in a simple expression."""
+ return Subtype.SIMPLE_EXPRESSION in self.subtypes
+
@property
@py3compat.lru_cache()
def name(self):
diff --git a/yapf/yapflib/style.py b/yapf/yapflib/style.py
index 8345304..579458d 100644
--- a/yapf/yapflib/style.py
+++ b/yapf/yapflib/style.py
@@ -64,6 +64,26 @@ _STYLE_HELP = dict(
"""),
ALLOW_SPLIT_BEFORE_DICT_VALUE=textwrap.dedent("""\
Allow splits before the dictionary value."""),
+ ARITHMETIC_PRECEDENCE_INDICATION=textwrap.dedent("""\
+ Let spacing indicate operator precedence. For example:
+
+ a = 1 * 2 + 3 / 4
+ b = 1 / 2 - 3 * 4
+ c = (1 + 2) * (3 - 4)
+ d = (1 - 2) / (3 + 4)
+ e = 1 * 2 - 3
+ f = 1 + 2 + 3 + 4
+
+ will be formatted as follows to indicate precedence:
+
+ a = 1*2 + 3/4
+ b = 1/2 - 3*4
+ c = (1+2) * (3-4)
+ d = (1-2) / (3+4)
+ e = 1*2 - 3
+ f = 1 + 2 + 3 + 4
+
+ """),
BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF=textwrap.dedent("""\
Insert a blank line before a 'def' or 'class' immediately nested
within another 'def' or 'class'. For example:
@@ -319,6 +339,7 @@ def CreatePEP8Style():
ALLOW_MULTILINE_DICTIONARY_KEYS=False,
ALLOW_SPLIT_BEFORE_DEFAULT_OR_NAMED_ASSIGNS=True,
ALLOW_SPLIT_BEFORE_DICT_VALUE=True,
+ ARITHMETIC_PRECEDENCE_INDICATION=False,
BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF=False,
BLANK_LINE_BEFORE_CLASS_DOCSTRING=False,
BLANK_LINE_BEFORE_MODULE_DOCSTRING=False,
@@ -437,7 +458,7 @@ def _ContinuationAlignStyleStringConverter(s):
"""Option value converter for a continuation align style string."""
accepted_styles = ('SPACE', 'FIXED', 'VALIGN-RIGHT')
if s:
- r = s.upper()
+ r = s.strip('"\'').replace('_', '-').upper()
if r not in accepted_styles:
raise ValueError('unknown continuation align style: %r' % (s,))
else:
@@ -489,6 +510,7 @@ _STYLE_OPTION_VALUE_CONVERTER = dict(
ALLOW_MULTILINE_DICTIONARY_KEYS=_BoolConverter,
ALLOW_SPLIT_BEFORE_DEFAULT_OR_NAMED_ASSIGNS=_BoolConverter,
ALLOW_SPLIT_BEFORE_DICT_VALUE=_BoolConverter,
+ ARITHMETIC_PRECEDENCE_INDICATION=_BoolConverter,
BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF=_BoolConverter,
BLANK_LINE_BEFORE_CLASS_DOCSTRING=_BoolConverter,
BLANK_LINE_BEFORE_MODULE_DOCSTRING=_BoolConverter,
diff --git a/yapf/yapflib/subtype_assigner.py b/yapf/yapflib/subtype_assigner.py
index beb8052..af1e0ad 100644
--- a/yapf/yapflib/subtype_assigner.py
+++ b/yapf/yapflib/subtype_assigner.py
@@ -187,16 +187,27 @@ class _SubtypeAssigner(pytree_visitor.PyTreeVisitor):
# arith_expr ::= term (('+'|'-') term)*
for child in node.children:
self.Visit(child)
- if isinstance(child, pytree.Leaf) and child.value in '+-':
+ if _IsAExprOperator(child):
_AppendTokenSubtype(child, format_token.Subtype.BINARY_OPERATOR)
+ _AppendTokenSubtype(child, format_token.Subtype.A_EXPR_OPERATOR)
+
+ if _IsSimpleExpression(node):
+ for child in node.children:
+ if _IsAExprOperator(child):
+ _AppendTokenSubtype(child, format_token.Subtype.SIMPLE_EXPRESSION)
def Visit_term(self, node): # pylint: disable=invalid-name
- # term ::= factor (('*'|'/'|'%'|'//') factor)*
+ # term ::= factor (('*'|'/'|'%'|'//'|'@') factor)*
for child in node.children:
self.Visit(child)
- if (isinstance(child, pytree.Leaf) and
- child.value in {'*', '/', '%', '//', '@'}):
+ if _IsMExprOperator(child):
_AppendTokenSubtype(child, format_token.Subtype.BINARY_OPERATOR)
+ _AppendTokenSubtype(child, format_token.Subtype.M_EXPR_OPERATOR)
+
+ if _IsSimpleExpression(node):
+ for child in node.children:
+ if _IsMExprOperator(child):
+ _AppendTokenSubtype(child, format_token.Subtype.SIMPLE_EXPRESSION)
def Visit_factor(self, node): # pylint: disable=invalid-name
# factor ::= ('+'|'-'|'~') factor | power
@@ -446,3 +457,17 @@ def _InsertPseudoParentheses(node):
new_node = pytree.Node(syms.atom, [lparen, clone, rparen])
node.replace(new_node)
_AppendFirstLeafTokenSubtype(clone, format_token.Subtype.DICTIONARY_VALUE)
+
+
+def _IsAExprOperator(node):
+ return isinstance(node, pytree.Leaf) and node.value in {'+', '-'}
+
+
+def _IsMExprOperator(node):
+ return isinstance(node,
+ pytree.Leaf) and node.value in {'*', '/', '%', '//', '@'}
+
+
+def _IsSimpleExpression(node):
+ """A node with only leafs as children."""
+ return all(map(lambda c: isinstance(c, pytree.Leaf), node.children))
diff --git a/yapf/yapflib/unwrapped_line.py b/yapf/yapflib/unwrapped_line.py
index 40f1295..b45d12a 100644
--- a/yapf/yapflib/unwrapped_line.py
+++ b/yapf/yapflib/unwrapped_line.py
@@ -227,6 +227,40 @@ def _IsUnaryOperator(tok):
return format_token.Subtype.UNARY_OPERATOR in tok.subtypes
+def _HasPrecedence(tok):
+ """Whether a binary operation has presedence within its context."""
+ node = tok.node
+
+ # We let ancestor be the statement surrounding the operation that tok is the
+ # operator in.
+ ancestor = node.parent.parent
+
+ while ancestor is not None:
+ # Search through the ancestor nodes in the parse tree for operators with
+ # lower precedence.
+ predecessor_type = pytree_utils.NodeName(ancestor)
+ if predecessor_type in ['arith_expr', 'term']:
+ # An ancestor "arith_expr" or "term" means we have found an operator
+ # with lower presedence than our tok.
+ return True
+ if predecessor_type != 'atom':
+ # We understand the context to look for precedence within as an
+ # arbitrary nesting of "arith_expr", "term", and "atom" nodes. If we
+ # leave this context we have not found a lower presedence operator.
+ return False
+ # Under normal usage we expect a complete parse tree to be available and
+ # we will return before we get an AttributeError from the root.
+ ancestor = ancestor.parent
+
+
+def _PriorityIndicatingNoSpace(tok):
+ """Whether to remove spaces around an operator due to presedence."""
+ if not tok.is_arithmetic_op or not tok.is_simple_expr:
+ # Limit space removal to highest priority arithmetic operators
+ return False
+ return _HasPrecedence(tok)
+
+
def _SpaceRequiredBetween(left, right):
"""Return True if a space is required between the left and right token."""
lval = left.value
@@ -291,9 +325,9 @@ def _SpaceRequiredBetween(left, right):
# If there is a type hint, then we don't want to add a space between the
# equal sign and the hint.
return False
- if rval not in '[)]}.':
+ if rval not in '[)]}.' and not right.is_binary_op:
# A string followed by something other than a subscript, closing bracket,
- # or dot should have a space after it.
+ # dot, or a binary op should have a space after it.
return True
if left.is_binary_op and lval != '**' and _IsUnaryOperator(right):
# Space between the binary operator and the unary operator.
@@ -310,7 +344,15 @@ def _SpaceRequiredBetween(left, right):
return style.Get('SPACES_AROUND_POWER_OPERATOR')
# Enforce spaces around binary operators except the blacklisted ones.
blacklist = style.Get('NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS')
- return lval not in blacklist and rval not in blacklist
+ if lval in blacklist or rval in blacklist:
+ return False
+ if style.Get('ARITHMETIC_PRECEDENCE_INDICATION'):
+ if _PriorityIndicatingNoSpace(left) or _PriorityIndicatingNoSpace(right):
+ return False
+ else:
+ return True
+ else:
+ return True
if (_IsUnaryOperator(left) and lval != 'not' and
(right.is_name or right.is_number or rval == '(')):
# The previous token was a unary op. No space is desired between it and
|
google/yapf
|
9546d407a4f898cd341e4e12e4b7cd50b6c5c2a2
|
diff --git a/yapftests/reformatter_basic_test.py b/yapftests/reformatter_basic_test.py
index 970c7ca..2e6fd2e 100644
--- a/yapftests/reformatter_basic_test.py
+++ b/yapftests/reformatter_basic_test.py
@@ -729,6 +729,13 @@ xxxxxxxxxxx, yyyyyyyyyyyy, vvvvvvvvv)
uwlines = yapf_test_helper.ParseAndUnwrap(code)
self.assertCodeEqual(code, reformatter.Reformat(uwlines))
+ def testSpaceBetweenStringAndParentheses(self):
+ code = textwrap.dedent("""\
+ b = '0' ('hello')
+ """)
+ uwlines = yapf_test_helper.ParseAndUnwrap(code)
+ self.assertCodeEqual(code, reformatter.Reformat(uwlines))
+
def testMultilineString(self):
code = textwrap.dedent("""\
code = textwrap.dedent('''\
diff --git a/yapftests/reformatter_style_config_test.py b/yapftests/reformatter_style_config_test.py
index 5afd805..a369279 100644
--- a/yapftests/reformatter_style_config_test.py
+++ b/yapftests/reformatter_style_config_test.py
@@ -56,7 +56,7 @@ class TestsForStyleConfig(yapf_test_helper.YAPFTest):
uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
- def testOperatorStyle(self):
+ def testOperatorNoSpaceStyle(self):
try:
sympy_style = style.CreatePEP8Style()
sympy_style['NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS'] = \
@@ -64,9 +64,54 @@ class TestsForStyleConfig(yapf_test_helper.YAPFTest):
style.SetGlobalStyle(sympy_style)
unformatted_code = textwrap.dedent("""\
a = 1+2 * 3 - 4 / 5
+ b = '0' * 1
""")
expected_formatted_code = textwrap.dedent("""\
a = 1 + 2*3 - 4/5
+ b = '0'*1
+ """)
+
+ uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
+ self.assertCodeEqual(expected_formatted_code,
+ reformatter.Reformat(uwlines))
+ finally:
+ style.SetGlobalStyle(style.CreatePEP8Style())
+ style.DEFAULT_STYLE = self.current_style
+
+ def testOperatorPrecedenceStyle(self):
+ try:
+ pep8_with_precedence = style.CreatePEP8Style()
+ pep8_with_precedence['ARITHMETIC_PRECEDENCE_INDICATION'] = True
+ style.SetGlobalStyle(pep8_with_precedence)
+ unformatted_code = textwrap.dedent("""\
+ 1+2
+ (1 + 2) * (3 - (4 / 5))
+ a = 1 * 2 + 3 / 4
+ b = 1 / 2 - 3 * 4
+ c = (1 + 2) * (3 - 4)
+ d = (1 - 2) / (3 + 4)
+ e = 1 * 2 - 3
+ f = 1 + 2 + 3 + 4
+ g = 1 * 2 * 3 * 4
+ h = 1 + 2 - 3 + 4
+ i = 1 * 2 / 3 * 4
+ j = (1 * 2 - 3) + 4
+ k = (1 * 2 * 3) + (4 * 5 * 6 * 7 * 8)
+ """)
+ expected_formatted_code = textwrap.dedent("""\
+ 1 + 2
+ (1+2) * (3 - (4/5))
+ a = 1*2 + 3/4
+ b = 1/2 - 3*4
+ c = (1+2) * (3-4)
+ d = (1-2) / (3+4)
+ e = 1*2 - 3
+ f = 1 + 2 + 3 + 4
+ g = 1 * 2 * 3 * 4
+ h = 1 + 2 - 3 + 4
+ i = 1 * 2 / 3 * 4
+ j = (1*2 - 3) + 4
+ k = (1*2*3) + (4*5*6*7*8)
""")
uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
diff --git a/yapftests/style_test.py b/yapftests/style_test.py
index ff4643e..3d4e1b1 100644
--- a/yapftests/style_test.py
+++ b/yapftests/style_test.py
@@ -27,14 +27,25 @@ from yapftests import utils
class UtilsTest(unittest.TestCase):
def testContinuationAlignStyleStringConverter(self):
- self.assertEqual(style._ContinuationAlignStyleStringConverter(''), 'SPACE')
- self.assertEqual(
- style._ContinuationAlignStyleStringConverter('space'), 'SPACE')
- self.assertEqual(
- style._ContinuationAlignStyleStringConverter('fixed'), 'FIXED')
- self.assertEqual(
- style._ContinuationAlignStyleStringConverter('valign-right'),
- 'VALIGN-RIGHT')
+ for cont_align_space in ('', 'space', '"space"', '\'space\''):
+ self.assertEqual(
+ style._ContinuationAlignStyleStringConverter(cont_align_space),
+ 'SPACE')
+ for cont_align_fixed in ('fixed', '"fixed"', '\'fixed\''):
+ self.assertEqual(
+ style._ContinuationAlignStyleStringConverter(cont_align_fixed),
+ 'FIXED')
+ for cont_align_valignright in (
+ 'valign-right',
+ '"valign-right"',
+ '\'valign-right\'',
+ 'valign_right',
+ '"valign_right"',
+ '\'valign_right\'',
+ ):
+ self.assertEqual(
+ style._ContinuationAlignStyleStringConverter(cont_align_valignright),
+ 'VALIGN-RIGHT')
with self.assertRaises(ValueError) as ctx:
style._ContinuationAlignStyleStringConverter('blahblah')
self.assertIn("unknown continuation align style: 'blahblah'",
diff --git a/yapftests/subtype_assigner_test.py b/yapftests/subtype_assigner_test.py
index 8daead9..ef864f8 100644
--- a/yapftests/subtype_assigner_test.py
+++ b/yapftests/subtype_assigner_test.py
@@ -162,6 +162,48 @@ class SubtypeAssignerTest(yapf_test_helper.YAPFTest):
('1', [format_token.Subtype.NONE]),],
]) # yapf: disable
+ def testArithmeticOperators(self):
+ code = textwrap.dedent("""\
+ x = ((a + (b - 3) * (1 % c) @ d) / 3) // 1
+ """)
+ uwlines = yapf_test_helper.ParseAndUnwrap(code)
+ self._CheckFormatTokenSubtypes(uwlines, [
+ [('x', [format_token.Subtype.NONE]),
+ ('=', {format_token.Subtype.ASSIGN_OPERATOR}),
+ ('(', [format_token.Subtype.NONE]),
+ ('(', [format_token.Subtype.NONE]),
+ ('a', [format_token.Subtype.NONE]),
+ ('+', {format_token.Subtype.BINARY_OPERATOR,
+ format_token.Subtype.A_EXPR_OPERATOR}),
+ ('(', [format_token.Subtype.NONE]),
+ ('b', [format_token.Subtype.NONE]),
+ ('-', {format_token.Subtype.BINARY_OPERATOR,
+ format_token.Subtype.A_EXPR_OPERATOR,
+ format_token.Subtype.SIMPLE_EXPRESSION}),
+ ('3', [format_token.Subtype.NONE]),
+ (')', [format_token.Subtype.NONE]),
+ ('*', {format_token.Subtype.BINARY_OPERATOR,
+ format_token.Subtype.M_EXPR_OPERATOR}),
+ ('(', [format_token.Subtype.NONE]),
+ ('1', [format_token.Subtype.NONE]),
+ ('%', {format_token.Subtype.BINARY_OPERATOR,
+ format_token.Subtype.M_EXPR_OPERATOR,
+ format_token.Subtype.SIMPLE_EXPRESSION}),
+ ('c', [format_token.Subtype.NONE]),
+ (')', [format_token.Subtype.NONE]),
+ ('@', {format_token.Subtype.BINARY_OPERATOR,
+ format_token.Subtype.M_EXPR_OPERATOR}),
+ ('d', [format_token.Subtype.NONE]),
+ (')', [format_token.Subtype.NONE]),
+ ('/', {format_token.Subtype.BINARY_OPERATOR,
+ format_token.Subtype.M_EXPR_OPERATOR}),
+ ('3', [format_token.Subtype.NONE]),
+ (')', [format_token.Subtype.NONE]),
+ ('//', {format_token.Subtype.BINARY_OPERATOR,
+ format_token.Subtype.M_EXPR_OPERATOR}),
+ ('1', [format_token.Subtype.NONE]),],
+ ]) # yapf: disable
+
def testSubscriptColon(self):
code = textwrap.dedent("""\
x[0:42:1]
|
_CreateConfigParserFromConfigString buggy for values with quotes - it captures quotes too
ver: 0.24
steps repeat:
yapf --style='{use_tabs: true, continuation_align_style: "valign-right"}' --style-help
gives:
yapf: '"valign-right"' is not a valid setting for CONTINUATION_ALIGN_STYLE.
|
0.0
|
9546d407a4f898cd341e4e12e4b7cd50b6c5c2a2
|
[
"yapftests/reformatter_style_config_test.py::TestsForStyleConfig::testOperatorNoSpaceStyle",
"yapftests/reformatter_style_config_test.py::TestsForStyleConfig::testOperatorPrecedenceStyle",
"yapftests/style_test.py::UtilsTest::testContinuationAlignStyleStringConverter",
"yapftests/subtype_assigner_test.py::SubtypeAssignerTest::testArithmeticOperators"
] |
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testArgsAndKwargsFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBinaryOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeClassDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeModuleDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesAtEndOfFile",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeFunctionsNotInColumnZero",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketsInlinedInCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCoalesceBracketsOnDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBeforeFuncDef",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBetweenDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentColumnLimitOverflow",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithTrailingSpaces",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComprehensionForAndIf",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContiguousList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkerAfterStringWithContinuation",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationSpaceRetention",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDedentClosingBracketsWithTypeAnnotationExceedingLineLength",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictSetGenerator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryElementsOnOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryMakerFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryOnOwnLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryValuesOnOwnLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDisableEndingCommaHeuristic",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstrings",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontAddBlankLineAfterMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontSplitKeywordValueArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEllipses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEmptyContainers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingWhitespaceAfterSimpleStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessCharacters",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessLineCountWithDefaultKeywords",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExpressionPenalties",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFormattingListComprehensions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallContinuationLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInNestedDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18n",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nNonFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfConditionalParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfExpressionWithFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testImportAsList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentBlankLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineDepthOfSingleLineStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineWrapInForExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehension",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferNoBreakForTrivialExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLineOverArithmeticSplit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferThreeLinesForLineWrap",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListWithFunctionCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMatchingParenSplittingMatching",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineCommentReformatted",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDictionaryKeys",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineLambdas",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineShebang",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleUgliness",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNamedAssignNotAtEndOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedListsInDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoBreakOutsideOfBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoKeywordArgumentBreakage",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoPenaltySplitting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoQueueSeletionInMiddleOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpaceBetweenUnaryOpAndOpeningParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesAroundKeywordDefaultValues",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenOpeningBracketAndStartingOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenSubscriptsAndCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingAroundTermOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingBeforeEndingSubscriptBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingOnSingleArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWhenBinPacking",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWithinSubscriptList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotInParams",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotSplittingAfterSubscript",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOpeningAndClosingBrackets",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOverColumnLimit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testPseudoParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelativeImportStatements",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelaxArraySubscriptAffinity",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleFunctionsWithTrailingComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineCode",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineWithComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineFunctions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceAfterNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceBetweenStringAndParentheses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitAfterComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithInterspersedComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithTerminatingComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitStringsIfSurroundedByParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingAllArgs",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArgumentsTerminatedByComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArraysSensibly",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnCompoundStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionDefinition",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstElementListArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingOneArgumentList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableInlinedDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSubscriptExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailerOnSingleLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailingCommaAndBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCohesion",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCommaBeforeLastParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryOpInDictionaryValue",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnbreakableNot",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnformattedAfterMultilineString",
"yapftests/reformatter_style_config_test.py::TestsForStyleConfig::testSetGlobalStyle",
"yapftests/style_test.py::UtilsTest::testBoolConverter",
"yapftests/style_test.py::UtilsTest::testIntListConverter",
"yapftests/style_test.py::UtilsTest::testIntOrIntListConverter",
"yapftests/style_test.py::UtilsTest::testStringListConverter",
"yapftests/style_test.py::PredefinedStylesByNameTest::testChromiumByName",
"yapftests/style_test.py::PredefinedStylesByNameTest::testDefault",
"yapftests/style_test.py::PredefinedStylesByNameTest::testFacebookByName",
"yapftests/style_test.py::PredefinedStylesByNameTest::testGoogleByName",
"yapftests/style_test.py::PredefinedStylesByNameTest::testPEP8ByName",
"yapftests/style_test.py::StyleFromFileTest::testBoolOptionValue",
"yapftests/style_test.py::StyleFromFileTest::testDefaultBasedOnChromiumStyle",
"yapftests/style_test.py::StyleFromFileTest::testDefaultBasedOnFacebookStyle",
"yapftests/style_test.py::StyleFromFileTest::testDefaultBasedOnGoogleStyle",
"yapftests/style_test.py::StyleFromFileTest::testDefaultBasedOnPEP8Style",
"yapftests/style_test.py::StyleFromFileTest::testDefaultBasedOnStyle",
"yapftests/style_test.py::StyleFromFileTest::testErrorNoStyleFile",
"yapftests/style_test.py::StyleFromFileTest::testErrorNoStyleSection",
"yapftests/style_test.py::StyleFromFileTest::testErrorUnknownStyleOption",
"yapftests/style_test.py::StyleFromFileTest::testStringListOptionValue",
"yapftests/style_test.py::StyleFromDict::testDefaultBasedOnStyle",
"yapftests/style_test.py::StyleFromDict::testDefaultBasedOnStyleBadDict",
"yapftests/style_test.py::StyleFromCommandLine::testDefaultBasedOnDetaultTypeString",
"yapftests/style_test.py::StyleFromCommandLine::testDefaultBasedOnExplicitlyUnicodeTypeString",
"yapftests/style_test.py::StyleFromCommandLine::testDefaultBasedOnStyle",
"yapftests/style_test.py::StyleFromCommandLine::testDefaultBasedOnStyleBadString",
"yapftests/style_test.py::StyleFromCommandLine::testDefaultBasedOnStyleNotStrict",
"yapftests/style_test.py::StyleHelp::testHelpKeys",
"yapftests/subtype_assigner_test.py::SubtypeAssignerTest::testBitwiseOperators",
"yapftests/subtype_assigner_test.py::SubtypeAssignerTest::testFuncCallWithDefaultAssign",
"yapftests/subtype_assigner_test.py::SubtypeAssignerTest::testFuncDefDefaultAssign",
"yapftests/subtype_assigner_test.py::SubtypeAssignerTest::testFunctionCallWithStarExpression",
"yapftests/subtype_assigner_test.py::SubtypeAssignerTest::testSetComprehension",
"yapftests/subtype_assigner_test.py::SubtypeAssignerTest::testSubscriptColon",
"yapftests/subtype_assigner_test.py::SubtypeAssignerTest::testUnaryNotOperator"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-01-19 18:11:48+00:00
|
apache-2.0
| 2,610 |
|
google__yapf-689
|
diff --git a/CHANGELOG b/CHANGELOG
index ee72fdb..1df010a 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -11,6 +11,9 @@
- Parse integer lists correctly, removing quotes if the list is within a
string.
- Adjust the penalties of bitwise operands for '&' and '^', similar to '|'.
+- Avoid splitting after opening parens if SPLIT_BEFORE_FIRST_ARGUMENT is set
+ to False.
+- Adjust default SPLIT_PENALTY_AFTER_OPENING_BRACKET.
## [0.26.0] 2019-02-08
### Added
@@ -20,7 +23,7 @@
if they have higher precedence than other operators in the same expression.
### Changed
- `SPACES_BEFORE_COMMENT` can now be assigned to a specific value (standard
- behavior) or a list of column values. When assigned to a list, trailing
+ behavior) or a list of column values. When assigned to a list, trailing
comments will be horizontally aligned to the first column value within
the list that is greater than the maximum line length in the block.
- Don't modify the vertical spacing of a line that has a comment "pylint:
diff --git a/yapf/__init__.py b/yapf/__init__.py
index 65584f8..97a9633 100644
--- a/yapf/__init__.py
+++ b/yapf/__init__.py
@@ -195,9 +195,9 @@ def main(argv):
exclude_patterns_from_ignore_file = file_resources.GetExcludePatternsForDir(
os.getcwd())
- files = file_resources.GetCommandLineFiles(
- args.files, args.recursive,
- (args.exclude or []) + exclude_patterns_from_ignore_file)
+ files = file_resources.GetCommandLineFiles(args.files, args.recursive,
+ (args.exclude or []) +
+ exclude_patterns_from_ignore_file)
if not files:
raise errors.YapfError('Input filenames did not match any python files')
diff --git a/yapf/yapflib/format_decision_state.py b/yapf/yapflib/format_decision_state.py
index 8dd5e55..486be8b 100644
--- a/yapf/yapflib/format_decision_state.py
+++ b/yapf/yapflib/format_decision_state.py
@@ -359,6 +359,11 @@ class FormatDecisionState(object):
# assigns.
return False
+ # Don't split if not required
+ if (not style.Get('SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN') and
+ not style.Get('SPLIT_BEFORE_FIRST_ARGUMENT')):
+ return False
+
column = self.column - self.stack[-1].last_space
return column > style.Get('CONTINUATION_INDENT_WIDTH')
@@ -412,12 +417,14 @@ class FormatDecisionState(object):
pprevious = previous.previous_token
if (current.is_name and pprevious and pprevious.is_name and
previous.value == '('):
+
if (not self._FitsOnLine(previous, previous.matching_bracket) and
_IsFunctionCallWithArguments(current)):
# There is a function call, with more than 1 argument, where the first
- # argument is itself a function call with arguments. In this specific
- # case, if we split after the first argument's opening '(', then the
- # formatting will look bad for the rest of the arguments. E.g.:
+ # argument is itself a function call with arguments that does not fit
+ # into the line. In this specific case, if we split after the first
+ # argument's opening '(', then the formatting will look bad for the
+ # rest of the arguments. E.g.:
#
# outer_function_call(inner_function_call(
# inner_arg1, inner_arg2),
@@ -425,7 +432,31 @@ class FormatDecisionState(object):
#
# Instead, enforce a split before that argument to keep things looking
# good.
- return True
+ if (style.Get('SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN') or
+ style.Get('SPLIT_BEFORE_FIRST_ARGUMENT')):
+ return True
+
+ opening = _GetOpeningBracket(current)
+ if (opening and opening.value == '(' and opening.previous_token and
+ (opening.previous_token.is_name or
+ opening.previous_token.value in {'*', '**'})):
+ is_func_call = False
+ opening = current
+ while opening:
+ if opening.value == '(':
+ is_func_call = True
+ break
+ if (not (opening.is_name or opening.value in {'*', '**'}) and
+ opening.value != '.'):
+ break
+ opening = opening.next_token
+
+ if is_func_call:
+ if (not self._FitsOnLine(current, opening.matching_bracket) or
+ (opening.matching_bracket.next_token and
+ opening.matching_bracket.next_token.value != ',' and
+ not opening.matching_bracket.next_token.ClosesScope())):
+ return True
if (previous.OpensScope() and not current.OpensScope() and
not current.is_comment and
diff --git a/yapf/yapflib/reformatter.py b/yapf/yapflib/reformatter.py
index b7c7491..48858a3 100644
--- a/yapf/yapflib/reformatter.py
+++ b/yapf/yapflib/reformatter.py
@@ -660,8 +660,9 @@ def _CalculateNumberOfNewlines(first_token, indent_depth, prev_uwline,
prev_last_token.AdjustNewlinesBefore(
1 + style.Get('BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION'))
if first_token.newlines is not None:
- pytree_utils.SetNodeAnnotation(
- first_token.node, pytree_utils.Annotation.NEWLINES, None)
+ pytree_utils.SetNodeAnnotation(first_token.node,
+ pytree_utils.Annotation.NEWLINES,
+ None)
return NO_BLANK_LINES
elif _IsClassOrDef(prev_uwline):
if not style.Get('BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF'):
diff --git a/yapf/yapflib/style.py b/yapf/yapflib/style.py
index c94da3c..359246e 100644
--- a/yapf/yapflib/style.py
+++ b/yapf/yapflib/style.py
@@ -202,7 +202,7 @@ _STYLE_HELP = dict(
alignment column values; trailing comments within a block will
be aligned to the first column value that is greater than the maximum
line length within the block). For example:
-
+
With spaces_before_comment=5:
1 + 1 # Adding values
@@ -377,7 +377,7 @@ def CreatePEP8Style():
SPLIT_BEFORE_LOGICAL_OPERATOR=True,
SPLIT_BEFORE_NAMED_ASSIGNS=True,
SPLIT_COMPLEX_COMPREHENSION=False,
- SPLIT_PENALTY_AFTER_OPENING_BRACKET=30,
+ SPLIT_PENALTY_AFTER_OPENING_BRACKET=300,
SPLIT_PENALTY_AFTER_UNARY_OPERATOR=10000,
SPLIT_PENALTY_ARITHMETIC_OPERATOR=300,
SPLIT_PENALTY_BEFORE_IF_EXPR=0,
|
google/yapf
|
b65cd13fed16fc27d4dc45eee491dc1c2455fe08
|
diff --git a/yapftests/reformatter_buganizer_test.py b/yapftests/reformatter_buganizer_test.py
index 22309ac..4d555e3 100644
--- a/yapftests/reformatter_buganizer_test.py
+++ b/yapftests/reformatter_buganizer_test.py
@@ -1546,7 +1546,7 @@ class _():
try:
style.SetGlobalStyle(
style.CreateStyleFromConfig(
- '{based_on_style: pep8, split_penalty_import_names: 35}'))
+ '{based_on_style: pep8, split_penalty_import_names: 350}'))
unformatted_code = textwrap.dedent("""\
from a_very_long_or_indented_module_name_yada_yada import (long_argument_1,
long_argument_2)
@@ -2193,8 +2193,8 @@ dddddddddddddddddd().eeeeeeeeeeeeeeeeeeeee().fffffffffffffffff().ggggggggggggggg
})
""")
expected_formatted_code = textwrap.dedent("""\
- shelf_renderer.expand_text = text.translate_to_unicode(
- expand_text % {'creator': creator})
+ shelf_renderer.expand_text = text.translate_to_unicode(expand_text %
+ {'creator': creator})
""")
uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
diff --git a/yapftests/reformatter_pep8_test.py b/yapftests/reformatter_pep8_test.py
index 729b33c..05d2cf0 100644
--- a/yapftests/reformatter_pep8_test.py
+++ b/yapftests/reformatter_pep8_test.py
@@ -190,8 +190,10 @@ class TestsForPEP8Style(yapf_test_helper.YAPFTest):
if (aaaaaaaaaaaaaa + bbbbbbbbbbbbbbbb == ccccccccccccccccc and xxxxxxxxxxxxx
or yyyyyyyyyyyyyyyyy):
pass
- elif (xxxxxxxxxxxxxxx(
- aaaaaaaaaaa, bbbbbbbbbbbbbb, cccccccccccc, dddddddddd=None)):
+ elif (xxxxxxxxxxxxxxx(aaaaaaaaaaa,
+ bbbbbbbbbbbbbb,
+ cccccccccccc,
+ dddddddddd=None)):
pass
diff --git a/yapftests/reformatter_style_config_test.py b/yapftests/reformatter_style_config_test.py
index a369279..5fe9709 100644
--- a/yapftests/reformatter_style_config_test.py
+++ b/yapftests/reformatter_style_config_test.py
@@ -121,6 +121,78 @@ class TestsForStyleConfig(yapf_test_helper.YAPFTest):
style.SetGlobalStyle(style.CreatePEP8Style())
style.DEFAULT_STYLE = self.current_style
+ def testNoSplitBeforeFirstArgumentStyle1(self):
+ try:
+ pep8_no_split_before_first = style.CreatePEP8Style()
+ pep8_no_split_before_first['SPLIT_BEFORE_FIRST_ARGUMENT'] = False
+ pep8_no_split_before_first['SPLIT_BEFORE_NAMED_ASSIGNS'] = False
+ style.SetGlobalStyle(pep8_no_split_before_first)
+ formatted_code = textwrap.dedent("""\
+ # Example from in-code MustSplit comments
+ foo = outer_function_call(fitting_inner_function_call(inner_arg1, inner_arg2),
+ outer_arg1, outer_arg2)
+
+ foo = outer_function_call(
+ not_fitting_inner_function_call(inner_arg1, inner_arg2), outer_arg1,
+ outer_arg2)
+
+ # Examples Issue#424
+ a_super_long_version_of_print(argument1, argument2, argument3, argument4,
+ argument5, argument6, argument7)
+
+ CREDS_FILE = os.path.join(os.path.expanduser('~'),
+ 'apis/super-secret-admin-creds.json')
+
+ # Examples Issue#556
+ i_take_a_lot_of_params(arg1, param1=very_long_expression1(),
+ param2=very_long_expression2(),
+ param3=very_long_expression3(),
+ param4=very_long_expression4())
+
+ # Examples Issue#590
+ plt.plot(numpy.linspace(0, 1, 10), numpy.linspace(0, 1, 10), marker="x",
+ color="r")
+
+ plt.plot(veryverylongvariablename, veryverylongvariablename, marker="x",
+ color="r")
+ """)
+ uwlines = yapf_test_helper.ParseAndUnwrap(formatted_code)
+ self.assertCodeEqual(formatted_code, reformatter.Reformat(uwlines))
+ finally:
+ style.SetGlobalStyle(style.CreatePEP8Style())
+ style.DEFAULT_STYLE = self.current_style
+
+ def testNoSplitBeforeFirstArgumentStyle2(self):
+ try:
+ pep8_no_split_before_first = style.CreatePEP8Style()
+ pep8_no_split_before_first['SPLIT_BEFORE_FIRST_ARGUMENT'] = False
+ pep8_no_split_before_first['SPLIT_BEFORE_NAMED_ASSIGNS'] = True
+ style.SetGlobalStyle(pep8_no_split_before_first)
+ formatted_code = textwrap.dedent("""\
+ # Examples Issue#556
+ i_take_a_lot_of_params(arg1,
+ param1=very_long_expression1(),
+ param2=very_long_expression2(),
+ param3=very_long_expression3(),
+ param4=very_long_expression4())
+
+ # Examples Issue#590
+ plt.plot(numpy.linspace(0, 1, 10),
+ numpy.linspace(0, 1, 10),
+ marker="x",
+ color="r")
+
+ plt.plot(veryverylongvariablename,
+ veryverylongvariablename,
+ marker="x",
+ color="r")
+ """)
+ uwlines = yapf_test_helper.ParseAndUnwrap(formatted_code)
+ self.assertCodeEqual(formatted_code, reformatter.Reformat(uwlines))
+ finally:
+ style.SetGlobalStyle(style.CreatePEP8Style())
+ style.DEFAULT_STYLE = self.current_style
+
if __name__ == '__main__':
unittest.main()
|
`split_before_first_argument` doesn't work on some cases
There seem to be some corner cases where `split_before_first_argument` doesn't seem to work as expected (at least not as I'd expect). For example using this style config
```
[style]
based_on_style = pep8
align_closing_bracket_with_visual_indent=True
coalesce_brackets=True
dedent_closing_brackets=False
indent_dictionary_value=True
spaces_around_power_operator=False
space_between_ending_comma_and_closing_bracket=False
split_arguments_when_comma_terminated=True
split_before_first_argument = False
split_before_named_assigns = False
split_penalty_after_opening_bracket=30
split_penalty_for_added_line_split=30
use_tabs=False
```
the following unformatted code:
```
a_super_long_version_of_print(argument1, argument2, argument3, argument4, argument5, argument6, argument7)
CREDS_FILE = os.path.join(os.path.expanduser('~'), 'apis/super-secret-admin-creds.json')
```
Gets formatted into:
```
a_super_long_version_of_print(argument1, argument2, argument3, argument4,
argument5, argument6, argument7)
CREDS_FILE = os.path.join(
os.path.expanduser('~'), 'apis/super-secret-admin-creds.json')
```
While the formatted original first line looks the way I'd expect, with all the arguments it can fit in the first line, and the remaining ones hanging at the same indentation level as the first one, the second original line seems to apply a different heuristic. Instead of what I'm getting, I was expecting to get:
```
CREDS_FILE = os.path.join(os.path.expanduser('~'),
'apis/super-secret-admin-creds.json')
```
If this is the expected behaviour, I'd appreciate if you can let me know if there's a configuration knob I could use to achieve my desired style.
|
0.0
|
b65cd13fed16fc27d4dc45eee491dc1c2455fe08
|
[
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB67935687",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testHangingIndentCollision",
"yapftests/reformatter_style_config_test.py::TestsForStyleConfig::testNoSplitBeforeFirstArgumentStyle1",
"yapftests/reformatter_style_config_test.py::TestsForStyleConfig::testNoSplitBeforeFirstArgumentStyle2"
] |
[
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB111764402",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB112651423",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB112711217",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB112867548",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB113210278",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB116825060",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB117841880",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB118624921",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB120047670",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB120245013",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB13900309",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB14406499",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB14468247",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB15438132",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB15542157",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB15597568",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB15697268",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB15884241",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB16572361",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB16783631",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB17011869",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB17133019",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB17489866",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB17534869",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB18255697",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB18256666",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB18256826",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB18257115",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19073499",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19194420",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19287512",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19353268",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19372573",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19377034",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19547210",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB19626808",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20016122",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20073838",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20127686",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20128830",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20551180",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20559654",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20562732",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20605036",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20813997",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB20849933",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB22527411",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB23445244",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB23935890",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB23943842",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB23944849",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25131481",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25136704",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25136820",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25157123",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25165602",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25324261",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB25505359",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB26034238",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB26382315",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB26868213",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB27266946",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB27590179",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB27616132",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB28414371",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB29093579",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB29908765",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30087362",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30087363",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30173198",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30394228",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30442148",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30500455",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30536435",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB30760569",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB31063453",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB31847238",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB31911533",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB31937033",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB32167774",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB32570937",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB32714745",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB32737279",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB32931780",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB33047408",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB33228502",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB33842726",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB34682902",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB34774905",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB35021894",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB35210166",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB35210351",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB35212469",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB35417079",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB36215507",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB36806207",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB37099651",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB37460004",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB38343525",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB65176185",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB65197969",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB65241516",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB65246454",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB65546221",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB66011084",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB66912275",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB67312284",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB67455376",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB67935450",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB73166511",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB77329955",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB77923341",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB79462249",
"yapftests/reformatter_buganizer_test.py::BuganizerFixes::testB80484938",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testAlignClosingBracketWithVisualIndentation",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testBitwiseOperandSplitting",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testContiguousListEndingWithComment",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testContinuedNonOutdentedLine",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testIndent4",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testIndentSizeChanging",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testNoBlankBetweenClassAndDef",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testNoSplitBeforeDictValue",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSingleLineIfStatements",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSingleWhiteBeforeTrailingComment",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSpaceBetweenEndingCommandAndClosingBracket",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplitAroundNamedAssigns",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplitBeforeArithmeticOperators",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplitListsAndDictSetMakersIfCommaTerminated",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplittingBeforeFirstArgument",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplittingBeforeLogicalOperator",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplittingExpressionsInsideSubscripts",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testUnaryOperator",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testWrappingPercentExpressions",
"yapftests/reformatter_style_config_test.py::TestsForStyleConfig::testOperatorNoSpaceStyle",
"yapftests/reformatter_style_config_test.py::TestsForStyleConfig::testOperatorPrecedenceStyle",
"yapftests/reformatter_style_config_test.py::TestsForStyleConfig::testSetGlobalStyle"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-03-12 17:08:30+00:00
|
apache-2.0
| 2,611 |
|
google__yapf-918
|
diff --git a/README.rst b/README.rst
index e441317..56fb9d6 100644
--- a/README.rst
+++ b/README.rst
@@ -270,8 +270,11 @@ share several arguments which are described below:
>>> from yapf.yapflib.yapf_api import FormatCode # reformat a string of code
- >>> FormatCode("f ( a = 1, b = 2 )")
+ >>> formatted_code, changed = FormatCode("f ( a = 1, b = 2 )")
+ >>> formatted_code
'f(a=1, b=2)\n'
+ >>> changed
+ True
A ``style_config`` argument: Either a style name or a path to a file that contains
formatting style settings. If None is specified, use the default style
@@ -279,7 +282,7 @@ as set in ``style.DEFAULT_STYLE_FACTORY``.
.. code-block:: python
- >>> FormatCode("def g():\n return True", style_config='pep8')
+ >>> FormatCode("def g():\n return True", style_config='pep8')[0]
'def g():\n return True\n'
A ``lines`` argument: A list of tuples of lines (ints), [start, end],
@@ -289,15 +292,15 @@ than a whole file.
.. code-block:: python
- >>> FormatCode("def g( ):\n a=1\n b = 2\n return a==b", lines=[(1, 1), (2, 3)])
+ >>> FormatCode("def g( ):\n a=1\n b = 2\n return a==b", lines=[(1, 1), (2, 3)])[0]
'def g():\n a = 1\n b = 2\n return a==b\n'
A ``print_diff`` (bool): Instead of returning the reformatted source, return a
-diff that turns the formatted source into reformatter source.
+diff that turns the formatted source into reformatted source.
.. code-block:: python
- >>> print(FormatCode("a==b", filename="foo.py", print_diff=True))
+ >>> print(FormatCode("a==b", filename="foo.py", print_diff=True)[0])
--- foo.py (original)
+++ foo.py (reformatted)
@@ -1 +1 @@
@@ -316,14 +319,19 @@ the diff, the default is ``<unknown>``.
>>> print(open("foo.py").read()) # contents of file
a==b
- >>> FormatFile("foo.py")
- ('a == b\n', 'utf-8')
+ >>> reformatted_code, encoding, changed = FormatFile("foo.py")
+ >>> formatted_code
+ 'a == b\n'
+ >>> encoding
+ 'utf-8'
+ >>> changed
+ True
The ``in_place`` argument saves the reformatted code back to the file:
.. code-block:: python
- >>> FormatFile("foo.py", in_place=True)
+ >>> FormatFile("foo.py", in_place=True)[:2]
(None, 'utf-8')
>>> print(open("foo.py").read()) # contents of file (now fixed)
diff --git a/setup.py b/setup.py
index fe2a046..70e57da 100644
--- a/setup.py
+++ b/setup.py
@@ -17,7 +17,7 @@ import codecs
import sys
import unittest
-from setuptools import setup, Command
+from setuptools import find_packages, setup, Command
import yapf
@@ -49,7 +49,7 @@ with codecs.open('README.rst', 'r', 'utf-8') as fd:
author='Google Inc.',
maintainer='Bill Wendling',
maintainer_email='[email protected]',
- packages=['yapf', 'yapf.yapflib', 'yapftests'],
+ packages=find_packages('.'),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
diff --git a/yapf/yapflib/reformatter.py b/yapf/yapflib/reformatter.py
index 60386e5..d07be84 100644
--- a/yapf/yapflib/reformatter.py
+++ b/yapf/yapflib/reformatter.py
@@ -119,14 +119,14 @@ def _RetainRequiredVerticalSpacing(cur_uwline, prev_uwline, lines):
if prev_uwline is not None:
prev_tok = prev_uwline.last
+ if cur_uwline.disable:
+ # After the first token we are acting on a single line. So if it is
+ # disabled we must not reformat.
+ lines = set()
+
for cur_tok in cur_uwline.tokens:
_RetainRequiredVerticalSpacingBetweenTokens(cur_tok, prev_tok, lines)
-
prev_tok = cur_tok
- if cur_uwline.disable:
- # After the first token we are acting on a single line. So if it is
- # disabled we must not reformat.
- lines = set()
def _RetainRequiredVerticalSpacingBetweenTokens(cur_tok, prev_tok, lines):
@@ -491,10 +491,13 @@ def _AnalyzeSolutionSpace(initial_state):
if count > 10000:
node.state.ignore_stack_for_comparison = True
- if node.state in seen:
- continue
-
+ # Unconditionally add the state and check if it was present to avoid having to
+ # hash it twice in the common case (state hashing is expensive).
+ before_seen_count = len(seen)
seen.add(node.state)
+ # If seen didn't change size, the state was already present.
+ if before_seen_count == len(seen):
+ continue
# FIXME(morbo): Add a 'decision' element?
diff --git a/yapf/yapflib/unwrapped_line.py b/yapf/yapflib/unwrapped_line.py
index 475bd6e..0986314 100644
--- a/yapf/yapflib/unwrapped_line.py
+++ b/yapf/yapflib/unwrapped_line.py
@@ -323,6 +323,9 @@ def _SpaceRequiredBetween(left, right, is_line_disabled):
format_token.Subtype.DEFAULT_OR_NAMED_ASSIGN not in left.subtypes):
# Space between equal and '.' as in "X = ...".
return True
+ if lval == ':' and rval == '.':
+ # Space between : and ...
+ return True
if ((right.is_keyword or right.is_name) and
(left.is_keyword or left.is_name)):
# Don't merge two keywords/identifiers.
diff --git a/yapf/yapflib/yapf_api.py b/yapf/yapflib/yapf_api.py
index dde1df9..fdcce30 100644
--- a/yapf/yapflib/yapf_api.py
+++ b/yapf/yapflib/yapf_api.py
@@ -269,10 +269,9 @@ def _MarkLinesToFormat(uwlines, lines):
index += 1
while index < len(uwlines):
uwline = uwlines[index]
- if uwline.is_comment and _EnableYAPF(uwline.first.value.strip()):
- if not re.search(DISABLE_PATTERN,
- uwline.first.value.strip().split('\n')[-1].strip(),
- re.IGNORECASE):
+ line = uwline.first.value.strip()
+ if uwline.is_comment and _EnableYAPF(line):
+ if not _DisableYAPF(line):
break
uwline.disable = True
index += 1
|
google/yapf
|
c6077954245bc3add82dafd853a1c7305a6ebd20
|
diff --git a/yapftests/blank_line_calculator_test.py b/yapftests/blank_line_calculator_test.py
index 1ec0a5e..193f419 100644
--- a/yapftests/blank_line_calculator_test.py
+++ b/yapftests/blank_line_calculator_test.py
@@ -300,15 +300,12 @@ class BasicBlankLineCalculatorTest(yapf_test_helper.YAPFTest):
def B(): # 4
pass # 5
-
def C():
pass
def D(): # 9
pass # 10
-
-
def E():
pass
""")
@@ -375,6 +372,8 @@ class BasicBlankLineCalculatorTest(yapf_test_helper.YAPFTest):
pass # 7
+
+
def C():
pass
""")
@@ -410,6 +409,7 @@ class BasicBlankLineCalculatorTest(yapf_test_helper.YAPFTest):
+
def C():
pass
""")
diff --git a/yapftests/reformatter_pep8_test.py b/yapftests/reformatter_pep8_test.py
index bdd074a..a5301f1 100644
--- a/yapftests/reformatter_pep8_test.py
+++ b/yapftests/reformatter_pep8_test.py
@@ -698,6 +698,17 @@ class _():
reformatted_code = reformatter.Reformat(uwlines)
self.assertCodeEqual(expected_formatted_code, reformatted_code)
+ @unittest.skipUnless(py3compat.PY36, 'Requires Python 3.6')
+ def testSpaceBetweenColonAndElipses(self):
+ style.SetGlobalStyle(style.CreatePEP8Style())
+ code = textwrap.dedent("""\
+ class MyClass(ABC):
+
+ place: ...
+ """)
+ uwlines = yapf_test_helper.ParseAndUnwrap(code)
+ self.assertCodeEqual(code, reformatter.Reformat(uwlines, verify=False))
+
class TestsForSpacesInsideBrackets(yapf_test_helper.YAPFTest):
"""Test the SPACE_INSIDE_BRACKETS style option."""
diff --git a/yapftests/yapf_test.py b/yapftests/yapf_test.py
index e3e3df3..dc0d0a5 100644
--- a/yapftests/yapf_test.py
+++ b/yapftests/yapf_test.py
@@ -881,8 +881,6 @@ x = {
""")
expected_formatted_code = textwrap.dedent("""\
a = line_to_format
-
-
def f():
x = y + 42; z = n * 42
if True: a += 1 ; b += 1 ; c += 1
@@ -905,8 +903,6 @@ x = {
''')
expected_formatted_code = textwrap.dedent('''\
foo = 42
-
-
def f():
email_text += """<html>This is a really long docstring that goes over the column limit and is multi-line.<br><br>
<b>Czar: </b>"""+despot["Nicholas"]+"""<br>
@@ -1031,6 +1027,7 @@ x = {
def aaaaaaaaaaaaa(self):
pass
+
def bbbbbbbbbbbbb(self): # 5
pass
""")
@@ -1170,13 +1167,12 @@ x = {
def testPseudoParenSpaces(self):
unformatted_code = textwrap.dedent("""\
- def foo():
+ def foo():
def bar():
return {msg_id: author for author, msg_id in reader}
""")
expected_formatted_code = textwrap.dedent("""\
def foo():
-
def bar():
return {msg_id: author for author, msg_id in reader}
""")
@@ -1482,6 +1478,30 @@ CONTINUATION_ALIGN_STYLE = valign-right
expected_formatted_code,
extra_options=['--style', 'yapf', '--lines', '1-1'])
+ def testDisableWithLinesOption(self):
+ unformatted_code = textwrap.dedent("""\
+ # yapf_lines_bug.py
+ # yapf: disable
+ def outer_func():
+ def inner_func():
+ return
+ return
+ # yapf: enable
+ """)
+ expected_formatted_code = textwrap.dedent("""\
+ # yapf_lines_bug.py
+ # yapf: disable
+ def outer_func():
+ def inner_func():
+ return
+ return
+ # yapf: enable
+ """)
+ self.assertYapfReformats(
+ unformatted_code,
+ expected_formatted_code,
+ extra_options=['--lines', '1-8'])
+
@unittest.skipUnless(py3compat.PY36, 'Requires Python 3.6')
def testNoSpacesAroundBinaryOperators(self):
unformatted_code = """\
|
README documents the wrong programmatic API
Both `FormatCode` and `FormatFile` return two-item tuples, but the README suggests they just return a string.
https://github.com/google/yapf/blob/c6077954245bc3add82dafd853a1c7305a6ebd20/yapf/yapflib/yapf_api.py#L137-L139
|
0.0
|
c6077954245bc3add82dafd853a1c7305a6ebd20
|
[
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testLinesOnRangeBoundary",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testLinesRangeRemove",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testLinesRangeRemoveSome",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSpaceBetweenColonAndElipses",
"yapftests/yapf_test.py::CommandLineTest::testDisableWithLinesOption",
"yapftests/yapf_test.py::CommandLineTest::testDisabledMultilineStrings",
"yapftests/yapf_test.py::CommandLineTest::testPseudoParenSpaces",
"yapftests/yapf_test.py::CommandLineTest::testRetainVerticalFormattingBetweenDisabledLines",
"yapftests/yapf_test.py::CommandLineTest::testRetainingSemicolonsWhenSpecifyingLines"
] |
[
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testCodeAfterFunctionsAndClasses",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testCommentBeforeMethod",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testCommentSpacing",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testCommentsAfterDecorator",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testCommentsBeforeClassDefs",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testCommentsBeforeDecorator",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testComplexDecorators",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testDecorators",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testInnerClasses",
"yapftests/blank_line_calculator_test.py::BasicBlankLineCalculatorTest::testLinesRangeBoundaryNotOutside",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testAlignClosingBracketWithVisualIndentation",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testBitwiseOperandSplitting",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testContiguousListEndingWithComment",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testContinuedNonOutdentedLine",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testHangingIndentCollision",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testIndent4",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testIndentSizeChanging",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testListSplitting",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testNoBlankBetweenClassAndDef",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testNoBlankBetweenDefsInClass",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testNoBlankLineBeforeNestedFuncOrClass",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testNoBlankLinesOnlyForFirstNestedObject",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testNoSplitBeforeDictValue",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testParamListIndentationCollision1",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testParamListIndentationCollision2",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testParamListIndentationCollision3",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSingleLineIfStatements",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSingleWhiteBeforeTrailingComment",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSpaceBetweenEndingCommandAndClosingBracket",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplitAroundNamedAssigns",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplitBeforeArithmeticOperators",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplitListsAndDictSetMakersIfCommaTerminated",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplittingBeforeFirstArgument",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplittingBeforeLogicalOperator",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplittingExpressionsInsideSubscripts",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testStableInlinedDictionaryFormatting",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testTwoWordComparisonOperators",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testUnaryOperator",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testWrappingPercentExpressions",
"yapftests/reformatter_pep8_test.py::TestsForSpacesInsideBrackets::testAwait",
"yapftests/reformatter_pep8_test.py::TestsForSpacesInsideBrackets::testDefault",
"yapftests/reformatter_pep8_test.py::TestsForSpacesInsideBrackets::testEnabled",
"yapftests/reformatter_pep8_test.py::TestsForSpacesAroundSubscriptColon::testDefault",
"yapftests/reformatter_pep8_test.py::TestsForSpacesAroundSubscriptColon::testEnabled",
"yapftests/reformatter_pep8_test.py::TestsForSpacesAroundSubscriptColon::testWithSpaceInsideBrackets",
"yapftests/yapf_test.py::FormatCodeTest::testNoEndingNewline",
"yapftests/yapf_test.py::FormatCodeTest::testPrintAfterPeriod",
"yapftests/yapf_test.py::FormatCodeTest::testSimple",
"yapftests/yapf_test.py::FormatFileTest::testCRLFLineEnding",
"yapftests/yapf_test.py::FormatFileTest::testCommentsUnformatted",
"yapftests/yapf_test.py::FormatFileTest::testDisableAndReenableLinesPattern",
"yapftests/yapf_test.py::FormatFileTest::testDisableLinesPattern",
"yapftests/yapf_test.py::FormatFileTest::testDisablePartOfMultilineComment",
"yapftests/yapf_test.py::FormatFileTest::testDisabledHorizontalFormattingOnNewLine",
"yapftests/yapf_test.py::FormatFileTest::testDisabledMultilineStringInDictionary",
"yapftests/yapf_test.py::FormatFileTest::testDisabledSemiColonSeparatedStatements",
"yapftests/yapf_test.py::FormatFileTest::testDisabledWithPrecedingText",
"yapftests/yapf_test.py::FormatFileTest::testEnabledDisabledSameComment",
"yapftests/yapf_test.py::FormatFileTest::testFormatFile",
"yapftests/yapf_test.py::FormatFileTest::testFormatFileDiff",
"yapftests/yapf_test.py::FormatFileTest::testFormatFileInPlace",
"yapftests/yapf_test.py::FormatFileTest::testFormatFileLinesSelection",
"yapftests/yapf_test.py::FormatFileTest::testNoFile",
"yapftests/yapf_test.py::FormatFileTest::testSemicolonStatementsDisabled",
"yapftests/yapf_test.py::FormatFileTest::testSplittingSemicolonStatements",
"yapftests/yapf_test.py::CommandLineTest::testCP936Encoding",
"yapftests/yapf_test.py::CommandLineTest::testCoalesceBrackets",
"yapftests/yapf_test.py::CommandLineTest::testCommentFollowingMultilineString",
"yapftests/yapf_test.py::CommandLineTest::testDedentClosingBracket",
"yapftests/yapf_test.py::CommandLineTest::testDisableButAdjustIndentations",
"yapftests/yapf_test.py::CommandLineTest::testDisableFormattingInDataLiteral",
"yapftests/yapf_test.py::CommandLineTest::testDisableWhenSpecifyingLines",
"yapftests/yapf_test.py::CommandLineTest::testDisableWholeDataStructure",
"yapftests/yapf_test.py::CommandLineTest::testDisableWithLineRanges",
"yapftests/yapf_test.py::CommandLineTest::testEncodingVerification",
"yapftests/yapf_test.py::CommandLineTest::testFormatLinesSpecifiedInMiddleOfExpression",
"yapftests/yapf_test.py::CommandLineTest::testInPlaceReformatting",
"yapftests/yapf_test.py::CommandLineTest::testInPlaceReformattingBlank",
"yapftests/yapf_test.py::CommandLineTest::testInPlaceReformattingEmpty",
"yapftests/yapf_test.py::CommandLineTest::testMultilineCommentFormattingDisabled",
"yapftests/yapf_test.py::CommandLineTest::testNoSpacesAroundBinaryOperators",
"yapftests/yapf_test.py::CommandLineTest::testOmitFormattingLinesBeforeDisabledFunctionComment",
"yapftests/yapf_test.py::CommandLineTest::testReadFromStdin",
"yapftests/yapf_test.py::CommandLineTest::testReadFromStdinWithEscapedStrings",
"yapftests/yapf_test.py::CommandLineTest::testReadSingleLineCodeFromStdin",
"yapftests/yapf_test.py::CommandLineTest::testReformattingSkippingLines",
"yapftests/yapf_test.py::CommandLineTest::testReformattingSkippingSingleLine",
"yapftests/yapf_test.py::CommandLineTest::testReformattingSkippingToEndOfFile",
"yapftests/yapf_test.py::CommandLineTest::testReformattingSpecificLines",
"yapftests/yapf_test.py::CommandLineTest::testRetainVerticalFormattingBetweenDisabledAndEnabledLines",
"yapftests/yapf_test.py::CommandLineTest::testRetainingHorizontalWhitespace",
"yapftests/yapf_test.py::CommandLineTest::testRetainingVerticalWhitespace",
"yapftests/yapf_test.py::CommandLineTest::testSetCustomStyleBasedOnYapf",
"yapftests/yapf_test.py::CommandLineTest::testSetCustomStyleSpacesBeforeComment",
"yapftests/yapf_test.py::CommandLineTest::testSetYapfStyle",
"yapftests/yapf_test.py::CommandLineTest::testSpacingBeforeComments",
"yapftests/yapf_test.py::CommandLineTest::testSpacingBeforeCommentsInDicts",
"yapftests/yapf_test.py::CommandLineTest::testStyleOutputRoundTrip",
"yapftests/yapf_test.py::CommandLineTest::testTrailingCommentsWithDisabledFormatting",
"yapftests/yapf_test.py::CommandLineTest::testUnicodeEncodingPipedToFile",
"yapftests/yapf_test.py::CommandLineTest::testUseSpacesContinuationAlignStyleFixed",
"yapftests/yapf_test.py::CommandLineTest::testUseSpacesContinuationAlignStyleVAlignRight",
"yapftests/yapf_test.py::CommandLineTest::testUseTabs",
"yapftests/yapf_test.py::CommandLineTest::testUseTabsContinuationAlignStyleFixed",
"yapftests/yapf_test.py::CommandLineTest::testUseTabsContinuationAlignStyleVAlignRight",
"yapftests/yapf_test.py::CommandLineTest::testUseTabsWith",
"yapftests/yapf_test.py::CommandLineTest::testVerticalSpacingWithCommentWithContinuationMarkers",
"yapftests/yapf_test.py::BadInputTest::testBadCode",
"yapftests/yapf_test.py::BadInputTest::testBadSyntax",
"yapftests/yapf_test.py::DiffIndentTest::testSimple",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testArgs",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlock",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockCommentSuffix",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockFuncSuffix",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockIndentedCommentSuffix",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockIndentedFuncSuffix",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockMultiIndented",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockWithLongLine",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testDisableBlock",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testDisabledLine",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testSimple",
"yapftests/yapf_test.py::SpacesAroundDictTest::testStandard",
"yapftests/yapf_test.py::SpacesAroundListTest::testStandard",
"yapftests/yapf_test.py::SpacesAroundTupleTest::testStandard"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-19 23:42:41+00:00
|
apache-2.0
| 2,612 |
|
google__yapf-954
|
diff --git a/CHANGELOG b/CHANGELOG
index a35ce68..4cecbd3 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -6,6 +6,10 @@
### Added
- Look at the 'pyproject.toml' file to see if it contains ignore file information
for YAPF.
+### Fixed
+- Enable `BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF` knob for "pep8" style, so
+ method definitions inside a class are surrounded by a single blank line as
+ prescribed by PEP8.
## [0.31.0] 2021-03-14
### Added
diff --git a/yapf/yapflib/style.py b/yapf/yapflib/style.py
index 3d27109..a1e6940 100644
--- a/yapf/yapflib/style.py
+++ b/yapf/yapflib/style.py
@@ -418,7 +418,7 @@ def CreatePEP8Style():
ALLOW_SPLIT_BEFORE_DEFAULT_OR_NAMED_ASSIGNS=True,
ALLOW_SPLIT_BEFORE_DICT_VALUE=True,
ARITHMETIC_PRECEDENCE_INDICATION=False,
- BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF=False,
+ BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF=True,
BLANK_LINE_BEFORE_CLASS_DOCSTRING=False,
BLANK_LINE_BEFORE_MODULE_DOCSTRING=False,
BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION=2,
@@ -479,7 +479,6 @@ def CreateGoogleStyle():
"""Create the Google formatting style."""
style = CreatePEP8Style()
style['ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT'] = False
- style['BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF'] = True
style['COLUMN_LIMIT'] = 80
style['INDENT_DICTIONARY_VALUE'] = True
style['INDENT_WIDTH'] = 4
@@ -511,6 +510,7 @@ def CreateFacebookStyle():
"""Create the Facebook formatting style."""
style = CreatePEP8Style()
style['ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT'] = False
+ style['BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF'] = False
style['COLUMN_LIMIT'] = 80
style['DEDENT_CLOSING_BRACKETS'] = True
style['INDENT_CLOSING_BRACKETS'] = False
|
google/yapf
|
da0dbb3567920a7b9faf25fce00443da7d7b1e00
|
diff --git a/yapftests/reformatter_basic_test.py b/yapftests/reformatter_basic_test.py
index a67e4c4..8dce567 100644
--- a/yapftests/reformatter_basic_test.py
+++ b/yapftests/reformatter_basic_test.py
@@ -1982,6 +1982,7 @@ class A(object):
def testStableDictionaryFormatting(self):
code = textwrap.dedent("""\
class A(object):
+
def method(self):
filters = {
'expressions': [{
diff --git a/yapftests/reformatter_pep8_test.py b/yapftests/reformatter_pep8_test.py
index a5301f1..e1202c2 100644
--- a/yapftests/reformatter_pep8_test.py
+++ b/yapftests/reformatter_pep8_test.py
@@ -50,22 +50,22 @@ class TestsForPEP8Style(yapf_test_helper.YAPFTest):
uwlines = yapf_test_helper.ParseAndUnwrap(code)
self.assertCodeEqual(code, reformatter.Reformat(uwlines))
- def testNoBlankBetweenClassAndDef(self):
+ def testBlankBetweenClassAndDef(self):
unformatted_code = textwrap.dedent("""\
class Foo:
-
def joe():
pass
""")
expected_formatted_code = textwrap.dedent("""\
class Foo:
+
def joe():
pass
""")
uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
- def testNoBlankBetweenDefsInClass(self):
+ def testBlankBetweenDefsInClass(self):
unformatted_code = textwrap.dedent('''\
class TestClass:
def __init__(self):
@@ -77,6 +77,7 @@ class TestsForPEP8Style(yapf_test_helper.YAPFTest):
''')
expected_formatted_code = textwrap.dedent('''\
class TestClass:
+
def __init__(self):
self.running = False
@@ -174,6 +175,7 @@ class TestsForPEP8Style(yapf_test_helper.YAPFTest):
""")
expected_formatted_code = textwrap.dedent("""\
def f():
+
def g():
while (xxxxxxxxxxxxxxxxxxxx(yyyyyyyyyyyyy[zzzzz]) == 'aaaaaaaaaaa'
and xxxxxxxxxxxxxxxxxxxx(
@@ -341,11 +343,13 @@ class TestsForPEP8Style(yapf_test_helper.YAPFTest):
def testSplitAroundNamedAssigns(self):
unformatted_code = textwrap.dedent("""\
class a():
+
def a(): return a(
aaaaaaaaaa=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)
""")
expected_formatted_code = textwrap.dedent("""\
class a():
+
def a():
return a(
aaaaaaaaaa=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
@@ -501,6 +505,7 @@ class Demo:
"""
Demo docs
"""
+
def foo(self):
"""
foo docs
@@ -602,6 +607,7 @@ class _():
""")
expected_formatted_code = textwrap.dedent("""\
class _():
+
def __init__(
self,
title: Optional[str],
diff --git a/yapftests/reformatter_python3_test.py b/yapftests/reformatter_python3_test.py
index d06e406..ae55755 100644
--- a/yapftests/reformatter_python3_test.py
+++ b/yapftests/reformatter_python3_test.py
@@ -238,6 +238,7 @@ None.__ne__()
return
code = textwrap.dedent("""\
async def outer():
+
async def inner():
pass
""")
@@ -365,6 +366,7 @@ class Foo:
"""
expected_formatted_code = """\
class Foo:
+
def foo(self):
foofoofoofoofoofoofoofoo('foofoofoofoofoo', {
'foo': 'foo',
diff --git a/yapftests/yapf_test.py b/yapftests/yapf_test.py
index dc0d0a5..4e062cf 100644
--- a/yapftests/yapf_test.py
+++ b/yapftests/yapf_test.py
@@ -735,12 +735,14 @@ class CommandLineTest(unittest.TestCase):
def testDisableButAdjustIndentations(self):
unformatted_code = textwrap.dedent("""\
class SplitPenaltyTest(unittest.TestCase):
+
def testUnbreakable(self):
self._CheckPenalties(tree, [
]) # yapf: disable
""")
expected_formatted_code = textwrap.dedent("""\
class SplitPenaltyTest(unittest.TestCase):
+
def testUnbreakable(self):
self._CheckPenalties(tree, [
]) # yapf: disable
|
yapf 0.28.0 now removes blank line between class docstring and first function
Given this code:
```python
class Foo:
"""Cool class"""
def bar(self):
"""Cool function"""
pass
```
yapf 0.28.0 now removes the line after `"""Cool class"""`, which makes `pydocstyle` complain with:
> D204: 1 blank line required after class docstring
Yapf 0.27.0 keeps this blank line.
|
0.0
|
da0dbb3567920a7b9faf25fce00443da7d7b1e00
|
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableDictionaryFormatting",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testAlignClosingBracketWithVisualIndentation",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testBlankBetweenClassAndDef",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testBlankBetweenDefsInClass",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testNoBlankLinesOnlyForFirstNestedObject",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testParamListIndentationCollision1",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplitAroundNamedAssigns",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testAsyncFunctionsNested",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testDictUnpacking",
"yapftests/yapf_test.py::CommandLineTest::testDisableButAdjustIndentations"
] |
[
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testArgsAndKwargsFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBinaryOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeClassDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLineBeforeModuleDocstring",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesAtEndOfFile",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBeforeFunctionsNotInColumnZero",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testBlankLinesBetweenTopLevelImportsAndVariables",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testClosingBracketsInlinedInCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCoalesceBracketsOnDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBeforeFuncDef",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentBetweenDecorators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentColumnLimitOverflow",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testCommentsWithTrailingSpaces",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testComprehensionForAndIf",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContiguousList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationIndent",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkerAfterStringWithContinuation",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testContinuationSpaceRetention",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDedentClosingBracketsWithTypeAnnotationExceedingLineLength",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictSetGenerator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryElementsOnOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryMakerFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryOnOwnLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDictionaryValuesOnOwnLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDisableEndingCommaHeuristic",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDocstrings",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontAddBlankLineAfterMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testDontSplitKeywordValueArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEllipses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEmptyContainers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testEndingWhitespaceAfterSimpleStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessCharacters",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExcessLineCountWithDefaultKeywords",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testExpressionPenalties",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testForceMultilineDict_False",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testForceMultilineDict_True",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFormattingListComprehensions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallArguments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallContinuationLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testFunctionCallInNestedDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18n",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nCommentsInDataLiteral",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testI18nNonFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfConditionalParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIfExpressionWithFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testImportAsList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentBlankLines",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInDict",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsInTuple",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testIndentClosingBracketsWithTypeAnnotationExceedingLineLength",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineDepthOfSingleLineStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testLineWrapInForExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehension",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferNoBreakForTrivialExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferOneLineOverArithmeticSplit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListComprehensionPreferThreeLinesForLineWrap",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testListWithFunctionCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMatchingParenSplittingMatching",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineCommentReformatted",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDictionaryKeys",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineDocstringAndMultilineComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineLambdas",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineShebang",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleContinuationMarkers",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleDictionariesInList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testMultipleUgliness",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNamedAssignNotAtEndOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNestedListsInDictionary",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoBreakOutsideOfBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoKeywordArgumentBreakage",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoPenaltySplitting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoQueueSeletionInMiddleOfLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpaceBetweenUnaryOpAndOpeningParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesAroundKeywordDefaultValues",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenOpeningBracketAndStartingOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSpacesBetweenSubscriptsAndCalls",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingAroundTermOperators",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingBeforeEndingSubscriptBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingOnSingleArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWhenBinPacking",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNoSplittingWithinSubscriptList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotInParams",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testNotSplittingAfterSubscript",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOpeningAndClosingBrackets",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testOverColumnLimit",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testPseudoParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelativeImportStatements",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testRelaxArraySubscriptAffinity",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleFunctionsWithTrailingComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineCode",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSimpleMultilineWithComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineFunctions",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSingleLineList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceAfterNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSpaceBetweenStringAndParentheses",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitAfterComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithComment",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithInterspersedComments",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitListWithTerminatingComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplitStringsIfSurroundedByParens",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingAllArgs",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArgumentsTerminatedByComma",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingArraysSensibly",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnCompoundStatement",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionCall",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstArgumentOnFunctionDefinition",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingBeforeFirstElementListArgument",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingOneArgumentList",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSplittingTopLevelAllArgs",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testStableInlinedDictionaryFormatting",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testSubscriptExpression",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailerOnSingleLine",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTrailingCommaAndBracket",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCohesion",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testTupleCommaBeforeLastParen",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryNotOperator",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnaryOpInDictionaryValue",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnbreakableNot",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testUnformattedAfterMultilineString",
"yapftests/reformatter_basic_test.py::BasicReformatterTest::testWalrus",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testBitwiseOperandSplitting",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testContiguousListEndingWithComment",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testContinuedNonOutdentedLine",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testHangingIndentCollision",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testIndent4",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testIndentSizeChanging",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testListSplitting",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testNoBlankLineBeforeNestedFuncOrClass",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testNoSplitBeforeDictValue",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testParamListIndentationCollision2",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testParamListIndentationCollision3",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSingleLineIfStatements",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSingleWhiteBeforeTrailingComment",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSpaceBetweenColonAndElipses",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSpaceBetweenEndingCommandAndClosingBracket",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplitBeforeArithmeticOperators",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplitListsAndDictSetMakersIfCommaTerminated",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplittingBeforeFirstArgument",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplittingBeforeLogicalOperator",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testSplittingExpressionsInsideSubscripts",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testStableInlinedDictionaryFormatting",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testTwoWordComparisonOperators",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testUnaryOperator",
"yapftests/reformatter_pep8_test.py::TestsForPEP8Style::testWrappingPercentExpressions",
"yapftests/reformatter_pep8_test.py::TestsForSpacesInsideBrackets::testAwait",
"yapftests/reformatter_pep8_test.py::TestsForSpacesInsideBrackets::testDefault",
"yapftests/reformatter_pep8_test.py::TestsForSpacesInsideBrackets::testEnabled",
"yapftests/reformatter_pep8_test.py::TestsForSpacesAroundSubscriptColon::testDefault",
"yapftests/reformatter_pep8_test.py::TestsForSpacesAroundSubscriptColon::testEnabled",
"yapftests/reformatter_pep8_test.py::TestsForSpacesAroundSubscriptColon::testWithSpaceInsideBrackets",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testAnnotations",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testAsyncForElseNotIndentedInsideBody",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testAsyncFunctions",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testAsyncWithPrecedingComment",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testContinuationIndentWithAsync",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testEllipses",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testExecAsNonKeyword",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testForElseInAsyncNotMixedWithAsyncFor",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testFunctionTypedReturnNextLine",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testFunctionTypedReturnSameLine",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testKeepTypesIntact",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testKeywordOnlyArgSpecifier",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testMatrixMultiplication",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testMultilineFormatString",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testNoSpacesAroundPowerOperator",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testNoneKeyword",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testPEP448ParameterExpansion",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testParameterListIndentationConflicts",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testSpacesAroundDefaultOrNamedAssign",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testSplittingArguments",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testTypeHint",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testTypedNameWithLongNamedArg",
"yapftests/reformatter_python3_test.py::TestsForPython3Code::testTypedNames",
"yapftests/yapf_test.py::FormatCodeTest::testNoEndingNewline",
"yapftests/yapf_test.py::FormatCodeTest::testPrintAfterPeriod",
"yapftests/yapf_test.py::FormatCodeTest::testSimple",
"yapftests/yapf_test.py::FormatFileTest::testCRLFLineEnding",
"yapftests/yapf_test.py::FormatFileTest::testCommentsUnformatted",
"yapftests/yapf_test.py::FormatFileTest::testDisableAndReenableLinesPattern",
"yapftests/yapf_test.py::FormatFileTest::testDisableLinesPattern",
"yapftests/yapf_test.py::FormatFileTest::testDisablePartOfMultilineComment",
"yapftests/yapf_test.py::FormatFileTest::testDisabledHorizontalFormattingOnNewLine",
"yapftests/yapf_test.py::FormatFileTest::testDisabledMultilineStringInDictionary",
"yapftests/yapf_test.py::FormatFileTest::testDisabledSemiColonSeparatedStatements",
"yapftests/yapf_test.py::FormatFileTest::testDisabledWithPrecedingText",
"yapftests/yapf_test.py::FormatFileTest::testEnabledDisabledSameComment",
"yapftests/yapf_test.py::FormatFileTest::testFormatFile",
"yapftests/yapf_test.py::FormatFileTest::testFormatFileDiff",
"yapftests/yapf_test.py::FormatFileTest::testFormatFileInPlace",
"yapftests/yapf_test.py::FormatFileTest::testFormatFileLinesSelection",
"yapftests/yapf_test.py::FormatFileTest::testNoFile",
"yapftests/yapf_test.py::FormatFileTest::testSemicolonStatementsDisabled",
"yapftests/yapf_test.py::FormatFileTest::testSplittingSemicolonStatements",
"yapftests/yapf_test.py::CommandLineTest::testCP936Encoding",
"yapftests/yapf_test.py::CommandLineTest::testCoalesceBrackets",
"yapftests/yapf_test.py::CommandLineTest::testCommentFollowingMultilineString",
"yapftests/yapf_test.py::CommandLineTest::testDedentClosingBracket",
"yapftests/yapf_test.py::CommandLineTest::testDisableFormattingInDataLiteral",
"yapftests/yapf_test.py::CommandLineTest::testDisableWhenSpecifyingLines",
"yapftests/yapf_test.py::CommandLineTest::testDisableWholeDataStructure",
"yapftests/yapf_test.py::CommandLineTest::testDisableWithLineRanges",
"yapftests/yapf_test.py::CommandLineTest::testDisableWithLinesOption",
"yapftests/yapf_test.py::CommandLineTest::testDisabledMultilineStrings",
"yapftests/yapf_test.py::CommandLineTest::testEncodingVerification",
"yapftests/yapf_test.py::CommandLineTest::testFormatLinesSpecifiedInMiddleOfExpression",
"yapftests/yapf_test.py::CommandLineTest::testInPlaceReformatting",
"yapftests/yapf_test.py::CommandLineTest::testInPlaceReformattingBlank",
"yapftests/yapf_test.py::CommandLineTest::testInPlaceReformattingEmpty",
"yapftests/yapf_test.py::CommandLineTest::testMultilineCommentFormattingDisabled",
"yapftests/yapf_test.py::CommandLineTest::testNoSpacesAroundBinaryOperators",
"yapftests/yapf_test.py::CommandLineTest::testOmitFormattingLinesBeforeDisabledFunctionComment",
"yapftests/yapf_test.py::CommandLineTest::testPseudoParenSpaces",
"yapftests/yapf_test.py::CommandLineTest::testReadFromStdin",
"yapftests/yapf_test.py::CommandLineTest::testReadFromStdinWithEscapedStrings",
"yapftests/yapf_test.py::CommandLineTest::testReadSingleLineCodeFromStdin",
"yapftests/yapf_test.py::CommandLineTest::testReformattingSkippingLines",
"yapftests/yapf_test.py::CommandLineTest::testReformattingSkippingSingleLine",
"yapftests/yapf_test.py::CommandLineTest::testReformattingSkippingToEndOfFile",
"yapftests/yapf_test.py::CommandLineTest::testReformattingSpecificLines",
"yapftests/yapf_test.py::CommandLineTest::testRetainVerticalFormattingBetweenDisabledAndEnabledLines",
"yapftests/yapf_test.py::CommandLineTest::testRetainVerticalFormattingBetweenDisabledLines",
"yapftests/yapf_test.py::CommandLineTest::testRetainingHorizontalWhitespace",
"yapftests/yapf_test.py::CommandLineTest::testRetainingSemicolonsWhenSpecifyingLines",
"yapftests/yapf_test.py::CommandLineTest::testRetainingVerticalWhitespace",
"yapftests/yapf_test.py::CommandLineTest::testSetCustomStyleBasedOnYapf",
"yapftests/yapf_test.py::CommandLineTest::testSetCustomStyleSpacesBeforeComment",
"yapftests/yapf_test.py::CommandLineTest::testSetYapfStyle",
"yapftests/yapf_test.py::CommandLineTest::testSpacingBeforeComments",
"yapftests/yapf_test.py::CommandLineTest::testSpacingBeforeCommentsInDicts",
"yapftests/yapf_test.py::CommandLineTest::testStyleOutputRoundTrip",
"yapftests/yapf_test.py::CommandLineTest::testTrailingCommentsWithDisabledFormatting",
"yapftests/yapf_test.py::CommandLineTest::testUnicodeEncodingPipedToFile",
"yapftests/yapf_test.py::CommandLineTest::testUseSpacesContinuationAlignStyleFixed",
"yapftests/yapf_test.py::CommandLineTest::testUseSpacesContinuationAlignStyleVAlignRight",
"yapftests/yapf_test.py::CommandLineTest::testUseTabs",
"yapftests/yapf_test.py::CommandLineTest::testUseTabsContinuationAlignStyleFixed",
"yapftests/yapf_test.py::CommandLineTest::testUseTabsContinuationAlignStyleVAlignRight",
"yapftests/yapf_test.py::CommandLineTest::testUseTabsWith",
"yapftests/yapf_test.py::CommandLineTest::testVerticalSpacingWithCommentWithContinuationMarkers",
"yapftests/yapf_test.py::BadInputTest::testBadCode",
"yapftests/yapf_test.py::BadInputTest::testBadSyntax",
"yapftests/yapf_test.py::DiffIndentTest::testSimple",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testArgs",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlock",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockCommentSuffix",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockFuncSuffix",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockIndentedCommentSuffix",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockIndentedFuncSuffix",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockMultiIndented",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testBlockWithLongLine",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testDisableBlock",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testDisabledLine",
"yapftests/yapf_test.py::HorizontallyAlignedTrailingCommentsTest::testSimple",
"yapftests/yapf_test.py::SpacesAroundDictTest::testStandard",
"yapftests/yapf_test.py::SpacesAroundListTest::testStandard",
"yapftests/yapf_test.py::SpacesAroundTupleTest::testStandard"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-20 14:05:44+00:00
|
apache-2.0
| 2,613 |
|
googleapis__gapic-generator-python-654
|
diff --git a/gapic/schema/metadata.py b/gapic/schema/metadata.py
index 9459bb5e..b801bb76 100644
--- a/gapic/schema/metadata.py
+++ b/gapic/schema/metadata.py
@@ -90,6 +90,20 @@ class Address:
# Return the Python identifier.
return '.'.join(self.parent + (self.name,))
+ def __repr__(self) -> str:
+ return "({})".format(
+ ", ".join(
+ (
+ self.name,
+ self.module,
+ str(self.module_path),
+ str(self.package),
+ str(self.parent),
+ str(self.api_naming),
+ )
+ )
+ )
+
@property
def module_alias(self) -> str:
"""Return an appropriate module alias if necessary.
diff --git a/gapic/schema/wrappers.py b/gapic/schema/wrappers.py
index e68b397e..1b0db83e 100644
--- a/gapic/schema/wrappers.py
+++ b/gapic/schema/wrappers.py
@@ -222,7 +222,12 @@ class Field:
raise TypeError(f'Unrecognized protobuf type: {self.field_pb.type}. '
'This code should not be reachable; please file a bug.')
- def with_context(self, *, collisions: FrozenSet[str]) -> 'Field':
+ def with_context(
+ self,
+ *,
+ collisions: FrozenSet[str],
+ visited_messages: FrozenSet["MessageType"],
+ ) -> 'Field':
"""Return a derivative of this field with the provided context.
This method is used to address naming collisions. The returned
@@ -233,7 +238,8 @@ class Field:
self,
message=self.message.with_context(
collisions=collisions,
- skip_fields=True,
+ skip_fields=self.message in visited_messages,
+ visited_messages=visited_messages,
) if self.message else None,
enum=self.enum.with_context(collisions=collisions)
if self.enum else None,
@@ -406,7 +412,10 @@ class MessageType:
# Base case: If this is the last field in the path, return it outright.
if len(field_path) == 1:
- return cursor.with_context(collisions=collisions)
+ return cursor.with_context(
+ collisions=collisions,
+ visited_messages=frozenset({self}),
+ )
# Sanity check: If cursor is a repeated field, then raise an exception.
# Repeated fields are only permitted in the terminal position.
@@ -433,6 +442,7 @@ class MessageType:
def with_context(self, *,
collisions: FrozenSet[str],
skip_fields: bool = False,
+ visited_messages: FrozenSet["MessageType"] = frozenset(),
) -> 'MessageType':
"""Return a derivative of this message with the provided context.
@@ -444,10 +454,14 @@ class MessageType:
underlying fields. This provides for an "exit" in the case of circular
references.
"""
+ visited_messages = visited_messages | {self}
return dataclasses.replace(
self,
fields=collections.OrderedDict(
- (k, v.with_context(collisions=collisions))
+ (k, v.with_context(
+ collisions=collisions,
+ visited_messages=visited_messages
+ ))
for k, v in self.fields.items()
) if not skip_fields else self.fields,
nested_enums=collections.OrderedDict(
@@ -457,7 +471,9 @@ class MessageType:
nested_messages=collections.OrderedDict(
(k, v.with_context(
collisions=collisions,
- skip_fields=skip_fields,))
+ skip_fields=skip_fields,
+ visited_messages=visited_messages,
+ ))
for k, v in self.nested_messages.items()),
meta=self.meta.with_context(collisions=collisions),
)
|
googleapis/gapic-generator-python
|
d7829efe207a8730321279e594429e3bdbf2e080
|
diff --git a/tests/unit/schema/test_api.py b/tests/unit/schema/test_api.py
index c52c2f32..e91a310e 100644
--- a/tests/unit/schema/test_api.py
+++ b/tests/unit/schema/test_api.py
@@ -1214,3 +1214,76 @@ def test_resources_referenced_but_not_typed(reference_attr="type"):
def test_resources_referenced_but_not_typed_child_type():
test_resources_referenced_but_not_typed("child_type")
+
+
+def test_map_field_name_disambiguation():
+ squid_file_pb = descriptor_pb2.FileDescriptorProto(
+ name="mollusc.proto",
+ package="animalia.mollusca.v2",
+ message_type=(
+ descriptor_pb2.DescriptorProto(
+ name="Mollusc",
+ ),
+ ),
+ )
+ method_types_file_pb = descriptor_pb2.FileDescriptorProto(
+ name="mollusc_service.proto",
+ package="animalia.mollusca.v2",
+ message_type=(
+ descriptor_pb2.DescriptorProto(
+ name="CreateMolluscRequest",
+ field=(
+ descriptor_pb2.FieldDescriptorProto(
+ name="mollusc",
+ type="TYPE_MESSAGE",
+ type_name=".animalia.mollusca.v2.Mollusc",
+ number=1,
+ ),
+ descriptor_pb2.FieldDescriptorProto(
+ name="molluscs_map",
+ type="TYPE_MESSAGE",
+ number=2,
+ type_name=".animalia.mollusca.v2.CreateMolluscRequest.MolluscsMapEntry",
+ label="LABEL_REPEATED",
+ ),
+ ),
+ nested_type=(
+ descriptor_pb2.DescriptorProto(
+ name="MolluscsMapEntry",
+ field=(
+ descriptor_pb2.FieldDescriptorProto(
+ name="key",
+ type="TYPE_STRING",
+ number=1,
+ ),
+ descriptor_pb2.FieldDescriptorProto(
+ name="value",
+ type="TYPE_MESSAGE",
+ number=2,
+ # We use the same type for the map value as for
+ # the singleton above to better highlight the
+ # problem raised in
+ # https://github.com/googleapis/gapic-generator-python/issues/618.
+ # The module _is_ disambiguated for singleton
+ # fields but NOT for map fields.
+ type_name=".animalia.mollusca.v2.Mollusc"
+ ),
+ ),
+ options=descriptor_pb2.MessageOptions(map_entry=True),
+ ),
+ ),
+ ),
+ ),
+ )
+ my_api = api.API.build(
+ file_descriptors=[squid_file_pb, method_types_file_pb],
+ )
+ create = my_api.messages['animalia.mollusca.v2.CreateMolluscRequest']
+ mollusc = create.fields['mollusc']
+ molluscs_map = create.fields['molluscs_map']
+ mollusc_ident = str(mollusc.type.ident)
+ mollusc_map_ident = str(molluscs_map.message.fields['value'].type.ident)
+
+ # The same module used in the same place should have the same import alias.
+ # Because there's a "mollusc" name used, the import should be disambiguated.
+ assert mollusc_ident == mollusc_map_ident == "am_mollusc.Mollusc"
|
Map field message definitions do not consistently use module alias disambiguation
This is visible with Bigtable Admin. The generation produces output and generates no errors, but the generated unit tests fail.
```
from .bigtable_instance_admin import (CreateInstanceRequest, GetInstanceRequest, ListInstancesRequest, ListInstancesResponse, PartialUpdateInstanceRequest, DeleteInstanceRequest, CreateClusterRequest, GetClusterRequest, ListClustersRequest, ListClustersResponse, DeleteClusterRequest, CreateInstanceMetadata, UpdateInstanceMetadata, CreateClusterMetadata, UpdateClusterMetadata, CreateAppProfileRequest, GetAppProfileRequest, ListAppProfilesRequest, ListAppProfilesResponse, UpdateAppProfileRequest, DeleteAppProfileRequest, UpdateAppProfileMetadata, )
google/cloud/bigtable_admin_v2/types/bigtable_instance_admin.py:55: in <module>
class CreateInstanceRequest(proto.Message):
google/cloud/bigtable_admin_v2/types/bigtable_instance_admin.py:88: in CreateInstanceRequest
message=instance.Cluster,
E AttributeError: 'Field' object has no attribute 'Cluster
```
In the above stacktrace, `message=instance.Cluster` should be `message=gba_instance.Cluster`.
|
0.0
|
d7829efe207a8730321279e594429e3bdbf2e080
|
[
"tests/unit/schema/test_api.py::test_map_field_name_disambiguation"
] |
[
"tests/unit/schema/test_api.py::test_api_build",
"tests/unit/schema/test_api.py::test_top_level_messages",
"tests/unit/schema/test_api.py::test_top_level_enum",
"tests/unit/schema/test_api.py::test_proto_build",
"tests/unit/schema/test_api.py::test_proto_names",
"tests/unit/schema/test_api.py::test_proto_keyword_fname",
"tests/unit/schema/test_api.py::test_proto_oneof",
"tests/unit/schema/test_api.py::test_proto_names_import_collision",
"tests/unit/schema/test_api.py::test_proto_names_import_collision_flattening",
"tests/unit/schema/test_api.py::test_proto_builder_constructor",
"tests/unit/schema/test_api.py::test_not_target_file",
"tests/unit/schema/test_api.py::test_messages",
"tests/unit/schema/test_api.py::test_messages_reverse_declaration_order",
"tests/unit/schema/test_api.py::test_messages_recursive",
"tests/unit/schema/test_api.py::test_messages_nested",
"tests/unit/schema/test_api.py::test_out_of_order_enums",
"tests/unit/schema/test_api.py::test_undefined_type",
"tests/unit/schema/test_api.py::test_python_modules_nested",
"tests/unit/schema/test_api.py::test_services",
"tests/unit/schema/test_api.py::test_prior_protos",
"tests/unit/schema/test_api.py::test_lro",
"tests/unit/schema/test_api.py::test_lro_missing_annotation",
"tests/unit/schema/test_api.py::test_cross_file_lro",
"tests/unit/schema/test_api.py::test_enums",
"tests/unit/schema/test_api.py::test_file_level_resources",
"tests/unit/schema/test_api.py::test_resources_referenced_but_not_typed",
"tests/unit/schema/test_api.py::test_resources_referenced_but_not_typed_child_type"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-10-13 16:52:48+00:00
|
apache-2.0
| 2,614 |
|
googleapis__gapic-generator-python-717
|
diff --git a/gapic/schema/naming.py b/gapic/schema/naming.py
index c591ad59..3f49a18a 100644
--- a/gapic/schema/naming.py
+++ b/gapic/schema/naming.py
@@ -42,6 +42,7 @@ class Naming(abc.ABC):
version: str = ''
product_name: str = ''
proto_package: str = ''
+ _warehouse_package_name: str = ''
def __post_init__(self):
if not self.product_name:
@@ -141,6 +142,10 @@ class Naming(abc.ABC):
# with ('x.y',) will become a two-tuple: ('x', 'y')
i.capitalize() for i in '.'.join(opts.namespace).split('.')
))
+ if opts.warehouse_package_name:
+ package_info = dataclasses.replace(package_info,
+ _warehouse_package_name=opts.warehouse_package_name
+ )
# Done; return the naming information.
return package_info
@@ -186,9 +191,11 @@ class Naming(abc.ABC):
@property
def warehouse_package_name(self) -> str:
"""Return the appropriate Python package name for Warehouse."""
-
- # Piece the name and namespace together to come up with the
- # proper package name.
+ # If a custom name has been set, use it
+ if self._warehouse_package_name:
+ return self._warehouse_package_name
+ # Otherwise piece the name and namespace together to come
+ # up with the proper package name.
answer = list(self.namespace) + self.name.split(' ')
return '-'.join(answer).lower()
diff --git a/gapic/utils/options.py b/gapic/utils/options.py
index d99e34c6..b8e79a06 100644
--- a/gapic/utils/options.py
+++ b/gapic/utils/options.py
@@ -34,6 +34,7 @@ class Options:
"""
name: str = ''
namespace: Tuple[str, ...] = dataclasses.field(default=())
+ warehouse_package_name: str = ''
retry: Optional[Dict[str, Any]] = None
sample_configs: Tuple[str, ...] = dataclasses.field(default=())
templates: Tuple[str, ...] = dataclasses.field(default=('DEFAULT',))
@@ -53,6 +54,7 @@ class Options:
'add-iam-methods', # microgenerator implementation for `reroute_to_grpc_interface`
# transport type(s) delineated by '+' (i.e. grpc, rest, custom.[something], etc?)
'transport',
+ 'warehouse-package-name' # change the package name on PyPI
))
@classmethod
@@ -129,6 +131,8 @@ class Options:
answer = Options(
name=opts.pop('name', ['']).pop(),
namespace=tuple(opts.pop('namespace', [])),
+ warehouse_package_name=opts.pop(
+ 'warehouse-package-name', ['']).pop(),
retry=retry_cfg,
sample_configs=tuple(
cfg_path
|
googleapis/gapic-generator-python
|
39be474b4419dfa521ef51927fd36dbf257d68e3
|
diff --git a/tests/unit/generator/test_options.py b/tests/unit/generator/test_options.py
index 5235c2e4..60d365a8 100644
--- a/tests/unit/generator/test_options.py
+++ b/tests/unit/generator/test_options.py
@@ -152,3 +152,8 @@ def test_options_old_naming():
def test_options_add_iam_methods():
opts = Options.build('add-iam-methods')
assert opts.add_iam_methods
+
+
+def test_options_warehouse_package_name():
+ opts = Options.build('warehouse-package-name')
+ assert opts.warehouse_package_name
diff --git a/tests/unit/schema/test_naming.py b/tests/unit/schema/test_naming.py
index ec1e0dad..c0487b7d 100644
--- a/tests/unit/schema/test_naming.py
+++ b/tests/unit/schema/test_naming.py
@@ -218,6 +218,16 @@ def test_cli_override_name_and_namespace_versionless():
assert not n.version
+def test_cli_override_warehouse_package_name():
+ FileDesc = descriptor_pb2.FileDescriptorProto
+ proto1 = FileDesc(package='google.translation')
+ n = naming.Naming.build(
+ proto1,
+ opts=Options(warehouse_package_name='google-cloud-foo'),
+ )
+ assert n.warehouse_package_name == "google-cloud-foo"
+
+
def test_build_factory():
proto = descriptor_pb2.FileDescriptorProto(
package='google.mollusc.v1alpha1'
|
Allow package name to be customized via a generator option
https://github.com/googleapis/gapic-generator-python/blob/f86a47b6431e374ae1797061511b49fe6bf22daf/gapic/schema/naming.py#L186-L193
Occasionally we want to deviate from the generated provided `api.naming.warehouse_package_name`.
* The published package includes two GAPICs (firestore admin and firestore) and we want the library to be consistently named `google-cloud-firestore`.
* The API has a long name and we want to rename the package to make it easier to spell.
`google-cloud-assuredworkloads` -> `google-cloud-assured-workloads`.
The name is used to identify the library in request headers so it is somewhat important.
https://github.com/googleapis/gapic-generator-python/blob/af17501d258c7c37fc1081fcad5fe18f7629f4c3/gapic/templates/%25namespace/%25name_%25version/%25sub/services/%25service/transports/base.py.j2#L29-L33
CC @crwilcox
|
0.0
|
39be474b4419dfa521ef51927fd36dbf257d68e3
|
[
"tests/unit/generator/test_options.py::test_options_warehouse_package_name",
"tests/unit/schema/test_naming.py::test_cli_override_warehouse_package_name"
] |
[
"tests/unit/generator/test_options.py::test_options_empty",
"tests/unit/generator/test_options.py::test_options_replace_templates",
"tests/unit/generator/test_options.py::test_options_relative_templates",
"tests/unit/generator/test_options.py::test_options_unrecognized",
"tests/unit/generator/test_options.py::test_flags_unrecognized",
"tests/unit/generator/test_options.py::test_options_unrecognized_likely_typo",
"tests/unit/generator/test_options.py::test_options_trim_whitespace",
"tests/unit/generator/test_options.py::test_options_lazy_import",
"tests/unit/generator/test_options.py::test_options_old_naming",
"tests/unit/generator/test_options.py::test_options_add_iam_methods",
"tests/unit/schema/test_naming.py::test_long_name",
"tests/unit/schema/test_naming.py::test_module_name",
"tests/unit/schema/test_naming.py::test_versioned_module_name_no_version",
"tests/unit/schema/test_naming.py::test_versioned_module_name",
"tests/unit/schema/test_naming.py::test_namespace_packages",
"tests/unit/schema/test_naming.py::test_warehouse_package_name_no_namespace",
"tests/unit/schema/test_naming.py::test_warehouse_package_name_with_namespace",
"tests/unit/schema/test_naming.py::test_warehouse_package_name_multiple_words",
"tests/unit/schema/test_naming.py::test_build_no_annotations",
"tests/unit/schema/test_naming.py::test_build_no_annotations_no_version",
"tests/unit/schema/test_naming.py::test_build_no_namespace",
"tests/unit/schema/test_naming.py::test_inconsistent_package_error",
"tests/unit/schema/test_naming.py::test_subpackages",
"tests/unit/schema/test_naming.py::test_cli_override_name",
"tests/unit/schema/test_naming.py::test_cli_override_name_underscores",
"tests/unit/schema/test_naming.py::test_cli_override_namespace",
"tests/unit/schema/test_naming.py::test_cli_override_namespace_dotted",
"tests/unit/schema/test_naming.py::test_cli_override_name_and_namespace",
"tests/unit/schema/test_naming.py::test_cli_override_name_and_namespace_versionless",
"tests/unit/schema/test_naming.py::test_build_factory"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-12-22 01:18:07+00:00
|
apache-2.0
| 2,615 |
|
googleapis__google-resumable-media-python-343
|
diff --git a/google/resumable_media/_upload.py b/google/resumable_media/_upload.py
index b4eac56..c681cc0 100644
--- a/google/resumable_media/_upload.py
+++ b/google/resumable_media/_upload.py
@@ -794,14 +794,8 @@ class ResumableUpload(UploadBase):
The headers **do not** incorporate the ``_headers`` on the
current instance.
- Raises:
- ValueError: If the current upload is not in an invalid state.
-
.. _sans-I/O: https://sans-io.readthedocs.io/
"""
- if not self.invalid:
- raise ValueError("Upload is not in invalid state, no need to recover.")
-
headers = {_helpers.CONTENT_RANGE_HEADER: "bytes */*"}
return _PUT, self.resumable_url, None, headers
diff --git a/google/resumable_media/requests/upload.py b/google/resumable_media/requests/upload.py
index b565d7a..0649001 100644
--- a/google/resumable_media/requests/upload.py
+++ b/google/resumable_media/requests/upload.py
@@ -517,14 +517,15 @@ class ResumableUpload(_request_helpers.RequestsMixin, _upload.ResumableUpload):
)
def recover(self, transport):
- """Recover from a failure.
-
- This method should be used when a :class:`ResumableUpload` is in an
- :attr:`~ResumableUpload.invalid` state due to a request failure.
+ """Recover from a failure and check the status of the current upload.
This will verify the progress with the server and make sure the
current upload is in a valid state before :meth:`transmit_next_chunk`
- can be used again.
+ can be used again. See https://cloud.google.com/storage/docs/performing-resumable-uploads#status-check
+ for more information.
+
+ This method can be used when a :class:`ResumableUpload` is in an
+ :attr:`~ResumableUpload.invalid` state due to a request failure.
Args:
transport (~requests.Session): A ``requests`` object which can
|
googleapis/google-resumable-media-python
|
942665f1bb01d2efb604e0be52736690160973b9
|
diff --git a/tests/unit/test__upload.py b/tests/unit/test__upload.py
index 110ed77..db943d9 100644
--- a/tests/unit/test__upload.py
+++ b/tests/unit/test__upload.py
@@ -951,8 +951,13 @@ class TestResumableUpload(object):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
assert not upload.invalid
- with pytest.raises(ValueError):
- upload._prepare_recover_request()
+ method, url, payload, headers = upload._prepare_recover_request()
+ assert method == "PUT"
+ assert url == upload.resumable_url
+ assert payload is None
+ assert headers == {"content-range": "bytes */*"}
+ # Make sure headers are untouched.
+ assert upload._headers == {}
def test__prepare_recover_request(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
|
After retry limit reached, ResumableUpload.transmit_next_chunk propagates exception with invalid==False
The code below with comments probably best describes the issue... it shows two workarounds. A third workaround (not shown) might be to look for a retry timeout exception and assume the ResumableUpload is invalid despite it being in a recoverable state in my various tests. I'm wondering if a call to _make_invalid upon final retry limit reached is reasonable, or perhaps documenting implied invalidity after retry limit though the latter would seem odd since a retry limit having been reached is not equivalent to a non-recoverable state.
```
upload = ResumableUpload(upload_url, chunk_size)
response = upload.initiate(transport=session,
stream=stream,
metadata=metadata,
content_type="application/octet-stream",
stream_final=False)
while not upload.finished:
try:
pos_before_xmit = stream.tell()
upload.transmit_next_chunk(session)
except Exception as ex:
bytes_attempted = stream.tell() - pos_before_xmit
"""
#
# I first tried the following which skips recover
# and jumps back to transmit_next_chunk above.
# Without this, transmit_next_chunk fails. This
# seems somewhat equivalent to continuing
# above with retry reset.
#
if not upload.invalid:
stream.seek(pos_before_xmit, io.SEEK_SET)
else:
r = upload.recover(session)
"""
#
# After looking at internals, I tried this which
# also worked. Without the _make_invalid call,
# recover fails and the stream is not rewound,
# causing transmit_next_chunk to fail.
#
if not upload.invalid:
upload._make_invalid() # not really supposed to be called by users.
r = upload.recover(session)
# etc.
```
An aside, thanks to authors/contribs who created ResumableUpload.
|
0.0
|
942665f1bb01d2efb604e0be52736690160973b9
|
[
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_recover_request_not_invalid"
] |
[
"tests/unit/test__upload.py::TestUploadBase::test_constructor_defaults",
"tests/unit/test__upload.py::TestUploadBase::test_constructor_explicit",
"tests/unit/test__upload.py::TestUploadBase::test_finished_property",
"tests/unit/test__upload.py::TestUploadBase::test__process_response_bad_status",
"tests/unit/test__upload.py::TestUploadBase::test__process_response",
"tests/unit/test__upload.py::TestUploadBase::test__get_status_code",
"tests/unit/test__upload.py::TestUploadBase::test__get_headers",
"tests/unit/test__upload.py::TestUploadBase::test__get_body",
"tests/unit/test__upload.py::TestSimpleUpload::test__prepare_request_already_finished",
"tests/unit/test__upload.py::TestSimpleUpload::test__prepare_request_non_bytes_data",
"tests/unit/test__upload.py::TestSimpleUpload::test__prepare_request",
"tests/unit/test__upload.py::TestSimpleUpload::test__prepare_request_with_headers",
"tests/unit/test__upload.py::TestSimpleUpload::test_transmit",
"tests/unit/test__upload.py::TestMultipartUpload::test_constructor_defaults",
"tests/unit/test__upload.py::TestMultipartUpload::test_constructor_explicit",
"tests/unit/test__upload.py::TestMultipartUpload::test__prepare_request_already_finished",
"tests/unit/test__upload.py::TestMultipartUpload::test__prepare_request_non_bytes_data",
"tests/unit/test__upload.py::TestMultipartUpload::test__prepare_request",
"tests/unit/test__upload.py::TestMultipartUpload::test__prepare_request_with_headers",
"tests/unit/test__upload.py::TestMultipartUpload::test__prepare_request_with_checksum[md5]",
"tests/unit/test__upload.py::TestMultipartUpload::test__prepare_request_with_checksum[crc32c]",
"tests/unit/test__upload.py::TestMultipartUpload::test__prepare_request_with_checksum_overwrite[md5]",
"tests/unit/test__upload.py::TestMultipartUpload::test__prepare_request_with_checksum_overwrite[crc32c]",
"tests/unit/test__upload.py::TestMultipartUpload::test_transmit",
"tests/unit/test__upload.py::TestResumableUpload::test_constructor",
"tests/unit/test__upload.py::TestResumableUpload::test_constructor_bad_chunk_size",
"tests/unit/test__upload.py::TestResumableUpload::test_invalid_property",
"tests/unit/test__upload.py::TestResumableUpload::test_chunk_size_property",
"tests/unit/test__upload.py::TestResumableUpload::test_resumable_url_property",
"tests/unit/test__upload.py::TestResumableUpload::test_bytes_uploaded_property",
"tests/unit/test__upload.py::TestResumableUpload::test_total_bytes_property",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_initiate_request",
"tests/unit/test__upload.py::TestResumableUpload::test_prepare_initiate_request_with_signed_url",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_initiate_request_with_headers",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_initiate_request_known_size",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_initiate_request_unknown_size",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_initiate_request_already_initiated",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_initiate_request_bad_stream_position",
"tests/unit/test__upload.py::TestResumableUpload::test__process_initiate_response_non_200",
"tests/unit/test__upload.py::TestResumableUpload::test__process_initiate_response",
"tests/unit/test__upload.py::TestResumableUpload::test_initiate",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_request_already_finished",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_request_invalid",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_request_not_initiated",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_request_invalid_stream_state",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_request_success",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_request_success_with_headers",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_request_with_checksum[md5]",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_request_with_checksum[crc32c]",
"tests/unit/test__upload.py::TestResumableUpload::test__update_checksum[md5]",
"tests/unit/test__upload.py::TestResumableUpload::test__update_checksum[crc32c]",
"tests/unit/test__upload.py::TestResumableUpload::test__update_checksum_rewind[md5]",
"tests/unit/test__upload.py::TestResumableUpload::test__update_checksum_rewind[crc32c]",
"tests/unit/test__upload.py::TestResumableUpload::test__update_checksum_none",
"tests/unit/test__upload.py::TestResumableUpload::test__update_checksum_invalid",
"tests/unit/test__upload.py::TestResumableUpload::test__make_invalid",
"tests/unit/test__upload.py::TestResumableUpload::test__process_resumable_response_bad_status",
"tests/unit/test__upload.py::TestResumableUpload::test__process_resumable_response_success",
"tests/unit/test__upload.py::TestResumableUpload::test__process_resumable_response_partial_no_range",
"tests/unit/test__upload.py::TestResumableUpload::test__process_resumable_response_partial_bad_range",
"tests/unit/test__upload.py::TestResumableUpload::test__process_resumable_response_partial",
"tests/unit/test__upload.py::TestResumableUpload::test__validate_checksum_success[md5]",
"tests/unit/test__upload.py::TestResumableUpload::test__validate_checksum_success[crc32c]",
"tests/unit/test__upload.py::TestResumableUpload::test__validate_checksum_none",
"tests/unit/test__upload.py::TestResumableUpload::test__validate_checksum_header_no_match[md5]",
"tests/unit/test__upload.py::TestResumableUpload::test__validate_checksum_header_no_match[crc32c]",
"tests/unit/test__upload.py::TestResumableUpload::test__validate_checksum_mismatch[md5]",
"tests/unit/test__upload.py::TestResumableUpload::test__validate_checksum_mismatch[crc32c]",
"tests/unit/test__upload.py::TestResumableUpload::test_transmit_next_chunk",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_recover_request",
"tests/unit/test__upload.py::TestResumableUpload::test__prepare_recover_request_with_headers",
"tests/unit/test__upload.py::TestResumableUpload::test__process_recover_response_bad_status",
"tests/unit/test__upload.py::TestResumableUpload::test__process_recover_response_no_range",
"tests/unit/test__upload.py::TestResumableUpload::test__process_recover_response_bad_range",
"tests/unit/test__upload.py::TestResumableUpload::test__process_recover_response_with_range",
"tests/unit/test__upload.py::TestResumableUpload::test_recover",
"tests/unit/test__upload.py::test_get_boundary",
"tests/unit/test__upload.py::Test_construct_multipart_request::test_binary",
"tests/unit/test__upload.py::Test_construct_multipart_request::test_unicode",
"tests/unit/test__upload.py::test_get_total_bytes",
"tests/unit/test__upload.py::Test_get_next_chunk::test_exhausted_known_size",
"tests/unit/test__upload.py::Test_get_next_chunk::test_exhausted_known_size_zero",
"tests/unit/test__upload.py::Test_get_next_chunk::test_exhausted_known_size_zero_nonempty",
"tests/unit/test__upload.py::Test_get_next_chunk::test_success_known_size_lt_stream_size",
"tests/unit/test__upload.py::Test_get_next_chunk::test_success_known_size",
"tests/unit/test__upload.py::Test_get_next_chunk::test_success_unknown_size",
"tests/unit/test__upload.py::Test_get_content_range::test_known_size",
"tests/unit/test__upload.py::Test_get_content_range::test_unknown_size"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-07-14 21:50:01+00:00
|
apache-2.0
| 2,616 |
|
googleapis__proto-plus-python-348
|
diff --git a/proto/marshal/marshal.py b/proto/marshal/marshal.py
index bd21cbc..e9fbbb9 100644
--- a/proto/marshal/marshal.py
+++ b/proto/marshal/marshal.py
@@ -159,6 +159,22 @@ class BaseMarshal:
for rule_class in stringy_numbers.STRINGY_NUMBER_RULES:
self.register(rule_class._proto_type, rule_class())
+ def get_rule(self, proto_type):
+ # Rules are needed to convert values between proto-plus and pb.
+ # Retrieve the rule for the specified proto type.
+ # The NoopRule will be used when a rule is not found.
+ rule = self._rules.get(proto_type, self._noop)
+
+ # If we don't find a rule, also check under `_instances`
+ # in case there is a rule in another package.
+ # See https://github.com/googleapis/proto-plus-python/issues/349
+ if rule == self._noop and hasattr(self, "_instances"):
+ for _, instance in self._instances.items():
+ rule = instance._rules.get(proto_type, self._noop)
+ if rule != self._noop:
+ break
+ return rule
+
def to_python(self, proto_type, value, *, absent: bool = None):
# Internal protobuf has its own special type for lists of values.
# Return a view around it that implements MutableSequence.
@@ -174,10 +190,7 @@ class BaseMarshal:
# Same thing for maps of messages.
if value_type in compat.map_composite_types:
return MapComposite(value, marshal=self)
-
- # Convert ordinary values.
- rule = self._rules.get(proto_type, self._noop)
- return rule.to_python(value, absent=absent)
+ return self.get_rule(proto_type=proto_type).to_python(value, absent=absent)
def to_proto(self, proto_type, value, *, strict: bool = False):
# The protos in google/protobuf/struct.proto are exceptional cases,
@@ -212,9 +225,7 @@ class BaseMarshal:
recursive_type = type(proto_type().value)
return {k: self.to_proto(recursive_type, v) for k, v in value.items()}
- # Convert ordinary values.
- rule = self._rules.get(proto_type, self._noop)
- pb_value = rule.to_proto(value)
+ pb_value = self.get_rule(proto_type=proto_type).to_proto(value)
# Sanity check: If we are in strict mode, did we get the value we want?
if strict and not isinstance(pb_value, proto_type):
|
googleapis/proto-plus-python
|
9270fe5979f062b32ab71dbdf2650e6aca4c291d
|
diff --git a/tests/test_modules.py b/tests/test_modules.py
index 79a99da..7ab0e88 100644
--- a/tests/test_modules.py
+++ b/tests/test_modules.py
@@ -36,6 +36,38 @@ def test_module_package():
del sys.modules[__name__].__protobuf__
+def test_module_package_cross_api():
+ sys.modules[__name__].__protobuf__ = proto.module(package="spam.eggs.v1")
+ try:
+
+ class Baz(proto.Message):
+ foo = proto.RepeatedField(proto.INT64, number=1)
+
+ marshal = proto.Marshal(name="spam.eggs.v1")
+
+ assert Baz.meta.package == "spam.eggs.v1"
+ assert Baz.pb() in marshal._rules
+
+ sys.modules[__name__].__protobuf__ = proto.module(package="ham.pancakes.v1")
+
+ class AnotherMessage(proto.Message):
+ qux = proto.Field(proto.MESSAGE, number=1, message=Baz)
+
+ marshal = proto.Marshal(name="ham.pancakes.v1")
+
+ assert AnotherMessage.meta.package == "ham.pancakes.v1"
+ assert AnotherMessage.pb() in marshal._rules
+ # Confirm that Baz.pb() is no longer present in marshal._rules
+ assert Baz.pb() not in marshal._rules
+
+ # Test using multiple packages together
+ # See https://github.com/googleapis/proto-plus-python/issues/349.
+ msg = AnotherMessage(qux=Baz())
+ assert type(msg) == AnotherMessage
+ finally:
+ del sys.modules[__name__].__protobuf__
+
+
def test_module_package_explicit_marshal():
sys.modules[__name__].__protobuf__ = proto.module(
package="spam.eggs.v1",
|
Marshal fails with TypeError when using cross api message
See test code here https://github.com/googleapis/proto-plus-python/pull/348/commits/e123ad8813823c477d1ff1494a1c6c1ba85bff89, with corresponding failure [here](https://github.com/googleapis/proto-plus-python/actions/runs/4426034682/jobs/7761831001).
See the full stack trace below
```
________________________ test_module_package_cross_api _________________________
def test_module_package_cross_api():
sys.modules[__name__].__protobuf__ = proto.module(package="spam.eggs.v1")
try:
class Baz(proto.Message):
foo = proto.RepeatedField(proto.INT64, number=1)
marshal = proto.Marshal(name="spam.eggs.v1")
assert Baz.meta.package == "spam.eggs.v1"
assert Baz.pb() in marshal._rules
sys.modules[__name__].__protobuf__ = proto.module(package="ham.pancakes.v1")
class AnotherMessage(proto.Message):
qux = proto.Field(proto.MESSAGE, number=1, message=Baz)
marshal = proto.Marshal(name="ham.pancakes.v1")
assert AnotherMessage.meta.package == "ham.pancakes.v1"
assert AnotherMessage.pb() in marshal._rules
# Confirm that Baz.pb() is no longer present in marshal._rules
assert Baz.pb() not in marshal._rules
# Test using multiple packages together
> msg = AnotherMessage(qux=Baz())
tests/test_modules.py:65:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <[AttributeError('Unknown field for AnotherMessage: _pb') raised in repr()] AnotherMessage object at 0x7f112bbc07d0>
mapping = {'qux': }, ignore_unknown_fields = False, kwargs = {'qux': }
params = {'qux': }
marshal = <proto.marshal.marshal.Marshal object at 0x7f112bbc0910>, key = 'qux'
value = , pb_value =
def __init__(
self,
mapping=None,
*,
ignore_unknown_fields=False,
**kwargs,
):
# We accept several things for `mapping`:
# * An instance of this class.
# * An instance of the underlying protobuf descriptor class.
# * A dict
# * Nothing (keyword arguments only).
if mapping is None:
if not kwargs:
# Special fast path for empty construction.
super().__setattr__("_pb", self._meta.pb())
return
mapping = kwargs
elif isinstance(mapping, self._meta.pb):
# Make a copy of the mapping.
# This is a constructor for a new object, so users will assume
# that it will not have side effects on the arguments being
# passed in.
#
# The `wrap` method on the metaclass is the public API for taking
# ownership of the passed in protobuf object.
mapping = copy.deepcopy(mapping)
if kwargs:
mapping.MergeFrom(self._meta.pb(**kwargs))
super().__setattr__("_pb", mapping)
return
elif isinstance(mapping, type(self)):
# Just use the above logic on mapping's underlying pb.
self.__init__(mapping=mapping._pb, **kwargs)
return
elif isinstance(mapping, collections.abc.Mapping):
# Can't have side effects on mapping.
mapping = copy.copy(mapping)
# kwargs entries take priority for duplicate keys.
mapping.update(kwargs)
else:
# Sanity check: Did we get something not a map? Error if so.
raise TypeError(
"Invalid constructor input for %s: %r"
% (
self.__class__.__name__,
mapping,
)
)
params = {}
# Update the mapping to address any values that need to be
# coerced.
marshal = self._meta.marshal
for key, value in mapping.items():
(key, pb_type) = self._get_pb_type_from_key(key)
if pb_type is None:
if ignore_unknown_fields:
continue
raise ValueError(
"Unknown field for {}: {}".format(self.__class__.__name__, key)
)
try:
pb_value = marshal.to_proto(pb_type, value)
except ValueError:
# Underscores may be appended to field names
# that collide with python or proto-plus keywords.
# In case a key only exists with a `_` suffix, coerce the key
# to include the `_` suffix. It's not possible to
# natively define the same field with a trailing underscore in protobuf.
# See related issue
# https://github.com/googleapis/python-api-core/issues/2[27](https://github.com/googleapis/proto-plus-python/actions/runs/4426034682/jobs/7761831001#step:6:28)
if isinstance(value, dict):
if _upb:
# In UPB, pb_type is MessageMeta which doesn't expose attrs like it used to in Python/CPP.
keys_to_update = [
item
for item in value
if item not in pb_type.DESCRIPTOR.fields_by_name
and f"{item}_" in pb_type.DESCRIPTOR.fields_by_name
]
else:
keys_to_update = [
item
for item in value
if not hasattr(pb_type, item)
and hasattr(pb_type, f"{item}_")
]
for item in keys_to_update:
value[f"{item}_"] = value.pop(item)
pb_value = marshal.to_proto(pb_type, value)
if pb_value is not None:
params[key] = pb_value
# Create the internal protocol buffer.
> super().__setattr__("_pb", self._meta.pb(**params))
E TypeError: Parameter to MergeFrom() must be instance of same class: expected spam.eggs.v1.Baz got Baz.
proto/message.py:[60](https://github.com/googleapis/proto-plus-python/actions/runs/4426034682/jobs/7761831001#step:6:61)4: TypeError
```
|
0.0
|
9270fe5979f062b32ab71dbdf2650e6aca4c291d
|
[
"tests/test_modules.py::test_module_package_cross_api"
] |
[
"tests/test_modules.py::test_module_package",
"tests/test_modules.py::test_module_package_explicit_marshal",
"tests/test_modules.py::test_module_manifest"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-07 22:51:55+00:00
|
apache-2.0
| 2,617 |
|
googleapis__python-api-core-155
|
diff --git a/google/api_core/iam.py b/google/api_core/iam.py
index f130936..d83cbf3 100644
--- a/google/api_core/iam.py
+++ b/google/api_core/iam.py
@@ -136,7 +136,10 @@ class Policy(collections_abc.MutableMapping):
for b in self._bindings:
if b["role"] == key:
return b["members"]
- return set()
+ # binding does not yet exist, create one
+ new_binding = {"role": key, "members": set()}
+ self._bindings.append(new_binding)
+ return new_binding["members"]
def __setitem__(self, key, value):
self.__check_version__()
|
googleapis/python-api-core
|
b4860fec797f7d9f02a7241b2b6cef2d27f96f28
|
diff --git a/tests/unit/test_iam.py b/tests/unit/test_iam.py
index 896e10d..f9771f0 100644
--- a/tests/unit/test_iam.py
+++ b/tests/unit/test_iam.py
@@ -32,11 +32,11 @@ class TestPolicy:
policy = self._make_one()
assert policy.etag is None
assert policy.version is None
+ assert len(policy) == 0
+ assert dict(policy) == {}
assert policy.owners == empty
assert policy.editors == empty
assert policy.viewers == empty
- assert len(policy) == 0
- assert dict(policy) == {}
def test_ctor_explicit(self):
VERSION = 1
@@ -45,16 +45,24 @@ class TestPolicy:
policy = self._make_one(ETAG, VERSION)
assert policy.etag == ETAG
assert policy.version == VERSION
+ assert len(policy) == 0
+ assert dict(policy) == {}
assert policy.owners == empty
assert policy.editors == empty
assert policy.viewers == empty
- assert len(policy) == 0
- assert dict(policy) == {}
def test___getitem___miss(self):
policy = self._make_one()
assert policy["nonesuch"] == set()
+ def test__getitem___and_set(self):
+ from google.api_core.iam import OWNER_ROLE
+ policy = self._make_one()
+
+ # get the policy using the getter and then modify it
+ policy[OWNER_ROLE].add("user:[email protected]")
+ assert dict(policy) == {OWNER_ROLE: {"user:[email protected]"}}
+
def test___getitem___version3(self):
policy = self._make_one("DEADBEEF", 3)
with pytest.raises(InvalidOperationException, match=_DICT_ACCESS_MSG):
@@ -293,10 +301,10 @@ class TestPolicy:
policy = klass.from_api_repr(RESOURCE)
assert policy.etag == "ACAB"
assert policy.version is None
+ assert dict(policy) == {}
assert policy.owners == empty
assert policy.editors == empty
assert policy.viewers == empty
- assert dict(policy) == {}
def test_from_api_repr_complete(self):
from google.api_core.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE
|
google.api_core.iam.Policy.__getitem__ does not correctly save empty bindings
We recently tried to upgrade a tool from 1.15.0 to 1.26.1 and found it breaks some code that handles IAM policies. The commit that introduces the bug was released in 1.16.0: https://github.com/googleapis/python-api-core/commit/fd47fda5e3f5eca63522c8d81cffa22bc2a29ab6#diff-7cc73ea72342c139ff54060be9ff25b2f792f9225e0cc0f501dca9dbed9c4741 -
The new `__getitem__` implementation returns a new empty `set()` for roles not in the current policy. But it doesn't save that set in the bindings. So if the user manipulates it, the policy isn't actually updated. That breaks code written like this:
```python
policy = resource.get_iam_policy()
policy['roles/storage.objectAdmin'].add(principal)
bucket.set_iam_policy(policy)
```
This worked fine on v1.15.0 because of the use of `defaultdict`. But now, this adds the principal to a set that's not used by the policy.
Something like the following (untested) patch should do the trick:
```diff
diff --git a/google/api_core/iam.py b/google/api_core/iam.py
index f130936..d650336 100644
--- a/google/api_core/iam.py
+++ b/google/api_core/iam.py
@@ -136,7 +136,9 @@ class Policy(collections_abc.MutableMapping):
for b in self._bindings:
if b["role"] == key:
return b["members"]
- return set()
+
+ self[key] = set()
+ return self[key]
def __setitem__(self, key, value):
self.__check_version__()
```
|
0.0
|
b4860fec797f7d9f02a7241b2b6cef2d27f96f28
|
[
"tests/unit/test_iam.py::TestPolicy::test__getitem___and_set"
] |
[
"tests/unit/test_iam.py::TestPolicy::test_ctor_defaults",
"tests/unit/test_iam.py::TestPolicy::test_ctor_explicit",
"tests/unit/test_iam.py::TestPolicy::test___getitem___miss",
"tests/unit/test_iam.py::TestPolicy::test___getitem___version3",
"tests/unit/test_iam.py::TestPolicy::test___getitem___with_conditions",
"tests/unit/test_iam.py::TestPolicy::test___setitem__",
"tests/unit/test_iam.py::TestPolicy::test__set_item__overwrite",
"tests/unit/test_iam.py::TestPolicy::test___setitem___version3",
"tests/unit/test_iam.py::TestPolicy::test___setitem___with_conditions",
"tests/unit/test_iam.py::TestPolicy::test___delitem___hit",
"tests/unit/test_iam.py::TestPolicy::test___delitem___miss",
"tests/unit/test_iam.py::TestPolicy::test___delitem___version3",
"tests/unit/test_iam.py::TestPolicy::test___delitem___with_conditions",
"tests/unit/test_iam.py::TestPolicy::test_bindings_property",
"tests/unit/test_iam.py::TestPolicy::test_owners_getter",
"tests/unit/test_iam.py::TestPolicy::test_editors_getter",
"tests/unit/test_iam.py::TestPolicy::test_viewers_getter",
"tests/unit/test_iam.py::TestPolicy::test_from_api_repr_only_etag",
"tests/unit/test_iam.py::TestPolicy::test_from_api_repr_complete",
"tests/unit/test_iam.py::TestPolicy::test_from_api_repr_unknown_role",
"tests/unit/test_iam.py::TestPolicy::test_to_api_repr_defaults",
"tests/unit/test_iam.py::TestPolicy::test_to_api_repr_only_etag",
"tests/unit/test_iam.py::TestPolicy::test_to_api_repr_binding_wo_members",
"tests/unit/test_iam.py::TestPolicy::test_to_api_repr_binding_w_duplicates",
"tests/unit/test_iam.py::TestPolicy::test_to_api_repr_full"
] |
{
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-22 21:52:23+00:00
|
apache-2.0
| 2,618 |
|
googleapis__python-api-core-17
|
diff --git a/google/api_core/client_options.py b/google/api_core/client_options.py
index 137043f..7cb49c6 100644
--- a/google/api_core/client_options.py
+++ b/google/api_core/client_options.py
@@ -24,7 +24,12 @@ You can pass a client options object to a client.
from google.api_core.client_options import ClientOptions
from google.cloud.vision_v1 import ImageAnnotatorClient
- options = ClientOptions(api_endpoint="foo.googleapis.com")
+ def get_client_cert():
+ # code to load client certificate and private key.
+ return client_cert_bytes, client_private_key_bytes
+
+ options = ClientOptions(api_endpoint="foo.googleapis.com",
+ client_cert_source=get_client_cert)
client = ImageAnnotatorClient(client_options=options)
@@ -34,7 +39,11 @@ You can also pass a dictionary.
from google.cloud.vision_v1 import ImageAnnotatorClient
- client = ImageAnnotatorClient(client_options={"api_endpoint": "foo.googleapis.com"})
+ client = ImageAnnotatorClient(
+ client_options={
+ "api_endpoint": "foo.googleapis.com",
+ "client_cert_source" : get_client_cert
+ })
"""
@@ -45,10 +54,14 @@ class ClientOptions(object):
Args:
api_endpoint (str): The desired API endpoint, e.g., compute.googleapis.com
+ client_cert_source (Callable[[], (bytes, bytes)]): An optional callback
+ which returns client certificate bytes and private key bytes both in
+ PEM format.
"""
- def __init__(self, api_endpoint=None):
+ def __init__(self, api_endpoint=None, client_cert_source=None):
self.api_endpoint = api_endpoint
+ self.client_cert_source = client_cert_source
def __repr__(self):
return "ClientOptions: " + repr(self.__dict__)
diff --git a/noxfile.py b/noxfile.py
index 249ace7..dfb1257 100644
--- a/noxfile.py
+++ b/noxfile.py
@@ -112,7 +112,7 @@ def docs(session):
session.install(".", "grpcio >= 1.8.2", "grpcio-gcp >= 0.2.2")
session.install("-e", ".")
- session.install("sphinx", "alabaster", "recommonmark")
+ session.install("sphinx < 3.0", "alabaster", "recommonmark")
shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True)
session.run(
diff --git a/setup.py b/setup.py
index 820d5f4..30f83a6 100644
--- a/setup.py
+++ b/setup.py
@@ -31,7 +31,7 @@ release_status = "Development Status :: 5 - Production/Stable"
dependencies = [
"googleapis-common-protos >= 1.6.0, < 2.0dev",
"protobuf >= 3.4.0",
- "google-auth >= 0.4.0, < 2.0dev",
+ "google-auth >= 1.14.0, < 2.0dev",
"requests >= 2.18.0, < 3.0.0dev",
"setuptools >= 34.0.0",
"six >= 1.10.0",
|
googleapis/python-api-core
|
0c2c556e149b0b6696b515f3cdbd10a698b4e30b
|
diff --git a/tests/unit/test_client_options.py b/tests/unit/test_client_options.py
index 952adfc..7f17544 100644
--- a/tests/unit/test_client_options.py
+++ b/tests/unit/test_client_options.py
@@ -17,26 +17,46 @@ import pytest
from google.api_core import client_options
+def get_client_cert():
+ return b"cert", b"key"
+
+
def test_constructor():
- options = client_options.ClientOptions(api_endpoint="foo.googleapis.com")
+
+ options = client_options.ClientOptions(
+ api_endpoint="foo.googleapis.com", client_cert_source=get_client_cert
+ )
assert options.api_endpoint == "foo.googleapis.com"
+ assert options.client_cert_source() == (b"cert", b"key")
def test_from_dict():
- options = client_options.from_dict({"api_endpoint": "foo.googleapis.com"})
+ options = client_options.from_dict(
+ {"api_endpoint": "foo.googleapis.com", "client_cert_source": get_client_cert}
+ )
assert options.api_endpoint == "foo.googleapis.com"
+ # assert options.client_cert_source == get_client_cert
+ assert options.client_cert_source() == (b"cert", b"key")
def test_from_dict_bad_argument():
with pytest.raises(ValueError):
client_options.from_dict(
- {"api_endpoint": "foo.googleapis.com", "bad_arg": "1234"}
+ {
+ "api_endpoint": "foo.googleapis.com",
+ "bad_arg": "1234",
+ "client_cert_source": get_client_cert,
+ }
)
def test_repr():
options = client_options.ClientOptions(api_endpoint="foo.googleapis.com")
- assert repr(options) == "ClientOptions: {'api_endpoint': 'foo.googleapis.com'}"
+ assert (
+ repr(options)
+ == "ClientOptions: {'api_endpoint': 'foo.googleapis.com', 'client_cert_source': None}"
+ or "ClientOptions: {'client_cert_source': None, 'api_endpoint': 'foo.googleapis.com'}"
+ )
|
add client_cert_source to ClientOptions
google-api-go-client uses `WithClientCertSource` in `ClientOptions` to provide client cert/key, we need to add a `client_cert_source` to `ClientOptions` in python as well.
|
0.0
|
0c2c556e149b0b6696b515f3cdbd10a698b4e30b
|
[
"tests/unit/test_client_options.py::test_constructor",
"tests/unit/test_client_options.py::test_from_dict"
] |
[
"tests/unit/test_client_options.py::test_from_dict_bad_argument",
"tests/unit/test_client_options.py::test_repr"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-03-30 22:12:24+00:00
|
apache-2.0
| 2,619 |
|
googleapis__python-api-core-546
|
diff --git a/google/api_core/client_options.py b/google/api_core/client_options.py
index ee9f28a..e93f958 100644
--- a/google/api_core/client_options.py
+++ b/google/api_core/client_options.py
@@ -75,6 +75,11 @@ class ClientOptions(object):
authentication flows. Audience is typically a resource identifier.
If not set, the service endpoint value will be used as a default.
An example of a valid ``api_audience`` is: "https://language.googleapis.com".
+ universe_domain (Optional[str]): The desired universe domain. This must match
+ the one in credentials. If not set, the default universe domain is
+ `googleapis.com`. If both `api_endpoint` and `universe_domain` are set,
+ then `api_endpoint` is used as the service endpoint. If `api_endpoint` is
+ not specified, the format will be `{service}.{universe_domain}`.
Raises:
ValueError: If both ``client_cert_source`` and ``client_encrypted_cert_source``
@@ -91,6 +96,7 @@ class ClientOptions(object):
scopes=None,
api_key=None,
api_audience=None,
+ universe_domain=None,
):
if client_cert_source and client_encrypted_cert_source:
raise ValueError(
@@ -106,6 +112,7 @@ class ClientOptions(object):
self.scopes = scopes
self.api_key = api_key
self.api_audience = api_audience
+ self.universe_domain = universe_domain
def __repr__(self):
return "ClientOptions: " + repr(self.__dict__)
|
googleapis/python-api-core
|
fc12b40bfc6e0c4bb313196e2e3a9c9374ce1c45
|
diff --git a/tests/unit/test_client_options.py b/tests/unit/test_client_options.py
index 336ceea..396d662 100644
--- a/tests/unit/test_client_options.py
+++ b/tests/unit/test_client_options.py
@@ -38,6 +38,7 @@ def test_constructor():
"https://www.googleapis.com/auth/cloud-platform.read-only",
],
api_audience="foo2.googleapis.com",
+ universe_domain="googleapis.com",
)
assert options.api_endpoint == "foo.googleapis.com"
@@ -49,6 +50,7 @@ def test_constructor():
"https://www.googleapis.com/auth/cloud-platform.read-only",
]
assert options.api_audience == "foo2.googleapis.com"
+ assert options.universe_domain == "googleapis.com"
def test_constructor_with_encrypted_cert_source():
@@ -110,6 +112,7 @@ def test_from_dict():
options = client_options.from_dict(
{
"api_endpoint": "foo.googleapis.com",
+ "universe_domain": "googleapis.com",
"client_cert_source": get_client_cert,
"quota_project_id": "quote-proj",
"credentials_file": "path/to/credentials.json",
@@ -122,6 +125,7 @@ def test_from_dict():
)
assert options.api_endpoint == "foo.googleapis.com"
+ assert options.universe_domain == "googleapis.com"
assert options.client_cert_source() == (b"cert", b"key")
assert options.quota_project_id == "quote-proj"
assert options.credentials_file == "path/to/credentials.json"
@@ -148,6 +152,7 @@ def test_repr():
expected_keys = set(
[
"api_endpoint",
+ "universe_domain",
"client_cert_source",
"client_encrypted_cert_source",
"quota_project_id",
|
Feat: Add support for universe_domain as a client option for TPC
`universe_domain` is required as an optional field in `google.api_core.ClientOptions` to enable users to explicitly configure universe domain as a client option.
This will enable API endpoint to be resolved using a templated value if a universe domain is specified or otherwise default to GDU.
```python3
# user configures the universe domain:
client = Client(google.api_core.ClientOptions{universe_domain="foo.com"})
# api_endpoint points to the TPC universe:
api_endpoint = "service.foo.com"
```
```python3
# user does not configure the universe domain:
client = Client(google.api_core.ClientOptions{})
# api_endpoint defaults to GDU:
api_endpoint = "service.googleapis.com"
```
|
0.0
|
fc12b40bfc6e0c4bb313196e2e3a9c9374ce1c45
|
[
"tests/unit/test_client_options.py::test_constructor",
"tests/unit/test_client_options.py::test_from_dict",
"tests/unit/test_client_options.py::test_repr"
] |
[
"tests/unit/test_client_options.py::test_constructor_with_encrypted_cert_source",
"tests/unit/test_client_options.py::test_constructor_with_both_cert_sources",
"tests/unit/test_client_options.py::test_constructor_with_api_key",
"tests/unit/test_client_options.py::test_constructor_with_both_api_key_and_credentials_file",
"tests/unit/test_client_options.py::test_from_dict_bad_argument"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-11-06 19:13:45+00:00
|
apache-2.0
| 2,620 |
|
googleapis__python-api-core-621
|
diff --git a/google/api_core/universe.py b/google/api_core/universe.py
new file mode 100644
index 0000000..3566964
--- /dev/null
+++ b/google/api_core/universe.py
@@ -0,0 +1,82 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Helpers for universe domain."""
+
+from typing import Any, Optional
+
+DEFAULT_UNIVERSE = "googleapis.com"
+
+
+class EmptyUniverseError(ValueError):
+ def __init__(self):
+ message = "Universe Domain cannot be an empty string."
+ super().__init__(message)
+
+
+class UniverseMismatchError(ValueError):
+ def __init__(self, client_universe, credentials_universe):
+ message = (
+ f"The configured universe domain ({client_universe}) does not match the universe domain "
+ f"found in the credentials ({credentials_universe}). "
+ "If you haven't configured the universe domain explicitly, "
+ f"`{DEFAULT_UNIVERSE}` is the default."
+ )
+ super().__init__(message)
+
+
+def determine_domain(
+ client_universe_domain: Optional[str], universe_domain_env: Optional[str]
+) -> str:
+ """Return the universe domain used by the client.
+
+ Args:
+ client_universe_domain (Optional[str]): The universe domain configured via the client options.
+ universe_domain_env (Optional[str]): The universe domain configured via the
+ "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
+
+ Returns:
+ str: The universe domain to be used by the client.
+
+ Raises:
+ ValueError: If the universe domain is an empty string.
+ """
+ universe_domain = DEFAULT_UNIVERSE
+ if client_universe_domain is not None:
+ universe_domain = client_universe_domain
+ elif universe_domain_env is not None:
+ universe_domain = universe_domain_env
+ if len(universe_domain.strip()) == 0:
+ raise EmptyUniverseError
+ return universe_domain
+
+
+def compare_domains(client_universe: str, credentials: Any) -> bool:
+ """Returns True iff the universe domains used by the client and credentials match.
+
+ Args:
+ client_universe (str): The universe domain configured via the client options.
+ credentials Any: The credentials being used in the client.
+
+ Returns:
+ bool: True iff client_universe matches the universe in credentials.
+
+ Raises:
+ ValueError: when client_universe does not match the universe in credentials.
+ """
+ credentials_universe = getattr(credentials, "universe_domain", DEFAULT_UNIVERSE)
+
+ if client_universe != credentials_universe:
+ raise UniverseMismatchError(client_universe, credentials_universe)
+ return True
|
googleapis/python-api-core
|
4fed37cbc32122f156e38250b5fa8b2b08a787a1
|
diff --git a/tests/unit/test_universe.py b/tests/unit/test_universe.py
new file mode 100644
index 0000000..214e00a
--- /dev/null
+++ b/tests/unit/test_universe.py
@@ -0,0 +1,63 @@
+# Copyright 2024 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import pytest
+from google.api_core import universe
+
+
+class _Fake_Credentials:
+ def __init__(self, universe_domain=None):
+ if universe_domain:
+ self.universe_domain = universe_domain
+
+
+def test_determine_domain():
+ domain_client = "foo.com"
+ domain_env = "bar.com"
+
+ assert universe.determine_domain(domain_client, domain_env) == domain_client
+ assert universe.determine_domain(None, domain_env) == domain_env
+ assert universe.determine_domain(domain_client, None) == domain_client
+ assert universe.determine_domain(None, None) == universe.DEFAULT_UNIVERSE
+
+ with pytest.raises(universe.EmptyUniverseError):
+ universe.determine_domain("", None)
+
+ with pytest.raises(universe.EmptyUniverseError):
+ universe.determine_domain(None, "")
+
+
+def test_compare_domains():
+ fake_domain = "foo.com"
+ another_fake_domain = "bar.com"
+
+ assert universe.compare_domains(universe.DEFAULT_UNIVERSE, _Fake_Credentials())
+ assert universe.compare_domains(fake_domain, _Fake_Credentials(fake_domain))
+
+ with pytest.raises(universe.UniverseMismatchError) as excinfo:
+ universe.compare_domains(
+ universe.DEFAULT_UNIVERSE, _Fake_Credentials(fake_domain)
+ )
+ assert str(excinfo.value).find(universe.DEFAULT_UNIVERSE) >= 0
+ assert str(excinfo.value).find(fake_domain) >= 0
+
+ with pytest.raises(universe.UniverseMismatchError) as excinfo:
+ universe.compare_domains(fake_domain, _Fake_Credentials())
+ assert str(excinfo.value).find(fake_domain) >= 0
+ assert str(excinfo.value).find(universe.DEFAULT_UNIVERSE) >= 0
+
+ with pytest.raises(universe.UniverseMismatchError) as excinfo:
+ universe.compare_domains(fake_domain, _Fake_Credentials(another_fake_domain))
+ assert str(excinfo.value).find(fake_domain) >= 0
+ assert str(excinfo.value).find(another_fake_domain) >= 0
|
Add static code for supporting universe domain (to be used in both GAPICs and Apiary)
Universes other than the default `"googleapis.com"` need to be supported in both GAPICs and Apiary. The following code was added to GAPICs but can be moved to `python-api-core`:
```python3
def _get_universe_domain(
client_universe_domain: Optional[str], universe_domain_env: Optional[str]
) -> str: # temp disable Optional
"""Return the universe domain used by the client.
Args:
client_universe_domain (Optional[str]): The universe domain configured via the client options.
universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
Returns:
str: The universe domain to be used by the client.
Raises:
ValueError: If the universe domain is an empty string.
"""
universe_domain = _DEFAULT_UNIVERSE
if client_universe_domain is not None:
universe_domain = client_universe_domain
elif universe_domain_env is not None:
universe_domain = universe_domain_env
if len(universe_domain.strip()) == 0:
raise _Empty_Universe_Error
return universe_domain
def _compare_universes(
client_universe: str, credentials: Union[ga_credentials, oauth2_credentials]
) -> bool:
"""Returns True iff the universe domains used by the client and credentials match.
Args:
client_universe (str): The universe domain configured via the client options.
credentials Union[google.auth.credentials.Credentials, oauth2client.client.Credentials]: The credentials being used in the client.
Returns:
bool: True iff client_universe matches the universe in credentials.
Raises:
ValueError: when client_universe does not match the universe in credentials.
"""
credentials_universe = getattr(credentials, "universe_domain", _DEFAULT_UNIVERSE)
if client_universe != credentials_universe:
raise _UniverseMismatchError(client_universe, credentials_universe)
return True
```
|
0.0
|
4fed37cbc32122f156e38250b5fa8b2b08a787a1
|
[
"tests/unit/test_universe.py::test_determine_domain",
"tests/unit/test_universe.py::test_compare_domains"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-02-27 03:39:02+00:00
|
apache-2.0
| 2,621 |
|
googleapis__python-bigquery-66
|
diff --git a/google/cloud/bigquery/model.py b/google/cloud/bigquery/model.py
index d39ec5f2..a2510e86 100644
--- a/google/cloud/bigquery/model.py
+++ b/google/cloud/bigquery/model.py
@@ -430,6 +430,6 @@ class ModelReference(object):
return hash(self._key())
def __repr__(self):
- return "ModelReference(project='{}', dataset_id='{}', project_id='{}')".format(
+ return "ModelReference(project_id='{}', dataset_id='{}', model_id='{}')".format(
self.project, self.dataset_id, self.model_id
)
|
googleapis/python-bigquery
|
2abdef82bed31601d1ca1aa92a10fea1e09f5297
|
diff --git a/tests/unit/model/test_model.py b/tests/unit/model/test_model.py
index bbb93ef9..90fc09e6 100644
--- a/tests/unit/model/test_model.py
+++ b/tests/unit/model/test_model.py
@@ -316,5 +316,5 @@ def test_repr(target_class):
got = repr(model)
assert got == (
"Model(reference=ModelReference("
- "project='my-proj', dataset_id='my_dset', project_id='my_model'))"
+ "project_id='my-proj', dataset_id='my_dset', model_id='my_model'))"
)
diff --git a/tests/unit/model/test_model_reference.py b/tests/unit/model/test_model_reference.py
index ff1d1df7..39dabb55 100644
--- a/tests/unit/model/test_model_reference.py
+++ b/tests/unit/model/test_model_reference.py
@@ -136,5 +136,5 @@ def test_repr(target_class):
got = repr(model)
assert (
got
- == "ModelReference(project='my-proj', dataset_id='my_dset', project_id='my_model')"
+ == "ModelReference(project_id='my-proj', dataset_id='my_dset', model_id='my_model')"
)
|
Bigquery: Model reference repr seems wrong for model_id
For `ModelReference`'s repr use project_id against model_id
https://github.com/googleapis/python-bigquery/blob/be5c8b1ede9a2d762fd5574c32587d125eca4713/google/cloud/bigquery/model.py#L432-L435
|
0.0
|
2abdef82bed31601d1ca1aa92a10fea1e09f5297
|
[
"tests/unit/model/test_model.py::test_repr",
"tests/unit/model/test_model_reference.py::test_repr"
] |
[
"tests/unit/model/test_model.py::test_ctor",
"tests/unit/model/test_model.py::test_ctor_string",
"tests/unit/model/test_model.py::test_from_api_repr",
"tests/unit/model/test_model.py::test_from_api_repr_w_minimal_resource",
"tests/unit/model/test_model.py::test_from_api_repr_w_unknown_fields",
"tests/unit/model/test_model.py::test_build_resource[resource0-filter_fields0-expected0]",
"tests/unit/model/test_model.py::test_build_resource[resource1-filter_fields1-expected1]",
"tests/unit/model/test_model.py::test_build_resource[resource2-filter_fields2-expected2]",
"tests/unit/model/test_model.py::test_build_resource[resource3-filter_fields3-expected3]",
"tests/unit/model/test_model.py::test_build_resource[resource4-filter_fields4-expected4]",
"tests/unit/model/test_model.py::test_build_resource[resource5-filter_fields5-expected5]",
"tests/unit/model/test_model.py::test_set_description",
"tests/unit/model/test_model.py::test_set_expires",
"tests/unit/model/test_model.py::test_set_friendly_name",
"tests/unit/model/test_model.py::test_set_labels",
"tests/unit/model/test_model.py::test_replace_labels",
"tests/unit/model/test_model.py::test_set_encryption_configuration",
"tests/unit/model/test_model_reference.py::test_from_api_repr",
"tests/unit/model/test_model_reference.py::test_from_api_repr_w_unknown_fields",
"tests/unit/model/test_model_reference.py::test_to_api_repr",
"tests/unit/model/test_model_reference.py::test_from_string",
"tests/unit/model/test_model_reference.py::test_from_string_legacy_string",
"tests/unit/model/test_model_reference.py::test_from_string_not_fully_qualified",
"tests/unit/model/test_model_reference.py::test_from_string_with_default_project",
"tests/unit/model/test_model_reference.py::test_from_string_ignores_default_project",
"tests/unit/model/test_model_reference.py::test_eq",
"tests/unit/model/test_model_reference.py::test_hash"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-03-24 14:59:08+00:00
|
apache-2.0
| 2,622 |
|
googleapis__python-containeranalysis-251
|
diff --git a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/async_client.py b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/async_client.py
index e876c37..82e9826 100644
--- a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/async_client.py
+++ b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/async_client.py
@@ -221,9 +221,14 @@ class ContainerAnalysisAsyncClient:
)
def get_grafeas_client(self) -> grafeas_v1.GrafeasClient:
- transport = type(self).get_transport_class("grpc_asyncio")()
grafeas_transport = grafeas_v1.services.grafeas.transports.GrafeasGrpcTransport(
- host=transport._host, scopes=transport.AUTH_SCOPES
+ credentials=self.transport._credentials,
+ # Set ``credentials_file`` to ``None`` here as
+ # transport._credentials contains the credentials
+ # which are saved
+ credentials_file=None,
+ host=self.transport._host,
+ scopes=self.transport.AUTH_SCOPES,
)
return grafeas_v1.GrafeasClient(transport=grafeas_transport)
diff --git a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/client.py b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/client.py
index 83ec851..7884537 100644
--- a/google/cloud/devtools/containeranalysis_v1/services/container_analysis/client.py
+++ b/google/cloud/devtools/containeranalysis_v1/services/container_analysis/client.py
@@ -406,9 +406,14 @@ class ContainerAnalysisClient(metaclass=ContainerAnalysisClientMeta):
)
def get_grafeas_client(self) -> grafeas_v1.GrafeasClient:
- transport = type(self).get_transport_class("grpc")()
grafeas_transport = grafeas_v1.services.grafeas.transports.GrafeasGrpcTransport(
- host=transport._host, scopes=transport.AUTH_SCOPES
+ credentials=self.transport._credentials,
+ # Set ``credentials_file`` to ``None`` here as
+ # transport._credentials contains the credentials
+ # which are saved
+ credentials_file=None,
+ host=self.transport._host,
+ scopes=self.transport.AUTH_SCOPES,
)
return grafeas_v1.GrafeasClient(transport=grafeas_transport)
diff --git a/owlbot.py b/owlbot.py
index de2bcf1..2815408 100644
--- a/owlbot.py
+++ b/owlbot.py
@@ -69,10 +69,14 @@ for library in s.get_staging_dirs(default_version):
r'''\n\g<1>def get_grafeas_client(
self
) -> grafeas_v1.GrafeasClient:
- transport = type(self).get_transport_class("grpc")()
grafeas_transport = grafeas_v1.services.grafeas.transports.GrafeasGrpcTransport(
- host=transport._host,
- scopes=transport.AUTH_SCOPES
+ credentials=self.transport._credentials,
+ # Set ``credentials_file`` to ``None`` here as
+ # transport._credentials contains the credentials
+ # which are saved
+ credentials_file=None,
+ host = self.transport._host,
+ scopes=self.transport.AUTH_SCOPES
)
return grafeas_v1.GrafeasClient(transport=grafeas_transport)
@@ -86,10 +90,14 @@ for library in s.get_staging_dirs(default_version):
r'''\n\g<1>def get_grafeas_client(
self
) -> grafeas_v1.GrafeasClient:
- transport = type(self).get_transport_class("grpc_asyncio")()
grafeas_transport = grafeas_v1.services.grafeas.transports.GrafeasGrpcTransport(
- host=transport._host,
- scopes=transport.AUTH_SCOPES
+ credentials=self.transport._credentials,
+ # Set ``credentials_file`` to ``None`` here as
+ # transport._credentials contains the credentials
+ # which are saved
+ credentials_file=None,
+ host = self.transport._host,
+ scopes=self.transport.AUTH_SCOPES
)
return grafeas_v1.GrafeasClient(transport=grafeas_transport)
@@ -97,6 +105,48 @@ for library in s.get_staging_dirs(default_version):
\g<1>async def set_iam_policy(''',
)
+ # Add test to ensure that credentials propagate to client.get_grafeas_client()
+ num_replacements = s.replace(library / "tests/**/test_container_analysis.py",
+ """create_channel.assert_called_with\(
+ "containeranalysis.googleapis.com:443",
+ credentials=file_creds,
+ credentials_file=None,
+ quota_project_id=None,
+ default_scopes=\(
+ 'https://www.googleapis.com/auth/cloud-platform',
+\),
+ scopes=None,
+ default_host="containeranalysis.googleapis.com",
+ ssl_credentials=None,
+ options=\[
+ \("grpc.max_send_message_length", -1\),
+ \("grpc.max_receive_message_length", -1\),
+ \],
+ \)""",
+ """create_channel.assert_called_with(
+ "containeranalysis.googleapis.com:443",
+ credentials=file_creds,
+ credentials_file=None,
+ quota_project_id=None,
+ default_scopes=(
+ 'https://www.googleapis.com/auth/cloud-platform',
+),
+ scopes=None,
+ default_host="containeranalysis.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Also check client.get_grafeas_client() to make sure that the file credentials are used
+ assert file_creds == client.get_grafeas_client().transport._credentials
+ """
+ )
+
+ assert num_replacements == 1
+
s.move(library, excludes=["setup.py", "README.rst", "docs/index.rst"])
s.remove_staging_dirs()
|
googleapis/python-containeranalysis
|
a9b850b9155d51b882daa675b40577cc2fa9ee20
|
diff --git a/tests/unit/gapic/containeranalysis_v1/test_container_analysis.py b/tests/unit/gapic/containeranalysis_v1/test_container_analysis.py
index 8c6d80c..f660d72 100644
--- a/tests/unit/gapic/containeranalysis_v1/test_container_analysis.py
+++ b/tests/unit/gapic/containeranalysis_v1/test_container_analysis.py
@@ -650,6 +650,9 @@ def test_container_analysis_client_create_channel_credentials_file(
],
)
+ # Also check client.get_grafeas_client() to make sure that the file credentials are used
+ assert file_creds == client.get_grafeas_client().transport._credentials
+
@pytest.mark.parametrize("request_type", [iam_policy_pb2.SetIamPolicyRequest, dict,])
def test_set_iam_policy(request_type, transport: str = "grpc"):
|
Credentials to not propagate when using <Container analysis client>.get_grafeas_client()
Below is an example of the issue.
```
from google.cloud.devtools import containeranalysis_v1
from google.oauth2 import service_account
# path to service account json file
credentials_json_path = <path to your service account.json>
# Create credentials object
credentials = service_account.Credentials.from_service_account_file(credentials_json_path)
# Create a client for containeranalysis_v1
analysis_client = containeranalysis_v1.ContainerAnalysisClient(credentials=credentials)
# The output is <google.oauth2.service_account.Credentials object> which is what we want
print(analysis_client.transport._credentials)
# Create a client for grafeas
grafeas_client = analysis_client.get_grafeas_client()
# Here the output is <google.oauth2.credentials.Credentials object> not <google.oauth2.service_account.Credentials object>
print(grafeas_client.transport._credentials)
```
|
0.0
|
a9b850b9155d51b882daa675b40577cc2fa9ee20
|
[
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_create_channel_credentials_file[ContainerAnalysisAsyncClient-ContainerAnalysisGrpcAsyncIOTransport-grpc_asyncio-google.api_core.grpc_helpers_async]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_create_channel_credentials_file[ContainerAnalysisClient-ContainerAnalysisGrpcTransport-grpc-google.api_core.grpc_helpers]"
] |
[
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_transport_create_channel[ContainerAnalysisGrpcAsyncIOTransport-google.api_core.grpc_helpers_async]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_grpc_transport_client_cert_source_for_mtls[ContainerAnalysisGrpcAsyncIOTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy[SetIamPolicyRequest]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy_flattened_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_parse_common_organization_path",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_grpc_asyncio_transport_channel",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_client_options_credentials_file[ContainerAnalysisAsyncClient-ContainerAnalysisGrpcAsyncIOTransport-grpc_asyncio-google.api_core.grpc_helpers_async]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_transport_instance",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions_field_headers_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy_async_from_dict",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy_from_dict_foreign",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_client_ctx",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_grpc_transport_channel",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy_field_headers",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_parse_common_location_path",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy[dict]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_from_service_account_info[ContainerAnalysisAsyncClient]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary_empty_call",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy_empty_call",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_transport_close",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_transport_adc[ContainerAnalysisGrpcAsyncIOTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_common_location_path",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary_async_from_dict",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary_flattened",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_client_options_scopes[ContainerAnalysisAsyncClient-ContainerAnalysisGrpcAsyncIOTransport-grpc_asyncio]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy_empty_call",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary_flattened_error",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy_flattened_error",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions_flattened_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_client_options_scopes[ContainerAnalysisClient-ContainerAnalysisGrpcTransport-grpc]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions_from_dict_foreign",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_client_options_credentials_file[ContainerAnalysisClient-ContainerAnalysisGrpcTransport-grpc-google.api_core.grpc_helpers]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_api_key_credentials[ContainerAnalysisClient-ContainerAnalysisGrpcTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_base_transport_with_adc",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions_flattened_error",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy_field_headers_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_client_options[ContainerAnalysisAsyncClient-ContainerAnalysisGrpcAsyncIOTransport-grpc_asyncio]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_from_service_account_file[ContainerAnalysisAsyncClient]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary[dict]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_get_mtls_endpoint_and_cert_source[ContainerAnalysisClient]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions_flattened_error_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_transport_adc[ContainerAnalysisGrpcTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_transport_get_channel",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary[GetVulnerabilityOccurrencesSummaryRequest]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_transport_close_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_transport_channel_mtls_with_adc[ContainerAnalysisGrpcTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions[dict]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_mtls_env_auto[ContainerAnalysisAsyncClient-ContainerAnalysisGrpcAsyncIOTransport-grpc_asyncio-false]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy_flattened",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_from_service_account_info[ContainerAnalysisClient]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy_from_dict_foreign",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary_flattened_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_transport_auth_adc[ContainerAnalysisGrpcTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions_flattened",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_common_organization_path",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_credentials_transport_error",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions[TestIamPermissionsRequest]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy_flattened",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_client_options_from_dict",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_base_transport_error",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary_flattened_error_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_from_service_account_file[ContainerAnalysisClient]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy_flattened_error_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_auth_adc",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_service_account_always_use_jwt[ContainerAnalysisGrpcTransport-grpc]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_api_key_credentials[ContainerAnalysisAsyncClient-ContainerAnalysisGrpcAsyncIOTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_transport_auth_adc[ContainerAnalysisGrpcAsyncIOTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary_field_headers_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_client_options[ContainerAnalysisClient-ContainerAnalysisGrpcTransport-grpc]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_get_transport_class",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_service_account_always_use_jwt[ContainerAnalysisGrpcAsyncIOTransport-grpc_asyncio]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_parse_common_billing_account_path",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_common_folder_path",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_transport_channel_mtls_with_client_cert_source[ContainerAnalysisGrpcTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_base_transport",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy[GetIamPolicyRequest]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy_field_headers",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy_async_from_dict",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy_flattened_error",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_get_mtls_endpoint_and_cert_source[ContainerAnalysisAsyncClient]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy[dict]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions_async_from_dict",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_parse_common_project_path",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy_field_headers_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_mtls_env_auto[ContainerAnalysisClient-ContainerAnalysisGrpcTransport-grpc-false]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_transport_create_channel[ContainerAnalysisGrpcTransport-google.api_core.grpc_helpers]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions_field_headers",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_vulnerability_occurrences_summary_field_headers",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_transport_channel_mtls_with_adc[ContainerAnalysisGrpcAsyncIOTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_common_project_path",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_parse_common_folder_path",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_host_no_port",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_transport_grpc_default",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_test_iam_permissions_empty_call",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_mtls_env_auto[ContainerAnalysisAsyncClient-ContainerAnalysisGrpcAsyncIOTransport-grpc_asyncio-true]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_transport_channel_mtls_with_client_cert_source[ContainerAnalysisGrpcAsyncIOTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_host_with_port",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_base_transport_with_credentials_file",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test__get_default_mtls_endpoint",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_client_mtls_env_auto[ContainerAnalysisClient-ContainerAnalysisGrpcTransport-grpc-true]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_get_iam_policy_flattened_error_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_client_with_default_client_info",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_container_analysis_grpc_transport_client_cert_source_for_mtls[ContainerAnalysisGrpcTransport]",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_set_iam_policy_flattened_async",
"tests/unit/gapic/containeranalysis_v1/test_container_analysis.py::test_common_billing_account_path"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-03-04 00:56:15+00:00
|
apache-2.0
| 2,623 |
|
googleapis__python-datastore-115
|
diff --git a/google/cloud/datastore/key.py b/google/cloud/datastore/key.py
index d03359b..c9beaeb 100644
--- a/google/cloud/datastore/key.py
+++ b/google/cloud/datastore/key.py
@@ -441,7 +441,9 @@ class Key(object):
:returns: The last element of the key's path if it is either an ``id``
or a ``name``.
"""
- return self.id or self.name
+ if self.id is None:
+ return self.name
+ return self.id
@property
def project(self):
|
googleapis/python-datastore
|
5851522900fc07c9cc13e1af2cf7b54d709c9ddb
|
diff --git a/tests/unit/test_key.py b/tests/unit/test_key.py
index 73565ea..9d130fb 100644
--- a/tests/unit/test_key.py
+++ b/tests/unit/test_key.py
@@ -488,6 +488,11 @@ class TestKey(unittest.TestCase):
key = self._make_one("KIND", _NAME, project=self._DEFAULT_PROJECT)
self.assertEqual(key.id_or_name, _NAME)
+ def test_id_or_name_w_id_zero(self):
+ _ID = 0
+ key = self._make_one("KIND", _ID, project=self._DEFAULT_PROJECT)
+ self.assertEqual(key.id_or_name, _ID)
+
def test_parent_default(self):
key = self._make_one("KIND", project=self._DEFAULT_PROJECT)
self.assertIsNone(key.parent)
|
datastore Key id_or_name() returns None when id is 0
#### Description
Expecting the Key().is_partial to return False for a Key with id=0.
The is_partial property relies on the id_or_name property.
The id_or_name property returns None when the id=0, which is not expected. Expecting the id to be returned instead.
The id_or_name property implementation is to simple. Should check for None or isinstance(self.id, int)
#### Environment details
- OS type and version: Ubuntu 20.04
- Python version: Python 3.8.5
- pip version: pip 20.2.3
- `google-cloud-datastore` version: 1.15.3
#### Steps to reproduce
1. Create a datastore key instance with Id = 0
2. Retrieve the id_or_name property, returns None, expected 0.
#### Code example
```python
def test_datastore_key():
import google.cloud.datastore
k = google.cloud.datastore.Key('EntityKind', 0, project="unittest")
assert k.id == 0
assert k.id_or_name == 0
assert k.is_partial == False
```
#### Stack trace
```
assert None == 0
+None
-0
def test_datastore_key():
import google.cloud.datastore
k = google.cloud.datastore.Key('EntityKind', 0, project="unittest")
assert k.id == 0
> assert k.id_or_name == 0
E assert None == 0
E +None
E -0
```
|
0.0
|
5851522900fc07c9cc13e1af2cf7b54d709c9ddb
|
[
"tests/unit/test_key.py::TestKey::test_id_or_name_w_id_zero"
] |
[
"tests/unit/test_key.py::TestKey::test___eq_____ne___complete_key_w_incomplete_key_same_kind",
"tests/unit/test_key.py::TestKey::test___eq_____ne___incomplete_key_w_complete_key_same_kind",
"tests/unit/test_key.py::TestKey::test___eq_____ne___same_kind_and_id",
"tests/unit/test_key.py::TestKey::test___eq_____ne___same_kind_and_id_different_namespace",
"tests/unit/test_key.py::TestKey::test___eq_____ne___same_kind_and_id_different_project",
"tests/unit/test_key.py::TestKey::test___eq_____ne___same_kind_and_name",
"tests/unit/test_key.py::TestKey::test___eq_____ne___same_kind_and_name_different_namespace",
"tests/unit/test_key.py::TestKey::test___eq_____ne___same_kind_and_name_different_project",
"tests/unit/test_key.py::TestKey::test___eq_____ne___same_kind_different_ids",
"tests/unit/test_key.py::TestKey::test___eq_____ne___same_kind_different_names",
"tests/unit/test_key.py::TestKey::test___eq_____ne___two_incomplete_keys_same_kind",
"tests/unit/test_key.py::TestKey::test___eq_____ne___w_non_key",
"tests/unit/test_key.py::TestKey::test___hash___completed_w_id",
"tests/unit/test_key.py::TestKey::test___hash___completed_w_name",
"tests/unit/test_key.py::TestKey::test___hash___incomplete",
"tests/unit/test_key.py::TestKey::test__clone",
"tests/unit/test_key.py::TestKey::test__clone_with_parent",
"tests/unit/test_key.py::TestKey::test_completed_key_on_complete",
"tests/unit/test_key.py::TestKey::test_completed_key_on_partial_w_id",
"tests/unit/test_key.py::TestKey::test_completed_key_on_partial_w_invalid",
"tests/unit/test_key.py::TestKey::test_completed_key_on_partial_w_name",
"tests/unit/test_key.py::TestKey::test_ctor_bad_id_or_name",
"tests/unit/test_key.py::TestKey::test_ctor_bad_kind",
"tests/unit/test_key.py::TestKey::test_ctor_empty",
"tests/unit/test_key.py::TestKey::test_ctor_explicit",
"tests/unit/test_key.py::TestKey::test_ctor_no_project",
"tests/unit/test_key.py::TestKey::test_ctor_parent",
"tests/unit/test_key.py::TestKey::test_ctor_parent_bad_namespace",
"tests/unit/test_key.py::TestKey::test_ctor_parent_bad_project",
"tests/unit/test_key.py::TestKey::test_ctor_parent_bad_type",
"tests/unit/test_key.py::TestKey::test_ctor_parent_empty_path",
"tests/unit/test_key.py::TestKey::test_ctor_partial_parent",
"tests/unit/test_key.py::TestKey::test_ctor_w_explicit_project_empty_path",
"tests/unit/test_key.py::TestKey::test_from_legacy_urlsafe",
"tests/unit/test_key.py::TestKey::test_from_legacy_urlsafe_needs_padding",
"tests/unit/test_key.py::TestKey::test_from_legacy_urlsafe_with_location_prefix",
"tests/unit/test_key.py::TestKey::test_id_or_name_no_name_or_id",
"tests/unit/test_key.py::TestKey::test_id_or_name_no_name_or_id_child",
"tests/unit/test_key.py::TestKey::test_id_or_name_w_id_only",
"tests/unit/test_key.py::TestKey::test_id_or_name_w_name_only",
"tests/unit/test_key.py::TestKey::test_is_partial_no_name_or_id",
"tests/unit/test_key.py::TestKey::test_is_partial_w_id",
"tests/unit/test_key.py::TestKey::test_is_partial_w_name",
"tests/unit/test_key.py::TestKey::test_parent_default",
"tests/unit/test_key.py::TestKey::test_parent_explicit_nested",
"tests/unit/test_key.py::TestKey::test_parent_explicit_top_level",
"tests/unit/test_key.py::TestKey::test_parent_multiple_calls",
"tests/unit/test_key.py::TestKey::test_to_legacy_urlsafe",
"tests/unit/test_key.py::TestKey::test_to_legacy_urlsafe_strip_padding",
"tests/unit/test_key.py::TestKey::test_to_legacy_urlsafe_with_location_prefix",
"tests/unit/test_key.py::TestKey::test_to_protobuf_defaults",
"tests/unit/test_key.py::TestKey::test_to_protobuf_w_explicit_namespace",
"tests/unit/test_key.py::TestKey::test_to_protobuf_w_explicit_path",
"tests/unit/test_key.py::TestKey::test_to_protobuf_w_explicit_project",
"tests/unit/test_key.py::TestKey::test_to_protobuf_w_no_kind",
"tests/unit/test_key.py::Test__clean_app::test_already_clean",
"tests/unit/test_key.py::Test__clean_app::test_dev_server",
"tests/unit/test_key.py::Test__clean_app::test_european",
"tests/unit/test_key.py::Test__clean_app::test_standard",
"tests/unit/test_key.py::Test__get_empty::test_actually_set",
"tests/unit/test_key.py::Test__get_empty::test_unset",
"tests/unit/test_key.py::Test__check_database_id::test_empty_value",
"tests/unit/test_key.py::Test__check_database_id::test_failure",
"tests/unit/test_key.py::Test__add_id_or_name::test_add_id",
"tests/unit/test_key.py::Test__add_id_or_name::test_add_name",
"tests/unit/test_key.py::Test__add_id_or_name::test_both_empty_allowed",
"tests/unit/test_key.py::Test__add_id_or_name::test_both_empty_failure",
"tests/unit/test_key.py::Test__add_id_or_name::test_both_present",
"tests/unit/test_key.py::Test__get_flat_path::test_one_pair",
"tests/unit/test_key.py::Test__get_flat_path::test_partial_key",
"tests/unit/test_key.py::Test__get_flat_path::test_two_pairs",
"tests/unit/test_key.py::Test__to_legacy_path::test_one_pair",
"tests/unit/test_key.py::Test__to_legacy_path::test_partial_key",
"tests/unit/test_key.py::Test__to_legacy_path::test_two_pairs"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-11-09 10:39:31+00:00
|
apache-2.0
| 2,624 |
|
googleapis__python-firestore-821
|
diff --git a/google/cloud/firestore_v1/transforms.py b/google/cloud/firestore_v1/transforms.py
index f1361c9..ae061f6 100644
--- a/google/cloud/firestore_v1/transforms.py
+++ b/google/cloud/firestore_v1/transforms.py
@@ -26,6 +26,14 @@ class Sentinel(object):
def __repr__(self):
return "Sentinel: {}".format(self.description)
+ def __copy__(self):
+ # Sentinel identity should be preserved across copies.
+ return self
+
+ def __deepcopy__(self, memo):
+ # Sentinel identity should be preserved across deep copies.
+ return self
+
DELETE_FIELD = Sentinel("Value used to delete a field in a document.")
|
googleapis/python-firestore
|
81865ee2e1c6e3805c339e5db95e072d99297938
|
diff --git a/tests/unit/v1/test_transforms.py b/tests/unit/v1/test_transforms.py
index 218650b..1a46f27 100644
--- a/tests/unit/v1/test_transforms.py
+++ b/tests/unit/v1/test_transforms.py
@@ -114,3 +114,23 @@ def test__numericvalue___eq___same_value():
inst = _make_numeric_value(value)
other = _make_numeric_value(value)
assert inst == other
+
+
+def test__server_timestamp_is_same_after_copy():
+ from google.cloud.firestore_v1.transforms import SERVER_TIMESTAMP
+ import copy
+
+ value = SERVER_TIMESTAMP
+
+ value_copy = copy.copy(value)
+ assert value_copy is value
+
+
+def test__server_timestamp_is_same_after_deepcopy():
+ from google.cloud.firestore_v1.transforms import SERVER_TIMESTAMP
+ import copy
+
+ value = SERVER_TIMESTAMP
+
+ value_copy = copy.deepcopy(value)
+ assert value_copy is value
|
SERVER_TIMESTAMP should survive deep copies (dataclasses.asdict)
## Problem
Currently `SERVER_TIMESTAMP` does not work if it has been copied via `copy.deepcopy`.
This is especially important for `dataclasses`.
Here is an example script to demonstrate the problem
```python
from google.cloud.firestore_v1.transforms import Sentinel
from google.cloud.firestore_v1.transforms import SERVER_TIMESTAMP
import dataclasses
@dataclasses.dataclass
class Example:
timestamp: type[SERVER_TIMESTAMP] = SERVER_TIMESTAMP
example = Example()
assert example.timestamp is SERVER_TIMESTAMP
asdict = dataclasses.asdict(example)
assert asdict['timestamp'] is SERVER_TIMESTAMP
```
Currently the second assertion fails because the Sentinel has been deep copied.
```
Traceback (most recent call last):
File "/Users/michael/dev/rfp-tool/test.py", line 15, in <module>
assert asdict['timestamp'] is SERVER_TIMESTAMP
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError
```
## Solution
The Sentinel class should define dunder `__copy__` and `__deepcopy__` methods.
```
diff --git a/google/cloud/firestore_v1/transforms.py b/google/cloud/firestore_v1/transforms.py
index f1361c9..ef0def8 100644
--- a/google/cloud/firestore_v1/transforms.py
+++ b/google/cloud/firestore_v1/transforms.py
@@ -26,6 +26,15 @@ class Sentinel(object):
def __repr__(self):
return "Sentinel: {}".format(self.description)
+ def __copy__(self):
+ # Sentinel identity should be preserved across copies.
+ return self
+
+ def __deepcopy__(self):
+ # Sentinel identity should be preserved across deep copies.
+ return self
+
+
DELETE_FIELD = Sentinel("Value used to delete a field in a document.")
```
I will send a PR attached to this issue.
|
0.0
|
81865ee2e1c6e3805c339e5db95e072d99297938
|
[
"tests/unit/v1/test_transforms.py::test__server_timestamp_is_same_after_copy",
"tests/unit/v1/test_transforms.py::test__server_timestamp_is_same_after_deepcopy"
] |
[
"tests/unit/v1/test_transforms.py::test__valuelist_ctor_w_non_list_non_tuple",
"tests/unit/v1/test_transforms.py::test__valuelist_ctor_w_empty",
"tests/unit/v1/test_transforms.py::test__valuelist_ctor_w_non_empty_list",
"tests/unit/v1/test_transforms.py::test__valuelist_ctor_w_non_empty_tuple",
"tests/unit/v1/test_transforms.py::test__valuelist___eq___other_type",
"tests/unit/v1/test_transforms.py::test__valuelist___eq___different_values",
"tests/unit/v1/test_transforms.py::test__valuelist___eq___same_values",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_invalid_types[invalid_value0]",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_int[-10]",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_int[-1]",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_int[0]",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_int[1]",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_int[10]",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_float[-10.0]",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_float[-1.0]",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_float[0.0]",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_float[1.0]",
"tests/unit/v1/test_transforms.py::test__numericvalue_ctor_w_float[10.0]",
"tests/unit/v1/test_transforms.py::test__numericvalue___eq___other_type",
"tests/unit/v1/test_transforms.py::test__numericvalue___eq___different_value",
"tests/unit/v1/test_transforms.py::test__numericvalue___eq___same_value"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-12-12 00:54:16+00:00
|
apache-2.0
| 2,625 |
|
googleapis__python-logging-657
|
diff --git a/google/cloud/logging_v2/handlers/structured_log.py b/google/cloud/logging_v2/handlers/structured_log.py
index 6552825..55ed9c2 100644
--- a/google/cloud/logging_v2/handlers/structured_log.py
+++ b/google/cloud/logging_v2/handlers/structured_log.py
@@ -62,12 +62,15 @@ class StructuredLogHandler(logging.StreamHandler):
and write them to standard output
"""
- def __init__(self, *, labels=None, stream=None, project_id=None):
+ def __init__(
+ self, *, labels=None, stream=None, project_id=None, json_encoder_cls=None
+ ):
"""
Args:
labels (Optional[dict]): Additional labels to attach to logs.
stream (Optional[IO]): Stream to be used by the handler.
project (Optional[str]): Project Id associated with the logs.
+ json_encoder_cls (Optional[Type[JSONEncoder]]): Custom JSON encoder. Defaults to json.JSONEncoder
"""
super(StructuredLogHandler, self).__init__(stream=stream)
self.project_id = project_id
@@ -79,6 +82,8 @@ class StructuredLogHandler(logging.StreamHandler):
# make logs appear in GCP structured logging format
self._gcp_formatter = logging.Formatter(GCP_FORMAT)
+ self._json_encoder_cls = json_encoder_cls or json.JSONEncoder
+
def format(self, record):
"""Format the message into structured log JSON.
Args:
@@ -95,14 +100,18 @@ class StructuredLogHandler(logging.StreamHandler):
if key in GCP_STRUCTURED_LOGGING_FIELDS:
del message[key]
# if input is a dictionary, encode it as a json string
- encoded_msg = json.dumps(message, ensure_ascii=False)
+ encoded_msg = json.dumps(
+ message, ensure_ascii=False, cls=self._json_encoder_cls
+ )
# all json.dumps strings should start and end with parentheses
# strip them out to embed these fields in the larger JSON payload
if len(encoded_msg) > 2:
payload = encoded_msg[1:-1] + ","
elif message:
# properly break any formatting in string to make it json safe
- encoded_message = json.dumps(message, ensure_ascii=False)
+ encoded_message = json.dumps(
+ message, ensure_ascii=False, cls=self._json_encoder_cls
+ )
payload = '"message": {},'.format(encoded_message)
record._payload_str = payload or ""
|
googleapis/python-logging
|
061a3813e6053fbaef8b50f871864587a10bc966
|
diff --git a/tests/unit/handlers/test_structured_log.py b/tests/unit/handlers/test_structured_log.py
index 61bf36f..d930da7 100644
--- a/tests/unit/handlers/test_structured_log.py
+++ b/tests/unit/handlers/test_structured_log.py
@@ -46,6 +46,15 @@ class TestStructuredLogHandler(unittest.TestCase):
handler = self._make_one(project_id="foo")
self.assertEqual(handler.project_id, "foo")
+ def test_ctor_w_encoder(self):
+ import json
+
+ class CustomJSONEncoder(json.JSONEncoder):
+ pass
+
+ handler = self._make_one(json_encoder_cls=CustomJSONEncoder)
+ self.assertEqual(handler._json_encoder_cls, CustomJSONEncoder)
+
def test_format(self):
import logging
import json
@@ -207,6 +216,51 @@ class TestStructuredLogHandler(unittest.TestCase):
self.assertIn(expected_result, result)
self.assertIn("message", result)
+ def test_format_with_custom_json_encoder(self):
+ import json
+ import logging
+
+ from pathlib import Path
+ from typing import Any
+
+ class CustomJSONEncoder(json.JSONEncoder):
+ def default(self, obj: Any) -> Any:
+ if isinstance(obj, Path):
+ return str(obj)
+ return json.JSONEncoder.default(self, obj)
+
+ handler = self._make_one(json_encoder_cls=CustomJSONEncoder)
+
+ message = "hello world"
+ json_fields = {"path": Path("/path")}
+ record = logging.LogRecord(
+ None,
+ logging.INFO,
+ None,
+ None,
+ message,
+ None,
+ None,
+ )
+ setattr(record, "json_fields", json_fields)
+ expected_payload = {
+ "message": message,
+ "severity": "INFO",
+ "logging.googleapis.com/trace": "",
+ "logging.googleapis.com/spanId": "",
+ "logging.googleapis.com/trace_sampled": False,
+ "logging.googleapis.com/sourceLocation": {},
+ "httpRequest": {},
+ "logging.googleapis.com/labels": {},
+ "path": "/path",
+ }
+ handler.filter(record)
+
+ result = json.loads(handler.format(record))
+
+ self.assertEqual(set(expected_payload.keys()), set(result.keys()))
+ self.assertEqual(result["path"], "/path")
+
def test_format_with_reserved_json_field(self):
# drop json_field data with reserved names
# related issue: https://github.com/googleapis/python-logging/issues/543
|
Add support to custom `JSONEncoder`
**Is your feature request related to a problem? Please describe.**
My company is moving out from [structlog](https://www.structlog.org/en/stable/) to start using this package, as it is intended to have better integration with google products. We're using `StructuredLogHandler` to send the log records to google cloud logging. But something structlog used to do out-of-the-box was the ability to automatically convert the extra data we provide to the logger to be sent to the stream, and therefore, we need to check all the calls we're making to `logger.info()`, `debug()`, `warning()`, etc. to check if the data type is supported by JSONEncoder, otherwise the call to `hadler.format()` will raise `TypeError`, stating that `Object of type PosixPath is not JSON serializable` (this is one example of error we're getting, because the default encoder cannot encode `pathlib.Path` instances) and the log record will not be pushed to gcloud logging
**Describe the solution you'd like**
I'd like to be able to specify a custom class to encode the message to JSON, so the formatting is handled by the encoder, not the caller of `logger.info()` and its siblings
**Describe alternatives you've considered**
An alternative would be having a filter that prepares the data to be used by the handler, I'm even wrote a filter to handle that:
```python
class JsonableConverterFilter(logging.Filter):
"""Prepare log record to be JSON encoded
:class:`google.cloud.logging_v2.handlers.StructuredLogHandler` encodes directly to default JSON encoder without
the possibility to set up a custom encoder, so we need to hydrate the log record to not break when emitting
(because broken logs break silently)
The ideal solution would be to have a LogFormatter, but as GCloud's log handler formats to JSON inside the handler,
we need to circumvent this issue with a :class:`logging.Filter`
"""
def filter(self, record: logging.LogRecord) -> bool:
fields: Dict[str, Any] = getattr(record, "json_fields", {})
for key, value in fields.items():
fields[key] = JsonableConverterFilter.prepare_field(value)
return True
@classmethod
def prepare_field(cls, value: Any) -> TypeJSON:
"""Converts the provided type into a plain JSON type"""
# basic types
if isinstance(value, (int, str, float, bool)) or value is None:
return value
try:
iterator = iter(value)
except TypeError:
# probably a custom class
if not hasattr(value, "__dict__"):
return str(value)
iterator = iter(value.__dict__)
# hashmaps
if hasattr(value, "keys") and hasattr(value, "values"):
return {key: cls.prepare_field(val) for key, val in value.items()}
# sequences
return [cls.prepare_field(item) for item in iterator]
```
but it seems to me I'm deviating the purpose of log filters by doing that
**Additional context**
n/a for now
|
0.0
|
061a3813e6053fbaef8b50f871864587a10bc966
|
[
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_ctor_w_encoder",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format_with_custom_json_encoder"
] |
[
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_ctor_defaults",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_ctor_w_project",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_dict",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_encoded_json",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format_minimal",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format_with_arguments",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format_with_custom_formatter",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format_with_exception",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format_with_json_fields",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format_with_line_break",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format_with_nested_json",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format_with_quotes",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_format_with_reserved_json_field",
"tests/unit/handlers/test_structured_log.py::TestStructuredLogHandler::test_json_fields_input_unmodified"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-25 11:10:57+00:00
|
apache-2.0
| 2,626 |
|
googleapis__python-logging-812
|
diff --git a/google/__init__.py b/google/__init__.py
deleted file mode 100644
index 0e1bc51..0000000
--- a/google/__init__.py
+++ /dev/null
@@ -1,22 +0,0 @@
-# Copyright 2016 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-try:
- import pkg_resources
-
- pkg_resources.declare_namespace(__name__)
-except ImportError:
- import pkgutil
-
- __path__ = pkgutil.extend_path(__path__, __name__)
diff --git a/google/cloud/__init__.py b/google/cloud/__init__.py
deleted file mode 100644
index 0e1bc51..0000000
--- a/google/cloud/__init__.py
+++ /dev/null
@@ -1,22 +0,0 @@
-# Copyright 2016 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-try:
- import pkg_resources
-
- pkg_resources.declare_namespace(__name__)
-except ImportError:
- import pkgutil
-
- __path__ = pkgutil.extend_path(__path__, __name__)
diff --git a/setup.py b/setup.py
index f43fd0b..e4a7127 100644
--- a/setup.py
+++ b/setup.py
@@ -55,14 +55,10 @@ with io.open(readme_filename, encoding="utf-8") as readme_file:
packages = [
package
- for package in setuptools.PEP420PackageFinder.find()
+ for package in setuptools.find_namespace_packages()
if package.startswith("google")
]
-namespaces = ["google"]
-if "google.cloud" in packages:
- namespaces.append("google.cloud")
-
setuptools.setup(
name=name,
version=version,
@@ -89,7 +85,6 @@ setuptools.setup(
platforms="Posix; MacOS X; Windows",
packages=packages,
python_requires=">=3.7",
- namespace_packages=namespaces,
install_requires=dependencies,
include_package_data=True,
zip_safe=False,
|
googleapis/python-logging
|
d73cc56ba49d13d2c876c9dbf5c76b2308012161
|
diff --git a/tests/unit/test_packaging.py b/tests/unit/test_packaging.py
new file mode 100644
index 0000000..4369ca2
--- /dev/null
+++ b/tests/unit/test_packaging.py
@@ -0,0 +1,56 @@
+# Copyright 2023 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import subprocess
+import sys
+
+
+def test_namespace_package_compat(tmp_path):
+ # The ``google`` namespace package should not be masked
+ # by the presence of ``google-cloud-logging``.
+
+ google = tmp_path / "google"
+ google.mkdir()
+ google.joinpath("othermod.py").write_text("")
+
+ google_otherpkg = tmp_path / "google" / "otherpkg"
+ google_otherpkg.mkdir()
+ google_otherpkg.joinpath("__init__.py").write_text("")
+
+ # The ``google.cloud`` namespace package should not be masked
+ # by the presence of ``google-cloud-logging``.
+ google_cloud = tmp_path / "google" / "cloud"
+ google_cloud.mkdir()
+ google_cloud.joinpath("othermod.py").write_text("")
+
+ google_cloud_otherpkg = tmp_path / "google" / "cloud" / "otherpkg"
+ google_cloud_otherpkg.mkdir()
+ google_cloud_otherpkg.joinpath("__init__.py").write_text("")
+
+ env = dict(os.environ, PYTHONPATH=str(tmp_path))
+
+ for pkg in [
+ "google.othermod",
+ "google.cloud.othermod",
+ "google.otherpkg",
+ "google.cloud.otherpkg",
+ "google.cloud.logging",
+ ]:
+ cmd = [sys.executable, "-c", f"import {pkg}"]
+ subprocess.check_output(cmd, env=env)
+
+ for module in ["google.othermod", "google.cloud.othermod"]:
+ cmd = [sys.executable, "-m", module]
+ subprocess.check_output(cmd, env=env)
|
DeprecationWarning for pkg_resources.declare_namespace("google.logging")
Starting from `setuptools==67.3.0`, it has started raising DeprecationWarning. Some libraries treat them as errors during testing.
See: https://setuptools.pypa.io/en/latest/history.html#v67-3-0.
```python
/lib/python3.11/site-packages/pkg_resources/__init__.py:2804: DeprecationWarning: Deprecated call to `pkg_resources.declare_namespace('google.logging')`.
Implementing implicit namespace packages (as specified in PEP 420) is preferred to `pkg_resources.declare_namespace`. See https://setuptools.pypa.io/en/latest/references/keywords.html#keyword-namespace-packages
declare_namespace(pkg)
```
See similar discussion in https://github.com/matplotlib/matplotlib/issues/25244 and https://github.com/pypa/setuptools/pull/3434#issuecomment-1435697632.
Also opened a similar issue in `google.cloud`: https://github.com/googleapis/python-storage/issues/1000.
|
0.0
|
d73cc56ba49d13d2c876c9dbf5c76b2308012161
|
[
"tests/unit/test_packaging.py::test_namespace_package_compat"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_removed_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-11-15 18:28:45+00:00
|
apache-2.0
| 2,627 |
|
googleapis__python-pubsub-38
|
diff --git a/google/cloud/pubsub_v1/subscriber/_protocol/leaser.py b/google/cloud/pubsub_v1/subscriber/_protocol/leaser.py
index b603794..5830680 100644
--- a/google/cloud/pubsub_v1/subscriber/_protocol/leaser.py
+++ b/google/cloud/pubsub_v1/subscriber/_protocol/leaser.py
@@ -130,8 +130,8 @@ class Leaser(object):
# Determine the appropriate duration for the lease. This is
# based off of how long previous messages have taken to ack, with
# a sensible default and within the ranges allowed by Pub/Sub.
- p99 = self._manager.ack_histogram.percentile(99)
- _LOGGER.debug("The current p99 value is %d seconds.", p99)
+ deadline = self._manager.ack_deadline
+ _LOGGER.debug("The current deadline value is %d seconds.", deadline)
# Make a copy of the leased messages. This is needed because it's
# possible for another thread to modify the dictionary while
@@ -173,7 +173,7 @@ class Leaser(object):
# way for ``send_request`` to fail when the consumer
# is inactive.
self._manager.dispatcher.modify_ack_deadline(
- [requests.ModAckRequest(ack_id, p99) for ack_id in ack_ids]
+ [requests.ModAckRequest(ack_id, deadline) for ack_id in ack_ids]
)
# Now wait an appropriate period of time and do this again.
@@ -182,7 +182,7 @@ class Leaser(object):
# period between 0 seconds and 90% of the lease. This use of
# jitter (http://bit.ly/2s2ekL7) helps decrease contention in cases
# where there are many clients.
- snooze = random.uniform(0.0, p99 * 0.9)
+ snooze = random.uniform(0.0, deadline * 0.9)
_LOGGER.debug("Snoozing lease management for %f seconds.", snooze)
self._stop_event.wait(timeout=snooze)
diff --git a/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py b/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
index 9b3f8d5..0a25d46 100644
--- a/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
+++ b/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
@@ -191,9 +191,19 @@ class StreamingPullManager(object):
Returns:
int: The ack deadline.
"""
- target = min([self._last_histogram_size * 2, self._last_histogram_size + 100])
- if len(self.ack_histogram) > target:
+ target_size = min(
+ self._last_histogram_size * 2, self._last_histogram_size + 100
+ )
+ hist_size = len(self.ack_histogram)
+
+ if hist_size > target_size:
+ self._last_histogram_size = hist_size
self._ack_deadline = self.ack_histogram.percentile(percent=99)
+
+ if self.flow_control.max_duration_per_lease_extension > 0:
+ self._ack_deadline = min(
+ self._ack_deadline, self.flow_control.max_duration_per_lease_extension
+ )
return self._ack_deadline
@property
diff --git a/google/cloud/pubsub_v1/types.py b/google/cloud/pubsub_v1/types.py
index 28019f4..eb4f006 100644
--- a/google/cloud/pubsub_v1/types.py
+++ b/google/cloud/pubsub_v1/types.py
@@ -87,12 +87,19 @@ if sys.version_info >= (3, 5):
# these settings can be altered to tweak Pub/Sub behavior.
# The defaults should be fine for most use cases.
FlowControl = collections.namedtuple(
- "FlowControl", ["max_bytes", "max_messages", "max_lease_duration"]
+ "FlowControl",
+ [
+ "max_bytes",
+ "max_messages",
+ "max_lease_duration",
+ "max_duration_per_lease_extension",
+ ],
)
FlowControl.__new__.__defaults__ = (
100 * 1024 * 1024, # max_bytes: 100mb
1000, # max_messages: 1000
1 * 60 * 60, # max_lease_duration: 1 hour.
+ 0, # max_duration_per_lease_extension: disabled
)
if sys.version_info >= (3, 5):
@@ -112,6 +119,11 @@ if sys.version_info >= (3, 5):
"The maximum amount of time in seconds to hold a lease on a message "
"before dropping it from the lease management."
)
+ FlowControl.max_duration_per_lease_extension.__doc__ = (
+ "The max amount of time in seconds for a single lease extension attempt. "
+ "Bounds the delay before a message redelivery if the subscriber "
+ "fails to extend the deadline."
+ )
_shared_modules = [
|
googleapis/python-pubsub
|
4a7211b3b10f47e3c6b046686d81261002e9ec36
|
diff --git a/tests/unit/pubsub_v1/subscriber/test_leaser.py b/tests/unit/pubsub_v1/subscriber/test_leaser.py
index ec954b8..17409cb 100644
--- a/tests/unit/pubsub_v1/subscriber/test_leaser.py
+++ b/tests/unit/pubsub_v1/subscriber/test_leaser.py
@@ -84,6 +84,7 @@ def create_manager(flow_control=types.FlowControl()):
manager.is_active = True
manager.flow_control = flow_control
manager.ack_histogram = histogram.Histogram()
+ manager.ack_deadline = 10
return manager
diff --git a/tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py b/tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py
index 0886a45..70f320f 100644
--- a/tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py
+++ b/tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py
@@ -144,6 +144,17 @@ def test_ack_deadline():
assert manager.ack_deadline == 20
+def test_ack_deadline_with_max_duration_per_lease_extension():
+ manager = make_manager()
+ manager._flow_control = types.FlowControl(max_duration_per_lease_extension=5)
+
+ assert manager.ack_deadline == 5
+ for _ in range(5):
+ manager.ack_histogram.add(20)
+
+ assert manager.ack_deadline == 5
+
+
def test_maybe_pause_consumer_wo_consumer_set():
manager = make_manager(
flow_control=types.FlowControl(max_messages=10, max_bytes=1000)
|
pubsub: expose a max_duration_per_lease_extension setting for subscribers
For languages that support lease management, we have bound the percentile distribution to 10s - 10m. It would be useful if the upper bound were configurable.
A user might process messages very slowly (8m to ack)
If the application fails 5s after receiving a message (whose ack deadline was set to 8m, because that's the deadline the percentile distribution gave), the user has to wait 7m55s for the message to be redelivered
Users should be able to set `max_duration_per_lease_extension` = 20s, which caps an individual modAck RPC to 20s. This would have the downside of causing more modack RPCs to be sent, but the upside that the redelivery time would only be 15s
This setting differs from [`max_lease_duration`](https://github.com/googleapis/google-cloud-dotnet/blob/174e30c1ef39c5d1e1e51590b6af402aa0316c54/apis/Google.Cloud.PubSub.V1/Google.Cloud.PubSub.V1/SubscriberClient.cs#L229), which defines the total amount of time we'll hold a message.
In addition, `max_duration_per_lease_extension` should be disabled if <=0, and should default to 0.
|
0.0
|
4a7211b3b10f47e3c6b046686d81261002e9ec36
|
[
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_ack_deadline_with_max_duration_per_lease_extension"
] |
[
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_remove_not_managed",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_start_already_started",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_add_already_managed",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_remove_negative_bytes",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_add_and_remove",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_maintain_leases_no_ack_ids",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_maintain_leases_outdated_items",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_stop_no_join",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_maintain_leases_stopped",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_start_lease_expiry_timer_unknown_ack_id",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_stop",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_maintain_leases_ack_ids",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_maintain_leases_inactive",
"tests/unit/pubsub_v1/subscriber/test_leaser.py::test_start",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__on_response_no_leaser_overload",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__should_recover_true",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_send_unary",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_open_already_active",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__maybe_wrap_exception[exception0-ValueError]",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_close_callbacks",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_resume_not_paused",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__wrap_callback_errors_error",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_activate_ordering_keys",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_open",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_heartbeat_inactive",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_close_inactive_consumer",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_ack_deadline",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_retryable_stream_errors",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__should_terminate_true",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__should_recover_false",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_close_idempotent",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__should_terminate_false",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__on_response_with_ordering_keys",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__get_initial_request",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__get_initial_request_wo_leaser",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_lease_load_and_pause",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__maybe_release_messages_on_overload",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_send_streaming",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__on_response_none_data",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_close_no_dispatcher_error",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_constructor_and_default_state",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_close",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__maybe_release_messages_negative_on_hold_bytes_warning",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_constructor_with_options",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_heartbeat",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__maybe_wrap_exception[exception1-GoogleAPICallError]",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_maybe_pause_consumer_wo_consumer_set",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_send_unary_empty",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_drop_and_resume",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_send_unary_retry_error",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_maybe_resume_consumer_wo_consumer_set",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__maybe_release_messages_below_overload",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_send_unary_api_call_error",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__on_response_with_leaser_overload",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__wrap_callback_errors_no_error",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__on_response_delivery_attempt",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test__on_rpc_done",
"tests/unit/pubsub_v1/subscriber/test_streaming_pull_manager.py::test_open_has_been_closed"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-02-26 10:22:38+00:00
|
apache-2.0
| 2,628 |
|
googleapis__python-spanner-316
|
diff --git a/google/cloud/spanner_dbapi/parse_utils.py b/google/cloud/spanner_dbapi/parse_utils.py
index 9ac6f3d..0a7d505 100644
--- a/google/cloud/spanner_dbapi/parse_utils.py
+++ b/google/cloud/spanner_dbapi/parse_utils.py
@@ -37,6 +37,7 @@ TYPES_MAP = {
datetime.date: spanner.param_types.DATE,
DateStr: spanner.param_types.DATE,
TimestampStr: spanner.param_types.TIMESTAMP,
+ decimal.Decimal: spanner.param_types.NUMERIC,
}
SPANNER_RESERVED_KEYWORDS = {
|
googleapis/python-spanner
|
7015fd60a5f1624feacdef6bd018b9b111a3a5ae
|
diff --git a/tests/unit/spanner_dbapi/test_parse_utils.py b/tests/unit/spanner_dbapi/test_parse_utils.py
index c37c604..c612659 100644
--- a/tests/unit/spanner_dbapi/test_parse_utils.py
+++ b/tests/unit/spanner_dbapi/test_parse_utils.py
@@ -353,6 +353,7 @@ class TestParseUtils(unittest.TestCase):
@unittest.skipIf(skip_condition, skip_message)
def test_get_param_types(self):
import datetime
+ import decimal
from google.cloud.spanner_dbapi.parse_utils import DateStr
from google.cloud.spanner_dbapi.parse_utils import TimestampStr
@@ -369,6 +370,7 @@ class TestParseUtils(unittest.TestCase):
"h1": datetime.date(2011, 9, 1),
"i1": b"bytes",
"j1": None,
+ "k1": decimal.Decimal("3.194387483193242e+19"),
}
want_types = {
"a1": param_types.INT64,
@@ -380,6 +382,7 @@ class TestParseUtils(unittest.TestCase):
"g1": param_types.TIMESTAMP,
"h1": param_types.DATE,
"i1": param_types.BYTES,
+ "k1": param_types.NUMERIC,
}
got_types = get_param_types(params)
self.assertEqual(got_types, want_types)
|
float value cannot be used to insert data to NUMERIC field.
Float data type is mapped to float: spanner.param_types.FLOAT64 [Link](https://github.com/googleapis/python-spanner/blob/master/google/cloud/spanner_dbapi/parse_utils.py#L35).
We need to add support to map decimal.Decimal type in python to Numeric type in spanner.
#### Environment details
- OS type and version: MacOS Big Sur 11.2.3
- Python version: 3.8.8
- pip version: pip 21.0.1
- `google-cloud-spanner` version: 3.2.0
#### Steps to reproduce
1. Create a table with Numeric field.
2. Insert data in field with type float
#### Code example
```python
sql='INSERT INTO t (x) VALUES (%s)',
params=[3.194387483193242e+19]
```
Thanks!
|
0.0
|
7015fd60a5f1624feacdef6bd018b9b111a3a5ae
|
[
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_get_param_types"
] |
[
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_cast_for_spanner",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_classify_stmt",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_ensure_where_clause",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_escape_name",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_get_param_types_none",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_insert_from_select",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_parse_insert",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_parse_insert_invalid",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_rows_for_insert_or_update",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_sql_pyformat_args_to_spanner",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_sql_pyformat_args_to_spanner_invalid"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-04-22 13:20:41+00:00
|
apache-2.0
| 2,629 |
|
googleapis__python-spanner-317
|
diff --git a/google/cloud/spanner_dbapi/parse_utils.py b/google/cloud/spanner_dbapi/parse_utils.py
index 0a7d505..1744874 100644
--- a/google/cloud/spanner_dbapi/parse_utils.py
+++ b/google/cloud/spanner_dbapi/parse_utils.py
@@ -509,25 +509,11 @@ def sql_pyformat_args_to_spanner(sql, params):
resolved_value = pyfmt % params
named_args[key] = resolved_value
else:
- named_args[key] = cast_for_spanner(params[i])
+ named_args[key] = params[i]
return sanitize_literals_for_upload(sql), named_args
-def cast_for_spanner(value):
- """Convert the param to its Cloud Spanner equivalent type.
-
- :type value: Any
- :param value: The value to convert to a Cloud Spanner type.
-
- :rtype: Any
- :returns: The value converted to a Cloud Spanner type.
- """
- if isinstance(value, decimal.Decimal):
- return str(value)
- return value
-
-
def get_param_types(params):
"""Determine Cloud Spanner types for the given parameters.
|
googleapis/python-spanner
|
070a1712dc34afb68105194060bb2fe6177fbac5
|
diff --git a/tests/unit/spanner_dbapi/test_parse_utils.py b/tests/unit/spanner_dbapi/test_parse_utils.py
index c612659..73277a7 100644
--- a/tests/unit/spanner_dbapi/test_parse_utils.py
+++ b/tests/unit/spanner_dbapi/test_parse_utils.py
@@ -307,7 +307,7 @@ class TestParseUtils(unittest.TestCase):
),
(
"SELECT (an.p + @a0) AS np FROM an WHERE (an.p + @a1) = @a2",
- {"a0": 1, "a1": 1.0, "a2": str(31)},
+ {"a0": 1, "a1": 1.0, "a2": decimal.Decimal("31")},
),
),
]
@@ -339,17 +339,6 @@ class TestParseUtils(unittest.TestCase):
lambda: sql_pyformat_args_to_spanner(sql, params),
)
- def test_cast_for_spanner(self):
- import decimal
-
- from google.cloud.spanner_dbapi.parse_utils import cast_for_spanner
-
- dec = 3
- value = decimal.Decimal(dec)
- self.assertEqual(cast_for_spanner(value), str(dec))
- self.assertEqual(cast_for_spanner(5), 5)
- self.assertEqual(cast_for_spanner("string"), "string")
-
@unittest.skipIf(skip_condition, skip_message)
def test_get_param_types(self):
import datetime
|
float value cannot be used to insert data to NUMERIC field.
Float data type is mapped to float: spanner.param_types.FLOAT64 [Link](https://github.com/googleapis/python-spanner/blob/master/google/cloud/spanner_dbapi/parse_utils.py#L35).
We need to add support to map decimal.Decimal type in python to Numeric type in spanner.
#### Environment details
- OS type and version: MacOS Big Sur 11.2.3
- Python version: 3.8.8
- pip version: pip 21.0.1
- `google-cloud-spanner` version: 3.2.0
#### Steps to reproduce
1. Create a table with Numeric field.
2. Insert data in field with type float
#### Code example
```python
sql='INSERT INTO t (x) VALUES (%s)',
params=[3.194387483193242e+19]
```
Thanks!
|
0.0
|
070a1712dc34afb68105194060bb2fe6177fbac5
|
[
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_sql_pyformat_args_to_spanner"
] |
[
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_classify_stmt",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_ensure_where_clause",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_escape_name",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_get_param_types",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_get_param_types_none",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_insert_from_select",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_parse_insert",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_parse_insert_invalid",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_rows_for_insert_or_update",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_sql_pyformat_args_to_spanner_invalid"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-04-23 16:51:25+00:00
|
apache-2.0
| 2,630 |
|
googleapis__python-spanner-340
|
diff --git a/google/cloud/spanner_v1/_helpers.py b/google/cloud/spanner_v1/_helpers.py
index a9ae36d..1385809 100644
--- a/google/cloud/spanner_v1/_helpers.py
+++ b/google/cloud/spanner_v1/_helpers.py
@@ -30,6 +30,16 @@ from google.cloud.spanner_v1 import TypeCode
from google.cloud.spanner_v1 import ExecuteSqlRequest
+# Validation error messages
+NUMERIC_MAX_SCALE_ERR_MSG = (
+ "Max scale for a numeric is 9. The requested numeric has scale {}"
+)
+NUMERIC_MAX_PRECISION_ERR_MSG = (
+ "Max precision for the whole component of a numeric is 29. The requested "
+ + "numeric has a whole component with precision {}"
+)
+
+
def _try_to_coerce_bytes(bytestring):
"""Try to coerce a byte string into the right thing based on Python
version and whether or not it is base64 encoded.
@@ -87,6 +97,28 @@ def _merge_query_options(base, merge):
return combined
+def _assert_numeric_precision_and_scale(value):
+ """
+ Asserts that input numeric field is within Spanner supported range.
+
+ Spanner supports fixed 38 digits of precision and 9 digits of scale.
+ This number can be optionally prefixed with a plus or minus sign.
+ Read more here: https://cloud.google.com/spanner/docs/data-types#numeric_type
+
+ :type value: decimal.Decimal
+ :param value: The value to check for Cloud Spanner compatibility.
+
+ :raises NotSupportedError: If value is not within supported precision or scale of Spanner.
+ """
+ scale = value.as_tuple().exponent
+ precision = len(value.as_tuple().digits)
+
+ if scale < -9:
+ raise ValueError(NUMERIC_MAX_SCALE_ERR_MSG.format(abs(scale)))
+ if precision + scale > 29:
+ raise ValueError(NUMERIC_MAX_PRECISION_ERR_MSG.format(precision + scale))
+
+
# pylint: disable=too-many-return-statements,too-many-branches
def _make_value_pb(value):
"""Helper for :func:`_make_list_value_pbs`.
@@ -129,6 +161,7 @@ def _make_value_pb(value):
if isinstance(value, ListValue):
return Value(list_value=value)
if isinstance(value, decimal.Decimal):
+ _assert_numeric_precision_and_scale(value)
return Value(string_value=str(value))
raise ValueError("Unknown type: %s" % (value,))
|
googleapis/python-spanner
|
bf2791dbc7b2489b70cbd44fe7b108b098f57b57
|
diff --git a/tests/unit/spanner_dbapi/test_parse_utils.py b/tests/unit/spanner_dbapi/test_parse_utils.py
index 73277a7..11239d7 100644
--- a/tests/unit/spanner_dbapi/test_parse_utils.py
+++ b/tests/unit/spanner_dbapi/test_parse_utils.py
@@ -254,8 +254,6 @@ class TestParseUtils(unittest.TestCase):
@unittest.skipIf(skip_condition, skip_message)
def test_sql_pyformat_args_to_spanner(self):
- import decimal
-
from google.cloud.spanner_dbapi.parse_utils import sql_pyformat_args_to_spanner
cases = [
@@ -300,16 +298,6 @@ class TestParseUtils(unittest.TestCase):
("SELECT * from t WHERE id=10", {"f1": "app", "f2": "name"}),
("SELECT * from t WHERE id=10", {"f1": "app", "f2": "name"}),
),
- (
- (
- "SELECT (an.p + %s) AS np FROM an WHERE (an.p + %s) = %s",
- (1, 1.0, decimal.Decimal("31")),
- ),
- (
- "SELECT (an.p + @a0) AS np FROM an WHERE (an.p + @a1) = @a2",
- {"a0": 1, "a1": 1.0, "a2": decimal.Decimal("31")},
- ),
- ),
]
for ((sql_in, params), sql_want) in cases:
with self.subTest(sql=sql_in):
diff --git a/tests/unit/test__helpers.py b/tests/unit/test__helpers.py
index fecf258..305a6ce 100644
--- a/tests/unit/test__helpers.py
+++ b/tests/unit/test__helpers.py
@@ -233,6 +233,65 @@ class Test_make_value_pb(unittest.TestCase):
with self.assertRaises(ValueError):
self._callFUT(object())
+ def test_w_numeric_precision_and_scale_valid(self):
+ import decimal
+ from google.protobuf.struct_pb2 import Value
+
+ cases = [
+ decimal.Decimal("42"),
+ decimal.Decimal("9.9999999999999999999999999999999999999E+28"),
+ decimal.Decimal("-9.9999999999999999999999999999999999999E+28"),
+ decimal.Decimal("99999999999999999999999999999.999999999"),
+ decimal.Decimal("1E+28"),
+ decimal.Decimal("1E-9"),
+ ]
+ for value in cases:
+ with self.subTest(value=value):
+ value_pb = self._callFUT(value)
+ self.assertIsInstance(value_pb, Value)
+ self.assertEqual(value_pb.string_value, str(value))
+
+ def test_w_numeric_precision_and_scale_invalid(self):
+ import decimal
+ from google.cloud.spanner_v1._helpers import (
+ NUMERIC_MAX_SCALE_ERR_MSG,
+ NUMERIC_MAX_PRECISION_ERR_MSG,
+ )
+
+ max_precision_error_msg = NUMERIC_MAX_PRECISION_ERR_MSG.format("30")
+ max_scale_error_msg = NUMERIC_MAX_SCALE_ERR_MSG.format("10")
+
+ cases = [
+ (
+ decimal.Decimal("9.9999999999999999999999999999999999999E+29"),
+ max_precision_error_msg,
+ ),
+ (
+ decimal.Decimal("-9.9999999999999999999999999999999999999E+29"),
+ max_precision_error_msg,
+ ),
+ (
+ decimal.Decimal("999999999999999999999999999999.99999999"),
+ max_precision_error_msg,
+ ),
+ (
+ decimal.Decimal("-999999999999999999999999999999.99999999"),
+ max_precision_error_msg,
+ ),
+ (
+ decimal.Decimal("999999999999999999999999999999"),
+ max_precision_error_msg,
+ ),
+ (decimal.Decimal("1E+29"), max_precision_error_msg),
+ (decimal.Decimal("1E-10"), max_scale_error_msg),
+ ]
+
+ for value, err_msg in cases:
+ with self.subTest(value=value, err_msg=err_msg):
+ self.assertRaisesRegex(
+ ValueError, err_msg, lambda: self._callFUT(value),
+ )
+
class Test_make_list_value_pb(unittest.TestCase):
def _callFUT(self, *args, **kw):
|
Add validation in decimal to numeric conversion
Add validation in decimal to numeric conversion to ensure precision and recall is supported by spanner.
read more here: https://cloud.google.com/spanner/docs/data-types#numeric_type.
Similar validations are present in other clients eg: https://github.com/googleapis/java-spanner/blob/master/google-cloud-spanner/src/main/java/com/google/cloud/spanner/Value.java#L141-L155
|
0.0
|
bf2791dbc7b2489b70cbd44fe7b108b098f57b57
|
[
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_numeric_precision_and_scale_invalid"
] |
[
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_classify_stmt",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_ensure_where_clause",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_escape_name",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_get_param_types",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_get_param_types_none",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_insert_from_select",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_parse_insert",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_parse_insert_invalid",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_rows_for_insert_or_update",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_sql_pyformat_args_to_spanner",
"tests/unit/spanner_dbapi/test_parse_utils.py::TestParseUtils::test_sql_pyformat_args_to_spanner_invalid",
"tests/unit/test__helpers.py::Test_merge_query_options::test_base_dict_and_merge_none",
"tests/unit/test__helpers.py::Test_merge_query_options::test_base_empty_and_merge_empty",
"tests/unit/test__helpers.py::Test_merge_query_options::test_base_none_and_merge_none",
"tests/unit/test__helpers.py::Test_merge_query_options::test_base_none_merge_dict",
"tests/unit/test__helpers.py::Test_merge_query_options::test_base_none_merge_object",
"tests/unit/test__helpers.py::Test_merge_query_options::test_base_object_merge_dict",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_None",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_bool",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_bytes",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_date",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_explicit_unicode",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_float",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_float_nan",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_float_neg_inf",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_float_pos_inf",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_int",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_invalid_bytes",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_list",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_listvalue",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_numeric",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_numeric_precision_and_scale_valid",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_tuple",
"tests/unit/test__helpers.py::Test_make_value_pb::test_w_unknown_type",
"tests/unit/test__helpers.py::Test_make_list_value_pb::test_empty",
"tests/unit/test__helpers.py::Test_make_list_value_pb::test_w_multiple_values",
"tests/unit/test__helpers.py::Test_make_list_value_pb::test_w_single_value",
"tests/unit/test__helpers.py::Test_make_list_value_pbs::test_empty",
"tests/unit/test__helpers.py::Test_make_list_value_pbs::test_w_multiple_values",
"tests/unit/test__helpers.py::Test_make_list_value_pbs::test_w_single_values",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_array_empty",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_array_non_empty",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_bool",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_bytes",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_date",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_float",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_float_str",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_int",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_null",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_numeric",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_string",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_struct",
"tests/unit/test__helpers.py::Test_parse_value_pb::test_w_unknown_type",
"tests/unit/test__helpers.py::Test_parse_list_value_pbs::test_empty",
"tests/unit/test__helpers.py::Test_parse_list_value_pbs::test_non_empty",
"tests/unit/test__helpers.py::Test_SessionWrapper::test_ctor",
"tests/unit/test__helpers.py::Test_metadata_with_prefix::test"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-05-12 10:27:32+00:00
|
apache-2.0
| 2,631 |
|
googleapis__python-spanner-django-462
|
diff --git a/django_spanner/base.py b/django_spanner/base.py
index 70f5b1ba39..f5d2c835d5 100644
--- a/django_spanner/base.py
+++ b/django_spanner/base.py
@@ -18,62 +18,62 @@ from .validation import DatabaseValidation
class DatabaseWrapper(BaseDatabaseWrapper):
- vendor = 'spanner'
- display_name = 'Cloud Spanner'
+ vendor = "spanner"
+ display_name = "Cloud Spanner"
# Mapping of Field objects to their column types.
# https://cloud.google.com/spanner/docs/data-types#date-type
data_types = {
- 'AutoField': 'INT64',
- 'BigAutoField': 'INT64',
- 'BinaryField': 'BYTES(MAX)',
- 'BooleanField': 'BOOL',
- 'CharField': 'STRING(%(max_length)s)',
- 'DateField': 'DATE',
- 'DateTimeField': 'TIMESTAMP',
- 'DecimalField': 'FLOAT64',
- 'DurationField': 'INT64',
- 'EmailField': 'STRING(%(max_length)s)',
- 'FileField': 'STRING(%(max_length)s)',
- 'FilePathField': 'STRING(%(max_length)s)',
- 'FloatField': 'FLOAT64',
- 'IntegerField': 'INT64',
- 'BigIntegerField': 'INT64',
- 'IPAddressField': 'STRING(15)',
- 'GenericIPAddressField': 'STRING(39)',
- 'NullBooleanField': 'BOOL',
- 'OneToOneField': 'INT64',
- 'PositiveIntegerField': 'INT64',
- 'PositiveSmallIntegerField': 'INT64',
- 'SlugField': 'STRING(%(max_length)s)',
- 'SmallAutoField': 'INT64',
- 'SmallIntegerField': 'INT64',
- 'TextField': 'STRING(MAX)',
- 'TimeField': 'TIMESTAMP',
- 'UUIDField': 'STRING(32)',
+ "AutoField": "INT64",
+ "BigAutoField": "INT64",
+ "BinaryField": "BYTES(MAX)",
+ "BooleanField": "BOOL",
+ "CharField": "STRING(%(max_length)s)",
+ "DateField": "DATE",
+ "DateTimeField": "TIMESTAMP",
+ "DecimalField": "FLOAT64",
+ "DurationField": "INT64",
+ "EmailField": "STRING(%(max_length)s)",
+ "FileField": "STRING(%(max_length)s)",
+ "FilePathField": "STRING(%(max_length)s)",
+ "FloatField": "FLOAT64",
+ "IntegerField": "INT64",
+ "BigIntegerField": "INT64",
+ "IPAddressField": "STRING(15)",
+ "GenericIPAddressField": "STRING(39)",
+ "NullBooleanField": "BOOL",
+ "OneToOneField": "INT64",
+ "PositiveIntegerField": "INT64",
+ "PositiveSmallIntegerField": "INT64",
+ "SlugField": "STRING(%(max_length)s)",
+ "SmallAutoField": "INT64",
+ "SmallIntegerField": "INT64",
+ "TextField": "STRING(MAX)",
+ "TimeField": "TIMESTAMP",
+ "UUIDField": "STRING(32)",
}
operators = {
- 'exact': '= %s',
- 'iexact': 'REGEXP_CONTAINS(%s, %%%%s)',
+ "exact": "= %s",
+ "iexact": "REGEXP_CONTAINS(%s, %%%%s)",
# contains uses REGEXP_CONTAINS instead of LIKE to allow
# DatabaseOperations.prep_for_like_query() to do regular expression
# escaping. prep_for_like_query() is called for all the lookups that
# use REGEXP_CONTAINS except regex/iregex (see
# django.db.models.lookups.PatternLookup).
- 'contains': 'REGEXP_CONTAINS(%s, %%%%s)',
- 'icontains': 'REGEXP_CONTAINS(%s, %%%%s)',
- 'gt': '> %s',
- 'gte': '>= %s',
- 'lt': '< %s',
- 'lte': '<= %s',
+ "contains": "REGEXP_CONTAINS(%s, %%%%s)",
+ "icontains": "REGEXP_CONTAINS(%s, %%%%s)",
+ "gt": "> %s",
+ "gte": ">= %s",
+ "lt": "< %s",
+ "lte": "<= %s",
# Using REGEXP_CONTAINS instead of STARTS_WITH and ENDS_WITH for the
# same reasoning as described above for 'contains'.
- 'startswith': 'REGEXP_CONTAINS(%s, %%%%s)',
- 'endswith': 'REGEXP_CONTAINS(%s, %%%%s)',
- 'istartswith': 'REGEXP_CONTAINS(%s, %%%%s)',
- 'iendswith': 'REGEXP_CONTAINS(%s, %%%%s)',
- 'regex': 'REGEXP_CONTAINS(%s, %%%%s)',
- 'iregex': 'REGEXP_CONTAINS(%s, %%%%s)',
+ "startswith": "REGEXP_CONTAINS(%s, %%%%s)",
+ "endswith": "REGEXP_CONTAINS(%s, %%%%s)",
+ "istartswith": "REGEXP_CONTAINS(%s, %%%%s)",
+ "iendswith": "REGEXP_CONTAINS(%s, %%%%s)",
+ "regex": "REGEXP_CONTAINS(%s, %%%%s)",
+ "iregex": "REGEXP_CONTAINS(%s, %%%%s)",
}
# pattern_esc is used to generate SQL pattern lookup clauses when the
@@ -81,16 +81,18 @@ class DatabaseWrapper(BaseDatabaseWrapper):
# expression or the result of a bilateral transformation). In those cases,
# special characters for REGEXP_CONTAINS operators (e.g. \, *, _) must be
# escaped on database side.
- pattern_esc = r'REPLACE(REPLACE(REPLACE({}, "\\", "\\\\"), "%%", r"\%%"), "_", r"\_")'
+ pattern_esc = (
+ r'REPLACE(REPLACE(REPLACE({}, "\\", "\\\\"), "%%", r"\%%"), "_", r"\_")'
+ )
# These are all no-ops in favor of using REGEXP_CONTAINS in the customized
# lookups.
pattern_ops = {
- 'contains': '',
- 'icontains': '',
- 'startswith': '',
- 'istartswith': '',
- 'endswith': '',
- 'iendswith': '',
+ "contains": "",
+ "icontains": "",
+ "startswith": "",
+ "istartswith": "",
+ "endswith": "",
+ "iendswith": "",
}
Database = Database
@@ -104,7 +106,7 @@ class DatabaseWrapper(BaseDatabaseWrapper):
@property
def instance(self):
- return spanner.Client().instance(self.settings_dict['INSTANCE'])
+ return spanner.Client().instance(self.settings_dict["INSTANCE"])
@property
def _nodb_connection(self):
@@ -112,11 +114,11 @@ class DatabaseWrapper(BaseDatabaseWrapper):
def get_connection_params(self):
return {
- 'project': self.settings_dict['PROJECT'],
- 'instance': self.settings_dict['INSTANCE'],
- 'database': self.settings_dict['NAME'],
- 'user_agent': 'django_spanner/0.0.1',
- **self.settings_dict['OPTIONS'],
+ "project": self.settings_dict["PROJECT"],
+ "instance_id": self.settings_dict["INSTANCE"],
+ "database_id": self.settings_dict["NAME"],
+ "user_agent": "django_spanner/0.0.1",
+ **self.settings_dict["OPTIONS"],
}
def get_new_connection(self, conn_params):
@@ -137,7 +139,7 @@ class DatabaseWrapper(BaseDatabaseWrapper):
return False
try:
# Use a cursor directly, bypassing Django's utilities.
- self.connection.cursor().execute('SELECT 1')
+ self.connection.cursor().execute("SELECT 1")
except Database.Error:
return False
else:
diff --git a/setup.cfg b/setup.cfg
index f9e8dff043..43c26175ef 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -2,8 +2,10 @@
max-line-length = 119
[isort]
+use_parentheses=True
combine_as_imports = true
default_section = THIRDPARTY
include_trailing_comma = true
+force_grid_wrap=0
line_length = 79
-multi_line_output = 5
+multi_line_output = 3
\ No newline at end of file
diff --git a/spanner_dbapi/__init__.py b/spanner_dbapi/__init__.py
index f5d349a655..58037106ca 100644
--- a/spanner_dbapi/__init__.py
+++ b/spanner_dbapi/__init__.py
@@ -4,83 +4,122 @@
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
-from google.cloud import spanner_v1 as spanner
+"""Connection-based DB API for Cloud Spanner."""
+
+from google.cloud import spanner_v1
from .connection import Connection
-# These need to be included in the top-level package for PEP-0249 DB API v2.
from .exceptions import (
- DatabaseError, DataError, Error, IntegrityError, InterfaceError,
- InternalError, NotSupportedError, OperationalError, ProgrammingError,
+ DatabaseError,
+ DataError,
+ Error,
+ IntegrityError,
+ InterfaceError,
+ InternalError,
+ NotSupportedError,
+ OperationalError,
+ ProgrammingError,
Warning,
)
from .parse_utils import get_param_types
from .types import (
- BINARY, DATETIME, NUMBER, ROWID, STRING, Binary, Date, DateFromTicks, Time,
- TimeFromTicks, Timestamp, TimestampFromTicks,
+ BINARY,
+ DATETIME,
+ NUMBER,
+ ROWID,
+ STRING,
+ Binary,
+ Date,
+ DateFromTicks,
+ Time,
+ TimeFromTicks,
+ Timestamp,
+ TimestampFromTicks,
)
from .version import google_client_info
-# Globals that MUST be defined ###
-apilevel = "2.0" # Implements the Python Database API specification 2.0 version.
-# We accept arguments in the format '%s' aka ANSI C print codes.
-# as per https://www.python.org/dev/peps/pep-0249/#paramstyle
-paramstyle = 'format'
-# Threads may share the module but not connections. This is a paranoid threadsafety level,
-# but it is necessary for starters to use when debugging failures. Eventually once transactions
-# are working properly, we'll update the threadsafety level.
+apilevel = "2.0" # supports DP-API 2.0 level.
+paramstyle = "format" # ANSI C printf format codes, e.g. ...WHERE name=%s.
+
+# Threads may share the module, but not connections. This is a paranoid threadsafety
+# level, but it is necessary for starters to use when debugging failures.
+# Eventually once transactions are working properly, we'll update the
+# threadsafety level.
threadsafety = 1
-def connect(project=None, instance=None, database=None, credentials_uri=None, user_agent=None):
+def connect(instance_id, database_id, project=None, credentials=None, user_agent=None):
"""
- Connect to Cloud Spanner.
+ Create a connection to Cloud Spanner database.
- Args:
- project: The id of a project that already exists.
- instance: The id of an instance that already exists.
- database: The name of a database that already exists.
- credentials_uri: An optional string specifying where to retrieve the service
- account JSON for the credentials to connect to Cloud Spanner.
+ :type instance_id: :class:`str`
+ :param instance_id: ID of the instance to connect to.
- Returns:
- The Connection object associated to the Cloud Spanner instance.
+ :type database_id: :class:`str`
+ :param database_id: The name of the database to connect to.
- Raises:
- Error if it encounters any unexpected inputs.
- """
- if not project:
- raise Error("'project' is required.")
- if not instance:
- raise Error("'instance' is required.")
- if not database:
- raise Error("'database' is required.")
+ :type project: :class:`str`
+ :param project: (Optional) The ID of the project which owns the
+ instances, tables and data. If not provided, will
+ attempt to determine from the environment.
- client_kwargs = {
- 'project': project,
- 'client_info': google_client_info(user_agent),
- }
- if credentials_uri:
- client = spanner.Client.from_service_account_json(credentials_uri, **client_kwargs)
- else:
- client = spanner.Client(**client_kwargs)
+ :type credentials: :class:`google.auth.credentials.Credentials`
+ :param credentials: (Optional) The authorization credentials to attach to requests.
+ These credentials identify this application to the service.
+ If none are specified, the client will attempt to ascertain
+ the credentials from the environment.
+
+ :rtype: :class:`google.cloud.spanner_dbapi.connection.Connection`
+ :returns: Connection object associated with the given Cloud Spanner resource.
+
+ :raises: :class:`ValueError` in case of given instance/database
+ doesn't exist.
+ """
+ client = spanner_v1.Client(
+ project=project,
+ credentials=credentials,
+ client_info=google_client_info(user_agent),
+ )
- client_instance = client.instance(instance)
- if not client_instance.exists():
- raise ProgrammingError("instance '%s' does not exist." % instance)
+ instance = client.instance(instance_id)
+ if not instance.exists():
+ raise ValueError("instance '%s' does not exist." % instance_id)
- db = client_instance.database(database, pool=spanner.pool.BurstyPool())
- if not db.exists():
- raise ProgrammingError("database '%s' does not exist." % database)
+ database = instance.database(database_id, pool=spanner_v1.pool.BurstyPool())
+ if not database.exists():
+ raise ValueError("database '%s' does not exist." % database_id)
- return Connection(db)
+ return Connection(database)
__all__ = [
- 'DatabaseError', 'DataError', 'Error', 'IntegrityError', 'InterfaceError',
- 'InternalError', 'NotSupportedError', 'OperationalError', 'ProgrammingError',
- 'Warning', 'DEFAULT_USER_AGENT', 'apilevel', 'connect', 'paramstyle', 'threadsafety',
- 'get_param_types',
- 'Binary', 'Date', 'DateFromTicks', 'Time', 'TimeFromTicks', 'Timestamp',
- 'TimestampFromTicks',
- 'BINARY', 'STRING', 'NUMBER', 'DATETIME', 'ROWID', 'TimestampStr',
+ "DatabaseError",
+ "DataError",
+ "Error",
+ "IntegrityError",
+ "InterfaceError",
+ "InternalError",
+ "NotSupportedError",
+ "OperationalError",
+ "ProgrammingError",
+ "Warning",
+ "DEFAULT_USER_AGENT",
+ "apilevel",
+ "connect",
+ "paramstyle",
+ "threadsafety",
+ "get_param_types",
+ "Binary",
+ "Date",
+ "DateFromTicks",
+ "Time",
+ "TimeFromTicks",
+ "Timestamp",
+ "TimestampFromTicks",
+ "BINARY",
+ "STRING",
+ "NUMBER",
+ "DATETIME",
+ "ROWID",
+ "TimestampStr",
]
|
googleapis/python-spanner-django
|
5551b58d7983edc57f0482000254ea2df21476d6
|
diff --git a/tests/spanner_dbapi/test_connect.py b/tests/spanner_dbapi/test_connect.py
new file mode 100644
index 0000000000..64eaf8cd7d
--- /dev/null
+++ b/tests/spanner_dbapi/test_connect.py
@@ -0,0 +1,97 @@
+# Copyright 2020 Google LLC
+#
+# Use of this source code is governed by a BSD-style
+# license that can be found in the LICENSE file or at
+# https://developers.google.com/open-source/licenses/bsd
+
+"""connect() module function unit tests."""
+
+import unittest
+from unittest import mock
+
+import google.auth.credentials
+from google.api_core.gapic_v1.client_info import ClientInfo
+from spanner_dbapi import connect, Connection
+
+
+def _make_credentials():
+ class _CredentialsWithScopes(
+ google.auth.credentials.Credentials, google.auth.credentials.Scoped
+ ):
+ pass
+
+ return mock.Mock(spec=_CredentialsWithScopes)
+
+
+class Test_connect(unittest.TestCase):
+ def test_connect(self):
+ PROJECT = "test-project"
+ USER_AGENT = "user-agent"
+ CREDENTIALS = _make_credentials()
+ CLIENT_INFO = ClientInfo(user_agent=USER_AGENT)
+
+ with mock.patch("spanner_dbapi.spanner_v1.Client") as client_mock:
+ with mock.patch(
+ "spanner_dbapi.google_client_info", return_value=CLIENT_INFO
+ ) as client_info_mock:
+
+ connection = connect(
+ "test-instance", "test-database", PROJECT, CREDENTIALS, USER_AGENT
+ )
+
+ self.assertIsInstance(connection, Connection)
+ client_info_mock.assert_called_once_with(USER_AGENT)
+
+ client_mock.assert_called_once_with(
+ project=PROJECT, credentials=CREDENTIALS, client_info=CLIENT_INFO
+ )
+
+ def test_instance_not_found(self):
+ with mock.patch(
+ "google.cloud.spanner_v1.instance.Instance.exists", return_value=False
+ ) as exists_mock:
+
+ with self.assertRaises(ValueError):
+ connect("test-instance", "test-database")
+
+ exists_mock.assert_called_once_with()
+
+ def test_database_not_found(self):
+ with mock.patch(
+ "google.cloud.spanner_v1.instance.Instance.exists", return_value=True
+ ):
+ with mock.patch(
+ "google.cloud.spanner_v1.database.Database.exists", return_value=False
+ ) as exists_mock:
+
+ with self.assertRaises(ValueError):
+ connect("test-instance", "test-database")
+
+ exists_mock.assert_called_once_with()
+
+ def test_connect_instance_id(self):
+ INSTANCE = "test-instance"
+
+ with mock.patch(
+ "google.cloud.spanner_v1.client.Client.instance"
+ ) as instance_mock:
+ connection = connect(INSTANCE, "test-database")
+
+ instance_mock.assert_called_once_with(INSTANCE)
+
+ self.assertIsInstance(connection, Connection)
+
+ def test_connect_database_id(self):
+ DATABASE = "test-database"
+
+ with mock.patch(
+ "google.cloud.spanner_v1.instance.Instance.database"
+ ) as database_mock:
+ with mock.patch(
+ "google.cloud.spanner_v1.instance.Instance.exists", return_value=True
+ ):
+ connection = connect("test-instance", DATABASE)
+
+ database_mock.assert_called_once_with(DATABASE, pool=mock.ANY)
+
+ self.assertIsInstance(connection, Connection)
|
connect() surface issues
Looking at `connect()` function, there are several things which are raising questions.
**project arg:**
`project` is set as an optional arg: https://github.com/googleapis/python-spanner-django/blob/11222db2f82fd50ca87010321ded0b39021eb884/spanner_dbapi/__init__.py#L34 But few lines lower it is checked for existence (thus, it's required, not optional): https://github.com/googleapis/python-spanner-django/blob/11222db2f82fd50ca87010321ded0b39021eb884/spanner_dbapi/__init__.py#L51-L52 It seems to be pointless, as this arg is only passed to Spanner client, and the original Spanner client can handle an omitted project: it'll use `google.auth.default()` function to designate the project id from the environment. With this, I'd propose to drop this check and use `project` arg in the way of the original Spanner client.
**instance and database args:**
They are optional by definition, but in fact both are required. Probably, they should become required in definition (the function signature will be `connect(instance, database, project=None, credentials_uri=None, user_agent=None):`), so these checks could be dropped:
https://github.com/googleapis/python-spanner-django/blob/11222db2f82fd50ca87010321ded0b39021eb884/spanner_dbapi/__init__.py#L53-L56
**credentials_uri arg:**
This arg looks divergent from how the original Spanner client is dealing with credentials:
https://github.com/googleapis/python-spanner/blob/b6b0348f5870f55c88b3cae44e229325fd755b26/google/cloud/spanner_v1/client.py#L123-L129
I'd propose to change this arg to use `google.auth.credentials.Credentials` class as it's done in the original Spanner client.
|
0.0
|
5551b58d7983edc57f0482000254ea2df21476d6
|
[
"tests/spanner_dbapi/test_connect.py::Test_connect::test_connect"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-08-21 09:12:32+00:00
|
bsd-3-clause
| 2,632 |
|
googleapis__synthtool-1951
|
diff --git a/synthtool/gcp/templates/python_library/.github/blunderbuss.yml b/synthtool/gcp/templates/python_library/.github/blunderbuss.yml
index 18a3ed8..22ab79e 100644
--- a/synthtool/gcp/templates/python_library/.github/blunderbuss.yml
+++ b/synthtool/gcp/templates/python_library/.github/blunderbuss.yml
@@ -5,17 +5,23 @@
# team, please update `codeowner_team` in `.repo-metadata.json`.
{% if metadata['repo']['codeowner_team']|length -%}
assign_issues:
- - {{ metadata['repo']['codeowner_team'].replace("@","") }}
+ {%- for codeowner in metadata['repo']['codeowner_team'].replace("@","").split(" ") %}
+ - {{ codeowner }}
+ {%- endfor %}
assign_issues_by:
- labels:
- "samples"
to:
- googleapis/python-samples-reviewers
- - {{ metadata['repo']['codeowner_team'].replace("@","") }}
+ {%- for codeowner in metadata['repo']['codeowner_team'].replace("@","").split(" ") %}
+ - {{ codeowner }}
+ {%- endfor %}
assign_prs:
- - {{ metadata['repo']['codeowner_team'].replace("@","") }}
+ {%- for codeowner in metadata['repo']['codeowner_team'].replace("@","").split(" ") %}
+ - {{ codeowner }}
+ {%- endfor %}
{% else %}
assign_issues:
- googleapis/python-core-client-libraries
|
googleapis/synthtool
|
223f39e29577145d4238a522633c2f3e5e6dc8dc
|
diff --git a/tests/test_python_library.py b/tests/test_python_library.py
index 0019ba7..b4d5019 100644
--- a/tests/test_python_library.py
+++ b/tests/test_python_library.py
@@ -178,7 +178,7 @@ def assert_valid_yaml(file):
pytest.fail(f"unable to parse YAML: {file}")
-def test_library_blunderbuss():
+def test_library_blunderbuss_single_codeowner():
t = templates.Templates(PYTHON_LIBRARY / ".github")
result = t.render(
"blunderbuss.yml",
@@ -188,6 +188,7 @@ def test_library_blunderbuss():
config = yaml.safe_load(result)
assert "googleapis/python-core-client-libraries" not in config["assign_issues"]
assert "googleapis/foo" in config["assign_issues"]
+ assert "googleapis/foo" in config["assign_prs"]
assert (
"googleapis/python-samples-reviewers" in config["assign_issues_by"][0]["to"]
)
@@ -196,6 +197,28 @@ def test_library_blunderbuss():
pytest.fail(f"unable to parse YAML: {result}")
+def test_library_blunderbuss_multiple_codeowner():
+ t = templates.Templates(PYTHON_LIBRARY / ".github")
+ result = t.render(
+ "blunderbuss.yml",
+ metadata={"repo": {"codeowner_team": "googleapis/foo googleapis/bar"}},
+ ).read_text()
+ try:
+ config = yaml.safe_load(result)
+ assert "googleapis/python-core-client-libraries" not in config["assign_issues"]
+ assert "googleapis/foo" in config["assign_issues"]
+ assert "googleapis/bar" in config["assign_issues"]
+ assert "googleapis/foo" in config["assign_prs"]
+ assert "googleapis/bar" in config["assign_prs"]
+ assert (
+ "googleapis/python-samples-reviewers" in config["assign_issues_by"][0]["to"]
+ )
+ assert "googleapis/foo" in config["assign_issues_by"][0]["to"]
+ assert "googleapis/bar" in config["assign_issues_by"][0]["to"]
+ except yaml.YAMLError:
+ pytest.fail(f"unable to parse YAML: {result}")
+
+
def test_library_blunderbuss_no_codeowner():
t = templates.Templates(PYTHON_LIBRARY / ".github")
result = t.render(
|
Support multiple `codeowner_team`s in `.repo-metadata.json`
Today you can add a `codeowner_team` to `.repo-metadata.json`, and it will add that team as a CODEOWNER along side the language specific team. There are cases where we want multiple teams, often both a DPE team and a product engineering team that need CODEOWERS access. Ideally, `codeowner_team` would support both a string, and an array.
Today, we would need to:
- hand modify the `CODEOWNERS` file
- Add `CODEOWNERS` to the ignore list `synth.py` when copying templates
|
0.0
|
223f39e29577145d4238a522633c2f3e5e6dc8dc
|
[
"tests/test_python_library.py::test_library_blunderbuss_multiple_codeowner"
] |
[
"tests/test_python_library.py::test_library_noxfile[template_kwargs0-expected_text0]",
"tests/test_python_library.py::test_library_noxfile[template_kwargs1-expected_text1]",
"tests/test_python_library.py::test_library_noxfile[template_kwargs2-expected_text2]",
"tests/test_python_library.py::test_library_noxfile[template_kwargs3-expected_text3]",
"tests/test_python_library.py::test_library_noxfile[template_kwargs4-SYSTEM_TEST_EXTRAS:",
"tests/test_python_library.py::test_library_noxfile[template_kwargs5-expected_text5]",
"tests/test_python_library.py::test_library_noxfile[template_kwargs6-expected_text6]",
"tests/test_python_library.py::test_library_noxfile[template_kwargs7-expected_text7]",
"tests/test_python_library.py::test_library_noxfile[template_kwargs8-expected_text8]",
"tests/test_python_library.py::test_library_codeowners",
"tests/test_python_library.py::test_library_codeowners_without_metadata",
"tests/test_python_library.py::test_library_blunderbuss_single_codeowner",
"tests/test_python_library.py::test_library_blunderbuss_no_codeowner",
"tests/test_python_library.py::test_python_library",
"tests/test_python_library.py::test_split_system_tests",
"tests/test_python_library.py::test_configure_previous_major_version_branches[fixtures_dir0]",
"tests/test_python_library.py::test_configure_previous_major_version_branches[fixtures_dir1]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2024-04-10 11:39:56+00:00
|
apache-2.0
| 2,633 |
|
googleapis__synthtool-348
|
diff --git a/synthtool/transforms.py b/synthtool/transforms.py
index 2d10984..1fb43ec 100644
--- a/synthtool/transforms.py
+++ b/synthtool/transforms.py
@@ -185,35 +185,37 @@ def _replace_in_file(path, expr, replacement):
# Don't bother writing the file if we didn't change
# anything.
- if not count:
- return False
-
- fh.seek(0)
- fh.write(content)
- fh.truncate()
-
- return True
+ if count:
+ fh.seek(0)
+ fh.write(content)
+ fh.truncate()
+ return count
def replace(
sources: ListOfPathsOrStrs, before: str, after: str, flags: int = re.MULTILINE
-):
- """Replaces occurrences of before with after in all the given sources."""
+) -> int:
+ """Replaces occurrences of before with after in all the given sources.
+
+ Returns:
+ The number of times the text was found and replaced across all files.
+ """
expr = re.compile(before, flags=flags or 0)
paths = _filter_files(_expand_paths(sources, "."))
if not paths:
log.warning(f"No files were found in sources {sources} for replace()")
- any_replaced = False
+ count_replaced = 0
for path in paths:
replaced = _replace_in_file(path, expr, after)
- any_replaced = any_replaced or replaced
+ count_replaced += replaced
if replaced:
log.info(f"Replaced {before!r} in {path}.")
- if not any_replaced:
+ if not count_replaced:
log.warning(
f"No replacements made in {sources} for pattern {before}, maybe "
"replacement is not longer needed?"
)
+ return count_replaced
|
googleapis/synthtool
|
bb9c4d567016696a17664923270d2f0f4c79ef64
|
diff --git a/tests/test_transforms.py b/tests/test_transforms.py
index 0f37382..d26812a 100644
--- a/tests/test_transforms.py
+++ b/tests/test_transforms.py
@@ -27,18 +27,18 @@ from synthtool import _tracked_paths
@pytest.fixture()
def expand_path_fixtures(tmpdir):
- files = [
- "a.txt",
- "b.py",
- "c.md",
- normpath("dira/e.txt"),
- normpath("dira/f.py"),
- normpath("dirb/suba/g.py"),
- ]
-
- for file in files:
- path = tmpdir.join(file)
- path.write_text("content", encoding="utf-8", ensure=True)
+ files = {
+ "a.txt": "alpha text",
+ "b.py": "beta python",
+ "c.md": "see markdown",
+ "dira/e.txt": "epsilon text",
+ "dira/f.py": "eff python",
+ "dirb/suba/g.py": "gamma python",
+ }
+
+ for file_name, content in files.items():
+ path = tmpdir.join(normpath(file_name))
+ path.write_text(content, encoding="utf-8", ensure=True)
cwd = os.getcwd()
os.chdir(str(tmpdir))
@@ -165,3 +165,24 @@ def test__move_to_dest_subdir(expand_path_fixtures):
# Assert destination does not contain dira/f.py (excluded)
assert files == [normpath("dest/dira"), normpath("dest/dira/e.txt")]
+
+
+def test_simple_replace(expand_path_fixtures):
+ count_replaced = transforms.replace(["a.txt", "b.py"], "b..a", "GA")
+ assert 1 == count_replaced
+ assert "alpha text" == open("a.txt", "rt").read()
+ assert "GA python" == open("b.py", "rt").read()
+
+
+def test_multi_replace(expand_path_fixtures):
+ count_replaced = transforms.replace(["a.txt", "b.py"], r"(\w+)a", r"\1z")
+ assert 2 == count_replaced
+ assert "alphz text" == open("a.txt", "rt").read()
+ assert "betz python" == open("b.py", "rt").read()
+
+
+def test_replace_not_found(expand_path_fixtures):
+ count_replaced = transforms.replace(["a.txt", "b.py"], r"z", r"q")
+ assert 0 == count_replaced
+ assert "alpha text" == open("a.txt", "rt").read()
+ assert "beta python" == open("b.py", "rt").read()
|
Add ability to mark a replacement as required
For some libraries (like Grafeas), we are doing source replacement that must be done. It's possible that the source code changes (generator changes, formatting, etc) and the replacement fails to match. We already warn if the replacement doesn't happen which is great when it's for a bug fix. When it's a required replacement, we should give the option to make synth fail.
Perhaps, something like:
```python
s.replace(source_path, search, replace, required=True)
```
|
0.0
|
bb9c4d567016696a17664923270d2f0f4c79ef64
|
[
"tests/test_transforms.py::test_simple_replace",
"tests/test_transforms.py::test_multi_replace",
"tests/test_transforms.py::test_replace_not_found"
] |
[
"tests/test_transforms.py::test__expand_paths[a.txt-expected0]",
"tests/test_transforms.py::test__expand_paths[*-expected1]",
"tests/test_transforms.py::test__expand_paths[*.py-expected2]",
"tests/test_transforms.py::test__expand_paths[**/*.py-expected3]",
"tests/test_transforms.py::test__expand_paths[**/*-expected4]",
"tests/test_transforms.py::test__expand_paths_with_root[e.txt-expected0]",
"tests/test_transforms.py::test__expand_paths_with_root[*-expected1]",
"tests/test_transforms.py::test__filter_files",
"tests/test_transforms.py::test__file_copy_mode",
"tests/test_transforms.py::test__move_to_dest",
"tests/test_transforms.py::test__move_to_dest_subdir"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2019-12-17 20:39:15+00:00
|
apache-2.0
| 2,634 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.