instance_id
stringlengths
12
57
base_commit
stringlengths
40
40
created_at
stringdate
2015-01-06 14:05:07
2025-04-29 17:56:51
environment_setup_commit
stringlengths
40
40
hints_text
stringlengths
0
158k
patch
stringlengths
261
20.8k
problem_statement
stringlengths
11
52.5k
repo
stringlengths
7
53
test_patch
stringlengths
280
206k
meta
dict
version
stringclasses
463 values
install_config
dict
requirements
stringlengths
93
34k
environment
stringlengths
772
20k
FAIL_TO_PASS
sequencelengths
1
856
FAIL_TO_FAIL
sequencelengths
0
536
PASS_TO_PASS
sequencelengths
0
7.87k
PASS_TO_FAIL
sequencelengths
0
92
license_name
stringclasses
35 values
__index_level_0__
int64
11
21.4k
num_tokens_patch
int64
103
4.99k
before_filepaths
sequencelengths
0
14
jpadilla__pyjwt-71
0afba10cf16834e154a59280de089c30de3d9a61
2015-01-06 14:05:07
2d0e8272dbd1372289bff1b8e8eba446bed4befa
jpadilla: @mark-adams ready to move this forward. One thing I'd like to do before merging this in would be to write some comment blocks for the algorithms.
diff --git a/jwt/__init__.py b/jwt/__init__.py index 3a70913..b9a9986 100644 --- a/jwt/__init__.py +++ b/jwt/__init__.py @@ -5,16 +5,15 @@ Minimum implementation based on this spec: http://self-issued.info/docs/draft-jones-json-web-token-01.html """ -import base64 import binascii -import hashlib -import hmac -from datetime import datetime, timedelta + from calendar import timegm from collections import Mapping +from datetime import datetime, timedelta -from .compat import (json, string_types, text_type, constant_time_compare, - timedelta_total_seconds) +from jwt.utils import base64url_decode, base64url_encode + +from .compat import (json, string_types, text_type, timedelta_total_seconds) __version__ = '0.4.1' @@ -22,6 +21,7 @@ __all__ = [ # Functions 'encode', 'decode', + 'register_algorithm', # Exceptions 'InvalidTokenError', @@ -33,9 +33,25 @@ __all__ = [ # Deprecated aliases 'ExpiredSignature', 'InvalidAudience', - 'InvalidIssuer', + 'InvalidIssuer' ] +_algorithms = {} + + +def register_algorithm(alg_id, alg_obj): + """ Registers a new Algorithm for use when creating and verifying JWTs """ + if alg_id in _algorithms: + raise ValueError('Algorithm already has a handler.') + + if not isinstance(alg_obj, Algorithm): + raise TypeError('Object is not of type `Algorithm`') + + _algorithms[alg_id] = alg_obj + +from jwt.algorithms import Algorithm, _register_default_algorithms # NOQA +_register_default_algorithms() + class InvalidTokenError(Exception): pass @@ -56,187 +72,11 @@ class InvalidAudienceError(InvalidTokenError): class InvalidIssuerError(InvalidTokenError): pass - # Compatibility aliases (deprecated) ExpiredSignature = ExpiredSignatureError InvalidAudience = InvalidAudienceError InvalidIssuer = InvalidIssuerError -signing_methods = { - 'none': lambda msg, key: b'', - 'HS256': lambda msg, key: hmac.new(key, msg, hashlib.sha256).digest(), - 'HS384': lambda msg, key: hmac.new(key, msg, hashlib.sha384).digest(), - 'HS512': lambda msg, key: hmac.new(key, msg, hashlib.sha512).digest() -} - -verify_methods = { - 'HS256': lambda msg, key: hmac.new(key, msg, hashlib.sha256).digest(), - 'HS384': lambda msg, key: hmac.new(key, msg, hashlib.sha384).digest(), - 'HS512': lambda msg, key: hmac.new(key, msg, hashlib.sha512).digest() -} - - -def prepare_HS_key(key): - if not isinstance(key, string_types) and not isinstance(key, bytes): - raise TypeError('Expecting a string- or bytes-formatted key.') - - if isinstance(key, text_type): - key = key.encode('utf-8') - - return key - -prepare_key_methods = { - 'none': lambda key: None, - 'HS256': prepare_HS_key, - 'HS384': prepare_HS_key, - 'HS512': prepare_HS_key -} - -try: - from cryptography.hazmat.primitives import interfaces, hashes - from cryptography.hazmat.primitives.serialization import ( - load_pem_private_key, load_pem_public_key, load_ssh_public_key - ) - from cryptography.hazmat.primitives.asymmetric import ec, padding - from cryptography.hazmat.backends import default_backend - from cryptography.exceptions import InvalidSignature - - def sign_rsa(msg, key, hashalg): - signer = key.signer( - padding.PKCS1v15(), - hashalg - ) - - signer.update(msg) - return signer.finalize() - - def verify_rsa(msg, key, hashalg, sig): - verifier = key.verifier( - sig, - padding.PKCS1v15(), - hashalg - ) - - verifier.update(msg) - - try: - verifier.verify() - return True - except InvalidSignature: - return False - - signing_methods.update({ - 'RS256': lambda msg, key: sign_rsa(msg, key, hashes.SHA256()), - 'RS384': lambda msg, key: sign_rsa(msg, key, hashes.SHA384()), - 'RS512': lambda msg, key: sign_rsa(msg, key, hashes.SHA512()) - }) - - verify_methods.update({ - 'RS256': lambda msg, key, sig: verify_rsa(msg, key, hashes.SHA256(), sig), - 'RS384': lambda msg, key, sig: verify_rsa(msg, key, hashes.SHA384(), sig), - 'RS512': lambda msg, key, sig: verify_rsa(msg, key, hashes.SHA512(), sig) - }) - - def prepare_RS_key(key): - if isinstance(key, interfaces.RSAPrivateKey) or \ - isinstance(key, interfaces.RSAPublicKey): - return key - - if isinstance(key, string_types): - if isinstance(key, text_type): - key = key.encode('utf-8') - - try: - if key.startswith(b'ssh-rsa'): - key = load_ssh_public_key(key, backend=default_backend()) - else: - key = load_pem_private_key(key, password=None, backend=default_backend()) - except ValueError: - key = load_pem_public_key(key, backend=default_backend()) - else: - raise TypeError('Expecting a PEM-formatted key.') - - return key - - prepare_key_methods.update({ - 'RS256': prepare_RS_key, - 'RS384': prepare_RS_key, - 'RS512': prepare_RS_key - }) - - def sign_ecdsa(msg, key, hashalg): - signer = key.signer(ec.ECDSA(hashalg)) - - signer.update(msg) - return signer.finalize() - - def verify_ecdsa(msg, key, hashalg, sig): - verifier = key.verifier(sig, ec.ECDSA(hashalg)) - - verifier.update(msg) - - try: - verifier.verify() - return True - except InvalidSignature: - return False - - signing_methods.update({ - 'ES256': lambda msg, key: sign_ecdsa(msg, key, hashes.SHA256()), - 'ES384': lambda msg, key: sign_ecdsa(msg, key, hashes.SHA384()), - 'ES512': lambda msg, key: sign_ecdsa(msg, key, hashes.SHA512()), - }) - - verify_methods.update({ - 'ES256': lambda msg, key, sig: verify_ecdsa(msg, key, hashes.SHA256(), sig), - 'ES384': lambda msg, key, sig: verify_ecdsa(msg, key, hashes.SHA384(), sig), - 'ES512': lambda msg, key, sig: verify_ecdsa(msg, key, hashes.SHA512(), sig), - }) - - def prepare_ES_key(key): - if isinstance(key, interfaces.EllipticCurvePrivateKey) or \ - isinstance(key, interfaces.EllipticCurvePublicKey): - return key - - if isinstance(key, string_types): - if isinstance(key, text_type): - key = key.encode('utf-8') - - # Attempt to load key. We don't know if it's - # a Signing Key or a Verifying Key, so we try - # the Verifying Key first. - try: - key = load_pem_public_key(key, backend=default_backend()) - except ValueError: - key = load_pem_private_key(key, password=None, backend=default_backend()) - - else: - raise TypeError('Expecting a PEM-formatted key.') - - return key - - prepare_key_methods.update({ - 'ES256': prepare_ES_key, - 'ES384': prepare_ES_key, - 'ES512': prepare_ES_key - }) - -except ImportError: - pass - - -def base64url_decode(input): - rem = len(input) % 4 - - if rem > 0: - input += b'=' * (4 - rem) - - return base64.urlsafe_b64decode(input) - - -def base64url_encode(input): - return base64.urlsafe_b64encode(input).replace(b'=', b'') - def header(jwt): if isinstance(jwt, text_type): @@ -290,8 +130,10 @@ def encode(payload, key, algorithm='HS256', headers=None, json_encoder=None): # Segments signing_input = b'.'.join(segments) try: - key = prepare_key_methods[algorithm](key) - signature = signing_methods[algorithm](signing_input, key) + alg_obj = _algorithms[algorithm] + key = alg_obj.prepare_key(key) + signature = alg_obj.sign(signing_input, key) + except KeyError: raise NotImplementedError('Algorithm not supported') @@ -360,17 +202,12 @@ def verify_signature(payload, signing_input, header, signature, key='', raise TypeError('audience must be a string or None') try: - algorithm = header['alg'].upper() - key = prepare_key_methods[algorithm](key) + alg_obj = _algorithms[header['alg'].upper()] + key = alg_obj.prepare_key(key) - if algorithm.startswith('HS'): - expected = verify_methods[algorithm](signing_input, key) + if not alg_obj.verify(signing_input, key, signature): + raise DecodeError('Signature verification failed') - if not constant_time_compare(signature, expected): - raise DecodeError('Signature verification failed') - else: - if not verify_methods[algorithm](signing_input, key, signature): - raise DecodeError('Signature verification failed') except KeyError: raise DecodeError('Algorithm not supported') diff --git a/jwt/algorithms.py b/jwt/algorithms.py new file mode 100644 index 0000000..89ea75b --- /dev/null +++ b/jwt/algorithms.py @@ -0,0 +1,200 @@ +import hashlib +import hmac + +from jwt import register_algorithm +from jwt.compat import constant_time_compare, string_types, text_type + +try: + from cryptography.hazmat.primitives import interfaces, hashes + from cryptography.hazmat.primitives.serialization import ( + load_pem_private_key, load_pem_public_key, load_ssh_public_key + ) + from cryptography.hazmat.primitives.asymmetric import ec, padding + from cryptography.hazmat.backends import default_backend + from cryptography.exceptions import InvalidSignature + + has_crypto = True +except ImportError: + has_crypto = False + + +def _register_default_algorithms(): + """ Registers the algorithms that are implemented by the library """ + register_algorithm('none', NoneAlgorithm()) + register_algorithm('HS256', HMACAlgorithm(hashlib.sha256)) + register_algorithm('HS384', HMACAlgorithm(hashlib.sha384)) + register_algorithm('HS512', HMACAlgorithm(hashlib.sha512)) + + if has_crypto: + register_algorithm('RS256', RSAAlgorithm(hashes.SHA256())) + register_algorithm('RS384', RSAAlgorithm(hashes.SHA384())) + register_algorithm('RS512', RSAAlgorithm(hashes.SHA512())) + + register_algorithm('ES256', ECAlgorithm(hashes.SHA256())) + register_algorithm('ES384', ECAlgorithm(hashes.SHA384())) + register_algorithm('ES512', ECAlgorithm(hashes.SHA512())) + + +class Algorithm(object): + """ The interface for an algorithm used to sign and verify JWTs """ + def prepare_key(self, key): + """ + Performs necessary validation and conversions on the key and returns + the key value in the proper format for sign() and verify() + """ + raise NotImplementedError + + def sign(self, msg, key): + """ + Returns a digital signature for the specified message using the + specified key value + """ + raise NotImplementedError + + def verify(self, msg, key, sig): + """ + Verifies that the specified digital signature is valid for the specified + message and key values. + """ + raise NotImplementedError + + +class NoneAlgorithm(Algorithm): + """ + Placeholder for use when no signing or verification operations are required + """ + def prepare_key(self, key): + return None + + def sign(self, msg, key): + return b'' + + def verify(self, msg, key): + return True + + +class HMACAlgorithm(Algorithm): + """ + Performs signing and verification operations using HMAC and the specified + hash function + """ + def __init__(self, hash_alg): + self.hash_alg = hash_alg + + def prepare_key(self, key): + if not isinstance(key, string_types) and not isinstance(key, bytes): + raise TypeError('Expecting a string- or bytes-formatted key.') + + if isinstance(key, text_type): + key = key.encode('utf-8') + + return key + + def sign(self, msg, key): + return hmac.new(key, msg, self.hash_alg).digest() + + def verify(self, msg, key, sig): + return constant_time_compare(sig, self.sign(msg, key)) + +if has_crypto: + + class RSAAlgorithm(Algorithm): + """ + Performs signing and verification operations using RSASSA-PKCS-v1_5 and + the specified hash function + """ + + def __init__(self, hash_alg): + self.hash_alg = hash_alg + + def prepare_key(self, key): + if isinstance(key, interfaces.RSAPrivateKey) or \ + isinstance(key, interfaces.RSAPublicKey): + return key + + if isinstance(key, string_types): + if isinstance(key, text_type): + key = key.encode('utf-8') + + try: + if key.startswith(b'ssh-rsa'): + key = load_ssh_public_key(key, backend=default_backend()) + else: + key = load_pem_private_key(key, password=None, backend=default_backend()) + except ValueError: + key = load_pem_public_key(key, backend=default_backend()) + else: + raise TypeError('Expecting a PEM-formatted key.') + + return key + + def sign(self, msg, key): + signer = key.signer( + padding.PKCS1v15(), + self.hash_alg + ) + + signer.update(msg) + return signer.finalize() + + def verify(self, msg, key, sig): + verifier = key.verifier( + sig, + padding.PKCS1v15(), + self.hash_alg + ) + + verifier.update(msg) + + try: + verifier.verify() + return True + except InvalidSignature: + return False + + class ECAlgorithm(Algorithm): + """ + Performs signing and verification operations using ECDSA and the + specified hash function + """ + def __init__(self, hash_alg): + self.hash_alg = hash_alg + + def prepare_key(self, key): + if isinstance(key, interfaces.EllipticCurvePrivateKey) or \ + isinstance(key, interfaces.EllipticCurvePublicKey): + return key + + if isinstance(key, string_types): + if isinstance(key, text_type): + key = key.encode('utf-8') + + # Attempt to load key. We don't know if it's + # a Signing Key or a Verifying Key, so we try + # the Verifying Key first. + try: + key = load_pem_public_key(key, backend=default_backend()) + except ValueError: + key = load_pem_private_key(key, password=None, backend=default_backend()) + + else: + raise TypeError('Expecting a PEM-formatted key.') + + return key + + def sign(self, msg, key): + signer = key.signer(ec.ECDSA(self.hash_alg)) + + signer.update(msg) + return signer.finalize() + + def verify(self, msg, key, sig): + verifier = key.verifier(sig, ec.ECDSA(self.hash_alg)) + + verifier.update(msg) + + try: + verifier.verify() + return True + except InvalidSignature: + return False diff --git a/jwt/utils.py b/jwt/utils.py new file mode 100644 index 0000000..e6c1ef3 --- /dev/null +++ b/jwt/utils.py @@ -0,0 +1,14 @@ +import base64 + + +def base64url_decode(input): + rem = len(input) % 4 + + if rem > 0: + input += b'=' * (4 - rem) + + return base64.urlsafe_b64decode(input) + + +def base64url_encode(input): + return base64.urlsafe_b64encode(input).replace(b'=', b'') diff --git a/setup.py b/setup.py index 62d5df7..e703db6 100755 --- a/setup.py +++ b/setup.py @@ -1,8 +1,9 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- import os -import sys import re +import sys + from setuptools import setup
Move algorithm-specific logic to be class-based to allow for better extensibility In #42, we discussed changing to more of a registry model for registration of algorithms. This issue is suggesting that we move to that sort of a model.
jpadilla/pyjwt
diff --git a/tests/test_jwt.py b/tests/test_jwt.py index a57ab31..bd9ca06 100644 --- a/tests/test_jwt.py +++ b/tests/test_jwt.py @@ -45,6 +45,10 @@ class TestJWT(unittest.TestCase): self.payload = {'iss': 'jeff', 'exp': utc_timestamp() + 15, 'claim': 'insanity'} + def test_register_algorithm_rejects_non_algorithm_obj(self): + with self.assertRaises(TypeError): + jwt.register_algorithm('AAA123', {}) + def test_encode_decode(self): secret = 'secret' jwt_message = jwt.encode(self.payload, secret) @@ -549,35 +553,15 @@ class TestJWT(unittest.TestCase): load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_rsakey, *load_output) - def test_rsa_related_signing_methods(self): - if has_crypto: - self.assertTrue('RS256' in jwt.signing_methods) - self.assertTrue('RS384' in jwt.signing_methods) - self.assertTrue('RS512' in jwt.signing_methods) - else: - self.assertFalse('RS256' in jwt.signing_methods) - self.assertFalse('RS384' in jwt.signing_methods) - self.assertFalse('RS512' in jwt.signing_methods) - - def test_rsa_related_verify_methods(self): - if has_crypto: - self.assertTrue('RS256' in jwt.verify_methods) - self.assertTrue('RS384' in jwt.verify_methods) - self.assertTrue('RS512' in jwt.verify_methods) - else: - self.assertFalse('RS256' in jwt.verify_methods) - self.assertFalse('RS384' in jwt.verify_methods) - self.assertFalse('RS512' in jwt.verify_methods) - - def test_rsa_related_key_preparation_methods(self): + def test_rsa_related_algorithms(self): if has_crypto: - self.assertTrue('RS256' in jwt.prepare_key_methods) - self.assertTrue('RS384' in jwt.prepare_key_methods) - self.assertTrue('RS512' in jwt.prepare_key_methods) + self.assertTrue('RS256' in jwt._algorithms) + self.assertTrue('RS384' in jwt._algorithms) + self.assertTrue('RS512' in jwt._algorithms) else: - self.assertFalse('RS256' in jwt.prepare_key_methods) - self.assertFalse('RS384' in jwt.prepare_key_methods) - self.assertFalse('RS512' in jwt.prepare_key_methods) + self.assertFalse('RS256' in jwt._algorithms) + self.assertFalse('RS384' in jwt._algorithms) + self.assertFalse('RS512' in jwt._algorithms) @unittest.skipIf(not has_crypto, "Can't run without cryptography library") def test_encode_decode_with_ecdsa_sha256(self): @@ -669,35 +653,15 @@ class TestJWT(unittest.TestCase): load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_eckey, *load_output) - def test_ecdsa_related_signing_methods(self): - if has_crypto: - self.assertTrue('ES256' in jwt.signing_methods) - self.assertTrue('ES384' in jwt.signing_methods) - self.assertTrue('ES512' in jwt.signing_methods) - else: - self.assertFalse('ES256' in jwt.signing_methods) - self.assertFalse('ES384' in jwt.signing_methods) - self.assertFalse('ES512' in jwt.signing_methods) - - def test_ecdsa_related_verify_methods(self): - if has_crypto: - self.assertTrue('ES256' in jwt.verify_methods) - self.assertTrue('ES384' in jwt.verify_methods) - self.assertTrue('ES512' in jwt.verify_methods) - else: - self.assertFalse('ES256' in jwt.verify_methods) - self.assertFalse('ES384' in jwt.verify_methods) - self.assertFalse('ES512' in jwt.verify_methods) - - def test_ecdsa_related_key_preparation_methods(self): + def test_ecdsa_related_algorithms(self): if has_crypto: - self.assertTrue('ES256' in jwt.prepare_key_methods) - self.assertTrue('ES384' in jwt.prepare_key_methods) - self.assertTrue('ES512' in jwt.prepare_key_methods) + self.assertTrue('ES256' in jwt._algorithms) + self.assertTrue('ES384' in jwt._algorithms) + self.assertTrue('ES512' in jwt._algorithms) else: - self.assertFalse('ES256' in jwt.prepare_key_methods) - self.assertFalse('ES384' in jwt.prepare_key_methods) - self.assertFalse('ES512' in jwt.prepare_key_methods) + self.assertFalse('ES256' in jwt._algorithms) + self.assertFalse('ES384' in jwt._algorithms) + self.assertFalse('ES512' in jwt._algorithms) def test_check_audience(self): payload = {
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 2 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "cryptography", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cffi==1.17.1 cryptography==44.0.2 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pycparser==2.22 -e git+https://github.com/jpadilla/pyjwt.git@0afba10cf16834e154a59280de089c30de3d9a61#egg=PyJWT pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: pyjwt channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cffi==1.17.1 - cryptography==44.0.2 - pycparser==2.22 prefix: /opt/conda/envs/pyjwt
[ "tests/test_jwt.py::TestJWT::test_register_algorithm_rejects_non_algorithm_obj" ]
[ "tests/test_jwt.py::TestJWT::test_decodes_valid_es384_jwt", "tests/test_jwt.py::TestJWT::test_decodes_valid_rs384_jwt", "tests/test_jwt.py::TestJWT::test_ecdsa_related_algorithms", "tests/test_jwt.py::TestJWT::test_encode_decode_with_ecdsa_sha256", "tests/test_jwt.py::TestJWT::test_encode_decode_with_ecdsa_sha384", "tests/test_jwt.py::TestJWT::test_encode_decode_with_ecdsa_sha512", "tests/test_jwt.py::TestJWT::test_encode_decode_with_rsa_sha256", "tests/test_jwt.py::TestJWT::test_encode_decode_with_rsa_sha384", "tests/test_jwt.py::TestJWT::test_encode_decode_with_rsa_sha512", "tests/test_jwt.py::TestJWT::test_rsa_related_algorithms" ]
[ "tests/test_jwt.py::TestJWT::test_allow_skip_verification", "tests/test_jwt.py::TestJWT::test_bad_secret", "tests/test_jwt.py::TestJWT::test_bytes_secret", "tests/test_jwt.py::TestJWT::test_check_audience", "tests/test_jwt.py::TestJWT::test_check_audience_in_array", "tests/test_jwt.py::TestJWT::test_check_issuer", "tests/test_jwt.py::TestJWT::test_custom_headers", "tests/test_jwt.py::TestJWT::test_custom_json_encoder", "tests/test_jwt.py::TestJWT::test_decode_invalid_crypto_padding", "tests/test_jwt.py::TestJWT::test_decode_invalid_header_padding", "tests/test_jwt.py::TestJWT::test_decode_invalid_header_string", "tests/test_jwt.py::TestJWT::test_decode_invalid_payload_padding", "tests/test_jwt.py::TestJWT::test_decode_invalid_payload_string", "tests/test_jwt.py::TestJWT::test_decode_skip_expiration_verification", "tests/test_jwt.py::TestJWT::test_decode_skip_notbefore_verification", "tests/test_jwt.py::TestJWT::test_decode_unicode_value", "tests/test_jwt.py::TestJWT::test_decode_with_expiration", "tests/test_jwt.py::TestJWT::test_decode_with_expiration_with_leeway", "tests/test_jwt.py::TestJWT::test_decode_with_notbefore", "tests/test_jwt.py::TestJWT::test_decode_with_notbefore_with_leeway", "tests/test_jwt.py::TestJWT::test_decodes_valid_jwt", "tests/test_jwt.py::TestJWT::test_encode_bad_type", "tests/test_jwt.py::TestJWT::test_encode_datetime", "tests/test_jwt.py::TestJWT::test_encode_decode", "tests/test_jwt.py::TestJWT::test_encode_decode_with_algo_none", "tests/test_jwt.py::TestJWT::test_invalid_crypto_alg", "tests/test_jwt.py::TestJWT::test_load_no_verification", "tests/test_jwt.py::TestJWT::test_load_verify_valid_jwt", "tests/test_jwt.py::TestJWT::test_no_secret", "tests/test_jwt.py::TestJWT::test_nonascii_secret", "tests/test_jwt.py::TestJWT::test_raise_exception_invalid_audience", "tests/test_jwt.py::TestJWT::test_raise_exception_invalid_audience_in_array", "tests/test_jwt.py::TestJWT::test_raise_exception_invalid_issuer", "tests/test_jwt.py::TestJWT::test_raise_exception_token_without_audience", "tests/test_jwt.py::TestJWT::test_raise_exception_token_without_issuer", "tests/test_jwt.py::TestJWT::test_unicode_secret", "tests/test_jwt.py::TestJWT::test_verify_signature_no_secret" ]
[]
MIT License
11
4,219
[ "jwt/__init__.py", "setup.py" ]
msiemens__tinydb-46
65c302427777434c3c01bf36eb83ab86e6323a5e
2015-01-07 00:39:47
65c302427777434c3c01bf36eb83ab86e6323a5e
diff --git a/tinydb/database.py b/tinydb/database.py index 31a7483..cdaad19 100644 --- a/tinydb/database.py +++ b/tinydb/database.py @@ -199,7 +199,7 @@ class Table(object): old_ids = self._read().keys() if old_ids: - self._last_id = max(int(i, 10) for i in old_ids) + self._last_id = max(i for i in old_ids) else: self._last_id = 0 @@ -257,10 +257,11 @@ class Table(object): :rtype: dict """ - data = self._db._read(self.name) - - for eid in list(data): - data[eid] = Element(data[eid], eid) + raw_data = self._db._read(self.name) + data = {} + for key in list(raw_data): + eid = int(key) + data[eid] = Element(raw_data[key], eid) return data
Can not handle data by integer eid The id of the element will change to a unicode string after JSON serialization/deserialization. This causes no way to get the element by integer eid. ```python Python 2.7.6 (default, Sep 9 2014, 15:04:36) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from tinydb import TinyDB >>> db=TinyDB('/tmp/test.json') >>> db.insert({'foo':'bar'}) 1 >>> db.all() [{u'foo': u'bar'}] >>> element = db.all()[0] >>> element.eid u'1' >>> assert db.get(eid=1) is not None Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> assert db.get(eid='1') is not None >>> db.update({'foo':'blah'}, eids=[1]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/wolfg/.virtualenvs/opensource/lib/python2.7/site-packages/tinydb/database.py", line 335, in update cond, eids) File "/Users/wolfg/.virtualenvs/opensource/lib/python2.7/site-packages/tinydb/database.py", line 222, in process_elements func(data, eid) File "/Users/wolfg/.virtualenvs/opensource/lib/python2.7/site-packages/tinydb/database.py", line 334, in <lambda> self.process_elements(lambda data, eid: data[eid].update(fields), KeyError: 1 >>> db.update({'foo':'blah'}, eids=['1']) >>> db.all() [{u'foo': u'blah'}] >>> db.contains(eids=[1]) False >>> db.contains(eids=['1']) True ```
msiemens/tinydb
diff --git a/tests/test_tinydb.py b/tests/test_tinydb.py index 6f4e435..35b6fc1 100644 --- a/tests/test_tinydb.py +++ b/tests/test_tinydb.py @@ -337,3 +337,34 @@ def test_unicode_json(tmpdir): assert _db.contains(where('value') == unic_str1) assert _db.contains(where('value') == byte_str2) assert _db.contains(where('value') == unic_str2) + + +def test_eids_json(tmpdir): + """ + Regression test for issue #45 + """ + + path = str(tmpdir.join('db.json')) + + with TinyDB(path) as _db: + _db.purge() + assert _db.insert({'int': 1, 'char': 'a'}) == 1 + assert _db.insert({'int': 1, 'char': 'a'}) == 2 + + _db.purge() + assert _db.insert_multiple([{'int': 1, 'char': 'a'}, + {'int': 1, 'char': 'b'}, + {'int': 1, 'char': 'c'}]) == [1, 2, 3] + + assert _db.contains(eids=[1, 2]) + assert not _db.contains(eids=[88]) + + _db.update({'int': 2}, eids=[1, 2]) + assert _db.count(where('int') == 2) == 2 + + el = _db.all()[0] + assert _db.get(eid=el.eid) == el + assert _db.get(eid=float('NaN')) is None + + _db.remove(eids=[1, 2]) + assert len(_db) == 1
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
2.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.4", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 -e git+https://github.com/msiemens/tinydb.git@65c302427777434c3c01bf36eb83ab86e6323a5e#egg=tinydb toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: tinydb channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/tinydb
[ "tests/test_tinydb.py::test_eids_json" ]
[]
[ "tests/test_tinydb.py::test_purge[db0]", "tests/test_tinydb.py::test_purge[db1]", "tests/test_tinydb.py::test_all[db0]", "tests/test_tinydb.py::test_all[db1]", "tests/test_tinydb.py::test_insert[db0]", "tests/test_tinydb.py::test_insert[db1]", "tests/test_tinydb.py::test_insert_ids[db0]", "tests/test_tinydb.py::test_insert_ids[db1]", "tests/test_tinydb.py::test_insert_multiple[db0]", "tests/test_tinydb.py::test_insert_multiple[db1]", "tests/test_tinydb.py::test_insert_multiple_with_ids[db0]", "tests/test_tinydb.py::test_insert_multiple_with_ids[db1]", "tests/test_tinydb.py::test_remove[db0]", "tests/test_tinydb.py::test_remove[db1]", "tests/test_tinydb.py::test_remove_multiple[db0]", "tests/test_tinydb.py::test_remove_multiple[db1]", "tests/test_tinydb.py::test_remove_ids[db0]", "tests/test_tinydb.py::test_remove_ids[db1]", "tests/test_tinydb.py::test_update[db0]", "tests/test_tinydb.py::test_update[db1]", "tests/test_tinydb.py::test_update_transform[db0]", "tests/test_tinydb.py::test_update_transform[db1]", "tests/test_tinydb.py::test_update_ids[db0]", "tests/test_tinydb.py::test_update_ids[db1]", "tests/test_tinydb.py::test_search[db0]", "tests/test_tinydb.py::test_search[db1]", "tests/test_tinydb.py::test_contians[db0]", "tests/test_tinydb.py::test_contians[db1]", "tests/test_tinydb.py::test_get[db0]", "tests/test_tinydb.py::test_get[db1]", "tests/test_tinydb.py::test_get_ids[db0]", "tests/test_tinydb.py::test_get_ids[db1]", "tests/test_tinydb.py::test_count[db0]", "tests/test_tinydb.py::test_count[db1]", "tests/test_tinydb.py::test_contains[db0]", "tests/test_tinydb.py::test_contains[db1]", "tests/test_tinydb.py::test_contains_ids[db0]", "tests/test_tinydb.py::test_contains_ids[db1]", "tests/test_tinydb.py::test_get_idempotent[db0]", "tests/test_tinydb.py::test_get_idempotent[db1]", "tests/test_tinydb.py::test_multiple_dbs", "tests/test_tinydb.py::test_unique_ids", "tests/test_tinydb.py::test_lastid_after_open" ]
[]
MIT License
12
250
[ "tinydb/database.py" ]
pozytywnie__webapp-health-monitor-12
64bb87f0c5c8ec9863b7daf1fdd3f7ff6532738f
2015-01-12 12:24:43
64bb87f0c5c8ec9863b7daf1fdd3f7ff6532738f
diff --git a/webapp_health_monitor/verificators/base.py b/webapp_health_monitor/verificators/base.py index 0f4b6af..668536a 100644 --- a/webapp_health_monitor/verificators/base.py +++ b/webapp_health_monitor/verificators/base.py @@ -4,8 +4,8 @@ from webapp_health_monitor import errors class Verificator(object): verificator_name = None - def __init__(self, logger): - self.logger = logger + def __init__(self, **kwargs): + pass def run(self): raise NotImplementedError() @@ -40,7 +40,6 @@ class RangeVerificator(Verificator): def _check_value(self): value = self._get_value() - self.logger.check_range(self.lower_bound, value, self.upper_bound) self._check_lower_bound(value) self._check_upper_bound(value)
Use standard python logging method Simplify logging by using only build-in logging. Remove forwarding of custom logger class.
pozytywnie/webapp-health-monitor
diff --git a/tests/test_verificators.py b/tests/test_verificators.py index 84190b2..69c0a96 100644 --- a/tests/test_verificators.py +++ b/tests/test_verificators.py @@ -14,55 +14,39 @@ from webapp_health_monitor.verificators.system import ( class RangeVerificatorTest(TestCase): def test_lack_of_value_extractor_raises_bad_configuration(self): - logger = mock.Mock() - verificator = RangeVerificator(logger) + verificator = RangeVerificator() verificator.lower_bound = 0 verificator.upper_bound = 0 self.assertRaises(errors.BadConfigurationError, verificator.run) def test_lack_of_bounds_raises_bad_configuration(self): - logger = mock.Mock() - verificator = RangeVerificator(logger) + verificator = RangeVerificator() verificator.value_extractor = mock.Mock() self.assertRaises(errors.BadConfigurationError, verificator.run) def test_bad_bounds_raises_bad_configuration(self): - logger = mock.Mock() - verificator = RangeVerificator(logger) + verificator = RangeVerificator() verificator.value_extractor = mock.Mock() verificator.lower_bound = 1 verificator.upper_bound = 0 self.assertRaises(errors.BadConfigurationError, verificator.run) def test_value_below_lower_bound_raises_verification_error(self): - logger = mock.Mock() - verificator = RangeVerificator(logger) + verificator = RangeVerificator() verificator._get_value = mock.Mock(return_value=99) verificator.value_extractor = mock.Mock() verificator.lower_bound = 100 self.assertRaises(errors.VerificationError, verificator.run) def test_value_over_upper_bound_raises_verification_error(self): - logger = mock.Mock() - verificator = RangeVerificator(logger) + verificator = RangeVerificator() verificator._get_value = mock.Mock(return_value=100) verificator.value_extractor = mock.Mock() verificator.upper_bound = 99 self.assertRaises(errors.VerificationError, verificator.run) - def test_check_logging(self): - logger = mock.Mock() - verificator = RangeVerificator(logger) - verificator._get_value = mock.Mock(return_value=1) - verificator.value_extractor = mock.Mock() - verificator.lower_bound = 0 - verificator.upper_bound = 2 - verificator.run() - logger.check_range.assert_called_with(0, 1, 2) - def test_get_value(self): - logger = mock.Mock() - verificator = RangeVerificator(logger) + verificator = RangeVerificator() verificator.value_extractor = mock.Mock( extract=mock.Mock(return_value=1)) self.assertEqual(1, verificator._get_value()) @@ -74,8 +58,7 @@ class FreeDiskSpaceVerificatorTest(TestCase): def test_using_value_extractor(self, FreeDiskSpaceExtractor): class AppVerificator(FreeDiskSpaceVerificator): mount_point = '/home' - logger = mock.Mock() - verificator = AppVerificator(logger) + verificator = AppVerificator() FreeDiskSpaceExtractor.return_value.extract.return_value = 100 self.assertEqual(100, verificator._get_value()) FreeDiskSpaceExtractor.assert_called_with('/home') @@ -87,8 +70,7 @@ class PercentUsedDiskSpaceVerificatorTest(TestCase): def test_using_value_extractor(self, PercentUsedDiskSpaceExtractor): class AppVerificator(PercentUsedDiskSpaceVerificator): mount_point = '/home' - logger = mock.Mock() - verificator = AppVerificator(logger) + verificator = AppVerificator() PercentUsedDiskSpaceExtractor.return_value.extract.return_value = 100 self.assertEqual(100, verificator._get_value()) PercentUsedDiskSpaceExtractor.assert_called_with('/home')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 coveralls==4.0.1 docopt==0.6.2 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 mock==1.0.1 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 requests==2.32.3 tomli==2.2.1 urllib3==2.3.0 -e git+https://github.com/pozytywnie/webapp-health-monitor.git@64bb87f0c5c8ec9863b7daf1fdd3f7ff6532738f#egg=Webapp_Health_Monitor
name: webapp-health-monitor channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - coveralls==4.0.1 - docopt==0.6.2 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - mock==1.0.1 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - requests==2.32.3 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/webapp-health-monitor
[ "tests/test_verificators.py::RangeVerificatorTest::test_bad_bounds_raises_bad_configuration", "tests/test_verificators.py::RangeVerificatorTest::test_get_value", "tests/test_verificators.py::RangeVerificatorTest::test_lack_of_bounds_raises_bad_configuration", "tests/test_verificators.py::RangeVerificatorTest::test_lack_of_value_extractor_raises_bad_configuration", "tests/test_verificators.py::RangeVerificatorTest::test_value_below_lower_bound_raises_verification_error", "tests/test_verificators.py::RangeVerificatorTest::test_value_over_upper_bound_raises_verification_error", "tests/test_verificators.py::FreeDiskSpaceVerificatorTest::test_using_value_extractor", "tests/test_verificators.py::PercentUsedDiskSpaceVerificatorTest::test_using_value_extractor" ]
[]
[]
[]
MIT License
20
220
[ "webapp_health_monitor/verificators/base.py" ]
ipython__ipython-7469
296f56bf70643d1d19ae0c1ab2a9d86b326d5559
2015-01-15 00:40:54
148242288b1aeecf899f0d1fb086d13f37024c53
diff --git a/IPython/utils/io.py b/IPython/utils/io.py index df1e39e60..3d236eb4d 100644 --- a/IPython/utils/io.py +++ b/IPython/utils/io.py @@ -267,17 +267,18 @@ def atomic_writing(path, text=True, encoding='utf-8', **kwargs): path = os.path.join(os.path.dirname(path), os.readlink(path)) dirname, basename = os.path.split(path) - handle, tmp_path = tempfile.mkstemp(prefix=basename, dir=dirname) + tmp_dir = tempfile.mkdtemp(prefix=basename, dir=dirname) + tmp_path = os.path.join(tmp_dir, basename) if text: - fileobj = io.open(handle, 'w', encoding=encoding, **kwargs) + fileobj = io.open(tmp_path, 'w', encoding=encoding, **kwargs) else: - fileobj = io.open(handle, 'wb', **kwargs) + fileobj = io.open(tmp_path, 'wb', **kwargs) try: yield fileobj except: fileobj.close() - os.remove(tmp_path) + shutil.rmtree(tmp_dir) raise # Flush to disk @@ -299,6 +300,7 @@ def atomic_writing(path, text=True, encoding='utf-8', **kwargs): os.remove(path) os.rename(tmp_path, path) + shutil.rmtree(tmp_dir) def raw_print(*args, **kw):
atomic write umask Reported on gitter.im/ipython/ipython by @bigzachattack Sadly no one was on the chat at that time, too busy with a big bearded men dressed in red trying to smuggle things in our houses through the cheminee. ``` I noticed today working in master, that any new notebook I create or copy has permissions 0o600 and ignores my umask. In IPython.utils.io.atomic_writing() uses mkstemp() to create a temporary file for the atomic write. According to the python docs, mkstemp creates files as 0o600. After the write succeeds to the tmp file, _copy_metadata is called to copy the metadata from the original file to destination file. It will throw an exception if there is no source file. Thus when the notebook is copied into the notebook dir, it has permissions 0o600. Is this desired behavior, temporary, or a bug? I work in an environment where are default permissions are 0o660 to allow for users to easily share information, so defaulting new notebooks to 0o600 seriously inhibits this ability. ```
ipython/ipython
diff --git a/IPython/utils/tests/test_io.py b/IPython/utils/tests/test_io.py index 023c9641b..aa00a882b 100644 --- a/IPython/utils/tests/test_io.py +++ b/IPython/utils/tests/test_io.py @@ -1,16 +1,9 @@ # encoding: utf-8 """Tests for io.py""" -#----------------------------------------------------------------------------- -# Copyright (C) 2008-2011 The IPython Development Team -# -# Distributed under the terms of the BSD License. The full license is in -# the file COPYING, distributed as part of this software. -#----------------------------------------------------------------------------- - -#----------------------------------------------------------------------------- -# Imports -#----------------------------------------------------------------------------- +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + from __future__ import print_function from __future__ import absolute_import @@ -24,7 +17,7 @@ import nose.tools as nt -from IPython.testing.decorators import skipif +from IPython.testing.decorators import skipif, skip_win32 from IPython.utils.io import (Tee, capture_output, unicode_std_stream, atomic_writing, ) @@ -36,10 +29,6 @@ else: from StringIO import StringIO -#----------------------------------------------------------------------------- -# Tests -#----------------------------------------------------------------------------- - def test_tee_simple(): "Very simple check with stdout only" @@ -177,6 +166,33 @@ class CustomExc(Exception): pass with stdlib_io.open(f1, 'r') as f: nt.assert_equal(f.read(), u'written from symlink') +def _save_umask(): + global umask + umask = os.umask(0) + os.umask(umask) + +def _restore_umask(): + os.umask(umask) + +@skip_win32 [email protected]_setup(_save_umask, _restore_umask) +def test_atomic_writing_umask(): + with TemporaryDirectory() as td: + os.umask(0o022) + f1 = os.path.join(td, '1') + with atomic_writing(f1) as f: + f.write(u'1') + mode = stat.S_IMODE(os.stat(f1).st_mode) + nt.assert_equal(mode, 0o644, '{:o} != 644'.format(mode)) + + os.umask(0o057) + f2 = os.path.join(td, '2') + with atomic_writing(f2) as f: + f.write(u'2') + mode = stat.S_IMODE(os.stat(f2).st_mode) + nt.assert_equal(mode, 0o620, '{:o} != 620'.format(mode)) + + def test_atomic_writing_newlines(): with TemporaryDirectory() as td: path = os.path.join(td, 'testfile')
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
2.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "mock", "sphinx", "pandoc", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "docs/source/install/install.rst" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs @ file:///croot/attrs_1668696182826/work Babel==2.14.0 certifi @ file:///croot/certifi_1671487769961/work/certifi charset-normalizer==3.4.1 docutils==0.19 flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core idna==3.10 imagesize==1.4.1 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work importlib-resources==5.12.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/ipython/ipython.git@296f56bf70643d1d19ae0c1ab2a9d86b326d5559#egg=ipython Jinja2==3.1.6 jsonschema==4.17.3 MarkupSafe==2.1.5 mistune==3.0.2 mock==5.2.0 nose==1.3.7 numpydoc==1.5.0 packaging @ file:///croot/packaging_1671697413597/work pandoc==2.4 pkgutil_resolve_name==1.3.10 pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work plumbum==1.8.3 ply==3.11 py @ file:///opt/conda/conda-bld/py_1644396412707/work Pygments==2.17.2 pyrsistent==0.19.3 pytest==7.1.2 pytz==2025.2 pyzmq==26.2.1 requests==2.31.0 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tornado==6.2 typing_extensions @ file:///croot/typing_extensions_1669924550328/work urllib3==2.0.7 zipp @ file:///croot/zipp_1672387121353/work
name: ipython channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=22.1.0=py37h06a4308_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - flit-core=3.6.0=pyhd3eb1b0_0 - importlib-metadata=4.11.3=py37h06a4308_0 - importlib_metadata=4.11.3=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=22.0=py37h06a4308_0 - pip=22.3.1=py37h06a4308_0 - pluggy=1.0.0=py37h06a4308_1 - py=1.11.0=pyhd3eb1b0_0 - pytest=7.1.2=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py37h06a4308_0 - typing_extensions=4.4.0=py37h06a4308_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zipp=3.11.0=py37h06a4308_0 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - babel==2.14.0 - charset-normalizer==3.4.1 - docutils==0.19 - idna==3.10 - imagesize==1.4.1 - importlib-resources==5.12.0 - jinja2==3.1.6 - jsonschema==4.17.3 - markupsafe==2.1.5 - mistune==3.0.2 - mock==5.2.0 - nose==1.3.7 - numpydoc==1.5.0 - pandoc==2.4 - pkgutil-resolve-name==1.3.10 - plumbum==1.8.3 - ply==3.11 - pygments==2.17.2 - pyrsistent==0.19.3 - pytz==2025.2 - pyzmq==26.2.1 - requests==2.31.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tornado==6.2 - urllib3==2.0.7 prefix: /opt/conda/envs/ipython
[ "IPython/utils/tests/test_io.py::test_atomic_writing_umask" ]
[]
[ "IPython/utils/tests/test_io.py::test_tee_simple", "IPython/utils/tests/test_io.py::TeeTestCase::test", "IPython/utils/tests/test_io.py::test_io_init", "IPython/utils/tests/test_io.py::test_capture_output", "IPython/utils/tests/test_io.py::test_UnicodeStdStream", "IPython/utils/tests/test_io.py::test_UnicodeStdStream_nowrap", "IPython/utils/tests/test_io.py::test_atomic_writing", "IPython/utils/tests/test_io.py::test_atomic_writing_newlines" ]
[]
BSD 3-Clause "New" or "Revised" License
22
348
[ "IPython/utils/io.py" ]
martinblech__xmltodict-81
a3a95592b875cc3d2472a431a197c9c1a5d8a788
2015-01-18 14:47:10
b80fc18b7dbf278bf460f514fb4ead693c60d6f7
diff --git a/xmltodict.py b/xmltodict.py index 4fdbb16..b0ba601 100755 --- a/xmltodict.py +++ b/xmltodict.py @@ -318,7 +318,8 @@ def unparse(input_dict, output=None, encoding='utf-8', full_document=True, can be customized with the `newl` and `indent` parameters. """ - ((key, value),) = input_dict.items() + if full_document and len(input_dict) != 1: + raise ValueError('Document must have exactly one root.') must_return = False if output is None: output = StringIO() @@ -326,7 +327,8 @@ def unparse(input_dict, output=None, encoding='utf-8', full_document=True, content_handler = XMLGenerator(output, encoding) if full_document: content_handler.startDocument() - _emit(key, value, content_handler, **kwargs) + for key, value in input_dict.items(): + _emit(key, value, content_handler, **kwargs) if full_document: content_handler.endDocument() if must_return:
Parameter to Disable Multiple Root Check I'm trying to convert a dict to an xml snippet, but this xml snippet is just supposed to be part of a later full document, so it may or may not have one root element. Unfortunately a ValueError is thrown if there is more than one possible root element - it would be great if there was a keyword parameter to disable that check. (Or perhaps when `full_document=False`) So for example: ```python xmltodict.unparse({'node': [1,2,3]}, full_document=False) # would produce something like this without throwing an error: """<node>1</node> <node>2</node> <node>3</node> """ ```
martinblech/xmltodict
diff --git a/tests/test_dicttoxml.py b/tests/test_dicttoxml.py index e449316..4b1d4b8 100644 --- a/tests/test_dicttoxml.py +++ b/tests/test_dicttoxml.py @@ -49,10 +49,21 @@ class DictToXMLTestCase(unittest.TestCase): self.assertEqual(obj, parse(unparse(obj))) self.assertEqual(unparse(obj), unparse(parse(unparse(obj)))) + def test_no_root(self): + self.assertRaises(ValueError, unparse, {}) + def test_multiple_roots(self): self.assertRaises(ValueError, unparse, {'a': '1', 'b': '2'}) self.assertRaises(ValueError, unparse, {'a': ['1', '2', '3']}) + def test_no_root_nofulldoc(self): + self.assertEqual(unparse({}, full_document=False), '') + + def test_multiple_roots_nofulldoc(self): + obj = OrderedDict((('a', 1), ('b', 2))) + xml = unparse(obj, full_document=False) + self.assertEqual(xml, '<a>1</a><b>2</b>') + def test_nested(self): obj = {'a': {'b': '1', 'c': '2'}} self.assertEqual(obj, parse(unparse(obj)))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "coverage", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work nose==1.3.7 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work -e git+https://github.com/martinblech/xmltodict.git@a3a95592b875cc3d2472a431a197c9c1a5d8a788#egg=xmltodict
name: xmltodict channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - nose==1.3.7 prefix: /opt/conda/envs/xmltodict
[ "tests/test_dicttoxml.py::DictToXMLTestCase::test_multiple_roots_nofulldoc", "tests/test_dicttoxml.py::DictToXMLTestCase::test_no_root_nofulldoc" ]
[]
[ "tests/test_dicttoxml.py::DictToXMLTestCase::test_attr_order_roundtrip", "tests/test_dicttoxml.py::DictToXMLTestCase::test_attrib", "tests/test_dicttoxml.py::DictToXMLTestCase::test_attrib_and_cdata", "tests/test_dicttoxml.py::DictToXMLTestCase::test_cdata", "tests/test_dicttoxml.py::DictToXMLTestCase::test_encoding", "tests/test_dicttoxml.py::DictToXMLTestCase::test_fulldoc", "tests/test_dicttoxml.py::DictToXMLTestCase::test_list", "tests/test_dicttoxml.py::DictToXMLTestCase::test_multiple_roots", "tests/test_dicttoxml.py::DictToXMLTestCase::test_nested", "tests/test_dicttoxml.py::DictToXMLTestCase::test_no_root", "tests/test_dicttoxml.py::DictToXMLTestCase::test_preprocessor", "tests/test_dicttoxml.py::DictToXMLTestCase::test_preprocessor_skipkey", "tests/test_dicttoxml.py::DictToXMLTestCase::test_pretty_print", "tests/test_dicttoxml.py::DictToXMLTestCase::test_root", "tests/test_dicttoxml.py::DictToXMLTestCase::test_semistructured", "tests/test_dicttoxml.py::DictToXMLTestCase::test_simple_cdata" ]
[]
MIT License
30
267
[ "xmltodict.py" ]
jacebrowning__dropthebeat-25
3f0891ee65703490136f44851c06b8356992a05c
2015-01-19 02:00:09
3f0891ee65703490136f44851c06b8356992a05c
diff --git a/dtb/gui.py b/dtb/gui.py index f96defc..7651d52 100755 --- a/dtb/gui.py +++ b/dtb/gui.py @@ -193,13 +193,19 @@ class Application(ttk.Frame): # pragma: no cover - manual test, pylint: disable def do_ignore(self): """Ignore selected songs.""" for index in (int(s) for s in self.listbox_incoming.curselection()): - self.incoming[index].ignore() + song = self.incoming[index] + song.ignore() self.update() def do_download(self): - """Download all songs.""" - for index in (int(s) for s in self.listbox_incoming.curselection()): - self.incoming[index].download() + """Download selected songs.""" + indicies = (int(s) for s in self.listbox_incoming.curselection()) + try: + for index in indicies: + song = self.incoming[index] + song.download(catch=False) + except IOError as exc: + self.show_error_from_exception(exc, "Download Error") self.update() def update(self): @@ -219,6 +225,12 @@ class Application(ttk.Frame): # pragma: no cover - manual test, pylint: disable for song in self.incoming: self.listbox_incoming.insert(tk.END, song.in_string) + @staticmethod + def show_error_from_exception(exception, title="Error"): + """Convert an exception to an error dialog.""" + message = str(exception).capitalize().replace(": ", ":\n\n") + messagebox.showerror(title, message) + def main(args=None): """Process command-line arguments and run the program.""" diff --git a/dtb/song.py b/dtb/song.py index 7bd39a9..5df079d 100755 --- a/dtb/song.py +++ b/dtb/song.py @@ -67,7 +67,7 @@ class Song(object): filename = os.path.basename(self.source) return "{} (to {})".format(filename, self.friendname) - def download(self): + def download(self, catch=True): """Move the song to the user's download directory. @return: path to downloaded file or None on broken links @@ -78,6 +78,9 @@ class Song(object): dst = None # Move the file or copy from the link try: + if not os.path.isdir(self.downloads): + msg = "invalid download location: {}".format(self.downloads) + raise IOError(msg) if src == self.path: logging.info("moving {}...".format(src)) # Copy then delete in case the operation is cancelled @@ -95,8 +98,9 @@ class Song(object): logging.warning("broken link: {}".format(self.path)) os.remove(self.path) except IOError as error: - # TODO: these errors need to be left uncaught for the GUI - logging.warning(error) + logging.error(error) + if not catch: + raise return dst def ignore(self):
Strange Behavior when download path does not exist If my download path does not exist on my machine I end up with a file named whatever is the directory was supposed to be. e.g. Download path: `~/jkloo/downloads/fake` The directory `fake` does not exist. The result is a file (`testfile.jpg`) downloads as `fake` in the directory `~/jkloo/downloads`. Adding the `.jpg` extension and opening the image reveals the expected file. This is likely only an issue when a user manually changes their DL path in `info.yml` or the first time the GUI is run on a machine / for a user. possible fixes: 1. only save the DL path if it exists - create the DL directory if it doesn't exist - error pop-up if path does not exist
jacebrowning/dropthebeat
diff --git a/dtb/test/test_song.py b/dtb/test/test_song.py index c80778a..250dfa8 100644 --- a/dtb/test/test_song.py +++ b/dtb/test/test_song.py @@ -100,10 +100,22 @@ class TestSong(unittest.TestCase): # pylint: disable=R0904 mock_remove.assert_called_once_with(self.broken.path) @patch('os.remove', Mock(side_effect=IOError)) - def test_download_error(self): + def test_download_error_caught(self): """Verify errors are caught while downloading.""" self.song.download() + @patch('os.remove', Mock(side_effect=IOError)) + def test_download_error_uncaught(self): + """Verify errors are not caught while downloading if requested.""" + self.assertRaises(IOError, self.song.download, catch=False) + + @patch('os.remove') + @patch('os.path.isdir', Mock(return_value=False)) + def test_download_invalid_dest(self, mock_remove): + """Verify downloads are only attempted with a valid destination.""" + self.song.download() + self.assertFalse(mock_remove.called) + @patch('os.remove') def test_ignore(self, mock_remove): """Verify a song can be ignored."""
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_media", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 2 }
0.0
{ "env_vars": null, "env_yml_path": null, "install": "python setup.py install", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
DropTheBeat==0.1.dev0 exceptiongroup==1.2.2 iniconfig==2.1.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 PyYAML==3.13 tomli==2.2.1
name: dropthebeat channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - dropthebeat==0.1.dev0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pyyaml==3.13 - tomli==2.2.1 prefix: /opt/conda/envs/dropthebeat
[ "dtb/test/test_song.py::TestSong::test_download_error_uncaught" ]
[]
[ "dtb/test/test_song.py::TestSong::test_download_broken", "dtb/test/test_song.py::TestSong::test_download_error_caught", "dtb/test/test_song.py::TestSong::test_download_invalid_dest", "dtb/test/test_song.py::TestSong::test_download_link", "dtb/test/test_song.py::TestSong::test_download_song", "dtb/test/test_song.py::TestSong::test_ignore", "dtb/test/test_song.py::TestSong::test_in_string", "dtb/test/test_song.py::TestSong::test_link", "dtb/test/test_song.py::TestSong::test_link_missing_directory", "dtb/test/test_song.py::TestSong::test_out_string", "dtb/test/test_song.py::TestSong::test_source_file", "dtb/test/test_song.py::TestSong::test_source_file_bad", "dtb/test/test_song.py::TestSong::test_source_link", "dtb/test/test_song.py::TestSong::test_source_song", "dtb/test/test_song.py::TestSong::test_str" ]
[]
The MIT License (MIT)
31
726
[ "dtb/gui.py", "dtb/song.py" ]
pre-commit__pre-commit-hooks-39
9f107a03276857c668fe3e090752d3d22a4195e5
2015-02-27 02:24:38
f82fb149af2c1b552b50e3e38e38ed3a44d4cda1
diff --git a/pre_commit_hooks/autopep8_wrapper.py b/pre_commit_hooks/autopep8_wrapper.py index a79a120..f6f55fb 100644 --- a/pre_commit_hooks/autopep8_wrapper.py +++ b/pre_commit_hooks/autopep8_wrapper.py @@ -10,7 +10,7 @@ import autopep8 def main(argv=None): argv = argv if argv is not None else sys.argv[1:] - args = autopep8.parse_args(argv) + args = autopep8.parse_args(argv, apply_config=True) retv = 0 for filename in args.files: diff --git a/setup.py b/setup.py index 4fb9139..b86acd1 100644 --- a/setup.py +++ b/setup.py @@ -27,7 +27,7 @@ setup( packages=find_packages('.', exclude=('tests*', 'testing*')), install_requires=[ 'argparse', - 'autopep8', + 'autopep8>=1.1', 'flake8', 'plumbum', 'pyflakes',
Autopep8 doesn't respect pep8 section in setup.cfg Since https://github.com/hhatto/autopep8/pull/167 autopep8 has started reading the ```pep8``` section from ```tox.ini``` or ```setup.cfg``` of a project. However, the autopep8 hook ignores this as it calls ```autopep8.parse_args()``` and ```autopep8.fix_code()``` without a second value (which defaults to ```False```). Any way we could get this to work?
pre-commit/pre-commit-hooks
diff --git a/tests/autopep8_wrapper_test.py b/tests/autopep8_wrapper_test.py index f32e8a0..9a395c9 100644 --- a/tests/autopep8_wrapper_test.py +++ b/tests/autopep8_wrapper_test.py @@ -2,7 +2,7 @@ from __future__ import absolute_import from __future__ import unicode_literals import io -import os.path +import os import pytest @@ -17,9 +17,30 @@ from pre_commit_hooks.autopep8_wrapper import main ), ) def test_main_failing(tmpdir, input_src, expected_ret, output_src): - filename = os.path.join(tmpdir.strpath, 'test.py') + filename = tmpdir.join('test.py').strpath with io.open(filename, 'w') as file_obj: file_obj.write(input_src) ret = main([filename, '-i', '-v']) assert ret == expected_ret assert io.open(filename).read() == output_src + + [email protected]_fixture +def in_tmpdir(tmpdir): + pwd = os.getcwd() + os.chdir(tmpdir.strpath) + try: + yield + finally: + os.chdir(pwd) + + [email protected]('in_tmpdir') +def test_respects_config_file(): + with io.open('setup.cfg', 'w') as setup_cfg: + setup_cfg.write('[pep8]\nignore=E221') + + with io.open('test.py', 'w') as test_py: + test_py.write('print(1 + 2)\n') + + assert main(['test.py', '-i', '-v']) == 0
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 2 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "flake8", "pylint" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==3.3.9 autopep8==2.3.2 dill==0.3.9 exceptiongroup==1.2.2 flake8==7.2.0 iniconfig==2.1.0 isort==6.0.1 mccabe==0.7.0 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 plumbum==1.9.0 -e git+https://github.com/pre-commit/pre-commit-hooks.git@9f107a03276857c668fe3e090752d3d22a4195e5#egg=pre_commit_hooks pycodestyle==2.13.0 pyflakes==3.3.1 pylint==3.3.6 pytest==8.3.5 PyYAML==6.0.2 simplejson==3.20.1 swebench_matterhorn @ file:///swebench_matterhorn tomli==2.2.1 tomlkit==0.13.2 typing_extensions==4.13.0
name: pre-commit-hooks channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - astroid==3.3.9 - autopep8==2.3.2 - dill==0.3.9 - exceptiongroup==1.2.2 - flake8==7.2.0 - iniconfig==2.1.0 - isort==6.0.1 - mccabe==0.7.0 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - plumbum==1.9.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pylint==3.3.6 - pytest==8.3.5 - pyyaml==6.0.2 - simplejson==3.20.1 - swebench-matterhorn==0.0.0 - tomli==2.2.1 - tomlkit==0.13.2 - typing-extensions==4.13.0 prefix: /opt/conda/envs/pre-commit-hooks
[ "tests/autopep8_wrapper_test.py::test_respects_config_file" ]
[]
[ "tests/autopep8_wrapper_test.py::test_main_failing[print(1" ]
[]
MIT License
46
267
[ "pre_commit_hooks/autopep8_wrapper.py", "setup.py" ]
tornadoweb__tornado-1373
cf2a54794ff5067d6d815013d6570ee10f74d5e5
2015-03-09 04:21:31
cf2a54794ff5067d6d815013d6570ee10f74d5e5
diff --git a/tornado/httpserver.py b/tornado/httpserver.py index 226f966a..13a6e92f 100644 --- a/tornado/httpserver.py +++ b/tornado/httpserver.py @@ -37,11 +37,9 @@ from tornado import httputil from tornado import iostream from tornado import netutil from tornado.tcpserver import TCPServer -from tornado.util import Configurable -class HTTPServer(TCPServer, Configurable, - httputil.HTTPServerConnectionDelegate): +class HTTPServer(TCPServer, httputil.HTTPServerConnectionDelegate): r"""A non-blocking, single-threaded HTTP server. A server is defined by a subclass of `.HTTPServerConnectionDelegate`, @@ -122,20 +120,12 @@ class HTTPServer(TCPServer, Configurable, two arguments ``(server_conn, request_conn)`` (in accordance with the documentation) instead of one ``(request_conn)``. """ - def __init__(self, *args, **kwargs): - # Ignore args to __init__; real initialization belongs in - # initialize since we're Configurable. (there's something - # weird in initialization order between this class, - # Configurable, and TCPServer so we can't leave __init__ out - # completely) - pass - - def initialize(self, request_callback, no_keep_alive=False, io_loop=None, - xheaders=False, ssl_options=None, protocol=None, - decompress_request=False, - chunk_size=None, max_header_size=None, - idle_connection_timeout=None, body_timeout=None, - max_body_size=None, max_buffer_size=None): + def __init__(self, request_callback, no_keep_alive=False, io_loop=None, + xheaders=False, ssl_options=None, protocol=None, + decompress_request=False, + chunk_size=None, max_header_size=None, + idle_connection_timeout=None, body_timeout=None, + max_body_size=None, max_buffer_size=None): self.request_callback = request_callback self.no_keep_alive = no_keep_alive self.xheaders = xheaders @@ -152,14 +142,6 @@ class HTTPServer(TCPServer, Configurable, read_chunk_size=chunk_size) self._connections = set() - @classmethod - def configurable_base(cls): - return HTTPServer - - @classmethod - def configurable_default(cls): - return HTTPServer - @gen.coroutine def close_all_connections(self): while self._connections: diff --git a/tornado/simple_httpclient.py b/tornado/simple_httpclient.py index 6321a81d..f3cb1b86 100644 --- a/tornado/simple_httpclient.py +++ b/tornado/simple_httpclient.py @@ -135,14 +135,10 @@ class SimpleAsyncHTTPClient(AsyncHTTPClient): release_callback = functools.partial(self._release_fetch, key) self._handle_request(request, release_callback, callback) - def _connection_class(self): - return _HTTPConnection - def _handle_request(self, request, release_callback, final_callback): - self._connection_class()( - self.io_loop, self, request, release_callback, - final_callback, self.max_buffer_size, self.tcp_client, - self.max_header_size) + _HTTPConnection(self.io_loop, self, request, release_callback, + final_callback, self.max_buffer_size, self.tcp_client, + self.max_header_size) def _release_fetch(self, key): del self.active[key] @@ -352,7 +348,14 @@ class _HTTPConnection(httputil.HTTPMessageDelegate): self.request.headers["Accept-Encoding"] = "gzip" req_path = ((self.parsed.path or '/') + (('?' + self.parsed.query) if self.parsed.query else '')) - self.connection = self._create_connection(stream) + self.stream.set_nodelay(True) + self.connection = HTTP1Connection( + self.stream, True, + HTTP1ConnectionParameters( + no_keep_alive=True, + max_header_size=self.max_header_size, + decompress=self.request.decompress_response), + self._sockaddr) start_line = httputil.RequestStartLine(self.request.method, req_path, '') self.connection.write_headers(start_line, self.request.headers) @@ -361,20 +364,10 @@ class _HTTPConnection(httputil.HTTPMessageDelegate): else: self._write_body(True) - def _create_connection(self, stream): - stream.set_nodelay(True) - connection = HTTP1Connection( - stream, True, - HTTP1ConnectionParameters( - no_keep_alive=True, - max_header_size=self.max_header_size, - decompress=self.request.decompress_response), - self._sockaddr) - return connection - def _write_body(self, start_read): if self.request.body is not None: self.connection.write(self.request.body) + self.connection.finish() elif self.request.body_producer is not None: fut = self.request.body_producer(self.connection.write) if is_future(fut): @@ -385,7 +378,7 @@ class _HTTPConnection(httputil.HTTPMessageDelegate): self._read_response() self.io_loop.add_future(fut, on_body_written) return - self.connection.finish() + self.connection.finish() if start_read: self._read_response() diff --git a/tornado/util.py b/tornado/util.py index 606ced19..d943ce2b 100644 --- a/tornado/util.py +++ b/tornado/util.py @@ -198,21 +198,21 @@ class Configurable(object): __impl_class = None __impl_kwargs = None - def __new__(cls, *args, **kwargs): + def __new__(cls, **kwargs): base = cls.configurable_base() - init_kwargs = {} + args = {} if cls is base: impl = cls.configured_class() if base.__impl_kwargs: - init_kwargs.update(base.__impl_kwargs) + args.update(base.__impl_kwargs) else: impl = cls - init_kwargs.update(kwargs) + args.update(kwargs) instance = super(Configurable, cls).__new__(impl) # initialize vs __init__ chosen for compatibility with AsyncHTTPClient # singleton magic. If we get rid of that we can switch to __init__ # here too. - instance.initialize(*args, **init_kwargs) + instance.initialize(**args) return instance @classmethod @@ -233,9 +233,6 @@ class Configurable(object): """Initialize a `Configurable` subclass instance. Configurable classes should use `initialize` instead of ``__init__``. - - .. versionchanged:: 4.2 - Now accepts positional arguments in addition to keyword arguments. """ @classmethod diff --git a/tornado/web.py b/tornado/web.py index 62f3779d..155da550 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -650,8 +650,7 @@ class RequestHandler(object): else: assert isinstance(status, int) and 300 <= status <= 399 self.set_status(status) - self.set_header("Location", urlparse.urljoin(utf8(self.request.uri), - utf8(url))) + self.set_header("Location", utf8(url)) self.finish() def write(self, chunk):
redirect requests starting with '//' to '/' leading to wrong place Tornado uses `urljoin` to join `self.request.uri` and the destination but when `self.request.uri` starts with '//' it generates locations still start with '//' because this behaviour of `urljoin`: ``` >>> from urllib.parse import urljoin >>> urljoin('//abc', '/abc') '//abc/abc' ``` I suggest using `self.request.full_url()` instead. Also, the HTTP specification says that the Location header should include the host part. PS: `self.request.full_url()` doesn't work for proxy requests that have full urls in their request line.
tornadoweb/tornado
diff --git a/tornado/test/httpserver_test.py b/tornado/test/httpserver_test.py index c1ba831c..62ef6ca3 100644 --- a/tornado/test/httpserver_test.py +++ b/tornado/test/httpserver_test.py @@ -162,22 +162,19 @@ class BadSSLOptionsTest(unittest.TestCase): application = Application() module_dir = os.path.dirname(__file__) existing_certificate = os.path.join(module_dir, 'test.crt') - existing_key = os.path.join(module_dir, 'test.key') - self.assertRaises((ValueError, IOError), - HTTPServer, application, ssl_options={ - "certfile": "/__mising__.crt", + self.assertRaises(ValueError, HTTPServer, application, ssl_options={ + "certfile": "/__mising__.crt", }) - self.assertRaises((ValueError, IOError), - HTTPServer, application, ssl_options={ - "certfile": existing_certificate, - "keyfile": "/__missing__.key" + self.assertRaises(ValueError, HTTPServer, application, ssl_options={ + "certfile": existing_certificate, + "keyfile": "/__missing__.key" }) # This actually works because both files exist HTTPServer(application, ssl_options={ "certfile": existing_certificate, - "keyfile": existing_key, + "keyfile": existing_certificate }) diff --git a/tornado/test/runtests.py b/tornado/test/runtests.py index cb9969d3..20133d4e 100644 --- a/tornado/test/runtests.py +++ b/tornado/test/runtests.py @@ -8,7 +8,6 @@ import operator import textwrap import sys from tornado.httpclient import AsyncHTTPClient -from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.netutil import Resolver from tornado.options import define, options, add_parse_callback @@ -124,8 +123,6 @@ def main(): define('httpclient', type=str, default=None, callback=lambda s: AsyncHTTPClient.configure( s, defaults=dict(allow_ipv6=False))) - define('httpserver', type=str, default=None, - callback=HTTPServer.configure) define('ioloop', type=str, default=None) define('ioloop_time_monotonic', default=False) define('resolver', type=str, default=None, diff --git a/tornado/test/util_test.py b/tornado/test/util_test.py index 0936c89a..a0fbae43 100644 --- a/tornado/test/util_test.py +++ b/tornado/test/util_test.py @@ -46,15 +46,13 @@ class TestConfigurable(Configurable): class TestConfig1(TestConfigurable): - def initialize(self, pos_arg=None, a=None): + def initialize(self, a=None): self.a = a - self.pos_arg = pos_arg class TestConfig2(TestConfigurable): - def initialize(self, pos_arg=None, b=None): + def initialize(self, b=None): self.b = b - self.pos_arg = pos_arg class ConfigurableTest(unittest.TestCase): @@ -104,10 +102,9 @@ class ConfigurableTest(unittest.TestCase): self.assertIsInstance(obj, TestConfig1) self.assertEqual(obj.a, 3) - obj = TestConfigurable(42, a=4) + obj = TestConfigurable(a=4) self.assertIsInstance(obj, TestConfig1) self.assertEqual(obj.a, 4) - self.assertEqual(obj.pos_arg, 42) self.checkSubclasses() # args bound in configure don't apply when using the subclass directly @@ -120,10 +117,9 @@ class ConfigurableTest(unittest.TestCase): self.assertIsInstance(obj, TestConfig2) self.assertEqual(obj.b, 5) - obj = TestConfigurable(42, b=6) + obj = TestConfigurable(b=6) self.assertIsInstance(obj, TestConfig2) self.assertEqual(obj.b, 6) - self.assertEqual(obj.pos_arg, 42) self.checkSubclasses() # args bound in configure don't apply when using the subclass directly diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py index f3c8505a..a52f1667 100644 --- a/tornado/test/web_test.py +++ b/tornado/test/web_test.py @@ -597,6 +597,7 @@ class WSGISafeWebTest(WebTestCase): url("/redirect", RedirectHandler), url("/web_redirect_permanent", WebRedirectHandler, {"url": "/web_redirect_newpath"}), url("/web_redirect", WebRedirectHandler, {"url": "/web_redirect_newpath", "permanent": False}), + url("//web_redirect_double_slash", WebRedirectHandler, {"url": '/web_redirect_newpath'}), url("/header_injection", HeaderInjectionHandler), url("/get_argument", GetArgumentHandler), url("/get_arguments", GetArgumentsHandler), @@ -730,6 +731,11 @@ js_embed() self.assertEqual(response.code, 302) self.assertEqual(response.headers['Location'], '/web_redirect_newpath') + def test_web_redirect_double_slash(self): + response = self.fetch("//web_redirect_double_slash", follow_redirects=False) + self.assertEqual(response.code, 301) + self.assertEqual(response.headers['Location'], '/web_redirect_newpath') + def test_header_injection(self): response = self.fetch("/header_injection") self.assertEqual(response.body, b"ok") diff --git a/tornado/testing.py b/tornado/testing.py index 93f0dbe1..3d3bcf72 100644 --- a/tornado/testing.py +++ b/tornado/testing.py @@ -417,8 +417,10 @@ class AsyncHTTPSTestCase(AsyncHTTPTestCase): Interface is generally the same as `AsyncHTTPTestCase`. """ def get_http_client(self): - return AsyncHTTPClient(io_loop=self.io_loop, force_instance=True, - defaults=dict(validate_cert=False)) + # Some versions of libcurl have deadlock bugs with ssl, + # so always run these tests with SimpleAsyncHTTPClient. + return SimpleAsyncHTTPClient(io_loop=self.io_loop, force_instance=True, + defaults=dict(validate_cert=False)) def get_httpserver_options(self): return dict(ssl_options=self.get_ssl_options())
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 4 }
4.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "maint/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 autopep8==1.1 certifi==14.5.14 coverage==3.7.1 docutils==0.12 flake8==2.3.0 importlib-metadata==4.8.3 iniconfig==1.1.1 Jinja2==2.7.3 MarkupSafe==0.23 mccabe==0.3 packaging==21.3 pep8==1.6.0 pkginfo==1.2.1 pluggy==1.0.0 py==1.11.0 pycurl==7.19.5.1 pyflakes==0.8.1 Pygments==2.0.2 pyparsing==3.1.4 pytest==7.0.1 requests==2.5.1 Sphinx==1.2.3 sphinx-rtd-theme==0.1.6 tomli==1.2.3 -e git+https://github.com/tornadoweb/tornado.git@cf2a54794ff5067d6d815013d6570ee10f74d5e5#egg=tornado tox==1.8.1 twine==1.4.0 Twisted==15.0.0 typing_extensions==4.1.1 virtualenv==12.0.7 zipp==3.6.0 zope.interface==4.1.2
name: tornado channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - autopep8==1.1 - certifi==14.5.14 - coverage==3.7.1 - docutils==0.12 - flake8==2.3.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jinja2==2.7.3 - markupsafe==0.23 - mccabe==0.3 - packaging==21.3 - pep8==1.6.0 - pkginfo==1.2.1 - pluggy==1.0.0 - py==1.11.0 - pycurl==7.19.5.1 - pyflakes==0.8.1 - pygments==2.0.2 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.5.1 - sphinx==1.2.3 - sphinx-rtd-theme==0.1.6 - tomli==1.2.3 - tox==1.8.1 - twine==1.4.0 - twisted==15.0.0 - typing-extensions==4.1.1 - virtualenv==12.0.7 - zipp==3.6.0 - zope-interface==4.1.2 prefix: /opt/conda/envs/tornado
[ "tornado/test/web_test.py::WSGISafeWebTest::test_web_redirect_double_slash" ]
[ "tornado/test/httpserver_test.py::HTTPServerRawTest::test_malformed_first_line", "tornado/test/httpserver_test.py::HTTPServerRawTest::test_malformed_headers", "tornado/test/httpserver_test.py::UnixSocketTest::test_unix_socket_bad_request", "tornado/test/httpserver_test.py::MaxHeaderSizeTest::test_large_headers", "tornado/test/httpserver_test.py::BodyLimitsTest::test_body_size_override_reset", "tornado/test/httpserver_test.py::BodyLimitsTest::test_large_body_buffered", "tornado/test/httpserver_test.py::BodyLimitsTest::test_large_body_buffered_chunked", "tornado/test/httpserver_test.py::BodyLimitsTest::test_large_body_streaming", "tornado/test/httpserver_test.py::BodyLimitsTest::test_large_body_streaming_chunked", "tornado/test/httpserver_test.py::BodyLimitsTest::test_timeout", "tornado/test/web_test.py::ClearAllCookiesTest::test_clear_all_cookies" ]
[ "tornado/test/httpserver_test.py::SSLv23Test::test_large_post", "tornado/test/httpserver_test.py::SSLv23Test::test_non_ssl_request", "tornado/test/httpserver_test.py::SSLv23Test::test_ssl", "tornado/test/httpserver_test.py::SSLv3Test::test_large_post", "tornado/test/httpserver_test.py::SSLv3Test::test_non_ssl_request", "tornado/test/httpserver_test.py::SSLv3Test::test_ssl", "tornado/test/httpserver_test.py::TLSv1Test::test_large_post", "tornado/test/httpserver_test.py::TLSv1Test::test_non_ssl_request", "tornado/test/httpserver_test.py::TLSv1Test::test_ssl", "tornado/test/httpserver_test.py::SSLContextTest::test_large_post", "tornado/test/httpserver_test.py::SSLContextTest::test_non_ssl_request", "tornado/test/httpserver_test.py::SSLContextTest::test_ssl", "tornado/test/httpserver_test.py::BadSSLOptionsTest::test_missing_arguments", "tornado/test/httpserver_test.py::BadSSLOptionsTest::test_missing_key", "tornado/test/httpserver_test.py::HTTPConnectionTest::test_100_continue", "tornado/test/httpserver_test.py::HTTPConnectionTest::test_multipart_form", "tornado/test/httpserver_test.py::HTTPConnectionTest::test_newlines", "tornado/test/httpserver_test.py::HTTPServerTest::test_double_slash", "tornado/test/httpserver_test.py::HTTPServerTest::test_empty_post_parameters", "tornado/test/httpserver_test.py::HTTPServerTest::test_empty_query_string", "tornado/test/httpserver_test.py::HTTPServerTest::test_malformed_body", "tornado/test/httpserver_test.py::HTTPServerTest::test_query_string_encoding", "tornado/test/httpserver_test.py::HTTPServerTest::test_types", "tornado/test/httpserver_test.py::HTTPServerRawTest::test_chunked_request_body", "tornado/test/httpserver_test.py::HTTPServerRawTest::test_empty_request", "tornado/test/httpserver_test.py::XHeaderTest::test_ip_headers", "tornado/test/httpserver_test.py::XHeaderTest::test_scheme_headers", "tornado/test/httpserver_test.py::SSLXHeaderTest::test_request_without_xprotocol", "tornado/test/httpserver_test.py::ManualProtocolTest::test_manual_protocol", "tornado/test/httpserver_test.py::UnixSocketTest::test_unix_socket", "tornado/test/httpserver_test.py::KeepAliveTest::test_cancel_during_download", "tornado/test/httpserver_test.py::KeepAliveTest::test_finish_while_closed", "tornado/test/httpserver_test.py::KeepAliveTest::test_http10", "tornado/test/httpserver_test.py::KeepAliveTest::test_http10_keepalive", "tornado/test/httpserver_test.py::KeepAliveTest::test_http10_keepalive_extra_crlf", "tornado/test/httpserver_test.py::KeepAliveTest::test_keepalive_chunked", "tornado/test/httpserver_test.py::KeepAliveTest::test_pipelined_cancel", "tornado/test/httpserver_test.py::KeepAliveTest::test_pipelined_requests", "tornado/test/httpserver_test.py::KeepAliveTest::test_request_close", "tornado/test/httpserver_test.py::KeepAliveTest::test_two_requests", "tornado/test/httpserver_test.py::GzipTest::test_gzip", "tornado/test/httpserver_test.py::GzipTest::test_uncompressed", "tornado/test/httpserver_test.py::GzipUnsupportedTest::test_gzip_unsupported", "tornado/test/httpserver_test.py::GzipUnsupportedTest::test_uncompressed", "tornado/test/httpserver_test.py::StreamingChunkSizeTest::test_chunked_body", "tornado/test/httpserver_test.py::StreamingChunkSizeTest::test_chunked_compressed", "tornado/test/httpserver_test.py::StreamingChunkSizeTest::test_compressed_body", "tornado/test/httpserver_test.py::StreamingChunkSizeTest::test_regular_body", "tornado/test/httpserver_test.py::MaxHeaderSizeTest::test_small_headers", "tornado/test/httpserver_test.py::IdleTimeoutTest::test_idle_after_use", "tornado/test/httpserver_test.py::IdleTimeoutTest::test_unused_connection", "tornado/test/httpserver_test.py::BodyLimitsTest::test_large_body_streaming_chunked_override", "tornado/test/httpserver_test.py::BodyLimitsTest::test_large_body_streaming_override", "tornado/test/httpserver_test.py::BodyLimitsTest::test_small_body", "tornado/test/httpserver_test.py::LegacyInterfaceTest::test_legacy_interface", "tornado/test/util_test.py::RaiseExcInfoTest::test_two_arg_exception", "tornado/test/util_test.py::ConfigurableTest::test_config_args", "tornado/test/util_test.py::ConfigurableTest::test_config_class", "tornado/test/util_test.py::ConfigurableTest::test_config_class_args", "tornado/test/util_test.py::ConfigurableTest::test_default", "tornado/test/util_test.py::UnicodeLiteralTest::test_unicode_escapes", "tornado/test/util_test.py::ArgReplacerTest::test_keyword", "tornado/test/util_test.py::ArgReplacerTest::test_omitted", "tornado/test/util_test.py::ArgReplacerTest::test_position", "tornado/test/util_test.py::TimedeltaToSecondsTest::test_timedelta_to_seconds", "tornado/test/util_test.py::ImportObjectTest::test_import_member", "tornado/test/util_test.py::ImportObjectTest::test_import_member_unicode", "tornado/test/util_test.py::ImportObjectTest::test_import_module", "tornado/test/util_test.py::ImportObjectTest::test_import_module_unicode", "tornado/test/web_test.py::SecureCookieV1Test::test_arbitrary_bytes", "tornado/test/web_test.py::SecureCookieV1Test::test_cookie_tampering_future_timestamp", "tornado/test/web_test.py::SecureCookieV1Test::test_round_trip", "tornado/test/web_test.py::CookieTest::test_cookie_special_char", "tornado/test/web_test.py::CookieTest::test_get_cookie", "tornado/test/web_test.py::CookieTest::test_set_cookie", "tornado/test/web_test.py::CookieTest::test_set_cookie_domain", "tornado/test/web_test.py::CookieTest::test_set_cookie_expires_days", "tornado/test/web_test.py::CookieTest::test_set_cookie_false_flags", "tornado/test/web_test.py::CookieTest::test_set_cookie_max_age", "tornado/test/web_test.py::CookieTest::test_set_cookie_overwrite", "tornado/test/web_test.py::AuthRedirectTest::test_absolute_auth_redirect", "tornado/test/web_test.py::AuthRedirectTest::test_relative_auth_redirect", "tornado/test/web_test.py::ConnectionCloseTest::test_connection_close", "tornado/test/web_test.py::RequestEncodingTest::test_group_encoding", "tornado/test/web_test.py::RequestEncodingTest::test_group_question_mark", "tornado/test/web_test.py::RequestEncodingTest::test_slashes", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument_invalid_unicode", "tornado/test/web_test.py::WSGISafeWebTest::test_decode_argument_plus", "tornado/test/web_test.py::WSGISafeWebTest::test_get_argument", "tornado/test/web_test.py::WSGISafeWebTest::test_get_body_arguments", "tornado/test/web_test.py::WSGISafeWebTest::test_get_query_arguments", "tornado/test/web_test.py::WSGISafeWebTest::test_header_injection", "tornado/test/web_test.py::WSGISafeWebTest::test_multi_header", "tornado/test/web_test.py::WSGISafeWebTest::test_no_gzip", "tornado/test/web_test.py::WSGISafeWebTest::test_optional_path", "tornado/test/web_test.py::WSGISafeWebTest::test_redirect", "tornado/test/web_test.py::WSGISafeWebTest::test_reverse_url", "tornado/test/web_test.py::WSGISafeWebTest::test_types", "tornado/test/web_test.py::WSGISafeWebTest::test_uimodule_resources", "tornado/test/web_test.py::WSGISafeWebTest::test_uimodule_unescaped", "tornado/test/web_test.py::WSGISafeWebTest::test_web_redirect", "tornado/test/web_test.py::NonWSGIWebTests::test_empty_flush", "tornado/test/web_test.py::NonWSGIWebTests::test_flow_control", "tornado/test/web_test.py::ErrorResponseTest::test_default", "tornado/test/web_test.py::ErrorResponseTest::test_failed_write_error", "tornado/test/web_test.py::ErrorResponseTest::test_write_error", "tornado/test/web_test.py::StaticFileTest::test_absolute_static_url", "tornado/test/web_test.py::StaticFileTest::test_absolute_version_exclusion", "tornado/test/web_test.py::StaticFileTest::test_include_host_override", "tornado/test/web_test.py::StaticFileTest::test_relative_version_exclusion", "tornado/test/web_test.py::StaticFileTest::test_static_304_if_modified_since", "tornado/test/web_test.py::StaticFileTest::test_static_304_if_none_match", "tornado/test/web_test.py::StaticFileTest::test_static_404", "tornado/test/web_test.py::StaticFileTest::test_static_etag", "tornado/test/web_test.py::StaticFileTest::test_static_files", "tornado/test/web_test.py::StaticFileTest::test_static_head", "tornado/test/web_test.py::StaticFileTest::test_static_head_range", "tornado/test/web_test.py::StaticFileTest::test_static_if_modified_since_pre_epoch", "tornado/test/web_test.py::StaticFileTest::test_static_if_modified_since_time_zone", "tornado/test/web_test.py::StaticFileTest::test_static_invalid_range", "tornado/test/web_test.py::StaticFileTest::test_static_range_if_none_match", "tornado/test/web_test.py::StaticFileTest::test_static_unsatisfiable_range_invalid_start", "tornado/test/web_test.py::StaticFileTest::test_static_unsatisfiable_range_zero_suffix", "tornado/test/web_test.py::StaticFileTest::test_static_url", "tornado/test/web_test.py::StaticFileTest::test_static_with_range", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_end_edge", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_full_file", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_full_past_end", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_neg_end", "tornado/test/web_test.py::StaticFileTest::test_static_with_range_partial_past_end", "tornado/test/web_test.py::StaticDefaultFilenameTest::test_static_default_filename", "tornado/test/web_test.py::StaticDefaultFilenameTest::test_static_default_redirect", "tornado/test/web_test.py::StaticFileWithPathTest::test_serve", "tornado/test/web_test.py::CustomStaticFileTest::test_serve", "tornado/test/web_test.py::CustomStaticFileTest::test_static_url", "tornado/test/web_test.py::HostMatchingTest::test_host_matching", "tornado/test/web_test.py::NamedURLSpecGroupsTest::test_named_urlspec_groups", "tornado/test/web_test.py::ClearHeaderTest::test_clear_header", "tornado/test/web_test.py::Header304Test::test_304_headers", "tornado/test/web_test.py::StatusReasonTest::test_status", "tornado/test/web_test.py::DateHeaderTest::test_date_header", "tornado/test/web_test.py::RaiseWithReasonTest::test_httperror_str", "tornado/test/web_test.py::RaiseWithReasonTest::test_raise_with_reason", "tornado/test/web_test.py::ErrorHandlerXSRFTest::test_404_xsrf", "tornado/test/web_test.py::ErrorHandlerXSRFTest::test_error_xsrf", "tornado/test/web_test.py::GzipTestCase::test_gzip", "tornado/test/web_test.py::GzipTestCase::test_gzip_not_requested", "tornado/test/web_test.py::GzipTestCase::test_gzip_static", "tornado/test/web_test.py::GzipTestCase::test_vary_already_present", "tornado/test/web_test.py::PathArgsInPrepareTest::test_kw", "tornado/test/web_test.py::PathArgsInPrepareTest::test_pos", "tornado/test/web_test.py::ExceptionHandlerTest::test_http_error", "tornado/test/web_test.py::ExceptionHandlerTest::test_known_error", "tornado/test/web_test.py::ExceptionHandlerTest::test_unknown_error", "tornado/test/web_test.py::BuggyLoggingTest::test_buggy_log_exception", "tornado/test/web_test.py::UIMethodUIModuleTest::test_ui_method", "tornado/test/web_test.py::GetArgumentErrorTest::test_catch_error", "tornado/test/web_test.py::MultipleExceptionTest::test_multi_exception", "tornado/test/web_test.py::SetLazyPropertiesTest::test_set_properties", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_from_ui_module_is_lazy", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_from_ui_module_works", "tornado/test/web_test.py::GetCurrentUserTest::test_get_current_user_works", "tornado/test/web_test.py::UnimplementedHTTPMethodsTest::test_unimplemented_standard_methods", "tornado/test/web_test.py::UnimplementedNonStandardMethodsTest::test_unimplemented_other", "tornado/test/web_test.py::UnimplementedNonStandardMethodsTest::test_unimplemented_patch", "tornado/test/web_test.py::AllHTTPMethodsTest::test_standard_methods", "tornado/test/web_test.py::PatchMethodTest::test_other", "tornado/test/web_test.py::PatchMethodTest::test_patch", "tornado/test/web_test.py::FinishInPrepareTest::test_finish_in_prepare", "tornado/test/web_test.py::Default404Test::test_404", "tornado/test/web_test.py::Custom404Test::test_404", "tornado/test/web_test.py::DefaultHandlerArgumentsTest::test_403", "tornado/test/web_test.py::HandlerByNameTest::test_handler_by_name", "tornado/test/web_test.py::StreamingRequestBodyTest::test_close_during_upload", "tornado/test/web_test.py::StreamingRequestBodyTest::test_early_return", "tornado/test/web_test.py::StreamingRequestBodyTest::test_early_return_with_data", "tornado/test/web_test.py::StreamingRequestBodyTest::test_streaming_body", "tornado/test/web_test.py::StreamingRequestFlowControlTest::test_flow_control", "tornado/test/web_test.py::IncorrectContentLengthTest::test_content_length_too_high", "tornado/test/web_test.py::IncorrectContentLengthTest::test_content_length_too_low", "tornado/test/web_test.py::ClientCloseTest::test_client_close", "tornado/test/web_test.py::SignedValueTest::test_expired", "tornado/test/web_test.py::SignedValueTest::test_known_values", "tornado/test/web_test.py::SignedValueTest::test_name_swap", "tornado/test/web_test.py::SignedValueTest::test_non_ascii", "tornado/test/web_test.py::SignedValueTest::test_payload_tampering", "tornado/test/web_test.py::SignedValueTest::test_signature_tampering", "tornado/test/web_test.py::XSRFTest::test_cross_user", "tornado/test/web_test.py::XSRFTest::test_distinct_tokens", "tornado/test/web_test.py::XSRFTest::test_refresh_token", "tornado/test/web_test.py::XSRFTest::test_versioning", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_body_no_cookie", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_cookie_no_body", "tornado/test/web_test.py::XSRFTest::test_xsrf_fail_no_token", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_header", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_non_hex_token", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_post_body", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_query_string", "tornado/test/web_test.py::XSRFTest::test_xsrf_success_short_token", "tornado/test/web_test.py::FinishExceptionTest::test_finish_exception", "tornado/test/web_test.py::DecoratorTest::test_addslash", "tornado/test/web_test.py::DecoratorTest::test_removeslash", "tornado/test/web_test.py::CacheTest::test_multiple_strong_etag_match", "tornado/test/web_test.py::CacheTest::test_multiple_strong_etag_not_match", "tornado/test/web_test.py::CacheTest::test_multiple_weak_etag_match", "tornado/test/web_test.py::CacheTest::test_multiple_weak_etag_not_match", "tornado/test/web_test.py::CacheTest::test_strong_etag_match", "tornado/test/web_test.py::CacheTest::test_strong_etag_not_match", "tornado/test/web_test.py::CacheTest::test_weak_etag_match", "tornado/test/web_test.py::CacheTest::test_weak_etag_not_match", "tornado/test/web_test.py::CacheTest::test_wildcard_etag", "tornado/test/web_test.py::RequestSummaryTest::test_missing_remote_ip" ]
[]
Apache License 2.0
56
1,757
[ "tornado/httpserver.py", "tornado/simple_httpclient.py", "tornado/util.py", "tornado/web.py" ]
caesar0301__treelib-40
65635f48781f4426be9f55f1555d0c08454157bc
2015-03-10 07:23:19
bbd7bc557ab87dd0ebc449495f6041825be4a7c8
diff --git a/treelib/tree.py b/treelib/tree.py index 9bcf610..634566c 100644 --- a/treelib/tree.py +++ b/treelib/tree.py @@ -556,16 +556,16 @@ class Tree(object): if not self.contains(nid): raise NodeIDAbsentError("Node '%s' is not in the tree" % nid) - label = ('{0}'.format(self[nid].tag.decode('utf-8')))\ + label = ('{0}'.format(self[nid].tag))\ if idhidden \ else ('{0}[{1}]'.format( - self[nid].tag.decode('utf-8'), - self[nid].identifier.decode('utf-8'))) + self[nid].tag, + self[nid].identifier)) filter = (self._real_true) if (filter is None) else filter if level == self.ROOT: - func(label) + func(label.encode('utf8')) else: leading = ''.join(map(lambda x: DT_VLINE + ' ' * 3 if not x else ' ' * 4, iflast[0:-1]))
AttributeError: 'str' object has no attribute 'decode' python3.4, OSX 10.10 ```python >>> from treelib import Tree, Node >>> tree = Tree() >>> tree.create_node("Harry", "harry") >>> tree.create_node("Jane", "jane", parent="harry") >>> tree.show() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.4/site-packages/treelib/tree.py", line 517, in show func=print) File "/usr/local/lib/python3.4/site-packages/treelib/tree.py", line 560, in _print_backend if idhidden \ AttributeError: 'str' object has no attribute 'decode' ```
caesar0301/treelib
diff --git a/tests/test_treelib.py b/tests/test_treelib.py index 952f851..a061c8a 100644 --- a/tests/test_treelib.py +++ b/tests/test_treelib.py @@ -1,4 +1,10 @@ #!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import unicode_literals +try: + from StringIO import StringIO as BytesIO +except ImportError: + from io import BytesIO import unittest from treelib import Tree, Node from treelib.tree import NodeIDAbsentError @@ -58,9 +64,9 @@ class NodeCase(unittest.TestCase): class TreeCase(unittest.TestCase): def setUp(self): tree = Tree() - tree.create_node("Harry", "harry") - tree.create_node("Jane", "jane", parent="harry") - tree.create_node("Bill", "bill", parent="harry") + tree.create_node("Hárry", "hárry") + tree.create_node("Jane", "jane", parent="hárry") + tree.create_node("Bill", "bill", parent="hárry") tree.create_node("Diane", "diane", parent="jane") tree.create_node("George", "george", parent="bill") self.tree = tree @@ -71,14 +77,14 @@ class TreeCase(unittest.TestCase): self.assertEqual(isinstance(self.copytree, Tree), True) def test_is_root(self): - self.assertTrue(self.tree._nodes['harry'].is_root()) + self.assertTrue(self.tree._nodes['hárry'].is_root()) self.assertFalse(self.tree._nodes['jane'].is_root()) def test_paths_to_leaves(self): paths = self.tree.paths_to_leaves() self.assertEqual( len(paths), 2 ) - self.assertTrue( ['harry', 'jane', 'diane'] in paths ) - self.assertTrue( ['harry', 'bill', 'george'] in paths ) + self.assertTrue( ['hárry', 'jane', 'diane'] in paths ) + self.assertTrue( ['hárry', 'bill', 'george'] in paths ) def test_nodes(self): self.assertEqual(len(self.tree.nodes), 5) @@ -148,7 +154,7 @@ class TreeCase(unittest.TestCase): # Try getting the level of the node """ self.tree.show() - Harry + Hárry |___ Bill | |___ George | |___ Jill @@ -161,7 +167,7 @@ class TreeCase(unittest.TestCase): self.assertEqual(self.tree.depth(self.tree.get_node("george")), 2) self.assertEqual(self.tree.depth("jane"), 1) self.assertEqual(self.tree.depth("bill"), 1) - self.assertEqual(self.tree.depth("harry"), 0) + self.assertEqual(self.tree.depth("hárry"), 0) # Try getting Exception node = Node("Test One", "identifier 1") @@ -177,11 +183,11 @@ class TreeCase(unittest.TestCase): in leaves), True) def test_link_past_node(self): - self.tree.create_node("Jill", "jill", parent="harry") + self.tree.create_node("Jill", "jill", parent="hárry") self.tree.create_node("Mark", "mark", parent="jill") - self.assertEqual("mark" not in self.tree.is_branch("harry"), True) + self.assertEqual("mark" not in self.tree.is_branch("hárry"), True) self.tree.link_past_node("jill") - self.assertEqual("mark" in self.tree.is_branch("harry"), True) + self.assertEqual("mark" in self.tree.is_branch("hárry"), True) def test_expand_tree(self): nodes = [self.tree[nid] for nid in self.tree.expand_tree()] @@ -202,7 +208,7 @@ class TreeCase(unittest.TestCase): self.tree.remove_node("jill") def test_rsearch(self): - for nid in ["harry", "jane", "diane"]: + for nid in ["hárry", "jane", "diane"]: self.assertEqual(nid in self.tree.rsearch("diane"), True) def test_subtree(self): @@ -216,8 +222,8 @@ class TreeCase(unittest.TestCase): def test_remove_subtree(self): subtree_shallow = self.tree.remove_subtree("jane") - self.assertEqual("jane" not in self.tree.is_branch("harry"), True) - self.tree.paste("harry", subtree_shallow) + self.assertEqual("jane" not in self.tree.is_branch("hárry"), True) + self.tree.paste("hárry", subtree_shallow) def test_to_json(self): self.assertEqual.__self__.maxDiff = None @@ -225,7 +231,7 @@ class TreeCase(unittest.TestCase): self.tree.to_json(True) def test_siblings(self): - self.assertEqual(len(self.tree.siblings("harry")) == 0, True) + self.assertEqual(len(self.tree.siblings("hárry")) == 0, True) self.assertEqual(self.tree.siblings("jane")[0].identifier == "bill", True) @@ -239,13 +245,29 @@ class TreeCase(unittest.TestCase): self.tree.remove_node("jill") def test_level(self): - self.assertEqual(self.tree.level('harry'), 0) + self.assertEqual(self.tree.level('hárry'), 0) depth = self.tree.depth() self.assertEqual(self.tree.level('diane'), depth) self.assertEqual(self.tree.level('diane', lambda x: x.identifier!='jane'), depth-1) + def test_print_backend(self): + reader = BytesIO() + + def write(line): + reader.write(line + b'\n') + + self.tree._print_backend(func=write) + + assert reader.getvalue() == """\ +Hárry +├── Bill +│ └── George +└── Jane + └── Diane +""".encode('utf8') + def tearDown(self): self.tree = None self.copytree = None
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
1.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "coverage", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work nose==1.3.7 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work -e git+https://github.com/caesar0301/treelib.git@65635f48781f4426be9f55f1555d0c08454157bc#egg=treelib
name: treelib channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - nose==1.3.7 prefix: /opt/conda/envs/treelib
[ "tests/test_treelib.py::TreeCase::test_print_backend" ]
[]
[ "tests/test_treelib.py::NodeCase::test_data", "tests/test_treelib.py::NodeCase::test_initialization", "tests/test_treelib.py::NodeCase::test_set_bpointer", "tests/test_treelib.py::NodeCase::test_set_fpointer", "tests/test_treelib.py::NodeCase::test_set_identifier", "tests/test_treelib.py::NodeCase::test_set_is_leaf", "tests/test_treelib.py::NodeCase::test_set_tag", "tests/test_treelib.py::TreeCase::test_children", "tests/test_treelib.py::TreeCase::test_depth", "tests/test_treelib.py::TreeCase::test_expand_tree", "tests/test_treelib.py::TreeCase::test_getitem", "tests/test_treelib.py::TreeCase::test_is_root", "tests/test_treelib.py::TreeCase::test_leaves", "tests/test_treelib.py::TreeCase::test_level", "tests/test_treelib.py::TreeCase::test_link_past_node", "tests/test_treelib.py::TreeCase::test_move_node", "tests/test_treelib.py::TreeCase::test_nodes", "tests/test_treelib.py::TreeCase::test_parent", "tests/test_treelib.py::TreeCase::test_paste_tree", "tests/test_treelib.py::TreeCase::test_paths_to_leaves", "tests/test_treelib.py::TreeCase::test_remove_node", "tests/test_treelib.py::TreeCase::test_remove_subtree", "tests/test_treelib.py::TreeCase::test_rsearch", "tests/test_treelib.py::TreeCase::test_siblings", "tests/test_treelib.py::TreeCase::test_subtree", "tests/test_treelib.py::TreeCase::test_to_json", "tests/test_treelib.py::TreeCase::test_tree", "tests/test_treelib.py::TreeCase::test_tree_data" ]
[]
Apache License 2.0
58
282
[ "treelib/tree.py" ]
enthought__okonomiyaki-34
d32923ad74059883e31aaed8c12d3cd5e0288acd
2015-03-17 21:13:01
d32923ad74059883e31aaed8c12d3cd5e0288acd
diff --git a/okonomiyaki/platforms/epd_platform.py b/okonomiyaki/platforms/epd_platform.py index 441712a..d32d37a 100644 --- a/okonomiyaki/platforms/epd_platform.py +++ b/okonomiyaki/platforms/epd_platform.py @@ -172,20 +172,16 @@ def _guess_architecture(): """ Returns the architecture of the running python. """ - x86 = "x86" - amd64 = "amd64" - bits = platform.architecture()[0] machine = platform.machine() - if machine in ("AMD64", "x86_64"): - if bits == "32bit": - return x86 - elif bits == "64bit": - return amd64 - elif machine in ("x86", "i386", "i686") and bits == "32bit": - return x86 + + if machine in ("AMD64", "x86_64", "x86", "i386", "i686"): + if sys.maxsize > 2 ** 32: + return "amd64" + else: + return "x86" else: - raise OkonomiyakiError("Unknown bits/machine combination {0}/{1}". - format(bits, machine)) + raise OkonomiyakiError("Unknown machine combination {0!r}". + format(machine)) def _guess_epd_platform(arch=None): diff --git a/okonomiyaki/platforms/platform.py b/okonomiyaki/platforms/platform.py index bb20a39..f5db84f 100644 --- a/okonomiyaki/platforms/platform.py +++ b/okonomiyaki/platforms/platform.py @@ -3,6 +3,8 @@ from __future__ import absolute_import import platform import sys +from okonomiyaki.platforms import epd_platform + from okonomiyaki.bundled.traitlets import HasTraits, Enum, Instance, Unicode from okonomiyaki.platforms.epd_platform import EPDPlatform from okonomiyaki.errors import OkonomiyakiError @@ -200,18 +202,14 @@ def _guess_architecture(): """ Returns the architecture of the running python. """ - bits = platform.architecture()[0] - machine = platform.machine() - if machine in ("AMD64", "x86_64"): - if bits == "32bit": - return Arch.from_name(X86) - elif bits == "64bit": - return Arch.from_name(X86_64) - elif machine in ("x86", "i386", "i686") and bits == "32bit": + epd_platform_arch = epd_platform._guess_architecture() + if epd_platform_arch == "x86": return Arch.from_name(X86) + elif epd_platform_arch == "amd64": + return Arch.from_name(X86_64) else: - raise OkonomiyakiError("Unknown bits/machine combination {0}/{1}". - format(bits, machine)) + raise OkonomiyakiError("Unknown architecture {0!r}". + format(epd_platform_arch)) def _guess_machine():
Fix platform guessing on 64 bits processes on 32 bits kernel See #31
enthought/okonomiyaki
diff --git a/okonomiyaki/platforms/tests/common.py b/okonomiyaki/platforms/tests/common.py index b7ff851..8eb942b 100644 --- a/okonomiyaki/platforms/tests/common.py +++ b/okonomiyaki/platforms/tests/common.py @@ -63,14 +63,12 @@ mock_osx_10_7 = MultiPatcher([ # Architecture mocking mock_machine = lambda machine: Patcher(mock.patch("platform.machine", lambda: machine)) -mock_architecture = lambda arch: Patcher(mock.patch("platform.architecture", - lambda: arch)) mock_machine_x86 = Patcher(mock_machine("x86")) -mock_architecture_32bit = Patcher(mock_architecture(("32bit",))) +mock_architecture_32bit = Patcher(mock.patch("sys.maxsize", 2**32-1)) mock_machine_x86_64 = Patcher(mock_machine("x86_64")) -mock_architecture_64bit = Patcher(mock_architecture(("64bit",))) +mock_architecture_64bit = Patcher(mock.patch("sys.maxsize", 2**64-1)) mock_x86 = MultiPatcher([mock_machine_x86, mock_architecture_32bit]) mock_x86_64 = MultiPatcher([mock_machine_x86_64, mock_architecture_64bit]) diff --git a/okonomiyaki/platforms/tests/test_epd_platform.py b/okonomiyaki/platforms/tests/test_epd_platform.py index edb27a8..9cf711f 100644 --- a/okonomiyaki/platforms/tests/test_epd_platform.py +++ b/okonomiyaki/platforms/tests/test_epd_platform.py @@ -8,9 +8,12 @@ from okonomiyaki.platforms.epd_platform import (_guess_architecture, _guess_epd_platform, applies) from okonomiyaki.platforms.legacy import _SUBDIR -from .common import (mock_centos_3_5, mock_centos_5_8, mock_centos_6_3, - mock_darwin, mock_machine_armv71, mock_solaris, - mock_ubuntu_raring, mock_windows, mock_x86, mock_x86_64) +from .common import (mock_architecture_32bit, mock_architecture_64bit, + mock_centos_3_5, mock_centos_5_8, mock_centos_6_3, + mock_darwin, mock_machine_x86, mock_machine_x86_64, + mock_machine_armv71, mock_solaris, + mock_ubuntu_raring, mock_windows, mock_x86, + mock_x86_64) class TestEPDPlatform(unittest.TestCase): @@ -94,12 +97,52 @@ class TestGuessEPDPlatform(unittest.TestCase): @mock_darwin def test_guess_darwin_platform(self): - epd_platform = _guess_epd_platform("x86") + # When + with mock_machine_x86: + epd_platform = _guess_epd_platform("x86") + + # Then self.assertEqual(epd_platform.short, "osx-32") - epd_platform = _guess_epd_platform("amd64") + # When + with mock_machine_x86: + epd_platform = _guess_epd_platform("amd64") + + # Then + self.assertEqual(epd_platform.short, "osx-64") + + # When + with mock_machine_x86: + with mock_architecture_32bit: + epd_platform = _guess_epd_platform() + + # Then + self.assertEqual(epd_platform.short, "osx-32") + + # When + with mock_machine_x86: + with mock_architecture_64bit: + epd_platform = _guess_epd_platform() + + # Then self.assertEqual(epd_platform.short, "osx-64") + # When + with mock_machine_x86_64: + with mock_architecture_64bit: + epd_platform = _guess_epd_platform() + + # Then + self.assertEqual(epd_platform.short, "osx-64") + + # When + with mock_machine_x86_64: + with mock_architecture_32bit: + epd_platform = _guess_epd_platform() + + # Then + self.assertEqual(epd_platform.short, "osx-32") + def test_guess_linux2_platform(self): with mock_centos_5_8: epd_platform = _guess_epd_platform("x86") @@ -109,27 +152,27 @@ class TestGuessEPDPlatform(unittest.TestCase): self.assertEqual(epd_platform.short, "rh5-64") with mock.patch("platform.machine", lambda: "x86"): - with mock.patch("platform.architecture", lambda: ("32bit",)): + with mock_architecture_32bit: epd_platform = _guess_epd_platform() self.assertEqual(epd_platform.short, "rh5-32") with mock.patch("platform.machine", lambda: "i386"): - with mock.patch("platform.architecture", lambda: ("32bit",)): + with mock_architecture_32bit: epd_platform = _guess_epd_platform() self.assertEqual(epd_platform.short, "rh5-32") with mock.patch("platform.machine", lambda: "i686"): - with mock.patch("platform.architecture", lambda: ("32bit",)): + with mock_architecture_32bit: epd_platform = _guess_epd_platform() self.assertEqual(epd_platform.short, "rh5-32") with mock.patch("platform.machine", lambda: "x86_64"): - with mock.patch("platform.architecture", lambda: ("32bit",)): + with mock_architecture_32bit: epd_platform = _guess_epd_platform() self.assertEqual(epd_platform.short, "rh5-32") with mock.patch("platform.machine", lambda: "x86_64"): - with mock.patch("platform.architecture", lambda: ("64bit",)): + with mock_architecture_64bit: epd_platform = _guess_epd_platform() self.assertEqual(epd_platform.short, "rh5-64")
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 2 }
0.4
{ "env_vars": null, "env_yml_path": [], "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [], "python": "3.7", "reqs_path": [ "dev_requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi coverage==7.2.7 docutils==0.20.1 enum34==1.1.10 exceptiongroup==1.2.2 flake8==5.0.4 haas==0.9.0 importlib-metadata==4.2.0 iniconfig==2.0.0 mccabe==0.7.0 mock==5.2.0 -e git+https://github.com/enthought/okonomiyaki.git@d32923ad74059883e31aaed8c12d3cd5e0288acd#egg=okonomiyaki packaging==24.0 pbr==6.1.1 pluggy==1.2.0 pycodestyle==2.9.1 pyflakes==2.5.0 pytest==7.4.4 six==1.17.0 statistics==1.0.3.5 stevedore==3.5.2 tomli==2.0.1 typing_extensions==4.7.1 zipp==3.15.0
name: okonomiyaki channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.2.7 - docutils==0.20.1 - enum34==1.1.10 - exceptiongroup==1.2.2 - flake8==5.0.4 - haas==0.9.0 - importlib-metadata==4.2.0 - iniconfig==2.0.0 - mccabe==0.7.0 - mock==5.2.0 - packaging==24.0 - pbr==6.1.1 - pluggy==1.2.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pytest==7.4.4 - six==1.17.0 - statistics==1.0.3.5 - stevedore==3.5.2 - tomli==2.0.1 - typing-extensions==4.7.1 - zipp==3.15.0 prefix: /opt/conda/envs/okonomiyaki
[ "okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_all", "okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_current_linux", "okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_current_windows", "okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_darwin_platform", "okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_linux2_platform" ]
[]
[ "okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_epd_platform_from_string", "okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_guessed_epd_platform", "okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatform::test_short_names_consistency", "okonomiyaki/platforms/tests/test_epd_platform.py::TestEPDPlatformApplies::test_applies_rh", "okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_linux2_unsupported", "okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_solaris_unsupported", "okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_unsupported_processor", "okonomiyaki/platforms/tests/test_epd_platform.py::TestGuessEPDPlatform::test_guess_win32_platform" ]
[]
BSD License
68
806
[ "okonomiyaki/platforms/epd_platform.py", "okonomiyaki/platforms/platform.py" ]
ministryofjustice__salt-shaker-21
f7ab3acca99aa24b58d6d14f747c1d7b1daeac2c
2015-03-20 14:58:51
a7349bcd65608b0b2f18aadf3c181009b2d78398
diff --git a/shaker/helpers.py b/shaker/helpers.py index a04e149..8aa577f 100644 --- a/shaker/helpers.py +++ b/shaker/helpers.py @@ -2,6 +2,7 @@ import logging import json import requests import os +import re def get_valid_github_token(online_validation_enabled = False): """ @@ -97,3 +98,69 @@ def validate_github_access(response): logging.error("Unknown problem checking credentials: %s" % response_message) return valid_credentials + +def parse_metadata(metadata): + """ + Entry function to handle the metadata parsing workflow and return a metadata + object which is cleaned up + + Args: + metadata (dictionary): Keyed salt formula dependency information + + Returns: + parsed_metadata (dictionary): The original metadata parsed and cleaned up + """ + # Remove duplicates + parsed_metadata = resolve_metadata_duplicates(metadata) + return parsed_metadata + +def resolve_metadata_duplicates(metadata): + """ + Strip duplicates out of a metadata file. If we have no additional criteria, + simply take the first one. Or can resolve by latest version or preferred organisation + if required + + Args: + metadata (dictionary): Keyed salt formula dependency information + + Returns: + resolved_dependencies (dictionary): The original metadata stripped of duplicates + If the metadata could not be resolved then we return the original args version + """ + # Only start to make alterations if we have a valid metadata format + # Otherwise throw an exception + + # If metadata is not a dictionary or does not contain + # a dependencies field then throw an exception + if not (isinstance(metadata, type({}))): + raise TypeError("resolve_metadata_duplicates: Metadata is not a " + "dictionary but type '%s'" % (type(metadata))) + elif not ("dependencies" in metadata): + raise IndexError("resolve_metadata_duplicates: Metadata has " + "no key called 'dependencies'" + ) + # Count the duplicates we find + count_duplicates = 0 + + resolved_dependency_collection = {} + for dependency in metadata["dependencies"]: + # Filter out formula name + org, formula = dependency.split(':')[1].split('.git')[0].split('/') + + # Simply take the first formula found, ignore subsequent + # formulas with the same name even from different organisations + # Just warn, not erroring out + if formula not in resolved_dependency_collection: + resolved_dependency_collection[formula] = dependency + else: + # Do some sort of tag resolution + count_duplicates += 1 + logging.warning("resolve_metadata_duplicates: Skipping duplicate dependency %s" %(formula)) + + # Only alter the metadata if we need to + if count_duplicates > 0: + resolved_dependencies = resolved_dependency_collection.values() + metadata["dependencies"] = resolved_dependencies + + return metadata + diff --git a/shaker/resolve_deps.py b/shaker/resolve_deps.py index c7a205c..f8a7b45 100644 --- a/shaker/resolve_deps.py +++ b/shaker/resolve_deps.py @@ -131,7 +131,8 @@ def get_reqs(org_name, formula_name, constraint=None): # Check for successful access and any credential problems if helpers.validate_github_access(metadata): found_metadata = True - data = yaml.load(metadata.text) + # Read in the yaml metadata from body, stripping out duplicate entries + data = helpers.parse_metadata(yaml.load(metadata.text)) reqs = data['dependencies'] if 'dependencies' in data and data['dependencies'] else [] else: reqs = requests.get(req_url.format(org_name, formula_name,
Duplicates in metadata.yml We don't throw an error if some idiot (me) puts duplicate lines in metadata.yml
ministryofjustice/salt-shaker
diff --git a/tests/test_metadata_handling.py b/tests/test_metadata_handling.py new file mode 100644 index 0000000..7723861 --- /dev/null +++ b/tests/test_metadata_handling.py @@ -0,0 +1,67 @@ +import unittest +import yaml +from shaker import helpers +from nose.tools import raises + +class TestMetadataHandling(unittest.TestCase): + + # Sample metadata with duplicates + _sample_metadata_duplicates = { + "dependencies": [ + "[email protected]:test_organisation/test1-formula.git==v1.0.1", + "[email protected]:test_organisation/test1-formula.git==v1.0.2", + "[email protected]:test_organisation/test2-formula.git==v2.0.1", + "[email protected]:test_organisation/test3-formula.git==v3.0.1", + "[email protected]:test_organisation/test3-formula.git==v3.0.2" + ], + "entry": ["dummy"] + } + + _sample_metadata_no_duplicates = { + "dependencies": [ + "[email protected]:test_organisation/test1-formula.git==v1.0.1", + "[email protected]:test_organisation/test2-formula.git==v2.0.1", + "[email protected]:test_organisation/test3-formula.git==v3.0.1" + ], + "entry": ["dummy"] + } + + def test_resolve_metadata_duplicates(self): + """ + Check if we successfully remove duplicates from a sample metadata + """ + original_metadata = self._sample_metadata_duplicates + expected_metadata = self._sample_metadata_no_duplicates + resolved_metadata = helpers.resolve_metadata_duplicates(original_metadata) + + expected_metadata_dependencies = expected_metadata["dependencies"] + resolved_metadata_dependencies = resolved_metadata["dependencies"] + expected_metadata_entries = expected_metadata["entry"] + resolved_metadata_entries = resolved_metadata["entry"] + + # Test dependencies found + for expected_metadata_dependency in expected_metadata_dependencies: + self.assertTrue(expected_metadata_dependency in resolved_metadata_dependencies, + "test_resolve_metadata_duplicates: dependency '%s' not found in de-duplicated metadata" + % (expected_metadata_dependency)) + + # Test entry found + for expected_metadata_entry in expected_metadata_entries: + self.assertTrue(expected_metadata_entry in resolved_metadata_entries, + "test_resolve_metadata_duplicates: Entry '%s' not found in de-duplicated metadata" + % (expected_metadata_entry)) + + @raises(TypeError) + def test_resolve_metadata_duplicates_bad_metadata_object(self): + """ + Check if bad yaml metadata will throw up a TypeError. + """ + # Callable with bad metadata + helpers.resolve_metadata_duplicates("not-a-dictionary") + + @raises(IndexError) + def test_resolve_metadata_duplicates_metadata_missing_index(self): + """ + Check if metadata with a missing index will throw an error + """ + helpers.resolve_metadata_duplicates({})
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "responses", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y libgit2-dev libssh2-1-dev" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 pycparser==2.22 pygit2==1.15.1 pytest==8.3.5 PyYAML==6.0.2 requests==2.32.3 responses==0.25.7 -e git+https://github.com/ministryofjustice/salt-shaker.git@f7ab3acca99aa24b58d6d14f747c1d7b1daeac2c#egg=salt_shaker tomli==2.2.1 urllib3==2.3.0
name: salt-shaker channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pycparser==2.22 - pygit2==1.15.1 - pytest==8.3.5 - pyyaml==6.0.2 - requests==2.32.3 - responses==0.25.7 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/salt-shaker
[ "tests/test_metadata_handling.py::TestMetadataHandling::test_resolve_metadata_duplicates", "tests/test_metadata_handling.py::TestMetadataHandling::test_resolve_metadata_duplicates_bad_metadata_object", "tests/test_metadata_handling.py::TestMetadataHandling::test_resolve_metadata_duplicates_metadata_missing_index" ]
[]
[]
[]
null
69
866
[ "shaker/helpers.py", "shaker/resolve_deps.py" ]
ipython__ipython-8111
2af39462d92d3834d5780a87f44d5e6cee7ecb81
2015-03-21 23:44:47
ff02638008de8c90ca5f177e559efa048a2557a0
diff --git a/IPython/config/application.py b/IPython/config/application.py index ef97162b3..264d3793a 100644 --- a/IPython/config/application.py +++ b/IPython/config/application.py @@ -159,7 +159,7 @@ def _log_level_changed(self, name, old, new): help="The date format used by logging formatters for %(asctime)s" ) def _log_datefmt_changed(self, name, old, new): - self._log_format_changed() + self._log_format_changed('log_format', self.log_format, self.log_format) log_format = Unicode("[%(name)s]%(highlevel)s %(message)s", config=True, help="The Logging format template",
`_log_format_changed()` missing 3 required positional arguments In `IPython.config.application`, the `_log_datefmt_changed` handler calls `_log_format_changed` but does not pass it the required arguments. My guess would be that this is the correct implementation: ``` def _log_datefmt_changed(self, name, old, new): self._log_format_changed(name, self.log_format, self.log_format) ``` However I am not really sure what the `name` parameter is for, so I might be wrong.
ipython/ipython
diff --git a/IPython/config/tests/test_application.py b/IPython/config/tests/test_application.py index a03d548c2..5da6a1306 100644 --- a/IPython/config/tests/test_application.py +++ b/IPython/config/tests/test_application.py @@ -80,6 +80,7 @@ def test_log(self): # trigger reconstruction of the log formatter app.log.handlers = [handler] app.log_format = "%(message)s" + app.log_datefmt = "%Y-%m-%d %H:%M" app.log.info("hello") nt.assert_in("hello", stream.getvalue())
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
3.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 execnet==1.9.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/ipython/ipython.git@2af39462d92d3834d5780a87f44d5e6cee7ecb81#egg=ipython nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 pytest-asyncio==0.16.0 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-xdist==3.0.2 requests==2.27.1 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 zipp==3.6.0
name: ipython channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - coverage==6.2 - execnet==1.9.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-asyncio==0.16.0 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-xdist==3.0.2 - requests==2.27.1 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/ipython
[ "IPython/config/tests/test_application.py::TestApplication::test_log" ]
[]
[ "IPython/config/tests/test_application.py::TestApplication::test_aliases", "IPython/config/tests/test_application.py::TestApplication::test_basic", "IPython/config/tests/test_application.py::TestApplication::test_config", "IPython/config/tests/test_application.py::TestApplication::test_config_propagation", "IPython/config/tests/test_application.py::TestApplication::test_extra_args", "IPython/config/tests/test_application.py::TestApplication::test_flag_clobber", "IPython/config/tests/test_application.py::TestApplication::test_flags", "IPython/config/tests/test_application.py::TestApplication::test_flatten_aliases", "IPython/config/tests/test_application.py::TestApplication::test_flatten_flags", "IPython/config/tests/test_application.py::TestApplication::test_multi_file", "IPython/config/tests/test_application.py::TestApplication::test_unicode_argv" ]
[]
BSD 3-Clause "New" or "Revised" License
71
176
[ "IPython/config/application.py" ]
CleanCut__green-40
9450d48e8099b15e87ddbd12243fb61db29fe4ba
2015-03-25 15:20:15
9450d48e8099b15e87ddbd12243fb61db29fe4ba
diff --git a/green/loader.py b/green/loader.py index f93d26c..50e5e91 100644 --- a/green/loader.py +++ b/green/loader.py @@ -121,11 +121,21 @@ def findDottedModuleAndParentDir(file_path): return (dotted_module, parent_dir) +def isNoseDisabledCase(test_case_class, attrname): + test_func = getattr(test_case_class, attrname) + nose_enabled = getattr(test_func, "__test__", None) + + if nose_enabled is False: + return True + else: + return False + def loadFromTestCase(test_case_class): debug("Examining test case {}".format(test_case_class.__name__), 3) test_case_names = list(filter( lambda attrname: (attrname.startswith('test') and - callable(getattr(test_case_class, attrname))), + callable(getattr(test_case_class, attrname)) and + not isNoseDisabledCase(test_case_class, attrname)), dir(test_case_class))) debug("Test case names: {}".format(test_case_names)) test_case_names.sort(
Make green work with nose_parameterized Green doesn't work with `nose_parameterized` since it executes tests that `nose_parameterized` [marks](https://github.com/wolever/nose-parameterized/blob/master/nose_parameterized/parameterized.py#L232) as disabled using the nose-specific [`__test__`](https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py#L140) attribute This attribute is easy to detect, so we should prune any tests that have it set.
CleanCut/green
diff --git a/green/test/test_loader.py b/green/test/test_loader.py index 09f0b76..397844f 100644 --- a/green/test/test_loader.py +++ b/green/test/test_loader.py @@ -264,6 +264,17 @@ class TestLoadFromTestCase(unittest.TestCase): set(['test_method1', 'test_method2'])) + def test_nose_disabled_attribute(self): + "Tests disabled by nose generators dont get loaded" + class HasDisabled(unittest.TestCase): + def test_method(self): + pass + + test_method.__test__ = False + + suite = loader.loadFromTestCase(HasDisabled) + self.assertEqual(suite.countTestCases(), 0) + class TestLoadFromModuleFilename(unittest.TestCase):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.4", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 -e git+https://github.com/CleanCut/green.git@9450d48e8099b15e87ddbd12243fb61db29fe4ba#egg=green importlib-metadata==4.8.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-termstyle==0.1.10 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: green channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-termstyle==0.1.10 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/green
[ "green/test/test_loader.py::TestLoadFromTestCase::test_nose_disabled_attribute" ]
[ "green/test/test_loader.py::TestCompletions::test_completionPartial", "green/test/test_loader.py::TestCompletions::test_completionPartialShort", "green/test/test_loader.py::TestLoadTargets::test_emptyDirAbsolute", "green/test/test_loader.py::TestLoadTargets::test_emptyDirRelative", "green/test/test_loader.py::TestLoadTargets::test_partiallyGoodName" ]
[ "green/test/test_loader.py::TestToProtoTestList::test_moduleImportFailure", "green/test/test_loader.py::TestToProtoTestList::test_moduleImportFailureIgnored", "green/test/test_loader.py::TestCompletions::test_completionBad", "green/test/test_loader.py::TestCompletions::test_completionDot", "green/test/test_loader.py::TestCompletions::test_completionEmpty", "green/test/test_loader.py::TestCompletions::test_completionExact", "green/test/test_loader.py::TestCompletions::test_completionIgnoresErrors", "green/test/test_loader.py::TestIsPackage::test_no", "green/test/test_loader.py::TestIsPackage::test_yes", "green/test/test_loader.py::TestDottedModule::test_bad_path", "green/test/test_loader.py::TestDottedModule::test_good_path", "green/test/test_loader.py::TestLoadFromTestCase::test_normal", "green/test/test_loader.py::TestLoadFromTestCase::test_runTest", "green/test/test_loader.py::TestLoadFromModuleFilename::test_skipped_module", "green/test/test_loader.py::TestDiscover::test_bad_input", "green/test/test_loader.py::TestLoadTargets::test_BigDirWithAbsoluteImports", "green/test/test_loader.py::TestLoadTargets::test_DirWithInit", "green/test/test_loader.py::TestLoadTargets::test_DottedName", "green/test/test_loader.py::TestLoadTargets::test_DottedNamePackageFromPath", "green/test/test_loader.py::TestLoadTargets::test_MalformedModuleByName", "green/test/test_loader.py::TestLoadTargets::test_ModuleByName", "green/test/test_loader.py::TestLoadTargets::test_duplicate_targets", "green/test/test_loader.py::TestLoadTargets::test_emptyDirDot", "green/test/test_loader.py::TestLoadTargets::test_explicit_filename_error", "green/test/test_loader.py::TestLoadTargets::test_multiple_targets", "green/test/test_loader.py::TestLoadTargets::test_relativeDotDir" ]
[]
MIT License
74
270
[ "green/loader.py" ]
eadhost__eadator-2
9ca6058a79729250f0c4399ac54e48d1543017c3
2015-03-26 06:44:18
9ca6058a79729250f0c4399ac54e48d1543017c3
diff --git a/eadator/eadator.py b/eadator/eadator.py index d1734ea..6a0c32e 100755 --- a/eadator/eadator.py +++ b/eadator/eadator.py @@ -16,14 +16,20 @@ def main(argv=None): type=argparse.FileType('r')) parser.add_argument('--dtd', required=False, ) parser.add_argument('--xsd', required=False, ) + parser.add_argument('--count', action='store_true' ) if argv is None: argv = parser.parse_args() - message, valid = validate(argv.eadfile[0], argv.dtd, argv.xsd) + message, valid, error_count = validate(argv.eadfile[0], argv.dtd, argv.xsd) if not valid: pp(message) + + if argv.count: + print("Error count : %d" % error_count) + + if not valid: exit(1) def validate(eadfile, dtd=None, xsd=None): @@ -48,12 +54,14 @@ def validate(eadfile, dtd=None, xsd=None): validator = etree.XMLSchema(etree.parse(xsd)) message = None + error_count = 0 valid = validator.validate(eadfile) if not valid: message = validator.error_log + error_count = len(message) - return message, valid + return message, valid, error_count # main() idiom for importing into REPL for debugging
Add the number of errors Hello, Could you add the number of errors at the end of the list of errors? It could be useful for verify if a modification adds or deletes an error. Thanks.
eadhost/eadator
diff --git a/tests/test_eadator.py b/tests/test_eadator.py index a90571d..68d55d9 100755 --- a/tests/test_eadator.py +++ b/tests/test_eadator.py @@ -17,17 +17,32 @@ class TestEadator(unittest.TestCase): type=argparse.FileType('r')) parser.add_argument('--dtd', default="%s/ents/ead.dtd" % lib_folder, required=False, ) parser.add_argument('--xsd', default="%s/ents/ead.xsd" % lib_folder, required=False, ) + parser.add_argument('--count', action='store_true' ) # test valid instances eadator.main(parser.parse_args([os.path.join(cmd_folder,'test-dtd-valid.xml')])) eadator.main(parser.parse_args([os.path.join(cmd_folder,'test-xsd-valid.xml')])) - eadator.validate(os.path.join(cmd_folder,'test-dtd-valid.xml')) - eadator.validate(os.path.join(cmd_folder,'test-xsd-valid.xml')) + + message, valid, error_count = eadator.validate(os.path.join(cmd_folder,'test-dtd-valid.xml')) + self.assertTrue(valid) + self.assertEqual(0,error_count) + + message, valid, error_count = eadator.validate(os.path.join(cmd_folder,'test-xsd-valid.xml')) + self.assertTrue(valid) + self.assertEqual(0,error_count) # test invalid instances self.assertRaises(SystemExit, eadator.main, parser.parse_args([os.path.join(cmd_folder,'test-dtd-invalid.xml')])) self.assertRaises(SystemExit, eadator.main, parser.parse_args([os.path.join(cmd_folder,'test-dtd-invalid.xml')])) + message, valid, error_count = eadator.validate(os.path.join(cmd_folder,'test-dtd-invalid.xml')) + self.assertFalse(valid) + self.assertEqual(1,error_count) + + message, valid, error_count = eadator.validate(os.path.join(cmd_folder,'test-xsd-invalid.xml')) + self.assertFalse(valid) + self.assertEqual(1,error_count) + if __name__ == '__main__': unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 1 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y libxml2-dev libxslt-dev" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/eadhost/eadator.git@9ca6058a79729250f0c4399ac54e48d1543017c3#egg=eadator exceptiongroup==1.2.2 iniconfig==2.1.0 lxml==5.3.1 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1
name: eadator channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - lxml==5.3.1 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/eadator
[ "tests/test_eadator.py::TestEadator::test_eadator" ]
[]
[]
[]
BSD License
75
362
[ "eadator/eadator.py" ]
mkdocs__mkdocs-395
88bb485ee4bd863f1cbfed6a786ef995cc844929
2015-04-02 19:29:19
bfc393ce2dd31d0fea2be3a5b0fec20ed361bfe0
diff --git a/mkdocs/nav.py b/mkdocs/nav.py index c8257e12..932399b4 100644 --- a/mkdocs/nav.py +++ b/mkdocs/nav.py @@ -209,14 +209,17 @@ def _generate_site_navigation(pages_config, url_context, use_directory_urls=True ) raise exceptions.ConfigurationError(msg) + # If both the title and child_title are None, then we + # have just been given a path. If that path contains a / + # then lets automatically nest it. + if title is None and child_title is None and os.path.sep in path: + filename = path.split(os.path.sep)[-1] + child_title = filename_to_title(filename) + if title is None: filename = path.split(os.path.sep)[0] title = filename_to_title(filename) - if child_title is None and os.path.sep in path: - filename = path.split(os.path.sep)[-1] - child_title = filename_to_title(filename) - url = utils.get_url_path(path, use_directory_urls) if not child_title:
Title is used as a section if file is in subdirectory Assuming I have a file at `research/stats.md` and a config line: ``` pages: - ["research/stats.md", "Stats about Our Collection"] ``` I would assume that it would generate a top-level nav item titled "Stats about Our Collection". In reality, it generates a section **Stats about Our Collection** with a sub-item titled **stats**. I'm 90% sure this has to do with the logic in [nav.py](https://github.com/mkdocs/mkdocs/blob/master/mkdocs/nav.py#L212-L218) around `child_titles`.
mkdocs/mkdocs
diff --git a/mkdocs/tests/nav_tests.py b/mkdocs/tests/nav_tests.py index 7013a66e..b6876f35 100644 --- a/mkdocs/tests/nav_tests.py +++ b/mkdocs/tests/nav_tests.py @@ -63,6 +63,39 @@ class SiteNavigationTests(unittest.TestCase): self.assertEqual(len(site_navigation.nav_items), 3) self.assertEqual(len(site_navigation.pages), 6) + def test_nested_ungrouped(self): + pages = [ + ('index.md', 'Home'), + ('about/contact.md', 'Contact'), + ('about/sub/license.md', 'License Title') + ] + expected = dedent(""" + Home - / + Contact - /about/contact/ + License Title - /about/sub/license/ + """) + site_navigation = nav.SiteNavigation(pages) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.nav_items), 3) + self.assertEqual(len(site_navigation.pages), 3) + + def test_nested_ungrouped_no_titles(self): + pages = [ + ('index.md',), + ('about/contact.md'), + ('about/sub/license.md') + ] + expected = dedent(""" + Home - / + About + Contact - /about/contact/ + License - /about/sub/license/ + """) + site_navigation = nav.SiteNavigation(pages) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.nav_items), 2) + self.assertEqual(len(site_navigation.pages), 3) + def test_walk_simple_toc(self): pages = [ ('index.md', 'Home'),
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "mock", "pytest" ], "pre_install": [ "pip install tox" ], "python": "3.4", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 distlib==0.3.9 filelock==3.4.1 ghp-import==2.1.0 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 Jinja2==3.0.3 Markdown==2.4.1 MarkupSafe==2.0.1 -e git+https://github.com/mkdocs/mkdocs.git@88bb485ee4bd863f1cbfed6a786ef995cc844929#egg=mkdocs mock==5.2.0 nose==1.3.7 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-dateutil==2.9.0.post0 PyYAML==6.0.1 six==1.17.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 virtualenv==20.17.1 watchdog==2.3.1 zipp==3.6.0
name: mkdocs channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - distlib==0.3.9 - filelock==3.4.1 - ghp-import==2.1.0 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jinja2==3.0.3 - markdown==2.4.1 - markupsafe==2.0.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-dateutil==2.9.0.post0 - pyyaml==6.0.1 - six==1.17.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - virtualenv==20.17.1 - watchdog==2.3.1 - zipp==3.6.0 prefix: /opt/conda/envs/mkdocs
[ "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped" ]
[]
[ "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_base_url", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_empty_toc_item", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation_windows", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_indented_toc", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_invalid_pages_config", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_relative_md_links_have_slash", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_simple_toc", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_empty_toc", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_indented_toc", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_simple_toc" ]
[]
BSD 2-Clause "Simplified" License
80
265
[ "mkdocs/nav.py" ]
mkdocs__mkdocs-402
74e60382b84b3af9969b30cc2cd9a98894d113f5
2015-04-03 08:53:55
bfc393ce2dd31d0fea2be3a5b0fec20ed361bfe0
diff --git a/mkdocs/compat.py b/mkdocs/compat.py index 49bd396a..518a4937 100644 --- a/mkdocs/compat.py +++ b/mkdocs/compat.py @@ -13,6 +13,7 @@ if PY2: httpserver = httpserver import SocketServer socketserver = SocketServer + from HTMLParser import HTMLParser import itertools zip = itertools.izip @@ -30,6 +31,7 @@ else: # PY3 httpserver = httpserver import socketserver socketserver = socketserver + from html.parser import HTMLParser zip = zip diff --git a/mkdocs/toc.py b/mkdocs/toc.py index 410aff5a..89627381 100644 --- a/mkdocs/toc.py +++ b/mkdocs/toc.py @@ -14,9 +14,7 @@ The steps we take to generate a table of contents are: * Parse table of contents HTML into the underlying data structure. """ -import re - -TOC_LINK_REGEX = re.compile('<a href=["]([^"]*)["]>([^<]*)</a>') +from mkdocs.compat import HTMLParser class TableOfContents(object): @@ -52,6 +50,32 @@ class AnchorLink(object): return ret +class TOCParser(HTMLParser): + + def __init__(self): + HTMLParser.__init__(self) + self.links = [] + + self.in_anchor = True + self.attrs = None + self.title = '' + + def handle_starttag(self, tag, attrs): + + if tag == 'a': + self.in_anchor = True + self.attrs = dict(attrs) + + def handle_endtag(self, tag): + if tag == 'a': + self.in_anchor = False + + def handle_data(self, data): + + if self.in_anchor: + self.title += data + + def _parse_html_table_of_contents(html): """ Given a table of contents string that has been automatically generated by @@ -63,9 +87,11 @@ def _parse_html_table_of_contents(html): parents = [] ret = [] for line in lines: - match = TOC_LINK_REGEX.search(line) - if match: - href, title = match.groups() + parser = TOCParser() + parser.feed(line) + if parser.title: + href = parser.attrs['href'] + title = parser.title nav = AnchorLink(title, href) # Add the item to its parent if required. If it is a topmost # item then instead append it to our return value.
Not all headers are automatically linked I have an API reference site for a project that's hosted on ReadTheDocs using mkdocs as the documentation engine. Headers that contain things like `<code>` blocks aren't linked, while all others seem to be. I can reproduce this locally with a plain mkdocs install using the RTD theme. Here's an example: http://carbon.lpghatguy.com/en/latest/Classes/Collections.Tuple/ All three of the methods in that page should be automatically linked in the sidebar navigation, but only the one without any fancy decoration is. All of them have been given valid HTML ids, so they're possible to link, they just aren't. The markdown for that page, which works around a couple RTD bugs and doesn't look that great, is here: https://raw.githubusercontent.com/lua-carbon/carbon/master/docs/Classes/Collections.Tuple.md
mkdocs/mkdocs
diff --git a/mkdocs/tests/toc_tests.py b/mkdocs/tests/toc_tests.py index 03ab9cd0..b0bdea11 100644 --- a/mkdocs/tests/toc_tests.py +++ b/mkdocs/tests/toc_tests.py @@ -29,6 +29,20 @@ class TableOfContentsTests(unittest.TestCase): toc = self.markdown_to_toc(md) self.assertEqual(str(toc).strip(), expected) + def test_indented_toc_html(self): + md = dedent(""" + # Heading 1 + ## <code>Heading</code> 2 + ## Heading 3 + """) + expected = dedent(""" + Heading 1 - #heading-1 + Heading 2 - #heading-2 + Heading 3 - #heading-3 + """) + toc = self.markdown_to_toc(md) + self.assertEqual(str(toc).strip(), expected) + def test_flat_toc(self): md = dedent(""" # Heading 1
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
0.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": null, "python": "3.7", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi coverage==7.2.7 exceptiongroup==1.2.2 ghp-import==2.1.0 importlib-metadata==6.7.0 iniconfig==2.0.0 Jinja2==3.1.6 Markdown==2.4.1 MarkupSafe==2.1.5 -e git+https://github.com/mkdocs/mkdocs.git@74e60382b84b3af9969b30cc2cd9a98894d113f5#egg=mkdocs packaging==24.0 pluggy==1.2.0 pytest==7.4.4 pytest-cov==4.1.0 python-dateutil==2.9.0.post0 PyYAML==6.0.1 six==1.17.0 tomli==2.0.1 typing_extensions==4.7.1 watchdog==3.0.0 zipp==3.15.0
name: mkdocs channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.2.7 - exceptiongroup==1.2.2 - ghp-import==2.1.0 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - jinja2==3.1.6 - markdown==2.4.1 - markupsafe==2.1.5 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - pytest-cov==4.1.0 - python-dateutil==2.9.0.post0 - pyyaml==6.0.1 - six==1.17.0 - tomli==2.0.1 - typing-extensions==4.7.1 - watchdog==3.0.0 - zipp==3.15.0 prefix: /opt/conda/envs/mkdocs
[ "mkdocs/tests/toc_tests.py::TableOfContentsTests::test_indented_toc_html" ]
[]
[ "mkdocs/tests/toc_tests.py::TableOfContentsTests::test_flat_h2_toc", "mkdocs/tests/toc_tests.py::TableOfContentsTests::test_flat_toc", "mkdocs/tests/toc_tests.py::TableOfContentsTests::test_indented_toc", "mkdocs/tests/toc_tests.py::TableOfContentsTests::test_mixed_toc" ]
[]
BSD 2-Clause "Simplified" License
81
646
[ "mkdocs/compat.py", "mkdocs/toc.py" ]
mkdocs__mkdocs-443
74d3191e419b7cb79fe66f700119ead3365f70d0
2015-04-09 12:25:57
bfc393ce2dd31d0fea2be3a5b0fec20ed361bfe0
diff --git a/mkdocs/main.py b/mkdocs/main.py index d73f9091..8b9a9412 100755 --- a/mkdocs/main.py +++ b/mkdocs/main.py @@ -55,7 +55,7 @@ def main(cmd, args, options=None): build(config, clean_site_dir=clean_site_dir) gh_deploy(config) elif cmd == 'new': - new(args, options) + new(args) else: print('MkDocs (version {0})'.format(__version__)) print('mkdocs [help|new|build|serve|gh-deploy|json] {options}') diff --git a/mkdocs/new.py b/mkdocs/new.py index 88531757..af969670 100644 --- a/mkdocs/new.py +++ b/mkdocs/new.py @@ -1,10 +1,13 @@ # coding: utf-8 from __future__ import print_function + import os from io import open -config_text = 'site_name: My Docs\n' -index_text = """# Welcome to MkDocs +from mkdocs import compat + +config_text = compat.unicode('site_name: My Docs\n') +index_text = compat.unicode("""# Welcome to MkDocs For full documentation visit [mkdocs.org](http://mkdocs.org). @@ -21,10 +24,11 @@ For full documentation visit [mkdocs.org](http://mkdocs.org). docs/ index.md # The documentation homepage. ... # Other markdown pages, images and other files. -""" +""") + +def new(args): -def new(args, options): if len(args) != 1: print("Usage 'mkdocs new [directory-name]'") return
`mkdocs new` broken under python2 current master, python 2.7.9 virtualenv only top directory and mkdocs.yml created, no docs dir or index.md ``` (karasu)[lashni@orphan src]$ mkdocs new karasu Creating project directory: karasu Writing config file: karasu/mkdocs.yml Traceback (most recent call last): File "/home/lashni/dev/karasu/bin/mkdocs", line 9, in <module> load_entry_point('mkdocs==0.11.1', 'console_scripts', 'mkdocs')() File "/home/lashni/dev/karasu/src/mkdocs/mkdocs/main.py", line 74, in run_main main(cmd, args=sys.argv[2:], options=dict(opts)) File "/home/lashni/dev/karasu/src/mkdocs/mkdocs/main.py", line 58, in main new(args, options) File "/home/lashni/dev/karasu/src/mkdocs/mkdocs/new.py", line 47, in new open(config_path, 'w', encoding='utf-8').write(config_text) TypeError: must be unicode, not str ``` current master, python 3.4.3 virtualenv, files/dirs created successfully ``` (test)[lashni@orphan src]$ mkdocs new karasu Creating project directory: karasu Writing config file: karasu/mkdocs.yml Writing initial docs: karasu/docs/index.md ```
mkdocs/mkdocs
diff --git a/mkdocs/tests/new_tests.py b/mkdocs/tests/new_tests.py new file mode 100644 index 00000000..e54fcb58 --- /dev/null +++ b/mkdocs/tests/new_tests.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# coding: utf-8 + +import tempfile +import unittest +import os + +from mkdocs import new + + +class NewTests(unittest.TestCase): + + def test_new(self): + + tempdir = tempfile.mkdtemp() + os.chdir(tempdir) + + new.new(["myproject", ]) + + expected_paths = [ + os.path.join(tempdir, "myproject"), + os.path.join(tempdir, "myproject", "mkdocs.yml"), + os.path.join(tempdir, "myproject", "docs"), + os.path.join(tempdir, "myproject", "docs", "index.md"), + ] + + for expected_path in expected_paths: + self.assertTrue(os.path.exists(expected_path))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
0.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 execnet==2.1.1 ghp-import==2.1.0 importlib_metadata==8.6.1 iniconfig==2.1.0 Jinja2==3.1.6 Markdown==3.7 MarkupSafe==3.0.2 -e git+https://github.com/mkdocs/mkdocs.git@74d3191e419b7cb79fe66f700119ead3365f70d0#egg=mkdocs packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 python-dateutil==2.9.0.post0 PyYAML==6.0.2 six==1.17.0 tomli==2.2.1 typing_extensions==4.13.0 watchdog==6.0.0 zipp==3.21.0
name: mkdocs channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - ghp-import==2.1.0 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jinja2==3.1.6 - markdown==3.7 - markupsafe==3.0.2 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - six==1.17.0 - tomli==2.2.1 - typing-extensions==4.13.0 - watchdog==6.0.0 - zipp==3.21.0 prefix: /opt/conda/envs/mkdocs
[ "mkdocs/tests/new_tests.py::NewTests::test_new" ]
[]
[]
[]
BSD 2-Clause "Simplified" License
86
422
[ "mkdocs/main.py", "mkdocs/new.py" ]
Pylons__webob-192
643ac0afc561165575a999d7458daa2bc5b0a2c1
2015-04-11 16:22:54
9b79f5f913fb1f07c68102a2279ed757a2a9abf6
diff --git a/webob/request.py b/webob/request.py index 01c170f..8269ac5 100644 --- a/webob/request.py +++ b/webob/request.py @@ -785,8 +785,10 @@ class BaseRequest(object): return NoVars('Not an HTML form submission (Content-Type: %s)' % content_type) self._check_charset() - if self.is_body_seekable: - self.body_file_raw.seek(0) + + self.make_body_seekable() + self.body_file_raw.seek(0) + fs_environ = env.copy() # FieldStorage assumes a missing CONTENT_LENGTH, but a # default of 0 is better: @@ -806,11 +808,6 @@ class BaseRequest(object): keep_blank_values=True) vars = MultiDict.from_fieldstorage(fs) - - #ctype = self.content_type or 'application/x-www-form-urlencoded' - ctype = self._content_type_raw or 'application/x-www-form-urlencoded' - f = FakeCGIBody(vars, ctype) - self.body_file = io.BufferedReader(f) env['webob._parsed_post_vars'] = (vars, self.body_file_raw) return vars
Accessing request.POST modifyed body I have a request which is POSTing JSON data, but some clients do not send along a `Content-Type` header. When this happens accessing `request.POST` will mangle the request body. Here is an example: ```python (Pdb) p request.content_type '' (Pdb) p request.body '{"password": "last centurion", "email": "[email protected]"}' (Pdb) p request.POST MultiDict([('{"password": "last centurion", "email": "[email protected]"}', '******')]) (Pdb) p request.body '%7B%22password%22%3A+%22last+centurion%22%2C+%22email%22%3A+%22rory%40wiggy.net%22%7D=' ```
Pylons/webob
diff --git a/tests/test_request.py b/tests/test_request.py index ebe5daf..f325bb9 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -512,6 +512,21 @@ class TestRequestCommon(unittest.TestCase): result = req.POST self.assertEqual(result['var1'], 'value1') + def test_POST_json_no_content_type(self): + data = b'{"password": "last centurion", "email": "[email protected]"}' + INPUT = BytesIO(data) + environ = {'wsgi.input': INPUT, + 'REQUEST_METHOD': 'POST', + 'CONTENT_LENGTH':len(data), + 'webob.is_body_seekable': True, + } + req = self._makeOne(environ) + r_1 = req.body + r_2 = req.POST + r_3 = req.body + self.assertEqual(r_1, b'{"password": "last centurion", "email": "[email protected]"}') + self.assertEqual(r_3, b'{"password": "last centurion", "email": "[email protected]"}') + def test_PUT_bad_content_type(self): from webob.multidict import NoVars data = b'input' @@ -2980,14 +2995,10 @@ class TestRequest_functional(unittest.TestCase): content_type='multipart/form-data; boundary=boundary', POST=_cgi_escaping_body ) - f0 = req.body_file_raw post1 = req.POST - f1 = req.body_file_raw - self.assertTrue(f1 is not f0) + self.assertTrue('webob._parsed_post_vars' in req.environ) post2 = req.POST - f2 = req.body_file_raw self.assertTrue(post1 is post2) - self.assertTrue(f1 is f2) def test_middleware_body(self): @@ -3391,6 +3402,11 @@ class FakeCGIBodyTests(unittest.TestCase): 'application/x-www-form-urlencoded') self.assertEqual(body.read(), b'bananas=bananas') + def test_readable(self): + from webob.request import FakeCGIBody + body = FakeCGIBody({'bananas': 'bananas'}, 'application/something') + self.assertTrue(body.readable()) + class Test_cgi_FieldStorage__repr__patch(unittest.TestCase): def _callFUT(self, fake):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.4", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work -e git+https://github.com/Pylons/webob.git@643ac0afc561165575a999d7458daa2bc5b0a2c1#egg=WebOb zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: webob channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/webob
[ "tests/test_request.py::TestRequestCommon::test_POST_json_no_content_type" ]
[]
[ "tests/test_request.py::TestRequestCommon::test_GET_reflects_query_string", "tests/test_request.py::TestRequestCommon::test_GET_updates_query_string", "tests/test_request.py::TestRequestCommon::test_POST_existing_cache_hit", "tests/test_request.py::TestRequestCommon::test_POST_missing_content_type", "tests/test_request.py::TestRequestCommon::test_POST_multipart", "tests/test_request.py::TestRequestCommon::test_POST_not_POST_or_PUT", "tests/test_request.py::TestRequestCommon::test_PUT_bad_content_type", "tests/test_request.py::TestRequestCommon::test_PUT_missing_content_type", "tests/test_request.py::TestRequestCommon::test__text_get_without_charset", "tests/test_request.py::TestRequestCommon::test__text_set_without_charset", "tests/test_request.py::TestRequestCommon::test_as_bytes_skip_body", "tests/test_request.py::TestRequestCommon::test_as_string_deprecated", "tests/test_request.py::TestRequestCommon::test_blank__ctype_as_kw", "tests/test_request.py::TestRequestCommon::test_blank__ctype_in_env", "tests/test_request.py::TestRequestCommon::test_blank__ctype_in_headers", "tests/test_request.py::TestRequestCommon::test_blank__method_subtitution", "tests/test_request.py::TestRequestCommon::test_blank__post_file_w_wrong_ctype", "tests/test_request.py::TestRequestCommon::test_blank__post_files", "tests/test_request.py::TestRequestCommon::test_blank__post_multipart", "tests/test_request.py::TestRequestCommon::test_blank__post_urlencoded", "tests/test_request.py::TestRequestCommon::test_blank__str_post_data_for_unsupported_ctype", "tests/test_request.py::TestRequestCommon::test_body_deleter_None", "tests/test_request.py::TestRequestCommon::test_body_file_deleter", "tests/test_request.py::TestRequestCommon::test_body_file_getter", "tests/test_request.py::TestRequestCommon::test_body_file_getter_cache", "tests/test_request.py::TestRequestCommon::test_body_file_getter_seekable", "tests/test_request.py::TestRequestCommon::test_body_file_getter_unreadable", "tests/test_request.py::TestRequestCommon::test_body_file_raw", "tests/test_request.py::TestRequestCommon::test_body_file_seekable_input_is_seekable", "tests/test_request.py::TestRequestCommon::test_body_file_seekable_input_not_seekable", "tests/test_request.py::TestRequestCommon::test_body_file_setter_non_bytes", "tests/test_request.py::TestRequestCommon::test_body_file_setter_w_bytes", "tests/test_request.py::TestRequestCommon::test_body_getter", "tests/test_request.py::TestRequestCommon::test_body_setter_None", "tests/test_request.py::TestRequestCommon::test_body_setter_non_string_raises", "tests/test_request.py::TestRequestCommon::test_body_setter_value", "tests/test_request.py::TestRequestCommon::test_cache_control_gets_cached", "tests/test_request.py::TestRequestCommon::test_cache_control_reflects_environ", "tests/test_request.py::TestRequestCommon::test_cache_control_set_dict", "tests/test_request.py::TestRequestCommon::test_cache_control_set_object", "tests/test_request.py::TestRequestCommon::test_cache_control_updates_environ", "tests/test_request.py::TestRequestCommon::test_call_application_calls_application", "tests/test_request.py::TestRequestCommon::test_call_application_closes_iterable_when_mixed_w_write_calls", "tests/test_request.py::TestRequestCommon::test_call_application_provides_write", "tests/test_request.py::TestRequestCommon::test_call_application_raises_exc_info", "tests/test_request.py::TestRequestCommon::test_call_application_returns_exc_info", "tests/test_request.py::TestRequestCommon::test_cookies_empty_environ", "tests/test_request.py::TestRequestCommon::test_cookies_is_mutable", "tests/test_request.py::TestRequestCommon::test_cookies_w_webob_parsed_cookies_matching_source", "tests/test_request.py::TestRequestCommon::test_cookies_w_webob_parsed_cookies_mismatched_source", "tests/test_request.py::TestRequestCommon::test_cookies_wo_webob_parsed_cookies", "tests/test_request.py::TestRequestCommon::test_copy_get", "tests/test_request.py::TestRequestCommon::test_ctor_environ_getter_raises_WTF", "tests/test_request.py::TestRequestCommon::test_ctor_w_environ", "tests/test_request.py::TestRequestCommon::test_ctor_w_non_utf8_charset", "tests/test_request.py::TestRequestCommon::test_ctor_wo_environ_raises_WTF", "tests/test_request.py::TestRequestCommon::test_from_bytes_extra_data", "tests/test_request.py::TestRequestCommon::test_from_string_deprecated", "tests/test_request.py::TestRequestCommon::test_is_body_readable_GET", "tests/test_request.py::TestRequestCommon::test_is_body_readable_PATCH", "tests/test_request.py::TestRequestCommon::test_is_body_readable_POST", "tests/test_request.py::TestRequestCommon::test_is_body_readable_special_flag", "tests/test_request.py::TestRequestCommon::test_is_body_readable_unknown_method_and_content_length", "tests/test_request.py::TestRequestCommon::test_json_body", "tests/test_request.py::TestRequestCommon::test_json_body_array", "tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_accept_encoding", "tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_modified_since", "tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_none_match", "tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_if_range", "tests/test_request.py::TestRequestCommon::test_remove_conditional_headers_range", "tests/test_request.py::TestRequestCommon::test_scheme", "tests/test_request.py::TestRequestCommon::test_set_cookies", "tests/test_request.py::TestRequestCommon::test_text_body", "tests/test_request.py::TestRequestCommon::test_urlargs_deleter_w_wsgiorg_key", "tests/test_request.py::TestRequestCommon::test_urlargs_deleter_w_wsgiorg_key_empty", "tests/test_request.py::TestRequestCommon::test_urlargs_deleter_wo_keys", "tests/test_request.py::TestRequestCommon::test_urlargs_getter_w_paste_key", "tests/test_request.py::TestRequestCommon::test_urlargs_getter_w_wsgiorg_key", "tests/test_request.py::TestRequestCommon::test_urlargs_getter_wo_keys", "tests/test_request.py::TestRequestCommon::test_urlargs_setter_w_paste_key", "tests/test_request.py::TestRequestCommon::test_urlargs_setter_w_wsgiorg_key", "tests/test_request.py::TestRequestCommon::test_urlargs_setter_wo_keys", "tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_paste_key", "tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_wsgiorg_key_empty_tuple", "tests/test_request.py::TestRequestCommon::test_urlvars_deleter_w_wsgiorg_key_non_empty_tuple", "tests/test_request.py::TestRequestCommon::test_urlvars_deleter_wo_keys", "tests/test_request.py::TestRequestCommon::test_urlvars_getter_w_paste_key", "tests/test_request.py::TestRequestCommon::test_urlvars_getter_w_wsgiorg_key", "tests/test_request.py::TestRequestCommon::test_urlvars_getter_wo_keys", "tests/test_request.py::TestRequestCommon::test_urlvars_setter_w_paste_key", "tests/test_request.py::TestRequestCommon::test_urlvars_setter_w_wsgiorg_key", "tests/test_request.py::TestRequestCommon::test_urlvars_setter_wo_keys", "tests/test_request.py::TestBaseRequest::test_application_url", "tests/test_request.py::TestBaseRequest::test_client_addr_no_xff", "tests/test_request.py::TestBaseRequest::test_client_addr_no_xff_no_remote_addr", "tests/test_request.py::TestBaseRequest::test_client_addr_prefers_xff", "tests/test_request.py::TestBaseRequest::test_client_addr_xff_multival", "tests/test_request.py::TestBaseRequest::test_client_addr_xff_singleval", "tests/test_request.py::TestBaseRequest::test_content_length_getter", "tests/test_request.py::TestBaseRequest::test_content_length_setter_w_str", "tests/test_request.py::TestBaseRequest::test_content_type_deleter_clears_environ_value", "tests/test_request.py::TestBaseRequest::test_content_type_deleter_no_environ_value", "tests/test_request.py::TestBaseRequest::test_content_type_getter_no_parameters", "tests/test_request.py::TestBaseRequest::test_content_type_getter_w_parameters", "tests/test_request.py::TestBaseRequest::test_content_type_setter_existing_paramter_no_new_paramter", "tests/test_request.py::TestBaseRequest::test_content_type_setter_w_None", "tests/test_request.py::TestBaseRequest::test_domain_nocolon", "tests/test_request.py::TestBaseRequest::test_domain_withcolon", "tests/test_request.py::TestBaseRequest::test_encget_doesnt_raises_with_default", "tests/test_request.py::TestBaseRequest::test_encget_no_encattr", "tests/test_request.py::TestBaseRequest::test_encget_raises_without_default", "tests/test_request.py::TestBaseRequest::test_encget_with_encattr", "tests/test_request.py::TestBaseRequest::test_encget_with_encattr_latin_1", "tests/test_request.py::TestBaseRequest::test_header_getter", "tests/test_request.py::TestBaseRequest::test_headers_getter", "tests/test_request.py::TestBaseRequest::test_headers_setter", "tests/test_request.py::TestBaseRequest::test_host_deleter_hit", "tests/test_request.py::TestBaseRequest::test_host_deleter_miss", "tests/test_request.py::TestBaseRequest::test_host_get", "tests/test_request.py::TestBaseRequest::test_host_get_w_no_http_host", "tests/test_request.py::TestBaseRequest::test_host_getter_w_HTTP_HOST", "tests/test_request.py::TestBaseRequest::test_host_getter_wo_HTTP_HOST", "tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_no_port", "tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_oddball_port", "tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_and_standard_port", "tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_no_port", "tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_oddball_port", "tests/test_request.py::TestBaseRequest::test_host_port_w_http_host_https_and_standard_port", "tests/test_request.py::TestBaseRequest::test_host_port_wo_http_host", "tests/test_request.py::TestBaseRequest::test_host_setter", "tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_no_port", "tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_oddball_port", "tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_and_standard_port", "tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_no_port", "tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_oddball_port", "tests/test_request.py::TestBaseRequest::test_host_url_w_http_host_https_and_standard_port", "tests/test_request.py::TestBaseRequest::test_host_url_wo_http_host", "tests/test_request.py::TestBaseRequest::test_http_version", "tests/test_request.py::TestBaseRequest::test_is_xhr_header_hit", "tests/test_request.py::TestBaseRequest::test_is_xhr_header_miss", "tests/test_request.py::TestBaseRequest::test_is_xhr_no_header", "tests/test_request.py::TestBaseRequest::test_json_body", "tests/test_request.py::TestBaseRequest::test_method", "tests/test_request.py::TestBaseRequest::test_no_headers_deleter", "tests/test_request.py::TestBaseRequest::test_path", "tests/test_request.py::TestBaseRequest::test_path_info", "tests/test_request.py::TestBaseRequest::test_path_info_peek_empty", "tests/test_request.py::TestBaseRequest::test_path_info_peek_just_leading_slash", "tests/test_request.py::TestBaseRequest::test_path_info_peek_non_empty", "tests/test_request.py::TestBaseRequest::test_path_info_pop_empty", "tests/test_request.py::TestBaseRequest::test_path_info_pop_just_leading_slash", "tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_no_pattern", "tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_w_pattern_hit", "tests/test_request.py::TestBaseRequest::test_path_info_pop_non_empty_w_pattern_miss", "tests/test_request.py::TestBaseRequest::test_path_info_pop_skips_empty_elements", "tests/test_request.py::TestBaseRequest::test_path_qs_no_qs", "tests/test_request.py::TestBaseRequest::test_path_qs_w_qs", "tests/test_request.py::TestBaseRequest::test_path_url", "tests/test_request.py::TestBaseRequest::test_query_string", "tests/test_request.py::TestBaseRequest::test_relative_url", "tests/test_request.py::TestBaseRequest::test_relative_url_to_app_false_other_w_leading_slash", "tests/test_request.py::TestBaseRequest::test_relative_url_to_app_false_other_wo_leading_slash", "tests/test_request.py::TestBaseRequest::test_relative_url_to_app_true_w_leading_slash", "tests/test_request.py::TestBaseRequest::test_relative_url_to_app_true_wo_leading_slash", "tests/test_request.py::TestBaseRequest::test_remote_addr", "tests/test_request.py::TestBaseRequest::test_remote_user", "tests/test_request.py::TestBaseRequest::test_script_name", "tests/test_request.py::TestBaseRequest::test_server_name", "tests/test_request.py::TestBaseRequest::test_server_port_getter", "tests/test_request.py::TestBaseRequest::test_server_port_setter_with_string", "tests/test_request.py::TestBaseRequest::test_upath_info", "tests/test_request.py::TestBaseRequest::test_upath_info_set_unicode", "tests/test_request.py::TestBaseRequest::test_url_no_qs", "tests/test_request.py::TestBaseRequest::test_url_w_qs", "tests/test_request.py::TestBaseRequest::test_uscript_name", "tests/test_request.py::TestLegacyRequest::test_application_url", "tests/test_request.py::TestLegacyRequest::test_client_addr_no_xff", "tests/test_request.py::TestLegacyRequest::test_client_addr_no_xff_no_remote_addr", "tests/test_request.py::TestLegacyRequest::test_client_addr_prefers_xff", "tests/test_request.py::TestLegacyRequest::test_client_addr_xff_multival", "tests/test_request.py::TestLegacyRequest::test_client_addr_xff_singleval", "tests/test_request.py::TestLegacyRequest::test_content_length_getter", "tests/test_request.py::TestLegacyRequest::test_content_length_setter_w_str", "tests/test_request.py::TestLegacyRequest::test_content_type_deleter_clears_environ_value", "tests/test_request.py::TestLegacyRequest::test_content_type_deleter_no_environ_value", "tests/test_request.py::TestLegacyRequest::test_content_type_getter_no_parameters", "tests/test_request.py::TestLegacyRequest::test_content_type_getter_w_parameters", "tests/test_request.py::TestLegacyRequest::test_content_type_setter_existing_paramter_no_new_paramter", "tests/test_request.py::TestLegacyRequest::test_content_type_setter_w_None", "tests/test_request.py::TestLegacyRequest::test_encget_doesnt_raises_with_default", "tests/test_request.py::TestLegacyRequest::test_encget_no_encattr", "tests/test_request.py::TestLegacyRequest::test_encget_raises_without_default", "tests/test_request.py::TestLegacyRequest::test_encget_with_encattr", "tests/test_request.py::TestLegacyRequest::test_header_getter", "tests/test_request.py::TestLegacyRequest::test_headers_getter", "tests/test_request.py::TestLegacyRequest::test_headers_setter", "tests/test_request.py::TestLegacyRequest::test_host_deleter_hit", "tests/test_request.py::TestLegacyRequest::test_host_deleter_miss", "tests/test_request.py::TestLegacyRequest::test_host_get_w_http_host", "tests/test_request.py::TestLegacyRequest::test_host_get_w_no_http_host", "tests/test_request.py::TestLegacyRequest::test_host_getter_w_HTTP_HOST", "tests/test_request.py::TestLegacyRequest::test_host_getter_wo_HTTP_HOST", "tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_no_port", "tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_oddball_port", "tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_and_standard_port", "tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_no_port", "tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_oddball_port", "tests/test_request.py::TestLegacyRequest::test_host_port_w_http_host_https_and_standard_port", "tests/test_request.py::TestLegacyRequest::test_host_port_wo_http_host", "tests/test_request.py::TestLegacyRequest::test_host_setter", "tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_no_port", "tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_oddball_port", "tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_and_standard_port", "tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_no_port", "tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_oddball_port", "tests/test_request.py::TestLegacyRequest::test_host_url_w_http_host_https_and_standard_port", "tests/test_request.py::TestLegacyRequest::test_host_url_wo_http_host", "tests/test_request.py::TestLegacyRequest::test_http_version", "tests/test_request.py::TestLegacyRequest::test_is_xhr_header_hit", "tests/test_request.py::TestLegacyRequest::test_is_xhr_header_miss", "tests/test_request.py::TestLegacyRequest::test_is_xhr_no_header", "tests/test_request.py::TestLegacyRequest::test_json_body", "tests/test_request.py::TestLegacyRequest::test_method", "tests/test_request.py::TestLegacyRequest::test_no_headers_deleter", "tests/test_request.py::TestLegacyRequest::test_path", "tests/test_request.py::TestLegacyRequest::test_path_info", "tests/test_request.py::TestLegacyRequest::test_path_info_peek_empty", "tests/test_request.py::TestLegacyRequest::test_path_info_peek_just_leading_slash", "tests/test_request.py::TestLegacyRequest::test_path_info_peek_non_empty", "tests/test_request.py::TestLegacyRequest::test_path_info_pop_empty", "tests/test_request.py::TestLegacyRequest::test_path_info_pop_just_leading_slash", "tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_no_pattern", "tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_w_pattern_hit", "tests/test_request.py::TestLegacyRequest::test_path_info_pop_non_empty_w_pattern_miss", "tests/test_request.py::TestLegacyRequest::test_path_info_pop_skips_empty_elements", "tests/test_request.py::TestLegacyRequest::test_path_qs_no_qs", "tests/test_request.py::TestLegacyRequest::test_path_qs_w_qs", "tests/test_request.py::TestLegacyRequest::test_path_url", "tests/test_request.py::TestLegacyRequest::test_query_string", "tests/test_request.py::TestLegacyRequest::test_relative_url", "tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_false_other_w_leading_slash", "tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_false_other_wo_leading_slash", "tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_true_w_leading_slash", "tests/test_request.py::TestLegacyRequest::test_relative_url_to_app_true_wo_leading_slash", "tests/test_request.py::TestLegacyRequest::test_remote_addr", "tests/test_request.py::TestLegacyRequest::test_remote_user", "tests/test_request.py::TestLegacyRequest::test_script_name", "tests/test_request.py::TestLegacyRequest::test_server_name", "tests/test_request.py::TestLegacyRequest::test_server_port_getter", "tests/test_request.py::TestLegacyRequest::test_server_port_setter_with_string", "tests/test_request.py::TestLegacyRequest::test_upath_info", "tests/test_request.py::TestLegacyRequest::test_upath_info_set_unicode", "tests/test_request.py::TestLegacyRequest::test_url_no_qs", "tests/test_request.py::TestLegacyRequest::test_url_w_qs", "tests/test_request.py::TestLegacyRequest::test_uscript_name", "tests/test_request.py::TestRequestConstructorWarnings::test_ctor_w_decode_param_names", "tests/test_request.py::TestRequestConstructorWarnings::test_ctor_w_unicode_errors", "tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_del", "tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_del_missing", "tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_get", "tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_get_missing", "tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_set", "tests/test_request.py::TestRequestWithAdhocAttr::test_adhoc_attrs_set_nonadhoc", "tests/test_request.py::TestRequest_functional::test_accept_best_match", "tests/test_request.py::TestRequest_functional::test_as_bytes", "tests/test_request.py::TestRequest_functional::test_as_text", "tests/test_request.py::TestRequest_functional::test_authorization", "tests/test_request.py::TestRequest_functional::test_bad_cookie", "tests/test_request.py::TestRequest_functional::test_blank", "tests/test_request.py::TestRequest_functional::test_body_file_noseek", "tests/test_request.py::TestRequest_functional::test_body_file_seekable", "tests/test_request.py::TestRequest_functional::test_body_property", "tests/test_request.py::TestRequest_functional::test_broken_clen_header", "tests/test_request.py::TestRequest_functional::test_broken_seek", "tests/test_request.py::TestRequest_functional::test_call_WSGI_app", "tests/test_request.py::TestRequest_functional::test_cgi_escaping_fix", "tests/test_request.py::TestRequest_functional::test_content_type_none", "tests/test_request.py::TestRequest_functional::test_conttype_set_del", "tests/test_request.py::TestRequest_functional::test_cookie_quoting", "tests/test_request.py::TestRequest_functional::test_copy_body", "tests/test_request.py::TestRequest_functional::test_env_keys", "tests/test_request.py::TestRequest_functional::test_from_bytes", "tests/test_request.py::TestRequest_functional::test_from_file_patch", "tests/test_request.py::TestRequest_functional::test_from_garbage_file", "tests/test_request.py::TestRequest_functional::test_from_mimeparse", "tests/test_request.py::TestRequest_functional::test_from_text", "tests/test_request.py::TestRequest_functional::test_get_response_catch_exc_info_true", "tests/test_request.py::TestRequest_functional::test_gets", "tests/test_request.py::TestRequest_functional::test_gets_with_query_string", "tests/test_request.py::TestRequest_functional::test_headers", "tests/test_request.py::TestRequest_functional::test_headers2", "tests/test_request.py::TestRequest_functional::test_host_property", "tests/test_request.py::TestRequest_functional::test_host_url", "tests/test_request.py::TestRequest_functional::test_language_parsing1", "tests/test_request.py::TestRequest_functional::test_language_parsing2", "tests/test_request.py::TestRequest_functional::test_language_parsing3", "tests/test_request.py::TestRequest_functional::test_middleware_body", "tests/test_request.py::TestRequest_functional::test_mime_parsing1", "tests/test_request.py::TestRequest_functional::test_mime_parsing2", "tests/test_request.py::TestRequest_functional::test_mime_parsing3", "tests/test_request.py::TestRequest_functional::test_nonstr_keys", "tests/test_request.py::TestRequest_functional::test_params", "tests/test_request.py::TestRequest_functional::test_path_info_p", "tests/test_request.py::TestRequest_functional::test_path_quoting", "tests/test_request.py::TestRequest_functional::test_post_does_not_reparse", "tests/test_request.py::TestRequest_functional::test_repr_invalid", "tests/test_request.py::TestRequest_functional::test_repr_nodefault", "tests/test_request.py::TestRequest_functional::test_req_kw_none_val", "tests/test_request.py::TestRequest_functional::test_request_init", "tests/test_request.py::TestRequest_functional::test_request_noenviron_param", "tests/test_request.py::TestRequest_functional::test_request_patch", "tests/test_request.py::TestRequest_functional::test_request_put", "tests/test_request.py::TestRequest_functional::test_request_query_and_POST_vars", "tests/test_request.py::TestRequest_functional::test_set_body", "tests/test_request.py::TestRequest_functional::test_unexpected_kw", "tests/test_request.py::TestRequest_functional::test_urlargs_property", "tests/test_request.py::TestRequest_functional::test_urlvars_property", "tests/test_request.py::FakeCGIBodyTests::test_encode_multipart_no_boundary", "tests/test_request.py::FakeCGIBodyTests::test_encode_multipart_value_type_options", "tests/test_request.py::FakeCGIBodyTests::test_fileno", "tests/test_request.py::FakeCGIBodyTests::test_iter", "tests/test_request.py::FakeCGIBodyTests::test_read_bad_content_type", "tests/test_request.py::FakeCGIBodyTests::test_read_urlencoded", "tests/test_request.py::FakeCGIBodyTests::test_readable", "tests/test_request.py::FakeCGIBodyTests::test_readline", "tests/test_request.py::FakeCGIBodyTests::test_repr", "tests/test_request.py::Test_cgi_FieldStorage__repr__patch::test_with_file", "tests/test_request.py::Test_cgi_FieldStorage__repr__patch::test_without_file", "tests/test_request.py::TestLimitedLengthFile::test_fileno", "tests/test_request.py::Test_environ_from_url::test_environ_from_url", "tests/test_request.py::Test_environ_from_url::test_environ_from_url_highorder_path_info", "tests/test_request.py::Test_environ_from_url::test_fileupload_mime_type_detection", "tests/test_request.py::TestRequestMultipart::test_multipart_with_charset" ]
[]
null
90
285
[ "webob/request.py" ]
softlayer__softlayer-python-523
200787d4c3bf37bc4e701caf6a52e24dd07d18a3
2015-04-14 01:39:04
200787d4c3bf37bc4e701caf6a52e24dd07d18a3
diff --git a/SoftLayer/CLI/call_api.py b/SoftLayer/CLI/call_api.py index 4d89cf74..e24e185d 100644 --- a/SoftLayer/CLI/call_api.py +++ b/SoftLayer/CLI/call_api.py @@ -9,21 +9,24 @@ @click.command('call', short_help="Call arbitrary API endpoints.") @click.argument('service') @click.argument('method') [email protected]('parameters', nargs=-1) @click.option('--id', '_id', help="Init parameter") @click.option('--mask', help="String-based object mask") @click.option('--limit', type=click.INT, help="Result limit") @click.option('--offset', type=click.INT, help="Result offset") @environment.pass_env -def cli(env, service, method, _id, mask, limit, offset): +def cli(env, service, method, parameters, _id, mask, limit, offset): """Call arbitrary API endpoints with the given SERVICE and METHOD. \b Examples: slcli call-api Account getObject slcli call-api Account getVirtualGuests --limit=10 --mask=id,hostname - slcli call-api Virtual_Guest getObject --id=2710344 + slcli call-api Virtual_Guest getObject --id=12345 + slcli call-api Metric_Tracking_Object getBandwidthData --id=1234 \\ + "2015-01-01 00:00:00" "2015-01-1 12:00:00" public """ - result = env.client.call(service, method, + result = env.client.call(service, method, *parameters, id=_id, mask=mask, limit=limit,
enableSnapshots method not working Hi, I'm trying to enable HOURLY/DAILY/WEEKLY snapshots using slcli as follows: slcli call-api Network_Storage enableSnapshots --id=XXXXXX --retentionCount=3 --scheduleType=HOURLY --minute=59 Error: no such option: --retentionCount According to the WSDL all these parameters are required. Thanks, Sadek
softlayer/softlayer-python
diff --git a/SoftLayer/tests/CLI/modules/call_api_tests.py b/SoftLayer/tests/CLI/modules/call_api_tests.py index b14cd9f1..2555b8e8 100644 --- a/SoftLayer/tests/CLI/modules/call_api_tests.py +++ b/SoftLayer/tests/CLI/modules/call_api_tests.py @@ -119,6 +119,17 @@ def test_list_table(self): :......:......:.......:.....:........: """) + def test_parameters(self): + mock = self.set_mock('SoftLayer_Service', 'method') + mock.return_value = {} + + result = self.run_command(['call-api', 'Service', 'method', + 'arg1', '1234']) + + self.assertEqual(result.exit_code, 0) + self.assert_called_with('SoftLayer_Service', 'method', + args=('arg1', '1234')) + class CallCliHelperTests(testing.TestCase):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
3.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "tools/test-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 distlib==0.3.9 docutils==0.18.1 filelock==3.4.1 fixtures==4.0.1 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 Jinja2==3.0.3 MarkupSafe==2.0.1 mock==5.2.0 nose==1.3.7 packaging==21.3 pbr==6.1.1 platformdirs==2.4.0 pluggy==1.0.0 prettytable==2.5.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytz==2025.2 requests==2.27.1 six==1.17.0 snowballstemmer==2.2.0 -e git+https://github.com/softlayer/softlayer-python.git@200787d4c3bf37bc4e701caf6a52e24dd07d18a3#egg=SoftLayer Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testtools==2.6.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 wcwidth==0.2.13 zipp==3.6.0
name: softlayer-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - distlib==0.3.9 - docutils==0.18.1 - filelock==3.4.1 - fixtures==4.0.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jinja2==3.0.3 - markupsafe==2.0.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pbr==6.1.1 - platformdirs==2.4.0 - pluggy==1.0.0 - prettytable==2.5.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytz==2025.2 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testtools==2.6.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/softlayer-python
[ "SoftLayer/tests/CLI/modules/call_api_tests.py::CallCliTests::test_parameters" ]
[]
[ "SoftLayer/tests/CLI/modules/call_api_tests.py::CallCliTests::test_list", "SoftLayer/tests/CLI/modules/call_api_tests.py::CallCliTests::test_list_table", "SoftLayer/tests/CLI/modules/call_api_tests.py::CallCliTests::test_object", "SoftLayer/tests/CLI/modules/call_api_tests.py::CallCliTests::test_object_nested", "SoftLayer/tests/CLI/modules/call_api_tests.py::CallCliTests::test_object_table", "SoftLayer/tests/CLI/modules/call_api_tests.py::CallCliTests::test_options", "SoftLayer/tests/CLI/modules/call_api_tests.py::CallCliHelperTests::test_format_api_dict", "SoftLayer/tests/CLI/modules/call_api_tests.py::CallCliHelperTests::test_format_api_list", "SoftLayer/tests/CLI/modules/call_api_tests.py::CallCliHelperTests::test_format_api_list_non_objects" ]
[]
MIT License
91
423
[ "SoftLayer/CLI/call_api.py" ]
softlayer__softlayer-python-524
200787d4c3bf37bc4e701caf6a52e24dd07d18a3
2015-04-14 18:26:39
200787d4c3bf37bc4e701caf6a52e24dd07d18a3
diff --git a/SoftLayer/CLI/server/detail.py b/SoftLayer/CLI/server/detail.py index 61eeb43e..943b694b 100644 --- a/SoftLayer/CLI/server/detail.py +++ b/SoftLayer/CLI/server/detail.py @@ -35,7 +35,7 @@ def cli(env, identifier, passwords, price): result = utils.NestedDict(result) table.add_row(['id', result['id']]) - table.add_row(['guid', result['globalIdentifier']] or formatting.blank()) + table.add_row(['guid', result['globalIdentifier'] or formatting.blank()]) table.add_row(['hostname', result['hostname']]) table.add_row(['domain', result['domain']]) table.add_row(['fqdn', result['fullyQualifiedDomainName']]) diff --git a/SoftLayer/managers/hardware.py b/SoftLayer/managers/hardware.py index 1a1e350f..70aea1ec 100644 --- a/SoftLayer/managers/hardware.py +++ b/SoftLayer/managers/hardware.py @@ -47,51 +47,22 @@ def cancel_hardware(self, hardware_id, reason='unneeded', comment='', :param string comment: An optional comment to include with the cancellation. """ - # Check to see if this is actually a pre-configured server (BMC). They - # require a different cancellation call. - server = self.get_hardware(hardware_id, - mask='id,bareMetalInstanceFlag') - - if server.get('bareMetalInstanceFlag'): - return self.cancel_metal(hardware_id, immediate) + # Get cancel reason reasons = self.get_cancellation_reasons() - cancel_reason = reasons['unneeded'] - - if reason in reasons: - cancel_reason = reasons[reason] - - # Arguments per SLDN: - # attachmentId - Hardware ID - # Reason - # content - Comment about the cancellation - # cancelAssociatedItems - # attachmentType - Only option is HARDWARE - return self.client['Ticket'].createCancelServerTicket(hardware_id, - cancel_reason, - comment, - True, - 'HARDWARE') - - def cancel_metal(self, hardware_id, immediate=False): - """Cancels the specified bare metal instance. - - :param int id: The ID of the bare metal instance to be cancelled. - :param bool immediate: If true, the bare metal instance will be - cancelled immediately. Otherwise, it will be - scheduled to cancel on the anniversary date. - """ + cancel_reason = reasons.get(reason, reasons['unneeded']) + hw_billing = self.get_hardware(hardware_id, mask='mask[id, billingItem.id]') + if 'billingItem' not in hw_billing: + raise SoftLayer.SoftLayerError( + "No billing item found for hardware") billing_id = hw_billing['billingItem']['id'] - billing_item = self.client['Billing_Item'] - - if immediate: - return billing_item.cancelService(id=billing_id) - else: - return billing_item.cancelServiceOnAnniversaryDate(id=billing_id) + return self.client.call('Billing_Item', 'cancelItem', + immediate, False, cancel_reason, comment, + id=billing_id) def list_hardware(self, tags=None, cpus=None, memory=None, hostname=None, domain=None, datacenter=None, nic_speed=None,
problem with hourly bare metal servers immediate cancelation in CLI and manager slcli server cancel --immediate <server id> does not produce an error, but cancels server on its monthly anniversary. The cause of the problem is "old" logic in cancel_hardware method of harware.py. In SL API 4.0 harware.py place_order now only supports the fast server provisioning package (see version 4 notes: #469), but cancel_hardware is still looking for a 'bareMetalInstanceFlag' and using Billing_Item cancelService. It should use Billing_Item cancelItem instead
softlayer/softlayer-python
diff --git a/SoftLayer/tests/managers/hardware_tests.py b/SoftLayer/tests/managers/hardware_tests.py index 283598c9..79aa5025 100644 --- a/SoftLayer/tests/managers/hardware_tests.py +++ b/SoftLayer/tests/managers/hardware_tests.py @@ -243,57 +243,53 @@ def test_place_order(self, create_dict): self.assert_called_with('SoftLayer_Product_Order', 'placeOrder', args=({'test': 1, 'verify': 1},)) - def test_cancel_metal_immediately(self): - - result = self.hardware.cancel_metal(6327, immediate=True) - - self.assertEqual(result, True) - self.assert_called_with('SoftLayer_Billing_Item', 'cancelService', - identifier=6327) - - def test_cancel_metal_on_anniversary(self): - - result = self.hardware.cancel_metal(6327, False) - - self.assertEqual(result, True) - self.assert_called_with('SoftLayer_Billing_Item', - 'cancelServiceOnAnniversaryDate', - identifier=6327) - def test_cancel_hardware_without_reason(self): mock = self.set_mock('SoftLayer_Hardware_Server', 'getObject') - mock.return_value = {'id': 987, 'bareMetalInstanceFlag': False} + mock.return_value = {'id': 987, 'billingItem': {'id': 1234}} result = self.hardware.cancel_hardware(987) - self.assertEqual(result, - fixtures.SoftLayer_Ticket.createCancelServerTicket) + self.assertEqual(result, True) reasons = self.hardware.get_cancellation_reasons() - args = (987, reasons['unneeded'], '', True, 'HARDWARE') - self.assert_called_with('SoftLayer_Ticket', 'createCancelServerTicket', + args = (False, False, reasons['unneeded'], '') + self.assert_called_with('SoftLayer_Billing_Item', 'cancelItem', + identifier=1234, args=args) def test_cancel_hardware_with_reason_and_comment(self): mock = self.set_mock('SoftLayer_Hardware_Server', 'getObject') - mock.return_value = {'id': 987, 'bareMetalInstanceFlag': False} + mock.return_value = {'id': 987, 'billingItem': {'id': 1234}} - result = self.hardware.cancel_hardware(987, 'sales', 'Test Comment') + result = self.hardware.cancel_hardware(6327, + reason='sales', + comment='Test Comment') - self.assertEqual(result, - fixtures.SoftLayer_Ticket.createCancelServerTicket) + self.assertEqual(result, True) reasons = self.hardware.get_cancellation_reasons() - args = (987, reasons['sales'], 'Test Comment', True, 'HARDWARE') - self.assert_called_with('SoftLayer_Ticket', 'createCancelServerTicket', + args = (False, False, reasons['sales'], 'Test Comment') + self.assert_called_with('SoftLayer_Billing_Item', 'cancelItem', + identifier=1234, args=args) - def test_cancel_hardware_on_bmc(self): + def test_cancel_hardware(self): result = self.hardware.cancel_hardware(6327) self.assertEqual(result, True) self.assert_called_with('SoftLayer_Billing_Item', - 'cancelServiceOnAnniversaryDate', - identifier=6327) + 'cancelItem', + identifier=6327, + args=(False, False, 'No longer needed', '')) + + def test_cancel_hardware_no_billing_item(self): + mock = self.set_mock('SoftLayer_Hardware_Server', 'getObject') + mock.return_value = {'id': 987} + + ex = self.assertRaises(SoftLayer.SoftLayerError, + self.hardware.cancel_hardware, + 6327) + self.assertEqual("No billing item found for hardware", + str(ex)) def test_change_port_speed_public(self): self.hardware.change_port_speed(2, True, 100)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
3.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "tools/test-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 distlib==0.3.9 docutils==0.18.1 filelock==3.4.1 fixtures==4.0.1 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 Jinja2==3.0.3 MarkupSafe==2.0.1 mock==5.2.0 nose==1.3.7 packaging==21.3 pbr==6.1.1 platformdirs==2.4.0 pluggy==1.0.0 prettytable==2.5.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytz==2025.2 requests==2.27.1 six==1.17.0 snowballstemmer==2.2.0 -e git+https://github.com/softlayer/softlayer-python.git@200787d4c3bf37bc4e701caf6a52e24dd07d18a3#egg=SoftLayer Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testtools==2.6.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 wcwidth==0.2.13 zipp==3.6.0
name: softlayer-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - distlib==0.3.9 - docutils==0.18.1 - filelock==3.4.1 - fixtures==4.0.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jinja2==3.0.3 - markupsafe==2.0.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pbr==6.1.1 - platformdirs==2.4.0 - pluggy==1.0.0 - prettytable==2.5.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytz==2025.2 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testtools==2.6.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/softlayer-python
[ "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_hardware", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_hardware_no_billing_item", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_hardware_with_reason_and_comment", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_hardware_without_reason" ]
[]
[ "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_change_port_speed_private", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_change_port_speed_public", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_edit", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_edit_blank", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_edit_meta", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_generate_create_dict", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_generate_create_dict_invalid_size", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_generate_create_dict_no_items", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_generate_create_dict_no_regions", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_create_options", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_create_options_package_missing", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_hardware", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_init_with_ordering_manager", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_list_hardware", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_list_hardware_with_filters", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_place_order", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_reload", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_rescue", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_resolve_ids_hostname", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_resolve_ids_ip", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_update_firmware", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_update_firmware_selective", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_verify_order", "SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_bandwidth_price_id_no_items", "SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_default_price_id_item_not_first", "SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_default_price_id_no_items", "SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_extra_price_id_no_items", "SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_os_price_id_no_items", "SoftLayer/tests/managers/hardware_tests.py::HardwareHelperTests::test_get_port_speed_price_id_no_items" ]
[]
MIT License
94
797
[ "SoftLayer/CLI/server/detail.py", "SoftLayer/managers/hardware.py" ]
falconry__falcon-505
9dc3d87259b8fc50abc638a42b20e1eaa04d0cbc
2015-04-15 12:55:19
6608a5f10aead236ae5345488813de805b85b064
diff --git a/falcon/request.py b/falcon/request.py index 0663c21..be8aabf 100644 --- a/falcon/request.py +++ b/falcon/request.py @@ -343,6 +343,9 @@ class Request(object): value = self.env['HTTP_RANGE'] if value.startswith('bytes='): value = value[6:] + else: + msg = "The value must be prefixed with 'bytes='" + raise HTTPInvalidHeader(msg, 'Range') except KeyError: return None
Make "bytes" prefix in Range header value required Currently, range header values without a "bytes" prefix are allowed. Change the code to always require a "bytes" prefix.
falconry/falcon
diff --git a/tests/test_req_vars.py b/tests/test_req_vars.py index 904d622..5ee1809 100644 --- a/tests/test_req_vars.py +++ b/tests/test_req_vars.py @@ -368,15 +368,15 @@ class TestReqVars(testing.TestBase): self.assertEqual(preferred_type, None) def test_range(self): - headers = {'Range': '10-'} + headers = {'Range': 'bytes=10-'} req = Request(testing.create_environ(headers=headers)) self.assertEqual(req.range, (10, -1)) - headers = {'Range': '10-20'} + headers = {'Range': 'bytes=10-20'} req = Request(testing.create_environ(headers=headers)) self.assertEqual(req.range, (10, 20)) - headers = {'Range': '-10240'} + headers = {'Range': 'bytes=-10240'} req = Request(testing.create_environ(headers=headers)) self.assertEqual(req.range, (-10240, -1)) @@ -392,62 +392,62 @@ class TestReqVars(testing.TestBase): self.assertIs(req.range, None) def test_range_invalid(self): - headers = {'Range': '10240'} + headers = {'Range': 'bytes=10240'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': '-'} + headers = {'Range': 'bytes=-'} expected_desc = ('The value provided for the Range header is ' 'invalid. The byte offsets are missing.') self._test_error_details(headers, 'range', falcon.HTTPInvalidHeader, 'Invalid header value', expected_desc) - headers = {'Range': '--'} + headers = {'Range': 'bytes=--'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': '-3-'} + headers = {'Range': 'bytes=-3-'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': '-3-4'} + headers = {'Range': 'bytes=-3-4'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': '3-3-4'} + headers = {'Range': 'bytes=3-3-4'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': '3-3-'} + headers = {'Range': 'bytes=3-3-'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': '3-3- '} + headers = {'Range': 'bytes=3-3- '} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'fizbit'} + headers = {'Range': 'bytes=fizbit'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'a-'} + headers = {'Range': 'bytes=a-'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'a-3'} + headers = {'Range': 'bytes=a-3'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': '-b'} + headers = {'Range': 'bytes=-b'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': '3-b'} + headers = {'Range': 'bytes=3-b'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'x-y'} + headers = {'Range': 'bytes=x-y'} expected_desc = ('The value provided for the Range header is ' 'invalid. It must be a byte range formatted ' 'according to RFC 2616.') @@ -463,6 +463,14 @@ class TestReqVars(testing.TestBase): falcon.HTTPInvalidHeader, 'Invalid header value', expected_desc) + headers = {'Range': '10-'} + expected_desc = ("The value provided for the Range " + "header is invalid. The value must be " + "prefixed with 'bytes='") + self._test_error_details(headers, 'range', + falcon.HTTPInvalidHeader, + 'Invalid header value', expected_desc) + def test_missing_attribute_header(self): req = Request(testing.create_environ()) self.assertEqual(req.range, None)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "coverage", "ddt", "pyyaml", "requests", "six", "testtools", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "tools/test-requires" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 ddt==1.7.2 exceptiongroup==1.2.2 -e git+https://github.com/falconry/falcon.git@9dc3d87259b8fc50abc638a42b20e1eaa04d0cbc#egg=falcon idna==3.10 iniconfig==2.1.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 python-mimeparse==2.0.0 PyYAML==6.0.2 requests==2.32.3 six==1.17.0 testtools==2.7.2 tomli==2.2.1 urllib3==2.3.0
name: falcon channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - ddt==1.7.2 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - python-mimeparse==2.0.0 - pyyaml==6.0.2 - requests==2.32.3 - six==1.17.0 - testtools==2.7.2 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/falcon
[ "tests/test_req_vars.py::TestReqVars::test_range_invalid" ]
[ "tests/test_req_vars.py::TestReqVars::test_client_accepts" ]
[ "tests/test_req_vars.py::TestReqVars::test_attribute_headers", "tests/test_req_vars.py::TestReqVars::test_bogus_content_length_nan", "tests/test_req_vars.py::TestReqVars::test_bogus_content_length_neg", "tests/test_req_vars.py::TestReqVars::test_client_accepts_bogus", "tests/test_req_vars.py::TestReqVars::test_client_accepts_props", "tests/test_req_vars.py::TestReqVars::test_client_prefers", "tests/test_req_vars.py::TestReqVars::test_content_length", "tests/test_req_vars.py::TestReqVars::test_content_length_method", "tests/test_req_vars.py::TestReqVars::test_content_type_method", "tests/test_req_vars.py::TestReqVars::test_date", "tests/test_req_vars.py::TestReqVars::test_date_invalid_1_Thu__04_Apr_2013", "tests/test_req_vars.py::TestReqVars::test_date_invalid_2_", "tests/test_req_vars.py::TestReqVars::test_date_missing", "tests/test_req_vars.py::TestReqVars::test_empty", "tests/test_req_vars.py::TestReqVars::test_empty_path", "tests/test_req_vars.py::TestReqVars::test_host", "tests/test_req_vars.py::TestReqVars::test_method", "tests/test_req_vars.py::TestReqVars::test_missing_attribute_header", "tests/test_req_vars.py::TestReqVars::test_missing_qs", "tests/test_req_vars.py::TestReqVars::test_range", "tests/test_req_vars.py::TestReqVars::test_reconstruct_url", "tests/test_req_vars.py::TestReqVars::test_relative_uri", "tests/test_req_vars.py::TestReqVars::test_subdomain", "tests/test_req_vars.py::TestReqVars::test_uri", "tests/test_req_vars.py::TestReqVars::test_uri_http_1_0", "tests/test_req_vars.py::TestReqVars::test_uri_https" ]
[]
Apache License 2.0
97
130
[ "falcon/request.py" ]
Pylons__webob-197
9b79f5f913fb1f07c68102a2279ed757a2a9abf6
2015-04-23 02:49:34
9b79f5f913fb1f07c68102a2279ed757a2a9abf6
diff --git a/webob/response.py b/webob/response.py index a164938..9579b7e 100644 --- a/webob/response.py +++ b/webob/response.py @@ -116,16 +116,13 @@ class Response(object): if 'charset' in kw: charset = kw.pop('charset') elif self.default_charset: - if (content_type - and 'charset=' not in content_type - and (content_type == 'text/html' - or content_type.startswith('text/') - or content_type.startswith('application/xml') - or content_type.startswith('application/json') - or (content_type.startswith('application/') - and (content_type.endswith('+xml') or content_type.endswith('+json'))))): - charset = self.default_charset - if content_type and charset: + if content_type and 'charset=' not in content_type: + if (content_type == 'text/html' + or content_type.startswith('text/') + or _is_xml(content_type) + or _is_json(content_type)): + charset = self.default_charset + if content_type and charset and not _is_json(content_type): content_type += '; charset=' + charset elif self._headerlist and charset: self.charset = charset @@ -1231,6 +1228,16 @@ class EmptyResponse(object): __next__ = next # py3 +def _is_json(content_type): + return (content_type.startswith('application/json') + or (content_type.startswith('application/') + and content_type.endswith('+json'))) + +def _is_xml(content_type): + return (content_type.startswith('application/xml') + or (content_type.startswith('application/') + and content_type.endswith('+xml'))) + def _request_uri(environ): """Like wsgiref.url.request_uri, except eliminates :80 ports
JSON content shouldn't need a UTF-8 on the content-type Fix this issue: https://github.com/Pylons/pyramid/issues/1611#issuecomment-93073442
Pylons/webob
diff --git a/tests/test_response.py b/tests/test_response.py index d9c1cd3..6425a22 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -104,6 +104,7 @@ def test_set_response_status_code_generic_reason(): assert res.status_code == 299 assert res.status == '299 Success' + def test_content_type(): r = Response() # default ctype and charset @@ -121,6 +122,21 @@ def test_init_content_type_w_charset(): v = 'text/plain;charset=ISO-8859-1' eq_(Response(content_type=v).headers['content-type'], v) +def test_init_adds_default_charset_when_not_json(): + content_type = 'text/plain' + expected = 'text/plain; charset=UTF-8' + eq_(Response(content_type=content_type).headers['content-type'], expected) + +def test_init_no_charset_when_json(): + content_type = 'application/json' + expected = content_type + eq_(Response(content_type=content_type).headers['content-type'], expected) + +def test_init_keeps_specified_charset_when_json(): + content_type = 'application/json;charset=ISO-8859-1' + expected = content_type + eq_(Response(content_type=content_type).headers['content-type'], expected) + def test_cookies(): res = Response()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "coverage", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work nose==1.3.7 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work -e git+https://github.com/Pylons/webob.git@9b79f5f913fb1f07c68102a2279ed757a2a9abf6#egg=WebOb
name: webob channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - nose==1.3.7 prefix: /opt/conda/envs/webob
[ "tests/test_response.py::test_init_no_charset_when_json" ]
[]
[ "tests/test_response.py::test_response", "tests/test_response.py::test_set_response_status_binary", "tests/test_response.py::test_set_response_status_str_no_reason", "tests/test_response.py::test_set_response_status_str_generic_reason", "tests/test_response.py::test_set_response_status_code", "tests/test_response.py::test_set_response_status_bad", "tests/test_response.py::test_set_response_status_code_generic_reason", "tests/test_response.py::test_content_type", "tests/test_response.py::test_init_content_type_w_charset", "tests/test_response.py::test_init_adds_default_charset_when_not_json", "tests/test_response.py::test_init_keeps_specified_charset_when_json", "tests/test_response.py::test_cookies", "tests/test_response.py::test_unicode_cookies_error_raised", "tests/test_response.py::test_unicode_cookies_warning_issued", "tests/test_response.py::test_http_only_cookie", "tests/test_response.py::test_headers", "tests/test_response.py::test_response_copy", "tests/test_response.py::test_response_copy_content_md5", "tests/test_response.py::test_HEAD_closes", "tests/test_response.py::test_HEAD_conditional_response_returns_empty_response", "tests/test_response.py::test_HEAD_conditional_response_range_empty_response", "tests/test_response.py::test_conditional_response_if_none_match_false", "tests/test_response.py::test_conditional_response_if_none_match_true", "tests/test_response.py::test_conditional_response_if_none_match_weak", "tests/test_response.py::test_conditional_response_if_modified_since_false", "tests/test_response.py::test_conditional_response_if_modified_since_true", "tests/test_response.py::test_conditional_response_range_not_satisfiable_response", "tests/test_response.py::test_HEAD_conditional_response_range_not_satisfiable_response", "tests/test_response.py::test_md5_etag", "tests/test_response.py::test_md5_etag_set_content_md5", "tests/test_response.py::test_decode_content_defaults_to_identity", "tests/test_response.py::test_decode_content_with_deflate", "tests/test_response.py::test_content_length", "tests/test_response.py::test_app_iter_range", "tests/test_response.py::test_app_iter_range_inner_method", "tests/test_response.py::test_content_type_in_headerlist", "tests/test_response.py::test_str_crlf", "tests/test_response.py::test_from_file", "tests/test_response.py::test_from_file2", "tests/test_response.py::test_from_text_file", "tests/test_response.py::test_from_file_w_leading_space_in_header", "tests/test_response.py::test_file_bad_header", "tests/test_response.py::test_from_file_not_unicode_headers", "tests/test_response.py::test_set_status", "tests/test_response.py::test_set_headerlist", "tests/test_response.py::test_request_uri_no_script_name", "tests/test_response.py::test_request_uri_https", "tests/test_response.py::test_app_iter_range_starts_after_iter_end", "tests/test_response.py::test_resp_write_app_iter_non_list", "tests/test_response.py::test_response_file_body_writelines", "tests/test_response.py::test_response_write_non_str", "tests/test_response.py::test_response_file_body_write_empty_app_iter", "tests/test_response.py::test_response_file_body_write_empty_body", "tests/test_response.py::test_response_file_body_close_not_implemented", "tests/test_response.py::test_response_file_body_repr", "tests/test_response.py::test_body_get_is_none", "tests/test_response.py::test_body_get_is_unicode_notverylong", "tests/test_response.py::test_body_get_is_unicode", "tests/test_response.py::test_body_set_not_unicode_or_str", "tests/test_response.py::test_body_set_unicode", "tests/test_response.py::test_body_set_under_body_doesnt_exist", "tests/test_response.py::test_body_del", "tests/test_response.py::test_text_get_no_charset", "tests/test_response.py::test_unicode_body", "tests/test_response.py::test_text_get_decode", "tests/test_response.py::test_text_set_no_charset", "tests/test_response.py::test_text_set_not_unicode", "tests/test_response.py::test_text_del", "tests/test_response.py::test_body_file_del", "tests/test_response.py::test_write_unicode", "tests/test_response.py::test_write_unicode_no_charset", "tests/test_response.py::test_write_text", "tests/test_response.py::test_app_iter_del", "tests/test_response.py::test_charset_set_no_content_type_header", "tests/test_response.py::test_charset_del_no_content_type_header", "tests/test_response.py::test_content_type_params_get_no_semicolon_in_content_type_header", "tests/test_response.py::test_content_type_params_get_semicolon_in_content_type_header", "tests/test_response.py::test_content_type_params_set_value_dict_empty", "tests/test_response.py::test_content_type_params_set_ok_param_quoting", "tests/test_response.py::test_set_cookie_overwrite", "tests/test_response.py::test_set_cookie_value_is_None", "tests/test_response.py::test_set_cookie_expires_is_None_and_max_age_is_int", "tests/test_response.py::test_set_cookie_expires_is_None_and_max_age_is_timedelta", "tests/test_response.py::test_set_cookie_expires_is_not_None_and_max_age_is_None", "tests/test_response.py::test_set_cookie_expires_is_timedelta_and_max_age_is_None", "tests/test_response.py::test_delete_cookie", "tests/test_response.py::test_delete_cookie_with_path", "tests/test_response.py::test_delete_cookie_with_domain", "tests/test_response.py::test_unset_cookie_not_existing_and_not_strict", "tests/test_response.py::test_unset_cookie_not_existing_and_strict", "tests/test_response.py::test_unset_cookie_key_in_cookies", "tests/test_response.py::test_merge_cookies_no_set_cookie", "tests/test_response.py::test_merge_cookies_resp_is_Response", "tests/test_response.py::test_merge_cookies_resp_is_wsgi_callable", "tests/test_response.py::test_body_get_body_is_None_len_app_iter_is_zero", "tests/test_response.py::test_cache_control_get", "tests/test_response.py::test_location", "tests/test_response.py::test_request_uri_http", "tests/test_response.py::test_request_uri_no_script_name2", "tests/test_response.py::test_cache_control_object_max_age_ten", "tests/test_response.py::test_cache_control_set_object_error", "tests/test_response.py::test_cache_expires_set", "tests/test_response.py::test_status_code_set", "tests/test_response.py::test_cache_control_set_dict", "tests/test_response.py::test_cache_control_set_None", "tests/test_response.py::test_cache_control_set_unicode", "tests/test_response.py::test_cache_control_set_control_obj_is_not_None", "tests/test_response.py::test_cache_control_del", "tests/test_response.py::test_body_file_get", "tests/test_response.py::test_body_file_write_no_charset", "tests/test_response.py::test_body_file_write_unicode_encodes", "tests/test_response.py::test_repr", "tests/test_response.py::test_cache_expires_set_timedelta", "tests/test_response.py::test_cache_expires_set_int", "tests/test_response.py::test_cache_expires_set_None", "tests/test_response.py::test_cache_expires_set_zero", "tests/test_response.py::test_encode_content_unknown", "tests/test_response.py::test_encode_content_identity", "tests/test_response.py::test_encode_content_gzip_already_gzipped", "tests/test_response.py::test_encode_content_gzip_notyet_gzipped", "tests/test_response.py::test_encode_content_gzip_notyet_gzipped_lazy", "tests/test_response.py::test_encode_content_gzip_buffer_coverage", "tests/test_response.py::test_decode_content_identity", "tests/test_response.py::test_decode_content_weird", "tests/test_response.py::test_decode_content_gzip", "tests/test_response.py::test__abs_headerlist_location_with_scheme", "tests/test_response.py::test__abs_headerlist_location_no_scheme", "tests/test_response.py::test_response_set_body_file1", "tests/test_response.py::test_response_set_body_file2", "tests/test_response.py::test_response_json_body", "tests/test_response.py::test_cache_expires_set_zero_then_nonzero" ]
[]
null
103
432
[ "webob/response.py" ]
softlayer__softlayer-python-531
05ca114d4cf35597182051d5acb4db74fc333cfc
2015-04-23 15:10:47
1195b2020ef6efc40462d59eb079f26e5f39a6d8
diff --git a/SoftLayer/CLI/config/setup.py b/SoftLayer/CLI/config/setup.py index 30ba070a..f9b37d55 100644 --- a/SoftLayer/CLI/config/setup.py +++ b/SoftLayer/CLI/config/setup.py @@ -13,14 +13,12 @@ import click -def get_api_key(client, username, secret, endpoint_url=None): +def get_api_key(client, username, secret): """Attempts API-Key and password auth to get an API key. This will also generate an API key if one doesn't exist """ - client.endpoint_url = endpoint_url - client.auth = None # Try to use a client with username/api key if len(secret) == 64: try: @@ -50,8 +48,8 @@ def cli(env): username, secret, endpoint_url, timeout = get_user_input(env) - api_key = get_api_key(env.client, username, secret, - endpoint_url=endpoint_url) + env.client.transport.transport.endpoint_url = endpoint_url + api_key = get_api_key(env.client, username, secret) path = '~/.softlayer' if env.config_file: @@ -79,6 +77,7 @@ def cli(env): parsed_config.set('softlayer', 'username', username) parsed_config.set('softlayer', 'api_key', api_key) parsed_config.set('softlayer', 'endpoint_url', endpoint_url) + parsed_config.set('softlayer', 'timeout', timeout) config_fd = os.fdopen(os.open(config_path, (os.O_WRONLY | os.O_CREAT | os.O_TRUNC), @@ -96,47 +95,28 @@ def get_user_input(env): """Ask for username, secret (api_key or password) and endpoint_url.""" defaults = config.get_settings_from_client(env.client) - timeout = defaults['timeout'] # Ask for username - for _ in range(3): - username = (env.input('Username [%s]: ' % defaults['username']) or - defaults['username']) - if username: - break - else: - raise exceptions.CLIAbort('Aborted after 3 attempts') + username = env.input('Username', default=defaults['username']) # Ask for 'secret' which can be api_key or their password - for _ in range(3): - secret = (env.getpass('API Key or Password [%s]: ' - % defaults['api_key']) or - defaults['api_key']) - if secret: - break - else: - raise exceptions.CLIAbort('Aborted after 3 attempts') + secret = env.getpass('API Key or Password', default=defaults['api_key']) # Ask for which endpoint they want to use - for _ in range(3): - endpoint_type = env.input( - 'Endpoint (public|private|custom): ') - endpoint_type = endpoint_type.lower() - if not endpoint_type: - endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT - break - if endpoint_type == 'public': - endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT - break - elif endpoint_type == 'private': - endpoint_url = SoftLayer.API_PRIVATE_ENDPOINT - break - elif endpoint_type == 'custom': - endpoint_url = env.input( - 'Endpoint URL [%s]: ' % defaults['endpoint_url'] - ) or defaults['endpoint_url'] - break - else: - raise exceptions.CLIAbort('Aborted after 3 attempts') + endpoint_type = env.input( + 'Endpoint (public|private|custom)', default='public') + endpoint_type = endpoint_type.lower() + if endpoint_type is None: + endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT + if endpoint_type == 'public': + endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT + elif endpoint_type == 'private': + endpoint_url = SoftLayer.API_PRIVATE_ENDPOINT + elif endpoint_type == 'custom': + endpoint_url = env.input('Endpoint URL', + default=defaults['endpoint_url']) + + # Ask for timeout + timeout = env.input('Timeout', default=defaults['timeout'] or 0) return username, secret, endpoint_url, timeout diff --git a/SoftLayer/CLI/core.py b/SoftLayer/CLI/core.py index d2278394..a6839522 100644 --- a/SoftLayer/CLI/core.py +++ b/SoftLayer/CLI/core.py @@ -138,17 +138,19 @@ def cli(ctx, if env.client is None: # Environment can be passed in explicitly. This is used for testing if fixtures: - transport = SoftLayer.FixtureTransport() + client = SoftLayer.BaseClient( + transport=SoftLayer.FixtureTransport(), + auth=None, + ) else: # Create SL Client - transport = SoftLayer.XmlRpcTransport() - - wrapped_transport = SoftLayer.TimingTransport(transport) - env.client = SoftLayer.create_client_from_env( - proxy=proxy, - config_file=config, - transport=wrapped_transport, - ) + client = SoftLayer.create_client_from_env( + proxy=proxy, + config_file=config, + ) + + client.transport = SoftLayer.TimingTransport(client.transport) + env.client = client @cli.resultcallback() diff --git a/SoftLayer/CLI/environment.py b/SoftLayer/CLI/environment.py index b67b8c24..f5800590 100644 --- a/SoftLayer/CLI/environment.py +++ b/SoftLayer/CLI/environment.py @@ -44,13 +44,13 @@ def fmt(self, output): """Format output based on current the environment format.""" return formatting.format_output(output, fmt=self.format) - def input(self, prompt): + def input(self, prompt, default=None): """Provide a command prompt.""" - return click.prompt(prompt) + return click.prompt(prompt, default=default) - def getpass(self, prompt): + def getpass(self, prompt, default=None): """Provide a password prompt.""" - return click.prompt(prompt, hide_input=True) + return click.prompt(prompt, hide_input=True, default=default) # Command loading methods def list_commands(self, *path): diff --git a/SoftLayer/CLI/formatting.py b/SoftLayer/CLI/formatting.py index 1f7e495a..f1554af0 100644 --- a/SoftLayer/CLI/formatting.py +++ b/SoftLayer/CLI/formatting.py @@ -160,27 +160,6 @@ def transaction_status(transaction): transaction['transactionStatus'].get('friendlyName')) -def valid_response(prompt, *valid): - """Prompt user for input. - - Will display a prompt for a command-line user. If the input is in the - valid given valid list then it will return True. Otherwise, it will - return False. If no input is received from the user, None is returned - instead. - - :param string prompt: string prompt to give to the user - :param string \\*valid: valid responses - """ - ans = click.prompt(prompt).lower() - - if ans in valid: - return True - elif ans == '': - return None - - return False - - def confirm(prompt_str, default=False): """Show a confirmation prompt to a command-line user. @@ -188,16 +167,17 @@ def confirm(prompt_str, default=False): :param bool default: Default value to True or False """ if default: + default_str = 'y' prompt = '%s [Y/n]' % prompt_str else: + default_str = 'n' prompt = '%s [y/N]' % prompt_str - response = valid_response(prompt, 'y', 'yes', 'yeah', 'yup', 'yolo') - - if response is None: - return default + ans = click.prompt(prompt, default=default_str, show_default=False) + if ans.lower() in ('y', 'yes', 'yeah', 'yup', 'yolo'): + return True - return response + return False def no_going_back(confirmation): @@ -209,10 +189,14 @@ def no_going_back(confirmation): if not confirmation: confirmation = 'yes' - return valid_response( - 'This action cannot be undone! ' - 'Type "%s" or press Enter to abort' % confirmation, - str(confirmation)) + prompt = ('This action cannot be undone! Type "%s" or press Enter ' + 'to abort' % confirmation) + + ans = click.confirm(prompt, default='', show_default=False).lower() + if ans == str(confirmation): + return True + + return False class SequentialOutput(list): diff --git a/SoftLayer/config.py b/SoftLayer/config.py index 8c679e6c..120cadab 100644 --- a/SoftLayer/config.py +++ b/SoftLayer/config.py @@ -16,9 +16,12 @@ def get_client_settings_args(**kwargs): :param \\*\\*kwargs: Arguments that are passed into the client instance """ + timeout = kwargs.get('timeout') + if timeout is not None: + timeout = float(timeout) return { 'endpoint_url': kwargs.get('endpoint_url'), - 'timeout': float(kwargs.get('timeout') or 0), + 'timeout': timeout, 'proxy': kwargs.get('proxy'), 'username': kwargs.get('username'), 'api_key': kwargs.get('api_key'),
[Bug] slcli config setup doesnt accept default value when one is already present When you already have a `.softlayer` configured, and you `slcli config setup`, it loads previous values from `.softlayer` and shows them to you, but pressing enter at the prompt doesnt keep the previous value and move on to the next setting, it sits there and forces you to retype it and it shouldnt do that. It also doesnt prompt for a timeout value, it should prompt and accept no value provided as meaning dont set and use default. Using 4.0.0
softlayer/softlayer-python
diff --git a/SoftLayer/tests/CLI/environment_tests.py b/SoftLayer/tests/CLI/environment_tests.py index e1ebf0e2..b3826df8 100644 --- a/SoftLayer/tests/CLI/environment_tests.py +++ b/SoftLayer/tests/CLI/environment_tests.py @@ -43,13 +43,13 @@ def test_get_command(self): @mock.patch('click.prompt') def test_input(self, prompt_mock): r = self.env.input('input') - prompt_mock.assert_called_with('input') + prompt_mock.assert_called_with('input', default=None) self.assertEqual(prompt_mock(), r) @mock.patch('click.prompt') def test_getpass(self, prompt_mock): r = self.env.getpass('input') - prompt_mock.assert_called_with('input', hide_input=True) + prompt_mock.assert_called_with('input', default=None, hide_input=True) self.assertEqual(prompt_mock(), r) def test_resolve_alias(self): diff --git a/SoftLayer/tests/CLI/helper_tests.py b/SoftLayer/tests/CLI/helper_tests.py index 80ae0bd6..d75e8e2b 100644 --- a/SoftLayer/tests/CLI/helper_tests.py +++ b/SoftLayer/tests/CLI/helper_tests.py @@ -41,50 +41,21 @@ def test_fail(self): class PromptTests(testing.TestCase): - @mock.patch('click.prompt') - def test_invalid_response(self, prompt_mock): - prompt_mock.return_value = 'y' - result = formatting.valid_response('test', 'n') - prompt_mock.assert_called_with('test') - self.assertFalse(result) - - prompt_mock.return_value = 'wakakwakwaka' - result = formatting.valid_response('test', 'n') - prompt_mock.assert_called_with('test') - self.assertFalse(result) - - prompt_mock.return_value = '' - result = formatting.valid_response('test', 'n') - prompt_mock.assert_called_with('test') - self.assertEqual(result, None) - - @mock.patch('click.prompt') - def test_valid_response(self, prompt_mock): - prompt_mock.return_value = 'n' - result = formatting.valid_response('test', 'n') - prompt_mock.assert_called_with('test') - self.assertTrue(result) - - prompt_mock.return_value = 'N' - result = formatting.valid_response('test', 'n') - prompt_mock.assert_called_with('test') - self.assertTrue(result) - - @mock.patch('click.prompt') - def test_do_or_die(self, prompt_mock): + @mock.patch('click.confirm') + def test_do_or_die(self, confirm_mock): confirmed = '37347373737' - prompt_mock.return_value = confirmed + confirm_mock.return_value = confirmed result = formatting.no_going_back(confirmed) self.assertTrue(result) # no_going_back should cast int's to str() confirmed = '4712309182309' - prompt_mock.return_value = confirmed + confirm_mock.return_value = confirmed result = formatting.no_going_back(int(confirmed)) self.assertTrue(result) confirmed = None - prompt_mock.return_value = '' + confirm_mock.return_value = '' result = formatting.no_going_back(confirmed) self.assertFalse(result) @@ -98,9 +69,19 @@ def test_confirmation(self, prompt_mock): res = formatting.confirm('Confirm?', default=False) self.assertFalse(res) - prompt_mock.return_value = '' + prompt_mock.return_value = 'Y' res = formatting.confirm('Confirm?', default=True) self.assertTrue(res) + prompt_mock.assert_called_with('Confirm? [Y/n]', + default='y', + show_default=False) + + prompt_mock.return_value = 'N' + res = formatting.confirm('Confirm?', default=False) + self.assertFalse(res) + prompt_mock.assert_called_with('Confirm? [y/N]', + default='n', + show_default=False) class FormattedItemTests(testing.TestCase): diff --git a/SoftLayer/tests/CLI/modules/config_tests.py b/SoftLayer/tests/CLI/modules/config_tests.py index 630cfa4c..fe835799 100644 --- a/SoftLayer/tests/CLI/modules/config_tests.py +++ b/SoftLayer/tests/CLI/modules/config_tests.py @@ -48,7 +48,7 @@ def test_setup(self, input, getpass, confirm_mock): with tempfile.NamedTemporaryFile() as config_file: confirm_mock.return_value = True getpass.return_value = 'A' * 64 - input.side_effect = ['user', 'public'] + input.side_effect = ['user', 'public', 0] result = self.run_command(['--config=%s' % config_file.name, 'config', 'setup']) @@ -71,7 +71,7 @@ def test_setup_cancel(self, input, getpass, confirm_mock): with tempfile.NamedTemporaryFile() as config_file: confirm_mock.return_value = False getpass.return_value = 'A' * 64 - input.side_effect = ['user', 'public'] + input.side_effect = ['user', 'public', 0] result = self.run_command(['--config=%s' % config_file.name, 'config', 'setup']) @@ -83,7 +83,7 @@ def test_setup_cancel(self, input, getpass, confirm_mock): @mock.patch('SoftLayer.CLI.environment.Environment.input') def test_get_user_input_private(self, input, getpass): getpass.return_value = 'A' * 64 - input.side_effect = ['user', 'private'] + input.side_effect = ['user', 'private', 0] username, secret, endpoint_url, timeout = ( config.get_user_input(self.env)) @@ -96,7 +96,7 @@ def test_get_user_input_private(self, input, getpass): @mock.patch('SoftLayer.CLI.environment.Environment.input') def test_get_user_input_custom(self, input, getpass): getpass.return_value = 'A' * 64 - input.side_effect = ['user', 'custom', 'custom-endpoint'] + input.side_effect = ['user', 'custom', 'custom-endpoint', 0] _, _, endpoint_url, _ = config.get_user_input(self.env) @@ -106,7 +106,7 @@ def test_get_user_input_custom(self, input, getpass): @mock.patch('SoftLayer.CLI.environment.Environment.input') def test_get_user_input_default(self, input, getpass): self.env.getpass.return_value = 'A' * 64 - self.env.input.side_effect = ['user', ''] + self.env.input.side_effect = ['user', 'public', 0] _, _, endpoint_url, _ = config.get_user_input(self.env)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 5 }
4.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "tools/test-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 distlib==0.3.9 docutils==0.18.1 filelock==3.4.1 fixtures==4.0.1 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 Jinja2==3.0.3 MarkupSafe==2.0.1 mock==5.2.0 nose==1.3.7 packaging==21.3 pbr==6.1.1 platformdirs==2.4.0 pluggy==1.0.0 prettytable==2.5.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytz==2025.2 requests==2.27.1 six==1.17.0 snowballstemmer==2.2.0 -e git+https://github.com/softlayer/softlayer-python.git@05ca114d4cf35597182051d5acb4db74fc333cfc#egg=SoftLayer Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testtools==2.6.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 wcwidth==0.2.13 zipp==3.6.0
name: softlayer-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - distlib==0.3.9 - docutils==0.18.1 - filelock==3.4.1 - fixtures==4.0.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jinja2==3.0.3 - markupsafe==2.0.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pbr==6.1.1 - platformdirs==2.4.0 - pluggy==1.0.0 - prettytable==2.5.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytz==2025.2 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testtools==2.6.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/softlayer-python
[ "SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_getpass", "SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_input", "SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_confirmation", "SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_do_or_die" ]
[]
[ "SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_get_command", "SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_get_command_invalid", "SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_list_commands", "SoftLayer/tests/CLI/environment_tests.py::EnvironmentTests::test_resolve_alias", "SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_default", "SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_fail", "SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_blank", "SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_gb", "SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_init", "SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_mb_to_gb", "SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_init", "SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_str", "SoftLayer/tests/CLI/helper_tests.py::FormattedListTests::test_to_python", "SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn", "SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn_empty", "SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_active_txn_missing", "SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_transaction_status", "SoftLayer/tests/CLI/helper_tests.py::FormattedTxnTests::test_transaction_status_missing", "SoftLayer/tests/CLI/helper_tests.py::CLIAbortTests::test_init", "SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_multiple", "SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_none", "SoftLayer/tests/CLI/helper_tests.py::ResolveIdTests::test_resolve_id_one", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_formatted_item", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_json", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_json_keyvaluetable", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_list", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_python", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_python_keyvaluetable", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_raw", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_string", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_format_output_table", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_sequentialoutput", "SoftLayer/tests/CLI/helper_tests.py::TestFormatOutput::test_unknown", "SoftLayer/tests/CLI/helper_tests.py::TestTemplateArgs::test_no_template_option", "SoftLayer/tests/CLI/helper_tests.py::TestTemplateArgs::test_template_options", "SoftLayer/tests/CLI/helper_tests.py::TestExportToTemplate::test_export_to_template", "SoftLayer/tests/CLI/modules/config_tests.py::TestHelpShow::test_show", "SoftLayer/tests/CLI/modules/config_tests.py::TestHelpSetup::test_get_user_input_custom", "SoftLayer/tests/CLI/modules/config_tests.py::TestHelpSetup::test_get_user_input_default", "SoftLayer/tests/CLI/modules/config_tests.py::TestHelpSetup::test_get_user_input_private", "SoftLayer/tests/CLI/modules/config_tests.py::TestHelpSetup::test_setup", "SoftLayer/tests/CLI/modules/config_tests.py::TestHelpSetup::test_setup_cancel" ]
[]
MIT License
105
2,261
[ "SoftLayer/CLI/config/setup.py", "SoftLayer/CLI/core.py", "SoftLayer/CLI/environment.py", "SoftLayer/CLI/formatting.py", "SoftLayer/config.py" ]
mne-tools__mne-python-2018
0bf2f433842c26436fc8f1ee168dfa49b07c45c3
2015-04-24 12:26:56
edceb8f38349d6dc0cade1c9f8384cc0707ce3e8
diff --git a/mne/report.py b/mne/report.py index a8e0d21a6..892aab074 100644 --- a/mne/report.py +++ b/mne/report.py @@ -554,7 +554,12 @@ image_template = Template(u""" {{if comment is not None}} <br><br> <div style="text-align:center;"> - {{comment}} + <style> + p.test {word-wrap: break-word;} + </style> + <p class="test"> + {{comment}} + </p> </div> {{endif}} {{else}} @@ -698,10 +703,16 @@ class Report(object): if not isinstance(captions, (list, tuple)): captions = [captions] if not isinstance(comments, (list, tuple)): - comments = [comments] - if not len(items) == len(captions): - raise ValueError('Captions and report items must have the same' - ' length.') + if comments is None: + comments = [comments] * len(captions) + else: + comments = [comments] + if len(comments) != len(items): + raise ValueError('Comments and report items must have the same ' + 'length or comments should be None.') + elif len(captions) != len(items): + raise ValueError('Captions and report items must have the same ' + 'length.') # Book-keeping of section names if section not in self.sections:
BUG: Adding more than one figure to Report is broken If a call to `add_figs_to_section` is made with a list of figures, only the first one is added. In this example, only the first figure appears on the report. ```Python import numpy as np import matplotlib.pyplot as plt from mne.report import Report r = Report('test') fig1 = plt.figure() plt.plot([1, 2], [1, 1]) fig2 = plt.figure() plt.plot([1, 2], [2, 2]) r.add_figs_to_section([fig1, fig2], section='ts', captions=['fig1', 'fig2']) r.save('test.html', overwrite=True) ```
mne-tools/mne-python
diff --git a/mne/tests/test_report.py b/mne/tests/test_report.py index 500f408b4..dd0d02ffe 100644 --- a/mne/tests/test_report.py +++ b/mne/tests/test_report.py @@ -212,4 +212,21 @@ def test_add_htmls_to_section(): assert_equal(html, html_compare) +def test_validate_input(): + report = Report() + items = ['a', 'b', 'c'] + captions = ['Letter A', 'Letter B', 'Letter C'] + section = 'ABCs' + comments = ['First letter of the alphabet.', + 'Second letter of the alphabet', + 'Third letter of the alphabet'] + assert_raises(ValueError, report._validate_input, items, captions[:-1], + section, comments=None) + assert_raises(ValueError, report._validate_input, items, captions, section, + comments=comments[:-1]) + values = report._validate_input(items, captions, section, comments=None) + items_new, captions_new, comments_new = values + assert_equal(len(comments_new), len(items)) + + run_tests_if_main()
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 1 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "numpy>=1.16.0", "pandas>=1.0.0", "scikit-learn", "h5py", "pysurfer", "nose", "nose-timer", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
apptools==5.2.1 certifi @ file:///croot/certifi_1671487769961/work/certifi configobj==5.0.9 cycler==0.11.0 envisage==7.0.3 exceptiongroup==1.2.2 fonttools==4.38.0 h5py==3.8.0 importlib-metadata==6.7.0 importlib-resources==5.12.0 iniconfig==2.0.0 joblib==1.3.2 kiwisolver==1.4.5 matplotlib==3.5.3 mayavi==4.8.1 -e git+https://github.com/mne-tools/mne-python.git@0bf2f433842c26436fc8f1ee168dfa49b07c45c3#egg=mne nibabel==4.0.2 nose==1.3.7 nose-timer==1.0.1 numpy==1.21.6 packaging==24.0 pandas==1.3.5 Pillow==9.5.0 pluggy==1.2.0 pyface==8.0.0 Pygments==2.17.2 pyparsing==3.1.4 pysurfer==0.11.2 pytest==7.4.4 python-dateutil==2.9.0.post0 pytz==2025.2 scikit-learn==1.0.2 scipy==1.7.3 six==1.17.0 threadpoolctl==3.1.0 tomli==2.0.1 traits==6.4.3 traitsui==8.0.0 typing_extensions==4.7.1 vtk==9.3.1 zipp==3.15.0
name: mne-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - apptools==5.2.1 - configobj==5.0.9 - cycler==0.11.0 - envisage==7.0.3 - exceptiongroup==1.2.2 - fonttools==4.38.0 - h5py==3.8.0 - importlib-metadata==6.7.0 - importlib-resources==5.12.0 - iniconfig==2.0.0 - joblib==1.3.2 - kiwisolver==1.4.5 - matplotlib==3.5.3 - mayavi==4.8.1 - nibabel==4.0.2 - nose==1.3.7 - nose-timer==1.0.1 - numpy==1.21.6 - packaging==24.0 - pandas==1.3.5 - pillow==9.5.0 - pluggy==1.2.0 - pyface==8.0.0 - pygments==2.17.2 - pyparsing==3.1.4 - pysurfer==0.11.2 - pytest==7.4.4 - python-dateutil==2.9.0.post0 - pytz==2025.2 - scikit-learn==1.0.2 - scipy==1.7.3 - six==1.17.0 - threadpoolctl==3.1.0 - tomli==2.0.1 - traits==6.4.3 - traitsui==8.0.0 - typing-extensions==4.7.1 - vtk==9.3.1 - zipp==3.15.0 prefix: /opt/conda/envs/mne-python
[ "mne/tests/test_report.py::test_validate_input" ]
[]
[]
[]
BSD 3-Clause "New" or "Revised" License
106
361
[ "mne/report.py" ]
google__yapf-131
5e7c8aadfe6ed7d892e858b305ef2ca60c65bfcc
2015-04-27 19:32:21
5e7c8aadfe6ed7d892e858b305ef2ca60c65bfcc
coveralls: [![Coverage Status](https://coveralls.io/builds/2434186/badge)](https://coveralls.io/builds/2434186) Coverage decreased (-0.2%) to 91.89% when pulling **53c06d00461e35cfd3ae9a27cecc7dcc9d0912f0 on sbc100:handle_errors** into **8c7840c8b835568116219e9d960764198add4927 on google:master**.
diff --git a/yapf/__init__.py b/yapf/__init__.py index 7634c5c..7ffdfee 100644 --- a/yapf/__init__.py +++ b/yapf/__init__.py @@ -32,6 +32,7 @@ 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 @@ -40,10 +41,6 @@ from yapf.yapflib import yapf_api __version__ = '0.1.7' -class YapfError(Exception): - pass - - def main(argv): """Main program. @@ -147,7 +144,7 @@ def main(argv): files = file_resources.GetCommandLineFiles(args.files, args.recursive) if not files: - raise YapfError('Input filenames did not match any python files') + raise errors.YapfError('Input filenames did not match any python files') FormatFiles(files, lines, style_config=args.style, no_local_style=args.no_local_style, @@ -213,15 +210,19 @@ def _GetLines(line_strings): # The 'list' here is needed by Python 3. line = list(map(int, line_string.split('-', 1))) if line[0] < 1: - raise ValueError('invalid start of line range: %r' % line) + raise errors.YapfError('invalid start of line range: %r' % line) if line[0] > line[1]: - raise ValueError('end comes before start in line range: %r', line) + raise errors.YapfError('end comes before start in line range: %r', line) lines.append(tuple(line)) return lines def run_main(): # pylint: disable=invalid-name - sys.exit(main(sys.argv)) + try: + sys.exit(main(sys.argv)) + except errors.YapfError as e: + sys.stderr.write('yapf: ' + str(e) + '\n') + sys.exit(1) if __name__ == '__main__': diff --git a/yapf/yapflib/__init__.py b/yapf/yapflib/__init__.py index e7522b2..f526bc3 100644 --- a/yapf/yapflib/__init__.py +++ b/yapf/yapflib/__init__.py @@ -11,3 +11,4 @@ # 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. + diff --git a/yapf/yapflib/errors.py b/yapf/yapflib/errors.py new file mode 100644 index 0000000..1bf5bc7 --- /dev/null +++ b/yapf/yapflib/errors.py @@ -0,0 +1,22 @@ +# 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. + + +class YapfError(Exception): + """Parent class for user errors or input errors. + + Exceptions of this type are handled by the command line tool + and result in clear error messages, as opposed to backtraces. + """ + pass diff --git a/yapf/yapflib/style.py b/yapf/yapflib/style.py index 7d1ecbb..518ace8 100644 --- a/yapf/yapflib/style.py +++ b/yapf/yapflib/style.py @@ -18,13 +18,10 @@ import re import textwrap from yapf.yapflib import py3compat +from yapf.yapflib import errors -class Error(Exception): - pass - - -class StyleConfigError(Error): +class StyleConfigError(errors.YapfError): """Raised when there's a problem reading the style configuration.""" pass
yapf crashes with misggin style (e.g. --style=foo) I've got a fix for this that I will send a PR for. This is the crash: ``` PYTHONPATH=$PWD/yapf python -m yapf --style=foo -i -r . Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/local/google/home/sbc/dev/yapf/yapf/__main__.py", line 16, in <module> yapf.run_main() File "yapf/__init__.py", line 209, in run_main sys.exit(main(sys.argv)) File "yapf/__init__.py", line 146, in main verify=args.verify) File "yapf/__init__.py", line 174, in FormatFiles print_diff=print_diff, verify=verify) File "yapf/yapflib/yapf_api.py", line 78, in FormatFile verify=verify), encoding File "yapf/yapflib/yapf_api.py", line 100, in FormatCode style.SetGlobalStyle(style.CreateStyleFromConfig(style_config)) File "yapf/yapflib/style.py", line 212, in CreateStyleFromConfig config = _CreateConfigParserFromConfigFile(style_config) File "yapf/yapflib/style.py", line 234, in _CreateConfigParserFromConfigFile '"{0}" is not a valid style or file path'.format(config_filename)) yapf.yapflib.style.StyleConfigError: "foo" is not a valid style or file path ```
google/yapf
diff --git a/yapftests/main_test.py b/yapftests/main_test.py index 314dcba..e216d67 100644 --- a/yapftests/main_test.py +++ b/yapftests/main_test.py @@ -57,10 +57,23 @@ def patched_input(code): yapf.py3compat.raw_input = raw_input +class RunMainTest(unittest.TestCase): + + def testShouldHandleYapfError(self): + """run_main should handle YapfError and sys.exit(1)""" + expected_message = 'yapf: Input filenames did not match any python files\n' + sys.argv = ['yapf', 'foo.c'] + with captured_output() as (out, err): + with self.assertRaises(SystemExit): + ret = yapf.run_main() + self.assertEqual(out.getvalue(), '') + self.assertEqual(err.getvalue(), expected_message) + + class MainTest(unittest.TestCase): def testNoPythonFilesMatched(self): - with self.assertRaisesRegexp(yapf.YapfError, + with self.assertRaisesRegexp(yapf.errors.YapfError, 'did not match any python files'): yapf.main(['yapf', 'foo.c'])
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 3 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work -e git+https://github.com/google/yapf.git@5e7c8aadfe6ed7d892e858b305ef2ca60c65bfcc#egg=yapf
name: yapf channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/yapf
[ "yapftests/main_test.py::RunMainTest::testShouldHandleYapfError", "yapftests/main_test.py::MainTest::testNoPythonFilesMatched" ]
[]
[ "yapftests/main_test.py::MainTest::testEchoBadInput", "yapftests/main_test.py::MainTest::testEchoInput", "yapftests/main_test.py::MainTest::testEchoInputWithStyle", "yapftests/main_test.py::MainTest::testHelp", "yapftests/main_test.py::MainTest::testVersion" ]
[]
Apache License 2.0
112
1,076
[ "yapf/__init__.py", "yapf/yapflib/__init__.py", "yapf/yapflib/style.py" ]
typesafehub__conductr-cli-50
171c9dc9c17827b586d3002ba49186e5653f37bf
2015-05-01 08:35:41
e5561a7e43d92a0c19e7b6e31a36448455a17fba
diff --git a/conductr_cli/bundle_utils.py b/conductr_cli/bundle_utils.py index cf11423..c7b72e2 100644 --- a/conductr_cli/bundle_utils.py +++ b/conductr_cli/bundle_utils.py @@ -7,5 +7,5 @@ def short_id(bundle_id): def conf(bundle_path): bundle_zip = ZipFile(bundle_path) - bundleConf = [bundle_zip.read(name) for name in bundle_zip.namelist() if name.endswith('bundle.conf')] - return bundleConf[0].decode('utf-8') if len(bundleConf) == 1 else '' + bundle_configuration = [bundle_zip.read(name) for name in bundle_zip.namelist() if name.endswith('bundle.conf')] + return bundle_configuration[0].decode('utf-8') if len(bundle_configuration) == 1 else '' diff --git a/conductr_cli/conduct.py b/conductr_cli/conduct.py index 3f62279..0aafe51 100755 --- a/conductr_cli/conduct.py +++ b/conductr_cli/conduct.py @@ -3,7 +3,8 @@ import argcomplete import argparse -from conductr_cli import conduct_info, conduct_load, conduct_run, conduct_services, conduct_stop, conduct_unload, conduct_version +from conductr_cli \ + import conduct_info, conduct_load, conduct_run, conduct_services, conduct_stop, conduct_unload, conduct_version import os diff --git a/conductr_cli/conduct_info.py b/conductr_cli/conduct_info.py index 82dbb02..0c35ad9 100644 --- a/conductr_cli/conduct_info.py +++ b/conductr_cli/conduct_info.py @@ -12,7 +12,7 @@ def info(args): response = requests.get(url) conduct_logging.raise_for_status_inc_3xx(response) - if (args.verbose): + if args.verbose: conduct_logging.pretty_json(response.text) data = [ @@ -38,6 +38,6 @@ def calc_column_widths(data): for column, value in row.items(): column_len = len(str(value)) width_key = column + '_width' - if (column_len > column_widths.get(width_key, 0)): + if column_len > column_widths.get(width_key, 0): column_widths[width_key] = column_len return column_widths diff --git a/conductr_cli/conduct_load.py b/conductr_cli/conduct_load.py index 5de7897..3da8ef7 100644 --- a/conductr_cli/conduct_load.py +++ b/conductr_cli/conduct_load.py @@ -2,59 +2,64 @@ from pyhocon import ConfigFactory, ConfigTree from pyhocon.exceptions import ConfigMissingException from conductr_cli import bundle_utils, conduct_url, conduct_logging from functools import partial +from urllib.parse import ParseResult, urlparse, urlunparse +from urllib.request import urlretrieve +from pathlib import Path + import json -import os -import re import requests - @conduct_logging.handle_connection_error @conduct_logging.handle_http_error @conduct_logging.handle_invalid_config @conduct_logging.handle_no_file +@conduct_logging.handle_bad_zip def load(args): """`conduct load` command""" - if not os.path.isfile(args.bundle): - raise FileNotFoundError(args.bundle) - - if args.configuration is not None and not os.path.isfile(args.configuration): - raise FileNotFoundError(args.configuration) + print('Retrieving bundle...') + bundle_file, bundle_headers = urlretrieve(get_url(args.bundle)) + if args.configuration is not None: + print('Retrieving configuration...') + configuration_file, configuration_headers = urlretrieve(get_url(args.configuration)) \ + if args.configuration is not None else (None, None) - bundle_conf = ConfigFactory.parse_string(bundle_utils.conf(args.bundle)) - overlay_bundle_conf = None if args.configuration is None else \ - ConfigFactory.parse_string(bundle_utils.conf(args.configuration)) + bundle_conf = ConfigFactory.parse_string(bundle_utils.conf(bundle_file)) + overlay_bundle_conf = None if configuration_file is None else \ + ConfigFactory.parse_string(bundle_utils.conf(configuration_file)) - withBundleConfs = partial(applyToConfs, bundle_conf, overlay_bundle_conf) + with_bundle_configurations = partial(apply_to_configurations, bundle_conf, overlay_bundle_conf) url = conduct_url.url('bundles', args) files = [ - ('nrOfCpus', withBundleConfs(ConfigTree.get_string, 'nrOfCpus')), - ('memory', withBundleConfs(ConfigTree.get_string, 'memory')), - ('diskSpace', withBundleConfs(ConfigTree.get_string, 'diskSpace')), - ('roles', ' '.join(withBundleConfs(ConfigTree.get_list, 'roles'))), - ('bundleName', withBundleConfs(ConfigTree.get_string, 'name')), - ('system', withBundleConfs(ConfigTree.get_string, 'system')), - ('bundle', open(args.bundle, 'rb')) + ('nrOfCpus', with_bundle_configurations(ConfigTree.get_string, 'nrOfCpus')), + ('memory', with_bundle_configurations(ConfigTree.get_string, 'memory')), + ('diskSpace', with_bundle_configurations(ConfigTree.get_string, 'diskSpace')), + ('roles', ' '.join(with_bundle_configurations(ConfigTree.get_list, 'roles'))), + ('bundleName', with_bundle_configurations(ConfigTree.get_string, 'name')), + ('system', with_bundle_configurations(ConfigTree.get_string, 'system')), + ('bundle', open(bundle_file, 'rb')) ] - if args.configuration is not None: - files.append(('configuration', open(args.configuration, 'rb'))) + if configuration_file is not None: + files.append(('configuration', open(configuration_file, 'rb'))) + print('Loading bundle to ConductR...') response = requests.post(url, files=files) conduct_logging.raise_for_status_inc_3xx(response) - if (args.verbose): + if args.verbose: conduct_logging.pretty_json(response.text) response_json = json.loads(response.text) - bundleId = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId']) + bundle_id = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId']) print('Bundle loaded.') - print('Start bundle with: conduct run{} {}'.format(args.cli_parameters, bundleId)) - print('Unload bundle with: conduct unload{} {}'.format(args.cli_parameters, bundleId)) + print('Start bundle with: conduct run{} {}'.format(args.cli_parameters, bundle_id)) + print('Unload bundle with: conduct unload{} {}'.format(args.cli_parameters, bundle_id)) print('Print ConductR info with: conduct info{}'.format(args.cli_parameters)) -def applyToConfs(base_conf, overlay_conf, method, key): + +def apply_to_configurations(base_conf, overlay_conf, method, key): if overlay_conf is None: return method(base_conf, key) else: @@ -62,3 +67,10 @@ def applyToConfs(base_conf, overlay_conf, method, key): return method(overlay_conf, key) except ConfigMissingException: return method(base_conf, key) + + +def get_url(uri): + parsed = urlparse(uri, scheme='file') + op = Path(uri) + np = str(op.cwd() / op if parsed.scheme == 'file' and op.root == '' else parsed.path) + return urlunparse(ParseResult(parsed.scheme, parsed.netloc, np, parsed.params, parsed.query, parsed.fragment)) diff --git a/conductr_cli/conduct_logging.py b/conductr_cli/conduct_logging.py index a4c94d0..c6d13a4 100644 --- a/conductr_cli/conduct_logging.py +++ b/conductr_cli/conduct_logging.py @@ -1,9 +1,12 @@ import json import sys +import urllib + from pyhocon.exceptions import ConfigException from requests import status_codes from requests.exceptions import ConnectionError, HTTPError - +from urllib.error import URLError +from zipfile import BadZipFile # print to stderr def error(message, *objs): @@ -15,7 +18,7 @@ def warning(message, *objs): def connection_error(err, args): - error('Unable to contact Typesafe ConductR.') + error('Unable to contact ConductR.') error('Reason: {}'.format(err.args[0])) error('Make sure it can be accessed at {}:{}.'.format(args[0].ip, args[0].port)) @@ -74,7 +77,9 @@ def handle_no_file(func): def handler(*args, **kwargs): try: return func(*args, **kwargs) - except FileNotFoundError as err: + except urllib.error.HTTPError as err: + error('Resource not found: {}', err.url) + except URLError as err: error('File not found: {}', err.args[0]) # Do not change the wrapped function name, @@ -84,6 +89,20 @@ def handle_no_file(func): return handler +def handle_bad_zip(func): + def handler(*args, **kwargs): + try: + return func(*args, **kwargs) + except BadZipFile as err: + error('Problem with the bundle: {}', err.args[0]) + + # Do not change the wrapped function name, + # so argparse configuration can be tested. + handler.__name__ = func.__name__ + + return handler + + def raise_for_status_inc_3xx(response): """ raise status when status code is 3xx diff --git a/conductr_cli/conduct_run.py b/conductr_cli/conduct_run.py index e45ead1..779603c 100644 --- a/conductr_cli/conduct_run.py +++ b/conductr_cli/conduct_run.py @@ -13,12 +13,12 @@ def run(args): response = requests.put(url) conduct_logging.raise_for_status_inc_3xx(response) - if (args.verbose): + if args.verbose: conduct_logging.pretty_json(response.text) response_json = json.loads(response.text) - bundleId = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId']) + bundle_id = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId']) print('Bundle run request sent.') - print('Stop bundle with: conduct stop{} {}'.format(args.cli_parameters, bundleId)) + print('Stop bundle with: conduct stop{} {}'.format(args.cli_parameters, bundle_id)) print('Print ConductR info with: conduct info{}'.format(args.cli_parameters)) diff --git a/conductr_cli/conduct_services.py b/conductr_cli/conduct_services.py index 2b07544..236033b 100644 --- a/conductr_cli/conduct_services.py +++ b/conductr_cli/conduct_services.py @@ -13,7 +13,7 @@ def services(args): response = requests.get(url) conduct_logging.raise_for_status_inc_3xx(response) - if (args.verbose): + if args.verbose: conduct_logging.pretty_json(response.text) data = sorted([ @@ -39,7 +39,8 @@ def services(args): service_endpoints[url.path] |= {service['service']} except KeyError: service_endpoints[url.path] = {service['service']} - duplicate_endpoints = [service for (service, endpoint) in service_endpoints.items() if len(endpoint) > 1] if len(service_endpoints) > 0 else [] + duplicate_endpoints = [service for (service, endpoint) in service_endpoints.items() if len(endpoint) > 1] \ + if len(service_endpoints) > 0 else [] data.insert(0, {'service': 'SERVICE', 'bundle_id': 'BUNDLE ID', 'bundle_name': 'BUNDLE NAME', 'status': 'STATUS'}) diff --git a/conductr_cli/conduct_stop.py b/conductr_cli/conduct_stop.py index b15457d..fdfae85 100644 --- a/conductr_cli/conduct_stop.py +++ b/conductr_cli/conduct_stop.py @@ -13,12 +13,12 @@ def stop(args): response = requests.put(url) conduct_logging.raise_for_status_inc_3xx(response) - if (args.verbose): + if args.verbose: conduct_logging.pretty_json(response.text) response_json = json.loads(response.text) - bundleId = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId']) + bundle_id = response_json['bundleId'] if args.long_ids else bundle_utils.short_id(response_json['bundleId']) print('Bundle stop request sent.') - print('Unload bundle with: conduct unload{} {}'.format(args.cli_parameters, bundleId)) + print('Unload bundle with: conduct unload{} {}'.format(args.cli_parameters, bundle_id)) print('Print ConductR info with: conduct info{}'.format(args.cli_parameters)) diff --git a/conductr_cli/conduct_unload.py b/conductr_cli/conduct_unload.py index b6bc47b..49d9990 100644 --- a/conductr_cli/conduct_unload.py +++ b/conductr_cli/conduct_unload.py @@ -12,7 +12,7 @@ def unload(args): response = requests.delete(url) conduct_logging.raise_for_status_inc_3xx(response) - if (args.verbose): + if args.verbose: conduct_logging.pretty_json(response.text) print('Bundle unload request sent.') diff --git a/conductr_cli/conduct_version.py b/conductr_cli/conduct_version.py index 206d209..0e23b33 100644 --- a/conductr_cli/conduct_version.py +++ b/conductr_cli/conduct_version.py @@ -2,5 +2,5 @@ from conductr_cli import __version__ # `conduct version` command -def version(args): +def version(): print(__version__)
conduct load should support urls We should extend the `load` sub command so that it can download a remote resource for the purposes of then uploading it to ConductR. Accepting a URL therefore allows us to pull down bundles and their respective configurations from remote locations.
typesafehub/conductr-cli
diff --git a/conductr_cli/test/cli_test_case.py b/conductr_cli/test/cli_test_case.py index f57eaad..5f44a83 100644 --- a/conductr_cli/test/cli_test_case.py +++ b/conductr_cli/test/cli_test_case.py @@ -10,7 +10,7 @@ class CliTestCase(): @property def default_connection_error(self): - return strip_margin("""|ERROR: Unable to contact Typesafe ConductR. + return strip_margin("""|ERROR: Unable to contact ConductR. |ERROR: Reason: test reason |ERROR: Make sure it can be accessed at {}:{}. |""") @@ -47,7 +47,7 @@ class CliTestCase(): def strip_margin(string, marginChar='|'): - return '\n'.join([line[line.index(marginChar) + 1:] for line in string.split('\n')]) + return '\n'.join([line[line.find(marginChar) + 1:] for line in string.split('\n')]) def create_temp_bundle_with_contents(contents): diff --git a/conductr_cli/test/test_conduct_load.py b/conductr_cli/test/test_conduct_load.py index 8ec2e54..220b4c3 100644 --- a/conductr_cli/test/test_conduct_load.py +++ b/conductr_cli/test/test_conduct_load.py @@ -2,6 +2,7 @@ from unittest import TestCase from unittest.mock import call, patch, MagicMock from conductr_cli.test.cli_test_case import CliTestCase, create_temp_bundle, create_temp_bundle_with_contents, strip_margin from conductr_cli import conduct_load +from urllib.error import URLError import shutil @@ -52,7 +53,9 @@ class TestConductLoadCommand(TestCase, CliTestCase): ('bundle', 1) ] - output_template = """|Bundle loaded. + output_template = """|Retrieving bundle... + |{downloading_configuration}Loading bundle to ConductR... + |{verbose}Bundle loaded. |Start bundle with: conduct run{params} {bundle_id} |Unload bundle with: conduct unload{params} {bundle_id} |Print ConductR info with: conduct info{params} @@ -62,64 +65,84 @@ class TestConductLoadCommand(TestCase, CliTestCase): def tearDownClass(cls): shutil.rmtree(cls.tmpdir) - def default_output(self, params='', bundle_id='45e0c47'): - return strip_margin(self.output_template.format(**{'params': params, 'bundle_id': bundle_id})) + def default_output(self, params='', bundle_id='45e0c47', downloading_configuration='', verbose=''): + return strip_margin(self.output_template.format(**{ + 'params': params, + 'bundle_id': bundle_id, + 'downloading_configuration': downloading_configuration, + 'verbose': verbose})) def test_success(self): + urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ())) http_method = self.respond_with(200, self.default_response) stdout = MagicMock() - openMock = MagicMock(return_value=1) + open_mock = MagicMock(return_value=1) - with patch('requests.post', http_method), patch('sys.stdout', stdout), patch('builtins.open', openMock): + with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \ + patch('requests.post', http_method), \ + patch('sys.stdout', stdout), \ + patch('builtins.open', open_mock): conduct_load.load(MagicMock(**self.default_args)) - openMock.assert_called_with(self.bundle_file, 'rb') + open_mock.assert_called_with(self.bundle_file, 'rb') http_method.assert_called_with(self.default_url, files=self.default_files) self.assertEqual(self.default_output(), self.output(stdout)) def test_success_verbose(self): + urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ())) http_method = self.respond_with(200, self.default_response) stdout = MagicMock() - openMock = MagicMock(return_value=1) + open_mock = MagicMock(return_value=1) - with patch('requests.post', http_method), patch('sys.stdout', stdout), patch('builtins.open', openMock): + with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \ + patch('requests.post', http_method), \ + patch('sys.stdout', stdout), \ + patch('builtins.open', open_mock): args = self.default_args.copy() args.update({'verbose': True}) conduct_load.load(MagicMock(**args)) - openMock.assert_called_with(self.bundle_file, 'rb') + open_mock.assert_called_with(self.bundle_file, 'rb') http_method.assert_called_with(self.default_url, files=self.default_files) - self.assertEqual(self.default_response + self.default_output(), self.output(stdout)) + self.assertEqual(self.default_output(verbose=self.default_response), self.output(stdout)) def test_success_long_ids(self): + urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ())) http_method = self.respond_with(200, self.default_response) stdout = MagicMock() - openMock = MagicMock(return_value=1) + open_mock = MagicMock(return_value=1) - with patch('requests.post', http_method), patch('sys.stdout', stdout), patch('builtins.open', openMock): + with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \ + patch('requests.post', http_method), \ + patch('sys.stdout', stdout), \ + patch('builtins.open', open_mock): args = self.default_args.copy() args.update({'long_ids': True}) conduct_load.load(MagicMock(**args)) - openMock.assert_called_with(self.bundle_file, 'rb') + open_mock.assert_called_with(self.bundle_file, 'rb') http_method.assert_called_with(self.default_url, files=self.default_files) self.assertEqual(self.default_output(bundle_id='45e0c477d3e5ea92aa8d85c0d8f3e25c'), self.output(stdout)) def test_success_custom_ip_port(self): + urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ())) http_method = self.respond_with(200, self.default_response) stdout = MagicMock() - openMock = MagicMock(return_value=1) + open_mock = MagicMock(return_value=1) cli_parameters = ' --ip 127.0.1.1 --port 9006' - with patch('requests.post', http_method), patch('sys.stdout', stdout), patch('builtins.open', openMock): + with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock),\ + patch('requests.post', http_method), \ + patch('sys.stdout', stdout), \ + patch('builtins.open', open_mock): args = self.default_args.copy() args.update({'cli_parameters': cli_parameters}) conduct_load.load(MagicMock(**args)) - openMock.assert_called_with(self.bundle_file, 'rb') + open_mock.assert_called_with(self.bundle_file, 'rb') http_method.assert_called_with(self.default_url, files=self.default_files) self.assertEqual( @@ -127,22 +150,26 @@ class TestConductLoadCommand(TestCase, CliTestCase): self.output(stdout)) def test_success_with_configuration(self): - http_method = self.respond_with(200, self.default_response) - stdout = MagicMock() - openMock = MagicMock(return_value=1) - tmpdir, config_file = create_temp_bundle_with_contents({ 'bundle.conf': '{name="overlaid-name"}', 'config.sh': 'echo configuring' }) - with patch('requests.post', http_method), patch('sys.stdout', stdout), patch('builtins.open', openMock): + urlretrieve_mock = MagicMock(side_effect=[(self.bundle_file, ()), (config_file, ())]) + http_method = self.respond_with(200, self.default_response) + stdout = MagicMock() + open_mock = MagicMock(return_value=1) + + with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \ + patch('requests.post', http_method), \ + patch('sys.stdout', stdout), \ + patch('builtins.open', open_mock): args = self.default_args.copy() args.update({'configuration': config_file}) conduct_load.load(MagicMock(**args)) self.assertEqual( - openMock.call_args_list, + open_mock.call_args_list, [call(self.bundle_file, 'rb'), call(config_file, 'rb')] ) @@ -150,17 +177,21 @@ class TestConductLoadCommand(TestCase, CliTestCase): expected_files[4] = ('bundleName', 'overlaid-name') http_method.assert_called_with(self.default_url, files=expected_files) - self.assertEqual(self.default_output(), self.output(stdout)) + self.assertEqual(self.default_output(downloading_configuration='Retrieving configuration...\n'), self.output(stdout)) def test_failure(self): + urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ())) http_method = self.respond_with(404) stderr = MagicMock() - openMock = MagicMock(return_value=1) + open_mock = MagicMock(return_value=1) - with patch('requests.post', http_method), patch('sys.stderr', stderr), patch('builtins.open', openMock): + with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \ + patch('requests.post', http_method), \ + patch('sys.stderr', stderr), \ + patch('builtins.open', open_mock): conduct_load.load(MagicMock(**self.default_args)) - openMock.assert_called_with(self.bundle_file, 'rb') + open_mock.assert_called_with(self.bundle_file, 'rb') http_method.assert_called_with(self.default_url, files=self.default_files) self.assertEqual( @@ -169,14 +200,18 @@ class TestConductLoadCommand(TestCase, CliTestCase): self.output(stderr)) def test_failure_invalid_address(self): + urlretrieve_mock = MagicMock(return_value=(self.bundle_file, ())) http_method = self.raise_connection_error('test reason') stderr = MagicMock() - openMock = MagicMock(return_value=1) + open_mock = MagicMock(return_value=1) - with patch('requests.post', http_method), patch('sys.stderr', stderr), patch('builtins.open', openMock): + with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), \ + patch('requests.post', http_method), \ + patch('sys.stderr', stderr), \ + patch('builtins.open', open_mock): conduct_load.load(MagicMock(**self.default_args)) - openMock.assert_called_with(self.bundle_file, 'rb') + open_mock.assert_called_with(self.bundle_file, 'rb') http_method.assert_called_with(self.default_url, files=self.default_files) self.assertEqual( @@ -295,9 +330,10 @@ class TestConductLoadCommand(TestCase, CliTestCase): shutil.rmtree(tmpdir) def test_failure_no_bundle(self): + urlretrieve_mock = MagicMock(side_effect=URLError('no_such.bundle')) stderr = MagicMock() - with patch('sys.stderr', stderr): + with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), patch('sys.stderr', stderr): args = self.default_args.copy() args.update({'bundle': 'no_such.bundle'}) conduct_load.load(MagicMock(**args)) @@ -308,9 +344,11 @@ class TestConductLoadCommand(TestCase, CliTestCase): self.output(stderr)) def test_failure_no_configuration(self): + urlretrieve_mock = MagicMock(side_effect=[(self.bundle_file, ()), URLError('no_such.conf')]) + stderr = MagicMock() - with patch('sys.stderr', stderr): + with patch('conductr_cli.conduct_load.urlretrieve', urlretrieve_mock), patch('sys.stderr', stderr): args = self.default_args.copy() args.update({'configuration': 'no_such.conf'}) conduct_load.load(MagicMock(**args))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 10 }
0.13
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
argcomplete==3.6.1 certifi==2025.1.31 charset-normalizer==3.4.1 -e git+https://github.com/typesafehub/conductr-cli.git@171c9dc9c17827b586d3002ba49186e5653f37bf#egg=conductr_cli exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work idna==3.10 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pyhocon==0.2.1 pyparsing==2.0.3 pytest @ file:///croot/pytest_1738938843180/work requests==2.32.3 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work urllib3==2.3.0
name: conductr-cli channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argcomplete==3.6.1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - idna==3.10 - pyhocon==0.2.1 - pyparsing==2.0.3 - requests==2.32.3 - urllib3==2.3.0 prefix: /opt/conda/envs/conductr-cli
[ "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_invalid_address", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_bundle", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_configuration", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_custom_ip_port", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_long_ids", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_verbose", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_with_configuration" ]
[]
[ "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_disk_space", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_memory", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_nr_of_cpus", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_roles", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_roles_not_a_list" ]
[]
Apache License 2.0
117
3,259
[ "conductr_cli/bundle_utils.py", "conductr_cli/conduct.py", "conductr_cli/conduct_info.py", "conductr_cli/conduct_load.py", "conductr_cli/conduct_logging.py", "conductr_cli/conduct_run.py", "conductr_cli/conduct_services.py", "conductr_cli/conduct_stop.py", "conductr_cli/conduct_unload.py", "conductr_cli/conduct_version.py" ]
falconry__falcon-538
0af00afd67d92dbf9c6a721d0a1d1218408c1eb7
2015-05-01 23:38:20
b78ffaac7c412d3b3d6cd3c70dd05024d79d2cce
diff --git a/falcon/routing/compiled.py b/falcon/routing/compiled.py index 1a2f903..79a7bac 100644 --- a/falcon/routing/compiled.py +++ b/falcon/routing/compiled.py @@ -29,74 +29,6 @@ class CompiledRouter(object): tree for each look-up, it generates inlined, bespoke Python code to perform the search, then compiles that code. This makes the route processing quite fast. - - The generated code looks something like this:: - - def find(path, return_values, expressions, params): - path_len = len(path) - if path_len > 0: - if path[0] == "repos": - if path_len > 1: - params["org"] = path[1] - if path_len > 2: - params["repo"] = path[2] - if path_len > 3: - if path[3] == "commits": - return return_values[3] - if path[3] == "compare": - if path_len > 4: - match = expressions[0].match(path[4]) - if match is not None: - params.update(match.groupdict()) - if path_len > 5: - if path[5] == "full": - return return_values[5] - if path[5] == "part": - return return_values[6] - return None - return return_values[4] - if path[4] == "all": - return return_values[7] - match = expressions[1].match(path[4]) - if match is not None: - params.update(match.groupdict()) - if path_len > 5: - if path[5] == "full": - return return_values[9] - return None - return return_values[8] - return None - return None - return None - return return_values[2] - return return_values[1] - return return_values[0] - if path[0] == "teams": - if path_len > 1: - params["id"] = path[1] - if path_len > 2: - if path[2] == "members": - return return_values[11] - return None - return return_values[10] - return None - if path[0] == "user": - if path_len > 1: - if path[1] == "memberships": - return return_values[12] - return None - return None - if path[0] == "emojis": - if path_len > 1: - if path[1] == "signs": - if path_len > 2: - params["id"] = path[2] - return return_values[14] - return None - return None - return return_values[13] - return None - return None """ def __init__(self): @@ -125,6 +57,7 @@ class CompiledRouter(object): if node.matches(segment): path_index += 1 if path_index == len(path): + # NOTE(kgriffs): Override previous node node.method_map = method_map node.resource = resource else: @@ -179,6 +112,10 @@ class CompiledRouter(object): level_indent = indent found_simple = False + # NOTE(kgriffs): Sort static nodes before var nodes so that + # none of them get masked. False sorts before True. + nodes = sorted(nodes, key=lambda node: node.is_var) + for node in nodes: if node.is_var: if node.is_complex: @@ -225,7 +162,13 @@ class CompiledRouter(object): if node.resource is None: line('return None') else: - line('return return_values[%d]' % resource_idx) + # NOTE(kgriffs): Make sure that we have consumed all of + # the segments for the requested route; otherwise we could + # mistakenly match "/foo/23/bar" against "/foo/{id}". + line('if path_len == %d:' % (level + 1)) + line('return return_values[%d]' % resource_idx, 1) + + line('return None') indent = level_indent @@ -326,7 +269,7 @@ class CompiledRouterNode(object): # # simple, simple ==> True # simple, complex ==> True - # simple, string ==> True + # simple, string ==> False # complex, simple ==> True # complex, complex ==> False # complex, string ==> False @@ -334,7 +277,6 @@ class CompiledRouterNode(object): # string, complex ==> False # string, string ==> False # - other = CompiledRouterNode(segment) if self.is_var: @@ -352,10 +294,13 @@ class CompiledRouterNode(object): # /foo/{thing1} # /foo/{thing2} # - # or + # On the other hand, this is OK: # # /foo/{thing1} # /foo/all - return True + # + return other.is_var + # NOTE(kgriffs): If self is a static string match, then all the cases + # for other are False, so no need to check. return False
URI template conflicts after router update I have been abusing the route order a bit, and would like to know if there is a way to do this with the new router, or if this is actually a bug. ```python application = falcon.API() application.add_route('/action1', Action1Handler()) application.add_route('/action2', Action2Handler()) application.add_route('/action3', Action3Handler()) application.add_route('/{action}', ActionFallbackHandler()) ``` I realize this is probably a strange use case, and I could move the top 3 handlers into the bottom one and just relay the requests to the various other handlers, but this way seems cleaner.
falconry/falcon
diff --git a/tests/test_default_router.py b/tests/test_default_router.py index cb14489..8e3b518 100644 --- a/tests/test_default_router.py +++ b/tests/test_default_router.py @@ -7,6 +7,9 @@ class ResourceWithId(object): def __init__(self, resource_id): self.resource_id = resource_id + def __repr__(self): + return 'ResourceWithId({0})'.format(self.resource_id) + def on_get(self, req, resp): resp.body = self.resource_id @@ -36,19 +39,33 @@ def setup_routes(router_interface): {}, ResourceWithId(10)) router_interface.add_route( '/repos/{org}/{repo}/compare/all', {}, ResourceWithId(11)) + + # NOTE(kgriffs): The ordering of these calls is significant; we + # need to test that the {id} field does not match the other routes, + # regardless of the order they are added. router_interface.add_route( '/emojis/signs/0', {}, ResourceWithId(12)) router_interface.add_route( '/emojis/signs/{id}', {}, ResourceWithId(13)) + router_interface.add_route( + '/emojis/signs/42', {}, ResourceWithId(14)) + router_interface.add_route( + '/emojis/signs/42/small', {}, ResourceWithId(14.1)) + router_interface.add_route( + '/emojis/signs/78/small', {}, ResourceWithId(14.1)) + router_interface.add_route( '/repos/{org}/{repo}/compare/{usr0}:{branch0}...{usr1}:{branch1}/part', - {}, ResourceWithId(14)) + {}, ResourceWithId(15)) router_interface.add_route( '/repos/{org}/{repo}/compare/{usr0}:{branch0}', - {}, ResourceWithId(15)) + {}, ResourceWithId(16)) router_interface.add_route( '/repos/{org}/{repo}/compare/{usr0}:{branch0}/full', - {}, ResourceWithId(16)) + {}, ResourceWithId(17)) + + router_interface.add_route( + '/gists/{id}/raw', {}, ResourceWithId(18)) @ddt.ddt @@ -61,14 +78,23 @@ class TestStandaloneRouter(testing.TestBase): @ddt.data( '/teams/{collision}', '/repos/{org}/{repo}/compare/{simple-collision}', - '/emojis/signs/1', + '/emojis/signs/{id_too}', ) def test_collision(self, template): self.assertRaises( ValueError, - self.router.add_route, template, {}, ResourceWithId(6) + self.router.add_route, template, {}, ResourceWithId(-1) ) + def test_dump(self): + print(self.router._src) + + def test_override(self): + self.router.add_route('/emojis/signs/0', {}, ResourceWithId(-1)) + + resource, method_map, params = self.router.find('/emojis/signs/0') + self.assertEqual(resource.resource_id, -1) + def test_missing(self): resource, method_map, params = self.router.find('/this/does/not/exist') self.assertIs(resource, None) @@ -90,17 +116,24 @@ class TestStandaloneRouter(testing.TestBase): resource, method_map, params = self.router.find('/emojis/signs/1') self.assertEqual(resource.resource_id, 13) - def test_dead_segment(self): - resource, method_map, params = self.router.find('/teams') - self.assertIs(resource, None) + resource, method_map, params = self.router.find('/emojis/signs/42') + self.assertEqual(resource.resource_id, 14) - resource, method_map, params = self.router.find('/emojis/signs') - self.assertIs(resource, None) + resource, method_map, params = self.router.find('/emojis/signs/42/small') + self.assertEqual(resource.resource_id, 14.1) - resource, method_map, params = self.router.find('/emojis/signs/stop') - self.assertEqual(params, { - 'id': 'stop', - }) + resource, method_map, params = self.router.find('/emojis/signs/1/small') + self.assertEqual(resource, None) + + @ddt.data( + '/teams', + '/emojis/signs', + '/gists', + '/gists/42', + ) + def test_dead_segment(self, template): + resource, method_map, params = self.router.find(template) + self.assertIs(resource, None) def test_malformed_pattern(self): resource, method_map, params = self.router.find( @@ -120,6 +153,16 @@ class TestStandaloneRouter(testing.TestBase): self.assertEqual(resource.resource_id, 6) self.assertEqual(params, {'id': '42'}) + resource, method_map, params = self.router.find('/emojis/signs/stop') + self.assertEqual(params, {'id': 'stop'}) + + resource, method_map, params = self.router.find('/gists/42/raw') + self.assertEqual(params, {'id': '42'}) + + def test_subsegment_not_found(self): + resource, method_map, params = self.router.find('/emojis/signs/0/x') + self.assertIs(resource, None) + def test_multivar(self): resource, method_map, params = self.router.find( '/repos/racker/falcon/commits') @@ -131,7 +174,7 @@ class TestStandaloneRouter(testing.TestBase): self.assertEqual(resource.resource_id, 11) self.assertEqual(params, {'org': 'racker', 'repo': 'falcon'}) - @ddt.data(('', 5), ('/full', 10), ('/part', 14)) + @ddt.data(('', 5), ('/full', 10), ('/part', 15)) @ddt.unpack def test_complex(self, url_postfix, resource_id): uri = '/repos/racker/falcon/compare/johndoe:master...janedoe:dev' @@ -147,7 +190,7 @@ class TestStandaloneRouter(testing.TestBase): 'branch1': 'dev' }) - @ddt.data(('', 15), ('/full', 16)) + @ddt.data(('', 16), ('/full', 17)) @ddt.unpack def test_complex_alt(self, url_postfix, resource_id): uri = '/repos/falconry/falcon/compare/johndoe:master'
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "coverage", "ddt", "pyyaml", "requests", "testtools", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///croot/attrs_1668696182826/work certifi @ file:///croot/certifi_1671487769961/work/certifi charset-normalizer==3.4.1 coverage==7.2.7 ddt==1.7.2 -e git+https://github.com/falconry/falcon.git@0af00afd67d92dbf9c6a721d0a1d1218408c1eb7#egg=falcon flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core idna==3.10 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work nose==1.3.7 packaging @ file:///croot/packaging_1671697413597/work pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pytest==7.1.2 python-mimeparse==1.6.0 PyYAML==6.0.1 requests==2.31.0 six==1.17.0 testtools==2.7.1 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work typing_extensions @ file:///croot/typing_extensions_1669924550328/work urllib3==2.0.7 zipp @ file:///croot/zipp_1672387121353/work
name: falcon channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=22.1.0=py37h06a4308_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - flit-core=3.6.0=pyhd3eb1b0_0 - importlib-metadata=4.11.3=py37h06a4308_0 - importlib_metadata=4.11.3=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=22.0=py37h06a4308_0 - pip=22.3.1=py37h06a4308_0 - pluggy=1.0.0=py37h06a4308_1 - py=1.11.0=pyhd3eb1b0_0 - pytest=7.1.2=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py37h06a4308_0 - typing_extensions=4.4.0=py37h06a4308_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zipp=3.11.0=py37h06a4308_0 - zlib=1.2.13=h5eee18b_1 - pip: - charset-normalizer==3.4.1 - coverage==7.2.7 - ddt==1.7.2 - idna==3.10 - nose==1.3.7 - python-mimeparse==1.6.0 - pyyaml==6.0.1 - requests==2.31.0 - six==1.17.0 - testtools==2.7.1 - urllib3==2.0.7 prefix: /opt/conda/envs/falcon
[ "tests/test_default_router.py::TestStandaloneRouter::test_collision_1__teams__collision_", "tests/test_default_router.py::TestStandaloneRouter::test_collision_2__repos__org___repo__compare__simple_collision_", "tests/test_default_router.py::TestStandaloneRouter::test_collision_3__emojis_signs__id_too_", "tests/test_default_router.py::TestStandaloneRouter::test_complex_1______5_", "tests/test_default_router.py::TestStandaloneRouter::test_complex_2____full___10_", "tests/test_default_router.py::TestStandaloneRouter::test_complex_3____part___15_", "tests/test_default_router.py::TestStandaloneRouter::test_complex_alt_1______16_", "tests/test_default_router.py::TestStandaloneRouter::test_complex_alt_2____full___17_", "tests/test_default_router.py::TestStandaloneRouter::test_dead_segment_1__teams", "tests/test_default_router.py::TestStandaloneRouter::test_dead_segment_2__emojis_signs", "tests/test_default_router.py::TestStandaloneRouter::test_dead_segment_3__gists", "tests/test_default_router.py::TestStandaloneRouter::test_dead_segment_4__gists_42", "tests/test_default_router.py::TestStandaloneRouter::test_dump", "tests/test_default_router.py::TestStandaloneRouter::test_literal", "tests/test_default_router.py::TestStandaloneRouter::test_literal_segment", "tests/test_default_router.py::TestStandaloneRouter::test_malformed_pattern", "tests/test_default_router.py::TestStandaloneRouter::test_missing", "tests/test_default_router.py::TestStandaloneRouter::test_multivar", "tests/test_default_router.py::TestStandaloneRouter::test_override", "tests/test_default_router.py::TestStandaloneRouter::test_subsegment_not_found", "tests/test_default_router.py::TestStandaloneRouter::test_variable" ]
[]
[]
[]
Apache License 2.0
118
1,298
[ "falcon/routing/compiled.py" ]
mkdocs__mkdocs-497
aa7dd95813f49ad187111af387fa3f427720184b
2015-05-05 05:36:38
463c5b647e9ce5992b519708a0b9c4cba891d65c
diff --git a/mkdocs/build.py b/mkdocs/build.py index 86617977..1bc2c318 100644 --- a/mkdocs/build.py +++ b/mkdocs/build.py @@ -10,9 +10,8 @@ from jinja2.exceptions import TemplateNotFound from six.moves.urllib.parse import urljoin import jinja2 import json -import markdown -from mkdocs import nav, search, toc, utils +from mkdocs import nav, search, utils from mkdocs.relative_path_ext import RelativePathExtension import mkdocs @@ -39,19 +38,8 @@ def convert_markdown(markdown_source, site_navigation=None, extensions=(), stric builtin_extensions = ['meta', 'toc', 'tables', 'fenced_code'] mkdocs_extensions = [RelativePathExtension(site_navigation, strict), ] extensions = utils.reduce_list(builtin_extensions + mkdocs_extensions + user_extensions) - md = markdown.Markdown( - extensions=extensions, - extension_configs=extension_configs - ) - html_content = md.convert(markdown_source) - - # On completely blank markdown files, no Meta or tox properties are added - # to the generated document. - meta = getattr(md, 'Meta', {}) - toc_html = getattr(md, 'toc', '') - # Post process the generated table of contents into a data structure - table_of_contents = toc.TableOfContents(toc_html) + html_content, table_of_contents, meta = utils.convert_markdown(markdown_source, extensions, extension_configs) return (html_content, table_of_contents, meta) diff --git a/mkdocs/nav.py b/mkdocs/nav.py index 1b8c6c48..85d33513 100644 --- a/mkdocs/nav.py +++ b/mkdocs/nav.py @@ -15,18 +15,37 @@ from mkdocs import utils, exceptions log = logging.getLogger(__name__) -def filename_to_title(filename): +def file_to_title(filename): """ Automatically generate a default title, given a filename. + + The method parses the file to check for a title, uses the filename + as a title otherwise. """ if utils.is_homepage(filename): return 'Home' + try: + with open(filename, 'r') as f: + lines = f.read() + _, table_of_contents, meta = utils.convert_markdown(lines, ['meta', 'toc']) + if "title" in meta: + return meta["title"][0] + if len(table_of_contents.items) > 0: + return table_of_contents.items[0].title + except IOError: + # File couldn't be found - use filename as the title + # this is used in tests. We use the filename as the title + # in that case + pass + + # No title found in the document, using the filename title = os.path.splitext(filename)[0] title = title.replace('-', ' ').replace('_', ' ') - # Captialize if the filename was all lowercase, otherwise leave it as-is. + # Capitalize if the filename was all lowercase, otherwise leave it as-is. if title.lower() == title: title = title.capitalize() + return title @@ -220,18 +239,18 @@ def _generate_site_navigation(pages_config, url_context, use_directory_urls=True # then lets automatically nest it. if title is None and child_title is None and os.path.sep in path: filename = path.split(os.path.sep)[-1] - child_title = filename_to_title(filename) + child_title = file_to_title(filename) if title is None: filename = path.split(os.path.sep)[0] - title = filename_to_title(filename) + title = file_to_title(filename) # If we don't have a child title but the other title is the same, we # should be within a section and the child title needs to be inferred # from the filename. if len(nav_items) and title == nav_items[-1].title == title and child_title is None: filename = path.split(os.path.sep)[-1] - child_title = filename_to_title(filename) + child_title = file_to_title(filename) url = utils.get_url_path(path, use_directory_urls) diff --git a/mkdocs/utils.py b/mkdocs/utils.py index 67e4356d..9149ec09 100644 --- a/mkdocs/utils.py +++ b/mkdocs/utils.py @@ -9,9 +9,15 @@ and structure of the site and pages in the site. import os import shutil +import markdown +import logging +from mkdocs import toc from six.moves.urllib.parse import urlparse from six.moves.urllib.request import pathname2url + +log = logging.getLogger(__name__) + try: from collections import OrderedDict import yaml @@ -272,6 +278,34 @@ def path_to_url(path): return pathname2url(path) +def convert_markdown(markdown_source, extensions=None, extension_configs=None): + """ + Convert the Markdown source file to HTML content, and additionally + return the parsed table of contents, and a dictionary of any metadata + that was specified in the Markdown file. + `extensions` is an optional sequence of Python Markdown extensions to add + to the default set. + """ + extensions = extensions or [] + extension_configs = extension_configs or {} + + md = markdown.Markdown( + extensions=extensions, + extension_configs=extension_configs + ) + html_content = md.convert(markdown_source) + + # On completely blank markdown files, no Meta or tox properties are added + # to the generated document. + meta = getattr(md, 'Meta', {}) + toc_html = getattr(md, 'toc', '') + + # Post process the generated table of contents into a data structure + table_of_contents = toc.TableOfContents(toc_html) + + return (html_content, table_of_contents, meta) + + def get_theme_names(): """Return a list containing all the names of all the builtin themes."""
If no title is provided in the mkdocs.yml use the title in the markdown file As per the title, this came up in #308 but it's something I've wanted for a while.
mkdocs/mkdocs
diff --git a/mkdocs/tests/nav_tests.py b/mkdocs/tests/nav_tests.py index cdd2bf9f..90fc4469 100644 --- a/mkdocs/tests/nav_tests.py +++ b/mkdocs/tests/nav_tests.py @@ -348,3 +348,16 @@ class SiteNavigationTests(unittest.TestCase): for page, expected_ancestor in zip(site_navigation.pages, ancestors): self.assertEqual(page.ancestors, expected_ancestor) + + def test_file_to_tile(self): + title = nav.file_to_title("mkdocs/tests/resources/empty.md") + self.assertEqual(title, "Mkdocs/tests/resources/empty") + + title = nav.file_to_title("mkdocs/tests/resources/with_title.md") + self.assertEqual(title, "Title") + + title = nav.file_to_title("mkdocs/tests/resources/title_metadata.md") + self.assertEqual(title, "Metadata Title") + + title = nav.file_to_title("mkdocs/tests/resources/no_title_metadata.md") + self.assertEqual(title, "Title") diff --git a/mkdocs/tests/resources/empty.md b/mkdocs/tests/resources/empty.md new file mode 100644 index 00000000..f208f991 --- /dev/null +++ b/mkdocs/tests/resources/empty.md @@ -0,0 +1,1 @@ +There's no title in this file. diff --git a/mkdocs/tests/resources/no_title_metadata.md b/mkdocs/tests/resources/no_title_metadata.md new file mode 100644 index 00000000..af50b648 --- /dev/null +++ b/mkdocs/tests/resources/no_title_metadata.md @@ -0,0 +1,4 @@ +author: I have no title in metadata + +# Title + diff --git a/mkdocs/tests/resources/title_metadata.md b/mkdocs/tests/resources/title_metadata.md new file mode 100644 index 00000000..dd4c6f02 --- /dev/null +++ b/mkdocs/tests/resources/title_metadata.md @@ -0,0 +1,4 @@ +title: Metadata Title + +# Title + diff --git a/mkdocs/tests/resources/with_title.md b/mkdocs/tests/resources/with_title.md new file mode 100644 index 00000000..e7f1dc2f --- /dev/null +++ b/mkdocs/tests/resources/with_title.md @@ -0,0 +1,2 @@ +# Title +
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 3 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/project.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
click==8.1.8 exceptiongroup==1.2.2 ghp-import==2.1.0 importlib_metadata==8.6.1 iniconfig==2.1.0 Jinja2==3.1.6 livereload==2.7.1 Markdown==3.7 MarkupSafe==3.0.2 -e git+https://github.com/mkdocs/mkdocs.git@aa7dd95813f49ad187111af387fa3f427720184b#egg=mkdocs mock==5.2.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 PyYAML==6.0.2 six==1.17.0 tomli==2.2.1 tornado==6.4.2 zipp==3.21.0
name: mkdocs channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - click==8.1.8 - exceptiongroup==1.2.2 - ghp-import==2.1.0 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jinja2==3.1.6 - livereload==2.7.1 - markdown==3.7 - markupsafe==3.0.2 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - six==1.17.0 - tomli==2.2.1 - tornado==6.4.2 - zipp==3.21.0 prefix: /opt/conda/envs/mkdocs
[ "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_file_to_tile" ]
[]
[ "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_ancestors", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_base_url", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_empty_toc_item", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_generate_site_navigation_windows", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_indented_toc", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_indented_toc_missing_child_title", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_invalid_pages_config", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_nested_ungrouped_no_titles_windows", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_relative_md_links_have_slash", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_simple_toc", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_empty_toc", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_indented_toc", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_walk_simple_toc" ]
[]
BSD 2-Clause "Simplified" License
124
1,420
[ "mkdocs/build.py", "mkdocs/nav.py", "mkdocs/utils.py" ]
peterbe__premailer-124
f211f3f1bcfc87dc0318f056d319bb5575f62a72
2015-05-08 16:42:16
f211f3f1bcfc87dc0318f056d319bb5575f62a72
graingert: Use `if urlparse.urlparse(base_url).scheme:` peterbe: @graingert done. peterbe: @graingert I force-pushed a new commit message. Just for you :) graingert: Bling peterbe: So, @graingert you approve? What do you think @ewjoachim ? ewjoachim: Nothing to add, I'm ok.
diff --git a/premailer/premailer.py b/premailer/premailer.py index b53fc23..2d3a221 100644 --- a/premailer/premailer.py +++ b/premailer/premailer.py @@ -17,7 +17,7 @@ if sys.version_info >= (3,): # pragma: no cover # As in, Python 3 from io import StringIO from urllib.request import urlopen - from urllib.parse import urljoin + from urllib.parse import urljoin, urlparse STR_TYPE = str else: # Python 2 try: @@ -26,7 +26,7 @@ else: # Python 2 from StringIO import StringIO StringIO = StringIO # shut up pyflakes from urllib2 import urlopen - from urlparse import urljoin + from urlparse import urljoin, urlparse STR_TYPE = basestring import cssutils @@ -402,25 +402,23 @@ class Premailer(object): # URLs # if self.base_url: - if not self.base_url.endswith('/'): - self.base_url += '/' + if not urlparse(self.base_url).scheme: + raise ValueError('Base URL must start have a scheme') for attr in ('href', 'src'): for item in page.xpath("//@%s" % attr): parent = item.getparent() + url = parent.attrib[attr] if ( attr == 'href' and self.preserve_internal_links and - parent.attrib[attr].startswith('#') + url.startswith('#') ): continue if ( attr == 'src' and self.preserve_inline_attachments and - parent.attrib[attr].startswith('cid:') + url.startswith('cid:') ): continue - parent.attrib[attr] = urljoin( - self.base_url, - parent.attrib[attr].lstrip('/') - ) + parent.attrib[attr] = urljoin(self.base_url, url) if hasattr(self.html, "getroottree"): return root
Replacement of urls beginning with // When using a link whose href starts with "//", Premailer should just add http or https depending on the base url it uses. Currently, it replaces it with the full host, so ``//another.host/`` becomes ``http://my.base.host/another.host/``
peterbe/premailer
diff --git a/premailer/tests/test_premailer.py b/premailer/tests/test_premailer.py index ba63f85..4390a4e 100644 --- a/premailer/tests/test_premailer.py +++ b/premailer/tests/test_premailer.py @@ -478,7 +478,6 @@ class Tests(unittest.TestCase): </head> <body> <img src="/images/foo.jpg"> - <img src="/images/bar.gif"> <img src="http://www.googe.com/photos/foo.jpg"> <a href="/home">Home</a> <a href="http://www.peterbe.com">External</a> @@ -494,10 +493,9 @@ class Tests(unittest.TestCase): <title>Title</title> </head> <body> - <img src="http://kungfupeople.com/base/images/foo.jpg"> - <img src="http://kungfupeople.com/base/images/bar.gif"> + <img src="http://kungfupeople.com/images/foo.jpg"> <img src="http://www.googe.com/photos/foo.jpg"> - <a href="http://kungfupeople.com/base/home">Home</a> + <a href="http://kungfupeople.com/home">Home</a> <a href="http://www.peterbe.com">External</a> <a href="http://www.peterbe.com/base/">External 2</a> <a href="http://kungfupeople.com/base/subpage">Subpage</a> @@ -505,7 +503,7 @@ class Tests(unittest.TestCase): </body> </html>''' - p = Premailer(html, base_url='http://kungfupeople.com/base', + p = Premailer(html, base_url='http://kungfupeople.com/base/', preserve_internal_links=True) result_html = p.transform() @@ -2302,3 +2300,36 @@ sheet" type="text/css"> result_html = p.transform() compare_html(expect_html, result_html) + + def test_links_without_protocol(self): + """If you the base URL is set to https://example.com and your html + contains <img src="//otherdomain.com/">... then the URL to point to + is "https://otherdomain.com/" not "https://example.com/file.css" + """ + html = """<html> + <head> + </head> + <body> + <img src="//example.com"> + </body> + </html>""" + + expect_html = """<html> + <head> + </head> + <body> + <img src="{protocol}://example.com"> + </body> + </html>""" + + p = Premailer(html, base_url='https://www.peterbe.com') + result_html = p.transform() + compare_html(expect_html.format(protocol="https"), result_html) + + p = Premailer(html, base_url='http://www.peterbe.com') + result_html = p.transform() + compare_html(expect_html.format(protocol="http"), result_html) + + # Because you can't set a base_url without a full protocol + p = Premailer(html, base_url='www.peterbe.com') + assert_raises(ValueError, p.transform)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "lxml cssselect cssutils nose mock", "pip_packages": [ "nose", "mock", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cssselect @ file:///croot/cssselect_1707339882883/work cssutils @ file:///home/conda/feedstock_root/build_artifacts/cssutils_1734884840740/work exceptiongroup==1.2.2 iniconfig==2.1.0 lxml @ file:///croot/lxml_1737039601731/work mock @ file:///tmp/build/80754af9/mock_1607622725907/work nose @ file:///opt/conda/conda-bld/nose_1642704612149/work packaging==24.2 pluggy==1.5.0 -e git+https://github.com/peterbe/premailer.git@f211f3f1bcfc87dc0318f056d319bb5575f62a72#egg=premailer pytest==8.3.5 tomli==2.2.1
name: premailer channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - cssselect=1.2.0=py39h06a4308_0 - cssutils=2.11.0=pyhd8ed1ab_1 - icu=73.1=h6a678d5_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - libxml2=2.13.5=hfdd30dd_0 - libxslt=1.1.41=h097e994_0 - lxml=5.3.0=py39h57af460_1 - mock=4.0.3=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - nose=1.3.7=pyhd3eb1b0_1008 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/premailer
[ "premailer/tests/test_premailer.py::Tests::test_base_url_with_path", "premailer/tests/test_premailer.py::Tests::test_links_without_protocol" ]
[]
[ "premailer/tests/test_premailer.py::Tests::test_apple_newsletter_example", "premailer/tests/test_premailer.py::Tests::test_base_url_fixer", "premailer/tests/test_premailer.py::Tests::test_basic_html", "premailer/tests/test_premailer.py::Tests::test_basic_html_shortcut_function", "premailer/tests/test_premailer.py::Tests::test_basic_html_with_pseudo_selector", "premailer/tests/test_premailer.py::Tests::test_basic_xml", "premailer/tests/test_premailer.py::Tests::test_broken_xml", "premailer/tests/test_premailer.py::Tests::test_child_selector", "premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_argument", "premailer/tests/test_premailer.py::Tests::test_command_line_fileinput_from_stdin", "premailer/tests/test_premailer.py::Tests::test_command_line_preserve_style_tags", "premailer/tests/test_premailer.py::Tests::test_comments_in_media_queries", "premailer/tests/test_premailer.py::Tests::test_css_disable_basic_html_attributes", "premailer/tests/test_premailer.py::Tests::test_css_text", "premailer/tests/test_premailer.py::Tests::test_css_text_with_only_body_present", "premailer/tests/test_premailer.py::Tests::test_css_with_html_attributes", "premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_excluded", "premailer/tests/test_premailer.py::Tests::test_css_with_pseudoclasses_included", "premailer/tests/test_premailer.py::Tests::test_disabled_validator", "premailer/tests/test_premailer.py::Tests::test_doctype", "premailer/tests/test_premailer.py::Tests::test_empty_style_tag", "premailer/tests/test_premailer.py::Tests::test_external_links", "premailer/tests/test_premailer.py::Tests::test_external_links_unfindable", "premailer/tests/test_premailer.py::Tests::test_external_styles_and_links", "premailer/tests/test_premailer.py::Tests::test_external_styles_on_http", "premailer/tests/test_premailer.py::Tests::test_external_styles_on_https", "premailer/tests/test_premailer.py::Tests::test_external_styles_with_base_url", "premailer/tests/test_premailer.py::Tests::test_favour_rule_with_class_over_generic", "premailer/tests/test_premailer.py::Tests::test_favour_rule_with_element_over_generic", "premailer/tests/test_premailer.py::Tests::test_favour_rule_with_id_over_others", "premailer/tests/test_premailer.py::Tests::test_favour_rule_with_important_over_others", "premailer/tests/test_premailer.py::Tests::test_fontface_selectors_with_no_selectortext", "premailer/tests/test_premailer.py::Tests::test_ignore_some_external_stylesheets", "premailer/tests/test_premailer.py::Tests::test_ignore_some_incorrectly", "premailer/tests/test_premailer.py::Tests::test_ignore_some_inline_stylesheets", "premailer/tests/test_premailer.py::Tests::test_ignore_style_elements_with_media_attribute", "premailer/tests/test_premailer.py::Tests::test_include_star_selector", "premailer/tests/test_premailer.py::Tests::test_inline_wins_over_external", "premailer/tests/test_premailer.py::Tests::test_keyframe_selectors", "premailer/tests/test_premailer.py::Tests::test_last_child", "premailer/tests/test_premailer.py::Tests::test_last_child_exclude_pseudo", "premailer/tests/test_premailer.py::Tests::test_leftover_important", "premailer/tests/test_premailer.py::Tests::test_load_external_url", "premailer/tests/test_premailer.py::Tests::test_load_external_url_gzip", "premailer/tests/test_premailer.py::Tests::test_mailto_url", "premailer/tests/test_premailer.py::Tests::test_mediaquery", "premailer/tests/test_premailer.py::Tests::test_merge_styles_basic", "premailer/tests/test_premailer.py::Tests::test_merge_styles_non_trivial", "premailer/tests/test_premailer.py::Tests::test_merge_styles_with_class", "premailer/tests/test_premailer.py::Tests::test_mixed_pseudo_selectors", "premailer/tests/test_premailer.py::Tests::test_multiple_style_elements", "premailer/tests/test_premailer.py::Tests::test_multithreading", "premailer/tests/test_premailer.py::Tests::test_parse_style_rules", "premailer/tests/test_premailer.py::Tests::test_precedence_comparison", "premailer/tests/test_premailer.py::Tests::test_prefer_inline_to_class", "premailer/tests/test_premailer.py::Tests::test_shortcut_function", "premailer/tests/test_premailer.py::Tests::test_strip_important", "premailer/tests/test_premailer.py::Tests::test_style_attribute_specificity", "premailer/tests/test_premailer.py::Tests::test_style_block_with_external_urls", "premailer/tests/test_premailer.py::Tests::test_turnoff_cache_works_as_expected", "premailer/tests/test_premailer.py::Tests::test_type_test", "premailer/tests/test_premailer.py::Tests::test_xml_cdata" ]
[]
BSD 3-Clause "New" or "Revised" License
129
467
[ "premailer/premailer.py" ]
typesafehub__conductr-cli-57
357be15356b14f09069cf542e8a4765edd6a0d0a
2015-05-13 17:22:23
357be15356b14f09069cf542e8a4765edd6a0d0a
diff --git a/conductr_cli/conduct_load.py b/conductr_cli/conduct_load.py index 38bc3d8..982965d 100644 --- a/conductr_cli/conduct_load.py +++ b/conductr_cli/conduct_load.py @@ -19,11 +19,14 @@ def load(args): """`conduct load` command""" print('Retrieving bundle...') - bundle_file, bundle_headers = urlretrieve(get_url(args.bundle)) + bundle_name, bundle_url = get_url(args.bundle) + bundle_file, bundle_headers = urlretrieve(bundle_url) + + configuration_file, configuration_headers, configuration_name = (None, None, None) if args.configuration is not None: print('Retrieving configuration...') - configuration_file, configuration_headers = urlretrieve(get_url(args.configuration)) \ - if args.configuration is not None else (None, None) + configuration_name, configuration_url = get_url(args.configuration) + configuration_file, configuration_headers = urlretrieve(configuration_url) bundle_conf = ConfigFactory.parse_string(bundle_utils.conf(bundle_file)) overlay_bundle_conf = None if configuration_file is None else \ @@ -39,10 +42,10 @@ def load(args): ('roles', ' '.join(with_bundle_configurations(ConfigTree.get_list, 'roles'))), ('bundleName', with_bundle_configurations(ConfigTree.get_string, 'name')), ('system', with_bundle_configurations(ConfigTree.get_string, 'system')), - ('bundle', open(bundle_file, 'rb')) + ('bundle', (bundle_name, open(bundle_file, 'rb'))) ] if configuration_file is not None: - files.append(('configuration', open(configuration_file, 'rb'))) + files.append(('configuration', (configuration_name, open(configuration_file, 'rb')))) print('Loading bundle to ConductR...') response = requests.post(url, files=files) @@ -74,4 +77,5 @@ def get_url(uri): parsed = urlparse(uri, scheme='file') op = Path(uri) np = str(op.cwd() / op if parsed.scheme == 'file' and op.root == '' else parsed.path) - return urlunparse(ParseResult(parsed.scheme, parsed.netloc, np, parsed.params, parsed.query, parsed.fragment)) + url = urlunparse(ParseResult(parsed.scheme, parsed.netloc, np, parsed.params, parsed.query, parsed.fragment)) + return (url.split('/')[-1], url)
Unable to load bundle from https ConductR RC1, CLI 0.15 Loading a bundle via https hangs. The cli must be terminated. ```bash > conduct load https://github.com/typesafehub/project-doc/releases/download/1.0/project-doc-1.0-SNAPSHOT-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip Retrieving bundle... Retrieving configuration... Loading bundle to ConductR... ``` If I wget the bundle to the local file system, the bundle loads successfully.
typesafehub/conductr-cli
diff --git a/conductr_cli/test/test_conduct_load.py b/conductr_cli/test/test_conduct_load.py index b5503cb..93ee6f7 100644 --- a/conductr_cli/test/test_conduct_load.py +++ b/conductr_cli/test/test_conduct_load.py @@ -2,6 +2,7 @@ from unittest import TestCase from conductr_cli.test.cli_test_case import CliTestCase, create_temp_bundle, create_temp_bundle_with_contents, strip_margin from conductr_cli import conduct_load from urllib.error import URLError +import os import shutil try: @@ -54,7 +55,7 @@ class TestConductLoadCommand(TestCase, CliTestCase): ('roles', ' '.join(roles)), ('bundleName', bundleName), ('system', system), - ('bundle', 1) + ('bundle', ('bundle.zip', 1)) ] output_template = """|Retrieving bundle... @@ -177,7 +178,7 @@ class TestConductLoadCommand(TestCase, CliTestCase): [call(self.bundle_file, 'rb'), call(config_file, 'rb')] ) - expected_files = self.default_files + [('configuration', 1)] + expected_files = self.default_files + [('configuration', ('bundle.zip', 1))] expected_files[4] = ('bundleName', 'overlaid-name') http_method.assert_called_with(self.default_url, files=expected_files) @@ -361,3 +362,16 @@ class TestConductLoadCommand(TestCase, CliTestCase): strip_margin("""|ERROR: File not found: no_such.conf |"""), self.output(stderr)) + + +class TestGetUrl(TestCase): + + def test_url(self): + filename, url = conduct_load.get_url('https://site.com/bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip') + self.assertEqual('bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip', filename) + self.assertEqual('https://site.com/bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip', url) + + def test_file(self): + filename, url = conduct_load.get_url('bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip') + self.assertEqual('bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip', filename) + self.assertEqual('file://' + os.getcwd() + '/bundle-1.0-e78ed07d4a895e14595a21aef1bf616b1b0e4d886f3265bc7b152acf93d259b5.zip', url)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 1 }
0.15
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "flake8", "pep8-naming", "git+https://github.com/zheller/flake8-quotes#aef86c4f8388e790332757e5921047ad53160a75", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
argcomplete==3.6.1 certifi==2025.1.31 charset-normalizer==3.4.1 -e git+https://github.com/typesafehub/conductr-cli.git@357be15356b14f09069cf542e8a4765edd6a0d0a#egg=conductr_cli exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work flake8==7.2.0 flake8-quotes @ git+https://github.com/zheller/flake8-quotes@e75accbd40f0e1fa1e8f0e746b93c9766db8f106 idna==3.10 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mccabe==0.7.0 nose==1.3.7 packaging @ file:///croot/packaging_1734472117206/work pep8-naming==0.14.1 pluggy @ file:///croot/pluggy_1733169602837/work pycodestyle==2.13.0 pyflakes==3.3.1 pyhocon==0.2.1 pyparsing==2.0.3 pytest @ file:///croot/pytest_1738938843180/work requests==2.32.3 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work urllib3==2.3.0
name: conductr-cli channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argcomplete==3.6.1 - certifi==2025.1.31 - charset-normalizer==3.4.1 - flake8==7.2.0 - flake8-quotes==3.4.0 - idna==3.10 - mccabe==0.7.0 - nose==1.3.7 - pep8-naming==0.14.1 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pyhocon==0.2.1 - pyparsing==2.0.3 - requests==2.32.3 - urllib3==2.3.0 prefix: /opt/conda/envs/conductr-cli
[ "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_invalid_address", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_custom_ip_port", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_long_ids", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_verbose", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_success_with_configuration", "conductr_cli/test/test_conduct_load.py::TestGetUrl::test_file", "conductr_cli/test/test_conduct_load.py::TestGetUrl::test_url" ]
[]
[ "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_bundle", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_configuration", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_disk_space", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_memory", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_nr_of_cpus", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_no_roles", "conductr_cli/test/test_conduct_load.py::TestConductLoadCommand::test_failure_roles_not_a_list" ]
[]
Apache License 2.0
135
546
[ "conductr_cli/conduct_load.py" ]
pysmt__pysmt-114
4fd83af49e7784a874f57620809404d530929366
2015-05-17 17:12:04
689cc79ff2731837903b14daa266afc99b4feb21
diff --git a/pysmt/simplifier.py b/pysmt/simplifier.py index 418bc0d..3303577 100644 --- a/pysmt/simplifier.py +++ b/pysmt/simplifier.py @@ -445,7 +445,7 @@ class Simplifier(walkers.DagWalker): res = args[0].bv_unsigned_value() // args[1].bv_unsigned_value() res = res % 2**formula.bv_width() return self.manager.BV(res, width=formula.bv_width()) - return self.manager.BVUdiv(*args) + return self.manager.BVUDiv(*args) def walk_bv_urem(self, formula, args): if args[0].is_bv_constant() and args[1].is_bv_constant: @@ -454,7 +454,7 @@ class Simplifier(walkers.DagWalker): else: res = args[0].bv_unsigned_value() % args[1].bv_unsigned_value() return self.manager.BV(res, width=formula.bv_width()) - return self.manager.BVUrem(*args) + return self.manager.BVURem(*args) def walk_bv_ult(self, formula, args): if args[0].is_bv_constant() and args[1].is_bv_constant: @@ -506,7 +506,7 @@ class Simplifier(walkers.DagWalker): filler = bitstr[0] res = filler*formula.bv_extend_step() + bitstr return self.manager.BV(res, width=formula.bv_width()) - return self.manager.BVSext(args[0], formula.bv_extend_step()) + return self.manager.BVSExt(args[0], formula.bv_extend_step()) def walk_bv_zext(self, formula, args): if args[0].is_bv_constant(): @@ -517,7 +517,7 @@ class Simplifier(walkers.DagWalker): return self.manager.BVZExt(args[0], formula.bv_extend_step()) def walk_bv_concat(self, formula, args): - if args[0].is_bv_constant() and args[1].is_bv_constant: + if args[0].is_bv_constant() and args[1].is_bv_constant(): w0 = args[0].bv_width() w1 = args[1].bv_width() res = (2**w1) * args[0].bv_unsigned_value() + \ @@ -526,14 +526,14 @@ class Simplifier(walkers.DagWalker): return self.manager.BVConcat(*args) def walk_bv_lshl(self, formula, args): - if args[0].is_bv_constant() and args[1].is_bv_constant: + if args[0].is_bv_constant() and args[1].is_bv_constant(): res = args[0].bv_unsigned_value() << args[1].bv_unsigned_value() w = args[0].bv_width() return self.manager.BV(res % (2 ** w), w) return self.manager.BVLShl(*args) def walk_bv_lshr(self, formula, args): - if args[0].is_bv_constant() and args[1].is_bv_constant: + if args[0].is_bv_constant() and args[1].is_bv_constant(): res = args[0].bv_unsigned_value() >> args[1].bv_unsigned_value() w = args[0].bv_width() return self.manager.BV(res % (2 ** w), w) diff --git a/pysmt/walkers/identitydag.py b/pysmt/walkers/identitydag.py index 1fc1915..b422926 100644 --- a/pysmt/walkers/identitydag.py +++ b/pysmt/walkers/identitydag.py @@ -31,72 +31,135 @@ class IdentityDagWalker(DagWalker): DagWalker.__init__(self, env=env, invalidate_memoization=invalidate_memoization) + self.mgr = self.env.formula_manager def walk_symbol(self, formula, args): - return self.env.formula_manager.Symbol(formula.symbol_name(), + return self.mgr.Symbol(formula.symbol_name(), formula.symbol_type()) def walk_real_constant(self, formula, args): - return self.env.formula_manager.Real(formula.constant_value()) + return self.mgr.Real(formula.constant_value()) def walk_int_constant(self, formula, args): - return self.env.formula_manager.Int(formula.constant_value()) + return self.mgr.Int(formula.constant_value()) def walk_bool_constant(self, formula, args): - return self.env.formula_manager.Bool(formula.constant_value()) + return self.mgr.Bool(formula.constant_value()) def walk_and(self, formula, args): - return self.env.formula_manager.And(args) + return self.mgr.And(args) def walk_or(self, formula, args): - return self.env.formula_manager.Or(args) + return self.mgr.Or(args) def walk_not(self, formula, args): - return self.env.formula_manager.Not(args[0]) + return self.mgr.Not(*args) def walk_iff(self, formula, args): - return self.env.formula_manager.Iff(args[0], args[1]) + return self.mgr.Iff(*args) def walk_implies(self, formula, args): - return self.env.formula_manager.Implies(args[0], args[1]) + return self.mgr.Implies(*args) def walk_equals(self, formula, args): - return self.env.formula_manager.Equals(args[0], args[1]) + return self.mgr.Equals(*args) def walk_ite(self, formula, args): - return self.env.formula_manager.Ite(args[0], args[1], args[2]) + return self.mgr.Ite(*args) def walk_ge(self, formula, args): - return self.env.formula_manager.GE(args[0], args[1]) + return self.mgr.GE(*args) def walk_le(self, formula, args): - return self.env.formula_manager.LE(args[0], args[1]) + return self.mgr.LE(*args) def walk_gt(self, formula, args): - return self.env.formula_manager.GT(args[0], args[1]) + return self.mgr.GT(*args) def walk_lt(self, formula, args): - return self.env.formula_manager.LT(args[0], args[1]) + return self.mgr.LT(*args) def walk_forall(self, formula, args): qvars = [self.walk_symbol(v, None) for v in formula.quantifier_vars()] - return self.env.formula_manager.ForAll(qvars,args[0]) + return self.mgr.ForAll(qvars, *args) def walk_exists(self, formula, args): qvars = [self.walk_symbol(v, None) for v in formula.quantifier_vars()] - return self.env.formula_manager.Exists(qvars,args[0]) + return self.mgr.Exists(qvars, *args) def walk_plus(self, formula, args): - return self.env.formula_manager.Plus(args) + return self.mgr.Plus(args) def walk_times(self, formula, args): - return self.env.formula_manager.Times(args[0], args[1]) + return self.mgr.Times(*args) def walk_minus(self, formula, args): - return self.env.formula_manager.Minus(args[0], args[1]) + return self.mgr.Minus(*args) def walk_function(self, formula, args): - return self.env.formula_manager.Function(formula.function_name(), args) + return self.mgr.Function(formula.function_name(), args) def walk_toreal(self, formula, args): - return self.env.formula_manager.ToReal(args[0]) + return self.mgr.ToReal(*args) + + def walk_bv_constant(self, formula, args): + return self.mgr.BV(formula.constant_value(), formula.bv_width()) + + def walk_bv_and(self, formula, args): + return self.mgr.BVAnd(*args) + + def walk_bv_not(self, formula, args): + return self.mgr.BVNot(*args) + + def walk_bv_neg(self, formula, args): + return self.mgr.BVNeg(*args) + + def walk_bv_or(self, formula, args): + return self.mgr.BVOr(*args) + + def walk_bv_xor(self, formula, args): + return self.mgr.BVXor(*args) + + def walk_bv_add(self, formula, args): + return self.mgr.BVAdd(*args) + + def walk_bv_mul(self, formula, args): + return self.mgr.BVMul(*args) + + def walk_bv_udiv(self, formula, args): + return self.mgr.BVUDiv(*args) + + def walk_bv_urem(self, formula, args): + return self.mgr.BVURem(*args) + + def walk_bv_ult(self, formula, args): + return self.mgr.BVULT(*args) + + def walk_bv_ule(self, formula, args): + return self.mgr.BVULE(*args) + + def walk_bv_extract(self, formula, args): + return self.mgr.BVExtract(args[0], + start=formula.bv_extract_start(), + end=formula.bv_extract_end()) + + def walk_bv_ror(self, formula, args): + return self.mgr.BVRor(args[0], formula.bv_rotation_step()) + + def walk_bv_rol(self, formula, args): + return self.mgr.BVRol(args[0], formula.bv_rotation_step()) + + def walk_bv_sext(self, formula, args): + return self.mgr.BVSExt(args[0], formula.bv_extend_step()) + + def walk_bv_zext(self, formula, args): + return self.mgr.BVZExt(args[0], formula.bv_extend_step()) + + def walk_bv_concat(self, formula, args): + return self.mgr.BVConcat(*args) + + def walk_bv_lshl(self, formula, args): + return self.mgr.BVLShl(*args) + + def walk_bv_lshr(self, formula, args): + return self.mgr.BVLShr(*args)
IdentityDagWalker lacks BV support
pysmt/pysmt
diff --git a/pysmt/test/test_walkers.py b/pysmt/test/test_walkers.py index 22a96c7..6defb39 100644 --- a/pysmt/test/test_walkers.py +++ b/pysmt/test/test_walkers.py @@ -25,6 +25,7 @@ from pysmt.typing import INT, BOOL, REAL, FunctionType from pysmt.walkers import TreeWalker, DagWalker, IdentityDagWalker from pysmt.test import TestCase from pysmt.formula import FormulaManager +from pysmt.test.examples import get_example_formulae from six.moves import xrange @@ -100,7 +101,7 @@ class TestWalkers(TestCase): self.assertFalse(tree_walker.is_complete()) - def test_identity_walker(self): + def test_identity_walker_simple(self): def walk_and_to_or(formula, args, **kwargs): return Or(args) @@ -125,6 +126,11 @@ class TestWalkers(TestCase): result = walker.walk(alternation) self.assertEqual(result, expected) + def test_identity_dag_walker(self): + idw = IdentityDagWalker() + for (f, _, _, _) in get_example_formulae(): + rebuilt = idw.walk(f) + self.assertTrue(rebuilt == f, "Rebuilt formula is not identical") def test_substitution_on_quantifiers(self): x, y = FreshSymbol(), FreshSymbol()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 2 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 -e git+https://github.com/pysmt/pysmt.git@4fd83af49e7784a874f57620809404d530929366#egg=PySMT pytest==8.3.5 six==1.17.0 tomli==2.2.1
name: pysmt channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - six==1.17.0 - tomli==2.2.1 prefix: /opt/conda/envs/pysmt
[ "pysmt/test/test_walkers.py::TestWalkers::test_identity_dag_walker" ]
[]
[ "pysmt/test/test_walkers.py::TestWalkers::test_identity_walker_simple", "pysmt/test/test_walkers.py::TestWalkers::test_iterative_get_free_variables", "pysmt/test/test_walkers.py::TestWalkers::test_subst", "pysmt/test/test_walkers.py::TestWalkers::test_substituter_conditions", "pysmt/test/test_walkers.py::TestWalkers::test_substitution_complex", "pysmt/test/test_walkers.py::TestWalkers::test_substitution_on_functions", "pysmt/test/test_walkers.py::TestWalkers::test_substitution_on_quantifiers", "pysmt/test/test_walkers.py::TestWalkers::test_substitution_term", "pysmt/test/test_walkers.py::TestWalkers::test_undefined_node", "pysmt/test/test_walkers.py::TestWalkers::test_walker_is_complete" ]
[]
Apache License 2.0
142
2,449
[ "pysmt/simplifier.py", "pysmt/walkers/identitydag.py" ]
pre-commit__pre-commit-231
9515ca06378d74f1e4f8013db2b5230c1f15edaa
2015-05-18 19:48:14
9515ca06378d74f1e4f8013db2b5230c1f15edaa
asottile: @Lucas-C look correct? coveralls: [![Coverage Status](https://coveralls.io/builds/2591860/badge)](https://coveralls.io/builds/2591860) Coverage decreased (-0.04%) to 99.96% when pulling **b140f92cd7e20368b27d19ea01227402e71c294a on no_defaults_in_config_227** into **9515ca06378d74f1e4f8013db2b5230c1f15edaa on master**.
diff --git a/pre_commit/clientlib/validate_config.py b/pre_commit/clientlib/validate_config.py index bdd0e2c..e4a90a6 100644 --- a/pre_commit/clientlib/validate_config.py +++ b/pre_commit/clientlib/validate_config.py @@ -33,7 +33,7 @@ CONFIG_JSON_SCHEMA = { 'properties': { 'id': {'type': 'string'}, 'files': {'type': 'string'}, - 'exclude': {'type': 'string', 'default': '^$'}, + 'exclude': {'type': 'string'}, 'language_version': {'type': 'string'}, 'args': { 'type': 'array', @@ -71,7 +71,7 @@ def validate_config_extra(config): ) for hook in repo['hooks']: try_regex(repo, hook['id'], hook.get('files', ''), 'files') - try_regex(repo, hook['id'], hook['exclude'], 'exclude') + try_regex(repo, hook['id'], hook.get('exclude', ''), 'exclude') load_config = get_validator( diff --git a/pre_commit/clientlib/validate_manifest.py b/pre_commit/clientlib/validate_manifest.py index 283d7c4..4295014 100644 --- a/pre_commit/clientlib/validate_manifest.py +++ b/pre_commit/clientlib/validate_manifest.py @@ -20,6 +20,7 @@ MANIFEST_JSON_SCHEMA = { 'name': {'type': 'string'}, 'description': {'type': 'string', 'default': ''}, 'entry': {'type': 'string'}, + 'exclude': {'type': 'string', 'default': '^$'}, 'language': {'type': 'string'}, 'language_version': {'type': 'string', 'default': 'default'}, 'files': {'type': 'string'}, @@ -52,8 +53,14 @@ def validate_files(hook_config): if not is_regex_valid(hook_config['files']): raise InvalidManifestError( 'Invalid files regex at {0}: {1}'.format( - hook_config['id'], - hook_config['files'], + hook_config['id'], hook_config['files'], + ) + ) + + if not is_regex_valid(hook_config.get('exclude', '')): + raise InvalidManifestError( + 'Invalid exclude regex at {0}: {1}'.format( + hook_config['id'], hook_config['exclude'], ) )
Bug: base manifest value for 'exclude' is always ignored I stumbled upon this bug while working on #226: the culprit is [`Repository.hooks`](https://github.com/pre-commit/pre-commit/blob/master/pre_commit/repository.py#L48). A quick fix for this would be to simply remove the default value from `pre_commit/clientlib/validate_config.py`, but the root cause is that any default value defined for a field in this file will make the corresponding manifest field useless. Basically here is what happens in `Repository.hooks`: - all the hooks defined in the current repository are enumerated - at this stage, a `hook` is a dict closely matching the Yaml the config file content, **plus** default values for fields not defined in the Yaml but having a JSON schema 'default' - when doing the dict merge, **every** (key,value) pair in `hook` overrides the corresponding manifest entry. This includes default config value like `exclude: '$^'` overriding a base manifest value like `exclude: '.bak$'` Hence I suggest either adding a test ensuring there will never be any 'default' defined in `CONFIG_JSON_SCHEMA`, or improving the merge logic.
pre-commit/pre-commit
diff --git a/tests/clientlib/validate_config_test.py b/tests/clientlib/validate_config_test.py index c507f28..b474f1b 100644 --- a/tests/clientlib/validate_config_test.py +++ b/tests/clientlib/validate_config_test.py @@ -174,3 +174,23 @@ def test_config_with_local_hooks_definition_passes(config_obj): jsonschema.validate(config_obj, CONFIG_JSON_SCHEMA) config = apply_defaults(config_obj, CONFIG_JSON_SCHEMA) validate_config_extra(config) + + +def test_does_not_contain_defaults(): + """Due to the way our merging works, if this schema has any defaults they + will clobber potentially useful values in the backing manifest. #227 + """ + to_process = [(CONFIG_JSON_SCHEMA, ())] + while to_process: + schema, route = to_process.pop() + # Check this value + if isinstance(schema, dict): + if 'default' in schema: + raise AssertionError( + 'Unexpected default in schema at {0}'.format( + ' => '.join(route), + ) + ) + + for key, value in schema.items(): + to_process.append((value, route + (key,))) diff --git a/tests/clientlib/validate_manifest_test.py b/tests/clientlib/validate_manifest_test.py index 5e5690e..937f432 100644 --- a/tests/clientlib/validate_manifest_test.py +++ b/tests/clientlib/validate_manifest_test.py @@ -46,6 +46,9 @@ def test_additional_manifest_check_passing(obj): [{'id': 'a', 'language': 'not a language', 'files': ''}], [{'id': 'a', 'language': 'python3', 'files': ''}], [{'id': 'a', 'language': 'python', 'files': 'invalid regex('}], + [{'id': 'a', 'language': 'not a language', 'files': ''}], + [{'id': 'a', 'language': 'python3', 'files': ''}], + [{'id': 'a', 'language': 'python', 'files': '', 'exclude': '('}], ), ) def test_additional_manifest_failing(obj): diff --git a/tests/manifest_test.py b/tests/manifest_test.py index ba30d42..39ecc74 100644 --- a/tests/manifest_test.py +++ b/tests/manifest_test.py @@ -22,6 +22,7 @@ def test_manifest_contents(manifest): 'args': [], 'description': '', 'entry': 'bin/hook.sh', + 'exclude': '^$', 'expected_return_value': 0, 'files': '', 'id': 'bash_hook', @@ -36,6 +37,7 @@ def test_hooks(manifest): 'args': [], 'description': '', 'entry': 'bin/hook.sh', + 'exclude': '^$', 'expected_return_value': 0, 'files': '', 'id': 'bash_hook',
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aspy.yaml==1.3.0 astroid==1.3.2 attrs==22.2.0 cached-property==1.5.2 certifi==2021.5.30 coverage==6.2 distlib==0.3.9 filelock==3.4.1 flake8==5.0.4 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 jsonschema==3.2.0 logilab-common==1.9.7 mccabe==0.7.0 mock==5.2.0 mypy-extensions==1.0.0 nodeenv==1.6.0 ordereddict==1.1 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 -e git+https://github.com/pre-commit/pre-commit.git@9515ca06378d74f1e4f8013db2b5230c1f15edaa#egg=pre_commit py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 pylint==1.3.1 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 PyYAML==6.0.1 simplejson==3.20.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 virtualenv==20.17.1 zipp==3.6.0
name: pre-commit channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - aspy-yaml==1.3.0 - astroid==1.3.2 - attrs==22.2.0 - cached-property==1.5.2 - coverage==6.2 - distlib==0.3.9 - filelock==3.4.1 - flake8==5.0.4 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jsonschema==3.2.0 - logilab-common==1.9.7 - mccabe==0.7.0 - mock==5.2.0 - mypy-extensions==1.0.0 - nodeenv==1.6.0 - ordereddict==1.1 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pylint==1.3.1 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pyyaml==6.0.1 - simplejson==3.20.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - virtualenv==20.17.1 - zipp==3.6.0 prefix: /opt/conda/envs/pre-commit
[ "tests/clientlib/validate_config_test.py::test_does_not_contain_defaults", "tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj5]" ]
[ "tests/clientlib/validate_config_test.py::test_run[input0-0]", "tests/clientlib/validate_config_test.py::test_run[input1-0]", "tests/clientlib/validate_manifest_test.py::test_run[input0-0]", "tests/clientlib/validate_manifest_test.py::test_run[input1-0]", "tests/manifest_test.py::test_manifest_contents", "tests/manifest_test.py::test_hooks" ]
[ "tests/clientlib/validate_config_test.py::test_run[input2-1]", "tests/clientlib/validate_config_test.py::test_run[input3-1]", "tests/clientlib/validate_config_test.py::test_run[input4-1]", "tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj0-False]", "tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj1-True]", "tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj2-True]", "tests/clientlib/validate_config_test.py::test_is_valid_according_to_schema[config_obj3-False]", "tests/clientlib/validate_config_test.py::test_config_with_failing_regexes_fails", "tests/clientlib/validate_config_test.py::test_config_with_ok_regexes_passes", "tests/clientlib/validate_config_test.py::test_config_with_invalid_exclude_regex_fails", "tests/clientlib/validate_config_test.py::test_config_with_ok_exclude_regex_passes", "tests/clientlib/validate_config_test.py::test_config_with_local_hooks_definition_fails[config_obj0]", "tests/clientlib/validate_config_test.py::test_config_with_local_hooks_definition_passes[config_obj0]", "tests/clientlib/validate_config_test.py::test_config_with_local_hooks_definition_passes[config_obj1]", "tests/clientlib/validate_manifest_test.py::test_run[input2-1]", "tests/clientlib/validate_manifest_test.py::test_run[input3-1]", "tests/clientlib/validate_manifest_test.py::test_run[input4-1]", "tests/clientlib/validate_manifest_test.py::test_additional_manifest_check_raises_for_bad_language", "tests/clientlib/validate_manifest_test.py::test_additional_manifest_check_passing[obj0]", "tests/clientlib/validate_manifest_test.py::test_additional_manifest_check_passing[obj1]", "tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj0]", "tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj1]", "tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj2]", "tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj3]", "tests/clientlib/validate_manifest_test.py::test_additional_manifest_failing[obj4]", "tests/clientlib/validate_manifest_test.py::test_is_valid_according_to_schema[manifest_obj0-False]", "tests/clientlib/validate_manifest_test.py::test_is_valid_according_to_schema[manifest_obj1-True]", "tests/clientlib/validate_manifest_test.py::test_is_valid_according_to_schema[manifest_obj2-True]" ]
[]
MIT License
143
565
[ "pre_commit/clientlib/validate_config.py", "pre_commit/clientlib/validate_manifest.py" ]
pre-commit__pre-commit-235
b4bc5e47423635e187d50d8730584d2c8ff06772
2015-05-24 03:03:11
5791d84236d82f8aa8609c3ff1c69a991d8c6607
diff --git a/pre_commit/commands/install_uninstall.py b/pre_commit/commands/install_uninstall.py index c84d29b..47c9484 100644 --- a/pre_commit/commands/install_uninstall.py +++ b/pre_commit/commands/install_uninstall.py @@ -48,6 +48,9 @@ def install(runner, overwrite=False, hooks=False, hook_type='pre-commit'): hook_path = runner.get_hook_path(hook_type) legacy_path = hook_path + '.legacy' + if not os.path.exists(os.path.dirname(hook_path)): + os.makedirs(os.path.dirname(hook_path)) + # If we have an existing hook, move it to pre-commit.legacy if ( os.path.exists(hook_path) and
Some versions of git don't create .git/hooks directory Noticed here: https://github.com/victorlin/bugbuzz-python/pull/1#issuecomment-104971132
pre-commit/pre-commit
diff --git a/tests/commands/install_uninstall_test.py b/tests/commands/install_uninstall_test.py index 9e1806e..ca82c06 100644 --- a/tests/commands/install_uninstall_test.py +++ b/tests/commands/install_uninstall_test.py @@ -5,6 +5,7 @@ import io import os import os.path import re +import shutil import subprocess import sys @@ -78,6 +79,15 @@ def test_install_pre_commit(tmpdir_factory): assert pre_push_contents == expected_contents +def test_install_hooks_directory_not_present(tmpdir_factory): + path = git_dir(tmpdir_factory) + # Simulate some git clients which don't make .git/hooks #234 + shutil.rmtree(os.path.join(path, '.git', 'hooks')) + runner = Runner(path) + install(runner) + assert os.path.exists(runner.pre_commit_path) + + def test_uninstall_does_not_blow_up_when_not_there(tmpdir_factory): path = git_dir(tmpdir_factory) runner = Runner(path)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aspy.yaml==1.3.0 astroid==1.3.2 attrs==22.2.0 cached-property==1.5.2 certifi==2021.5.30 coverage==6.2 distlib==0.3.9 filelock==3.4.1 flake8==5.0.4 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 jsonschema==3.2.0 logilab-common==1.9.7 mccabe==0.7.0 mock==5.2.0 mypy-extensions==1.0.0 nodeenv==1.6.0 ordereddict==1.1 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 -e git+https://github.com/pre-commit/pre-commit.git@b4bc5e47423635e187d50d8730584d2c8ff06772#egg=pre_commit py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 pylint==1.3.1 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 PyYAML==6.0.1 simplejson==3.20.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 virtualenv==20.17.1 zipp==3.6.0
name: pre-commit channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - aspy-yaml==1.3.0 - astroid==1.3.2 - attrs==22.2.0 - cached-property==1.5.2 - coverage==6.2 - distlib==0.3.9 - filelock==3.4.1 - flake8==5.0.4 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jsonschema==3.2.0 - logilab-common==1.9.7 - mccabe==0.7.0 - mock==5.2.0 - mypy-extensions==1.0.0 - nodeenv==1.6.0 - ordereddict==1.1 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pylint==1.3.1 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pyyaml==6.0.1 - simplejson==3.20.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - virtualenv==20.17.1 - zipp==3.6.0 prefix: /opt/conda/envs/pre-commit
[ "tests/commands/install_uninstall_test.py::test_install_hooks_directory_not_present" ]
[ "tests/commands/install_uninstall_test.py::test_install_pre_commit_and_run", "tests/commands/install_uninstall_test.py::test_install_idempotent", "tests/commands/install_uninstall_test.py::test_environment_not_sourced", "tests/commands/install_uninstall_test.py::test_failing_hooks_returns_nonzero", "tests/commands/install_uninstall_test.py::test_install_existing_hooks_no_overwrite", "tests/commands/install_uninstall_test.py::test_install_existing_hook_no_overwrite_idempotent", "tests/commands/install_uninstall_test.py::test_failing_existing_hook_returns_1", "tests/commands/install_uninstall_test.py::test_install_overwrite_no_existing_hooks", "tests/commands/install_uninstall_test.py::test_install_overwrite", "tests/commands/install_uninstall_test.py::test_uninstall_restores_legacy_hooks", "tests/commands/install_uninstall_test.py::test_replace_old_commit_script", "tests/commands/install_uninstall_test.py::test_installs_hooks_with_hooks_True", "tests/commands/install_uninstall_test.py::test_installed_from_venv", "tests/commands/install_uninstall_test.py::test_pre_push_integration_failing", "tests/commands/install_uninstall_test.py::test_pre_push_integration_accepted" ]
[ "tests/commands/install_uninstall_test.py::test_is_not_our_pre_commit", "tests/commands/install_uninstall_test.py::test_is_our_pre_commit", "tests/commands/install_uninstall_test.py::test_is_not_previous_pre_commit", "tests/commands/install_uninstall_test.py::test_is_also_not_previous_pre_commit", "tests/commands/install_uninstall_test.py::test_is_previous_pre_commit", "tests/commands/install_uninstall_test.py::test_install_pre_commit", "tests/commands/install_uninstall_test.py::test_uninstall_does_not_blow_up_when_not_there", "tests/commands/install_uninstall_test.py::test_uninstall", "tests/commands/install_uninstall_test.py::test_uninstall_doesnt_remove_not_our_hooks" ]
[]
MIT License
148
176
[ "pre_commit/commands/install_uninstall.py" ]
nose-devs__nose2-245
bf9945309d5118ad4723619452c486593964d1b8
2015-05-27 19:59:26
bbf5897eb1aa224100e86ba594042e4399fd2f5f
landscape-bot: [![Code Health](https://landscape.io/badge/175759/landscape.svg?style=flat)](https://landscape.io/diff/163690) Repository health decreased by 0.00% when pulling **[28cda3a](https://github.com/dlax/nose2/commit/28cda3abf4d51b58fd686b0b6c0ff5c46c38f51b) on dlax:generator-exception** into **[bf99453](https://github.com/nose-devs/nose2/commit/bf9945309d5118ad4723619452c486593964d1b8) on nose-devs:master**. * [1 new problem was found](https://landscape.io/diff/163690) (including 0 errors and 1 code smell). * [1 problem was fixed](https://landscape.io/diff/163690/fixed) (including 0 errors and 1 code smell). coveralls: [![Coverage Status](https://coveralls.io/builds/2664738/badge)](https://coveralls.io/builds/2664738) Coverage decreased (-0.06%) to 84.25% when pulling **28cda3abf4d51b58fd686b0b6c0ff5c46c38f51b on dlax:generator-exception** into **bf9945309d5118ad4723619452c486593964d1b8 on nose-devs:master**. coveralls: [![Coverage Status](https://coveralls.io/builds/2664738/badge)](https://coveralls.io/builds/2664738) Coverage decreased (-0.06%) to 84.25% when pulling **28cda3abf4d51b58fd686b0b6c0ff5c46c38f51b on dlax:generator-exception** into **bf9945309d5118ad4723619452c486593964d1b8 on nose-devs:master**. landscape-bot: [![Code Health](https://landscape.io/badge/175789/landscape.svg?style=flat)](https://landscape.io/diff/163709) Repository health increased by 0.07% when pulling **[ce05d05](https://github.com/dlax/nose2/commit/ce05d05f4ed1d9bb60cade4ccdb031637385585b) on dlax:generator-exception** into **[bf99453](https://github.com/nose-devs/nose2/commit/bf9945309d5118ad4723619452c486593964d1b8) on nose-devs:master**. * No new problems were introduced. * [1 problem was fixed](https://landscape.io/diff/163709/fixed) (including 0 errors and 1 code smell). coveralls: [![Coverage Status](https://coveralls.io/builds/2664909/badge)](https://coveralls.io/builds/2664909) Coverage increased (+0.02%) to 84.32% when pulling **ce05d05f4ed1d9bb60cade4ccdb031637385585b on dlax:generator-exception** into **bf9945309d5118ad4723619452c486593964d1b8 on nose-devs:master**. dlax: Hmm, this does not actually fixes #48 completly since the exception context is not forwarded down to the test failure. Will work further on this... dlax: Pushed a new version. coveralls: [![Coverage Status](https://coveralls.io/builds/2668668/badge)](https://coveralls.io/builds/2668668) Coverage decreased (-2.57%) to 81.73% when pulling **778265de7a289dda9ab9755ba2c08c89642b80ac on dlax:generator-exception** into **bf9945309d5118ad4723619452c486593964d1b8 on nose-devs:master**. landscape-bot: [![Code Health](https://landscape.io/badge/176074/landscape.svg?style=flat)](https://landscape.io/diff/164010) Code quality remained the same when pulling **[778265d](https://github.com/dlax/nose2/commit/778265de7a289dda9ab9755ba2c08c89642b80ac) on dlax:generator-exception** into **[bf99453](https://github.com/nose-devs/nose2/commit/bf9945309d5118ad4723619452c486593964d1b8) on nose-devs:master**.
diff --git a/nose2/loader.py b/nose2/loader.py index 2778280..394899f 100644 --- a/nose2/loader.py +++ b/nose2/loader.py @@ -7,6 +7,8 @@ import logging import traceback +import six + from nose2 import events from nose2.compat import unittest @@ -114,7 +116,11 @@ class PluggableTestLoader(object): def _makeFailedTest(self, classname, methodname, exception): def testFailure(self): - raise exception + if isinstance(exception, Exception): + raise exception + else: + # exception tuple (type, value, traceback) + six.reraise(*exception) attrs = {methodname: testFailure} TestClass = type(classname, (unittest.TestCase,), attrs) return self.suiteClass((TestClass(methodname),))
Loader errors throw away tracebacks and exception detail For instance if a generator test throws an AttributeError, the details of the attribute error are lost and the user only sees "AttributeError" -- not very helpful.
nose-devs/nose2
diff --git a/nose2/tests/unit/test_loader.py b/nose2/tests/unit/test_loader.py index 24114e5..8dc152c 100644 --- a/nose2/tests/unit/test_loader.py +++ b/nose2/tests/unit/test_loader.py @@ -8,6 +8,21 @@ class TestPluggableTestLoader(TestCase): self.session = session.Session() self.loader = loader.PluggableTestLoader(self.session) + def test_failed_load_tests_exception(self): + suite = self.loader.failedLoadTests('test', RuntimeError('err')) + tc = suite._tests[0] + with self.assertRaises(RuntimeError) as cm: + tc.test() + self.assertEqual(cm.exception.args, ('err', )) + + def test_failed_load_tests_exc_info(self): + suite = self.loader.failedLoadTests( + 'test', (RuntimeError, RuntimeError('err'), None)) + tc = suite._tests[0] + with self.assertRaises(RuntimeError) as cm: + tc.test() + self.assertEqual(cm.exception.args, ('err', )) + def test_load_from_module_calls_hook(self): self.session.hooks.register('loadTestsFromModule', FakePlugin()) evt = events.LoadFromModuleEvent(self.loader, 'some_module')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose2", "pytest" ], "pre_install": [], "python": "3.7", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi cov-core==1.15.0 coverage==7.2.7 exceptiongroup==1.2.2 importlib-metadata==6.7.0 iniconfig==2.0.0 -e git+https://github.com/nose-devs/nose2.git@bf9945309d5118ad4723619452c486593964d1b8#egg=nose2 packaging==24.0 pluggy==1.2.0 pytest==7.4.4 six==1.17.0 tomli==2.0.1 typing_extensions==4.7.1 zipp==3.15.0
name: nose2 channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cov-core==1.15.0 - coverage==7.2.7 - exceptiongroup==1.2.2 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - six==1.17.0 - tomli==2.0.1 - typing-extensions==4.7.1 - zipp==3.15.0 prefix: /opt/conda/envs/nose2
[ "nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_failed_load_tests_exc_info" ]
[]
[ "nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_failed_load_tests_exception", "nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_load_from_module_calls_hook", "nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_load_from_name_calls_hook", "nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_load_from_names_calls_hook", "nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_loader_from_names_calls_module_hook", "nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_loader_from_names_calls_name_hook", "nose2/tests/unit/test_loader.py::TestPluggableTestLoader::test_loader_from_names_calls_names_hook" ]
[]
BSD
152
215
[ "nose2/loader.py" ]
eve-val__evelink-212
db9e7bfeef9478a047f4f7db4f88324e185e4873
2015-06-01 04:28:15
4061903e92787ce22eddb75b3776c407fb70837b
diff --git a/evelink/char.py b/evelink/char.py index 609d76d..0514dc6 100644 --- a/evelink/char.py +++ b/evelink/char.py @@ -137,7 +137,7 @@ class Char(object): """Get a list of PI routing entries for a character's planet.""" return api.APIResult(parse_planetary_routes(api_result.result), api_result.timestamp, api_result.expires) - @auto_call('char/KillLog', map_params={'before_kill': 'beforeKillID'}) + @auto_call('char/KillMails', map_params={'before_kill': 'beforeKillID'}) def kills(self, before_kill=None, api_result=None): """Look up recent kills for a character. @@ -147,6 +147,19 @@ class Char(object): return api.APIResult(parse_kills(api_result.result), api_result.timestamp, api_result.expires) + @auto_call('char/KillLog', map_params={'before_kill': 'beforeKillID'}) + def kill_log(self, before_kill=None, api_result=None): + """Look up recent kills for a character. + + Note: this method uses the long cache version of the endpoint. If you + want to use the short cache version (recommended), use kills(). + + before_kill: + Optional. Only show kills before this kill id. (Used for paging.) + """ + + return api.APIResult(parse_kills(api_result.result), api_result.timestamp, api_result.expires) + @auto_call('char/Notifications') def notifications(self, api_result=None): """Returns the message headers for notifications.""" diff --git a/evelink/corp.py b/evelink/corp.py index 5e98fcc..ebf1133 100644 --- a/evelink/corp.py +++ b/evelink/corp.py @@ -136,7 +136,7 @@ class Corp(object): return api.APIResult(results, api_result.timestamp, api_result.expires) - @api.auto_call('corp/KillLog', map_params={'before_kill': 'beforeKillID'}) + @api.auto_call('corp/KillMails', map_params={'before_kill': 'beforeKillID'}) def kills(self, before_kill=None, api_result=None): """Look up recent kills for a corporation. @@ -146,6 +146,19 @@ class Corp(object): return api.APIResult(parse_kills(api_result.result), api_result.timestamp, api_result.expires) + @api.auto_call('corp/KillLog', map_params={'before_kill': 'beforeKillID'}) + def kill_log(self, before_kill=None, api_result=None): + """Look up recent kills for a corporation. + + Note: this method uses the long cache version of the endpoint. If you + want to use the short cache version (recommended), use kills(). + + before_kill: + Optional. Only show kills before this kill id. (Used for paging.) + """ + + return api.APIResult(parse_kills(api_result.result), api_result.timestamp, api_result.expires) + @api.auto_call('corp/AccountBalance') def wallet_info(self, api_result=None): """Get information about corp wallets."""
kills() uses KillLog rather than KillMails KillLog is a long cache endpoint, so you can only query it once. KillMails isn't a long cache, so you can query it as often as you want.
eve-val/evelink
diff --git a/tests/test_char.py b/tests/test_char.py index ca37666..64e3631 100644 --- a/tests/test_char.py +++ b/tests/test_char.py @@ -291,6 +291,23 @@ class CharTestCase(APITestCase): self.assertEqual(current, 12345) self.assertEqual(expires, 67890) + self.assertEqual(result, mock.sentinel.kills) + self.assertEqual(self.api.mock_calls, [ + mock.call.get('char/KillMails', params={'characterID': 1}), + ]) + self.assertEqual(mock_parse.mock_calls, [ + mock.call(mock.sentinel.api_result), + ]) + + @mock.patch('evelink.char.parse_kills') + def test_kill_log(self, mock_parse): + self.api.get.return_value = API_RESULT_SENTINEL + mock_parse.return_value = mock.sentinel.kills + + result, current, expires = self.char.kill_log() + self.assertEqual(current, 12345) + self.assertEqual(expires, 67890) + self.assertEqual(result, mock.sentinel.kills) self.assertEqual(self.api.mock_calls, [ mock.call.get('char/KillLog', params={'characterID': 1}), @@ -304,7 +321,7 @@ class CharTestCase(APITestCase): self.char.kills(before_kill=12345) self.assertEqual(self.api.mock_calls, [ - mock.call.get('char/KillLog', params={'characterID': 1, 'beforeKillID': 12345}), + mock.call.get('char/KillMails', params={'characterID': 1, 'beforeKillID': 12345}), ]) def test_character_sheet(self): diff --git a/tests/test_corp.py b/tests/test_corp.py index 0e96533..5738401 100644 --- a/tests/test_corp.py +++ b/tests/test_corp.py @@ -165,6 +165,23 @@ class CorpTestCase(APITestCase): result, current, expires = self.corp.kills() + self.assertEqual(result, mock.sentinel.kills) + self.assertEqual(self.api.mock_calls, [ + mock.call.get('corp/KillMails', params={}), + ]) + self.assertEqual(mock_parse.mock_calls, [ + mock.call(mock.sentinel.api_result), + ]) + self.assertEqual(current, 12345) + self.assertEqual(expires, 67890) + + @mock.patch('evelink.corp.parse_kills') + def test_kill_log(self, mock_parse): + self.api.get.return_value = API_RESULT_SENTINEL + mock_parse.return_value = mock.sentinel.kills + + result, current, expires = self.corp.kill_log() + self.assertEqual(result, mock.sentinel.kills) self.assertEqual(self.api.mock_calls, [ mock.call.get('corp/KillLog', params={}),
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
0.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "mock", "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements_py3.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 -e git+https://github.com/eve-val/evelink.git@db9e7bfeef9478a047f4f7db4f88324e185e4873#egg=EVELink exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 mock==1.0b1 nose==1.1.2 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 requests==2.32.3 six==1.17.0 tomli==2.2.1 urllib3==2.3.0
name: evelink channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - mock==1.0b1 - nose==1.1.2 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - requests==2.32.3 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/evelink
[ "tests/test_char.py::CharTestCase::test_kill_log", "tests/test_char.py::CharTestCase::test_kills", "tests/test_char.py::CharTestCase::test_kills_paged", "tests/test_corp.py::CorpTestCase::test_kill_log", "tests/test_corp.py::CorpTestCase::test_kills" ]
[]
[ "tests/test_char.py::CharTestCase::test_assets", "tests/test_char.py::CharTestCase::test_blueprints", "tests/test_char.py::CharTestCase::test_calendar_attendees", "tests/test_char.py::CharTestCase::test_calendar_events", "tests/test_char.py::CharTestCase::test_character_sheet", "tests/test_char.py::CharTestCase::test_contact_notifications", "tests/test_char.py::CharTestCase::test_contacts", "tests/test_char.py::CharTestCase::test_contract_bids", "tests/test_char.py::CharTestCase::test_contract_items", "tests/test_char.py::CharTestCase::test_contracts", "tests/test_char.py::CharTestCase::test_current_training", "tests/test_char.py::CharTestCase::test_event_attendees", "tests/test_char.py::CharTestCase::test_faction_warfare_stats", "tests/test_char.py::CharTestCase::test_industry_jobs", "tests/test_char.py::CharTestCase::test_industry_jobs_history", "tests/test_char.py::CharTestCase::test_locations", "tests/test_char.py::CharTestCase::test_mailing_lists", "tests/test_char.py::CharTestCase::test_medals", "tests/test_char.py::CharTestCase::test_message_bodies", "tests/test_char.py::CharTestCase::test_messages", "tests/test_char.py::CharTestCase::test_notification_texts", "tests/test_char.py::CharTestCase::test_notifications", "tests/test_char.py::CharTestCase::test_orders", "tests/test_char.py::CharTestCase::test_planetary_colonies", "tests/test_char.py::CharTestCase::test_planetary_links", "tests/test_char.py::CharTestCase::test_planetary_pins", "tests/test_char.py::CharTestCase::test_planetary_routes", "tests/test_char.py::CharTestCase::test_research", "tests/test_char.py::CharTestCase::test_skill_queue", "tests/test_char.py::CharTestCase::test_standings", "tests/test_char.py::CharTestCase::test_wallet_balance", "tests/test_char.py::CharTestCase::test_wallet_info", "tests/test_char.py::CharTestCase::test_wallet_journal", "tests/test_char.py::CharTestCase::test_wallet_limit", "tests/test_char.py::CharTestCase::test_wallet_paged", "tests/test_char.py::CharTestCase::test_wallet_transactions_limit", "tests/test_char.py::CharTestCase::test_wallet_transactions_paged", "tests/test_char.py::CharTestCase::test_wallet_transcations", "tests/test_corp.py::CorpTestCase::test_assets", "tests/test_corp.py::CorpTestCase::test_blueprints", "tests/test_corp.py::CorpTestCase::test_contacts", "tests/test_corp.py::CorpTestCase::test_container_log", "tests/test_corp.py::CorpTestCase::test_contract_bids", "tests/test_corp.py::CorpTestCase::test_contract_items", "tests/test_corp.py::CorpTestCase::test_contracts", "tests/test_corp.py::CorpTestCase::test_corporation_sheet", "tests/test_corp.py::CorpTestCase::test_corporation_sheet_public", "tests/test_corp.py::CorpTestCase::test_customs_offices", "tests/test_corp.py::CorpTestCase::test_facilities", "tests/test_corp.py::CorpTestCase::test_faction_warfare_stats", "tests/test_corp.py::CorpTestCase::test_industry_jobs", "tests/test_corp.py::CorpTestCase::test_industry_jobs_history", "tests/test_corp.py::CorpTestCase::test_locations", "tests/test_corp.py::CorpTestCase::test_medals", "tests/test_corp.py::CorpTestCase::test_member_medals", "tests/test_corp.py::CorpTestCase::test_members", "tests/test_corp.py::CorpTestCase::test_members_not_extended", "tests/test_corp.py::CorpTestCase::test_npc_standings", "tests/test_corp.py::CorpTestCase::test_orders", "tests/test_corp.py::CorpTestCase::test_permissions", "tests/test_corp.py::CorpTestCase::test_permissions_log", "tests/test_corp.py::CorpTestCase::test_shareholders", "tests/test_corp.py::CorpTestCase::test_starbase_details", "tests/test_corp.py::CorpTestCase::test_starbases", "tests/test_corp.py::CorpTestCase::test_station_services", "tests/test_corp.py::CorpTestCase::test_stations", "tests/test_corp.py::CorpTestCase::test_titles", "tests/test_corp.py::CorpTestCase::test_wallet_info", "tests/test_corp.py::CorpTestCase::test_wallet_journal", "tests/test_corp.py::CorpTestCase::test_wallet_journal_account_key", "tests/test_corp.py::CorpTestCase::test_wallet_journal_limit", "tests/test_corp.py::CorpTestCase::test_wallet_journal_paged", "tests/test_corp.py::CorpTestCase::test_wallet_transactions_account_key", "tests/test_corp.py::CorpTestCase::test_wallet_transactions_limit", "tests/test_corp.py::CorpTestCase::test_wallet_transactions_paged", "tests/test_corp.py::CorpTestCase::test_wallet_transcations" ]
[]
MIT License
155
749
[ "evelink/char.py", "evelink/corp.py" ]
pre-commit__pre-commit-239
1c46446427ab0dfa6293221426b855420533ef8d
2015-06-02 19:44:23
5791d84236d82f8aa8609c3ff1c69a991d8c6607
coveralls: [![Coverage Status](https://coveralls.io/builds/2711896/badge)](https://coveralls.io/builds/2711896) Coverage decreased (-0.03%) to 99.97% when pulling **971060d4b9756a9d102e5bb3ee4d04027d35011c on Lucas-C:master** into **1c46446427ab0dfa6293221426b855420533ef8d on pre-commit:master**. asottile: ++ thanks for the quick code! I was going to get to this later but you beat me to it! test-n-ship
diff --git a/pre_commit/commands/autoupdate.py b/pre_commit/commands/autoupdate.py index 1a24b09..9e1e79f 100644 --- a/pre_commit/commands/autoupdate.py +++ b/pre_commit/commands/autoupdate.py @@ -8,6 +8,7 @@ from aspy.yaml import ordered_load import pre_commit.constants as C from pre_commit.clientlib.validate_config import CONFIG_JSON_SCHEMA +from pre_commit.clientlib.validate_config import is_local_hooks from pre_commit.clientlib.validate_config import load_config from pre_commit.jsonschema_extensions import remove_defaults from pre_commit.ordereddict import OrderedDict @@ -67,6 +68,8 @@ def autoupdate(runner): ) for repo_config in input_configs: + if is_local_hooks(repo_config): + continue sys.stdout.write('Updating {0}...'.format(repo_config['repo'])) sys.stdout.flush() try: diff --git a/pre_commit/repository.py b/pre_commit/repository.py index 71cc356..83a3c01 100644 --- a/pre_commit/repository.py +++ b/pre_commit/repository.py @@ -125,9 +125,8 @@ class Repository(object): class LocalRepository(Repository): - def __init__(self, repo_config, repo_path_getter=None): - repo_path_getter = None - super(LocalRepository, self).__init__(repo_config, repo_path_getter) + def __init__(self, repo_config): + super(LocalRepository, self).__init__(repo_config, None) @cached_property def hooks(self):
pre-commit autoupdate fails on `local` hooks repos ``` $ pre-commit autoupdate Updating [email protected]:pre-commit/pre-commit-hooks...updating 9ce45609a92f648c87b42207410386fd69a5d1e5 -> cf550fcab3f12015f8676b8278b30e1a5bc10e70. Updating [email protected]:pre-commit/pre-commit...updating 4352d45451296934bc17494073b82bcacca3205c -> 1c46446427ab0dfa6293221426b855420533ef8d. Updating [email protected]:asottile/reorder_python_imports...updating aeda21eb7df6af8c9f6cd990abb086375c71c953 -> 3d86483455ab5bd06cc1069fdd5ac57be5463f10. Updating local...An unexpected error has occurred: AttributeError: 'NoneType' object has no attribute 'repo_path' Check the log at ~/.pre-commit/pre-commit.log (venv-pre_commit)asottile@work:~/workspace/pre-commit$ cat ~/.pre-commit/pre-commit.log An unexpected error has occurred: AttributeError: 'NoneType' object has no attribute 'repo_path' Traceback (most recent call last): File "/home/asottile/workspace/pre-commit/pre_commit/error_handler.py", line 34, in error_handler yield File "/home/asottile/workspace/pre-commit/pre_commit/main.py", line 142, in main return autoupdate(runner) File "/home/asottile/workspace/pre-commit/pre_commit/commands/autoupdate.py", line 73, in autoupdate new_repo_config = _update_repository(repo_config, runner) File "/home/asottile/workspace/pre-commit/pre_commit/commands/autoupdate.py", line 33, in _update_repository with cwd(repo.repo_path_getter.repo_path): AttributeError: 'NoneType' object has no attribute 'repo_path' (venv-pre_commit)asottile@work:~/workspace/pre-commit$ git diff diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 397ee72..20393a7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -20,3 +20,10 @@ sha: aeda21eb7df6af8c9f6cd990abb086375c71c953 hooks: - id: reorder-python-imports +- repo: local + hooks: + - id: herp + name: Herp + entry: echo derp + language: system + files: ^$ ```
pre-commit/pre-commit
diff --git a/testing/fixtures.py b/testing/fixtures.py index 1c0184a..820a72b 100644 --- a/testing/fixtures.py +++ b/testing/fixtures.py @@ -35,6 +35,19 @@ def make_repo(tmpdir_factory, repo_source): return path +def config_with_local_hooks(): + return OrderedDict(( + ('repo', 'local'), + ('hooks', [OrderedDict(( + ('id', 'do_not_commit'), + ('name', 'Block if "DO NOT COMMIT" is found'), + ('entry', 'DO NOT COMMIT'), + ('language', 'pcre'), + ('files', '^(.*)$'), + ))]) + )) + + def make_config_from_repo(repo_path, sha=None, hooks=None, check=True): manifest = load_manifest(os.path.join(repo_path, C.MANIFEST_FILE)) config = OrderedDict(( diff --git a/tests/commands/autoupdate_test.py b/tests/commands/autoupdate_test.py index 5dbc439..771e67b 100644 --- a/tests/commands/autoupdate_test.py +++ b/tests/commands/autoupdate_test.py @@ -13,6 +13,9 @@ from pre_commit.runner import Runner from pre_commit.util import cmd_output from pre_commit.util import cwd from testing.auto_namedtuple import auto_namedtuple +from testing.fixtures import add_config_to_repo +from testing.fixtures import config_with_local_hooks +from testing.fixtures import git_dir from testing.fixtures import make_config_from_repo from testing.fixtures import make_repo from testing.fixtures import write_config @@ -137,3 +140,10 @@ def test_autoupdate_hook_disappearing_repo( after = open(C.CONFIG_FILE).read() assert ret == 1 assert before == after + + +def test_autoupdate_local_hooks(tmpdir_factory): + git_path = git_dir(tmpdir_factory) + config = config_with_local_hooks() + path = add_config_to_repo(git_path, config) + assert autoupdate(Runner(path)) == 0 diff --git a/tests/repository_test.py b/tests/repository_test.py index f2e8850..e7ad227 100644 --- a/tests/repository_test.py +++ b/tests/repository_test.py @@ -12,10 +12,10 @@ from pre_commit.clientlib.validate_config import CONFIG_JSON_SCHEMA from pre_commit.clientlib.validate_config import validate_config_extra from pre_commit.jsonschema_extensions import apply_defaults from pre_commit.languages.python import PythonEnv -from pre_commit.ordereddict import OrderedDict from pre_commit.repository import Repository from pre_commit.util import cmd_output from pre_commit.util import cwd +from testing.fixtures import config_with_local_hooks from testing.fixtures import git_dir from testing.fixtures import make_config_from_repo from testing.fixtures import make_repo @@ -404,16 +404,7 @@ def test_tags_on_repositories(in_tmpdir, tmpdir_factory, store): def test_local_repository(): - config = OrderedDict(( - ('repo', 'local'), - ('hooks', [OrderedDict(( - ('id', 'do_not_commit'), - ('name', 'Block if "DO NOT COMMIT" is found'), - ('entry', 'DO NOT COMMIT'), - ('language', 'pcre'), - ('files', '^(.*)$'), - ))]) - )) + config = config_with_local_hooks() local_repo = Repository.create(config, 'dummy') with pytest.raises(NotImplementedError): local_repo.sha
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_git_commit_hash", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 2 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aspy.yaml==1.3.0 astroid==1.3.2 attrs==22.2.0 cached-property==1.5.2 certifi==2021.5.30 coverage==6.2 distlib==0.3.9 filelock==3.4.1 flake8==5.0.4 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 jsonschema==3.2.0 logilab-common==1.9.7 mccabe==0.7.0 mock==5.2.0 mypy-extensions==1.0.0 nodeenv==1.6.0 ordereddict==1.1 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 -e git+https://github.com/pre-commit/pre-commit.git@1c46446427ab0dfa6293221426b855420533ef8d#egg=pre_commit py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 pylint==1.3.1 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 PyYAML==6.0.1 simplejson==3.20.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 virtualenv==20.17.1 zipp==3.6.0
name: pre-commit channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - aspy-yaml==1.3.0 - astroid==1.3.2 - attrs==22.2.0 - cached-property==1.5.2 - coverage==6.2 - distlib==0.3.9 - filelock==3.4.1 - flake8==5.0.4 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jsonschema==3.2.0 - logilab-common==1.9.7 - mccabe==0.7.0 - mock==5.2.0 - mypy-extensions==1.0.0 - nodeenv==1.6.0 - ordereddict==1.1 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pylint==1.3.1 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pyyaml==6.0.1 - simplejson==3.20.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - virtualenv==20.17.1 - zipp==3.6.0 prefix: /opt/conda/envs/pre-commit
[ "tests/commands/autoupdate_test.py::test_autoupdate_local_hooks" ]
[ "tests/commands/autoupdate_test.py::test_up_to_date_repo", "tests/commands/autoupdate_test.py::test_autoupdate_up_to_date_repo", "tests/commands/autoupdate_test.py::test_out_of_date_repo", "tests/commands/autoupdate_test.py::test_autoupdate_out_of_date_repo", "tests/commands/autoupdate_test.py::test_hook_disppearing_repo_raises", "tests/commands/autoupdate_test.py::test_autoupdate_hook_disappearing_repo", "tests/repository_test.py::test_python_hook", "tests/repository_test.py::test_python_hook_args_with_spaces", "tests/repository_test.py::test_switch_language_versions_doesnt_clobber", "tests/repository_test.py::test_versioned_python_hook", "tests/repository_test.py::test_run_a_node_hook", "tests/repository_test.py::test_run_versioned_node_hook", "tests/repository_test.py::test_run_a_ruby_hook", "tests/repository_test.py::test_run_versioned_ruby_hook", "tests/repository_test.py::test_system_hook_with_spaces", "tests/repository_test.py::test_run_a_script_hook", "tests/repository_test.py::test_run_hook_with_spaced_args", "tests/repository_test.py::test_pcre_hook_no_match", "tests/repository_test.py::test_pcre_hook_matching", "tests/repository_test.py::test_pcre_many_files", "tests/repository_test.py::test_cwd_of_hook", "tests/repository_test.py::test_lots_of_files", "tests/repository_test.py::test_languages", "tests/repository_test.py::test_reinstall", "tests/repository_test.py::test_control_c_control_c_on_install", "tests/repository_test.py::test_really_long_file_paths", "tests/repository_test.py::test_config_overrides_repo_specifics", "tests/repository_test.py::test_tags_on_repositories" ]
[ "tests/repository_test.py::test_repo_url", "tests/repository_test.py::test_sha", "tests/repository_test.py::test_local_repository" ]
[]
MIT License
156
379
[ "pre_commit/commands/autoupdate.py", "pre_commit/repository.py" ]
pydoit__doit-58
dcefd2159bca7fa80e236fc3fec91688a39ba7c4
2015-06-07 18:22:26
e551006a0a5a93a197d413b663bd455061e3f74d
diff --git a/doit/cmd_run.py b/doit/cmd_run.py index 8a3693a..50e34b9 100644 --- a/doit/cmd_run.py +++ b/doit/cmd_run.py @@ -116,6 +116,18 @@ opt_pdb = { } +# use ".*" as default regex for delayed tasks without explicitly specified regex +opt_auto_delayed_regex = { + 'name': 'auto_delayed_regex', + 'short': '', + 'long': 'auto-delayed-regex', + 'type': bool, + 'default': False, + 'help': +"""Uses the default regex ".*" for every delayed task loader for which no regex was explicitly defined""" +} + + class Run(DoitCmdBase): doc_purpose = "run tasks" doc_usage = "[TASK/TARGET...]" @@ -124,7 +136,8 @@ class Run(DoitCmdBase): cmd_options = (opt_always, opt_continue, opt_verbosity, opt_reporter, opt_outfile, opt_num_process, - opt_parallel_type, opt_pdb, opt_single) + opt_parallel_type, opt_pdb, opt_single, + opt_auto_delayed_regex) def __init__(self, **kwargs): @@ -162,7 +175,7 @@ class Run(DoitCmdBase): def _execute(self, outfile, verbosity=None, always=False, continue_=False, reporter='console', num_process=0, par_type='process', - single=False): + single=False, auto_delayed_regex=False): """ @param reporter: (str) one of provided reporters or ... @@ -172,7 +185,7 @@ class Run(DoitCmdBase): """ # get tasks to be executed # self.control is saved on instance to be used by 'auto' command - self.control = TaskControl(self.task_list) + self.control = TaskControl(self.task_list, auto_delayed_regex=auto_delayed_regex) self.control.process(self.sel_tasks) if single: diff --git a/doit/control.py b/doit/control.py index 6350b99..c60d688 100644 --- a/doit/control.py +++ b/doit/control.py @@ -26,9 +26,10 @@ class TaskControl(object): Value: task_name """ - def __init__(self, task_list): + def __init__(self, task_list, auto_delayed_regex=False): self.tasks = {} self.targets = {} + self.auto_delayed_regex = auto_delayed_regex # name of task in order to be executed # this the order as in the dodo file. the real execution @@ -174,22 +175,51 @@ class TaskControl(object): # by task name if filter_ in self.tasks: selected_task.append(filter_) + continue + # by target - elif filter_ in self.targets: + if filter_ in self.targets: selected_task.append(self.targets[filter_]) - else: - # if can not find name check if it is a sub-task of a delayed - basename = filter_.split(':', 1)[0] - if basename in self.tasks: - loader = self.tasks[basename].loader - loader.basename = basename - self.tasks[filter_] = Task(filter_, None, loader=loader) - selected_task.append(filter_) + continue + + # if can not find name check if it is a sub-task of a delayed + basename = filter_.split(':', 1)[0] + if basename in self.tasks: + loader = self.tasks[basename].loader + loader.basename = basename + self.tasks[filter_] = Task(filter_, None, loader=loader) + selected_task.append(filter_) + continue + + # check if target matches any regex + import re + tasks = [] + for task in list(self.tasks.values()): + if task.loader and (task.loader.target_regex or self.auto_delayed_regex): + if re.match(task.loader.target_regex if task.loader.target_regex else '.*', filter_): + tasks.append(task) + if len(tasks) > 0: + if len(tasks) == 1: + task = tasks[0] + loader = task.loader + loader.basename = task.name + name = '_regex_target_' + filter_ + self.tasks[name] = Task(name, None, + loader=loader, + file_dep=[filter_]) + selected_task.append(name) else: - msg = ('cmd `run` invalid parameter: "%s".' + - ' Must be a task, or a target.\n' + - 'Type "doit list" to see available tasks') - raise InvalidCommand(msg % filter_) + name = '_regex_target_' + filter_ + self.tasks[name] = Task(name, None, + task_dep=[task.name for task in tasks], + file_dep=[filter_]) + selected_task.append(name) + else: + # not found + msg = ('cmd `run` invalid parameter: "%s".' + + ' Must be a task, or a target.\n' + + 'Type "doit list" to see available tasks') + raise InvalidCommand(msg % filter_) return selected_task @@ -416,6 +446,9 @@ class TaskDispatcher(object): basename = this_task.loader.basename or this_task.name new_tasks = generate_tasks(basename, ref(), ref.__doc__) TaskControl.set_implicit_deps(self.targets, new_tasks) + # check itself for implicit dep (used by regex_target) + TaskControl.add_implicit_task_dep( + self.targets, this_task, this_task.file_dep) for nt in new_tasks: if not nt.loader: nt.loader = DelayedLoaded diff --git a/doit/loader.py b/doit/loader.py index 1f3bcd4..123d0f4 100644 --- a/doit/loader.py +++ b/doit/loader.py @@ -98,10 +98,11 @@ def get_module(dodo_file, cwd=None, seek_parent=False): -def create_after(executed=None): +def create_after(executed=None, target_regex=None): """Annotate a task-creator function with delayed loader info""" def decorated(func): - func.doit_create_after = DelayedLoader(func, executed=executed) + func.doit_create_after = DelayedLoader(func, executed=executed, + target_regex=target_regex) return func return decorated diff --git a/doit/reporter.py b/doit/reporter.py index 4f5cbe3..18df356 100644 --- a/doit/reporter.py +++ b/doit/reporter.py @@ -53,7 +53,8 @@ class ConsoleReporter(object): def skip_uptodate(self, task): """skipped up-to-date task""" - self.write("-- %s\n" % task.title()) + if task.actions and (task.name[0] != '_'): + self.write("-- %s\n" % task.title()) def skip_ignore(self, task): """skipped ignored task""" diff --git a/doit/task.py b/doit/task.py index 7595877..3440123 100644 --- a/doit/task.py +++ b/doit/task.py @@ -31,9 +31,10 @@ class DelayedLoader(object): the loader call the creator function :ivar basename: (str) basename used when creating tasks """ - def __init__(self, creator, executed=None): + def __init__(self, creator, executed=None, target_regex=None): self.creator = creator self.task_dep = executed + self.target_regex = target_regex self.basename = None self.created = False
specify target of a DelayedTask on command line Since not all tasks are created before execution starts, it is required some special handling for target names of targets that have not been created yet. See discussion on https://github.com/getnikola/nikola/issues/1562#issuecomment-70836094 General idea is that if a target is not found, before raising an error to the user try to load DelayedTasks (as done by command list) to look for the given `target` name. Some considerations: 1) as of now a DelayedTask creates an implicit `task_dep` for the task given in it's `executed` param. But this `task_dep` is not preserved when the DelayedTask is re-created. It should not only be preserved but all created tasks should include this `task_dep` because the guarantee that the dependent task was already executed wont exist anymore! 2) if the selected tasks for execution includes know tasks and targets they should be executed **before**, any DelayedTask is loaded to look for an unknown `target`. This will ensure that same command line will work nicely even if it is on its first execution. <bountysource-plugin> --- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/7952756-specify-target-of-a-delayedtask-on-command-line?utm_campaign=plugin&utm_content=tracker%2F1885485&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F1885485&utm_medium=issues&utm_source=github). </bountysource-plugin>
pydoit/doit
diff --git a/tests/test_control.py b/tests/test_control.py index 4237acb..734b449 100644 --- a/tests/test_control.py +++ b/tests/test_control.py @@ -111,6 +111,43 @@ class TestTaskControlCmdOptions(object): assert control.tasks['taskY:foo'].loader.basename == 'taskY' assert control.tasks['taskY:foo'].loader is t2.loader + def test_filter_delayed_regex_single(self): + t1 = Task("taskX", None) + t2 = Task("taskY", None, loader=DelayedLoader(lambda: None, target_regex='a.*')) + t3 = Task("taskZ", None, loader=DelayedLoader(lambda: None, target_regex='b.*')) + t4 = Task("taskW", None, loader=DelayedLoader(lambda: None)) + control = TaskControl([t1, t2, t3, t4], auto_delayed_regex=False) + l = control._filter_tasks(['abc']) + assert isinstance(t2.loader, DelayedLoader) + assert len(l) == 1 + assert l[0] == '_regex_target_abc' + assert control.tasks[l[0]].file_dep == {'abc'} + assert control.tasks[l[0]].loader.basename == 'taskY' + assert control.tasks[l[0]].loader is t2.loader + + def test_filter_delayed_regex_multiple(self): + t1 = Task("taskX", None) + t2 = Task("taskY", None, loader=DelayedLoader(lambda: None, target_regex='a.*')) + t3 = Task("taskZ", None, loader=DelayedLoader(lambda: None, target_regex='ab.')) + t4 = Task("taskW", None, loader=DelayedLoader(lambda: None)) + control = TaskControl([t1, t2, t3, t4], auto_delayed_regex=False) + l = control._filter_tasks(['abc']) + assert len(l) == 1 + assert l[0] == '_regex_target_abc' + assert control.tasks[l[0]].file_dep == {'abc'} + assert set(control.tasks[l[0]].task_dep) == {t2.name, t3.name} + + def test_filter_delayed_regex_auto(self): + t1 = Task("taskX", None) + t2 = Task("taskY", None, loader=DelayedLoader(lambda: None, target_regex='a.*')) + t3 = Task("taskZ", None, loader=DelayedLoader(lambda: None)) + control = TaskControl([t1, t2, t3], auto_delayed_regex=True) + l = control._filter_tasks(['abc']) + assert len(l) == 1 + assert l[0] == '_regex_target_abc' + assert control.tasks[l[0]].file_dep == {'abc'} + assert set(control.tasks[l[0]].task_dep) == {t2.name, t3.name} + # filter a non-existent task raises an error def testFilterWrongName(self): tc = TaskControl(TASKS_SAMPLE)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 5 }
0.28
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[test]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.10 pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y libgeos-dev" ], "python": "3.7", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///croot/attrs_1668696182826/work certifi @ file:///croot/certifi_1671487769961/work/certifi -e git+https://github.com/pydoit/doit.git@dcefd2159bca7fa80e236fc3fec91688a39ba7c4#egg=doit flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work numpy @ file:///opt/conda/conda-bld/numpy_and_numpy_base_1653915516269/work packaging @ file:///croot/packaging_1671697413597/work pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyinotify==0.9.6 pytest==7.1.2 six==1.17.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work typing_extensions @ file:///croot/typing_extensions_1669924550328/work zipp @ file:///croot/zipp_1672387121353/work
name: doit channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=22.1.0=py37h06a4308_0 - blas=1.0=openblas - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - flit-core=3.6.0=pyhd3eb1b0_0 - importlib-metadata=4.11.3=py37h06a4308_0 - importlib_metadata=4.11.3=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=11.2.0=h00389a5_1 - libgfortran5=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.21=h043d6bf_0 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - numpy=1.21.5=py37hf838250_3 - numpy-base=1.21.5=py37h1e6e340_3 - openssl=1.1.1w=h7f8727e_0 - packaging=22.0=py37h06a4308_0 - pip=22.3.1=py37h06a4308_0 - pluggy=1.0.0=py37h06a4308_1 - py=1.11.0=pyhd3eb1b0_0 - pytest=7.1.2=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py37h06a4308_0 - typing_extensions=4.4.0=py37h06a4308_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zipp=3.11.0=py37h06a4308_0 - zlib=1.2.13=h5eee18b_1 - pip: - pyinotify==0.9.6 - six==1.17.0 prefix: /opt/conda/envs/doit
[ "tests/test_control.py::TestTaskControlCmdOptions::test_filter_delayed_regex_single", "tests/test_control.py::TestTaskControlCmdOptions::test_filter_delayed_regex_multiple", "tests/test_control.py::TestTaskControlCmdOptions::test_filter_delayed_regex_auto" ]
[]
[ "tests/test_control.py::TestTaskControlInit::test_addTask", "tests/test_control.py::TestTaskControlInit::test_targetDependency", "tests/test_control.py::TestTaskControlInit::test_addTaskSameName", "tests/test_control.py::TestTaskControlInit::test_addInvalidTask", "tests/test_control.py::TestTaskControlInit::test_userErrorTaskDependency", "tests/test_control.py::TestTaskControlInit::test_userErrorSetupTask", "tests/test_control.py::TestTaskControlInit::test_sameTarget", "tests/test_control.py::TestTaskControlInit::test_wild", "tests/test_control.py::TestTaskControlInit::test_bug770150_task_dependency_from_target", "tests/test_control.py::TestTaskControlCmdOptions::testFilter", "tests/test_control.py::TestTaskControlCmdOptions::testProcessSelection", "tests/test_control.py::TestTaskControlCmdOptions::testProcessAll", "tests/test_control.py::TestTaskControlCmdOptions::testFilterPattern", "tests/test_control.py::TestTaskControlCmdOptions::testFilterSubtask", "tests/test_control.py::TestTaskControlCmdOptions::testFilterTarget", "tests/test_control.py::TestTaskControlCmdOptions::test_filter_delayed_subtask", "tests/test_control.py::TestTaskControlCmdOptions::testFilterWrongName", "tests/test_control.py::TestTaskControlCmdOptions::testFilterEmptyList", "tests/test_control.py::TestTaskControlCmdOptions::testOptions", "tests/test_control.py::TestTaskControlCmdOptions::testPosParam", "tests/test_control.py::TestExecNode::test_repr", "tests/test_control.py::TestExecNode::test_ready_select__not_waiting", "tests/test_control.py::TestExecNode::test_parent_status_failure", "tests/test_control.py::TestExecNode::test_parent_status_ignore", "tests/test_control.py::TestExecNode::test_step", "tests/test_control.py::TestDecoratorNoNone::test_filtering", "tests/test_control.py::TestTaskDispatcher_GenNone::test_create", "tests/test_control.py::TestTaskDispatcher_GenNone::test_already_created", "tests/test_control.py::TestTaskDispatcher_GenNone::test_cyclic", "tests/test_control.py::TestTaskDispatcher_node_add_wait_run::test_wait", "tests/test_control.py::TestTaskDispatcher_node_add_wait_run::test_none", "tests/test_control.py::TestTaskDispatcher_node_add_wait_run::test_deps_not_ok", "tests/test_control.py::TestTaskDispatcher_node_add_wait_run::test_calc_dep_already_executed", "tests/test_control.py::TestTaskDispatcher_add_task::test_no_deps", "tests/test_control.py::TestTaskDispatcher_add_task::test_task_deps", "tests/test_control.py::TestTaskDispatcher_add_task::test_task_deps_already_created", "tests/test_control.py::TestTaskDispatcher_add_task::test_task_deps_no_wait", "tests/test_control.py::TestTaskDispatcher_add_task::test_calc_dep", "tests/test_control.py::TestTaskDispatcher_add_task::test_calc_dep_already_executed", "tests/test_control.py::TestTaskDispatcher_add_task::test_setup_task__run", "tests/test_control.py::TestTaskDispatcher_add_task::test_delayed_creation", "tests/test_control.py::TestTaskDispatcher_add_task::test_delayed_creation_sub_task", "tests/test_control.py::TestTaskDispatcher_get_next_node::test_none", "tests/test_control.py::TestTaskDispatcher_get_next_node::test_ready", "tests/test_control.py::TestTaskDispatcher_get_next_node::test_to_run", "tests/test_control.py::TestTaskDispatcher_get_next_node::test_to_run_none", "tests/test_control.py::TestTaskDispatcher_update_waiting::test_wait_select", "tests/test_control.py::TestTaskDispatcher_update_waiting::test_wait_run", "tests/test_control.py::TestTaskDispatcher_update_waiting::test_wait_run_deps_not_ok", "tests/test_control.py::TestTaskDispatcher_update_waiting::test_waiting_node_updated", "tests/test_control.py::TestTaskDispatcher_dispatcher_generator::test_normal", "tests/test_control.py::TestTaskDispatcher_dispatcher_generator::test_delayed_creation" ]
[]
MIT License
160
1,838
[ "doit/cmd_run.py", "doit/control.py", "doit/loader.py", "doit/reporter.py", "doit/task.py" ]
scieloorg__xylose-77
35ee660d381ec682445b2014aadc4b1fa96e414a
2015-06-12 18:46:22
c0be8f42edd0a64900280c871c76b856c2a191f7
diff --git a/setup.py b/setup.py index 0193a00..bb78b72 100755 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ except ImportError: setup( name="xylose", - version='0.10b', + version='0.11b', description="A SciELO library to abstract a JSON data structure that is a product of the ISIS2JSON conversion using the ISIS2JSON type 3 data model.", author="SciELO", author_email="[email protected]", diff --git a/xylose/scielodocument.py b/xylose/scielodocument.py index 5e7c073..59a6a86 100644 --- a/xylose/scielodocument.py +++ b/xylose/scielodocument.py @@ -25,8 +25,8 @@ else: html_parser = unescape # -------------- -LICENSE_REGEX = re.compile(r'a.+href="(.+)"') -LICENSE_CREATIVE_COMMONS = re.compile(r'licenses/(.*?)/.') # Extracts the creative commons id from the url. +LICENSE_REGEX = re.compile(r'a.+?href="(.+?)"') +LICENSE_CREATIVE_COMMONS = re.compile(r'licenses/(.*?/\d\.\d)') # Extracts the creative commons id from the url. DOI_REGEX = re.compile(r'\d{2}\.\d+/.*$') def html_decode(string): @@ -90,6 +90,7 @@ class Journal(object): for dlicense in self.data['v540']: if not 't' in dlicense: continue + license_url = LICENSE_REGEX.findall(dlicense['t']) if len(license_url) == 0: continue @@ -400,6 +401,7 @@ class Article(object): for dlicense in self.data['v540']: if not 't' in dlicense: continue + license_url = LICENSE_REGEX.findall(dlicense['t']) if len(license_url) == 0: continue
Ajustar identificação de licença A identificação de licença coleta atualmente apenas o tipo da licença, ex: by, by-nc..... É importante também considerar a versão ex: by/3.0 by/4.0 by-nc/3.0
scieloorg/xylose
diff --git a/tests/test_document.py b/tests/test_document.py index 745859f..db84c57 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -351,13 +351,13 @@ class JournalTests(unittest.TestCase): journal = Journal(self.fulldoc['title']) - self.assertEqual(journal.permissions['id'], 'by') + self.assertEqual(journal.permissions['id'], 'by/3.0') def test_permission_id(self): journal = Journal(self.fulldoc['title']) - self.assertEqual(journal.permissions['id'], 'by-nc') + self.assertEqual(journal.permissions['id'], 'by-nc/3.0') def test_permission_url(self):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 2 }
0.10
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "", "pip_packages": [ "nose", "coverage", "mocker", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 mocker==1.1.1 nose==1.3.7 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1 -e git+https://github.com/scieloorg/xylose.git@35ee660d381ec682445b2014aadc4b1fa96e414a#egg=xylose
name: xylose channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - mocker==1.1.1 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/xylose
[ "tests/test_document.py::JournalTests::test_permission_id", "tests/test_document.py::JournalTests::test_permission_t1" ]
[]
[ "tests/test_document.py::ToolsTests::test_get_language_iso639_1_defined", "tests/test_document.py::ToolsTests::test_get_language_iso639_1_undefined", "tests/test_document.py::ToolsTests::test_get_language_iso639_2_defined", "tests/test_document.py::ToolsTests::test_get_language_iso639_2_undefined", "tests/test_document.py::ToolsTests::test_get_language_without_iso_format", "tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day", "tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_month", "tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_month_not_int", "tests/test_document.py::ToolsTests::test_get_publication_date_wrong_day_not_int", "tests/test_document.py::ToolsTests::test_get_publication_date_wrong_month_not_int", "tests/test_document.py::ToolsTests::test_get_publication_date_year", "tests/test_document.py::ToolsTests::test_get_publication_date_year_day", "tests/test_document.py::ToolsTests::test_get_publication_date_year_month", "tests/test_document.py::ToolsTests::test_get_publication_date_year_month_day", "tests/test_document.py::JournalTests::test_any_issn_priority_electronic", "tests/test_document.py::JournalTests::test_any_issn_priority_electronic_without_electronic", "tests/test_document.py::JournalTests::test_any_issn_priority_print", "tests/test_document.py::JournalTests::test_any_issn_priority_print_without_print", "tests/test_document.py::JournalTests::test_collection_acronym", "tests/test_document.py::JournalTests::test_creation_date", "tests/test_document.py::JournalTests::test_current_status", "tests/test_document.py::JournalTests::test_current_status_lots_of_changes_study_case_1", "tests/test_document.py::JournalTests::test_current_status_some_changes", "tests/test_document.py::JournalTests::test_current_without_v51", "tests/test_document.py::JournalTests::test_journal", "tests/test_document.py::JournalTests::test_journal_abbreviated_title", "tests/test_document.py::JournalTests::test_journal_acronym", "tests/test_document.py::JournalTests::test_journal_title", "tests/test_document.py::JournalTests::test_journal_title_nlm", "tests/test_document.py::JournalTests::test_journal_url", "tests/test_document.py::JournalTests::test_languages", "tests/test_document.py::JournalTests::test_languages_without_v350", "tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_with_v935_without_v35", "tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_without_v935_without_v35", "tests/test_document.py::JournalTests::test_permission_text", "tests/test_document.py::JournalTests::test_permission_url", "tests/test_document.py::JournalTests::test_permission_without_v540", "tests/test_document.py::JournalTests::test_permission_without_v540_t", "tests/test_document.py::JournalTests::test_publisher_loc", "tests/test_document.py::JournalTests::test_publisher_name", "tests/test_document.py::JournalTests::test_scielo_issn", "tests/test_document.py::JournalTests::test_status", "tests/test_document.py::JournalTests::test_status_lots_of_changes", "tests/test_document.py::JournalTests::test_status_lots_of_changes_study_case_1", "tests/test_document.py::JournalTests::test_status_some_changes", "tests/test_document.py::JournalTests::test_status_without_v51", "tests/test_document.py::JournalTests::test_subject_areas", "tests/test_document.py::JournalTests::test_update_date", "tests/test_document.py::JournalTests::test_without_journal_abbreviated_title", "tests/test_document.py::JournalTests::test_without_journal_acronym", "tests/test_document.py::JournalTests::test_without_journal_title", "tests/test_document.py::JournalTests::test_without_journal_title_nlm", "tests/test_document.py::JournalTests::test_without_journal_url", "tests/test_document.py::JournalTests::test_without_publisher_loc", "tests/test_document.py::JournalTests::test_without_publisher_name", "tests/test_document.py::JournalTests::test_without_scielo_domain", "tests/test_document.py::JournalTests::test_without_scielo_domain_title_v690", "tests/test_document.py::JournalTests::test_without_subject_areas", "tests/test_document.py::JournalTests::test_without_wos_citation_indexes", "tests/test_document.py::JournalTests::test_without_wos_subject_areas", "tests/test_document.py::JournalTests::test_wos_citation_indexes", "tests/test_document.py::JournalTests::test_wos_subject_areas", "tests/test_document.py::ArticleTests::test_acceptance_date", "tests/test_document.py::ArticleTests::test_affiliation_just_with_affiliation_name", "tests/test_document.py::ArticleTests::test_affiliation_without_affiliation_name", "tests/test_document.py::ArticleTests::test_affiliations", "tests/test_document.py::ArticleTests::test_ahead_publication_date", "tests/test_document.py::ArticleTests::test_article", "tests/test_document.py::ArticleTests::test_author_with_two_affiliations", "tests/test_document.py::ArticleTests::test_author_with_two_role", "tests/test_document.py::ArticleTests::test_author_without_affiliations", "tests/test_document.py::ArticleTests::test_author_without_surname_and_given_names", "tests/test_document.py::ArticleTests::test_authors", "tests/test_document.py::ArticleTests::test_collection_acronym", "tests/test_document.py::ArticleTests::test_collection_acronym_priorizing_collection", "tests/test_document.py::ArticleTests::test_collection_acronym_retrieving_v992", "tests/test_document.py::ArticleTests::test_collection_name_brazil", "tests/test_document.py::ArticleTests::test_collection_name_undefined", "tests/test_document.py::ArticleTests::test_corporative_authors", "tests/test_document.py::ArticleTests::test_document_type", "tests/test_document.py::ArticleTests::test_doi", "tests/test_document.py::ArticleTests::test_doi_clean_1", "tests/test_document.py::ArticleTests::test_doi_clean_2", "tests/test_document.py::ArticleTests::test_doi_v237", "tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_1", "tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_2", "tests/test_document.py::ArticleTests::test_end_page_loaded_through_xml", "tests/test_document.py::ArticleTests::test_file_code", "tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_1", "tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_2", "tests/test_document.py::ArticleTests::test_first_author", "tests/test_document.py::ArticleTests::test_first_author_without_author", "tests/test_document.py::ArticleTests::test_fulltexts_field_fulltexts", "tests/test_document.py::ArticleTests::test_fulltexts_without_field_fulltexts", "tests/test_document.py::ArticleTests::test_html_url", "tests/test_document.py::ArticleTests::test_invalid_document_type", "tests/test_document.py::ArticleTests::test_issue", "tests/test_document.py::ArticleTests::test_issue_label_field_v4", "tests/test_document.py::ArticleTests::test_issue_label_without_field_v4", "tests/test_document.py::ArticleTests::test_issue_url", "tests/test_document.py::ArticleTests::test_journal_abbreviated_title", "tests/test_document.py::ArticleTests::test_journal_acronym", "tests/test_document.py::ArticleTests::test_journal_title", "tests/test_document.py::ArticleTests::test_keywords", "tests/test_document.py::ArticleTests::test_keywords_iso639_2", "tests/test_document.py::ArticleTests::test_keywords_with_undefined_language", "tests/test_document.py::ArticleTests::test_keywords_without_subfield_k", "tests/test_document.py::ArticleTests::test_keywords_without_subfield_l", "tests/test_document.py::ArticleTests::test_languages_field_fulltexts", "tests/test_document.py::ArticleTests::test_languages_field_v40", "tests/test_document.py::ArticleTests::test_last_page", "tests/test_document.py::ArticleTests::test_mixed_affiliations", "tests/test_document.py::ArticleTests::test_normalized_affiliations", "tests/test_document.py::ArticleTests::test_normalized_affiliations_undefined_ISO_3166_CODE", "tests/test_document.py::ArticleTests::test_normalized_affiliations_without_p", "tests/test_document.py::ArticleTests::test_original_abstract_with_just_one_language_defined", "tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined", "tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined_but_different_of_the_article_original_language", "tests/test_document.py::ArticleTests::test_original_abstract_without_language_defined", "tests/test_document.py::ArticleTests::test_original_language_invalid_iso639_2", "tests/test_document.py::ArticleTests::test_original_language_iso639_2", "tests/test_document.py::ArticleTests::test_original_language_original", "tests/test_document.py::ArticleTests::test_original_title_with_just_one_language_defined", "tests/test_document.py::ArticleTests::test_original_title_with_language_defined", "tests/test_document.py::ArticleTests::test_original_title_with_language_defined_but_different_of_the_article_original_language", "tests/test_document.py::ArticleTests::test_original_title_without_language_defined", "tests/test_document.py::ArticleTests::test_pdf_url", "tests/test_document.py::ArticleTests::test_processing_date", "tests/test_document.py::ArticleTests::test_project_name", "tests/test_document.py::ArticleTests::test_project_sponsors", "tests/test_document.py::ArticleTests::test_publication_contract", "tests/test_document.py::ArticleTests::test_publication_date", "tests/test_document.py::ArticleTests::test_publisher_id", "tests/test_document.py::ArticleTests::test_publisher_loc", "tests/test_document.py::ArticleTests::test_publisher_name", "tests/test_document.py::ArticleTests::test_receive_date", "tests/test_document.py::ArticleTests::test_review_date", "tests/test_document.py::ArticleTests::test_start_page", "tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_1", "tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_2", "tests/test_document.py::ArticleTests::test_start_page_loaded_through_xml", "tests/test_document.py::ArticleTests::test_subject_areas", "tests/test_document.py::ArticleTests::test_supplement_issue", "tests/test_document.py::ArticleTests::test_supplement_volume", "tests/test_document.py::ArticleTests::test_thesis_degree", "tests/test_document.py::ArticleTests::test_thesis_organization", "tests/test_document.py::ArticleTests::test_thesis_organization_and_division", "tests/test_document.py::ArticleTests::test_thesis_organization_without_name", "tests/test_document.py::ArticleTests::test_translated_abstracts", "tests/test_document.py::ArticleTests::test_translated_abstracts_without_v83", "tests/test_document.py::ArticleTests::test_translated_abtracts_iso639_2", "tests/test_document.py::ArticleTests::test_translated_titles", "tests/test_document.py::ArticleTests::test_translated_titles_iso639_2", "tests/test_document.py::ArticleTests::test_translated_titles_without_v12", "tests/test_document.py::ArticleTests::test_volume", "tests/test_document.py::ArticleTests::test_whitwout_acceptance_date", "tests/test_document.py::ArticleTests::test_whitwout_ahead_publication_date", "tests/test_document.py::ArticleTests::test_whitwout_receive_date", "tests/test_document.py::ArticleTests::test_whitwout_review_date", "tests/test_document.py::ArticleTests::test_without_affiliations", "tests/test_document.py::ArticleTests::test_without_authors", "tests/test_document.py::ArticleTests::test_without_citations", "tests/test_document.py::ArticleTests::test_without_collection_acronym", "tests/test_document.py::ArticleTests::test_without_corporative_authors", "tests/test_document.py::ArticleTests::test_without_document_type", "tests/test_document.py::ArticleTests::test_without_doi", "tests/test_document.py::ArticleTests::test_without_html_url", "tests/test_document.py::ArticleTests::test_without_issue", "tests/test_document.py::ArticleTests::test_without_issue_url", "tests/test_document.py::ArticleTests::test_without_journal_abbreviated_title", "tests/test_document.py::ArticleTests::test_without_journal_acronym", "tests/test_document.py::ArticleTests::test_without_journal_title", "tests/test_document.py::ArticleTests::test_without_keywords", "tests/test_document.py::ArticleTests::test_without_last_page", "tests/test_document.py::ArticleTests::test_without_normalized_affiliations", "tests/test_document.py::ArticleTests::test_without_original_abstract", "tests/test_document.py::ArticleTests::test_without_original_title", "tests/test_document.py::ArticleTests::test_without_pages", "tests/test_document.py::ArticleTests::test_without_pdf_url", "tests/test_document.py::ArticleTests::test_without_processing_date", "tests/test_document.py::ArticleTests::test_without_project_name", "tests/test_document.py::ArticleTests::test_without_project_sponsor", "tests/test_document.py::ArticleTests::test_without_publication_contract", "tests/test_document.py::ArticleTests::test_without_publication_date", "tests/test_document.py::ArticleTests::test_without_publisher_id", "tests/test_document.py::ArticleTests::test_without_publisher_loc", "tests/test_document.py::ArticleTests::test_without_publisher_name", "tests/test_document.py::ArticleTests::test_without_scielo_domain", "tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69", "tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69_and_with_title_v690", "tests/test_document.py::ArticleTests::test_without_scielo_domain_title_v690", "tests/test_document.py::ArticleTests::test_without_start_page", "tests/test_document.py::ArticleTests::test_without_subject_areas", "tests/test_document.py::ArticleTests::test_without_suplement_issue", "tests/test_document.py::ArticleTests::test_without_supplement_volume", "tests/test_document.py::ArticleTests::test_without_thesis_degree", "tests/test_document.py::ArticleTests::test_without_thesis_organization", "tests/test_document.py::ArticleTests::test_without_volume", "tests/test_document.py::ArticleTests::test_without_wos_citation_indexes", "tests/test_document.py::ArticleTests::test_without_wos_subject_areas", "tests/test_document.py::ArticleTests::test_wos_citation_indexes", "tests/test_document.py::ArticleTests::test_wos_subject_areas", "tests/test_document.py::CitationTest::test_a_link_access_date", "tests/test_document.py::CitationTest::test_analytic_institution_for_a_article_citation", "tests/test_document.py::CitationTest::test_analytic_institution_for_a_book_citation", "tests/test_document.py::CitationTest::test_article_title", "tests/test_document.py::CitationTest::test_article_without_title", "tests/test_document.py::CitationTest::test_authors_article", "tests/test_document.py::CitationTest::test_authors_book", "tests/test_document.py::CitationTest::test_authors_link", "tests/test_document.py::CitationTest::test_authors_thesis", "tests/test_document.py::CitationTest::test_book_chapter_title", "tests/test_document.py::CitationTest::test_book_edition", "tests/test_document.py::CitationTest::test_book_volume", "tests/test_document.py::CitationTest::test_book_without_chapter_title", "tests/test_document.py::CitationTest::test_citation_sample_congress", "tests/test_document.py::CitationTest::test_citation_sample_link", "tests/test_document.py::CitationTest::test_citation_sample_link_without_comment", "tests/test_document.py::CitationTest::test_conference_edition", "tests/test_document.py::CitationTest::test_conference_name", "tests/test_document.py::CitationTest::test_conference_sponsor", "tests/test_document.py::CitationTest::test_conference_without_name", "tests/test_document.py::CitationTest::test_conference_without_sponsor", "tests/test_document.py::CitationTest::test_date", "tests/test_document.py::CitationTest::test_doi", "tests/test_document.py::CitationTest::test_editor", "tests/test_document.py::CitationTest::test_end_page_14", "tests/test_document.py::CitationTest::test_end_page_514", "tests/test_document.py::CitationTest::test_end_page_withdout_data", "tests/test_document.py::CitationTest::test_first_author_article", "tests/test_document.py::CitationTest::test_first_author_book", "tests/test_document.py::CitationTest::test_first_author_link", "tests/test_document.py::CitationTest::test_first_author_thesis", "tests/test_document.py::CitationTest::test_first_author_without_monographic_authors", "tests/test_document.py::CitationTest::test_first_author_without_monographic_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_index_number", "tests/test_document.py::CitationTest::test_institutions_all_fields", "tests/test_document.py::CitationTest::test_institutions_v11", "tests/test_document.py::CitationTest::test_institutions_v17", "tests/test_document.py::CitationTest::test_institutions_v29", "tests/test_document.py::CitationTest::test_institutions_v50", "tests/test_document.py::CitationTest::test_institutions_v58", "tests/test_document.py::CitationTest::test_invalid_edition", "tests/test_document.py::CitationTest::test_isbn", "tests/test_document.py::CitationTest::test_isbn_but_not_a_book", "tests/test_document.py::CitationTest::test_issn", "tests/test_document.py::CitationTest::test_issn_but_not_an_article", "tests/test_document.py::CitationTest::test_issue_part", "tests/test_document.py::CitationTest::test_issue_title", "tests/test_document.py::CitationTest::test_journal_issue", "tests/test_document.py::CitationTest::test_journal_volume", "tests/test_document.py::CitationTest::test_link", "tests/test_document.py::CitationTest::test_link_title", "tests/test_document.py::CitationTest::test_link_without_title", "tests/test_document.py::CitationTest::test_monographic_authors", "tests/test_document.py::CitationTest::test_monographic_first_author", "tests/test_document.py::CitationTest::test_pages_14", "tests/test_document.py::CitationTest::test_pages_514", "tests/test_document.py::CitationTest::test_pages_withdout_data", "tests/test_document.py::CitationTest::test_publication_type_article", "tests/test_document.py::CitationTest::test_publication_type_book", "tests/test_document.py::CitationTest::test_publication_type_conference", "tests/test_document.py::CitationTest::test_publication_type_link", "tests/test_document.py::CitationTest::test_publication_type_thesis", "tests/test_document.py::CitationTest::test_publication_type_undefined", "tests/test_document.py::CitationTest::test_publisher", "tests/test_document.py::CitationTest::test_publisher_address", "tests/test_document.py::CitationTest::test_publisher_address_without_e", "tests/test_document.py::CitationTest::test_series_book", "tests/test_document.py::CitationTest::test_series_but_neither_journal_book_or_conference_citation", "tests/test_document.py::CitationTest::test_series_conference", "tests/test_document.py::CitationTest::test_series_journal", "tests/test_document.py::CitationTest::test_source_book_title", "tests/test_document.py::CitationTest::test_source_journal", "tests/test_document.py::CitationTest::test_source_journal_without_journal_title", "tests/test_document.py::CitationTest::test_sponsor", "tests/test_document.py::CitationTest::test_start_page_14", "tests/test_document.py::CitationTest::test_start_page_514", "tests/test_document.py::CitationTest::test_start_page_withdout_data", "tests/test_document.py::CitationTest::test_thesis_institution", "tests/test_document.py::CitationTest::test_thesis_title", "tests/test_document.py::CitationTest::test_thesis_without_title", "tests/test_document.py::CitationTest::test_title_when_article_citation", "tests/test_document.py::CitationTest::test_title_when_conference_citation", "tests/test_document.py::CitationTest::test_title_when_link_citation", "tests/test_document.py::CitationTest::test_title_when_thesis_citation", "tests/test_document.py::CitationTest::test_with_volume_but_not_a_journal_article_neither_a_book", "tests/test_document.py::CitationTest::test_without_analytic_institution", "tests/test_document.py::CitationTest::test_without_authors", "tests/test_document.py::CitationTest::test_without_date", "tests/test_document.py::CitationTest::test_without_doi", "tests/test_document.py::CitationTest::test_without_edition", "tests/test_document.py::CitationTest::test_without_editor", "tests/test_document.py::CitationTest::test_without_first_author", "tests/test_document.py::CitationTest::test_without_index_number", "tests/test_document.py::CitationTest::test_without_institutions", "tests/test_document.py::CitationTest::test_without_issue", "tests/test_document.py::CitationTest::test_without_issue_part", "tests/test_document.py::CitationTest::test_without_issue_title", "tests/test_document.py::CitationTest::test_without_link", "tests/test_document.py::CitationTest::test_without_monographic_authors", "tests/test_document.py::CitationTest::test_without_monographic_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_without_publisher", "tests/test_document.py::CitationTest::test_without_publisher_address", "tests/test_document.py::CitationTest::test_without_series", "tests/test_document.py::CitationTest::test_without_sponsor", "tests/test_document.py::CitationTest::test_without_thesis_institution", "tests/test_document.py::CitationTest::test_without_volume" ]
[]
BSD 2-Clause "Simplified" License
166
492
[ "setup.py", "xylose/scielodocument.py" ]
praw-dev__praw-426
eb91d191eb09d94df144589ba6561f387a3a2922
2015-06-15 14:08:27
eb91d191eb09d94df144589ba6561f387a3a2922
diff --git a/praw/objects.py b/praw/objects.py index df96fbf1..f4014f10 100755 --- a/praw/objects.py +++ b/praw/objects.py @@ -75,7 +75,7 @@ class RedditContentObject(object): def __getattr__(self, attr): """Return the value of the `attr` attribute.""" - if not self.has_fetched: + if attr != '__setstate__' and not self.has_fetched: self.has_fetched = self._populate(None, True) return getattr(self, attr) raise AttributeError('\'%s\' has no attribute \'%s\'' % (type(self),
Can't unpickle Comment objects (maximum recursion depth exceeded) Here's the stack trace: ```pytb >>> import pickle >>> import praw >>> r = praw.Reddit('test') >>> comment = r.get_info(thing_id='t1_cs6woop') >>> pickled = pickle.dumps(comment) >>> pickle.loads(pickled) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/python2.7/pickle.py", line 1382, in loads return Unpickler(file).load() File "/usr/lib/python2.7/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.7/pickle.py", line 1215, in load_build setstate = getattr(inst, "__setstate__", None) File "/home/___/.virtualenvs/___/local/lib/python2.7/site-packages/praw/objects.py", line 82, in __getattr__ if not self.has_fetched: File "/home/___/.virtualenvs/___/local/lib/python2.7/site-packages/praw/objects.py", line 82, in __getattr__ if not self.has_fetched: File "/home/___/.virtualenvs/___/local/lib/python2.7/site-packages/praw/objects.py", line 82, in __getattr__ if not self.has_fetched: ... RuntimeError: maximum recursion depth exceeded ```
praw-dev/praw
diff --git a/tests/cassettes/test_unpickle_comment.json b/tests/cassettes/test_unpickle_comment.json new file mode 100644 index 00000000..ce5e4d79 --- /dev/null +++ b/tests/cassettes/test_unpickle_comment.json @@ -0,0 +1,1 @@ +{"recorded_with": "betamax/0.4.2", "http_interactions": [{"recorded_at": "2015-06-15T13:50:36", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"transfer-encoding": ["chunked"], "cache-control": ["private, no-cache", "no-cache"], "server": ["cloudflare-nginx"], "set-cookie": ["__cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236; expires=Tue, 14-Jun-16 13:50:36 GMT; path=/; domain=.reddit.com; HttpOnly", "secure_session=; Domain=reddit.com; Max-Age=-1434376237; Path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; HttpOnly", "reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; Domain=reddit.com; Path=/; HttpOnly"], "x-moose": ["majestic"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-frame-options": ["SAMEORIGIN"], "cf-ray": ["1f6ebeb510a504a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:37 GMT"], "content-type": ["application/json; charset=UTF-8"], "x-content-type-options": ["nosniff"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAAxzLTWrDMBBA4auIWSug0c+MpXNkV0oZWaM6TRMV26GL4LuXdPs+3hO+tnGHYp6g6zrWDYp5e7cGmuzyn++q7WPZ958Xdfne1Bq4jbbItkAxcPt8CD+uv3zBPElGVidEnZPXWmtLVSmRsnOkVTwqR7AG5jGuF339HJyfiK13mE6OTpjOjkpyJbCdnSLGij0mwTozhTzFGuI8hRaw9Zgl+64NjuP4AwAA//8DABH3aj7KAAAA"}, "url": "https://api.reddit.com/api/login/.json"}, "request": {"headers": {"Accept-Encoding": ["gzip, deflate"], "Connection": ["keep-alive"], "Accept": ["*/*"], "Content-Length": ["45"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Content-Type": ["application/x-www-form-urlencoded"]}, "body": {"encoding": "utf-8", "string": "passwd=1111&api_type=json&user=PyAPITestUser2"}, "uri": "https://api.reddit.com/api/login/.json", "method": "POST"}}, {"recorded_at": "2015-06-15T13:50:37", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["299"], "content-type": ["application/json; charset=UTF-8"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["2574"], "server": ["cloudflare-nginx"], "x-content-type-options": ["nosniff"], "x-moose": ["majestic"], "x-ratelimit-used": ["1"], "x-frame-options": ["SAMEORIGIN"], "x-sup-id": ["http://www.reddit.com/sup.json#e4356386a7"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=HcLLGdCwZSCTj%2BYMBgG8Ln0%2FKHA5a%2FIoJVNJ%2Fv%2FXrv6TSUaosRpQ67%2Fyfcg6Z7i5Diz8FZevtuCHzUmagS6TUQ7G47Go4bcv"], "cf-ray": ["1f6ebeb9f0cd04a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:37 GMT"], "x-ratelimit-reset": ["563"], "vary": ["accept-encoding"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAC3YflUC/+2cW2/bRhqG/4rgi6KLzcRzPqQoFotFgV1gL3rRYi/qhTAnRox1ikT5FPS/d2ZIKpTkOpJFUrLrG8cmafKd+b734Ts0oy8X1/nUXXwYXPw3Xxb59OPFu8GF04UOm75cTGZupJejuNsvVlO4yPESeWSVdAR7yz3VAmVQQwup4BZxCWVmtDeCIB7PZEf52C38NJzhty/rSxVo4yrLlVl45/JimJe72RAXbJZOMM6n18MiL8Y+7vlffp0PfpoWi/vBbDq4WkFoSfyqbDzW6OnUu6G5D4dOV+Nx2LTwk9mNHg8XXi9nUUW1PZ22uhoZEirvaLG+nF4Vo9ki7vv5/p8//+cXvyx+XfoFLg+49suwq1isfDr/fJynDRdx7yocFq41ny2KuO23/4dtS33j44UyPV7GXymvaj8vPc4f4i99DFOUjoDhB70IU7b5C+X5qiGsT/uUyLkOU76eTTQMF3P5tY67lna2iFOJ4inm88XsZmvG7CxMb9i6WOZ6nBdxT9RlZi5+e/HrNP+88oM47vsPA7mYf75Wo5vra2g4xYwb5KEWkmkBCUYs9IOiOOPcWcKQIDpp8KHUGyMsxzLMxjpfDO1yObRjvUyTeneXOmV2mwZeCxmOisk47v5uXPzg8ptBOv7Hq4uJu7r47mPxQ9w+j98cKzee6DKd6Wqavg9Xiz+lqazbNiqpGljP82ERSrGe6uEody71fz3YqZ6kXi7rUjeBDeUtJwVRArEikKP3qSGac1P4u3i1ZhOvFmkmRkUx/3B56afvb4NH5mGK9fvZ4uNl0yP/yN2PeHFLb8yDcvcCU5tB7Aj3yhAPkUDOkEwo5IThGRQ0k07wZNVK3XBV2FqhVLRSuJrH2sSGCrjY7v7patLYFA93JWdW+XKUxhsH8/vv7wZveNjGA3/peLCf/Kf5IpwCca0QM8QST53KoJRUU8yJ8t6K4DlOENMYKX81vZr+/adQ68EvsdXfnRAWh4tvwqLERfrh63h6oEnZM7s0IfDcaVIpfKNJVzRJQ+yaJs3xtQQTO5tMwhU+DDxC5AGtGJ4xawiTWglFJeXaK42QQ8YjgsL9HGbQKOY9UqcByBGC+yBEGcx3CIHluROiUvhGiE4IUUeAl0SIf4fBDJaziR+sprmdOf9h8H0sgAsHpX/d355IFFVfQaR2O79VLuwh8/TZoa7/NhkQwWx3fs6JDEJUCs+HDLH/B//SdhRKrR1llGUaxAECSsMXwxAHmDHHnIfCGX8cL9C9ZqlFe+QFD4NKmOuBF+vx9cCLDUJ0Hxn2UNS189eVbDofS8aCtfAznH97e/u+lPI+JKHLxeWWrssqHy0vy8Jexo1DG80yrL0SrRKdEo3S9MnlYwwIWinnldbzZACiBlnCDLAaOkCVRUBxYgAh0EKmncBKHMsANvnUOwNocd0HA1Kb4uWtaQMCm8t86K32nmRASmYBJThUhmICFNYUUSuJ4+mqPTLhcIHdI6Iq9C4i+HOWDQchIvR1ExG1laKTopGij5o2egIRldbzRMRrjQl0nmana0S0GRO21/FGIGQyiQHVMFiQQQi0CJXSWei7zHBHTKJ3/4w4SGIPlChr/QglXlCQqLSeJyVeaZDAhU1/ee6FEtX4jqXEHtH9yYcPZbdRuuuMVkmxh8wmGE7y8GFd/y1yUAnFcx4+HESOtvIFpZXW8yRHBhFTMLMgEjHcJjQHRjoGZMawFeFm4XQyzBHkuHsY0f7JgRLwuiZHalP4cJtWyseiYzPhC0eozUQGkFChMj4kP6kMBN5bhgWFWjC4wY7e4sUBAntARFnoXUQ8602JQxAR+7qJiNpKKVsEI0UfNW30BCLO7p2Jv0K4qB4cdI2INsPFdr5XjFPuwrKfhLsMoJxJoLTMAOYaqUw5bLKkqH9GHCSxe0pUtd6lBHtBQaLSep6UeKVBAkEh+6JEPb5jKbFHtv/mEoRSInad0Sop9pB5+iVIXf9tcjBIHlmitUqO1vIFopXWN3L0SI56VfCSyLF98zYSWw8xjX9g4KE0SIfSZAx4I32GrZHEZBvw6D9f7COxc0rUtd6lBH7OG5YnokSl9TwpwSVmQkIFsIAhR9JQZ00EjktOkWWKKlIuh59NCbx88CQp7Y8S05Wa2Gk/lPg6vmMpsceN+5v5AlH4yMP/Vkmxh8xT54uv9d8gBwotztQj75+1SI6yHZrkqB0WDRb9Fe3VdNfj5GhqfSNHr+Rgn/sgR9mm45t0sWPRsfkEkWitnacEMGs9oF6HynAoAVEeQRsWxBSe6GXtAwT2gIiy0I8gottHnO0i4pwfcb5WRFSu7RoRbYaL7XyvEKTaMgbCQtyFfM8EUAwjYJVVxlvJoD3Rm1gHSeyeElWtdykhXlCQqLSeJyWQEZYo5IDkVgPKKQMmw+FuwMOdweqwENXkWEoYlR439UkJWUyT7F4oUY3vWErske2fXoKkbmNk1xmtkmIPmadfgtT13yYHJbzbP46U7bDxx5HKYdFg0V/RXk13/Sk51lrPkxyWZZAqxwCjMuQLIzjQVEGgiPYI4bBHuWPJoa7v+ycHy/sgR9mmZjRvAx1bLzEQBDmlHkBtFKASWaA1lUBCzK1h2GJ8oiecBwjsARFloXcRQTtHROjrJiJqK0UnRSNFHzVt9AQiKq3niYhXGy5g+stE14hoM1xs53tuMJUaZUBLFOiNvANGaQE0F4IbKKGxJ3oT6yCJPVCirPUuJUjnS5D2gkSl9Twp8VqDhJU9vej9dXzHUmKPbP/NJQgl+G0J0qj/NjkIx52To618sdZ6nuQghiEmlAwRMkCDMkyA1FkWH2obmyFvnTv6ESdfrHonh7ntJV+kNhWdfB6WIZZyEyDumIOACmuBzCgCIbAaw1i4cdGU/PqPFwcI7B4RVaF3EYE6X4KEvm4iorZSdFI0UvRR00ZPIKLSep6IeK3honpw0DUi2gwX2/ke+swbRRBA3AR68wwCY6UCRuMMcoQhwklR/4w4SGIPlChrvUMJprr9H+ltBola63lS4pUGCfEJJef2QolqfMdSYo9s/80lCGGPfZxLq6TYQ+bplyB1/bfJgSl6ZH7aJUdb+WKt9TzJoUmGHQ/RAmGO438k40BRG3IklJo5IS1l6XWfI8hx9zC77Z0c+bwXcsQ2LW5uJmmOjkXHZsJXFCsBRRbyHnKAYiKAMpkHmBlnEDImY6f9jO59BHaPiKrQO4ggnYeL2NdNRNRWik6KRoo+atrozxFRaz1PRLzWcNHbp2i2Fy528j0nRGhPASc4viOnGVDCGwCxDs5kmUblZzH2z4iDJPZAid1PzKyc93KCRK31PCnxOoNEuLcX6Zp9UKIe37GU2CPbf3MJEu7mfNcZrZJiD5knX4Ks679JDi4JedancB9CjpbyRUNrK+RIfZ0VPrX15iQZn5WdWx75B7y/uSWyaAAA"}, "url": "https://api.reddit.com/user/PyAPITestUser2/comments.json?sort=new&t=all"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/comments.json?sort=new&t=all", "method": "GET"}}, {"recorded_at": "2015-06-15T13:50:38", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["298"], "transfer-encoding": ["chunked"], "cache-control": ["private, no-cache", "no-cache"], "x-moose": ["majestic"], "server": ["cloudflare-nginx"], "x-ratelimit-used": ["2"], "x-frame-options": ["SAMEORIGIN"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=6qsn21tVL7go5HvVpotLbf0tnpT2hujgxe4105fEz7G1t0%2BHh25pl%2FSGghZNuAZaGB%2FJKaxz67I%3D"], "cf-ray": ["1f6ebebe912c04a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:38 GMT"], "x-ratelimit-reset": ["562"], "content-type": ["application/json; charset=UTF-8"], "x-content-type-options": ["nosniff"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA1yRwW7DIBBEfwVxtqrYxgn2rcfecmjPaANLvYqBCnCUNsq/V6AkjXodzQ5vhgs/kjd8Yjx3vGHcQAY+sQufISkHtPCJWVgSNox7cFic++/X/ds7pvyRMNYrSspGwhp0d+uIkLEobSfFth02cnjZNIzPZFDZGJyK4RByerr5DItROqIxVPVid8HMkOby8LYVLq1j+Nl1BzNYsYGulwjCgu7sCOM49LtejhalMJ0WW7krcDcQtWb9gGnFHabUDOZ/1YX8UR0hujJG25WU4Bz6/BDHhvFwwqhaySeW41rOKKlS4SmIavyfozbE8xdFyBQ8n5hfl+UGcsJIltAovOHcY+sHCU1nW9f2h3BWOqw+l42u118AAAD//wMAKxRkF8UBAAA="}, "url": "https://api.reddit.com/user/PyAPITestUser2/about/.json"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/about/.json", "method": "GET"}}, {"recorded_at": "2015-06-15T13:50:38", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["297"], "content-type": ["application/json; charset=UTF-8"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["682"], "server": ["cloudflare-nginx"], "x-content-type-options": ["nosniff"], "x-moose": ["majestic"], "x-ratelimit-used": ["3"], "x-frame-options": ["SAMEORIGIN"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=AqxVkrSRF3bN55ymSSdkwfD%2FLdA4QMcYwodHHwNYU4Pccch5s1XTILSk9LACd6ER3FcO3MQmUDmhY5Rn5rzZjrp3D2F%2F%2BvsO"], "cf-ray": ["1f6ebec1714204a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:38 GMT"], "x-ratelimit-reset": ["562"], "vary": ["accept-encoding"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAC7YflUC/61UyU7cQBD9FccHTsx4XwaUAyIimgOLICdC1OqlPNOZ9kJ3e2BA/Hu6G5sxHJCQcrHsqvKrV/Wq6tnf8Ib5R56vM//Q8xnW2Hw9+wQ3DUjE65V1WpfqSc010vCo0VrXwtibXgjj6ZWNVMj9Y8EqLBQYB3fIsc7a3CKMcbRttOSk1600fi17GzuBHzMyrjqBd6jBNVibBMZMCO64CVPahqwBsz3NtdbdURCQuV73NVHz1x9qYBzPaVsH0c/0PF5dIX41u87l7cU5e7g0hPqL5RKj/vIpOl1GJ7ebEHV0/rdbOQ6gqOSd5m0zVu0fCH38bTbzbk7R5dmZN5sdrPSxNTK+9ajASn2/82t254/2zr782CN5BS3ytHpI6D0UjEZZXpQQVqQK0yIvUhpnxYLQjMa0giTJwoyFFiZwOHeNeze5RviRy8VAxfLWXAvXtGvXA+/kaun9Mk3z0oeUb7aPOfRJRXLDglR5SnHF4qLMU8DVgkAZFSRMynBB8pDFFo62QuBOAWIgQAMzGtY1NFpN1O56IjhFk47Z/NOyxT3Uuo8SuSuyKCxTVuRltFiYSqO8jG3hizJb4CysGKQljUqXu92CjMpPE/1Hab7O8avScDP/SPEnK8+wQc402bVhrEcRh6hPOvv1gZqstODNBglMYLLTmNK2N/oiTDXfWhLRvvNa4qridCLJQHio6ncShoeeefx5TWJ5EpB2WOJ4n9edkg95x13XGXq7G1QC1u6wREkcZ1lYFNncJPB76UQPZPDhNASuiZwBwmw6ogMS6rUl/wFtOHnvlRlvVt2a+vC7i+Vcyqi0hhoQNJgIR3JwDxuCFG0lIEem5o1lY5OZFgyc9a5zFb/29k0Wpexcj07c7KYXdN/TsbiXl38Stiz/ywUAAA=="}, "url": "https://api.reddit.com/r/reddit_api_test/about/.json"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/r/reddit_api_test/about/.json", "method": "GET"}}]} \ No newline at end of file diff --git a/tests/test_comments.py b/tests/test_comments.py index 343e8dc3..2acced95 100644 --- a/tests/test_comments.py +++ b/tests/test_comments.py @@ -1,6 +1,7 @@ """Tests for Comment class.""" from __future__ import print_function, unicode_literals +import pickle from praw import helpers from praw.objects import Comment, MoreComments from .helper import PRAWTest, betamax @@ -97,6 +98,15 @@ class CommentTest(PRAWTest): lambda item: isinstance(item, Comment)) self.assertEqual(comment._replies, None) + @betamax + def test_unpickle_comment(self): + item = next(self.r.user.get_comments()) + pkl = pickle.dumps(item) + try: + pickle.loads(pkl) + except RuntimeError: + self.fail("unpickling shouldn't throw a RuntimeError exception") + class MoreCommentsTest(PRAWTest): def betamax_init(self):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "flake8", "betamax", "betamax-matchers", "mock", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
betamax==0.9.0 betamax-matchers==0.4.0 certifi==2025.1.31 charset-normalizer==3.4.1 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work flake8==7.2.0 idna==3.10 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mccabe==0.7.0 mock==5.2.0 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work -e git+https://github.com/praw-dev/praw.git@eb91d191eb09d94df144589ba6561f387a3a2922#egg=praw pycodestyle==2.13.0 pyflakes==3.3.1 pytest @ file:///croot/pytest_1738938843180/work requests==2.32.3 requests-toolbelt==1.0.0 six==1.17.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work update-checker==0.18.0 urllib3==2.3.0
name: praw channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - betamax==0.9.0 - betamax-matchers==0.4.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - flake8==7.2.0 - idna==3.10 - mccabe==0.7.0 - mock==5.2.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - requests==2.32.3 - requests-toolbelt==1.0.0 - six==1.17.0 - update-checker==0.18.0 - urllib3==2.3.0 prefix: /opt/conda/envs/praw
[ "tests/test_comments.py::CommentTest::test_unpickle_comment" ]
[]
[ "tests/test_comments.py::CommentTest::test_add_comment", "tests/test_comments.py::CommentTest::test_add_reply", "tests/test_comments.py::CommentTest::test_edit", "tests/test_comments.py::CommentTest::test_front_page_comment_replies_are_none", "tests/test_comments.py::CommentTest::test_get_comments_permalink", "tests/test_comments.py::CommentTest::test_inbox_comment_permalink", "tests/test_comments.py::CommentTest::test_inbox_comment_replies_are_none", "tests/test_comments.py::CommentTest::test_save_comment", "tests/test_comments.py::CommentTest::test_spambox_comments_replies_are_none", "tests/test_comments.py::CommentTest::test_unicode_comment", "tests/test_comments.py::CommentTest::test_user_comment_permalink", "tests/test_comments.py::CommentTest::test_user_comment_replies_are_none", "tests/test_comments.py::MoreCommentsTest::test_all_comments", "tests/test_comments.py::MoreCommentsTest::test_comments_method" ]
[]
BSD 2-Clause "Simplified" License
168
163
[ "praw/objects.py" ]
mkdocs__mkdocs-668
98814de505c9d8f1849292372eff1c5ae492261c
2015-06-27 22:50:14
3dfd95deae8379473714b346e61c1d63e957bb98
landscape-bot: [![Code Health](https://landscape.io/badge/198248/landscape.svg?style=flat)](https://landscape.io/diff/187394) Code quality remained the same when pulling **[a5ab2e1](https://github.com/d0ugal/mkdocs/commit/a5ab2e12e22a199617fcffd129d4762bfc6b712b) on d0ugal:symlink** into **[98814de](https://github.com/mkdocs/mkdocs/commit/98814de505c9d8f1849292372eff1c5ae492261c) on mkdocs:master**.
diff --git a/mkdocs/config/config_options.py b/mkdocs/config/config_options.py index 38a61442..28ee62c8 100644 --- a/mkdocs/config/config_options.py +++ b/mkdocs/config/config_options.py @@ -332,6 +332,13 @@ class Extras(OptionallyRequired): dirs.sort() for filename in sorted(filenames): fullpath = os.path.join(dirpath, filename) + + # Some editors (namely Emacs) will create temporary symlinks + # for internal magic. We can just ignore these files. + if os.path.islink(fullpath): + if not os.path.exists(os.readlink(fullpath)): + continue + relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir)) if self.file_match(relpath): yield relpath
Ignore broken symlinks in mkdocs serve. What I am experiencing: * When I am editing `index.md` in Emacs, Emacs creates files like: ``` ➜ docs git:(master) ✗ ls -al .#* lrwxrwxrwx 1 paulproteus paulproteus 36 Jun 17 17:24 .#index.md -> [email protected]:1434311808 ``` * These files are Emacs' way of using symlinks to track which computer+process was Emacs-ing the file, so that in case of a crash, Emacs can figure out how to restore its state. What I expect: * When I edit `somethingelse.md` and press save, I expect the mkdocs livereload to reload the browser. What I see instead: ``` INFO - Building documentation... ERROR - file not found: /home/paulproteus/projects/sandstorm/docs/.#index.md ERROR - Error building page .#index.md [E 150617 17:22:21 ioloop:612] Exception in callback (3, <function null_wrapper at 0x7fc883190500>) Traceback (most recent call last): File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/ioloop.py", line 866, in start handler_func(fd_obj, events) File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/stack_context.py", line 275, in null_wrapper return fn(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1604, in handle_read self.process_events() File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1321, in process_events self._default_proc_fun(revent) File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 152, in inotify_event self.callback() File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/handlers.py", line 65, in poll_tasks filepath, delay = cls.watcher.examine() File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 72, in examine func and func() File "/usr/lib/python2.7/dist-packages/mkdocs/serve.py", line 74, in builder build(config, live_server=True) File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 299, in build build_pages(config) File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 259, in build_pages dump_json) File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 171, in _build_page input_content = io.open(input_path, 'r', encoding='utf-8').read() IOError: [Errno 2] No such file or directory: '/home/paulproteus/projects/sandstorm/docs/.#index.md' ``` What I propose: * If a "No such file or directory" error occurs, but the problem is a broken symlink, the `mkdocs` build should continue as if the file does not exist. Note that this arguably is a special-case to handle Emacs' own weirdness; a different way to do it would be to look at the list of git ignored files. * Perhaps in general, `mkdocs` should issue a warning (not an error) on broken symlinks, gracefully ignoring them. I'm open to a bunch of ideas. I wanted to file this in the hopes of sparking a discussion where the maintainers of mkdocs could express their opinion about the best way forward. Thanks so much! Also hi! I'm twitter.com/asheeshlaroia and was chatting with a mkdocs developer earlier today. Seems like a great project! I learned about it via http://ericholscher.com/blog/2014/feb/27/how-i-judge-documentation-quality/ !
mkdocs/mkdocs
diff --git a/mkdocs/tests/config/config_options_tests.py b/mkdocs/tests/config/config_options_tests.py index b1e7bff7..d16f675b 100644 --- a/mkdocs/tests/config/config_options_tests.py +++ b/mkdocs/tests/config/config_options_tests.py @@ -1,6 +1,7 @@ from __future__ import unicode_literals import os +import tempfile import unittest from mkdocs import utils @@ -251,6 +252,25 @@ class ExtrasTest(unittest.TestCase): self.assertRaises(config_options.ValidationError, option.validate, {}) + def test_talk(self): + + option = config_options.Extras(utils.is_markdown_file) + + tmp_dir = tempfile.mkdtemp() + + f1 = os.path.join(tmp_dir, 'file1.md') + f2 = os.path.join(tmp_dir, 'file2.md') + + open(f1, 'a').close() + + # symlink isn't available on Python 2 on Windows. + if hasattr(os, 'symlink'): + os.symlink('/path/that/doesnt/exist', f2) + + files = list(option.walk_docs_dir(tmp_dir)) + + self.assertEqual(['file1.md', ], files) + class PagesTest(unittest.TestCase):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.14
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/project.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
click==8.1.8 exceptiongroup==1.2.2 ghp-import==2.1.0 importlib_metadata==8.6.1 iniconfig==2.1.0 Jinja2==3.1.6 livereload==2.7.1 Markdown==3.7 MarkupSafe==3.0.2 mergedeep==1.3.4 -e git+https://github.com/mkdocs/mkdocs.git@98814de505c9d8f1849292372eff1c5ae492261c#egg=mkdocs mkdocs-bootstrap==0.2.0 mkdocs-bootswatch==0.5.0 mkdocs-get-deps==0.2.0 packaging==24.2 pathspec==0.12.1 platformdirs==4.3.7 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 PyYAML==6.0.2 pyyaml_env_tag==0.1 six==1.17.0 tomli==2.2.1 tornado==6.4.2 watchdog==6.0.0 zipp==3.21.0
name: mkdocs channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - click==8.1.8 - exceptiongroup==1.2.2 - ghp-import==2.1.0 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jinja2==3.1.6 - livereload==2.7.1 - markdown==3.7 - markupsafe==3.0.2 - mergedeep==1.3.4 - mkdocs-bootstrap==0.2.0 - mkdocs-bootswatch==0.5.0 - mkdocs-get-deps==0.2.0 - packaging==24.2 - pathspec==0.12.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - pyyaml-env-tag==0.1 - six==1.17.0 - tomli==2.2.1 - tornado==6.4.2 - watchdog==6.0.0 - zipp==3.21.0 prefix: /opt/conda/envs/mkdocs
[ "mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_talk" ]
[]
[ "mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_default", "mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_empty", "mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_replace_default", "mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_required", "mkdocs/tests/config/config_options_tests.py::OptionallyRequiredTest::test_required_no_default", "mkdocs/tests/config/config_options_tests.py::TypeTest::test_length", "mkdocs/tests/config/config_options_tests.py::TypeTest::test_multiple_types", "mkdocs/tests/config/config_options_tests.py::TypeTest::test_single_type", "mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid", "mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid_url", "mkdocs/tests/config/config_options_tests.py::URLTest::test_valid_url", "mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_bitbucket", "mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_custom", "mkdocs/tests/config/config_options_tests.py::RepoURLTest::test_repo_name_github", "mkdocs/tests/config/config_options_tests.py::DirTest::test_file", "mkdocs/tests/config/config_options_tests.py::DirTest::test_incorrect_type_attribute_error", "mkdocs/tests/config/config_options_tests.py::DirTest::test_incorrect_type_type_error", "mkdocs/tests/config/config_options_tests.py::DirTest::test_missing_dir", "mkdocs/tests/config/config_options_tests.py::DirTest::test_missing_dir_but_required", "mkdocs/tests/config/config_options_tests.py::DirTest::test_valid_dir", "mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_doc_dir_in_site_dir", "mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_site_dir_in_docs_dir", "mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme", "mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_invalid", "mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_empty", "mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_invalid", "mkdocs/tests/config/config_options_tests.py::ExtrasTest::test_provided", "mkdocs/tests/config/config_options_tests.py::PagesTest::test_invalid_config", "mkdocs/tests/config/config_options_tests.py::PagesTest::test_invalid_type", "mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided", "mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided_dict", "mkdocs/tests/config/config_options_tests.py::PagesTest::test_provided_empty", "mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_invalid_pages", "mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_many_pages", "mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_one_page", "mkdocs/tests/config/config_options_tests.py::NumPagesTest::test_provided", "mkdocs/tests/config/config_options_tests.py::PrivateTest::test_defined", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins_config", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_configkey", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_duplicates", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_item", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_option", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_dict_item", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_list_dicts", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_mixed_list", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_none", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_not_list", "mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_simple_list" ]
[]
BSD 2-Clause "Simplified" License
176
203
[ "mkdocs/config/config_options.py" ]
praw-dev__praw-441
c64e3f71841e8f0c996d42eb5dc9a91fc0c25dcb
2015-07-02 19:21:13
c64e3f71841e8f0c996d42eb5dc9a91fc0c25dcb
diff --git a/praw/objects.py b/praw/objects.py index 4640a73a..505438ae 100755 --- a/praw/objects.py +++ b/praw/objects.py @@ -81,10 +81,26 @@ class RedditContentObject(object): raise AttributeError('\'%s\' has no attribute \'%s\'' % (type(self), attr)) + def __getstate__(self): + """Needed for `pickle`. + + Without this, pickle protocol version 0 will make HTTP requests + upon serialization, hence slowing it down significantly. + """ + return self.__dict__ + def __ne__(self, other): """Return whether the other instance differs from the current.""" return not self == other + def __reduce_ex__(self, protocol): + """Needed for `pickle`. + + Without this, `pickle` protocol version 2 will make HTTP requests + upon serialization, hence slowing it down significantly. + """ + return self.__reduce__() + def __setattr__(self, name, value): """Set the `name` attribute to `value.""" if value and name == 'subreddit':
Pickling Comment objects is slow Test case: ```python import pickle, praw r = praw.Reddit('test') comment = r.get_info(thing_id='t1_aaaa') pickle.dumps(comment) ``` Looking at Wireshark, it seems to be caused by an HTTP request. Good news: implementing `def __getstate__(self): return self.__dict__` in `praw.objects.RedditContentObject` fixes it. Bad news: I'm not sure why since `pickle` use `__dict__` by default, [as per the docs](https://docs.python.org/2/library/pickle.html#object.__getstate__). I'm not really familiar with the intricacies of `pickle`, any ideas?
praw-dev/praw
diff --git a/tests/cassettes/test_pickling_v0.json b/tests/cassettes/test_pickling_v0.json new file mode 100644 index 00000000..784fdddf --- /dev/null +++ b/tests/cassettes/test_pickling_v0.json @@ -0,0 +1,1 @@ +{"recorded_with": "betamax/0.4.2", "http_interactions": [{"response": {"body": {"base64_string": "H4sIAAAAAAAAAxzLy4oDIRBA0V+RWhvQKrXU78huGEK1D3ryMrS9C/3vIbO9h/uG6xxPyOoNbdvGNiGrn1+toMou//nZWr2s+/76Upf7bFrBY9RV5gpZwRxcirzqdIIhogTXBD07omZMXyQsS6JUHZFERl99AK2gjHH7a9+fyWAMrNFYfzJ8Mni2mC1lDNraUrm45LupyXPqYWHxyZYYKLEXF52lXgSO4/gAAAD//wMAkqq30coAAAA=", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/api/login/.json", "headers": {"x-xss-protection": ["1; mode=block"], "set-cookie": ["__cfduid=d39c55cd52ddf9bd97d92e1bfab8520cb1435864405; expires=Fri, 01-Jul-16 19:13:25 GMT; path=/; domain=.reddit.com; HttpOnly", "secure_session=; Domain=reddit.com; Max-Age=-1435864406; Path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; HttpOnly", "reddit_session=7302867%2C2015-07-02T12%3A13%3A26%2C11cd7c495f0d9579f6b7a591c863975a48413fca; Domain=reddit.com; Path=/; HttpOnly"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:26 GMT"], "x-content-type-options": ["nosniff"], "cache-control": ["private, no-cache", "no-cache"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "pragma": ["no-cache"], "transfer-encoding": ["chunked"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "cf-ray": ["1ffcaaf8bc5f0893-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": "user=PyAPITestUser2&api_type=json&passwd=1111"}, "uri": "https://api.reddit.com/api/login/.json", "method": "POST", "headers": {"Content-Length": ["45"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Content-Type": ["application/x-www-form-urlencoded"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:26"}, {"response": {"body": {"base64_string": "H4sIAFeNlVUC/+2cXW/juBWG/4qRi0WLDif8/pjFoiiKBVqgF3uxi17sFAY/x5o4tmPLySSD/e8lKdkj22nGjiXZSXPj2JIsvuQ576NDSvHXi6ti4i4+DC7+VSzKYvLp4t3gwulSx01fL66nbqQXo7T7Vgj96d5+MUZgKL2lKBDBsJHC0+ACkcFJL7hGhEKLJIM0ncmOirGb+0k8w+9f102VaKOVxdLMvXNFOSyq3WyISzbl6aBxMbkalkU59mnPr35RDv6u7ch/GGiI4K3TfP6AoKWSccWdFNByJgUTzljItVcBO8sxNyFok85n9GTi3dDcx9NNluNx3DT319NbPR7OvV5Mk9J6e266VkSGxFD9uVxL0styNJ2nfb/c/+2XfyZhvy38HFcHXPlF3FXOlz6ffzYu8oaLtHcZD4ttzabzMm37/T9x20Lf+tRQ0ONF+krVql0UMzx16Uuf4jDmI2D8oOdxWDe/UJ2v7sL6tE+JnOkYlvWIN/u3sNN5Gm2UzjCbzae3WwNmp5MybZ0vCj0uyrQnyTJTl95e/CN2ZrCYXvvBclLYqYux+tPHJYQuHpT/uj+nZnwM+EYfKrXDMNbFfGgXi6Ed60XqS92sm97lrq3aGo7K63Fq8Idx+aMrbgf5+J8+Xly7jxc/fCp/TNtn6c0eitKxl/ngj5P8Pp4wfcoDssrP1FidqXpWDMs4nusBG44K53Kir/oz0dc5aUs0bETSxhhV/UaUMCwgI/B9jmqz+6X/klsL06nR83XWLee5w6OynH24vLy7u3tfyXlvp9eX88stbZdx63UM8uKyCu5l2ji0yT6XDSnDZWlXcjhXtZzlLI11yoEIge18nSyvG5vS4a6ix7JYjHLnUsz++OPd4M30zzH9aNyH6eu8VHnXsa7/bVLcLP0g9fv+w+DugY+YkTdTob1lSgZivTcUGwe5olBR5QMWghBliefOK9gzEo6V2wMvqiTY5QVGZ8WLWs4bL07Ii8rCXfOizSKh9l+dcR8GxWgJvfA3DwVXJnAvkZZOEGwlwRRDITjEQZHoPsG8j2WmPw0wjhDcAzKqPNhFBjovZNRyzgcZ/y6uisHPMWHvB9NJLgktSa/KHocDKr/QnnFws/C4eOgDBzHnbhauuNIt8qC+Hsv57OZKjW6vrqDhFDNukIdaSKYFJBgxLuM1GQfOnSUMCaL1x8nHyV9+jrEe/Jry+l2DDXXWSfWICbpAxLP70AREhYj84Vu3OibIt9TZIAjEcU7AHxm8vQjiJ+/vortmMRz6/XT+6bLprr8W7ic8v6O35kG5e4GpDRA7wr0yxEMkkDMkCIWcMDxAQUNELM8m3wELxFLRWuUbWDoCC3/pYLGf/efZPJ4Cca0QMyTW89SpAKWkmmJOlPdWRGNygpjGSPknwNJb0fFs8edAlCpndony7GWPXolydqshr40ouYtdE6XZv5aAsp4IeITIA1oyPGXWECa1EopKmuaVGiGHjEcExQs/DNCoOBVA6jQQOUJwH5TIebBLCSxfAiVqlW+U6IQSq1LgJVFij1sOT1QWdV5BpHazv1U27CHz9DXEKv7bdEAEs93xOTc6CFGrPB86JA+sV0gdZZQFDVIHAaXxxTDEAWbMMeehcCYvtT2fGehesy89M4PHTmXU9cCMdf96YMYGJbovHfZQ1LX715Fsuh9LxqK18DPdf8CqZg5uY1VzuPJLsktySzJL0yuPLntGvZTzWu95cgBRgyxhBlgNHaDKIqA4MYAQaCHTTmAljuUAu/7cOwdoedUHB3Kq4sVdvn90LAg2p/3QW+09CUBKZgElOEaGYgIU1hRRK4njudUeuXC4wO4xUQd6FxP8uVOIgzARc7uJiZWdkpuSmZKXmlZ6AhO13vPExGstF+gsj07XmGizXNie1xuBkAkSA6phtCGDEGgRI6VDzLtguCMmE7x/ThwksQdSVLF+hBQvrKCo9Z4nKV5pQYFLm5+R7YUUdf+OJcUeZfyTixFVtlG6645WabGHzCYcTrIYsY7/Fj2ohOK5ixEH0aOtOoPSWu950iNAxBQMFiQqxsuF5sBIx4AMDFsRLxpOZ9McQY8vDyPaPz1Qhl7X9MipCh/u8sz5WHxsVvvCEWqDCAAJFSPjYwUolYHAe8uwoFALdtqHOfcR2AMmqkDvYuLZT1IcgomU201MrOyUa4xopuSlppWewMTZPVPx/1Bk1AsJXWOizSJju9ZXjFPuMAEkXmkA5UwCpWUAmGukgnLYhKyof04cJLF7UtSx3iUFe2EFRa33PEnxSgsKBIXsixSr/h1Lij3q/O9ORyglYtcdrdJiD5mnn46s4r9NDwbJI9O11unRWp2BaK33jR490mM1Q3hJ9Ni+iBuJrYeYphsPPIYG6RiawIA30gdsjSQmbACk/zpjH4mdk2IV611S4Oc+iXkiUtR6z5MUXGImJFQg/d8NoDTGWhOB0xRUhKCoItX0+NmkwIsHT7LS/kgxWaprO+mHFN/6dywp9riAf7fOQBQ+clOgVVrsIfPUdca3+G/QA8UUZ+qRZ9RapkeVEk16rFyWTJY8lizWdNjj9GjqfaNHr/RgN33Qo0rV8W1u7Fh8bK4qEq2185QAZq0H1OsYGQ4lIMojaOPkmMITPdh9gMAeMFEF+hFMdL/s2S4mznnZ87VionZu15hos8jYrvUVglRbxkCcmLtY6zMBFMMIWGWV8VYyaE/0tNZBErsnRR3rXVKIF1ZQ1HrPkxTICEsUckByqwHllAETcLwq8HiFsDpOTDU5lhRG5SWoPkkhy0mW3Qsp6v4dS4o96vynpyM52xjZdUertNhD5umnI6v4b9ODEt79TZMqJTZumtQuSyZLHksWazrsf9Jjrfc86WFZgFQ5BhiVsc4wggNNFQSKaI8QjntU/lGzY+ihru77pwcr+qBHlapmNGsDH1sPORAEOaUeQG0UoBJZoDWVQELMrWHYYnyiVc8DBPaAiSrQu5igvWAi5nYTEys7JTclMyUvNa30BCZqveeJiVdbZFQ/Yto1JtosMrZrfW4wlRoFoCWKBEfeAaO0AJoLwQ2U0NgTPa11kMQeSFH/YO0OKUgv05H2Copa73mS4rUWFFb29FD4t/4dS4o96vzvTkcowW/TkUb8t+lBOO6FHm3VGWu950kPYhhiQslYTkZwUIYJkDqEtNhtbEDeOnf0siefL3unh7nrpc7IqSo6+V0tQyzlJoLcMQcBFdYCGSgCsXA1hrF48aK5Auy/zDhAYPeYqAO9iwnUy3Qk5nYTEys7JTclMyUvNa30BCZqveeJiddaZNQLCV1jos0iY7vWhz54owgCiJtIcB4gMFYqYDQOkCMMEc6K+ufEQRJ7IEUV6x1SMNX9f7O3WVCs9J4nKV5pQSE+o+zeXkhR9+9YUuxR5393OkLYYz8J0yot9pB5+unIKv7b9MAUPTI+7dOjrTpjrbcVeuTcDqXPqb05UMaHKnurI/8LycOnWhVpAAA=", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "headers": {"x-xss-protection": ["1; mode=block"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["2606"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:27 GMT"], "x-content-type-options": ["nosniff"], "x-ratelimit-reset": ["393"], "content-type": ["application/json; charset=UTF-8"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=y3Jhs4XJ5ugsyWdG9pnDnfGKSbeEgrfxPSdmstjKjWA%2BUzeRcc2LGH9Yml8p1SiJZyKNuVriYuO2wvi26Sdq9URNAtTXSZSa"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "vary": ["accept-encoding"], "pragma": ["no-cache"], "x-sup-id": ["http://www.reddit.com/sup.json#e4356386a7"], "x-ratelimit-used": ["1"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "x-ratelimit-remaining": ["299"], "cf-ray": ["1ffcaafdccd60893-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "method": "GET", "headers": {"Cookie": ["__cfduid=d39c55cd52ddf9bd97d92e1bfab8520cb1435864405; reddit_session=7302867%2C2015-07-02T12%3A13%3A26%2C11cd7c495f0d9579f6b7a591c863975a48413fca"], "Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:27"}]} \ No newline at end of file diff --git a/tests/cassettes/test_pickling_v1.json b/tests/cassettes/test_pickling_v1.json new file mode 100644 index 00000000..2b78d924 --- /dev/null +++ b/tests/cassettes/test_pickling_v1.json @@ -0,0 +1,1 @@ +{"recorded_with": "betamax/0.4.2", "http_interactions": [{"response": {"body": {"base64_string": "H4sIAAAAAAAAAxzLSW7DMAxA0asIXCsASYmazpFdURSyhtptEhWWVw189yLd/of/hK85HpDUE9q+j31CUm/vWkHNR/7Pj9bqx3ocPy/q+TabVnAfdc1zhaRg3rft1vDXfrpeqVcWH4SWUthxjjFybmhKw+ZNXshFLKAVlDG+t/b6vUEOzmtGkgv6C/KVOJFJHDVTFYk2SJfgoqm9CKJdfCfLjrAGQhRrBc7z/AMAAP//AwBlfaprygAAAA==", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/api/login/.json", "headers": {"x-xss-protection": ["1; mode=block"], "set-cookie": ["__cfduid=dea6ea5a6ed306c9a2fbe4aea3094d7ad1435864409; expires=Fri, 01-Jul-16 19:13:29 GMT; path=/; domain=.reddit.com; HttpOnly", "secure_session=; Domain=reddit.com; Max-Age=-1435864409; Path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; HttpOnly", "reddit_session=7302867%2C2015-07-02T12%3A13%3A29%2C21d559485f58693dfc5004b7f142610d81005445; Domain=reddit.com; Path=/; HttpOnly"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:29 GMT"], "x-content-type-options": ["nosniff"], "cache-control": ["private, no-cache", "no-cache"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "pragma": ["no-cache"], "transfer-encoding": ["chunked"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "cf-ray": ["1ffcab0cfb8008b1-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": "user=PyAPITestUser2&api_type=json&passwd=1111"}, "uri": "https://api.reddit.com/api/login/.json", "method": "POST", "headers": {"Content-Length": ["45"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Content-Type": ["application/x-www-form-urlencoded"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:29"}, {"response": {"body": {"base64_string": "H4sIAFqNlVUC/+2cy27jyBWGX0XwYpAgXe26X3owCIJggATIYhYzyGIcCHVtsS1LskTZbTfm3VNVpGRactySRVKy443bJmnWX3XO//GcEtvfzi6LiTv7NDj7V7Eoi8nnsw+DM6dLHQ99O7uaupFejNLp2WeJb9wdLqnlQmMpMGEYMW8QhlByZRkj3CIRT1sYDBMo3cmOirGb+0m8w+/f1kOV+dx6lMXSzL1zRTksqtNsiEs25emicTG5HJZFOfbpzK9+UQ7+ru3IfxpoiOCN03x+j6ClknHFnRTQciYFE85YyLVXATvLMTchaJPuZ/Rk4t3Q3MXbTZbjcTw091fTGz0ezr1eTJPS+ngeulZEhsRQ/aVcS9LLcjSdp3O/3P3tl38mYb8t/BxXF1z6RTxVzpc+3382LvKBs3R2GS+LY82m8zId+/0/8dhC3/g0UNDjRfqValS7KGZ46tIvfY7LmK+A8Qc9j8v6+Beq+9VTWN/2OZEzHcOyXvHm/BZ2Ok+rjdIdZrP59GZjwex0Uqaj80Whx0WZziRZZurSt2f/iJMZLKZXfrCcFHbqYqz+dLGE0MWL8r/uz2kYHwP+aA6V2mEY62I+tIvF0I71Is2lHtZNb/PUVmMNR+XVOA34w7j80RU3g3z9TxdnV+7i7IfP5Y/p+Cx9s4OidO15vvhikr+PN0w/5QVZ5WcarM5UPSuGZVzP9YINR4VzOdFX85noq5y0JRo2ImljjKp5IxodJCAj8GOOanP6pf+aRwvTqdHzddYt53nCo7KcfTo/v729/VjJ+WinV+fz8w1t5/HoVQzy4rwK7nk6OLTJPucNKcNlaVdyOFe1nOUsrXXKgQiBzXydLK8ah9LlrqLHsliM8uRSzP7448Pg3fQvMf1o3Ifp67xU+dShrv9tUlwv/SDN++7T4Paej5iR11OhvWVKBmK9NxQbB7miUFHlAxaCEGWJ584r2DMSDpXbAy+qJNjmBUYnxYtazjsvjsiLysJd86LNIqH2X51xnwbFaAm98Nf3BVcmcC+Rlk4QbCXBFEMhOMRBkeg+wbznGvnjAOMAwT0go8qDbWSg00JGLed0kPHv4rIY/BwT9m4wneSS0JL0VdnDcEDlV9ozDq4XHhf3feAg5tz1whWXukUe1M9jOZ9dX6rRzeUlNJxixg3yUAvJtIAkdp1cxmcyDpw7SxgSROuLycXkLz/HWA9+TXn9ocGGOuukesIEXSDixXNoAqJCRP7hYVodE+QhdR4RBOLYE/AnFm8ngvjJx9vorlkMh/44nX8+b7rrr4X7Cc9v6Y25V+5OYGoDxI5wrwzxEAnkDAlCIScMD1DQEBHLq42FTbBALBWtVb6DpSOw8NcOFvvFf5nN4y0Q1woxQ2I9T50KUEqqKeZEeW9FNCYniGmMlH8GLL0VHS8WfwpEqXJmmygv3vbolSgntxvy1oiSp9g1UZrzawko60bAI0Tu0ZLhKbOGMKmVUFTS1FdqhBwyHhEUH/wwQKNiK4DUcSBygOA+KJHzYJsSWL4GStQq3ynRCSVWpcBrosQOHzk8U1nUeQWR2s7+Vtmwg8zj1xCr+G/SARHMttfn1OggRK3ydOiQPLDeIXWUURY0SBMElMYvhiEOMGOOOQ+FM3mr7eXMQHeafe2ZGTxOKqOuB2as59cDMx5RovvSYQdFXbt/Hcmm+7FkLFoLv9D9e+xq5uA2djWHK78kuyS3JLM0vfLktmfUSzmv9Z4mBxA1yBJmgNXQAaosAooTAwiBFjLtBFbiUA6wqy+9c4CWl31wIKcqXtzmz48OBcHjth96q70nAUjJLKAEx8hQTIDCmiJqJXE8j9ojF/YX2D0m6kBvY4K/tIXYCxMxt5uYWNkpuSmZKXmpaaVnMFHrPU1MvNVygc7y6nSNiTbLhc2+3giETJAYUA2jDRmEQIsYKR1i3gXDHTGZ4P1zYi+JPZCiivUTpHhlBUWt9zRJ8UYLClza/I5sL6So53coKXYo45/djKiyjdJtd7RKix1kNuFwlM2Idfw36EElFC/djNiLHm3VGZTWek+THgEipmCwIFExPi40B0Y6BmRg2Ir40HA6m+YAeny9H9H+6YEy9LqmR05VeH+bO+dD8fG42heOUBtEAEioGBkfK0CpDATeW4YFhVqw477MuYvAHjBRBXobEy9+k2IfTKTcbmJiZadcY0QzJS81rfQMJk7unYr/hyKj3kjoGhNtFhmbtb5inHKHCSDxSQMoZxIoLQPAXCMVlMMmZEX9c2Ivid2Too71NinYKysoar2nSYo3WlAgKGRfpFjN71BS7FDnf7cdoZSIbXe0SosdZB6/HVnFf5MeDJIn2rXW6dFanYForfedHj3SY9UhvCZ6bD7EjcTWQ0zTBw88hgbpGJrAgDfSB2yNJCY8Akj/dcYuEjsnxSrW26TAL30T80ikqPWeJim4xExIqED6fzeA0hhrTQROLagIQVFFqvb4xaTAi3tPstL+SDFZqis76YcUD/M7lBQ7PMC/W2cgCp/4UKBVWuwg89h1xkP8H9EDxRRn6ol31FqmR5USTXqsXJZMljyWLNZ02NP0aOp9p0ev9GDXfdCjStXxTR7sUHw83lUkWmvnKQHMWg+o1zEyHEpAlEfQxuaYwiO92L2HwB4wUQX6CUx0v+3ZLiZOedvzrWKidm7XmGizyNis9RWCVFvGQGzMXaz1mQCKYQSsssp4Kxm0R3pbay+J3ZOijvU2KcQrKyhqvadJCmSEJQo5ILnVgHLKgAk4PhV4fEJYHRtTTQ4lhVF5C6pPUshykmX3Qop6foeSYoc6//l2JGcbI9vuaJUWO8g8fjuyiv8mPSjh3X9oUqXEow9NapclkyWPJYs1HfY/6bHWe5r0sCxAqhwDjMpYZxjBgaYKAkW0RwjHMyr/UbND6KEu7/qnByv6oEeVqmY0awMfGy85EAQ5pR5AbRSgElmgNZVAQsytYdhifKRdzz0E9oCJKtDbmKC9YCLmdhMTKzslNyUzJS81rfQMJmq9p4mJN1tkwPyJRdeYaLPI2Kz1ucFUahSAligSHHkHjNICaC4EN1BCY4/0ttZeEnsgRRXrbVKQXtqR9gqKWu9pkuKtFhRW9vRS+MP8DiXFDnX+d9sRSvB7O9KI/yY9CMe90KOtOmOt9zTpQQxDTCgZy8kIDsowAVKHkDa7jQ3IW+cO3vbk82Xv9DC3vdQZOVVFJ39XyxBLuYkgd8xBQIW1QAaKQCxcjWEsPrxorgD7LzP2ENg9JupAb2MC9dKOxNxuYmJlp+SmZKbkpaaVnsFErfc0MfFWi4x6I6FrTLRZZGzW+tAHbxRBAHETCc4DBMZKBYzGAXKEIcJZUf+c2EtiD6SoYr1FCqa6/9/sbRYUK72nSYo3WlCILyi7txdS1PM7lBQ71PnfbUcIe+pPwrRKix1kHr8dWcV/kx6YoifWp316tFVnrPW2Qo+c26H0ObUfL5Txocre6sr/Atr8huMVaQAA", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "headers": {"x-xss-protection": ["1; mode=block"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["2607"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:30 GMT"], "x-content-type-options": ["nosniff"], "x-ratelimit-reset": ["390"], "content-type": ["application/json; charset=UTF-8"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=9MZApNR3IAPjbhJiKbVbvujo6sivs6GURrLX9KX%2FCvGsONQwEOkhfoAl3ER7yTY2748o3j55GADAHujR7EOrq7oEdFe%2FFsY9"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "vary": ["accept-encoding"], "pragma": ["no-cache"], "x-sup-id": ["http://www.reddit.com/sup.json#e4356386a7"], "x-ratelimit-used": ["2"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "x-ratelimit-remaining": ["298"], "cf-ray": ["1ffcab124bf608b1-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "method": "GET", "headers": {"Cookie": ["__cfduid=dea6ea5a6ed306c9a2fbe4aea3094d7ad1435864409; reddit_session=7302867%2C2015-07-02T12%3A13%3A29%2C21d559485f58693dfc5004b7f142610d81005445"], "Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:30"}]} \ No newline at end of file diff --git a/tests/cassettes/test_pickling_v2.json b/tests/cassettes/test_pickling_v2.json new file mode 100644 index 00000000..3a4f3110 --- /dev/null +++ b/tests/cassettes/test_pickling_v2.json @@ -0,0 +1,1 @@ +{"recorded_with": "betamax/0.4.2", "http_interactions": [{"response": {"body": {"base64_string": "H4sIAAAAAAAAAxzLy2rEMAxA0V8xWnvAkuL48R3dlVJkWyHz9OBkMwz59zLd3sN9w2XrD8jmDTpGHxtk8/1jDTTZ5T8/VNvvuu/PDy1y29QauPe2yrZCNvB6Tc9RxjpuhThh1EQ6YcEkpRL5ElRRQ5uLF6FSp+bBGqi9X8/6+QM7inOw5NCfXDg5+kLKyJnJcuJCsixLQsZJWqzOFU01xsTE4sIslZuPcBzHHwAAAP//AwAKbaoxygAAAA==", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/api/login/.json", "headers": {"x-xss-protection": ["1; mode=block"], "set-cookie": ["__cfduid=d49ca6cca210c0b0c94548e0d7457f5e81435864411; expires=Fri, 01-Jul-16 19:13:31 GMT; path=/; domain=.reddit.com; HttpOnly", "secure_session=; Domain=reddit.com; Max-Age=-1435864412; Path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; HttpOnly", "reddit_session=7302867%2C2015-07-02T12%3A13%3A32%2C393b2afff91314ad8c00be9c889323a076ac3d58; Domain=reddit.com; Path=/; HttpOnly"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:32 GMT"], "x-content-type-options": ["nosniff"], "cache-control": ["private, no-cache", "no-cache"], "content-type": ["application/json; charset=UTF-8"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "pragma": ["no-cache"], "transfer-encoding": ["chunked"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "cf-ray": ["1ffcab1d4ce40467-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": "user=PyAPITestUser2&api_type=json&passwd=1111"}, "uri": "https://api.reddit.com/api/login/.json", "method": "POST", "headers": {"Content-Length": ["45"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Content-Type": ["application/x-www-form-urlencoded"], "Accept": ["*/*"], "Connection": ["keep-alive"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:32"}, {"response": {"body": {"base64_string": "H4sIAF2NlVUC/+2cW2/juBmG/4qRi0WLDic8H2axKIpigRboxV7sohc7hcHjWBPHdiw5mWSw/70kJXtkO83YsSw7aW5ykBTxJb/vffSRYvz14qqYuIsPg4t/FWVVTD5dvBtcOF3peOjrxfXUjXQ5SqevvpTVLUPlohJYOyMcQwZrLoRBKmiDscJeUuo0kp4z5LhId7KjYuzmfhLv8PvXVVMVWmulXJi5d66ohkV9mg1xxaY8XTQuJlfDqqjGPp351ZfV4O/ajvyHgYYI3jrN5w8IWioZV9xJAS1nUjDhjIVcexWwsxxzE6LGdD+jJxPvhuY+3m6yGI/jobm/nt7q8XDudTlNSpvjuelGERkSQ/XnaiVJL6rRdJ7O/XL/t1/+mYT9Vvo5ri+48mU8Vc0XPt9/Ni7ygYt0dhEvi23NpvMqHfv9P/FYqW99aijocZn+pG7VlsUMT136o09xGPMVMP6i53FY1/+gvl/ThdVtnxI50zEsqxFv96+003kabZTuMJvNp7cbA2ankyodnZeFHhdVOpNkmalLP178I3ZmUE6v/WAxKezUxVj96eMCQhcvyt/dn1MzPgZ8rQ+12mEY62I+tGU5tGNdpr40zbrpXe7asq3hqLoepwZ/GFc/uuJ2kK//6ePFtft48cOn6sd0fJZ+2EFRuvYyX/xxkn+ON0y/5QFZ5mdqrMlUPSuGVRzP1YANR4VzOdGX/Zno65y0FRq2ImljjOp+I0oYFpAR+D5Htd39yn/JrYXp1Oj5KusW89zhUVXNPlxe3t3dva/lvLfT68v55Ya2y3j0Oga5vKyDe5kODm2yz2VLynBR2aUczlUjZzFLY51yIEJgM18ni+vWoXS5q+mxKMpR7lyK2R9/vBu8mf45ph+N+zB9k5cqnzrU9b9NipuFH6R+338Y3D3wETPyZiq0t0zJQKz3hmLjIFcUKqp8wEIQoizx3HkFe0bCoXJ74EWdBNu8wOiseNHIeePFCXlRW/jYvOiySGj812Tch0ExWkAv/M1DwZUJ3EukpRMEW0kwxVAIDnFQJLpPMO+5Rv40wDhAcA/IqPNgGxnovJDRyDkfZPy7uCoGP8eEvR9MJ7kktCR9VfYwHFD5hfaMg5vS4+KhDxzEnLspXXGlO+RB8zyW89nNlRrdXl1Bwylm3CAPtZBMC0gwYlzGZzIOnDtLGBJE64+Tj5O//BxjPfg15fW7FhuarJPqERMcAxHP7kMbEDUi8i/funVkgnxLnTWCQBznBPyRwduJIH7y/i66axbDod9P558u2+76a+F+wvM7emselLsXmNoAsSPcK0M8RAI5Q4JQyAnDAxQ0RMTybPItsEAsFW1UvoHlSGDhLx0s9rP/PJvHWyCuFWKGxHqeOhWglFRTzIny3opoTE4Q0xgp/wRYeis6ni3+HIhS58w2UZ697NErUc5uNeS1ESV38dhEafevI6CsJgIeIfKAFgxPmTWESa2EopKmeaVGyCHjEUHxwQ8DNCpOBZA6DUQOENwHJXIebFMCy5dAiUblGyWOQollKfCSKLHDK4cnKosmryBS29nfKRt2kHn6GmIZ/006IILZ9vicGx2EaFSeDx2SB1YrpI4yyoIGqYOA0vjFMMQBZswx56FwJi+1PZ8Z6F6zLz0zg8dOZdT1wIxV/3pgxholjl867KDo2O5fRbLtfiwZi9bCz3T/HquaObitVc3h0i/JLsktySxtrzy67Bn1Us4bvefJAUQNsoQZYDV0gCqLgOLEAEKghUw7gVXe0XEIB9j15945QKurPjiQUxWXd/n90aEgWJ/2Q2+19yQAKZkFlOAYGYoJUFhTRK0kjudWe+TC/gKPj4km0NuY4M+dQuyFiZjbbUws7ZTclMyUvNS20hOYaPSeJyZea7lAZ3l0jo2JLsuFzXm9EQiZIDGgGkYbMgiBFjFSOsS8C4Y7YjLB++fEXhJ7IEUd60dI8cIKikbveZLilRYUuLJ5j2wvpGj6dygpdijjn1yMqLON0m13dEqLHWS24XCSxYhV/DfoQSUUz12M2IseXdUZlDZ6z5MeASKmYLAgUTE+LjQHRjoGZGDYivjQcDqb5gB6fHkY0f7pgTL0jk2PnKrw4S7PnA/Fx3q1LxyhNogAkFAxMj5WgFIZCLy3DAsKtWCn3cy5i8AeMFEHehsTz95JsQ8mUm63MbG0U64xopmSl9pWegITZ7en4v+hyGgWEo6NiS6LjM1aXzFOucMEkPikAZQzCZSWAWCukQrKYROyov45sZfE45OiifU2KdgLKygavedJildaUCAoZF+kWPbvUFLsUOd/dzpCKRHb7uiUFjvIPP10ZBn/TXowSB6ZrnVOj87qDEQbvW/06JEeyxnCS6LH5kPcSGw9xDS9eOAxNEjH0AQGvJE+YGskMWENIP3XGbtIPDoplrHeJgV+7k7ME5Gi0XuepOASMyGhAun/bgClMdaaCJymoCIERRWpp8fPJgUuHzzJSvsjxWShru2kH1J869+hpNjhAf7dOgNR+MhLgU5psYPMU9cZ3+K/Rg8UU5ypR/aodUyPOiXa9Fi6LJkseSxZrO2wx+nR1vtGj17pwW76oEedquPb3Nih+FhfVSRaa+cpAcxaD6jXMTIcSkCUR9DGyTGFJ9rYvYfAHjBRB/oRTBx/2bNbTJzzsudrxUTj3GNjossiY7PWVwhSbRkDcWLuYq3PBFAMI2CVVcZbyaA90W6tvSQenxRNrLdJIV5YQdHoPU9SICMsUcgBya0GlFMGTMDxqcDjE8LqODHV5FBSGJWXoPokhawmWXYvpGj6dygpdqjzn56O5GxjZNsdndJiB5mnn44s479JD0r48V+a1Cmx9tKkcVkyWfJYsljbYf+THiu950kPywKkyjHAqIx1hhEcaKogUER7hHA8o/KHmh1CD3V13z89WNEHPepUNaNZF/jY2ORAEOSUegC1UYBKZIHWVAIJMbeGYYvxiVY99xDYAybqQG9jgvaCiZjbbUws7ZTclMyUvNS20hOYaPSeJyZebZEB8xuLY2OiyyJjs9bnBlOpUQBaokhw5B0wSguQPrmVGyihsSfarbWXxB5IUcd6mxSkl+lIdwVFo/c8SfFaCwore9oU/q1/h5Jihzr/u9MRSvDbdKQV/016EI57oUdXdcZK73nSgxiGmFAylpMRHJRhAqQOIS12GxuQt84dvOzJ54ve6WHueqkzcqqKo3yuliGWchNB7piDgAprgQwUgVi4GsNYfHjRXAH2X2bsIfD4mGgCvY0J1Mt0JOZ2GxNLOyU3JTMlL7Wt9AQmGr3niYnXWmQ0CwnHxkSXRcZmrQ998EYRBBA3keA8QGCsVMBoHCBHGCKcFfXPib0k9kCKOtZbpGDq+P/N3mVBsdR7nqR4pQWF+Iyye3shRdO/Q0mxQ53/3ekIYY99JEyntNhB5umnI8v4b9IDU/TI+HRPj67qjJXeTuiRcztUPqf2+kAZH+rsra/8L3S6MKwVaQAA", "encoding": "UTF-8"}, "status": {"message": "OK", "code": 200}, "url": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "headers": {"x-xss-protection": ["1; mode=block"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["2607"], "server": ["cloudflare-nginx"], "date": ["Thu, 02 Jul 2015 19:13:33 GMT"], "x-content-type-options": ["nosniff"], "x-ratelimit-reset": ["387"], "content-type": ["application/json; charset=UTF-8"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=NI%2FS0Vy8geEeJ%2BBL7Qy5J2Q26m47mKxDD5uB2y%2B851CRfxV7GGUC7FAOqmbXqrgmuzZ%2BjeU5o6AO95wvK098lEadH8PZql7p"], "x-moose": ["majestic"], "x-ua-compatible": ["IE=edge"], "vary": ["accept-encoding"], "pragma": ["no-cache"], "x-sup-id": ["http://www.reddit.com/sup.json#e4356386a7"], "x-ratelimit-used": ["3"], "x-frame-options": ["SAMEORIGIN"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "x-ratelimit-remaining": ["297"], "cf-ray": ["1ffcab26cdfa0467-FRA"]}}, "request": {"body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/comments.json?t=all&sort=new", "method": "GET", "headers": {"Cookie": ["__cfduid=d49ca6cca210c0b0c94548e0d7457f5e81435864411; reddit_session=7302867%2C2015-07-02T12%3A13%3A32%2C393b2afff91314ad8c00be9c889323a076ac3d58"], "Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0.0 Python/2.7.8 Linux-3.16.0-41-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"]}}, "recorded_at": "2015-07-02T19:13:33"}]} \ No newline at end of file diff --git a/tests/cassettes/test_unpickle_comment.json b/tests/cassettes/test_unpickle_comment.json deleted file mode 100644 index ce5e4d79..00000000 --- a/tests/cassettes/test_unpickle_comment.json +++ /dev/null @@ -1,1 +0,0 @@ -{"recorded_with": "betamax/0.4.2", "http_interactions": [{"recorded_at": "2015-06-15T13:50:36", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"transfer-encoding": ["chunked"], "cache-control": ["private, no-cache", "no-cache"], "server": ["cloudflare-nginx"], "set-cookie": ["__cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236; expires=Tue, 14-Jun-16 13:50:36 GMT; path=/; domain=.reddit.com; HttpOnly", "secure_session=; Domain=reddit.com; Max-Age=-1434376237; Path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; HttpOnly", "reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; Domain=reddit.com; Path=/; HttpOnly"], "x-moose": ["majestic"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-frame-options": ["SAMEORIGIN"], "cf-ray": ["1f6ebeb510a504a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:37 GMT"], "content-type": ["application/json; charset=UTF-8"], "x-content-type-options": ["nosniff"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAAxzLTWrDMBBA4auIWSug0c+MpXNkV0oZWaM6TRMV26GL4LuXdPs+3hO+tnGHYp6g6zrWDYp5e7cGmuzyn++q7WPZ958Xdfne1Bq4jbbItkAxcPt8CD+uv3zBPElGVidEnZPXWmtLVSmRsnOkVTwqR7AG5jGuF339HJyfiK13mE6OTpjOjkpyJbCdnSLGij0mwTozhTzFGuI8hRaw9Zgl+64NjuP4AwAA//8DABH3aj7KAAAA"}, "url": "https://api.reddit.com/api/login/.json"}, "request": {"headers": {"Accept-Encoding": ["gzip, deflate"], "Connection": ["keep-alive"], "Accept": ["*/*"], "Content-Length": ["45"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Content-Type": ["application/x-www-form-urlencoded"]}, "body": {"encoding": "utf-8", "string": "passwd=1111&api_type=json&user=PyAPITestUser2"}, "uri": "https://api.reddit.com/api/login/.json", "method": "POST"}}, {"recorded_at": "2015-06-15T13:50:37", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["299"], "content-type": ["application/json; charset=UTF-8"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["2574"], "server": ["cloudflare-nginx"], "x-content-type-options": ["nosniff"], "x-moose": ["majestic"], "x-ratelimit-used": ["1"], "x-frame-options": ["SAMEORIGIN"], "x-sup-id": ["http://www.reddit.com/sup.json#e4356386a7"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=HcLLGdCwZSCTj%2BYMBgG8Ln0%2FKHA5a%2FIoJVNJ%2Fv%2FXrv6TSUaosRpQ67%2Fyfcg6Z7i5Diz8FZevtuCHzUmagS6TUQ7G47Go4bcv"], "cf-ray": ["1f6ebeb9f0cd04a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:37 GMT"], "x-ratelimit-reset": ["563"], "vary": ["accept-encoding"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAC3YflUC/+2cW2/bRhqG/4rgi6KLzcRzPqQoFotFgV1gL3rRYi/qhTAnRox1ikT5FPS/d2ZIKpTkOpJFUrLrG8cmafKd+b734Ts0oy8X1/nUXXwYXPw3Xxb59OPFu8GF04UOm75cTGZupJejuNsvVlO4yPESeWSVdAR7yz3VAmVQQwup4BZxCWVmtDeCIB7PZEf52C38NJzhty/rSxVo4yrLlVl45/JimJe72RAXbJZOMM6n18MiL8Y+7vlffp0PfpoWi/vBbDq4WkFoSfyqbDzW6OnUu6G5D4dOV+Nx2LTwk9mNHg8XXi9nUUW1PZ22uhoZEirvaLG+nF4Vo9ki7vv5/p8//+cXvyx+XfoFLg+49suwq1isfDr/fJynDRdx7yocFq41ny2KuO23/4dtS33j44UyPV7GXymvaj8vPc4f4i99DFOUjoDhB70IU7b5C+X5qiGsT/uUyLkOU76eTTQMF3P5tY67lna2iFOJ4inm88XsZmvG7CxMb9i6WOZ6nBdxT9RlZi5+e/HrNP+88oM47vsPA7mYf75Wo5vra2g4xYwb5KEWkmkBCUYs9IOiOOPcWcKQIDpp8KHUGyMsxzLMxjpfDO1yObRjvUyTeneXOmV2mwZeCxmOisk47v5uXPzg8ptBOv7Hq4uJu7r47mPxQ9w+j98cKzee6DKd6Wqavg9Xiz+lqazbNiqpGljP82ERSrGe6uEody71fz3YqZ6kXi7rUjeBDeUtJwVRArEikKP3qSGac1P4u3i1ZhOvFmkmRkUx/3B56afvb4NH5mGK9fvZ4uNl0yP/yN2PeHFLb8yDcvcCU5tB7Aj3yhAPkUDOkEwo5IThGRQ0k07wZNVK3XBV2FqhVLRSuJrH2sSGCrjY7v7patLYFA93JWdW+XKUxhsH8/vv7wZveNjGA3/peLCf/Kf5IpwCca0QM8QST53KoJRUU8yJ8t6K4DlOENMYKX81vZr+/adQ68EvsdXfnRAWh4tvwqLERfrh63h6oEnZM7s0IfDcaVIpfKNJVzRJQ+yaJs3xtQQTO5tMwhU+DDxC5AGtGJ4xawiTWglFJeXaK42QQ8YjgsL9HGbQKOY9UqcByBGC+yBEGcx3CIHluROiUvhGiE4IUUeAl0SIf4fBDJaziR+sprmdOf9h8H0sgAsHpX/d355IFFVfQaR2O79VLuwh8/TZoa7/NhkQwWx3fs6JDEJUCs+HDLH/B//SdhRKrR1llGUaxAECSsMXwxAHmDHHnIfCGX8cL9C9ZqlFe+QFD4NKmOuBF+vx9cCLDUJ0Hxn2UNS189eVbDofS8aCtfAznH97e/u+lPI+JKHLxeWWrssqHy0vy8Jexo1DG80yrL0SrRKdEo3S9MnlYwwIWinnldbzZACiBlnCDLAaOkCVRUBxYgAh0EKmncBKHMsANvnUOwNocd0HA1Kb4uWtaQMCm8t86K32nmRASmYBJThUhmICFNYUUSuJ4+mqPTLhcIHdI6Iq9C4i+HOWDQchIvR1ExG1laKTopGij5o2egIRldbzRMRrjQl0nmana0S0GRO21/FGIGQyiQHVMFiQQQi0CJXSWei7zHBHTKJ3/4w4SGIPlChr/QglXlCQqLSeJyVeaZDAhU1/ee6FEtX4jqXEHtH9yYcPZbdRuuuMVkmxh8wmGE7y8GFd/y1yUAnFcx4+HESOtvIFpZXW8yRHBhFTMLMgEjHcJjQHRjoGZMawFeFm4XQyzBHkuHsY0f7JgRLwuiZHalP4cJtWyseiYzPhC0eozUQGkFChMj4kP6kMBN5bhgWFWjC4wY7e4sUBAntARFnoXUQ8602JQxAR+7qJiNpKKVsEI0UfNW30BCLO7p2Jv0K4qB4cdI2INsPFdr5XjFPuwrKfhLsMoJxJoLTMAOYaqUw5bLKkqH9GHCSxe0pUtd6lBHtBQaLSep6UeKVBAkEh+6JEPb5jKbFHtv/mEoRSInad0Sop9pB5+iVIXf9tcjBIHlmitUqO1vIFopXWN3L0SI56VfCSyLF98zYSWw8xjX9g4KE0SIfSZAx4I32GrZHEZBvw6D9f7COxc0rUtd6lBH7OG5YnokSl9TwpwSVmQkIFsIAhR9JQZ00EjktOkWWKKlIuh59NCbx88CQp7Y8S05Wa2Gk/lPg6vmMpsceN+5v5AlH4yMP/Vkmxh8xT54uv9d8gBwotztQj75+1SI6yHZrkqB0WDRb9Fe3VdNfj5GhqfSNHr+Rgn/sgR9mm45t0sWPRsfkEkWitnacEMGs9oF6HynAoAVEeQRsWxBSe6GXtAwT2gIiy0I8gottHnO0i4pwfcb5WRFSu7RoRbYaL7XyvEKTaMgbCQtyFfM8EUAwjYJVVxlvJoD3Rm1gHSeyeElWtdykhXlCQqLSeJyWQEZYo5IDkVgPKKQMmw+FuwMOdweqwENXkWEoYlR439UkJWUyT7F4oUY3vWErske2fXoKkbmNk1xmtkmIPmadfgtT13yYHJbzbP46U7bDxx5HKYdFg0V/RXk13/Sk51lrPkxyWZZAqxwCjMuQLIzjQVEGgiPYI4bBHuWPJoa7v+ycHy/sgR9mmZjRvAx1bLzEQBDmlHkBtFKASWaA1lUBCzK1h2GJ8oiecBwjsARFloXcRQTtHROjrJiJqK0UnRSNFHzVt9AQiKq3niYhXGy5g+stE14hoM1xs53tuMJUaZUBLFOiNvANGaQE0F4IbKKGxJ3oT6yCJPVCirPUuJUjnS5D2gkSl9Twp8VqDhJU9vej9dXzHUmKPbP/NJQgl+G0J0qj/NjkIx52To618sdZ6nuQghiEmlAwRMkCDMkyA1FkWH2obmyFvnTv6ESdfrHonh7ntJV+kNhWdfB6WIZZyEyDumIOACmuBzCgCIbAaw1i4cdGU/PqPFwcI7B4RVaF3EYE6X4KEvm4iorZSdFI0UvRR00ZPIKLSep6IeK3honpw0DUi2gwX2/ke+swbRRBA3AR68wwCY6UCRuMMcoQhwklR/4w4SGIPlChrvUMJprr9H+ltBola63lS4pUGCfEJJef2QolqfMdSYo9s/80lCGGPfZxLq6TYQ+bplyB1/bfJgSl6ZH7aJUdb+WKt9TzJoUmGHQ/RAmGO438k40BRG3IklJo5IS1l6XWfI8hx9zC77Z0c+bwXcsQ2LW5uJmmOjkXHZsJXFCsBRRbyHnKAYiKAMpkHmBlnEDImY6f9jO59BHaPiKrQO4ggnYeL2NdNRNRWik6KRoo+atrozxFRaz1PRLzWcNHbp2i2Fy528j0nRGhPASc4viOnGVDCGwCxDs5kmUblZzH2z4iDJPZAid1PzKyc93KCRK31PCnxOoNEuLcX6Zp9UKIe37GU2CPbf3MJEu7mfNcZrZJiD5knX4Ks679JDi4JedancB9CjpbyRUNrK+RIfZ0VPrX15iQZn5WdWx75B7y/uSWyaAAA"}, "url": "https://api.reddit.com/user/PyAPITestUser2/comments.json?sort=new&t=all"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/comments.json?sort=new&t=all", "method": "GET"}}, {"recorded_at": "2015-06-15T13:50:38", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["298"], "transfer-encoding": ["chunked"], "cache-control": ["private, no-cache", "no-cache"], "x-moose": ["majestic"], "server": ["cloudflare-nginx"], "x-ratelimit-used": ["2"], "x-frame-options": ["SAMEORIGIN"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=6qsn21tVL7go5HvVpotLbf0tnpT2hujgxe4105fEz7G1t0%2BHh25pl%2FSGghZNuAZaGB%2FJKaxz67I%3D"], "cf-ray": ["1f6ebebe912c04a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:38 GMT"], "x-ratelimit-reset": ["562"], "content-type": ["application/json; charset=UTF-8"], "x-content-type-options": ["nosniff"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAAAAAAAAA1yRwW7DIBBEfwVxtqrYxgn2rcfecmjPaANLvYqBCnCUNsq/V6AkjXodzQ5vhgs/kjd8Yjx3vGHcQAY+sQufISkHtPCJWVgSNox7cFic++/X/ds7pvyRMNYrSspGwhp0d+uIkLEobSfFth02cnjZNIzPZFDZGJyK4RByerr5DItROqIxVPVid8HMkOby8LYVLq1j+Nl1BzNYsYGulwjCgu7sCOM49LtejhalMJ0WW7krcDcQtWb9gGnFHabUDOZ/1YX8UR0hujJG25WU4Bz6/BDHhvFwwqhaySeW41rOKKlS4SmIavyfozbE8xdFyBQ8n5hfl+UGcsJIltAovOHcY+sHCU1nW9f2h3BWOqw+l42u118AAAD//wMAKxRkF8UBAAA="}, "url": "https://api.reddit.com/user/PyAPITestUser2/about/.json"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/user/PyAPITestUser2/about/.json", "method": "GET"}}, {"recorded_at": "2015-06-15T13:50:38", "response": {"status": {"code": 200, "message": "OK"}, "headers": {"x-ratelimit-remaining": ["297"], "content-type": ["application/json; charset=UTF-8"], "cache-control": ["private, no-cache", "no-cache"], "content-length": ["682"], "server": ["cloudflare-nginx"], "x-content-type-options": ["nosniff"], "x-moose": ["majestic"], "x-ratelimit-used": ["3"], "x-frame-options": ["SAMEORIGIN"], "x-xss-protection": ["1; mode=block"], "connection": ["keep-alive"], "content-encoding": ["gzip"], "pragma": ["no-cache"], "x-ua-compatible": ["IE=edge"], "x-reddit-tracking": ["https://pixel.redditmedia.com/pixel/of_destiny.png?v=AqxVkrSRF3bN55ymSSdkwfD%2FLdA4QMcYwodHHwNYU4Pccch5s1XTILSk9LACd6ER3FcO3MQmUDmhY5Rn5rzZjrp3D2F%2F%2BvsO"], "cf-ray": ["1f6ebec1714204a3-CDG"], "date": ["Mon, 15 Jun 2015 13:50:38 GMT"], "x-ratelimit-reset": ["562"], "vary": ["accept-encoding"]}, "body": {"encoding": "UTF-8", "base64_string": "H4sIAC7YflUC/61UyU7cQBD9FccHTsx4XwaUAyIimgOLICdC1OqlPNOZ9kJ3e2BA/Hu6G5sxHJCQcrHsqvKrV/Wq6tnf8Ib5R56vM//Q8xnW2Hw9+wQ3DUjE65V1WpfqSc010vCo0VrXwtibXgjj6ZWNVMj9Y8EqLBQYB3fIsc7a3CKMcbRttOSk1600fi17GzuBHzMyrjqBd6jBNVibBMZMCO64CVPahqwBsz3NtdbdURCQuV73NVHz1x9qYBzPaVsH0c/0PF5dIX41u87l7cU5e7g0hPqL5RKj/vIpOl1GJ7ebEHV0/rdbOQ6gqOSd5m0zVu0fCH38bTbzbk7R5dmZN5sdrPSxNTK+9ajASn2/82t254/2zr782CN5BS3ytHpI6D0UjEZZXpQQVqQK0yIvUhpnxYLQjMa0giTJwoyFFiZwOHeNeze5RviRy8VAxfLWXAvXtGvXA+/kaun9Mk3z0oeUb7aPOfRJRXLDglR5SnHF4qLMU8DVgkAZFSRMynBB8pDFFo62QuBOAWIgQAMzGtY1NFpN1O56IjhFk47Z/NOyxT3Uuo8SuSuyKCxTVuRltFiYSqO8jG3hizJb4CysGKQljUqXu92CjMpPE/1Hab7O8avScDP/SPEnK8+wQc402bVhrEcRh6hPOvv1gZqstODNBglMYLLTmNK2N/oiTDXfWhLRvvNa4qridCLJQHio6ncShoeeefx5TWJ5EpB2WOJ4n9edkg95x13XGXq7G1QC1u6wREkcZ1lYFNncJPB76UQPZPDhNASuiZwBwmw6ogMS6rUl/wFtOHnvlRlvVt2a+vC7i+Vcyqi0hhoQNJgIR3JwDxuCFG0lIEem5o1lY5OZFgyc9a5zFb/29k0Wpexcj07c7KYXdN/TsbiXl38Stiz/ywUAAA=="}, "url": "https://api.reddit.com/r/reddit_api_test/about/.json"}, "request": {"headers": {"Connection": ["keep-alive"], "User-Agent": ["PRAW_test_suite PRAW/3.0a1 Python/2.7.8 Linux-3.16.0-37-generic-x86_64-with-Ubuntu-14.10-utopic"], "Accept": ["*/*"], "Accept-Encoding": ["gzip, deflate"], "Cookie": ["reddit_session=7302867%2C2015-06-15T06%3A50%3A37%2Cc0e114b1f45a1bc763984b34c83d31df49a92fed; __cfduid=d28895e21c18fe156bbe302205f9b22ac1434376236"]}, "body": {"encoding": "utf-8", "string": ""}, "uri": "https://api.reddit.com/r/reddit_api_test/about/.json", "method": "GET"}}]} \ No newline at end of file diff --git a/tests/test_comments.py b/tests/test_comments.py index e3c3aa27..2253f27e 100644 --- a/tests/test_comments.py +++ b/tests/test_comments.py @@ -2,6 +2,7 @@ from __future__ import print_function, unicode_literals import pickle +import mock from praw import helpers from praw.objects import Comment, MoreComments from .helper import PRAWTest, betamax @@ -98,10 +99,24 @@ class CommentTest(PRAWTest): lambda item: isinstance(item, Comment)) self.assertEqual(comment._replies, None) + def _test_pickling(self, protocol): + comment = next(self.r.user.get_comments()) + with mock.patch('praw.BaseReddit.request_json') as request_json_func: + unpickled_comment = pickle.loads(pickle.dumps(comment, protocol)) + self.assertEqual(comment, unpickled_comment) + self.assertEqual(request_json_func.called, 0) + @betamax() - def test_unpickle_comment(self): - item = next(self.r.user.get_comments()) - self.assertEqual(item, pickle.loads(pickle.dumps(item))) + def test_pickling_v0(self): + self._test_pickling(0) + + @betamax() + def test_pickling_v1(self): + self._test_pickling(1) + + @betamax() + def test_pickling_v2(self): + self._test_pickling(2) class MoreCommentsTest(PRAWTest):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 1 }
3.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "betamax>=0.4.2", "betamax-matchers>=0.2.0", "flake8", "mock>=1.0.0", "pytest", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
betamax==0.9.0 betamax-matchers==0.4.0 certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work execnet==2.1.1 flake8==7.2.0 idna==3.10 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mccabe==0.7.0 mock==5.2.0 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work -e git+https://github.com/praw-dev/praw.git@c64e3f71841e8f0c996d42eb5dc9a91fc0c25dcb#egg=praw pycodestyle==2.13.0 pyflakes==3.3.1 pytest @ file:///croot/pytest_1738938843180/work pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 requests==2.32.3 requests-toolbelt==1.0.0 six==1.17.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work typing_extensions==4.13.0 update-checker==0.18.0 urllib3==2.3.0
name: praw channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - betamax==0.9.0 - betamax-matchers==0.4.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - execnet==2.1.1 - flake8==7.2.0 - idna==3.10 - mccabe==0.7.0 - mock==5.2.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - requests==2.32.3 - requests-toolbelt==1.0.0 - six==1.17.0 - typing-extensions==4.13.0 - update-checker==0.18.0 - urllib3==2.3.0 prefix: /opt/conda/envs/praw
[ "tests/test_comments.py::CommentTest::test_pickling_v0", "tests/test_comments.py::CommentTest::test_pickling_v1", "tests/test_comments.py::CommentTest::test_pickling_v2" ]
[]
[ "tests/test_comments.py::CommentTest::test_add_comment", "tests/test_comments.py::CommentTest::test_add_reply", "tests/test_comments.py::CommentTest::test_edit", "tests/test_comments.py::CommentTest::test_front_page_comment_replies_are_none", "tests/test_comments.py::CommentTest::test_get_comments_permalink", "tests/test_comments.py::CommentTest::test_inbox_comment_permalink", "tests/test_comments.py::CommentTest::test_inbox_comment_replies_are_none", "tests/test_comments.py::CommentTest::test_save_comment", "tests/test_comments.py::CommentTest::test_spambox_comments_replies_are_none", "tests/test_comments.py::CommentTest::test_unicode_comment", "tests/test_comments.py::CommentTest::test_user_comment_permalink", "tests/test_comments.py::CommentTest::test_user_comment_replies_are_none", "tests/test_comments.py::MoreCommentsTest::test_all_comments", "tests/test_comments.py::MoreCommentsTest::test_comments_method" ]
[]
BSD 2-Clause "Simplified" License
180
278
[ "praw/objects.py" ]
mattboyer__git-guilt-34
58f92d3e37a115596a890ad3e2fe674636c682ee
2015-07-02 20:15:01
58f92d3e37a115596a890ad3e2fe674636c682ee
diff --git a/git_guilt/guilt.py b/git_guilt/guilt.py index 23a748a..3b400c5 100644 --- a/git_guilt/guilt.py +++ b/git_guilt/guilt.py @@ -78,13 +78,14 @@ class GitRunner(object): raise GitError("Malformed Git version") raw_version = self.run_git(GitRunner._version_args) - if not (raw_version and - 1 == len(raw_version) and - raw_version[0].startswith('git version') - ): - raise GitError("Couldn't determine Git version %s" % raw_version) + version_re = re.compile(r'^git version (\d+.\d+.\d+)') - return version_string_to_tuple(raw_version[0].split()[-1]) + if raw_version and 1 == len(raw_version): + match = version_re.match(raw_version[0]) + if match: + return version_string_to_tuple(match.group(1)) + + raise GitError("Couldn't determine Git version %s" % raw_version) def _get_git_root(self): # We should probably go beyond just finding the root dir for the Git
Git version detection fails on MacOS Here's what a friendly user had to report: > my MACBOOK running latest 10.10.3 comes preinstalled with ``` Laurences-MacBook-Pro:security Laurence$ git version git version 2.3.2 (Apple Git-55) ``` The parsing code that consumes the output of `git version` should be made more robust.
mattboyer/git-guilt
diff --git a/test/test_guilt.py b/test/test_guilt.py index 1433e33..3abda65 100644 --- a/test/test_guilt.py +++ b/test/test_guilt.py @@ -306,6 +306,27 @@ class GitRunnerTestCase(TestCase): ) mock_process.reset_mock() + @patch('git_guilt.guilt.subprocess.Popen') + def test_mac_version(self, mock_process): + mock_process.return_value.communicate = Mock( + return_value=(b'git version 2.3.2 (Apple Git-55)', None) + ) + mock_process.return_value.returncode = 0 + mock_process.return_value.wait = \ + Mock(return_value=None) + + version_tuple = self.runner._get_git_version() + + mock_process.assert_called_once_with( + ['nosuchgit', '--version'], + cwd='/my/arbitrary/path', + stderr=-1, + stdout=-1 + ) + mock_process.reset_mock() + + self.assertEquals((2,3,2), version_tuple) + def test_version_comparison(self): self.assertEquals((1, 0, 0), self.runner.version)
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.30
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.4", "reqs_path": [ "requirements-3.4.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 astroid==2.11.7 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 coveralls==3.3.1 dill==0.3.4 docopt==0.6.2 docutils==0.18.1 -e git+https://github.com/mattboyer/git-guilt.git@58f92d3e37a115596a890ad3e2fe674636c682ee#egg=git_guilt idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 Jinja2==3.0.3 lazy-object-proxy==1.7.1 MarkupSafe==2.0.1 mccabe==0.7.0 mock==5.2.0 nose==1.3.7 packaging==21.3 pep8==1.7.1 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 Pygments==2.14.0 pylint==2.13.9 pyparsing==3.1.4 pytest==7.0.1 pytest-cov==4.0.0 pytz==2025.2 requests==2.27.1 snowballstemmer==2.2.0 Sphinx==5.3.0 sphinx-argparse==0.3.2 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 tomli==1.2.3 typed-ast==1.5.5 typing_extensions==4.1.1 urllib3==1.26.20 wrapt==1.16.0 zipp==3.6.0
name: git-guilt channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - argparse==1.4.0 - astroid==2.11.7 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - coverage==6.2 - coveralls==3.3.1 - dill==0.3.4 - docopt==0.6.2 - docutils==0.18.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - jinja2==3.0.3 - lazy-object-proxy==1.7.1 - markupsafe==2.0.1 - mccabe==0.7.0 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pep8==1.7.1 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pygments==2.14.0 - pylint==2.13.9 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-cov==4.0.0 - pytz==2025.2 - requests==2.27.1 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinx-argparse==0.3.2 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - tomli==1.2.3 - typed-ast==1.5.5 - typing-extensions==4.1.1 - urllib3==1.26.20 - wrapt==1.16.0 - zipp==3.6.0 prefix: /opt/conda/envs/git-guilt
[ "test/test_guilt.py::GitRunnerTestCase::test_mac_version" ]
[]
[ "test/test_guilt.py::DeltaTestCase::test_comparison", "test/test_guilt.py::DeltaTestCase::test_eq", "test/test_guilt.py::DeltaTestCase::test_repr", "test/test_guilt.py::BinaryDeltaTestCase::test_comparison", "test/test_guilt.py::BinaryDeltaTestCase::test_eq", "test/test_guilt.py::BinaryDeltaTestCase::test_repr", "test/test_guilt.py::ArgTestCase::test_bad_args", "test/test_guilt.py::ArgTestCase::test_help", "test/test_guilt.py::GitRunnerTestCase::test_get_delta_files", "test/test_guilt.py::GitRunnerTestCase::test_get_delta_no_files", "test/test_guilt.py::GitRunnerTestCase::test_get_git_root_exception", "test/test_guilt.py::GitRunnerTestCase::test_populate_rev_tree", "test/test_guilt.py::GitRunnerTestCase::test_run_git", "test/test_guilt.py::GitRunnerTestCase::test_run_git_cwd", "test/test_guilt.py::GitRunnerTestCase::test_run_git_exception", "test/test_guilt.py::GitRunnerTestCase::test_run_git_no_output_error", "test/test_guilt.py::GitRunnerTestCase::test_run_git_no_output_no_error", "test/test_guilt.py::GitRunnerTestCase::test_run_git_non_zerp", "test/test_guilt.py::GitRunnerTestCase::test_run_git_stderr", "test/test_guilt.py::GitRunnerTestCase::test_version_comparison", "test/test_guilt.py::GitRunnerTestCase::test_version_retrieval", "test/test_guilt.py::TextBlameTests::test_blame_locs", "test/test_guilt.py::TextBlameTests::test_blame_locs_bad_encoding", "test/test_guilt.py::TextBlameTests::test_blame_locs_empty_file", "test/test_guilt.py::TextBlameTests::test_blame_locs_exception", "test/test_guilt.py::TextBlameTests::test_blame_locs_file_missing", "test/test_guilt.py::TextBlameTests::test_text_blame_repr", "test/test_guilt.py::BinaryBlameTests::test_bin_blame_repr", "test/test_guilt.py::BinaryBlameTests::test_blame_bytes", "test/test_guilt.py::BinaryBlameTests::test_blame_bytes_empty_file", "test/test_guilt.py::BinaryBlameTests::test_blame_bytes_file_missing", "test/test_guilt.py::BinaryBlameTests::test_blame_bytes_locs_exception", "test/test_guilt.py::GuiltTestCase::test_file_not_in_since_rev", "test/test_guilt.py::GuiltTestCase::test_file_not_in_until_rev", "test/test_guilt.py::GuiltTestCase::test_map_binary_blames", "test/test_guilt.py::GuiltTestCase::test_map_text_blames", "test/test_guilt.py::GuiltTestCase::test_populate_trees", "test/test_guilt.py::GuiltTestCase::test_reduce_locs", "test/test_guilt.py::GuiltTestCase::test_show_run", "test/test_guilt.py::FormatterTestCase::test_get_width_not_tty", "test/test_guilt.py::FormatterTestCase::test_get_width_tty", "test/test_guilt.py::FormatterTestCase::test_green", "test/test_guilt.py::FormatterTestCase::test_red", "test/test_guilt.py::FormatterTestCase::test_show_binary_guilt", "test/test_guilt.py::FormatterTestCase::test_show_text_guilt" ]
[]
null
181
283
[ "git_guilt/guilt.py" ]
marshmallow-code__marshmallow-234
4e922445601219dc6bfe014d36b3c61d9528e2ad
2015-07-07 10:29:53
b8ad05b5342914e857c442d75e8abe9ea8f867fb
diff --git a/marshmallow/schema.py b/marshmallow/schema.py index 4de0a123..7fe1289f 100644 --- a/marshmallow/schema.py +++ b/marshmallow/schema.py @@ -699,8 +699,8 @@ class BaseSchema(base.SchemaABC): """ if obj and many: try: # Homogeneous collection - obj_prototype = obj[0] - except IndexError: # Nothing to serialize + obj_prototype = next(iter(obj)) + except StopIteration: # Nothing to serialize return self.declared_fields obj = obj_prototype ret = self.dict_class()
fields.Nested does not support sets Currently `fields.Nested` assumes that the value of the field is a list - https://github.com/marshmallow-code/marshmallow/blob/dev/marshmallow/schema.py#L702 - and fails for `set` during serialization
marshmallow-code/marshmallow
diff --git a/tests/test_schema.py b/tests/test_schema.py index 29dada19..5d0dbbdf 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -3,6 +3,7 @@ import json import random +from collections import namedtuple import pytest @@ -687,6 +688,21 @@ def test_nested_only_and_exclude(): assert 'bar' not in result.data['inner'] +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple('DataClass', ['foo']) + data = dict(inners=set([DataClass(42), DataClass(2)])) + result = sch.dump(data) + assert len(result.data['inners']) == 2 + + def test_meta_serializer_fields(): u = User("John", age=42.3, email="[email protected]", homepage="http://john.com")
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
2.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "dev-requirements.txt", "docs/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster @ git+https://github.com/sloria/alabaster.git@667b1b676c6bf7226db057f098ec826d84d3ae40 babel==2.17.0 cachetools==5.5.2 certifi==2025.1.31 chardet==5.2.0 charset-normalizer==3.4.1 colorama==0.4.6 distlib==0.3.9 docutils==0.20.1 exceptiongroup==1.2.2 filelock==3.18.0 flake8==2.4.0 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 invoke==2.2.0 Jinja2==3.1.6 MarkupSafe==3.0.2 -e git+https://github.com/marshmallow-code/marshmallow.git@4e922445601219dc6bfe014d36b3c61d9528e2ad#egg=marshmallow mccabe==0.3.1 packaging==24.2 pep8==1.5.7 platformdirs==4.3.7 pluggy==1.5.0 pyflakes==0.8.1 Pygments==2.19.1 pyproject-api==1.9.0 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.32.3 six==1.17.0 snowballstemmer==2.2.0 Sphinx==7.2.6 sphinx-issues==0.2.0 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 urllib3==2.3.0 virtualenv==20.29.3 zipp==3.21.0
name: marshmallow channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.11+sloria0 - babel==2.17.0 - cachetools==5.5.2 - certifi==2025.1.31 - chardet==5.2.0 - charset-normalizer==3.4.1 - colorama==0.4.6 - distlib==0.3.9 - docutils==0.20.1 - exceptiongroup==1.2.2 - filelock==3.18.0 - flake8==2.4.0 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - invoke==2.2.0 - jinja2==3.1.6 - markupsafe==3.0.2 - mccabe==0.3.1 - packaging==24.2 - pep8==1.5.7 - platformdirs==4.3.7 - pluggy==1.5.0 - pyflakes==0.8.1 - pygments==2.19.1 - pyproject-api==1.9.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.32.3 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==7.2.6 - sphinx-issues==0.2.0 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - urllib3==2.3.0 - virtualenv==20.29.3 - zipp==3.21.0 prefix: /opt/conda/envs/marshmallow
[ "tests/test_schema.py::test_nested_with_sets" ]
[]
[ "tests/test_schema.py::test_serializing_basic_object[UserSchema]", "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", "tests/test_schema.py::test_serializer_dump", "tests/test_schema.py::test_dump_returns_dict_of_errors", "tests/test_schema.py::test_dump_with_strict_mode_raises_error[UserSchema]", "tests/test_schema.py::test_dump_with_strict_mode_raises_error[UserMetaSchema]", "tests/test_schema.py::test_dump_resets_errors", "tests/test_schema.py::test_load_resets_errors", "tests/test_schema.py::test_dump_resets_error_fields", "tests/test_schema.py::test_load_resets_error_fields", "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", "tests/test_schema.py::test_load_many_stores_error_indices", "tests/test_schema.py::test_dump_many", "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", "tests/test_schema.py::test_dump_many_stores_error_indices", "tests/test_schema.py::test_dump_many_doesnt_stores_error_indices_when_index_errors_is_false", "tests/test_schema.py::test_dump_returns_a_marshalresult", "tests/test_schema.py::test_dumps_returns_a_marshalresult", "tests/test_schema.py::test_dumping_single_object_with_collection_schema", "tests/test_schema.py::test_loading_single_object_with_collection_schema", "tests/test_schema.py::test_dumps_many", "tests/test_schema.py::test_load_returns_an_unmarshalresult", "tests/test_schema.py::test_load_many", "tests/test_schema.py::test_loads_returns_an_unmarshalresult", "tests/test_schema.py::test_loads_many", "tests/test_schema.py::test_loads_deserializes_from_json", "tests/test_schema.py::test_serializing_none", "tests/test_schema.py::test_default_many_symmetry", "tests/test_schema.py::TestValidate::test_validate_returns_errors_dict", "tests/test_schema.py::TestValidate::test_validate_many", "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", "tests/test_schema.py::TestValidate::test_validate_strict", "tests/test_schema.py::TestValidate::test_validate_required", "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", "tests/test_schema.py::test_dumps_returns_json", "tests/test_schema.py::test_naive_datetime_field", "tests/test_schema.py::test_datetime_formatted_field", "tests/test_schema.py::test_datetime_iso_field", "tests/test_schema.py::test_tz_datetime_field", "tests/test_schema.py::test_local_datetime_field", "tests/test_schema.py::test_class_variable", "tests/test_schema.py::test_serialize_many[UserSchema]", "tests/test_schema.py::test_serialize_many[UserMetaSchema]", "tests/test_schema.py::test_inheriting_schema", "tests/test_schema.py::test_custom_field", "tests/test_schema.py::test_url_field", "tests/test_schema.py::test_relative_url_field", "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", "tests/test_schema.py::test_email_field[UserSchema]", "tests/test_schema.py::test_email_field[UserMetaSchema]", "tests/test_schema.py::test_stored_invalid_email", "tests/test_schema.py::test_integer_field", "tests/test_schema.py::test_fixed_field", "tests/test_schema.py::test_as_string", "tests/test_schema.py::test_decimal_field", "tests/test_schema.py::test_price_field", "tests/test_schema.py::test_extra", "tests/test_schema.py::test_extra_many", "tests/test_schema.py::test_method_field[UserSchema]", "tests/test_schema.py::test_method_field[UserMetaSchema]", "tests/test_schema.py::test_function_field", "tests/test_schema.py::test_prefix[UserSchema]", "tests/test_schema.py::test_prefix[UserMetaSchema]", "tests/test_schema.py::test_fields_must_be_declared_as_instances", "tests/test_schema.py::test_serializing_generator[UserSchema]", "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", "tests/test_schema.py::test_serializing_dict", "tests/test_schema.py::test_serializing_dict_with_meta_fields", "tests/test_schema.py::test_exclude_in_init[UserSchema]", "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", "tests/test_schema.py::test_only_in_init[UserSchema]", "tests/test_schema.py::test_only_in_init[UserMetaSchema]", "tests/test_schema.py::test_invalid_only_param", "tests/test_schema.py::test_can_serialize_uuid", "tests/test_schema.py::test_can_serialize_time", "tests/test_schema.py::test_invalid_time", "tests/test_schema.py::test_invalid_date", "tests/test_schema.py::test_invalid_email", "tests/test_schema.py::test_invalid_url", "tests/test_schema.py::test_invalid_selection", "tests/test_schema.py::test_custom_json", "tests/test_schema.py::test_custom_error_message", "tests/test_schema.py::test_load_errors_with_many", "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", "tests/test_schema.py::test_only_and_exclude", "tests/test_schema.py::test_only_with_invalid_attribute", "tests/test_schema.py::test_nested_only_and_exclude", "tests/test_schema.py::test_meta_serializer_fields", "tests/test_schema.py::test_meta_fields_mapping", "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", "tests/test_schema.py::test_exclude_fields", "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", "tests/test_schema.py::test_dateformat_option", "tests/test_schema.py::test_default_dateformat", "tests/test_schema.py::test_inherit_meta", "tests/test_schema.py::test_inherit_meta_override", "tests/test_schema.py::test_additional", "tests/test_schema.py::test_cant_set_both_additional_and_fields", "tests/test_schema.py::test_serializing_none_meta", "tests/test_schema.py::TestErrorHandler::test_dump_with_custom_error_handler", "tests/test_schema.py::TestErrorHandler::test_load_with_custom_error_handler", "tests/test_schema.py::TestErrorHandler::test_validate_with_custom_error_handler", "tests/test_schema.py::TestErrorHandler::test_multiple_serializers_with_same_error_handler", "tests/test_schema.py::TestErrorHandler::test_setting_error_handler_class_attribute", "tests/test_schema.py::TestSchemaValidator::test_validator_decorator_is_deprecated", "tests/test_schema.py::TestSchemaValidator::test_validator_defined_on_class", "tests/test_schema.py::TestSchemaValidator::test_validator_that_raises_error_with_dict", "tests/test_schema.py::TestSchemaValidator::test_validator_that_raises_error_with_list", "tests/test_schema.py::TestSchemaValidator::test_mixed_schema_validators", "tests/test_schema.py::TestSchemaValidator::test_registered_validators_are_not_shared_with_ancestors", "tests/test_schema.py::TestSchemaValidator::test_registered_validators_are_not_shared_with_children", "tests/test_schema.py::TestSchemaValidator::test_inheriting_then_registering_validator", "tests/test_schema.py::TestSchemaValidator::test_multiple_schema_errors_can_be_stored", "tests/test_schema.py::TestSchemaValidator::test_schema_validation_error_with_stict_stores_correct_field_name", "tests/test_schema.py::TestSchemaValidator::test_schema_validation_error_with_strict_when_field_is_specified", "tests/test_schema.py::TestSchemaValidator::test_schema_validation_error_stored_on_multiple_fields", "tests/test_schema.py::TestSchemaValidator::test_validator_with_strict", "tests/test_schema.py::TestSchemaValidator::test_validator_defined_by_decorator", "tests/test_schema.py::TestSchemaValidator::test_validators_are_inherited", "tests/test_schema.py::TestSchemaValidator::test_uncaught_validation_errors_are_stored", "tests/test_schema.py::TestSchemaValidator::test_validation_error_with_error_parameter", "tests/test_schema.py::TestSchemaValidator::test_store_schema_validation_errors_on_specified_field", "tests/test_schema.py::TestSchemaValidator::test_errors_are_cleared_on_load", "tests/test_schema.py::TestSchemaValidator::test_errors_are_cleared_after_loading_collection", "tests/test_schema.py::TestSchemaValidator::test_raises_error_with_list", "tests/test_schema.py::TestSchemaValidator::test_raises_error_with_dict", "tests/test_schema.py::TestSchemaValidator::test_nested_schema_validators", "tests/test_schema.py::TestPreprocessors::test_preprocessor_decorator_is_deprecated", "tests/test_schema.py::TestPreprocessors::test_preprocessors_defined_on_class", "tests/test_schema.py::TestPreprocessors::test_registered_preprocessors_are_not_shared_with_ancestors", "tests/test_schema.py::TestPreprocessors::test_registered_preprocessors_are_not_shared_with_children", "tests/test_schema.py::TestPreprocessors::test_preprocessors_defined_by_decorator", "tests/test_schema.py::TestDataHandler::test_data_handler_is_deprecated", "tests/test_schema.py::TestDataHandler::test_schema_with_custom_data_handler", "tests/test_schema.py::TestDataHandler::test_registered_data_handlers_are_not_shared_with_ancestors", "tests/test_schema.py::TestDataHandler::test_registered_data_handlers_are_not_shared_with_children", "tests/test_schema.py::TestDataHandler::test_serializer_with_multiple_data_handlers", "tests/test_schema.py::TestDataHandler::test_setting_data_handlers_class_attribute", "tests/test_schema.py::TestDataHandler::test_root_data_handler", "tests/test_schema.py::test_schema_repr", "tests/test_schema.py::TestNestedSchema::test_flat_nested", "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", "tests/test_schema.py::TestNestedSchema::test_flat_nested2", "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", "tests/test_schema.py::TestNestedSchema::test_nested_none", "tests/test_schema.py::TestNestedSchema::test_nested", "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", "tests/test_schema.py::TestNestedSchema::test_nested_only", "tests/test_schema.py::TestNestedSchema::test_exclude", "tests/test_schema.py::TestNestedSchema::test_list_field", "tests/test_schema.py::TestNestedSchema::test_list_field_parent", "tests/test_schema.py::TestNestedSchema::test_nested_load_many", "tests/test_schema.py::TestNestedSchema::test_nested_errors", "tests/test_schema.py::TestNestedSchema::test_nested_strict", "tests/test_schema.py::TestNestedSchema::test_nested_method_field", "tests/test_schema.py::TestNestedSchema::test_nested_function_field", "tests/test_schema.py::TestNestedSchema::test_nested_prefixed_field", "tests/test_schema.py::TestNestedSchema::test_nested_prefixed_many_field", "tests/test_schema.py::TestNestedSchema::test_invalid_float_field", "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_many_field", "tests/test_schema.py::TestSelfReference::test_nesting_schema_within_itself", "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", "tests/test_schema.py::TestSelfReference::test_multiple_nested_self_fields", "tests/test_schema.py::TestSelfReference::test_nested_many", "tests/test_schema.py::test_serialization_with_required_field", "tests/test_schema.py::test_deserialization_with_required_field", "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", "tests/test_schema.py::TestContext::test_context_method", "tests/test_schema.py::TestContext::test_context_method_function", "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", "tests/test_schema.py::TestContext::test_fields_context", "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", "tests/test_schema.py::TestAccessor::test_accessor_is_used", "tests/test_schema.py::TestAccessor::test_accessor_with_many", "tests/test_schema.py::TestAccessor::test_accessor_decorator", "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", "tests/test_schema.py::TestRequiredFields::test_allow_none_param", "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", "tests/test_schema.py::TestDefaults::test_default_and_value_missing", "tests/test_schema.py::TestDefaults::test_loading_none", "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output" ]
[]
MIT License
189
163
[ "marshmallow/schema.py" ]
cdent__gabbi-56
f2a32ad31bc205580834f009f05586a533f390f7
2015-07-16 05:25:12
081a75f5f0ddfdc31c4bab62db2f084a50c9ee99
diff --git a/gabbi/handlers.py b/gabbi/handlers.py index f754d94..d39a987 100644 --- a/gabbi/handlers.py +++ b/gabbi/handlers.py @@ -120,6 +120,8 @@ class HeadersResponseHandler(ResponseHandler): test_key_value = {} def action(self, test, header, value): + header = header.lower() # case-insensitive comparison + response = test.response header_value = test.replace_template(value)
case-insensitive headers As far as I can tell, gabbi enforces lowercase headers: ```yaml response_headers: content-type: text/html; charset=utf-8 ``` ``` ... ✓ front page returns HTML ``` vs. ```yaml response_headers: Content-Type: text/html; charset=utf-8 ``` ``` ... E front page returns HTML ERROR: front page returns HTML "'Content-Type' header not available in response keys: dict_keys(['server', 'content-type', 'access-control-allow-origin', 'date', 'access-control-allow-credentials', 'connection', 'content-location', 'content-length', 'status'])" ``` From my perspective, the second version is more readable - so it would be nice if header name comparisons were case-insensitive.
cdent/gabbi
diff --git a/gabbi/tests/test_handlers.py b/gabbi/tests/test_handlers.py index b18e8ec..b647e80 100644 --- a/gabbi/tests/test_handlers.py +++ b/gabbi/tests/test_handlers.py @@ -94,10 +94,16 @@ class HandlersTest(unittest.TestCase): def test_response_headers(self): handler = handlers.HeadersResponseHandler(self.test_class) + self.test.response = {'content-type': 'text/plain'} + self.test.test_data = {'response_headers': { 'content-type': 'text/plain', }} - self.test.response = {'content-type': 'text/plain'} + self._assert_handler(handler) + + self.test.test_data = {'response_headers': { + 'Content-Type': 'text/plain', + }} self._assert_handler(handler) def test_response_headers_regex(self):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "tox", "pytest" ], "pre_install": [ "pip install tox" ], "python": "3.4", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 decorator==5.1.1 distlib==0.3.9 filelock==3.4.1 fixtures==4.0.1 -e git+https://github.com/cdent/gabbi.git@f2a32ad31bc205580834f009f05586a533f390f7#egg=gabbi httplib2==0.22.0 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 jsonpath-rw==1.4.0 packaging==21.3 pbr==6.1.1 platformdirs==2.4.0 pluggy==1.0.0 ply==3.11 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 six==1.17.0 testtools==2.6.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 virtualenv==20.17.1 wsgi_intercept==1.13.1 zipp==3.6.0
name: gabbi channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - decorator==5.1.1 - distlib==0.3.9 - filelock==3.4.1 - fixtures==4.0.1 - httplib2==0.22.0 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jsonpath-rw==1.4.0 - packaging==21.3 - pbr==6.1.1 - platformdirs==2.4.0 - pluggy==1.0.0 - ply==3.11 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - six==1.17.0 - testtools==2.6.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - virtualenv==20.17.1 - wsgi-intercept==1.13.1 - zipp==3.6.0 prefix: /opt/conda/envs/gabbi
[ "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers" ]
[]
[ "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_fail_data", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_fail_header", "gabbi/tests/test_handlers.py::HandlersTest::test_response_headers_regex", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_fail_data", "gabbi/tests/test_handlers.py::HandlersTest::test_response_json_paths_fail_path", "gabbi/tests/test_handlers.py::HandlersTest::test_response_strings", "gabbi/tests/test_handlers.py::HandlersTest::test_response_strings_fail" ]
[]
Apache License 2.0
194
134
[ "gabbi/handlers.py" ]
tailhook__injections-6
680d3403f0086e0a94d69604bba0bfcbd9596014
2015-07-16 17:37:03
680d3403f0086e0a94d69604bba0bfcbd9596014
diff --git a/injections/__init__.py b/injections/__init__.py index 47bdc0d..dce8a9e 100644 --- a/injections/__init__.py +++ b/injections/__init__.py @@ -1,6 +1,7 @@ from .core import ( Container, Dependency, + MissingDependencyError, has, depends, propagate, @@ -11,6 +12,7 @@ from .core import ( __all__ = [ 'Container', 'Dependency', + 'MissingDependencyError', 'has', 'depends', 'propagate', diff --git a/injections/core.py b/injections/core.py index a4dccae..edff1db 100644 --- a/injections/core.py +++ b/injections/core.py @@ -76,6 +76,13 @@ class Dependency: depends = Dependency # nicer declarative name +class MissingDependencyError(KeyError): + """Required dependency is missed in container""" + + def __str__(self): + return "Dependency {!r} is missed in container".format(self.args[0]) + + class Container(object): """Container for things that will be dependency-injected @@ -104,7 +111,10 @@ class Container(object): deps = getattr(inst, '__injections__', None) if deps: for attr, dep in deps.items(): - val = pro[dep.name] + val = pro.get(dep.name) + if val is None: + raise MissingDependencyError(dep.name) + if not isinstance(val, dep.type): raise TypeError("Wrong provider for {!r}".format(val)) setattr(inst, attr, val) diff --git a/setup.py b/setup.py index 41cf797..c1e7d04 100644 --- a/setup.py +++ b/setup.py @@ -16,4 +16,5 @@ setup(name='injections', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2', ], + license='MIT', )
Use custom exception for injecting container into object with unknown dependencies I have a class ``` @has class A: redis = depends(Redis) loop = depends(AbstractLoop) ``` When I try to initialize it from container with missing dependencies I have a `KeyError`. ``` inj = Container() inj['redis'] = create_redis() inj.inject(A()) # raises KeyError ``` Exception on injection stage is pretty cool but I suggest using custom exception class. Not `KeyError` but derived from it. Exception text also should be more informative than just `KeyError: 'loop'`.
tailhook/injections
diff --git a/injections/test_core.py b/injections/test_core.py index 2e9aabe..06006cd 100644 --- a/injections/test_core.py +++ b/injections/test_core.py @@ -126,3 +126,21 @@ class TestCore(TestCase): c['name'] = 1 with self.assertRaises(TypeError): c.inject(self.Consumer()) + + def test_missing_dependency(self): + c = di.Container() + c['a'] = 1 + + @di.has + class Consumer: + a = di.depends(int) + b = di.depends(int) + + if hasattr(self, 'assertRaisesRegex'): + checker = self.assertRaisesRegex + else: + checker = self.assertRaisesRegexp + + with checker(di.MissingDependencyError, + "Dependency 'b' is missed in container"): + c.inject(Consumer())
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 3 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "pytest" ], "pre_install": null, "python": "3.4", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/tailhook/injections.git@680d3403f0086e0a94d69604bba0bfcbd9596014#egg=injections more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work nose==1.3.7 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: injections channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - nose==1.3.7 prefix: /opt/conda/envs/injections
[ "injections/test_core.py::TestCore::test_missing_dependency" ]
[]
[ "injections/test_core.py::TestCore::test_clone", "injections/test_core.py::TestCore::test_cyclic", "injections/test_core.py::TestCore::test_interconnect", "injections/test_core.py::TestCore::test_larger_cycle", "injections/test_core.py::TestCore::test_ok", "injections/test_core.py::TestCore::test_wrong_type" ]
[]
MIT License
196
483
[ "injections/__init__.py", "injections/core.py", "setup.py" ]
softlayer__softlayer-python-602
1195b2020ef6efc40462d59eb079f26e5f39a6d8
2015-08-10 15:51:18
1195b2020ef6efc40462d59eb079f26e5f39a6d8
diff --git a/SoftLayer/CLI/server/detail.py b/SoftLayer/CLI/server/detail.py index 1b9d588e..9fc76c5d 100644 --- a/SoftLayer/CLI/server/detail.py +++ b/SoftLayer/CLI/server/detail.py @@ -62,14 +62,11 @@ def cli(env, identifier, passwords, price): table.add_row( ['created', result['provisionDate'] or formatting.blank()]) - if utils.lookup(result, 'billingItem') != []: - table.add_row(['owner', formatting.FormattedItem( - utils.lookup(result, 'billingItem', 'orderItem', - 'order', 'userRecord', - 'username') or formatting.blank(), - )]) - else: - table.add_row(['owner', formatting.blank()]) + table.add_row(['owner', formatting.FormattedItem( + utils.lookup(result, 'billingItem', 'orderItem', + 'order', 'userRecord', + 'username') or formatting.blank() + )]) vlan_table = formatting.Table(['type', 'number', 'id']) diff --git a/SoftLayer/CLI/virt/detail.py b/SoftLayer/CLI/virt/detail.py index b003e413..4fc115ce 100644 --- a/SoftLayer/CLI/virt/detail.py +++ b/SoftLayer/CLI/virt/detail.py @@ -67,14 +67,11 @@ def cli(self, identifier, passwords=False, price=False): table.add_row(['private_cpu', result['dedicatedAccountHostOnlyFlag']]) table.add_row(['created', result['createDate']]) table.add_row(['modified', result['modifyDate']]) - if utils.lookup(result, 'billingItem') != []: - table.add_row(['owner', formatting.FormattedItem( - utils.lookup(result, 'billingItem', 'orderItem', - 'order', 'userRecord', - 'username') or formatting.blank(), - )]) - else: - table.add_row(['owner', formatting.blank()]) + table.add_row(['owner', formatting.FormattedItem( + utils.lookup(result, 'billingItem', 'orderItem', + 'order', 'userRecord', + 'username') or formatting.blank(), + )]) vlan_table = formatting.Table(['type', 'number', 'id']) for vlan in result['networkVlans']: diff --git a/SoftLayer/managers/vs.py b/SoftLayer/managers/vs.py index 30de90b3..40ea9925 100644 --- a/SoftLayer/managers/vs.py +++ b/SoftLayer/managers/vs.py @@ -423,6 +423,7 @@ def verify_create_instance(self, **kwargs): Without actually placing an order. See :func:`create_instance` for a list of available options. """ + kwargs.pop('tags', None) create_options = self._generate_create_dict(**kwargs) return self.guest.generateOrderTemplate(create_options)
got an unexpected keyword argument 'tags' Hi there I came across an error when creating VS and providing tags either in the form of -g or --tag C:\Python34\Scripts>slcli vs create --test --hostname OS --domain vm.local --cpu 1 --memory 1024 --os WIN_LATEST_64 --datacenter lon02 --tag 1234 An unexpected error has occured: Traceback (most recent call last): File "C:\Python34\lib\site-packages\SoftLayer\CLI\core.py", line 181, in main cli.main() File "C:\Python34\lib\site-packages\click\core.py", line 644, in main rv = self.invoke(ctx) File "C:\Python34\lib\site-packages\click\core.py", line 991, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Python34\lib\site-packages\click\core.py", line 991, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Python34\lib\site-packages\click\core.py", line 837, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Python34\lib\site-packages\click\core.py", line 464, in invoke return callback(*args, **kwargs) File "C:\Python34\lib\site-packages\click\decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args[1:], **kwargs) File "C:\Python34\lib\site-packages\click\core.py", line 464, in invoke return callback(*args, **kwargs) File "C:\Python34\lib\site-packages\SoftLayer\CLI\virt\create.py", line 92, in cli result = vsi.verify_create_instance(**data) File "C:\Python34\lib\site-packages\SoftLayer\managers\vs.py", line 426, in verify_create_instance create_options = self._generate_create_dict(**kwargs) TypeError: _generate_create_dict() got an unexpected keyword argument 'tags'
softlayer/softlayer-python
diff --git a/SoftLayer/tests/managers/vs_tests.py b/SoftLayer/tests/managers/vs_tests.py index 3a179b46..9bdb3459 100644 --- a/SoftLayer/tests/managers/vs_tests.py +++ b/SoftLayer/tests/managers/vs_tests.py @@ -141,7 +141,7 @@ def test_reload_instance(self): def test_create_verify(self, create_dict): create_dict.return_value = {'test': 1, 'verify': 1} - self.vs.verify_create_instance(test=1, verify=1) + self.vs.verify_create_instance(test=1, verify=1, tags=['test', 'tags']) create_dict.assert_called_once_with(test=1, verify=1) self.assert_called_with('SoftLayer_Virtual_Guest',
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 3 }
4.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.6", "reqs_path": [ "tools/test-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.13 attrs==22.2.0 Babel==2.11.0 certifi==2021.5.30 charset-normalizer==2.0.12 click==8.0.4 coverage==6.2 distlib==0.3.9 docutils==0.18.1 filelock==3.4.1 fixtures==4.0.1 idna==3.10 imagesize==1.4.1 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 Jinja2==3.0.3 MarkupSafe==2.0.1 mock==5.2.0 nose==1.3.7 packaging==21.3 pbr==6.1.1 platformdirs==2.4.0 pluggy==1.0.0 prettytable==2.5.0 py==1.11.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 pytz==2025.2 requests==2.27.1 six==1.17.0 snowballstemmer==2.2.0 -e git+https://github.com/softlayer/softlayer-python.git@1195b2020ef6efc40462d59eb079f26e5f39a6d8#egg=SoftLayer Sphinx==5.3.0 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==2.0.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.5 testtools==2.6.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 wcwidth==0.2.13 zipp==3.6.0
name: softlayer-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.13 - attrs==22.2.0 - babel==2.11.0 - charset-normalizer==2.0.12 - click==8.0.4 - coverage==6.2 - distlib==0.3.9 - docutils==0.18.1 - filelock==3.4.1 - fixtures==4.0.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jinja2==3.0.3 - markupsafe==2.0.1 - mock==5.2.0 - nose==1.3.7 - packaging==21.3 - pbr==6.1.1 - platformdirs==2.4.0 - pluggy==1.0.0 - prettytable==2.5.0 - py==1.11.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pytz==2025.2 - requests==2.27.1 - six==1.17.0 - snowballstemmer==2.2.0 - sphinx==5.3.0 - sphinxcontrib-applehelp==1.0.2 - sphinxcontrib-devhelp==1.0.2 - sphinxcontrib-htmlhelp==2.0.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==1.0.3 - sphinxcontrib-serializinghtml==1.1.5 - testtools==2.6.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/softlayer-python
[ "SoftLayer/tests/managers/vs_tests.py::VSTests::test_create_verify" ]
[]
[ "SoftLayer/tests/managers/vs_tests.py::VSTests::test_cancel_instance", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_capture_additional_disks", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_captures", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_change_port_speed_private", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_change_port_speed_public", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_create_instance", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_create_instances", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_edit_blank", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_edit_full", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_edit_metadata", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_edit_tags", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_edit_tags_blank", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_basic", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_datacenter", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_dedicated", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_image_id", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_missing", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_monthly", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_multi_disk", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_network", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_no_disks", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_os_and_image", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_post_uri", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_private_network_only", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_private_vlan", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_public_vlan", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_single_disk", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_sshkey", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_generate_userdata", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_get_create_options", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_get_instance", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_get_item_id_for_upgrade", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_list_instances", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_list_instances_hourly", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_list_instances_monthly", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_list_instances_neither", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_list_instances_with_filters", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_reload_instance", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_rescue", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_resolve_ids_hostname", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_resolve_ids_ip", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_resolve_ids_ip_invalid", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_resolve_ids_ip_private", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_upgrade", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_upgrade_blank", "SoftLayer/tests/managers/vs_tests.py::VSTests::test_upgrade_full", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_active_and_provisiondate", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_active_not_provisioned", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_active_provision_pending", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_active_reload", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_iter_four_complete", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_iter_once_complete", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_iter_ten_incomplete", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_iter_two_incomplete", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_ready_iter_once_incomplete", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_reload_no_pending", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_reload_pending", "SoftLayer/tests/managers/vs_tests.py::VSWaitReadyGoTests::test_wait_interface" ]
[]
MIT License
209
698
[ "SoftLayer/CLI/server/detail.py", "SoftLayer/CLI/virt/detail.py", "SoftLayer/managers/vs.py" ]
tobgu__pyrsistent-57
d35ea98728473bd070ff1e6ac5304e4e12ea816c
2015-09-14 21:17:17
87706acb8297805b56bcc2c0f89ffa73eb1de0d1
diff --git a/pyrsistent/_field_common.py b/pyrsistent/_field_common.py index 6934978..04231c0 100644 --- a/pyrsistent/_field_common.py +++ b/pyrsistent/_field_common.py @@ -2,7 +2,8 @@ from collections import Iterable import six from pyrsistent._checked_types import ( CheckedType, CheckedPSet, CheckedPMap, CheckedPVector, - optional as optional_type, InvariantException, get_type, wrap_invariant) + optional as optional_type, InvariantException, get_type, wrap_invariant, + _restore_pickle) def set_fields(dct, bases, name): @@ -121,12 +122,42 @@ class PTypeError(TypeError): self.actual_type = actual_type -def _sequence_field(checked_class, suffix, item_type, optional, initial): +SEQ_FIELD_TYPE_SUFFIXES = { + CheckedPVector: "PVector", + CheckedPSet: "PSet", +} + +# Global dictionary to hold auto-generated field types: used for unpickling +_seq_field_types = {} + +def _restore_seq_field_pickle(checked_class, item_type, data): + """Unpickling function for auto-generated PVec/PSet field types.""" + type_ = _seq_field_types[checked_class, item_type] + return _restore_pickle(type_, data) + +def _make_seq_field_type(checked_class, item_type): + """Create a subclass of the given checked class with the given item type.""" + type_ = _seq_field_types.get((checked_class, item_type)) + if type_ is not None: + return type_ + + class TheType(checked_class): + __type__ = item_type + + def __reduce__(self): + return (_restore_seq_field_pickle, + (checked_class, item_type, list(self))) + + suffix = SEQ_FIELD_TYPE_SUFFIXES[checked_class] + TheType.__name__ = item_type.__name__.capitalize() + suffix + _seq_field_types[checked_class, item_type] = TheType + return TheType + +def _sequence_field(checked_class, item_type, optional, initial): """ Create checked field for either ``PSet`` or ``PVector``. :param checked_class: ``CheckedPSet`` or ``CheckedPVector``. - :param suffix: Suffix for new type name. :param item_type: The required type for the items in the set. :param optional: If true, ``None`` can be used as a value for this field. @@ -134,9 +165,7 @@ def _sequence_field(checked_class, suffix, item_type, optional, initial): :return: A ``field`` containing a checked class. """ - class TheType(checked_class): - __type__ = item_type - TheType.__name__ = item_type.__name__.capitalize() + suffix + TheType = _make_seq_field_type(checked_class, item_type) if optional: def factory(argument): @@ -164,7 +193,7 @@ def pset_field(item_type, optional=False, initial=()): :return: A ``field`` containing a ``CheckedPSet`` of the given type. """ - return _sequence_field(CheckedPSet, "PSet", item_type, optional, + return _sequence_field(CheckedPSet, item_type, optional, initial) @@ -180,13 +209,41 @@ def pvector_field(item_type, optional=False, initial=()): :return: A ``field`` containing a ``CheckedPVector`` of the given type. """ - return _sequence_field(CheckedPVector, "PVector", item_type, optional, + return _sequence_field(CheckedPVector, item_type, optional, initial) _valid = lambda item: (True, "") +# Global dictionary to hold auto-generated field types: used for unpickling +_pmap_field_types = {} + +def _restore_pmap_field_pickle(key_type, value_type, data): + """Unpickling function for auto-generated PMap field types.""" + type_ = _pmap_field_types[key_type, value_type] + return _restore_pickle(type_, data) + +def _make_pmap_field_type(key_type, value_type): + """Create a subclass of CheckedPMap with the given key and value types.""" + type_ = _pmap_field_types.get((key_type, value_type)) + if type_ is not None: + return type_ + + class TheMap(CheckedPMap): + __key_type__ = key_type + __value_type__ = value_type + + def __reduce__(self): + return (_restore_pmap_field_pickle, + (self.__key_type__, self.__value_type__, dict(self))) + + TheMap.__name__ = (key_type.__name__.capitalize() + + value_type.__name__.capitalize() + "PMap") + _pmap_field_types[key_type, value_type] = TheMap + return TheMap + + def pmap_field(key_type, value_type, optional=False, invariant=PFIELD_NO_INVARIANT): """ Create a checked ``PMap`` field. @@ -199,11 +256,7 @@ def pmap_field(key_type, value_type, optional=False, invariant=PFIELD_NO_INVARIA :return: A ``field`` containing a ``CheckedPMap``. """ - class TheMap(CheckedPMap): - __key_type__ = key_type - __value_type__ = value_type - TheMap.__name__ = (key_type.__name__.capitalize() + - value_type.__name__.capitalize() + "PMap") + TheMap = _make_pmap_field_type(key_type, value_type) if optional: def factory(argument):
p*_field prevents pickle from working on a PClass I would never use pickle in production, but as I was trying to write some strawman example storage code for an example app, I discovered that while I could pickle basic PClasses, I can't pickle any that use pmap_field or pvector_field (and probably others that have similar implementations) e.g.: ``` >>> class Foo(PClass): ... v = pvector_field(int) ... >>> Foo() Foo(v=IntPVector([])) >>> dumps(Foo()) Traceback (most recent call last): File "<stdin>", line 1, in <module> cPickle.PicklingError: Can't pickle <class 'pyrsistent._field_common.IntPVector'>: attribute lookup pyrsistent._field_common.IntPVector failed ``` The same happens for `pmap_field`. I guess this is because of the way that those functions generate classes at runtime? @tobgu if you can let me know what needs done to fix this I can try to submit a PR.
tobgu/pyrsistent
diff --git a/tests/class_test.py b/tests/class_test.py index f7254b4..0caddba 100644 --- a/tests/class_test.py +++ b/tests/class_test.py @@ -2,7 +2,9 @@ from collections import Hashable import math import pickle import pytest -from pyrsistent import field, InvariantException, PClass, optional, CheckedPVector +from pyrsistent import ( + field, InvariantException, PClass, optional, CheckedPVector, + pmap_field, pset_field, pvector_field) class Point(PClass): @@ -11,6 +13,12 @@ class Point(PClass): z = field(type=int, initial=0) +class TypedContainerObj(PClass): + map = pmap_field(str, str) + set = pset_field(str) + vec = pvector_field(str) + + def test_evolve_pclass_instance(): p = Point(x=1, y=2) p2 = p.set(x=p.x+2) @@ -165,6 +173,12 @@ def test_supports_pickling(): assert isinstance(p2, Point) +def test_supports_pickling_with_typed_container_fields(): + obj = TypedContainerObj(map={'foo': 'bar'}, set=['hello', 'there'], vec=['a', 'b']) + obj2 = pickle.loads(pickle.dumps(obj)) + assert obj == obj2 + + def test_can_remove_optional_member(): p1 = Point(x=1, y=2) p2 = p1.remove('y') @@ -250,4 +264,4 @@ def test_multiple_global_invariants(): MultiInvariantGlobal(one=1) assert False except InvariantException as e: - assert e.invariant_errors == (('x', 'y'),) \ No newline at end of file + assert e.invariant_errors == (('x', 'y'),) diff --git a/tests/record_test.py b/tests/record_test.py index 9146bd0..b2439e5 100644 --- a/tests/record_test.py +++ b/tests/record_test.py @@ -13,6 +13,12 @@ class ARecord(PRecord): y = field() +class RecordContainingContainers(PRecord): + map = pmap_field(str, str) + vec = pvector_field(str) + set = pset_field(str) + + def test_create(): r = ARecord(x=1, y='foo') assert r.x == 1 @@ -223,6 +229,11 @@ def test_pickling(): assert x == y assert isinstance(y, ARecord) +def test_supports_pickling_with_typed_container_fields(): + obj = RecordContainingContainers( + map={'foo': 'bar'}, set=['hello', 'there'], vec=['a', 'b']) + obj2 = pickle.loads(pickle.dumps(obj)) + assert obj == obj2 def test_all_invariant_errors_reported(): class BRecord(PRecord):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 1 }
0.11
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 attrs==25.3.0 babel==2.17.0 cachetools==5.5.2 certifi==2025.1.31 chardet==5.2.0 charset-normalizer==3.4.1 colorama==0.4.6 coverage==7.8.0 distlib==0.3.9 docutils==0.21.2 exceptiongroup==1.2.2 filelock==3.18.0 hypothesis==6.130.5 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 memory_profiler==0.31 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 psutil==2.1.1 py==1.11.0 Pygments==2.19.1 pyperform==1.86 pyproject-api==1.9.0 -e git+https://github.com/tobgu/pyrsistent.git@d35ea98728473bd070ff1e6ac5304e4e12ea816c#egg=pyrsistent pytest==8.3.5 pytest-cov==6.0.0 requests==2.32.3 six==1.17.0 snowballstemmer==2.2.0 sortedcontainers==2.4.0 Sphinx==7.4.7 sphinx_rtd_theme==0.1.5 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 urllib3==2.3.0 virtualenv==20.29.3 zipp==3.21.0
name: pyrsistent channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - attrs==25.3.0 - babel==2.17.0 - cachetools==5.5.2 - certifi==2025.1.31 - chardet==5.2.0 - charset-normalizer==3.4.1 - colorama==0.4.6 - coverage==7.8.0 - distlib==0.3.9 - docutils==0.21.2 - exceptiongroup==1.2.2 - filelock==3.18.0 - hypothesis==6.130.5 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - memory-profiler==0.31 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - psutil==2.1.1 - py==1.11.0 - pygments==2.19.1 - pyperform==1.86 - pyproject-api==1.9.0 - pytest==8.3.5 - pytest-cov==6.0.0 - requests==2.32.3 - six==1.17.0 - snowballstemmer==2.2.0 - sortedcontainers==2.4.0 - sphinx==7.4.7 - sphinx-rtd-theme==0.1.5 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - urllib3==2.3.0 - virtualenv==20.29.3 - zipp==3.21.0 prefix: /opt/conda/envs/pyrsistent
[ "tests/class_test.py::test_supports_pickling_with_typed_container_fields", "tests/record_test.py::test_supports_pickling_with_typed_container_fields" ]
[]
[ "tests/class_test.py::test_evolve_pclass_instance", "tests/class_test.py::test_direct_assignment_not_possible", "tests/class_test.py::test_direct_delete_not_possible", "tests/class_test.py::test_cannot_construct_with_undeclared_fields", "tests/class_test.py::test_cannot_construct_with_wrong_type", "tests/class_test.py::test_cannot_construct_without_mandatory_fields", "tests/class_test.py::test_field_invariant_must_hold", "tests/class_test.py::test_initial_value_set_when_not_present_in_arguments", "tests/class_test.py::test_can_create_nested_structures_from_dict_and_serialize_back_to_dict", "tests/class_test.py::test_can_serialize_with_custom_serializer", "tests/class_test.py::test_implements_proper_equality_based_on_equality_of_fields", "tests/class_test.py::test_is_hashable", "tests/class_test.py::test_supports_nested_transformation", "tests/class_test.py::test_repr", "tests/class_test.py::test_global_invariant_check", "tests/class_test.py::test_supports_pickling", "tests/class_test.py::test_can_remove_optional_member", "tests/class_test.py::test_cannot_remove_mandatory_member", "tests/class_test.py::test_cannot_remove_non_existing_member", "tests/class_test.py::test_evolver_without_evolution_returns_original_instance", "tests/class_test.py::test_evolver_with_evolution_to_same_element_returns_original_instance", "tests/class_test.py::test_evolver_supports_chained_set_and_remove", "tests/class_test.py::test_string_as_type_specifier", "tests/class_test.py::test_multiple_invariants_on_field", "tests/class_test.py::test_multiple_global_invariants", "tests/record_test.py::test_create", "tests/record_test.py::test_correct_assignment", "tests/record_test.py::test_direct_assignment_not_possible", "tests/record_test.py::test_cannot_assign_undeclared_fields", "tests/record_test.py::test_cannot_assign_wrong_type_to_fields", "tests/record_test.py::test_cannot_construct_with_undeclared_fields", "tests/record_test.py::test_cannot_construct_with_fields_of_wrong_type", "tests/record_test.py::test_support_record_inheritance", "tests/record_test.py::test_single_type_spec", "tests/record_test.py::test_remove", "tests/record_test.py::test_remove_non_existing_member", "tests/record_test.py::test_field_invariant_must_hold", "tests/record_test.py::test_global_invariant_must_hold", "tests/record_test.py::test_set_multiple_fields", "tests/record_test.py::test_initial_value", "tests/record_test.py::test_type_specification_must_be_a_type", "tests/record_test.py::test_initial_must_be_of_correct_type", "tests/record_test.py::test_invariant_must_be_callable", "tests/record_test.py::test_global_invariants_are_inherited", "tests/record_test.py::test_global_invariants_must_be_callable", "tests/record_test.py::test_repr", "tests/record_test.py::test_factory", "tests/record_test.py::test_factory_must_be_callable", "tests/record_test.py::test_nested_record_construction", "tests/record_test.py::test_pickling", "tests/record_test.py::test_all_invariant_errors_reported", "tests/record_test.py::test_precord_factory_method_is_idempotent", "tests/record_test.py::test_serialize", "tests/record_test.py::test_nested_serialize", "tests/record_test.py::test_serializer_must_be_callable", "tests/record_test.py::test_transform_without_update_returns_same_precord", "tests/record_test.py::test_nested_create_serialize", "tests/record_test.py::test_pset_field_initial_value", "tests/record_test.py::test_pset_field_custom_initial", "tests/record_test.py::test_pset_field_factory", "tests/record_test.py::test_pset_field_checked_set", "tests/record_test.py::test_pset_field_type", "tests/record_test.py::test_pset_field_mandatory", "tests/record_test.py::test_pset_field_default_non_optional", "tests/record_test.py::test_pset_field_explicit_non_optional", "tests/record_test.py::test_pset_field_optional", "tests/record_test.py::test_pset_field_name", "tests/record_test.py::test_pvector_field_initial_value", "tests/record_test.py::test_pvector_field_custom_initial", "tests/record_test.py::test_pvector_field_factory", "tests/record_test.py::test_pvector_field_checked_vector", "tests/record_test.py::test_pvector_field_type", "tests/record_test.py::test_pvector_field_mandatory", "tests/record_test.py::test_pvector_field_default_non_optional", "tests/record_test.py::test_pvector_field_explicit_non_optional", "tests/record_test.py::test_pvector_field_optional", "tests/record_test.py::test_pvector_field_name", "tests/record_test.py::test_pvector_field_create_from_nested_serialized_data", "tests/record_test.py::test_pmap_field_initial_value", "tests/record_test.py::test_pmap_field_factory", "tests/record_test.py::test_pmap_field_checked_map_key", "tests/record_test.py::test_pmap_field_checked_map_value", "tests/record_test.py::test_pmap_field_mandatory", "tests/record_test.py::test_pmap_field_default_non_optional", "tests/record_test.py::test_pmap_field_explicit_non_optional", "tests/record_test.py::test_pmap_field_optional", "tests/record_test.py::test_pmap_field_name", "tests/record_test.py::test_pmap_field_invariant", "tests/record_test.py::test_pmap_field_create_from_nested_serialized_data" ]
[]
MIT License
238
1,348
[ "pyrsistent/_field_common.py" ]
docker__docker-py-770
02f330d8dc3da47215bed47b44fac73941ea6920
2015-09-15 21:47:09
f479720d517a7db7f886916190b3032d29d18f10
shin-: #764 needs to be merged for the tests to pass.
diff --git a/docker/utils/utils.py b/docker/utils/utils.py index 46b35160..36edf8de 100644 --- a/docker/utils/utils.py +++ b/docker/utils/utils.py @@ -457,7 +457,8 @@ def create_host_config( restart_policy=None, cap_add=None, cap_drop=None, devices=None, extra_hosts=None, read_only=None, pid_mode=None, ipc_mode=None, security_opt=None, ulimits=None, log_config=None, mem_limit=None, - memswap_limit=None, cgroup_parent=None, group_add=None, version=None + memswap_limit=None, cgroup_parent=None, group_add=None, cpu_quota=None, + cpu_period=None, version=None ): host_config = {} @@ -518,7 +519,7 @@ def create_host_config( host_config['Devices'] = parse_devices(devices) if group_add: - if compare_version(version, '1.20') < 0: + if version_lt(version, '1.20'): raise errors.InvalidVersion( 'group_add param not supported for API version < 1.20' ) @@ -601,6 +602,30 @@ def create_host_config( log_config = LogConfig(**log_config) host_config['LogConfig'] = log_config + if cpu_quota: + if not isinstance(cpu_quota, int): + raise TypeError( + 'Invalid type for cpu_quota param: expected int but' + ' found {0}'.format(type(cpu_quota)) + ) + if version_lt(version, '1.19'): + raise errors.InvalidVersion( + 'cpu_quota param not supported for API version < 1.19' + ) + host_config['CpuQuota'] = cpu_quota + + if cpu_period: + if not isinstance(cpu_period, int): + raise TypeError( + 'Invalid type for cpu_period param: expected int but' + ' found {0}'.format(type(cpu_period)) + ) + if version_lt(version, '1.19'): + raise errors.InvalidVersion( + 'cpu_period param not supported for API version < 1.19' + ) + host_config['CpuPeriod'] = cpu_period + return host_config
Add support for --cpu-quota & --cpu-period run flags Any chance we could add support for the above run flags? https://docs.docker.com/reference/commandline/run/
docker/docker-py
diff --git a/tests/utils_test.py b/tests/utils_test.py index b67ac4ec..45929f73 100644 --- a/tests/utils_test.py +++ b/tests/utils_test.py @@ -25,6 +25,159 @@ TEST_CERT_DIR = os.path.join( ) +class HostConfigTest(base.BaseTestCase): + def test_create_host_config_no_options(self): + config = create_host_config(version='1.19') + self.assertFalse('NetworkMode' in config) + + def test_create_host_config_no_options_newer_api_version(self): + config = create_host_config(version='1.20') + self.assertEqual(config['NetworkMode'], 'default') + + def test_create_host_config_invalid_cpu_cfs_types(self): + with pytest.raises(TypeError): + create_host_config(version='1.20', cpu_quota='0') + + with pytest.raises(TypeError): + create_host_config(version='1.20', cpu_period='0') + + with pytest.raises(TypeError): + create_host_config(version='1.20', cpu_quota=23.11) + + with pytest.raises(TypeError): + create_host_config(version='1.20', cpu_period=1999.0) + + def test_create_host_config_with_cpu_quota(self): + config = create_host_config(version='1.20', cpu_quota=1999) + self.assertEqual(config.get('CpuQuota'), 1999) + + def test_create_host_config_with_cpu_period(self): + config = create_host_config(version='1.20', cpu_period=1999) + self.assertEqual(config.get('CpuPeriod'), 1999) + + +class UlimitTest(base.BaseTestCase): + def test_create_host_config_dict_ulimit(self): + ulimit_dct = {'name': 'nofile', 'soft': 8096} + config = create_host_config( + ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION + ) + self.assertIn('Ulimits', config) + self.assertEqual(len(config['Ulimits']), 1) + ulimit_obj = config['Ulimits'][0] + self.assertTrue(isinstance(ulimit_obj, Ulimit)) + self.assertEqual(ulimit_obj.name, ulimit_dct['name']) + self.assertEqual(ulimit_obj.soft, ulimit_dct['soft']) + self.assertEqual(ulimit_obj['Soft'], ulimit_obj.soft) + + def test_create_host_config_dict_ulimit_capitals(self): + ulimit_dct = {'Name': 'nofile', 'Soft': 8096, 'Hard': 8096 * 4} + config = create_host_config( + ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION + ) + self.assertIn('Ulimits', config) + self.assertEqual(len(config['Ulimits']), 1) + ulimit_obj = config['Ulimits'][0] + self.assertTrue(isinstance(ulimit_obj, Ulimit)) + self.assertEqual(ulimit_obj.name, ulimit_dct['Name']) + self.assertEqual(ulimit_obj.soft, ulimit_dct['Soft']) + self.assertEqual(ulimit_obj.hard, ulimit_dct['Hard']) + self.assertEqual(ulimit_obj['Soft'], ulimit_obj.soft) + + def test_create_host_config_obj_ulimit(self): + ulimit_dct = Ulimit(name='nofile', soft=8096) + config = create_host_config( + ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION + ) + self.assertIn('Ulimits', config) + self.assertEqual(len(config['Ulimits']), 1) + ulimit_obj = config['Ulimits'][0] + self.assertTrue(isinstance(ulimit_obj, Ulimit)) + self.assertEqual(ulimit_obj, ulimit_dct) + + def test_ulimit_invalid_type(self): + self.assertRaises(ValueError, lambda: Ulimit(name=None)) + self.assertRaises(ValueError, lambda: Ulimit(name='hello', soft='123')) + self.assertRaises(ValueError, lambda: Ulimit(name='hello', hard='456')) + + +class LogConfigTest(base.BaseTestCase): + def test_create_host_config_dict_logconfig(self): + dct = {'type': LogConfig.types.SYSLOG, 'config': {'key1': 'val1'}} + config = create_host_config( + version=DEFAULT_DOCKER_API_VERSION, log_config=dct + ) + self.assertIn('LogConfig', config) + self.assertTrue(isinstance(config['LogConfig'], LogConfig)) + self.assertEqual(dct['type'], config['LogConfig'].type) + + def test_create_host_config_obj_logconfig(self): + obj = LogConfig(type=LogConfig.types.SYSLOG, config={'key1': 'val1'}) + config = create_host_config( + version=DEFAULT_DOCKER_API_VERSION, log_config=obj + ) + self.assertIn('LogConfig', config) + self.assertTrue(isinstance(config['LogConfig'], LogConfig)) + self.assertEqual(obj, config['LogConfig']) + + def test_logconfig_invalid_config_type(self): + with pytest.raises(ValueError): + LogConfig(type=LogConfig.types.JSON, config='helloworld') + + +class KwargsFromEnvTest(base.BaseTestCase): + def setUp(self): + self.os_environ = os.environ.copy() + + def tearDown(self): + os.environ = self.os_environ + + def test_kwargs_from_env_empty(self): + os.environ.update(DOCKER_HOST='', + DOCKER_CERT_PATH='', + DOCKER_TLS_VERIFY='') + + kwargs = kwargs_from_env() + self.assertEqual(None, kwargs.get('base_url')) + self.assertEqual(None, kwargs.get('tls')) + + def test_kwargs_from_env_tls(self): + os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376', + DOCKER_CERT_PATH=TEST_CERT_DIR, + DOCKER_TLS_VERIFY='1') + kwargs = kwargs_from_env(assert_hostname=False) + self.assertEqual('https://192.168.59.103:2376', kwargs['base_url']) + self.assertTrue('ca.pem' in kwargs['tls'].verify) + self.assertTrue('cert.pem' in kwargs['tls'].cert[0]) + self.assertTrue('key.pem' in kwargs['tls'].cert[1]) + self.assertEqual(False, kwargs['tls'].assert_hostname) + try: + client = Client(**kwargs) + self.assertEqual(kwargs['base_url'], client.base_url) + self.assertEqual(kwargs['tls'].verify, client.verify) + self.assertEqual(kwargs['tls'].cert, client.cert) + except TypeError as e: + self.fail(e) + + def test_kwargs_from_env_no_cert_path(self): + try: + temp_dir = tempfile.mkdtemp() + cert_dir = os.path.join(temp_dir, '.docker') + shutil.copytree(TEST_CERT_DIR, cert_dir) + + os.environ.update(HOME=temp_dir, + DOCKER_CERT_PATH='', + DOCKER_TLS_VERIFY='1') + + kwargs = kwargs_from_env() + self.assertIn(cert_dir, kwargs['tls'].verify) + self.assertIn(cert_dir, kwargs['tls'].cert[0]) + self.assertIn(cert_dir, kwargs['tls'].cert[1]) + finally: + if temp_dir: + shutil.rmtree(temp_dir) + + class UtilsTest(base.BaseTestCase): longMessage = True @@ -39,12 +192,6 @@ class UtilsTest(base.BaseTestCase): local_tempfile.close() return local_tempfile.name - def setUp(self): - self.os_environ = os.environ.copy() - - def tearDown(self): - os.environ = self.os_environ - def test_parse_repository_tag(self): self.assertEqual(parse_repository_tag("root"), ("root", None)) @@ -103,51 +250,6 @@ class UtilsTest(base.BaseTestCase): assert parse_host(val, 'win32') == tcp_port - def test_kwargs_from_env_empty(self): - os.environ.update(DOCKER_HOST='', - DOCKER_CERT_PATH='', - DOCKER_TLS_VERIFY='') - - kwargs = kwargs_from_env() - self.assertEqual(None, kwargs.get('base_url')) - self.assertEqual(None, kwargs.get('tls')) - - def test_kwargs_from_env_tls(self): - os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376', - DOCKER_CERT_PATH=TEST_CERT_DIR, - DOCKER_TLS_VERIFY='1') - kwargs = kwargs_from_env(assert_hostname=False) - self.assertEqual('https://192.168.59.103:2376', kwargs['base_url']) - self.assertTrue('ca.pem' in kwargs['tls'].verify) - self.assertTrue('cert.pem' in kwargs['tls'].cert[0]) - self.assertTrue('key.pem' in kwargs['tls'].cert[1]) - self.assertEqual(False, kwargs['tls'].assert_hostname) - try: - client = Client(**kwargs) - self.assertEqual(kwargs['base_url'], client.base_url) - self.assertEqual(kwargs['tls'].verify, client.verify) - self.assertEqual(kwargs['tls'].cert, client.cert) - except TypeError as e: - self.fail(e) - - def test_kwargs_from_env_no_cert_path(self): - try: - temp_dir = tempfile.mkdtemp() - cert_dir = os.path.join(temp_dir, '.docker') - shutil.copytree(TEST_CERT_DIR, cert_dir) - - os.environ.update(HOME=temp_dir, - DOCKER_CERT_PATH='', - DOCKER_TLS_VERIFY='1') - - kwargs = kwargs_from_env() - self.assertIn(cert_dir, kwargs['tls'].verify) - self.assertIn(cert_dir, kwargs['tls'].cert[0]) - self.assertIn(cert_dir, kwargs['tls'].cert[1]) - finally: - if temp_dir: - shutil.rmtree(temp_dir) - def test_parse_env_file_proper(self): env_file = self.generate_tempfile( file_content='USER=jdoe\nPASS=secret') @@ -181,79 +283,6 @@ class UtilsTest(base.BaseTestCase): for filters, expected in tests: self.assertEqual(convert_filters(filters), expected) - def test_create_host_config_no_options(self): - config = create_host_config(version='1.19') - self.assertFalse('NetworkMode' in config) - - def test_create_host_config_no_options_newer_api_version(self): - config = create_host_config(version='1.20') - self.assertEqual(config['NetworkMode'], 'default') - - def test_create_host_config_dict_ulimit(self): - ulimit_dct = {'name': 'nofile', 'soft': 8096} - config = create_host_config( - ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION - ) - self.assertIn('Ulimits', config) - self.assertEqual(len(config['Ulimits']), 1) - ulimit_obj = config['Ulimits'][0] - self.assertTrue(isinstance(ulimit_obj, Ulimit)) - self.assertEqual(ulimit_obj.name, ulimit_dct['name']) - self.assertEqual(ulimit_obj.soft, ulimit_dct['soft']) - self.assertEqual(ulimit_obj['Soft'], ulimit_obj.soft) - - def test_create_host_config_dict_ulimit_capitals(self): - ulimit_dct = {'Name': 'nofile', 'Soft': 8096, 'Hard': 8096 * 4} - config = create_host_config( - ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION - ) - self.assertIn('Ulimits', config) - self.assertEqual(len(config['Ulimits']), 1) - ulimit_obj = config['Ulimits'][0] - self.assertTrue(isinstance(ulimit_obj, Ulimit)) - self.assertEqual(ulimit_obj.name, ulimit_dct['Name']) - self.assertEqual(ulimit_obj.soft, ulimit_dct['Soft']) - self.assertEqual(ulimit_obj.hard, ulimit_dct['Hard']) - self.assertEqual(ulimit_obj['Soft'], ulimit_obj.soft) - - def test_create_host_config_obj_ulimit(self): - ulimit_dct = Ulimit(name='nofile', soft=8096) - config = create_host_config( - ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION - ) - self.assertIn('Ulimits', config) - self.assertEqual(len(config['Ulimits']), 1) - ulimit_obj = config['Ulimits'][0] - self.assertTrue(isinstance(ulimit_obj, Ulimit)) - self.assertEqual(ulimit_obj, ulimit_dct) - - def test_ulimit_invalid_type(self): - self.assertRaises(ValueError, lambda: Ulimit(name=None)) - self.assertRaises(ValueError, lambda: Ulimit(name='hello', soft='123')) - self.assertRaises(ValueError, lambda: Ulimit(name='hello', hard='456')) - - def test_create_host_config_dict_logconfig(self): - dct = {'type': LogConfig.types.SYSLOG, 'config': {'key1': 'val1'}} - config = create_host_config( - version=DEFAULT_DOCKER_API_VERSION, log_config=dct - ) - self.assertIn('LogConfig', config) - self.assertTrue(isinstance(config['LogConfig'], LogConfig)) - self.assertEqual(dct['type'], config['LogConfig'].type) - - def test_create_host_config_obj_logconfig(self): - obj = LogConfig(type=LogConfig.types.SYSLOG, config={'key1': 'val1'}) - config = create_host_config( - version=DEFAULT_DOCKER_API_VERSION, log_config=obj - ) - self.assertIn('LogConfig', config) - self.assertTrue(isinstance(config['LogConfig'], LogConfig)) - self.assertEqual(obj, config['LogConfig']) - - def test_logconfig_invalid_config_type(self): - with pytest.raises(ValueError): - LogConfig(type=LogConfig.types.JSON, config='helloworld') - def test_resolve_repository_name(self): # docker hub library image self.assertEqual( @@ -407,6 +436,8 @@ class UtilsTest(base.BaseTestCase): None, ) + +class PortsTest(base.BaseTestCase): def test_split_port_with_host_ip(self): internal_port, external_port = split_port("127.0.0.1:1000:2000") self.assertEqual(internal_port, ["2000"])
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "flake8" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/docker/docker-py.git@02f330d8dc3da47215bed47b44fac73941ea6920#egg=docker_py exceptiongroup==1.2.2 flake8==7.2.0 iniconfig==2.1.0 mccabe==0.7.0 packaging==24.2 pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.2 pytest==8.3.5 requests==2.5.3 six==1.17.0 tomli==2.2.1 websocket_client==0.32.0
name: docker-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - flake8==7.2.0 - iniconfig==2.1.0 - mccabe==0.7.0 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.2 - pytest==8.3.5 - requests==2.5.3 - six==1.17.0 - tomli==2.2.1 - websocket-client==0.32.0 prefix: /opt/conda/envs/docker-py
[ "tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota" ]
[]
[ "tests/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/utils_test.py::HostConfigTest::test_create_host_config_no_options", "tests/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/utils_test.py::UlimitTest::test_ulimit_invalid_type", "tests/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/utils_test.py::UtilsTest::test_convert_filters", "tests/utils_test.py::UtilsTest::test_parse_bytes", "tests/utils_test.py::UtilsTest::test_parse_env_file_commented_line", "tests/utils_test.py::UtilsTest::test_parse_env_file_invalid_line", "tests/utils_test.py::UtilsTest::test_parse_env_file_proper", "tests/utils_test.py::UtilsTest::test_parse_host", "tests/utils_test.py::UtilsTest::test_parse_host_empty_value", "tests/utils_test.py::UtilsTest::test_parse_repository_tag", "tests/utils_test.py::UtilsTest::test_resolve_authconfig", "tests/utils_test.py::UtilsTest::test_resolve_registry_and_auth", "tests/utils_test.py::UtilsTest::test_resolve_repository_name", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/utils_test.py::PortsTest::test_host_only_with_colon", "tests/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/utils_test.py::PortsTest::test_port_only_with_colon", "tests/utils_test.py::PortsTest::test_split_port_invalid", "tests/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/utils_test.py::ExcludePathsTest::test_directory", "tests/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/utils_test.py::ExcludePathsTest::test_question_mark", "tests/utils_test.py::ExcludePathsTest::test_single_filename", "tests/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception" ]
[]
Apache License 2.0
239
527
[ "docker/utils/utils.py" ]
docker__docker-py-787
5e331a55a8e8e10354693172dce1aa63f58ebe97
2015-09-23 21:07:40
f479720d517a7db7f886916190b3032d29d18f10
shin-: @aanand Thanks, didn't know about `six.u`. PTAL? aanand: Cool. Perhaps the first test should be rewritten so it tests byte string input on all Python versions: ```python def test_convert_volume_bindings_binary_input(self): expected = [six.u('/mnt/지연:/unicode/박:rw')] data = { b'/mnt/지연': { 'bind': b'/unicode/박', 'mode': 'rw' } } self.assertEqual( convert_volume_binds(data), expected ) ``` shin-: Okay, I've tried all sorts of combination, I've settled on just separating py2 and py3 tests completely (so it's 2+2 now). On the bright side, results were consistent all along (and we have tests to prove it)! aanand: OK, I see the rationale, but instead of entirely separate test methods, could we just switch on the Python version *inside* the method? ```python def test_convert_volume_binds_unicode_bytes_input(self): if six.PY2: expected = [unicode('/mnt/지연:/unicode/박:rw', 'utf-8')] data = { '/mnt/지연': { 'bind': '/unicode/박', 'mode': 'rw' } } else: expected = ['/mnt/지연:/unicode/박:rw'] data = { bytes('/mnt/지연', 'utf-8'): { 'bind': bytes('/unicode/박', 'utf-8'), 'mode': 'rw' } } self.assertEqual(convert_volume_binds(data), expected) def test_convert_volume_binds_unicode_unicode_input(self): if six.PY2: expected = [unicode('/mnt/지연:/unicode/박:rw', 'utf-8')] data = { unicode('/mnt/지연', 'utf-8'): { 'bind': unicode('/unicode/박', 'utf-8'), 'mode': 'rw' } } else: expected = ['/mnt/지연:/unicode/박:rw'] data = { '/mnt/지연': { 'bind': '/unicode/박', 'mode': 'rw' } } self.assertEqual(convert_volume_binds(data), expected) ```
diff --git a/docker/utils/utils.py b/docker/utils/utils.py index 36edf8de..1fce1377 100644 --- a/docker/utils/utils.py +++ b/docker/utils/utils.py @@ -242,6 +242,9 @@ def convert_volume_binds(binds): result = [] for k, v in binds.items(): + if isinstance(k, six.binary_type): + k = k.decode('utf-8') + if isinstance(v, dict): if 'ro' in v and 'mode' in v: raise ValueError( @@ -249,6 +252,10 @@ def convert_volume_binds(binds): .format(repr(v)) ) + bind = v['bind'] + if isinstance(bind, six.binary_type): + bind = bind.decode('utf-8') + if 'ro' in v: mode = 'ro' if v['ro'] else 'rw' elif 'mode' in v: @@ -256,11 +263,15 @@ def convert_volume_binds(binds): else: mode = 'rw' - result.append('{0}:{1}:{2}'.format( - k, v['bind'], mode - )) + result.append( + six.text_type('{0}:{1}:{2}').format(k, bind, mode) + ) else: - result.append('{0}:{1}:rw'.format(k, v)) + if isinstance(v, six.binary_type): + v = v.decode('utf-8') + result.append( + six.text_type('{0}:{1}:rw').format(k, v) + ) return result
Create container bind volume with Unicode folder name If bind volume folder name is Unicode, for example Japanese, It will raise exception: Host volume and container volume both should handle Unicode. ``` File "/home/vagrant/.local/share/virtualenvs/qnap/local/lib/python2.7/site-packages/docker/utils/utils.py", line 461, in create_host_config host_config['Binds'] = convert_volume_binds(binds) File "/home/vagrant/.local/share/virtualenvs/qnap/local/lib/python2.7/site-packages/docker/utils/utils.py", line 208, in convert_volume_binds k, v['bind'], mode ```
docker/docker-py
diff --git a/tests/utils_test.py b/tests/utils_test.py index 45929f73..8ac1dcb9 100644 --- a/tests/utils_test.py +++ b/tests/utils_test.py @@ -1,15 +1,20 @@ +# -*- coding: utf-8 -*- + import os import os.path import shutil import tempfile +import pytest +import six + from docker.client import Client from docker.constants import DEFAULT_DOCKER_API_VERSION from docker.errors import DockerException from docker.utils import ( parse_repository_tag, parse_host, convert_filters, kwargs_from_env, create_host_config, Ulimit, LogConfig, parse_bytes, parse_env_file, - exclude_paths, + exclude_paths, convert_volume_binds, ) from docker.utils.ports import build_port_bindings, split_port from docker.auth import resolve_repository_name, resolve_authconfig @@ -17,7 +22,6 @@ from docker.auth import resolve_repository_name, resolve_authconfig from . import base from .helpers import make_tree -import pytest TEST_CERT_DIR = os.path.join( os.path.dirname(__file__), @@ -192,6 +196,89 @@ class UtilsTest(base.BaseTestCase): local_tempfile.close() return local_tempfile.name + def test_convert_volume_binds_empty(self): + self.assertEqual(convert_volume_binds({}), []) + self.assertEqual(convert_volume_binds([]), []) + + def test_convert_volume_binds_list(self): + data = ['/a:/a:ro', '/b:/c:z'] + self.assertEqual(convert_volume_binds(data), data) + + def test_convert_volume_binds_complete(self): + data = { + '/mnt/vol1': { + 'bind': '/data', + 'mode': 'ro' + } + } + self.assertEqual(convert_volume_binds(data), ['/mnt/vol1:/data:ro']) + + def test_convert_volume_binds_compact(self): + data = { + '/mnt/vol1': '/data' + } + self.assertEqual(convert_volume_binds(data), ['/mnt/vol1:/data:rw']) + + def test_convert_volume_binds_no_mode(self): + data = { + '/mnt/vol1': { + 'bind': '/data' + } + } + self.assertEqual(convert_volume_binds(data), ['/mnt/vol1:/data:rw']) + + def test_convert_volume_binds_unicode_bytes_input(self): + if six.PY2: + expected = [unicode('/mnt/지연:/unicode/박:rw', 'utf-8')] + + data = { + '/mnt/지연': { + 'bind': '/unicode/박', + 'mode': 'rw' + } + } + self.assertEqual( + convert_volume_binds(data), expected + ) + else: + expected = ['/mnt/지연:/unicode/박:rw'] + + data = { + bytes('/mnt/지연', 'utf-8'): { + 'bind': bytes('/unicode/박', 'utf-8'), + 'mode': 'rw' + } + } + self.assertEqual( + convert_volume_binds(data), expected + ) + + def test_convert_volume_binds_unicode_unicode_input(self): + if six.PY2: + expected = [unicode('/mnt/지연:/unicode/박:rw', 'utf-8')] + + data = { + unicode('/mnt/지연', 'utf-8'): { + 'bind': unicode('/unicode/박', 'utf-8'), + 'mode': 'rw' + } + } + self.assertEqual( + convert_volume_binds(data), expected + ) + else: + expected = ['/mnt/지연:/unicode/박:rw'] + + data = { + '/mnt/지연': { + 'bind': '/unicode/박', + 'mode': 'rw' + } + } + self.assertEqual( + convert_volume_binds(data), expected + ) + def test_parse_repository_tag(self): self.assertEqual(parse_repository_tag("root"), ("root", None))
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi coverage==7.2.7 -e git+https://github.com/docker/docker-py.git@5e331a55a8e8e10354693172dce1aa63f58ebe97#egg=docker_py exceptiongroup==1.2.2 importlib-metadata==6.7.0 iniconfig==2.0.0 packaging==24.0 pluggy==1.2.0 pytest==7.4.4 pytest-cov==4.1.0 requests==2.5.3 six==1.17.0 tomli==2.0.1 typing_extensions==4.7.1 websocket-client==0.32.0 zipp==3.15.0
name: docker-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.2.7 - exceptiongroup==1.2.2 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - pytest-cov==4.1.0 - requests==2.5.3 - six==1.17.0 - tomli==2.0.1 - typing-extensions==4.7.1 - websocket-client==0.32.0 - zipp==3.15.0 prefix: /opt/conda/envs/docker-py
[ "tests/utils_test.py::UtilsTest::test_convert_volume_binds_unicode_bytes_input" ]
[]
[ "tests/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/utils_test.py::HostConfigTest::test_create_host_config_no_options", "tests/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/utils_test.py::UlimitTest::test_ulimit_invalid_type", "tests/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/utils_test.py::UtilsTest::test_convert_filters", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_compact", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_complete", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_empty", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_list", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_no_mode", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_unicode_unicode_input", "tests/utils_test.py::UtilsTest::test_parse_bytes", "tests/utils_test.py::UtilsTest::test_parse_env_file_commented_line", "tests/utils_test.py::UtilsTest::test_parse_env_file_invalid_line", "tests/utils_test.py::UtilsTest::test_parse_env_file_proper", "tests/utils_test.py::UtilsTest::test_parse_host", "tests/utils_test.py::UtilsTest::test_parse_host_empty_value", "tests/utils_test.py::UtilsTest::test_parse_repository_tag", "tests/utils_test.py::UtilsTest::test_resolve_authconfig", "tests/utils_test.py::UtilsTest::test_resolve_registry_and_auth", "tests/utils_test.py::UtilsTest::test_resolve_repository_name", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/utils_test.py::PortsTest::test_host_only_with_colon", "tests/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/utils_test.py::PortsTest::test_port_only_with_colon", "tests/utils_test.py::PortsTest::test_split_port_invalid", "tests/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/utils_test.py::ExcludePathsTest::test_directory", "tests/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/utils_test.py::ExcludePathsTest::test_question_mark", "tests/utils_test.py::ExcludePathsTest::test_single_filename", "tests/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception" ]
[]
Apache License 2.0
246
386
[ "docker/utils/utils.py" ]
keleshev__schema-85
29286c1f9cce20cf70f2b15d9247f2ca6ef1d6c9
2015-09-26 00:20:07
eb7670f0f4615195393dc5350d49fa9a33304137
codecov-io: ## [Current coverage][1] is `98.07%` > Merging **#85** into **master** will increase coverage by **+0.05%** as of [`ea3e9e6`][3] ```diff @@ master #85 diff @@ ====================================== Files 1 1 Stmts 152 156 +4 Branches 0 0 Methods 0 0 ====================================== + Hit 149 153 +4 Partial 0 0 Missed 3 3 ``` > Review entire [Coverage Diff][4] as of [`ea3e9e6`][3] [1]: https://codecov.io/github/keleshev/schema?ref=ea3e9e6de11ed22e995df1b30ede806b9912bba5 [2]: https://codecov.io/github/keleshev/schema/features/suggestions?ref=ea3e9e6de11ed22e995df1b30ede806b9912bba5 [3]: https://codecov.io/github/keleshev/schema/commit/ea3e9e6de11ed22e995df1b30ede806b9912bba5 [4]: https://codecov.io/github/keleshev/schema/compare/e94b7144f3016654d1360eb1c070fd2db0d54a43...ea3e9e6de11ed22e995df1b30ede806b9912bba5 > Powered by [Codecov](https://codecov.io). Updated on successful CI builds. sjakobi: Anybody know a better name than `callable_str`? And does that function possibly need `_` as a prefix? skorokithakis: I think that the method does need an underscore as a prefix, it's not meant to be exported by the module. Other than that, I'm ready to merge this. skorokithakis: Oops, looks like there's a merge conflict. Can you resolve that so I can merge this?
diff --git a/schema.py b/schema.py index 1ecf845..d24744d 100644 --- a/schema.py +++ b/schema.py @@ -70,7 +70,7 @@ class Use(object): except SchemaError as x: raise SchemaError([None] + x.autos, [self._error] + x.errors) except BaseException as x: - f = self._callable.__name__ + f = _callable_str(self._callable) raise SchemaError('%s(%r) raised %r' % (f, data, x), self._error) @@ -176,7 +176,7 @@ class Schema(object): raise SchemaError('%r.validate(%r) raised %r' % (s, data, x), self._error) if flavor == CALLABLE: - f = s.__name__ + f = _callable_str(s) try: if s(data): return data @@ -211,3 +211,9 @@ class Optional(Schema): '"%r" is too complex.' % (self._schema,)) self.default = default self.key = self._schema + + +def _callable_str(callable_): + if hasattr(callable_, '__name__'): + return callable_.__name__ + return str(callable_)
doesn't work with operator.methodcaller from operator import methodcaller from schema import Schema f = methodcaller('endswith', '.csv') assert f('test.csv') Schema(f).validate('test.csv') AttributeError: 'operator.methodcaller' object has no attribute '__name__' We can't assume that all callables have a `__name__`, it would seem.
keleshev/schema
diff --git a/test_schema.py b/test_schema.py index ad49343..967dec0 100644 --- a/test_schema.py +++ b/test_schema.py @@ -1,5 +1,6 @@ from __future__ import with_statement from collections import defaultdict, namedtuple +from operator import methodcaller import os from pytest import raises @@ -383,8 +384,18 @@ def test_missing_keys_exception_with_non_str_dict_keys(): try: Schema({1: 'x'}).validate(dict()) except SchemaError as e: - assert (e.args[0] == - "Missing keys: 1") + assert e.args[0] == "Missing keys: 1" + raise + + +def test_issue_56_cant_rely_on_callables_to_have_name(): + s = Schema(methodcaller('endswith', '.csv')) + assert s.validate('test.csv') == 'test.csv' + with SE: + try: + s.validate('test.py') + except SchemaError as e: + assert "operator.methodcaller" in e.args[0] raise
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 -e git+https://github.com/keleshev/schema.git@29286c1f9cce20cf70f2b15d9247f2ca6ef1d6c9#egg=schema tomli==2.2.1
name: schema channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - tomli==2.2.1 prefix: /opt/conda/envs/schema
[ "test_schema.py::test_issue_56_cant_rely_on_callables_to_have_name" ]
[]
[ "test_schema.py::test_schema", "test_schema.py::test_validate_file", "test_schema.py::test_and", "test_schema.py::test_or", "test_schema.py::test_validate_list", "test_schema.py::test_list_tuple_set_frozenset", "test_schema.py::test_strictly", "test_schema.py::test_dict", "test_schema.py::test_dict_keys", "test_schema.py::test_dict_optional_keys", "test_schema.py::test_dict_optional_defaults", "test_schema.py::test_dict_subtypes", "test_schema.py::test_complex", "test_schema.py::test_nice_errors", "test_schema.py::test_use_error_handling", "test_schema.py::test_or_error_handling", "test_schema.py::test_and_error_handling", "test_schema.py::test_schema_error_handling", "test_schema.py::test_use_json", "test_schema.py::test_error_reporting", "test_schema.py::test_schema_repr", "test_schema.py::test_validate_object", "test_schema.py::test_issue_9_prioritized_key_comparison", "test_schema.py::test_issue_9_prioritized_key_comparison_in_dicts", "test_schema.py::test_missing_keys_exception_with_non_str_dict_keys", "test_schema.py::test_exception_handling_with_bad_validators" ]
[]
MIT License
250
308
[ "schema.py" ]
pypa__twine-134
b34f042da78aed22b6e512df61b495638b06ba03
2015-09-27 21:52:01
f487b7da9c42e4932bc33bf10d70cdc59fd16fd5
diff --git a/twine/commands/upload.py b/twine/commands/upload.py index 032cc21..2bd4a52 100644 --- a/twine/commands/upload.py +++ b/twine/commands/upload.py @@ -67,11 +67,13 @@ def upload(dists, repository, sign, identity, username, password, comment, if not sign and identity: raise ValueError("sign must be given along with identity") + dists = find_dists(dists) + # Determine if the user has passed in pre-signed distributions signatures = dict( (os.path.basename(d), d) for d in dists if d.endswith(".asc") ) - dists = [i for i in dists if not i.endswith(".asc")] + uploads = [i for i in dists if not i.endswith(".asc")] config = utils.get_repository_from_config(config_file, repository) @@ -86,24 +88,14 @@ def upload(dists, repository, sign, identity, username, password, comment, repository = Repository(config["repository"], username, password) - uploads = find_dists(dists) - for filename in uploads: package = PackageFile.from_filename(filename, comment) - # Sign the dist if requested - # if sign: - # sign_file(sign_with, filename, identity) - # signed_name = os.path.basename(filename) + ".asc" - signed_name = package.signed_filename + signed_name = package.signed_basefilename if signed_name in signatures: - with open(signatures[signed_name], "rb") as gpg: - package.gpg_signature = (signed_name, gpg.read()) - # data["gpg_signature"] = (signed_name, gpg.read()) + package.add_gpg_signature(signatures[signed_name], signed_name) elif sign: package.sign(sign_with, identity) - # with open(filename + ".asc", "rb") as gpg: - # data["gpg_signature"] = (signed_name, gpg.read()) resp = repository.upload(package) diff --git a/twine/package.py b/twine/package.py index e80116a..e062c71 100644 --- a/twine/package.py +++ b/twine/package.py @@ -49,6 +49,7 @@ class PackageFile(object): self.filetype = filetype self.safe_name = pkg_resources.safe_name(metadata.name) self.signed_filename = self.filename + '.asc' + self.signed_basefilename = self.basefilename + '.asc' self.gpg_signature = None md5_hash = hashlib.md5() @@ -141,6 +142,13 @@ class PackageFile(object): return data + def add_gpg_signature(self, signature_filepath, signature_filename): + if self.gpg_signature is not None: + raise ValueError('GPG Signature can only be added once') + + with open(signature_filepath, "rb") as gpg: + self.gpg_signature = (signature_filename, gpg.read()) + def sign(self, sign_with, identity): print("Signing {0}".format(self.basefilename)) gpg_args = (sign_with, "--detach-sign") @@ -149,5 +157,4 @@ class PackageFile(object): gpg_args += ("-a", self.filename) subprocess.check_call(gpg_args) - with open(self.signed_filename, "rb") as gpg: - self.pg_signature = (self.signed_filename, gpg.read()) + self.add_gpg_signature(self.signed_filename, self.signed_basefilename)
"twine upload" usually fails to upload .asc files On the most recent Foolscap release, I signed the sdist tarballs as usual, and tried to use twine to upload everything: ``` % python setup.py sdist --formats=zip,gztar bdist_wheel % ls dist foolscap-0.9.1-py2-none-any.whl foolscap-0.9.1.tar.gz foolscap-0.9.1.zip % (gpg sign them all) % ls dist foolscap-0.9.1-py2-none-any.whl foolscap-0.9.1.tar.gz foolscap-0.9.1.zip foolscap-0.9.1-py2-none-any.whl.asc foolscap-0.9.1.tar.gz.asc foolscap-0.9.1.zip.asc % python setup.py register % twine upload dist/* ``` Twine uploaded the tar/zip/whl files, but ignored the .asc signatures, and the resulting [pypi page](https://pypi.python.org/pypi/foolscap/0.9.1) doesn't show them either. After some digging, I found that `twine/upload.py upload()` will only use pre-signed .asc files if the command was run like `cd dist; twine upload *`. It won't use them if it was run as `cd dist; twine upload ./*` or `twine upload dist/*`. The problem seems to be that the `signatures` dictionary is indexed by the basename of the signature files, while the lookup key is using the full (original) filename of the tarball/etc with ".asc" appended. I think it might be simpler and safer to have the code just check for a neighboring .asc file inside the upload loop, something like: ```python for filename in uploads: package = PackageFile.from_filename(filename, comment) maybe_sig = package.signed_filename + ".asc" if os.path.exists(maybe_sig): package.gpg_signature = (os.path.basename(maybe_sig), sigdata) ... ``` I'll write up a patch for this. I started to look for a way of adding a test, but the code that looks for signatures happens deep enough in `upload()` that it'd need a oversized mock "Repository" class to exercise the .asc check without actually uploading anything. I'm not sure what the best way to approach the test would be.
pypa/twine
diff --git a/tests/test_package.py b/tests/test_package.py index fcc827a..d28eec1 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -55,3 +55,18 @@ def test_sign_file_with_identity(monkeypatch): pass args = ('gpg', '--detach-sign', '--local-user', 'identity', '-a', filename) assert replaced_check_call.calls == [pretend.call(args)] + + +def test_package_signed_name_is_correct(): + filename = 'tests/fixtures/deprecated-pypirc' + + pkg = package.PackageFile( + filename=filename, + comment=None, + metadata=pretend.stub(name="deprecated-pypirc"), + python_version=None, + filetype=None + ) + + assert pkg.signed_basefilename == "deprecated-pypirc.asc" + assert pkg.signed_filename == (filename + '.asc') diff --git a/tests/test_upload.py b/tests/test_upload.py index b40660f..7f99510 100644 --- a/tests/test_upload.py +++ b/tests/test_upload.py @@ -66,6 +66,7 @@ def test_find_dists_handles_real_files(): def test_get_config_old_format(tmpdir): pypirc = os.path.join(str(tmpdir), ".pypirc") + dists = ["tests/fixtures/twine-1.5.0-py2.py3-none-any.whl"] with open(pypirc, "w") as fp: fp.write(textwrap.dedent(""" @@ -75,7 +76,7 @@ def test_get_config_old_format(tmpdir): """)) try: - upload.upload(dists="foo", repository="pypi", sign=None, identity=None, + upload.upload(dists=dists, repository="pypi", sign=None, identity=None, username=None, password=None, comment=None, sign_with=None, config_file=pypirc, skip_existing=False) except KeyError as err:
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 2 }
1.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "coverage", "pretend", "flake8" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work flake8==7.2.0 idna==3.10 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mccabe==0.7.0 packaging @ file:///croot/packaging_1734472117206/work pkginfo==1.12.1.2 pluggy @ file:///croot/pluggy_1733169602837/work pretend==1.0.9 pycodestyle==2.13.0 pyflakes==3.3.1 pytest @ file:///croot/pytest_1738938843180/work requests==2.32.3 requests-toolbelt==1.0.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work -e git+https://github.com/pypa/twine.git@b34f042da78aed22b6e512df61b495638b06ba03#egg=twine urllib3==2.3.0
name: twine channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - flake8==7.2.0 - idna==3.10 - mccabe==0.7.0 - pkginfo==1.12.1.2 - pretend==1.0.9 - pycodestyle==2.13.0 - pyflakes==3.3.1 - requests==2.32.3 - requests-toolbelt==1.0.0 - urllib3==2.3.0 prefix: /opt/conda/envs/twine
[ "tests/test_package.py::test_package_signed_name_is_correct" ]
[]
[ "tests/test_package.py::test_sign_file", "tests/test_package.py::test_sign_file_with_identity", "tests/test_upload.py::test_ensure_wheel_files_uploaded_first", "tests/test_upload.py::test_ensure_if_no_wheel_files", "tests/test_upload.py::test_find_dists_expands_globs", "tests/test_upload.py::test_find_dists_errors_on_invalid_globs", "tests/test_upload.py::test_find_dists_handles_real_files", "tests/test_upload.py::test_get_config_old_format", "tests/test_upload.py::test_skip_existing_skips_files_already_on_PyPI", "tests/test_upload.py::test_skip_upload_respects_skip_existing" ]
[]
Apache License 2.0
253
834
[ "twine/commands/upload.py", "twine/package.py" ]
docker__docker-py-806
f479720d517a7db7f886916190b3032d29d18f10
2015-10-09 19:03:05
f479720d517a7db7f886916190b3032d29d18f10
dnephin: some CI failures, otherwise looks good
diff --git a/docker/auth/auth.py b/docker/auth/auth.py index 366bc67e..1ee9f812 100644 --- a/docker/auth/auth.py +++ b/docker/auth/auth.py @@ -102,7 +102,7 @@ def decode_auth(auth): def encode_header(auth): auth_json = json.dumps(auth).encode('ascii') - return base64.b64encode(auth_json) + return base64.urlsafe_b64encode(auth_json) def parse_auth(entries):
Auth fails with long passwords See https://github.com/docker/docker/issues/16840 docker-py is encoding `X-Registry-Auth` with regular base64 and not the url safe version of base64 that jwt tokens use.
docker/docker-py
diff --git a/tests/utils_test.py b/tests/utils_test.py index b1adde26..04183f9f 100644 --- a/tests/utils_test.py +++ b/tests/utils_test.py @@ -19,7 +19,9 @@ from docker.utils import ( exclude_paths, convert_volume_binds, decode_json_header ) from docker.utils.ports import build_port_bindings, split_port -from docker.auth import resolve_repository_name, resolve_authconfig +from docker.auth import ( + resolve_repository_name, resolve_authconfig, encode_header +) from . import base from .helpers import make_tree @@ -376,12 +378,21 @@ class UtilsTest(base.BaseTestCase): obj = {'a': 'b', 'c': 1} data = None if six.PY3: - data = base64.b64encode(bytes(json.dumps(obj), 'utf-8')) + data = base64.urlsafe_b64encode(bytes(json.dumps(obj), 'utf-8')) else: - data = base64.b64encode(json.dumps(obj)) + data = base64.urlsafe_b64encode(json.dumps(obj)) decoded_data = decode_json_header(data) self.assertEqual(obj, decoded_data) + def test_803_urlsafe_encode(self): + auth_data = { + 'username': 'root', + 'password': 'GR?XGR?XGR?XGR?X' + } + encoded = encode_header(auth_data) + assert b'/' not in encoded + assert b'_' in encoded + def test_resolve_repository_name(self): # docker hub library image self.assertEqual(
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi coverage==7.2.7 -e git+https://github.com/docker/docker-py.git@f479720d517a7db7f886916190b3032d29d18f10#egg=docker_py exceptiongroup==1.2.2 importlib-metadata==6.7.0 iniconfig==2.0.0 packaging==24.0 pluggy==1.2.0 pytest==7.4.4 pytest-cov==4.1.0 requests==2.5.3 six==1.17.0 tomli==2.0.1 typing_extensions==4.7.1 websocket-client==0.32.0 zipp==3.15.0
name: docker-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.2.7 - exceptiongroup==1.2.2 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - pytest-cov==4.1.0 - requests==2.5.3 - six==1.17.0 - tomli==2.0.1 - typing-extensions==4.7.1 - websocket-client==0.32.0 - zipp==3.15.0 prefix: /opt/conda/envs/docker-py
[ "tests/utils_test.py::UtilsTest::test_803_urlsafe_encode" ]
[]
[ "tests/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/utils_test.py::HostConfigTest::test_create_host_config_no_options", "tests/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/utils_test.py::UlimitTest::test_ulimit_invalid_type", "tests/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/utils_test.py::UtilsTest::test_convert_filters", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_compact", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_complete", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_empty", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_list", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_no_mode", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_unicode_bytes_input", "tests/utils_test.py::UtilsTest::test_convert_volume_binds_unicode_unicode_input", "tests/utils_test.py::UtilsTest::test_decode_json_header", "tests/utils_test.py::UtilsTest::test_parse_bytes", "tests/utils_test.py::UtilsTest::test_parse_env_file_commented_line", "tests/utils_test.py::UtilsTest::test_parse_env_file_invalid_line", "tests/utils_test.py::UtilsTest::test_parse_env_file_proper", "tests/utils_test.py::UtilsTest::test_parse_host", "tests/utils_test.py::UtilsTest::test_parse_host_empty_value", "tests/utils_test.py::UtilsTest::test_parse_repository_tag", "tests/utils_test.py::UtilsTest::test_resolve_authconfig", "tests/utils_test.py::UtilsTest::test_resolve_registry_and_auth", "tests/utils_test.py::UtilsTest::test_resolve_repository_name", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/utils_test.py::PortsTest::test_host_only_with_colon", "tests/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/utils_test.py::PortsTest::test_port_only_with_colon", "tests/utils_test.py::PortsTest::test_split_port_invalid", "tests/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/utils_test.py::ExcludePathsTest::test_directory", "tests/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/utils_test.py::ExcludePathsTest::test_question_mark", "tests/utils_test.py::ExcludePathsTest::test_single_filename", "tests/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception" ]
[]
Apache License 2.0
264
124
[ "docker/auth/auth.py" ]
pystorm__pystorm-14
111356b63c7a44261fb4d0c827745e793ca8717e
2015-10-27 16:46:13
eaa0bf28f57e43950379dfaabac7174ad5db4740
diff --git a/pystorm/component.py b/pystorm/component.py index 23d82e8..80c5abf 100644 --- a/pystorm/component.py +++ b/pystorm/component.py @@ -3,14 +3,17 @@ from __future__ import absolute_import, print_function, unicode_literals import logging import os +import re import signal import sys -from collections import deque, namedtuple +from collections import defaultdict, deque, namedtuple from logging.handlers import RotatingFileHandler from os.path import join from threading import RLock from traceback import format_exc +from six import iteritems + from .exceptions import StormWentAwayError from .serializers.msgpack_serializer import MsgpackSerializer from .serializers.json_serializer import JSONSerializer @@ -36,6 +39,9 @@ _PYTHON_LOG_LEVELS = {'critical': logging.CRITICAL, 'debug': logging.DEBUG, 'trace': logging.DEBUG} _SERIALIZERS = {"json": JSONSerializer, "msgpack": MsgpackSerializer} +# Convert names to valid Python identifiers by replacing non-word characters +# whitespace and leading digits with underscores. +_IDENTIFIER_RE = re.compile(r'\W|^(?=\d)') log = logging.getLogger(__name__) @@ -121,7 +127,7 @@ Tuple = namedtuple('Tuple', 'id component stream task values') :ivar task: the task the Tuple was generated from. :type task: int :ivar values: the payload of the Tuple where data is stored. -:type values: list +:type values: tuple (or namedtuple for Storm 0.10.0+) """ @@ -177,6 +183,7 @@ class Component(object): self.context = None self.pid = os.getpid() self.logger = None + self._source_tuple_types = defaultdict(dict) # pending commands/Tuples we read while trying to read task IDs self._pending_commands = deque() # pending task IDs we read while trying to read commands/Tuples @@ -207,6 +214,15 @@ class Component(object): self.topology_name = storm_conf.get('topology.name', '') self.task_id = context.get('taskid', '') self.component_name = context.get('componentid') + # source->stream->fields requires Storm 0.10.0 or later + source_stream_fields = context.get('source->stream->fields', {}) + for source, stream_fields in iteritems(source_stream_fields): + for stream, fields in iteritems(stream_fields): + type_name = (_IDENTIFIER_RE.sub('_', source.title()) + + _IDENTIFIER_RE.sub('_', stream.title()) + + 'Tuple') + self._source_tuple_types[source][stream] = namedtuple(type_name, + fields) # If using Storm before 0.10.0 componentid is not available if self.component_name is None: self.component_name = context.get('task->component', {})\ @@ -280,8 +296,12 @@ class Component(object): def read_tuple(self): cmd = self.read_command() - return Tuple(cmd['id'], cmd['comp'], cmd['stream'], cmd['task'], - cmd['tuple']) + source = cmd['comp'] + stream = cmd['stream'] + values = cmd['tuple'] + val_type = self._source_tuple_types[source].get(stream) + return Tuple(cmd['id'], source, stream, cmd['task'], + tuple(values) if val_type is None else val_type(*values)) def read_handshake(self): """Read and process an initial handshake message from Storm."""
Have Tuple.values be a namedtuple so fields can be accessed by name _From @dan-blanchard on April 15, 2015 13:57_ This was brought up as part of our discussion of the rejected #120. What we want to do is: - [x] Submit a PR to Storm that serializes [`TopologyContext.componentToStreamToFields`](https://github.com/apache/storm/blob/master/storm-core/src/jvm/backtype/storm/task/TopologyContext.java#L61) and sends that along as part of Multi-Lang handshake. - [x] Add a `_stream_fields` dictionary attribute to the `Component` class that maps from streams to `namedtuple` types representing the names of fields/values in the tuple. This should get created at handshake time based on the contents of `componentToStreamToFields`. - [x] Modify `Component.read_tuple()` to set `Tuple.values` to be a `namedtuple` of the appropriate type for the current stream (by looking it up in `Component._stream_fields`. This will allow users to get values out of their tuples by accessing values directly by name (`word = tup.values.word`), or by unpacking (`word, count = tup.values`). _Copied from original issue: Parsely/streamparse#127_
pystorm/pystorm
diff --git a/test/pystorm/test_bolt.py b/test/pystorm/test_bolt.py index f9586c3..80cf5c8 100644 --- a/test/pystorm/test_bolt.py +++ b/test/pystorm/test_bolt.py @@ -34,7 +34,7 @@ class BoltTests(unittest.TestCase): tup_json = "{}\nend\n".format(json.dumps(self.tup_dict)).encode('utf-8') self.tup = Tuple(self.tup_dict['id'], self.tup_dict['comp'], self.tup_dict['stream'], self.tup_dict['task'], - self.tup_dict['tuple'],) + tuple(self.tup_dict['tuple']),) self.bolt = Bolt(input_stream=BytesIO(tup_json), output_stream=BytesIO()) self.bolt.initialize({}, {}) @@ -190,7 +190,7 @@ class BoltTests(unittest.TestCase): def test_heartbeat_response(self, send_message_mock, read_tuple_mock): # Make sure we send sync for heartbeats read_tuple_mock.return_value = Tuple(id='foo', task=-1, - stream='__heartbeat', values=[], + stream='__heartbeat', values=(), component='__system') self.bolt._run() send_message_mock.assert_called_with(self.bolt, {'command': 'sync'}) @@ -201,7 +201,7 @@ class BoltTests(unittest.TestCase): # Make sure we send sync for heartbeats read_tuple_mock.return_value = Tuple(id=None, task=-1, component='__system', - stream='__tick', values=[50]) + stream='__tick', values=(50,)) self.bolt._run() process_tick_mock.assert_called_with(self.bolt, read_tuple_mock.return_value) @@ -239,8 +239,8 @@ class BatchingBoltTests(unittest.TestCase): tups_json = '\nend\n'.join([json.dumps(tup_dict) for tup_dict in self.tup_dicts] + ['']) self.tups = [Tuple(tup_dict['id'], tup_dict['comp'], tup_dict['stream'], - tup_dict['task'], tup_dict['tuple']) for tup_dict in - self.tup_dicts] + tup_dict['task'], tuple(tup_dict['tuple'])) + for tup_dict in self.tup_dicts] self.nontick_tups = [tup for tup in self.tups if tup.stream != '__tick'] self.bolt = BatchingBolt(input_stream=BytesIO(tups_json.encode('utf-8')), output_stream=BytesIO()) @@ -364,7 +364,7 @@ class BatchingBoltTests(unittest.TestCase): def test_heartbeat_response(self, send_message_mock, read_tuple_mock): # Make sure we send sync for heartbeats read_tuple_mock.return_value = Tuple(id='foo', task=-1, - stream='__heartbeat', values=[], + stream='__heartbeat', values=(), component='__system') self.bolt._run() send_message_mock.assert_called_with(self.bolt, {'command': 'sync'}) @@ -375,7 +375,7 @@ class BatchingBoltTests(unittest.TestCase): # Make sure we send sync for heartbeats read_tuple_mock.return_value = Tuple(id=None, task=-1, component='__system', - stream='__tick', values=[50]) + stream='__tick', values=(50,)) self.bolt._run() process_tick_mock.assert_called_with(self.bolt, read_tuple_mock.return_value) diff --git a/test/pystorm/test_component.py b/test/pystorm/test_component.py index f7228f4..c508ae1 100644 --- a/test/pystorm/test_component.py +++ b/test/pystorm/test_component.py @@ -7,6 +7,7 @@ from __future__ import absolute_import, print_function, unicode_literals import logging import os import unittest +from collections import namedtuple from io import BytesIO import simplejson as json @@ -24,49 +25,48 @@ log = logging.getLogger(__name__) class ComponentTests(unittest.TestCase): - - def test_read_handshake(self): - handshake_dict = { - "conf": { - "topology.message.timeout.secs": 3, - "topology.tick.tuple.freq.secs": 1, - "topology.debug": True - }, - "pidDir": ".", - "context": { - "task->component": { - "1": "example-spout", - "2": "__acker", - "3": "example-bolt1", - "4": "example-bolt2" - }, - "taskid": 3, - # Everything below this line is only available in Storm 0.10.0+ - "componentid": "example-bolt1", - "stream->target->grouping": { - "default": { - "example-bolt2": { - "type": "SHUFFLE" - } - } - }, - "streams": ["default"], - "stream->outputfields": {"default": ["word"]}, - "source->stream->grouping": { - "example-spout": { - "default": { - "type": "FIELDS", - "fields": ["word"] - } - } - }, - "source->stream->fields": { - "example-spout": { - "default": ["word"] - } + conf = {"topology.message.timeout.secs": 3, + "topology.tick.tuple.freq.secs": 1, + "topology.debug": True, + "topology.name": "foo"} + context = { + "task->component": { + "1": "example-spout", + "2": "__acker", + "3": "example-bolt1", + "4": "example-bolt2" + }, + "taskid": 3, + # Everything below this line is only available in Storm 0.11.0+ + "componentid": "example-bolt1", + "stream->target->grouping": { + "default": { + "example-bolt2": { + "type": "SHUFFLE" + } + } + }, + "streams": ["default"], + "stream->outputfields": {"default": ["word"]}, + "source->stream->grouping": { + "example-spout": { + "default": { + "type": "FIELDS", + "fields": ["word"] } } + }, + "source->stream->fields": { + "example-spout": { + "default": ["sentence", "word", "number"] + } } + } + + def test_read_handshake(self): + handshake_dict = {"conf": self.conf, + "pidDir": ".", + "context": self.context} pid_dir = handshake_dict['pidDir'] expected_conf = handshake_dict['conf'] expected_context = handshake_dict['context'] @@ -84,52 +84,18 @@ class ComponentTests(unittest.TestCase): component.serializer.output_stream.buffer.getvalue()) def test_setup_component(self): - conf = {"topology.message.timeout.secs": 3, - "topology.tick.tuple.freq.secs": 1, - "topology.debug": True, - "topology.name": "foo"} - context = { - "task->component": { - "1": "example-spout", - "2": "__acker", - "3": "example-bolt1", - "4": "example-bolt2" - }, - "taskid": 3, - # Everything below this line is only available in Storm 0.11.0+ - "componentid": "example-bolt1", - "stream->target->grouping": { - "default": { - "example-bolt2": { - "type": "SHUFFLE" - } - } - }, - "streams": ["default"], - "stream->outputfields": {"default": ["word"]}, - "source->stream->grouping": { - "example-spout": { - "default": { - "type": "FIELDS", - "fields": ["word"] - } - } - }, - "source->stream->fields": { - "example-spout": { - "default": ["word"] - } - } - } + conf = self.conf component = Component(input_stream=BytesIO(), output_stream=BytesIO()) - component._setup_component(conf, context) + component._setup_component(conf, self.context) + self.assertEqual(component._source_tuple_types['example-spout']['default'].__name__, + 'Example_SpoutDefaultTuple') self.assertEqual(component.topology_name, conf['topology.name']) - self.assertEqual(component.task_id, context['taskid']) + self.assertEqual(component.task_id, self.context['taskid']) self.assertEqual(component.component_name, - context['task->component'][str(context['taskid'])]) + self.context['task->component'][str(self.context['taskid'])]) self.assertEqual(component.storm_conf, conf) - self.assertEqual(component.context, context) + self.assertEqual(component.context, self.context) def test_read_message(self): inputs = [# Task IDs @@ -259,7 +225,7 @@ class ComponentTests(unittest.TestCase): for msg in inputs[::2]: output = json.loads(msg) output['component'] = output['comp'] - output['values'] = output['tuple'] + output['values'] = tuple(output['tuple']) del output['comp'] del output['tuple'] outputs.append(Tuple(**output)) @@ -272,6 +238,38 @@ class ComponentTests(unittest.TestCase): tup = component.read_tuple() self.assertEqual(output, tup) + def test_read_tuple_named_fields(self): + # This is only valid for bolts, so we only need to test with task IDs + # and Tuples + inputs = [('{ "id": "-6955786537413359385", "comp": "example-spout", ' + '"stream": "default", "task": 9, "tuple": ["snow white and ' + 'the seven dwarfs", "field2", 3]}\n'), 'end\n'] + + component = Component(input_stream=BytesIO(''.join(inputs).encode('utf-8')), + output_stream=BytesIO()) + component._setup_component(self.conf, self.context) + + Example_SpoutDefaultTuple = namedtuple('Example_SpoutDefaultTuple', + field_names=['sentence', 'word', + 'number']) + + outputs = [] + for msg in inputs[::2]: + output = json.loads(msg) + output['component'] = output['comp'] + output['values'] = Example_SpoutDefaultTuple(*output['tuple']) + del output['comp'] + del output['tuple'] + outputs.append(Tuple(**output)) + + for output in outputs: + log.info('Checking Tuple for %r', output) + tup = component.read_tuple() + self.assertEqual(output.values.sentence, tup.values.sentence) + self.assertEqual(output.values.word, tup.values.word) + self.assertEqual(output.values.number, tup.values.number) + self.assertEqual(output, tup) + def test_send_message(self): component = Component(input_stream=BytesIO(), output_stream=BytesIO()) inputs = [{"command": "emit", "id": 4, "stream": "", "task": 9,
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 importlib-metadata==4.8.3 iniconfig==1.1.1 mock==5.2.0 msgpack-python==0.5.6 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 -e git+https://github.com/pystorm/pystorm.git@111356b63c7a44261fb4d0c827745e793ca8717e#egg=pystorm pytest==7.0.1 simplejson==3.20.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: pystorm channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - mock==5.2.0 - msgpack-python==0.5.6 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - simplejson==3.20.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/pystorm
[ "test/pystorm/test_bolt.py::BoltTests::test_auto_ack_on", "test/pystorm/test_bolt.py::BoltTests::test_run", "test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_ack_off", "test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_ack_on", "test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_on", "test/pystorm/test_bolt.py::BatchingBoltTests::test_batching", "test/pystorm/test_bolt.py::BatchingBoltTests::test_group_key", "test/pystorm/test_component.py::ComponentTests::test_read_tuple", "test/pystorm/test_component.py::ComponentTests::test_read_tuple_named_fields", "test/pystorm/test_component.py::ComponentTests::test_setup_component" ]
[]
[ "test/pystorm/test_bolt.py::BoltTests::test_ack_id", "test/pystorm/test_bolt.py::BoltTests::test_ack_tuple", "test/pystorm/test_bolt.py::BoltTests::test_auto_ack_off", "test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_off", "test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_on", "test/pystorm/test_bolt.py::BoltTests::test_auto_anchor_override", "test/pystorm/test_bolt.py::BoltTests::test_auto_fail_off", "test/pystorm/test_bolt.py::BoltTests::test_auto_fail_on", "test/pystorm/test_bolt.py::BoltTests::test_emit_basic", "test/pystorm/test_bolt.py::BoltTests::test_emit_direct", "test/pystorm/test_bolt.py::BoltTests::test_emit_stream_anchors", "test/pystorm/test_bolt.py::BoltTests::test_fail_id", "test/pystorm/test_bolt.py::BoltTests::test_fail_tuple", "test/pystorm/test_bolt.py::BoltTests::test_heartbeat_response", "test/pystorm/test_bolt.py::BoltTests::test_process_tick", "test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_off", "test/pystorm/test_bolt.py::BatchingBoltTests::test_auto_fail_partial", "test/pystorm/test_bolt.py::BatchingBoltTests::test_heartbeat_response", "test/pystorm/test_bolt.py::BatchingBoltTests::test_process_tick", "test/pystorm/test_component.py::ComponentTests::test_log", "test/pystorm/test_component.py::ComponentTests::test_read_command", "test/pystorm/test_component.py::ComponentTests::test_read_handshake", "test/pystorm/test_component.py::ComponentTests::test_read_message", "test/pystorm/test_component.py::ComponentTests::test_read_message_unicode", "test/pystorm/test_component.py::ComponentTests::test_read_split_message", "test/pystorm/test_component.py::ComponentTests::test_read_task_ids", "test/pystorm/test_component.py::ComponentTests::test_send_message", "test/pystorm/test_component.py::ComponentTests::test_send_message_unicode" ]
[]
Apache License 2.0
276
821
[ "pystorm/component.py" ]
scrapy__scrapy-1563
dd9f777ba725d7a7dbb192302cc52a120005ad64
2015-10-29 06:21:42
6aa85aee2a274393307ac3e777180fcbdbdc9848
diff --git a/scrapy/http/request/form.py b/scrapy/http/request/form.py index a12a2fd07..4a9bd732e 100644 --- a/scrapy/http/request/form.py +++ b/scrapy/http/request/form.py @@ -11,6 +11,7 @@ from parsel.selector import create_root_node import six from scrapy.http.request import Request from scrapy.utils.python import to_bytes, is_listlike +from scrapy.utils.response import get_base_url class FormRequest(Request): @@ -44,7 +45,7 @@ class FormRequest(Request): def _get_form_url(form, url): if url is None: - return form.action or form.base_url + return urljoin(form.base_url, form.action) return urljoin(form.base_url, url) @@ -58,7 +59,7 @@ def _urlencode(seq, enc): def _get_form(response, formname, formid, formnumber, formxpath): """Find the form element """ text = response.body_as_unicode() - root = create_root_node(text, lxml.html.HTMLParser, base_url=response.url) + root = create_root_node(text, lxml.html.HTMLParser, base_url=get_base_url(response)) forms = root.xpath('//form') if not forms: raise ValueError("No <form> element found in %s" % response)
[Bug] Incorrectly picked URL in `scrapy.http.FormRequest.from_response` when there is a `<base>` tag ## Issue Description Incorrectly picked URL in `scrapy.http.FormRequest.from_response` when there is a `<base>` tag. ## How to Reproduce the Issue & Version Used ``` [pengyu@GLaDOS tmp]$ python2 Python 2.7.10 (default, Sep 7 2015, 13:51:49) [GCC 5.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import scrapy >>> scrapy.__version__ u'1.0.3' >>> html_body = ''' ... <html> ... <head> ... <base href="http://b.com/"> ... </head> ... <body> ... <form action="test_form"> ... </form> ... </body> ... </html> ... ''' >>> response = scrapy.http.TextResponse(url='http://a.com/', body=html_body) >>> request = scrapy.http.FormRequest.from_response(response) >>> request.url 'http://a.com/test_form' ``` ## Expected Result `request.url` shall be `'http://b.com/test_form'` ## Suggested Fix The issue can be fixed by fixing a few lines in `scrapy/http/request/form.py`
scrapy/scrapy
diff --git a/tests/test_http_request.py b/tests/test_http_request.py index ff0941961..60fd855dd 100644 --- a/tests/test_http_request.py +++ b/tests/test_http_request.py @@ -801,6 +801,25 @@ class FormRequestTest(RequestTest): self.assertEqual(fs[b'test2'], [b'val2']) self.assertEqual(fs[b'button1'], [b'']) + def test_html_base_form_action(self): + response = _buildresponse( + """ + <html> + <head> + <base href="http://b.com/"> + </head> + <body> + <form action="test_form"> + </form> + </body> + </html> + """, + url='http://a.com/' + ) + req = self.request_class.from_response(response) + self.assertEqual(req.url, 'http://b.com/test_form') + + def _buildresponse(body, **kwargs): kwargs.setdefault('body', body) kwargs.setdefault('url', 'http://example.com')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio" ], "pre_install": [ "apt-get update", "apt-get install -y gcc libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==25.3.0 Automat==24.8.1 cffi==1.17.1 constantly==23.10.4 coverage==7.8.0 cryptography==44.0.2 cssselect==1.3.0 exceptiongroup==1.2.2 execnet==2.1.1 hyperlink==21.0.0 idna==3.10 incremental==24.7.2 iniconfig==2.1.0 jmespath==1.0.1 lxml==5.3.1 packaging==24.2 parsel==1.10.0 pluggy==1.5.0 pyasn1==0.6.1 pyasn1_modules==0.4.2 pycparser==2.22 PyDispatcher==2.0.7 pyOpenSSL==25.0.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-cov==6.0.0 pytest-mock==3.14.0 pytest-xdist==3.6.1 queuelib==1.7.0 -e git+https://github.com/scrapy/scrapy.git@dd9f777ba725d7a7dbb192302cc52a120005ad64#egg=Scrapy service-identity==24.2.0 six==1.17.0 tomli==2.2.1 Twisted==24.11.0 typing_extensions==4.13.0 w3lib==2.3.1 zope.interface==7.2
name: scrapy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==25.3.0 - automat==24.8.1 - cffi==1.17.1 - constantly==23.10.4 - coverage==7.8.0 - cryptography==44.0.2 - cssselect==1.3.0 - exceptiongroup==1.2.2 - execnet==2.1.1 - hyperlink==21.0.0 - idna==3.10 - incremental==24.7.2 - iniconfig==2.1.0 - jmespath==1.0.1 - lxml==5.3.1 - packaging==24.2 - parsel==1.10.0 - pluggy==1.5.0 - pyasn1==0.6.1 - pyasn1-modules==0.4.2 - pycparser==2.22 - pydispatcher==2.0.7 - pyopenssl==25.0.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - pytest-xdist==3.6.1 - queuelib==1.7.0 - service-identity==24.2.0 - six==1.17.0 - tomli==2.2.1 - twisted==24.11.0 - typing-extensions==4.13.0 - w3lib==2.3.1 - zope-interface==7.2 prefix: /opt/conda/envs/scrapy
[ "tests/test_http_request.py::FormRequestTest::test_html_base_form_action" ]
[ "tests/test_http_request.py::FormRequestTest::test_from_response_button_notype", "tests/test_http_request.py::FormRequestTest::test_from_response_button_novalue", "tests/test_http_request.py::FormRequestTest::test_from_response_button_submit", "tests/test_http_request.py::FormRequestTest::test_from_response_checkbox", "tests/test_http_request.py::FormRequestTest::test_from_response_descendants", "tests/test_http_request.py::FormRequestTest::test_from_response_dont_click", "tests/test_http_request.py::FormRequestTest::test_from_response_dont_submit_image_as_input", "tests/test_http_request.py::FormRequestTest::test_from_response_dont_submit_reset_as_input", "tests/test_http_request.py::FormRequestTest::test_from_response_formid_exists", "tests/test_http_request.py::FormRequestTest::test_from_response_formid_notexist", "tests/test_http_request.py::FormRequestTest::test_from_response_formname_exists", "tests/test_http_request.py::FormRequestTest::test_from_response_formname_notexist", "tests/test_http_request.py::FormRequestTest::test_from_response_formname_notexists_fallback_formid", "tests/test_http_request.py::FormRequestTest::test_from_response_get", "tests/test_http_request.py::FormRequestTest::test_from_response_input_hidden", "tests/test_http_request.py::FormRequestTest::test_from_response_input_text", "tests/test_http_request.py::FormRequestTest::test_from_response_input_textarea", "tests/test_http_request.py::FormRequestTest::test_from_response_invalid_html5", "tests/test_http_request.py::FormRequestTest::test_from_response_multiple_clickdata", "tests/test_http_request.py::FormRequestTest::test_from_response_multiple_forms_clickdata", "tests/test_http_request.py::FormRequestTest::test_from_response_noformname", "tests/test_http_request.py::FormRequestTest::test_from_response_nr_index_clickdata", "tests/test_http_request.py::FormRequestTest::test_from_response_override_clickable", "tests/test_http_request.py::FormRequestTest::test_from_response_override_params", "tests/test_http_request.py::FormRequestTest::test_from_response_post", "tests/test_http_request.py::FormRequestTest::test_from_response_radio", "tests/test_http_request.py::FormRequestTest::test_from_response_select", "tests/test_http_request.py::FormRequestTest::test_from_response_submit_first_clickable", "tests/test_http_request.py::FormRequestTest::test_from_response_submit_not_first_clickable", "tests/test_http_request.py::FormRequestTest::test_from_response_submit_novalue", "tests/test_http_request.py::FormRequestTest::test_from_response_unicode_clickdata", "tests/test_http_request.py::FormRequestTest::test_from_response_xpath" ]
[ "tests/test_http_request.py::RequestTest::test_ajax_url", "tests/test_http_request.py::RequestTest::test_body", "tests/test_http_request.py::RequestTest::test_copy", "tests/test_http_request.py::RequestTest::test_copy_inherited_classes", "tests/test_http_request.py::RequestTest::test_eq", "tests/test_http_request.py::RequestTest::test_headers", "tests/test_http_request.py::RequestTest::test_immutable_attributes", "tests/test_http_request.py::RequestTest::test_init", "tests/test_http_request.py::RequestTest::test_method_always_str", "tests/test_http_request.py::RequestTest::test_replace", "tests/test_http_request.py::RequestTest::test_url", "tests/test_http_request.py::RequestTest::test_url_no_scheme", "tests/test_http_request.py::RequestTest::test_url_quoting", "tests/test_http_request.py::FormRequestTest::test_ajax_url", "tests/test_http_request.py::FormRequestTest::test_body", "tests/test_http_request.py::FormRequestTest::test_copy", "tests/test_http_request.py::FormRequestTest::test_copy_inherited_classes", "tests/test_http_request.py::FormRequestTest::test_custom_encoding", "tests/test_http_request.py::FormRequestTest::test_empty_formdata", "tests/test_http_request.py::FormRequestTest::test_eq", "tests/test_http_request.py::FormRequestTest::test_from_response_ambiguous_clickdata", "tests/test_http_request.py::FormRequestTest::test_from_response_errors_formnumber", "tests/test_http_request.py::FormRequestTest::test_from_response_errors_noform", "tests/test_http_request.py::FormRequestTest::test_from_response_extra_headers", "tests/test_http_request.py::FormRequestTest::test_from_response_formid_errors_formnumber", "tests/test_http_request.py::FormRequestTest::test_from_response_formname_errors_formnumber", "tests/test_http_request.py::FormRequestTest::test_from_response_invalid_nr_index_clickdata", "tests/test_http_request.py::FormRequestTest::test_from_response_non_matching_clickdata", "tests/test_http_request.py::FormRequestTest::test_from_response_override_method", "tests/test_http_request.py::FormRequestTest::test_from_response_override_url", "tests/test_http_request.py::FormRequestTest::test_headers", "tests/test_http_request.py::FormRequestTest::test_immutable_attributes", "tests/test_http_request.py::FormRequestTest::test_init", "tests/test_http_request.py::FormRequestTest::test_method_always_str", "tests/test_http_request.py::FormRequestTest::test_multi_key_values", "tests/test_http_request.py::FormRequestTest::test_replace", "tests/test_http_request.py::FormRequestTest::test_url", "tests/test_http_request.py::FormRequestTest::test_url_no_scheme", "tests/test_http_request.py::FormRequestTest::test_url_quoting", "tests/test_http_request.py::XmlRpcRequestTest::test_ajax_url", "tests/test_http_request.py::XmlRpcRequestTest::test_body", "tests/test_http_request.py::XmlRpcRequestTest::test_copy", "tests/test_http_request.py::XmlRpcRequestTest::test_copy_inherited_classes", "tests/test_http_request.py::XmlRpcRequestTest::test_eq", "tests/test_http_request.py::XmlRpcRequestTest::test_headers", "tests/test_http_request.py::XmlRpcRequestTest::test_immutable_attributes", "tests/test_http_request.py::XmlRpcRequestTest::test_init", "tests/test_http_request.py::XmlRpcRequestTest::test_method_always_str", "tests/test_http_request.py::XmlRpcRequestTest::test_replace", "tests/test_http_request.py::XmlRpcRequestTest::test_url", "tests/test_http_request.py::XmlRpcRequestTest::test_url_no_scheme", "tests/test_http_request.py::XmlRpcRequestTest::test_url_quoting", "tests/test_http_request.py::XmlRpcRequestTest::test_xmlrpc_dumps" ]
[]
BSD 3-Clause "New" or "Revised" License
279
309
[ "scrapy/http/request/form.py" ]
docker__docker-py-832
47ab89ec2bd3bddf1221b856ffbaff333edeabb4
2015-10-29 15:17:54
1ca2bc58f0cf2e2cdda2734395bd3e7ad9b178bf
diff --git a/docker/auth/auth.py b/docker/auth/auth.py index 2ed894ee..416dd7c4 100644 --- a/docker/auth/auth.py +++ b/docker/auth/auth.py @@ -96,7 +96,7 @@ def decode_auth(auth): auth = auth.encode('ascii') s = base64.b64decode(auth) login, pwd = s.split(b':', 1) - return login.decode('ascii'), pwd.decode('ascii') + return login.decode('utf8'), pwd.decode('utf8') def encode_header(auth):
decode_auth function does not handle utf-8 logins or password HI I have found that the function **decode_auth** (line 96, [file](https://github.com/docker/docker-py/blob/master/docker/auth/auth.py)) fails when decoding UTF-8 passwords from the .dockercfg file, and **load_config** returning an empty config. I have checked and docker hub can handle UTF-8 passwords, this code proves that: ```python # coding=utf-8 from docker import Client cred = { 'username': <user>, 'password': <utf-8 password> } c = Client(base_url='unix://var/run/docker.sock') res = c.pull(repository='<private container>', tag='latest', auth_config=cred) print(res) ``` Thank you
docker/docker-py
diff --git a/tests/unit/auth_test.py b/tests/unit/auth_test.py index 9f4d439b..67830381 100644 --- a/tests/unit/auth_test.py +++ b/tests/unit/auth_test.py @@ -316,3 +316,33 @@ class LoadConfigTest(base.Cleanup, base.BaseTestCase): self.assertEqual(cfg['password'], 'izayoi') self.assertEqual(cfg['email'], '[email protected]') self.assertEqual(cfg.get('auth'), None) + + def test_load_config_custom_config_env_utf8(self): + folder = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, folder) + + dockercfg_path = os.path.join(folder, 'config.json') + registry = 'https://your.private.registry.io' + auth_ = base64.b64encode( + b'sakuya\xc3\xa6:izayoi\xc3\xa6').decode('ascii') + config = { + 'auths': { + registry: { + 'auth': '{0}'.format(auth_), + 'email': '[email protected]' + } + } + } + + with open(dockercfg_path, 'w') as f: + json.dump(config, f) + + with mock.patch.dict(os.environ, {'DOCKER_CONFIG': folder}): + cfg = auth.load_config(None) + assert registry in cfg + self.assertNotEqual(cfg[registry], None) + cfg = cfg[registry] + self.assertEqual(cfg['username'], b'sakuya\xc3\xa6'.decode('utf8')) + self.assertEqual(cfg['password'], b'izayoi\xc3\xa6'.decode('utf8')) + self.assertEqual(cfg['email'], '[email protected]') + self.assertEqual(cfg.get('auth'), None)
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-xdist", "pytest-mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi coverage==7.2.7 -e git+https://github.com/docker/docker-py.git@47ab89ec2bd3bddf1221b856ffbaff333edeabb4#egg=docker_py exceptiongroup==1.2.2 execnet==2.0.2 importlib-metadata==6.7.0 iniconfig==2.0.0 packaging==24.0 pluggy==1.2.0 pytest==7.4.4 pytest-cov==4.1.0 pytest-mock==3.11.1 pytest-xdist==3.5.0 requests==2.5.3 six==1.17.0 tomli==2.0.1 typing_extensions==4.7.1 websocket-client==0.32.0 zipp==3.15.0
name: docker-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.2.7 - exceptiongroup==1.2.2 - execnet==2.0.2 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - pytest-cov==4.1.0 - pytest-mock==3.11.1 - pytest-xdist==3.5.0 - requests==2.5.3 - six==1.17.0 - tomli==2.0.1 - typing-extensions==4.7.1 - websocket-client==0.32.0 - zipp==3.15.0 prefix: /opt/conda/envs/docker-py
[ "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env_utf8" ]
[]
[ "tests/unit/auth_test.py::RegressionTest::test_803_urlsafe_encode", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_default_explicit_none", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_default_registry", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_fully_explicit", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_hostname_only", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_legacy_config", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_match", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_trailing_slash", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_wrong_insecure_proto", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_wrong_secure_proto", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_protocol", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_path_wrong_proto", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_hub_image", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_library_image", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_private_registry", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_unauthenticated_registry", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_hub_image", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_hub_library_image", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_localhost", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_localhost_with_username", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_no_dots_but_port", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_no_dots_but_port_and_username", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_private_registry", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_private_registry_with_port", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_repository_name_private_registry_with_username", "tests/unit/auth_test.py::LoadConfigTest::test_load_config", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env_with_auths", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_no_file", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_with_random_name" ]
[]
Apache License 2.0
281
136
[ "docker/auth/auth.py" ]
jonathanj__eliottree-40
4dae7890294edb4d845b00a8bb310bc08c555352
2015-10-30 07:46:22
26748c5e640b6d25d71eefad95920c41dab0f8db
diff --git a/eliottree/_cli.py b/eliottree/_cli.py index 6b0d24e..c333d8c 100644 --- a/eliottree/_cli.py +++ b/eliottree/_cli.py @@ -2,36 +2,20 @@ import argparse import codecs import json import sys -from datetime import datetime from itertools import chain from six import PY3 from six.moves import map -from toolz import compose from eliottree import ( Tree, filter_by_jmespath, filter_by_uuid, render_task_nodes) -def _convert_timestamp(task): - """ - Convert a ``timestamp`` key to a ``datetime``. - """ - task['timestamp'] = datetime.utcfromtimestamp(task['timestamp']) - return task - - -def build_task_nodes(files=None, select=None, task_uuid=None, - human_readable=True): +def build_task_nodes(files=None, select=None, task_uuid=None): """ Build the task nodes given some input data, query criteria and formatting options. """ - def task_transformers(): - if human_readable: - yield _convert_timestamp - yield json.loads - def filter_funcs(): if select is not None: for query in select: @@ -47,8 +31,7 @@ def build_task_nodes(files=None, select=None, task_uuid=None, files = [codecs.getreader('utf-8')(sys.stdin)] tree = Tree() - tasks = map(compose(*task_transformers()), - chain.from_iterable(files)) + tasks = map(json.loads, chain.from_iterable(files)) return tree.nodes(tree.merge_tasks(tasks, filter_funcs())) @@ -65,13 +48,13 @@ def display_task_tree(args): nodes = build_task_nodes( files=args.files, select=args.select, - task_uuid=args.task_uuid, - human_readable=args.human_readable) + task_uuid=args.task_uuid) render_task_nodes( write=write, nodes=nodes, ignored_task_keys=set(args.ignored_task_keys) or None, - field_limit=args.field_limit) + field_limit=args.field_limit, + human_readable=args.human_readable) def main(): diff --git a/eliottree/render.py b/eliottree/render.py index 4876a3e..626683c 100644 --- a/eliottree/render.py +++ b/eliottree/render.py @@ -8,20 +8,42 @@ DEFAULT_IGNORED_KEYS = set([ u'message_type']) -def _format_value(value): +def _format_value_raw(value): """ - Format a value for a task tree. + Format a value. """ if isinstance(value, datetime): if PY3: return value.isoformat(' ') else: return value.isoformat(' ').decode('ascii') - elif isinstance(value, text_type): + return None + + +def _format_value_hint(value, hint): + """ + Format a value given a rendering hint. + """ + if hint == u'timestamp': + return _format_value_raw(datetime.utcfromtimestamp(value)) + return None + + +def _format_value(value, field_hint=None, human_readable=False): + """ + Format a value for a task tree. + """ + if isinstance(value, text_type): return value elif isinstance(value, binary_type): # We guess bytes values are UTF-8. return value.decode('utf-8', 'replace') + if human_readable: + formatted = _format_value_raw(value) + if formatted is None: + formatted = _format_value_hint(value, field_hint) + if formatted is not None: + return formatted result = repr(value) if isinstance(result, binary_type): result = result.decode('utf-8', 'replace') @@ -48,7 +70,7 @@ def _truncate_value(value, limit): return value -def _render_task(write, task, ignored_task_keys, field_limit): +def _render_task(write, task, ignored_task_keys, field_limit, human_readable): """ Render a single ``_TaskNode`` as an ``ASCII`` tree. @@ -64,6 +86,9 @@ def _render_task(write, task, ignored_task_keys, field_limit): :type ignored_task_keys: ``set`` of ``text_type`` :param ignored_task_keys: Set of task key names to ignore. + + :type human_readable: ``bool`` + :param human_readable: Should this be rendered as human-readable? """ _write = _indented_write(write) num_items = len(task) @@ -78,9 +103,12 @@ def _render_task(write, task, ignored_task_keys, field_limit): _render_task(write=_write, task=value, ignored_task_keys={}, - field_limit=field_limit) + field_limit=field_limit, + human_readable=human_readable) else: - _value = _format_value(value) + _value = _format_value(value, + field_hint=key, + human_readable=human_readable) if field_limit: first_line = _truncate_value(_value, field_limit) else: @@ -96,7 +124,8 @@ def _render_task(write, task, ignored_task_keys, field_limit): _write(line + '\n') -def _render_task_node(write, node, field_limit, ignored_task_keys): +def _render_task_node(write, node, field_limit, ignored_task_keys, + human_readable): """ Render a single ``_TaskNode`` as an ``ASCII`` tree. @@ -112,6 +141,9 @@ def _render_task_node(write, node, field_limit, ignored_task_keys): :type ignored_task_keys: ``set`` of ``text_type`` :param ignored_task_keys: Set of task key names to ignore. + + :type human_readable: ``bool`` + :param human_readable: Should this be rendered as human-readable? """ _child_write = _indented_write(write) write( @@ -120,17 +152,20 @@ def _render_task_node(write, node, field_limit, ignored_task_keys): write=_child_write, task=node.task, field_limit=field_limit, - ignored_task_keys=ignored_task_keys) + ignored_task_keys=ignored_task_keys, + human_readable=human_readable) for child in node.children(): _render_task_node( write=_child_write, node=child, field_limit=field_limit, - ignored_task_keys=ignored_task_keys) + ignored_task_keys=ignored_task_keys, + human_readable=human_readable) -def render_task_nodes(write, nodes, field_limit, ignored_task_keys=None): +def render_task_nodes(write, nodes, field_limit, ignored_task_keys=None, + human_readable=False): """ Render a tree of task nodes as an ``ASCII`` tree. @@ -147,6 +182,9 @@ def render_task_nodes(write, nodes, field_limit, ignored_task_keys=None): :type ignored_task_keys: ``set`` of ``text_type`` :param ignored_task_keys: Set of task key names to ignore. + + :type human_readable: ``bool`` + :param human_readable: Should this be rendered as human-readable? """ if ignored_task_keys is None: ignored_task_keys = DEFAULT_IGNORED_KEYS @@ -156,7 +194,8 @@ def render_task_nodes(write, nodes, field_limit, ignored_task_keys=None): write=write, node=node, field_limit=field_limit, - ignored_task_keys=ignored_task_keys) + ignored_task_keys=ignored_task_keys, + human_readable=human_readable) write('\n') diff --git a/setup.py b/setup.py index e54a48d..9767156 100644 --- a/setup.py +++ b/setup.py @@ -29,7 +29,6 @@ setup( install_requires=[ "six>=1.9.0", "jmespath>=0.7.1", - "toolz>=0.7.2", ], extras_require={ "dev": ["pytest>=2.7.1", "testtools>=1.8.0"],
Human-readable values should only be formatted when rendered instead of modifying the tree data The problem with modifying the tree data is that it makes it very difficult to write queries against it if eliot-tree is changing it in undisclosed ways to suit it's renderer.
jonathanj/eliottree
diff --git a/eliottree/test/test_render.py b/eliottree/test/test_render.py index 81d3128..81dea43 100644 --- a/eliottree/test/test_render.py +++ b/eliottree/test/test_render.py @@ -15,14 +15,14 @@ class FormatValueTests(TestCase): """ Tests for ``eliottree.render._format_value``. """ - def test_datetime(self): + def test_datetime_human_readable(self): """ Format ``datetime`` values as ISO8601. """ now = datetime(2015, 6, 6, 22, 57, 12) self.assertThat( - _format_value(now), - Equals('2015-06-06 22:57:12')) + _format_value(now, human_readable=True), + Equals(u'2015-06-06 22:57:12')) def test_unicode(self): """ @@ -59,6 +59,16 @@ class FormatValueTests(TestCase): _format_value({'a': u('\N{SNOWMAN}')}), Equals("{'a': u'\\u2603'}")) + def test_timestamp_hint(self): + """ + Format "timestamp" hinted data as timestamps. + """ + # datetime(2015, 6, 6, 22, 57, 12) + now = 1433631432 + self.assertThat( + _format_value(now, field_hint='timestamp', human_readable=True), + Equals(u'2015-06-06 22:57:12')) + class RenderTaskNodesTests(TestCase): """ @@ -85,6 +95,28 @@ class RenderTaskNodesTests(TestCase): ' +-- app:action@2/succeeded\n' ' `-- timestamp: 1425356800\n\n')) + def test_tasks_human_readable(self): + """ + Render two tasks of sequential levels, by default most standard Eliot + task keys are ignored, values are formatted to be human readable. + """ + fd = StringIO() + tree = Tree() + tree.merge_tasks([action_task, action_task_end]) + render_task_nodes( + write=fd.write, + nodes=tree.nodes(), + field_limit=0, + human_readable=True) + self.assertThat( + fd.getvalue(), + Equals( + 'f3a32bb3-ea6b-457c-aa99-08a3d0491ab4\n' + '+-- app:action@1/started\n' + ' `-- timestamp: 2015-03-03 04:26:40\n' + ' +-- app:action@2/succeeded\n' + ' `-- timestamp: 2015-03-03 04:26:40\n\n')) + def test_multiline_field(self): """ When no field limit is specified for task values, multiple lines are
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 3 }
15.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": null, "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/jonathanj/eliottree.git@4dae7890294edb4d845b00a8bb310bc08c555352#egg=eliot_tree exceptiongroup==1.2.2 iniconfig==2.1.0 jmespath==1.0.1 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 six==1.17.0 testtools==2.7.2 tomli==2.2.1 toolz==1.0.0
name: eliottree channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - jmespath==1.0.1 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - six==1.17.0 - testtools==2.7.2 - tomli==2.2.1 - toolz==1.0.0 prefix: /opt/conda/envs/eliottree
[ "eliottree/test/test_render.py::FormatValueTests::test_datetime_human_readable", "eliottree/test/test_render.py::FormatValueTests::test_timestamp_hint", "eliottree/test/test_render.py::RenderTaskNodesTests::test_tasks_human_readable" ]
[]
[ "eliottree/test/test_render.py::FormatValueTests::test_other", "eliottree/test/test_render.py::FormatValueTests::test_str", "eliottree/test/test_render.py::FormatValueTests::test_unicode", "eliottree/test/test_render.py::RenderTaskNodesTests::test_dict_data", "eliottree/test/test_render.py::RenderTaskNodesTests::test_field_limit", "eliottree/test/test_render.py::RenderTaskNodesTests::test_ignored_keys", "eliottree/test/test_render.py::RenderTaskNodesTests::test_multiline_field", "eliottree/test/test_render.py::RenderTaskNodesTests::test_multiline_field_limit", "eliottree/test/test_render.py::RenderTaskNodesTests::test_nested", "eliottree/test/test_render.py::RenderTaskNodesTests::test_task_data", "eliottree/test/test_render.py::RenderTaskNodesTests::test_tasks" ]
[]
MIT License
282
1,897
[ "eliottree/_cli.py", "eliottree/render.py", "setup.py" ]
sprymix__csscompressor-4
153ab1bb6cd925dc73a314af74db874a3314010f
2015-11-01 06:16:44
bec3e582cb5ab7182a0ca08ba381e491b94ed10c
diff --git a/csscompressor/__init__.py b/csscompressor/__init__.py index 1b41119..1233cd3 100644 --- a/csscompressor/__init__.py +++ b/csscompressor/__init__.py @@ -56,9 +56,12 @@ _space_after_re = re.compile(r'([!{}:;>+\(\[,])\s+') _semi_re = re.compile(r';+}') _zero_fmt_spec_re = re.compile(r'''(\s|:|\(|,)(?:0?\.)?0 - (?:px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|m?s|k?hz)''', + (?:px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|k?hz)''', re.I | re.X) +_zero_req_unit_re = re.compile(r'''(\s|:|\(|,)(?:0?\.)?0 + (m?s)''', re.I | re.X) + _bg_pos_re = re.compile(r'''(background-position|webkit-mask-position|transform-origin| webkit-transform-origin|moz-transform-origin|o-transform-origin| ms-transform-origin):0(;|})''', re.I | re.X) @@ -377,6 +380,9 @@ def _compress(css, max_linelen=0): # Replace 0(px,em,%) with 0. css = _zero_fmt_spec_re.sub(lambda match: match.group(1) + '0', css) + # Replace 0.0(m,ms) or .0(m,ms) with 0(m,ms) + css = _zero_req_unit_re.sub(lambda match: match.group(1) + '0' + match.group(2), css) + # Replace 0 0 0 0; with 0. css = _quad_0_re.sub(r':0\1', css) css = _trip_0_re.sub(r':0\1', css)
Omitting the unit on a time value is invalid Input: `csscompressor.compress("transition: background-color 1s linear 0ms;")` Expected output: `'transition:background-color 1s linear 0ms;'` Actual output: `'transition:background-color 1s linear 0;'` According to the [MDN page on \<time>](https://developer.mozilla.org/en-US/docs/Web/CSS/time), omitting the unit is only valid for \<length>, so when I use csscompressor, the declaration containing the 0ms or 0s is ignored by both Firefox and Chrome. The same case is for `<frequency>`, and probably a few of the other ones, I think. Omitting the unit used to be valid in CSS2, but breaks in CSS3 unfortunately. This is a fairly simple fix (removing the `m?s` from `_zero_fmt_spec_re`), and I'll create a PR and some tests.
sprymix/csscompressor
diff --git a/csscompressor/tests/test_yui.py b/csscompressor/tests/test_yui.py index a0d6715..5d56d24 100644 --- a/csscompressor/tests/test_yui.py +++ b/csscompressor/tests/test_yui.py @@ -1458,7 +1458,7 @@ serve! */""" """ - output = """a{margin:0;_padding-top:0;background-position:0 0;padding:0;transition:opacity 0;transition-delay:0;transform:rotate3d(0,0,0);pitch:0;pitch:0}""" + output = """a{margin:0;_padding-top:0;background-position:0 0;padding:0;transition:opacity 0s;transition-delay:0ms;transform:rotate3d(0,0,0);pitch:0;pitch:0}""" self._test(input, output)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/sprymix/csscompressor.git@153ab1bb6cd925dc73a314af74db874a3314010f#egg=csscompressor exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: csscompressor channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 prefix: /opt/conda/envs/csscompressor
[ "csscompressor/tests/test_yui.py::TestYUI::test_yui_zeros" ]
[]
[ "csscompressor/tests/test_yui.py::TestYUI::test_yui_background_position", "csscompressor/tests/test_yui.py::TestYUI::test_yui_border_none", "csscompressor/tests/test_yui.py::TestYUI::test_yui_box_model_hack", "csscompressor/tests/test_yui.py::TestYUI::test_yui_bug2527974", "csscompressor/tests/test_yui.py::TestYUI::test_yui_bug2527991", "csscompressor/tests/test_yui.py::TestYUI::test_yui_bug2527998", "csscompressor/tests/test_yui.py::TestYUI::test_yui_bug2528034", "csscompressor/tests/test_yui.py::TestYUI::test_yui_charset_media", "csscompressor/tests/test_yui.py::TestYUI::test_yui_color_keyword", "csscompressor/tests/test_yui.py::TestYUI::test_yui_color_simple", "csscompressor/tests/test_yui.py::TestYUI::test_yui_color", "csscompressor/tests/test_yui.py::TestYUI::test_yui_comment", "csscompressor/tests/test_yui.py::TestYUI::test_yui_concat_charset", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_doublequotes", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_eof", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_linebreakindata", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_noquotes", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_singlequotes", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_base64_twourls", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_dbquote_font", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_nonbase64_doublequotes", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_nonbase64_noquotes", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_noquote_multiline_font", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_realdata_doublequotes", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_realdata_noquotes", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_realdata_singlequotes", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_realdata_yuiapp", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_singlequote_font", "csscompressor/tests/test_yui.py::TestYUI::test_yui_decimals", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dollar_header", "csscompressor/tests/test_yui.py::TestYUI::test_yui_font_face", "csscompressor/tests/test_yui.py::TestYUI::test_yui_ie5mac", "csscompressor/tests/test_yui.py::TestYUI::test_yui_lowercasing", "csscompressor/tests/test_yui.py::TestYUI::test_yui_media_empty_class", "csscompressor/tests/test_yui.py::TestYUI::test_yui_media_multi", "csscompressor/tests/test_yui.py::TestYUI::test_yui_media_test", "csscompressor/tests/test_yui.py::TestYUI::test_yui_old_ie_filter_matrix", "csscompressor/tests/test_yui.py::TestYUI::test_yui_opacity_filter", "csscompressor/tests/test_yui.py::TestYUI::test_yui_opera_pixel_ratio", "csscompressor/tests/test_yui.py::TestYUI::test_yui_preserve_case", "csscompressor/tests/test_yui.py::TestYUI::test_yui_preserve_important", "csscompressor/tests/test_yui.py::TestYUI::test_yui_preserve_new_line", "csscompressor/tests/test_yui.py::TestYUI::test_yui_preserve_strings", "csscompressor/tests/test_yui.py::TestYUI::test_yui_pseudo_first", "csscompressor/tests/test_yui.py::TestYUI::test_yui_pseudo", "csscompressor/tests/test_yui.py::TestYUI::test_yui_special_comments", "csscompressor/tests/test_yui.py::TestYUI::test_yui_star_underscore_hacks", "csscompressor/tests/test_yui.py::TestYUI::test_yui_string_in_comment", "csscompressor/tests/test_yui.py::TestYUI::test_yui_webkit_transform", "csscompressor/tests/test_yui.py::TestYUI::test_yui_dataurl_nonbase64_singlequotes" ]
[]
BSD
284
473
[ "csscompressor/__init__.py" ]
falconry__falcon-651
a8154de497b3ec5d6e5579026e74e9073e353819
2015-11-13 11:56:13
b78ffaac7c412d3b3d6cd3c70dd05024d79d2cce
kgriffs: I think this makes sense. It is a breaking change, but one that should be easy for developers to accommodate. A couple testing suggestions inline.
diff --git a/falcon/api.py b/falcon/api.py index cdc2c66..1a6b944 100644 --- a/falcon/api.py +++ b/falcon/api.py @@ -178,7 +178,8 @@ class API(object): # e.g. a 404. responder, params, resource = self._get_responder(req) - self._call_rsrc_mw(middleware_stack, req, resp, resource) + self._call_rsrc_mw(middleware_stack, req, resp, resource, + params) responder(req, resp, **params) self._call_resp_mw(middleware_stack, req, resp, resource) @@ -537,13 +538,13 @@ class API(object): # Put executed component on the stack stack.append(component) # keep track from outside - def _call_rsrc_mw(self, stack, req, resp, resource): + def _call_rsrc_mw(self, stack, req, resp, resource, params): """Run process_resource middleware methods.""" for component in self._middleware: _, process_resource, _ = component if process_resource is not None: - process_resource(req, resp, resource) + process_resource(req, resp, resource, params) def _call_resp_mw(self, stack, req, resp, resource): """Run process_response middleware."""
Pass params to process_resource This is needed for feature parity with global *before* hooks. We can use a shim to avoid breaking existing middleware.
falconry/falcon
diff --git a/tests/test_httpstatus.py b/tests/test_httpstatus.py index 3569e6b..f525be1 100644 --- a/tests/test_httpstatus.py +++ b/tests/test_httpstatus.py @@ -166,7 +166,7 @@ class TestHTTPStatusWithGlobalHooks(testing.TestBase): def test_raise_status_in_process_resource(self): """ Make sure we can raise status from middleware process resource """ class TestMiddleware: - def process_resource(self, req, resp, resource): + def process_resource(self, req, resp, resource, params): raise HTTPStatus(falcon.HTTP_200, headers={"X-Failed": "False"}, body="Pass") diff --git a/tests/test_middlewares.py b/tests/test_middlewares.py index 226e57f..519852a 100644 --- a/tests/test_middlewares.py +++ b/tests/test_middlewares.py @@ -1,3 +1,5 @@ +import json + import falcon import falcon.testing as testing from datetime import datetime @@ -11,7 +13,7 @@ class RequestTimeMiddleware(object): global context context['start_time'] = datetime.utcnow() - def process_resource(self, req, resp, resource): + def process_resource(self, req, resp, resource, params): global context context['mid_time'] = datetime.utcnow() @@ -34,7 +36,7 @@ class ExecutedFirstMiddleware(object): context['executed_methods'].append( '{0}.{1}'.format(self.__class__.__name__, 'process_request')) - def process_resource(self, req, resp, resource): + def process_resource(self, req, resp, resource, params): global context context['executed_methods'].append( '{0}.{1}'.format(self.__class__.__name__, 'process_resource')) @@ -55,9 +57,17 @@ class RemoveBasePathMiddleware(object): req.path = req.path.replace('/base_path', '', 1) +class AccessParamsMiddleware(object): + + def process_resource(self, req, resp, resource, params): + global context + params['added'] = True + context['params'] = params + + class MiddlewareClassResource(object): - def on_get(self, req, resp): + def on_get(self, req, resp, **kwargs): resp.status = falcon.HTTP_200 resp.body = {'status': 'ok'} @@ -368,3 +378,23 @@ class TestRemoveBasePathMiddleware(TestMiddleware): self.assertEqual(self.srmock.status, falcon.HTTP_200) self.simulate_request('/base_pathIncorrect/sub_path') self.assertEqual(self.srmock.status, falcon.HTTP_404) + + +class TestResourceMiddleware(TestMiddleware): + + def test_can_access_resource_params(self): + """Test that params can be accessed from within process_resource""" + global context + + class Resource: + def on_get(self, req, resp, **params): + resp.data = json.dumps(params) + + self.api = falcon.API(middleware=AccessParamsMiddleware()) + self.api.add_route('/path/{id}', Resource()) + resp = self.simulate_request('/path/22') + + self.assertIn('params', context) + self.assertTrue(context['params']) + self.assertEqual(context['params']['id'], '22') + self.assertEqual(json.loads(resp[0]), {"added": True, "id": "22"})
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "coverage", "ddt", "pyyaml", "requests", "testtools", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///croot/attrs_1668696182826/work certifi @ file:///croot/certifi_1671487769961/work/certifi charset-normalizer==3.4.1 coverage==7.2.7 ddt==1.7.2 -e git+https://github.com/falconry/falcon.git@a8154de497b3ec5d6e5579026e74e9073e353819#egg=falcon flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core idna==3.10 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work nose==1.3.7 packaging @ file:///croot/packaging_1671697413597/work pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pytest==7.1.2 python-mimeparse==1.6.0 PyYAML==6.0.1 requests==2.31.0 six==1.17.0 testtools==2.7.1 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work typing_extensions @ file:///croot/typing_extensions_1669924550328/work urllib3==2.0.7 zipp @ file:///croot/zipp_1672387121353/work
name: falcon channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=22.1.0=py37h06a4308_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - flit-core=3.6.0=pyhd3eb1b0_0 - importlib-metadata=4.11.3=py37h06a4308_0 - importlib_metadata=4.11.3=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=22.0=py37h06a4308_0 - pip=22.3.1=py37h06a4308_0 - pluggy=1.0.0=py37h06a4308_1 - py=1.11.0=pyhd3eb1b0_0 - pytest=7.1.2=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py37h06a4308_0 - typing_extensions=4.4.0=py37h06a4308_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zipp=3.11.0=py37h06a4308_0 - zlib=1.2.13=h5eee18b_1 - pip: - charset-normalizer==3.4.1 - coverage==7.2.7 - ddt==1.7.2 - idna==3.10 - nose==1.3.7 - python-mimeparse==1.6.0 - pyyaml==6.0.1 - requests==2.31.0 - six==1.17.0 - testtools==2.7.1 - urllib3==2.0.7 prefix: /opt/conda/envs/falcon
[ "tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_in_process_resource", "tests/test_middlewares.py::TestRequestTimeMiddleware::test_log_get_request", "tests/test_middlewares.py::TestSeveralMiddlewares::test_generate_trans_id_and_time_with_request", "tests/test_middlewares.py::TestSeveralMiddlewares::test_middleware_execution_order", "tests/test_middlewares.py::TestSeveralMiddlewares::test_order_mw_executed_when_exception_in_resp", "tests/test_middlewares.py::TestSeveralMiddlewares::test_order_mw_executed_when_exception_in_rsrc", "tests/test_middlewares.py::TestResourceMiddleware::test_can_access_resource_params" ]
[]
[ "tests/test_httpstatus.py::TestHTTPStatus::test_raise_status_empty_body", "tests/test_httpstatus.py::TestHTTPStatus::test_raise_status_in_before_hook", "tests/test_httpstatus.py::TestHTTPStatus::test_raise_status_in_responder", "tests/test_httpstatus.py::TestHTTPStatus::test_raise_status_runs_after_hooks", "tests/test_httpstatus.py::TestHTTPStatus::test_raise_status_survives_after_hooks", "tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_in_before_hook", "tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_in_process_request", "tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_runs_after_hooks", "tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_runs_process_response", "tests/test_httpstatus.py::TestHTTPStatusWithGlobalHooks::test_raise_status_survives_after_hooks", "tests/test_middlewares.py::TestRequestTimeMiddleware::test_add_invalid_middleware", "tests/test_middlewares.py::TestRequestTimeMiddleware::test_response_middleware_raises_exception", "tests/test_middlewares.py::TestTransactionIdMiddleware::test_generate_trans_id_with_request", "tests/test_middlewares.py::TestSeveralMiddlewares::test_inner_mw_throw_exception", "tests/test_middlewares.py::TestSeveralMiddlewares::test_inner_mw_with_ex_handler_throw_exception", "tests/test_middlewares.py::TestSeveralMiddlewares::test_order_mw_executed_when_exception_in_req", "tests/test_middlewares.py::TestSeveralMiddlewares::test_outer_mw_with_ex_handler_throw_exception", "tests/test_middlewares.py::TestRemoveBasePathMiddleware::test_base_path_is_removed_before_routing" ]
[]
Apache License 2.0
298
326
[ "falcon/api.py" ]
joblib__joblib-277
484405ccea3cbcbd95e3cf241f15bf3eeb1aa8b6
2015-11-23 15:25:34
40341615cc2600675ce7457d9128fb030f6f89fa
diff --git a/joblib/hashing.py b/joblib/hashing.py index f8a9ee6..93bc5e3 100644 --- a/joblib/hashing.py +++ b/joblib/hashing.py @@ -59,7 +59,8 @@ class Hasher(Pickler): try: self.dump(obj) except pickle.PicklingError as e: - warnings.warn('PicklingError while hashing %r: %r' % (obj, e)) + e.args += ('PicklingError while hashing %r: %r' % (obj, e),) + raise dumps = self.stream.getvalue() self._hash.update(dumps) if return_digest:
Surprising behaviour when one of the cached function arguments is not picklable As reported by @arthurmensch. When one of the arguments is not picklable, the cached function result will only depend on the hash of all the arguments before the non picklable one. A simple snippet to show the problem: ```python import joblib mem = joblib.Memory('/tmp/joblib') @mem.cache() def f(a, b): return b non_picklable = lambda: None print(f(non_picklable, 'first')) print(f(non_picklable, 'second')) ``` Output: ``` /home/lesteve/dev/joblib/joblib/hashing.py:62: UserWarning: PicklingError while hashing {'b': 'first', 'a': <function <lambda> at 0x7f400d7ec8c8>}: PicklingError("Can't pickle <function <lambda> at 0x7f400d7ec8c8>: it's not found as __main__.<lambda>",) warnings.warn('PicklingError while hashing %r: %r' % (obj, e)) ________________________________________________________________________________ [Memory] Calling __main__--tmp-test_hash_non_picklable_arguments.f... f(<function <lambda> at 0x7f400d7ec8c8>, 'first') ________________________________________________________________f - 0.0s, 0.0min first /home/lesteve/dev/joblib/joblib/hashing.py:62: UserWarning: PicklingError while hashing {'b': 'second', 'a': <function <lambda> at 0x7f400d7ec8c8>}: PicklingError("Can't pickle <function <lambda> at 0x7f400d7ec8c8>: it's not found as __main__.<lambda>",) warnings.warn('PicklingError while hashing %r: %r' % (obj, e)) first ``` Why not just raise an exception in this case rather than returning a result with a warning that is almost certain to be ignored by the user ? @GaelVaroquaux @ogrisel.
joblib/joblib
diff --git a/joblib/test/test_hashing.py b/joblib/test/test_hashing.py index f0ce0eb..88407d0 100644 --- a/joblib/test/test_hashing.py +++ b/joblib/test/test_hashing.py @@ -23,6 +23,7 @@ from nose.tools import assert_equal from joblib.hashing import hash, PY3 from joblib.func_inspect import filter_args from joblib.memory import Memory +from joblib.testing import assert_raises_regex from joblib.test.test_memory import env as test_memory_env from joblib.test.test_memory import setup_module as test_memory_setup_func @@ -429,3 +430,12 @@ def test_hashes_stay_the_same_with_numpy_objects(): for to_hash, expected in zip(to_hash_list, expected_list): yield assert_equal, hash(to_hash), expected + + +def test_hashing_pickling_error(): + def non_picklable(): + return 42 + + assert_raises_regex(pickle.PicklingError, + 'PicklingError while hashing', + hash, non_picklable) diff --git a/joblib/testing.py b/joblib/testing.py index 8555a5a..e5cbae5 100644 --- a/joblib/testing.py +++ b/joblib/testing.py @@ -5,7 +5,7 @@ Helper for testing. import sys import warnings import os.path - +import re def warnings_to_stdout(): """ Redirect all warnings to stdout. @@ -17,3 +17,30 @@ def warnings_to_stdout(): warnings.showwarning = showwarning #warnings.simplefilter('always') + + +try: + from nose.tools import assert_raises_regex +except ImportError: + # For Python 2.7 + try: + from nose.tools import assert_raises_regexp as assert_raises_regex + except ImportError: + # for Python 2.6 + def assert_raises_regex(expected_exception, expected_regexp, + callable_obj=None, *args, **kwargs): + """Helper function to check for message patterns in exceptions""" + + not_raised = False + try: + callable_obj(*args, **kwargs) + not_raised = True + except Exception as e: + error_message = str(e) + if not re.compile(expected_regexp).search(error_message): + raise AssertionError("Error message should match pattern " + "%r. %r does not." % + (expected_regexp, error_message)) + if not_raised: + raise AssertionError("Should have raised %r" % + expected_exception(expected_regexp))
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "", "pip_packages": [ "nose", "coverage", "numpy>=1.6.1", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==6.2 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/joblib/joblib.git@484405ccea3cbcbd95e3cf241f15bf3eeb1aa8b6#egg=joblib nose==1.3.7 numpy==1.19.5 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: joblib channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - numpy==1.19.5 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/joblib
[ "joblib/test/test_hashing.py::test_hashing_pickling_error" ]
[]
[ "joblib/test/test_hashing.py::test_memory_setup_func", "joblib/test/test_hashing.py::test_memory_teardown_func", "joblib/test/test_hashing.py::test_hash_methods", "joblib/test/test_hashing.py::test_numpy_datetime_array", "joblib/test/test_hashing.py::test_hash_numpy_noncontiguous", "joblib/test/test_hashing.py::test_hash_numpy_performance", "joblib/test/test_hashing.py::test_bound_methods_hash", "joblib/test/test_hashing.py::test_bound_cached_methods_hash", "joblib/test/test_hashing.py::test_hash_object_dtype", "joblib/test/test_hashing.py::test_numpy_scalar", "joblib/test/test_hashing.py::test_dict_hash", "joblib/test/test_hashing.py::test_set_hash", "joblib/test/test_hashing.py::test_string", "joblib/test/test_hashing.py::test_dtype" ]
[]
BSD 3-Clause "New" or "Revised" License
310
161
[ "joblib/hashing.py" ]
getlogbook__logbook-176
f4d4d9309d0a0ce097cfa52f0f3dad6280d7f2e3
2015-11-26 23:39:36
bb0f4fbeec318a140780b1ac8781599474cf2666
diff --git a/logbook/compat.py b/logbook/compat.py index c3896db..b65ac00 100644 --- a/logbook/compat.py +++ b/logbook/compat.py @@ -9,12 +9,13 @@ :copyright: (c) 2010 by Armin Ronacher, Georg Brandl. :license: BSD, see LICENSE for more details. """ -import sys +import collections import logging +import sys import warnings -import logbook from datetime import date, datetime +import logbook from logbook.helpers import u, string_types, iteritems _epoch_ord = date(1970, 1, 1).toordinal() @@ -63,8 +64,12 @@ class redirected_logging(object): class LoggingCompatRecord(logbook.LogRecord): def _format_message(self, msg, *args, **kwargs): - assert not kwargs - return msg % tuple(args) + if kwargs: + assert not args + return msg % kwargs + else: + assert not kwargs + return msg % tuple(args) class RedirectLoggingHandler(logging.Handler): @@ -124,10 +129,17 @@ class RedirectLoggingHandler(logging.Handler): def convert_record(self, old_record): """Converts an old logging record into a logbook log record.""" + args = old_record.args + kwargs = None + + # Logging allows passing a mapping object, in which case args will be a mapping. + if isinstance(args, collections.Mapping): + kwargs = args + args = None record = LoggingCompatRecord(old_record.name, self.convert_level(old_record.levelno), - old_record.msg, old_record.args, - None, old_record.exc_info, + old_record.msg, args, + kwargs, old_record.exc_info, self.find_extra(old_record), self.find_caller(old_record)) record.time = self.convert_time(old_record.created)
Exception in LoggingCompatRecord for mapping keys Example: ``` logger = logging.getLogger("test") logger.setLevel("DEBUG") logger.addHandler(RedirectLoggingHandler()) with logbook.StderrHandler(): logger.debug("test map %(name)s", {"name": "mapname"}) # raise exception in LoggingCompatRecord: #Traceback (most recent call last): # File "D:\bin\Python34\lib\site-packages\logbook\base.py", line 515, in message # return self._format_message(self.msg, *self.args, **self.kwargs) # File "D:\bin\Python34\lib\site-packages\logbook\compat.py", line 66, in _format_message # return msg % tuple(args) # TypeError: format requires a mapping ``` The quote from "logging/\_\_init\_\_.py" > # # The following statement allows passing of a dictionary as a sole # argument, so that you can do something like # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2}) # Suggested by Stefan Behnel. # Note that without the test for args[0], we get a problem because # during formatting, we test to see if the arg is present using # 'if self.args:'. If the event being logged is e.g. 'Value is %d' # and if the passed arg fails 'if self.args:' then no formatting # is done. For example, logger.warning('Value is %d', 0) would log # 'Value is %d' instead of 'Value is 0'. # For the use case of passing a dictionary, this should not be a # problem. # Issue #21172: a request was made to relax the isinstance check # to hasattr(args[0], '__getitem__'). However, the docs on string # formatting still seem to suggest a mapping object is required. # Thus, while not removing the isinstance check, it does now look # for collections.Mapping rather than, as before, dict. if (args and len(args) == 1 and isinstance(args[0], collections.Mapping) and args[0]): args = args[0]
getlogbook/logbook
diff --git a/tests/test_logging_compat.py b/tests/test_logging_compat.py index 48dfebe..31fdd40 100644 --- a/tests/test_logging_compat.py +++ b/tests/test_logging_compat.py @@ -36,8 +36,11 @@ def test_basic_compat(request, set_root_logger_level): logger.warn('This is from the old %s', 'system') logger.error('This is from the old system') logger.critical('This is from the old system') + logger.error('This is a %(what)s %(where)s', {'what': 'mapping', 'where': 'test'}) assert ('WARNING: %s: This is from the old system' % name) in captured.getvalue() + assert ('ERROR: %s: This is a mapping test' % + name) in captured.getvalue() if set_root_logger_level: assert handler.records[0].level == logbook.DEBUG else:
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[all]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
async-timeout==5.0.1 Cython==3.0.12 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work execnet==2.1.1 greenlet==3.1.1 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 -e git+https://github.com/getlogbook/logbook.git@f4d4d9309d0a0ce097cfa52f0f3dad6280d7f2e3#egg=Logbook MarkupSafe==3.0.2 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work pyzmq==26.3.0 redis==5.2.1 SQLAlchemy==2.0.40 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work typing_extensions==4.13.0
name: logbook channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - async-timeout==5.0.1 - cython==3.0.12 - execnet==2.1.1 - greenlet==3.1.1 - jinja2==3.1.6 - markupsafe==3.0.2 - pyzmq==26.3.0 - redis==5.2.1 - sqlalchemy==2.0.40 - typing-extensions==4.13.0 prefix: /opt/conda/envs/logbook
[ "tests/test_logging_compat.py::test_basic_compat[True]", "tests/test_logging_compat.py::test_basic_compat[False]" ]
[]
[ "tests/test_logging_compat.py::test_redirect_logbook", "tests/test_logging_compat.py::test_warning_redirections" ]
[]
BSD License
315
452
[ "logbook/compat.py" ]
juju-solutions__charms.benchmark-3
df2acf8736cce39d905990fd5008d6afa57863c3
2015-12-01 12:31:43
df2acf8736cce39d905990fd5008d6afa57863c3
tvansteenburgh: Unrelated to your change, but I don't think the `in_relation_hook()` guard on __init__.py:133 is correct. Benchmark.start() is usually called in an action, not a relation, and we want the action_uuid to be set on the relation regardless of when Benchmark.start() is called.
diff --git a/charms/benchmark/__init__.py b/charms/benchmark/__init__.py index 9a5458e..f0c15c5 100644 --- a/charms/benchmark/__init__.py +++ b/charms/benchmark/__init__.py @@ -130,14 +130,14 @@ class Benchmark(object): charm_dir = os.environ.get('CHARM_DIR') action_uuid = os.environ.get('JUJU_ACTION_UUID') - if in_relation_hook() and charm_dir and action_uuid: + if charm_dir and action_uuid: """ If the cabs-collector charm is installed, take a snapshot of the current profile data. """ # Do profile data collection immediately on this unit if os.path.exists(COLLECT_PROFILE_DATA): - subprocess.check_output([COLLECT_PROFILE_DATA]) + subprocess.check_output([COLLECT_PROFILE_DATA, action_uuid]) with open( os.path.join(
Action UUID needs to be set explicitly to the collect-profile-data script
juju-solutions/charms.benchmark
diff --git a/tests/test_charms-benchmark.py b/tests/test_charms-benchmark.py index 3b78034..8528993 100644 --- a/tests/test_charms-benchmark.py +++ b/tests/test_charms-benchmark.py @@ -146,7 +146,7 @@ class TestBenchmark(TestCase): COLLECT_PROFILE_DATA = '/usr/local/bin/collect-profile-data' exists.assert_any_call(COLLECT_PROFILE_DATA) - check_output.assert_any_call([COLLECT_PROFILE_DATA]) + check_output.assert_any_call([COLLECT_PROFILE_DATA, 'my_action']) @mock.patch('charms.benchmark.action_set') def test_benchmark_finish(self, action_set):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 1 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "coverage", "testtools", "pep8", "mock", "cherrypy", "pyyaml", "six", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "test-requires.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
autocommand==2.2.2 backports.tarfile==1.2.0 charmhelpers==1.2.1 -e git+https://github.com/juju-solutions/charms.benchmark.git@df2acf8736cce39d905990fd5008d6afa57863c3#egg=charms.benchmark cheroot==10.0.1 CherryPy==18.10.0 coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 jaraco.collections==5.1.0 jaraco.context==6.0.1 jaraco.functools==4.1.0 jaraco.text==4.0.0 Jinja2==3.1.6 MarkupSafe==3.0.2 mock==5.2.0 more-itertools==10.6.0 netaddr==1.3.0 nose==1.3.7 packaging==24.2 pbr==6.1.1 pep8==1.7.1 pluggy==1.5.0 portend==3.2.0 pytest==8.3.5 python-dateutil==2.9.0.post0 PyYAML==6.0.2 six==1.17.0 tempora==5.8.0 testtools==2.7.2 tomli==2.2.1 zc.lockfile==3.0.post1
name: charms.benchmark channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - autocommand==2.2.2 - backports-tarfile==1.2.0 - charmhelpers==1.2.1 - cheroot==10.0.1 - cherrypy==18.10.0 - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - jaraco-collections==5.1.0 - jaraco-context==6.0.1 - jaraco-functools==4.1.0 - jaraco-text==4.0.0 - jinja2==3.1.6 - markupsafe==3.0.2 - mock==5.2.0 - more-itertools==10.6.0 - netaddr==1.3.0 - nose==1.3.7 - packaging==24.2 - pbr==6.1.1 - pep8==1.7.1 - pluggy==1.5.0 - portend==3.2.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - six==1.17.0 - tempora==5.8.0 - testtools==2.7.2 - tomli==2.2.1 - zc-lockfile==3.0.post1 prefix: /opt/conda/envs/charms.benchmark
[ "tests/test_charms-benchmark.py::TestBenchmark::test_benchmark_start" ]
[]
[ "tests/test_charms-benchmark.py::TestBenchmark::test_benchmark_finish", "tests/test_charms-benchmark.py::TestBenchmark::test_benchmark_finish_oserror", "tests/test_charms-benchmark.py::TestBenchmark::test_benchmark_init", "tests/test_charms-benchmark.py::TestBenchmark::test_benchmark_meta", "tests/test_charms-benchmark.py::TestBenchmark::test_benchmark_set_composite_score", "tests/test_charms-benchmark.py::TestBenchmark::test_benchmark_start_oserror", "tests/test_charms-benchmark.py::TestBenchmark::test_set_data" ]
[]
null
318
227
[ "charms/benchmark/__init__.py" ]
pre-commit__pre-commit-310
6b005cff0d5d4f579be5dbb97102c4fee3b4e39f
2015-12-01 16:34:13
c1c3f3b571adcd0cf5a8cea7d9d80574c2572c02
diff --git a/pre_commit/error_handler.py b/pre_commit/error_handler.py index c8d2bfc..60038f4 100644 --- a/pre_commit/error_handler.py +++ b/pre_commit/error_handler.py @@ -7,7 +7,9 @@ import io import os.path import traceback +from pre_commit import five from pre_commit.errors import FatalError +from pre_commit.output import sys_stdout_write_wrapper from pre_commit.store import Store @@ -16,15 +18,15 @@ class PreCommitSystemExit(SystemExit): pass -def _log_and_exit(msg, exc, formatted, print_fn=print): - error_msg = '{0}: {1}: {2}'.format(msg, type(exc).__name__, exc) - print_fn(error_msg) - print_fn('Check the log at ~/.pre-commit/pre-commit.log') +def _log_and_exit(msg, exc, formatted, write_fn=sys_stdout_write_wrapper): + error_msg = '{0}: {1}: {2}\n'.format(msg, type(exc).__name__, exc) + write_fn(error_msg) + write_fn('Check the log at ~/.pre-commit/pre-commit.log\n') store = Store() store.require_created() - with io.open(os.path.join(store.directory, 'pre-commit.log'), 'w') as log: - log.write(error_msg + '\n') - log.write(formatted + '\n') + with io.open(os.path.join(store.directory, 'pre-commit.log'), 'wb') as log: + log.write(five.to_bytes(error_msg)) + log.write(five.to_bytes(formatted) + b'\n') raise PreCommitSystemExit(1)
Non-ascii prints in error handler without tty cause stacktrace ``` 23:00:13 style runtests: commands[0] | pre-commit run --all-files 23:00:13 [INFO] Installing environment for [email protected]:mirrors/pre-commit/mirrors-jshint. 23:00:13 [INFO] Once installed this environment will be reused. 23:00:13 [INFO] This may take a few minutes... 23:01:33 Traceback (most recent call last): 23:01:33 File ".tox/style/bin/pre-commit", line 11, in <module> 23:01:33 sys.exit(main()) 23:01:33 File ".../.tox/style/local/lib/python2.7/site-packages/pre_commit/main.py", line 157, in main 23:01:33 'Command {0} failed to exit with a returncode'.format(args.command) 23:01:33 File "/usr/lib64/python2.7/contextlib.py", line 35, in __exit__ 23:01:33 self.gen.throw(type, value, traceback) 23:01:33 File ".../.tox/style/local/lib/python2.7/site-packages/pre_commit/error_handler.py", line 41, in error_handler 23:01:33 traceback.format_exc(), 23:01:33 File ".../.tox/style/local/lib/python2.7/site-packages/pre_commit/error_handler.py", line 21, in _log_and_exit 23:01:33 print_fn(error_msg) 23:01:33 UnicodeEncodeError: 'ascii' codec can't encode characters in position 735-737: ordinal not in range(128) ```
pre-commit/pre-commit
diff --git a/tests/error_handler_test.py b/tests/error_handler_test.py index 161b88f..d8f966a 100644 --- a/tests/error_handler_test.py +++ b/tests/error_handler_test.py @@ -1,15 +1,18 @@ +# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals import io import os.path import re +import sys import mock import pytest from pre_commit import error_handler from pre_commit.errors import FatalError +from pre_commit.util import cmd_output @pytest.yield_fixture @@ -72,17 +75,17 @@ def test_error_handler_uncaught_error(mocked_log_and_exit): def test_log_and_exit(mock_out_store_directory): - mocked_print = mock.Mock() + mocked_write = mock.Mock() with pytest.raises(error_handler.PreCommitSystemExit): error_handler._log_and_exit( 'msg', FatalError('hai'), "I'm a stacktrace", - print_fn=mocked_print, + write_fn=mocked_write, ) - printed = '\n'.join(call[0][0] for call in mocked_print.call_args_list) + printed = ''.join(call[0][0] for call in mocked_write.call_args_list) assert printed == ( 'msg: FatalError: hai\n' - 'Check the log at ~/.pre-commit/pre-commit.log' + 'Check the log at ~/.pre-commit/pre-commit.log\n' ) log_file = os.path.join(mock_out_store_directory, 'pre-commit.log') @@ -92,3 +95,25 @@ def test_log_and_exit(mock_out_store_directory): 'msg: FatalError: hai\n' "I'm a stacktrace\n" ) + + +def test_error_handler_non_ascii_exception(mock_out_store_directory): + with pytest.raises(error_handler.PreCommitSystemExit): + with error_handler.error_handler(): + raise ValueError('☃') + + +def test_error_handler_no_tty(tempdir_factory): + output = cmd_output( + sys.executable, '-c', + 'from __future__ import unicode_literals\n' + 'from pre_commit.error_handler import error_handler\n' + 'with error_handler():\n' + ' raise ValueError("\\u2603")\n', + env=dict(os.environ, PRE_COMMIT_HOME=tempdir_factory.get()), + retcode=1, + ) + assert output[1].replace('\r', '') == ( + 'An unexpected error has occurred: ValueError: ☃\n' + 'Check the log at ~/.pre-commit/pre-commit.log\n' + )
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aspy.yaml==1.3.0 astroid==1.3.2 attrs==22.2.0 cached-property==1.5.2 certifi==2021.5.30 coverage==6.2 distlib==0.3.9 filelock==3.4.1 flake8==5.0.4 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 jsonschema==3.2.0 logilab-common==1.9.7 mccabe==0.7.0 mock==5.2.0 mypy-extensions==1.0.0 nodeenv==1.6.0 ordereddict==1.1 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 -e git+https://github.com/pre-commit/pre-commit.git@6b005cff0d5d4f579be5dbb97102c4fee3b4e39f#egg=pre_commit py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 pylint==1.3.1 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 PyYAML==6.0.1 simplejson==3.20.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 virtualenv==20.17.1 zipp==3.6.0
name: pre-commit channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argparse==1.4.0 - aspy-yaml==1.3.0 - astroid==1.3.2 - attrs==22.2.0 - cached-property==1.5.2 - coverage==6.2 - distlib==0.3.9 - filelock==3.4.1 - flake8==5.0.4 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - jsonschema==3.2.0 - logilab-common==1.9.7 - mccabe==0.7.0 - mock==5.2.0 - mypy-extensions==1.0.0 - nodeenv==1.6.0 - ordereddict==1.1 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pylint==1.3.1 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pyyaml==6.0.1 - simplejson==3.20.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - virtualenv==20.17.1 - zipp==3.6.0 prefix: /opt/conda/envs/pre-commit
[ "tests/error_handler_test.py::test_log_and_exit" ]
[]
[ "tests/error_handler_test.py::test_error_handler_no_exception", "tests/error_handler_test.py::test_error_handler_fatal_error", "tests/error_handler_test.py::test_error_handler_uncaught_error", "tests/error_handler_test.py::test_error_handler_non_ascii_exception", "tests/error_handler_test.py::test_error_handler_no_tty" ]
[]
MIT License
319
378
[ "pre_commit/error_handler.py" ]
projectmesa__mesa-178
57a0beb5947fc16b7b665f297504907e300b043c
2015-12-04 04:39:32
6db9efde7c659b9338fc8cf551f066cdba7031c3
diff --git a/mesa/space.py b/mesa/space.py index 5e3a9544..77fe8174 100644 --- a/mesa/space.py +++ b/mesa/space.py @@ -24,6 +24,20 @@ X = 0 Y = 1 +def accept_tuple_argument(wrapped_function): + ''' + Decorator to allow grid methods that take a list of (x, y) position tuples + to also handle a single position, by automatically wrapping tuple in + single-item list rather than forcing user to do it. + ''' + def wrapper(*args): + if isinstance(args[1], tuple) and len(args[1]) == 2: + return wrapped_function(args[0], [args[1]]) + else: + return wrapped_function(*args) + return wrapper + + class Grid(object): ''' Base class for a square grid. @@ -238,10 +252,11 @@ class Grid(object): x, y = pos return x < 0 or x >= self.width or y < 0 or y >= self.height + @accept_tuple_argument def iter_cell_list_contents(self, cell_list): ''' Args: - cell_list: Array-like of (x, y) tuples + cell_list: Array-like of (x, y) tuples, or single tuple. Returns: A iterator of the contents of the cells identified in cell_list @@ -249,10 +264,11 @@ class Grid(object): return ( self[y][x] for x, y in cell_list if not self.is_cell_empty((x, y))) + @accept_tuple_argument def get_cell_list_contents(self, cell_list): ''' Args: - cell_list: Array-like of (x, y) tuples + cell_list: Array-like of (x, y) tuples, or single tuple. Returns: A list of the contents of the cells identified in cell_list @@ -418,10 +434,11 @@ class MultiGrid(Grid): x, y = pos self.grid[y][x].remove(agent) + @accept_tuple_argument def iter_cell_list_contents(self, cell_list): ''' Args: - cell_list: Array-like of (x, y) tuples + cell_list: Array-like of (x, y) tuples, or single tuple. Returns: A iterator of the contents of the cells identified in cell_list
baby patch/tweak: allow cell methods to take single cell Cf. discussion in #176 -- taking on the small "(TODO: someone should probably fix that...)" from the tutorial re: grid's `get_cell_list_contents` requiring a list of cells even if it's just being passed a single cell. It's a very easy fix, I'm on the case. :-)
projectmesa/mesa
diff --git a/tests/test_grid.py b/tests/test_grid.py index b558f4d9..c09f0496 100644 --- a/tests/test_grid.py +++ b/tests/test_grid.py @@ -53,6 +53,43 @@ class TestBaseGrid(unittest.TestCase): x, y = agent.pos assert self.grid[y][x] == agent + def test_cell_agent_reporting(self): + ''' + Ensure that if an agent is in a cell, get_cell_list_contents accurately + reports that fact. + ''' + for agent in self.agents: + x, y = agent.pos + assert agent in self.grid.get_cell_list_contents([(x, y)]) + + def test_listfree_cell_agent_reporting(self): + ''' + Ensure that if an agent is in a cell, get_cell_list_contents accurately + reports that fact, even when single position is not wrapped in a list. + ''' + for agent in self.agents: + x, y = agent.pos + assert agent in self.grid.get_cell_list_contents((x, y)) + + def test_iter_cell_agent_reporting(self): + ''' + Ensure that if an agent is in a cell, iter_cell_list_contents + accurately reports that fact. + ''' + for agent in self.agents: + x, y = agent.pos + assert agent in self.grid.iter_cell_list_contents([(x, y)]) + + def test_listfree_iter_cell_agent_reporting(self): + ''' + Ensure that if an agent is in a cell, iter_cell_list_contents + accurately reports that fact, even when single position is not + wrapped in a list. + ''' + for agent in self.agents: + x, y = agent.pos + assert agent in self.grid.iter_cell_list_contents((x, y)) + def test_neighbors(self): ''' Test the base neighborhood methods on the non-toroid.
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_issue_reference", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 1 }
0.6
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "flake8" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 flake8==7.2.0 iniconfig==2.1.0 mccabe==0.7.0 -e git+https://github.com/projectmesa/mesa.git@57a0beb5947fc16b7b665f297504907e300b043c#egg=Mesa numpy==2.0.2 packaging==24.2 pandas==2.2.3 pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.1 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 pytz==2025.2 six==1.17.0 tomli==2.2.1 tornado==6.4.2 tzdata==2025.2
name: mesa channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - flake8==7.2.0 - iniconfig==2.1.0 - mccabe==0.7.0 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - six==1.17.0 - tomli==2.2.1 - tornado==6.4.2 - tzdata==2025.2 prefix: /opt/conda/envs/mesa
[ "tests/test_grid.py::TestBaseGrid::test_listfree_cell_agent_reporting", "tests/test_grid.py::TestBaseGrid::test_listfree_iter_cell_agent_reporting", "tests/test_grid.py::TestBaseGridTorus::test_listfree_cell_agent_reporting", "tests/test_grid.py::TestBaseGridTorus::test_listfree_iter_cell_agent_reporting" ]
[]
[ "tests/test_grid.py::TestBaseGrid::test_agent_positions", "tests/test_grid.py::TestBaseGrid::test_cell_agent_reporting", "tests/test_grid.py::TestBaseGrid::test_coord_iter", "tests/test_grid.py::TestBaseGrid::test_iter_cell_agent_reporting", "tests/test_grid.py::TestBaseGrid::test_neighbors", "tests/test_grid.py::TestBaseGridTorus::test_agent_positions", "tests/test_grid.py::TestBaseGridTorus::test_cell_agent_reporting", "tests/test_grid.py::TestBaseGridTorus::test_coord_iter", "tests/test_grid.py::TestBaseGridTorus::test_iter_cell_agent_reporting", "tests/test_grid.py::TestBaseGridTorus::test_neighbors", "tests/test_grid.py::TestSingleGrid::test_enforcement", "tests/test_grid.py::TestMultiGrid::test_agent_positions", "tests/test_grid.py::TestMultiGrid::test_neighbors" ]
[]
Apache License 2.0
321
581
[ "mesa/space.py" ]
andycasey__ads-36
5bd62ef2bf924116374455e222ea9ac8dc416b3a
2015-12-04 17:01:02
c039d67c2b2e9dad936758bc89df1fdd1cbd0aa1
diff --git a/ads/search.py b/ads/search.py index eb64e70..fed6c0c 100644 --- a/ads/search.py +++ b/ads/search.py @@ -275,7 +275,7 @@ class SearchQuery(BaseQuery): "title", "reference", "citation"] def __init__(self, query_dict=None, q=None, fq=None, fl=DEFAULT_FIELDS, - sort=None, start=0, rows=50, max_pages=3, **kwargs): + sort=None, start=0, rows=50, max_pages=1, **kwargs): """ constructor :param query_dict: raw query that will be sent unmodified. raw takes @@ -288,7 +288,7 @@ class SearchQuery(BaseQuery): :param start: solr "start" param (start) :param rows: solr "rows" param (rows) :param max_pages: Maximum number of pages to return. This value may - be modified after instansiation to increase the number of results + be modified after instantiation to increase the number of results :param kwargs: kwargs to add to `q` as "key:value" """ self._articles = [] @@ -385,7 +385,7 @@ class SearchQuery(BaseQuery): # if we have hit the max_pages limit, then iteration is done. page = math.ceil(len(self.articles)/self.query['rows']) - if page > self.max_pages: + if page >= self.max_pages: raise StopIteration("Maximum number of pages queried") # We aren't on the max_page of results nor do we have all
Number of returned results doesn't correspond to 'rows' key value in SearchQuery Example code: ```` In [5]: papers = ads.SearchQuery(q="supernova", sort="citation_count", rows=10) In [6]: print(len(list(papers))) 40 ```` Not massively important, but a bit surprising anyway. Any explanation? Thanks!
andycasey/ads
diff --git a/ads/tests/test_search.py b/ads/tests/test_search.py index 346d957..331a9f5 100644 --- a/ads/tests/test_search.py +++ b/ads/tests/test_search.py @@ -131,18 +131,24 @@ class TestSearchQuery(unittest.TestCase): self.assertEqual(len(sq.articles), 1) self.assertEqual(sq._query['start'], 1) self.assertEqual(next(sq).bibcode, '2012GCN..13229...1S') - self.assertEqual(len(list(sq)), 19) # 2 already returned + self.assertEqual(len(list(sq)), 18) # 2 already returned with self.assertRaisesRegexp( StopIteration, "Maximum number of pages queried"): next(sq) sq.max_pages = 500 - self.assertEqual(len(list(sq)), 28-19-2) + self.assertEqual(len(list(sq)), 28-18-2) with self.assertRaisesRegexp( StopIteration, "All records found"): next(sq) + # not setting max_pages should return the exact number of rows requests + sq = SearchQuery(q="unittest", rows=3) + with MockSolrResponse(sq.HTTP_ENDPOINT): + self.assertEqual(len(list(sq)), 3) + + def test_init(self): """ init should result in a properly formatted query attribute
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/andycasey/ads.git@5bd62ef2bf924116374455e222ea9ac8dc416b3a#egg=ads certifi==2025.1.31 charset-normalizer==3.4.1 exceptiongroup==1.2.2 httpretty==1.1.4 idna==3.10 iniconfig==2.1.0 MarkupSafe==3.0.2 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 requests==2.32.3 six==1.17.0 tomli==2.2.1 urllib3==2.3.0 Werkzeug==3.1.3
name: ads channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - charset-normalizer==3.4.1 - exceptiongroup==1.2.2 - httpretty==1.1.4 - idna==3.10 - iniconfig==2.1.0 - markupsafe==3.0.2 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - requests==2.32.3 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 - werkzeug==3.1.3 prefix: /opt/conda/envs/ads
[ "ads/tests/test_search.py::TestSearchQuery::test_iter" ]
[]
[ "ads/tests/test_search.py::TestArticle::test_cached_properties", "ads/tests/test_search.py::TestArticle::test_equals", "ads/tests/test_search.py::TestArticle::test_get_field", "ads/tests/test_search.py::TestArticle::test_init", "ads/tests/test_search.py::TestArticle::test_print_methods", "ads/tests/test_search.py::TestSearchQuery::test_init", "ads/tests/test_search.py::TestSolrResponse::test_articles", "ads/tests/test_search.py::TestSolrResponse::test_init", "ads/tests/test_search.py::TestSolrResponse::test_load_http_response", "ads/tests/test_search.py::Testquery::test_init" ]
[]
MIT License
323
385
[ "ads/search.py" ]
joblib__joblib-283
c60d263fcc71ba9f4532010b732cde42e437039b
2015-12-10 15:14:21
40341615cc2600675ce7457d9128fb030f6f89fa
lesteve: > inspect.getfullargspec is marked as deprecated since 3.5, why not directly use a compatibility function called signature and use the one from python >= 3.4. Yeah I am aware of that but I wanted to do the smallest change to make joblib.Memory support functions with signature or keyword-only arguments. scikit-learn went the way you mentioned and ended up having to backport OrderedDict in order to support python 2.6. aabadie: @lesteve, to me your change is an improvement and I'm ok to merge it. But if you have time and think it's worth reusing the scikit-learn strategy, then go ahead ;) lesteve: > @lesteve, to me your change is an improvement and I'm ok to merge it. But if you have time and think it's worth reusing the scikit-learn strategy, then go ahead ;) I am enclined to go with this simpler strategy for now. The only thing I want to look at is tackling this comment from above: > At the moment I am not doing any checks to see whether the keyword-only arguments were indeed passed as keywords. Maybe I should since there is some checks for the number of arguments in this function already. lesteve: Right, I fixed the keyword-only argument passed as positional parameter in joblib.function_inspect.filter_args. As you would expect, the snippet above now raises ``` ValueError: Keyword-only parameter 'kw1' was passed as positional parameter for func_with_kwonly_args(a, b, *, kw1='kw1', kw2='kw2'): func_with_kwonly_args(1, 2, 3, kw2=4) was called. ``` Any more comments ? aabadie: @lesteve, @ogrisel, could this one be merged ? ogrisel: Besides minor comments, LGTM. I can do the cosmetics changed when merging if you wish.
diff --git a/joblib/func_inspect.py b/joblib/func_inspect.py index cc5cbf6..3eee40b 100644 --- a/joblib/func_inspect.py +++ b/joblib/func_inspect.py @@ -11,11 +11,15 @@ import inspect import warnings import re import os - +import sys from ._compat import _basestring from .logger import pformat from ._memory_helpers import open_py_source + +PY3 = sys.version_info[0] >= 3 + + def get_func_code(func): """ Attempts to retrieve a reliable function code hash. @@ -156,6 +160,53 @@ def get_func_name(func, resolv_alias=True, win_characters=True): return module, name +def getfullargspec(func): + """Compatibility function to provide inspect.getfullargspec in Python 2 + + This should be rewritten using a backport of Python 3 signature + once we drop support for Python 2.6. We went for a simpler + approach at the time of writing because signature uses OrderedDict + which is not available in Python 2.6. + """ + try: + return inspect.getfullargspec(func) + except AttributeError: + arg_spec = inspect.getargspec(func) + import collections + tuple_fields = ('args varargs varkw defaults kwonlyargs ' + 'kwonlydefaults annotations') + tuple_type = collections.namedtuple('FullArgSpec', tuple_fields) + + return tuple_type(args=arg_spec.args, + varargs=arg_spec.varargs, + varkw=arg_spec.keywords, + defaults=arg_spec.defaults, + kwonlyargs=[], + kwonlydefaults=None, + annotations={}) + + +def _signature_str(function_name, arg_spec): + """Helper function to output a function signature""" + # inspect.formatargspec can not deal with the same + # number of arguments in python 2 and 3 + arg_spec_for_format = arg_spec[:7 if PY3 else 4] + + arg_spec_str = inspect.formatargspec(*arg_spec_for_format) + return '{0}{1}'.format(function_name, arg_spec_str) + + +def _function_called_str(function_name, args, kwargs): + """Helper function to output a function call""" + template_str = '{0}({1}, {2})' + + args_str = repr(args)[1:-1] + kwargs_str = ', '.join('%s=%s' % (k, v) + for k, v in kwargs.items()) + return template_str.format(function_name, args_str, + kwargs_str) + + def filter_args(func, ignore_lst, args=(), kwargs=dict()): """ Filters the given args and kwargs using a list of arguments to ignore, and a function specification. @@ -180,19 +231,22 @@ def filter_args(func, ignore_lst, args=(), kwargs=dict()): args = list(args) if isinstance(ignore_lst, _basestring): # Catch a common mistake - raise ValueError('ignore_lst must be a list of parameters to ignore ' + raise ValueError( + 'ignore_lst must be a list of parameters to ignore ' '%s (type %s) was given' % (ignore_lst, type(ignore_lst))) # Special case for functools.partial objects if (not inspect.ismethod(func) and not inspect.isfunction(func)): if ignore_lst: warnings.warn('Cannot inspect object %s, ignore list will ' - 'not work.' % func, stacklevel=2) + 'not work.' % func, stacklevel=2) return {'*': args, '**': kwargs} - arg_spec = inspect.getargspec(func) - arg_names = arg_spec.args - arg_defaults = arg_spec.defaults or {} - arg_keywords = arg_spec.keywords + arg_spec = getfullargspec(func) + arg_names = arg_spec.args + arg_spec.kwonlyargs + arg_defaults = arg_spec.defaults or () + arg_defaults = arg_defaults + tuple(arg_spec.kwonlydefaults[k] + for k in arg_spec.kwonlyargs) arg_varargs = arg_spec.varargs + arg_varkw = arg_spec.varkw if inspect.ismethod(func): # First argument is 'self', it has been removed by Python @@ -207,7 +261,18 @@ def filter_args(func, ignore_lst, args=(), kwargs=dict()): for arg_position, arg_name in enumerate(arg_names): if arg_position < len(args): # Positional argument or keyword argument given as positional - arg_dict[arg_name] = args[arg_position] + if arg_name not in arg_spec.kwonlyargs: + arg_dict[arg_name] = args[arg_position] + else: + raise ValueError( + "Keyword-only parameter '%s' was passed as " + 'positional parameter for %s:\n' + ' %s was called.' + % (arg_name, + _signature_str(name, arg_spec), + _function_called_str(name, args, kwargs)) + ) + else: position = arg_position - len(arg_names) if arg_name in kwargs: @@ -217,28 +282,24 @@ def filter_args(func, ignore_lst, args=(), kwargs=dict()): arg_dict[arg_name] = arg_defaults[position] except (IndexError, KeyError): # Missing argument - raise ValueError('Wrong number of arguments for %s%s:\n' - ' %s(%s, %s) was called.' - % (name, - inspect.formatargspec(*inspect.getargspec(func)), - name, - repr(args)[1:-1], - ', '.join('%s=%s' % (k, v) - for k, v in kwargs.items()) - ) - ) + raise ValueError( + 'Wrong number of arguments for %s:\n' + ' %s was called.' + % (_signature_str(name, arg_spec), + _function_called_str(name, args, kwargs)) + ) varkwargs = dict() for arg_name, arg_value in sorted(kwargs.items()): if arg_name in arg_dict: arg_dict[arg_name] = arg_value - elif arg_keywords is not None: + elif arg_varkw is not None: varkwargs[arg_name] = arg_value else: raise TypeError("Ignore list for %s() contains an unexpected " "keyword argument '%s'" % (name, arg_name)) - if arg_keywords is not None: + if arg_varkw is not None: arg_dict['**'] = varkwargs if arg_varargs is not None: varargs = args[arg_position + 1:] @@ -250,13 +311,10 @@ def filter_args(func, ignore_lst, args=(), kwargs=dict()): arg_dict.pop(item) else: raise ValueError("Ignore list: argument '%s' is not defined for " - "function %s%s" % - (item, name, - inspect.formatargspec(arg_names, - arg_varargs, - arg_keywords, - arg_defaults, - ))) + "function %s" + % (item, + _signature_str(name, arg_spec)) + ) # XXX: Return a sorted list of pairs? return arg_dict
Replace deprecated usage of inspect.getargspec inspect.getargspec has been deprecated since 3.0 (in favor of inspect.getfullargspec until 3.2 and in favor of inspect.signature since 3.3) and will be removed in 3.6. It also creates visible DeprecationWarning in 3.5.
joblib/joblib
diff --git a/joblib/test/test_func_inspect.py b/joblib/test/test_func_inspect.py index 15c6b43..62920e9 100644 --- a/joblib/test/test_func_inspect.py +++ b/joblib/test/test_func_inspect.py @@ -11,12 +11,15 @@ import shutil import nose import tempfile import functools +import sys from joblib.func_inspect import filter_args, get_func_name, get_func_code from joblib.func_inspect import _clean_win_chars, format_signature from joblib.memory import Memory from joblib.test.common import with_numpy +from joblib.testing import assert_raises_regex +PY3 = sys.version_info[0] >= 3 ############################################################################### # Module-level functions, for tests @@ -165,6 +168,37 @@ def test_func_inspect_errors(): __file__.replace('.pyc', '.py')) +if PY3: + exec(""" +def func_with_kwonly_args(a, b, *, kw1='kw1', kw2='kw2'): pass + +def func_with_signature(a: int, b: int) -> None: pass +""") + + def test_filter_args_python_3(): + nose.tools.assert_equal( + filter_args(func_with_kwonly_args, + [], (1, 2), {'kw1': 3, 'kw2': 4}), + {'a': 1, 'b': 2, 'kw1': 3, 'kw2': 4}) + + # filter_args doesn't care about keyword-only arguments so you + # can pass 'kw1' into *args without any problem + assert_raises_regex( + ValueError, + "Keyword-only parameter 'kw1' was passed as positional parameter", + filter_args, + func_with_kwonly_args, [], (1, 2, 3), {'kw2': 2}) + + nose.tools.assert_equal( + filter_args(func_with_kwonly_args, ['b', 'kw2'], (1, 2), + {'kw1': 3, 'kw2': 4}), + {'a': 1, 'kw1': 3}) + + nose.tools.assert_equal( + filter_args(func_with_signature, ['b'], (1, 2)), + {'a': 1}) + + def test_bound_methods(): """ Make sure that calling the same method on two different instances of the same class does resolv to different signatures. diff --git a/joblib/test/test_memory.py b/joblib/test/test_memory.py index 14e319f..5f0bbfd 100644 --- a/joblib/test/test_memory.py +++ b/joblib/test/test_memory.py @@ -21,7 +21,9 @@ import nose from joblib.memory import Memory, MemorizedFunc, NotMemorizedFunc, MemorizedResult from joblib.memory import NotMemorizedResult, _FUNCTION_HASHES from joblib.test.common import with_numpy, np +from joblib.testing import assert_raises_regex +PY3 = sys.version_info[0] >= 3 ############################################################################### # Module-level variables for the tests @@ -676,3 +678,48 @@ def test_memory_in_memory_function_code_change(): def test_clear_memory_with_none_cachedir(): mem = Memory(cachedir=None) mem.clear() + +if PY3: + exec(""" +def func_with_kwonly_args(a, b, *, kw1='kw1', kw2='kw2'): + return a, b, kw1, kw2 + +def func_with_signature(a: int, b: float) -> float: + return a + b +""") + + def test_memory_func_with_kwonly_args(): + mem = Memory(cachedir=env['dir'], verbose=0) + func_cached = mem.cache(func_with_kwonly_args) + + nose.tools.assert_equal(func_cached(1, 2, kw1=3), (1, 2, 3, 'kw2')) + + # Making sure that providing a keyword-only argument by + # position raises an exception + assert_raises_regex( + ValueError, + "Keyword-only parameter 'kw1' was passed as positional parameter", + func_cached, + 1, 2, 3, {'kw2': 4}) + + # Keyword-only parameter passed by position with cached call + # should still raise ValueError + func_cached(1, 2, kw1=3, kw2=4) + + assert_raises_regex( + ValueError, + "Keyword-only parameter 'kw1' was passed as positional parameter", + func_cached, + 1, 2, 3, {'kw2': 4}) + + # Test 'ignore' parameter + func_cached = mem.cache(func_with_kwonly_args, ignore=['kw2']) + nose.tools.assert_equal(func_cached(1, 2, kw1=3, kw2=4), (1, 2, 3, 4)) + nose.tools.assert_equal(func_cached(1, 2, kw1=3, kw2='ignored'), (1, 2, 3, 4)) + + + def test_memory_func_with_signature(): + mem = Memory(cachedir=env['dir'], verbose=0) + func_cached = mem.cache(func_with_signature) + + nose.tools.assert_equal(func_cached(1, 2.), 3.)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.9
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "coverage", "pytest" ], "pre_install": null, "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 coverage==6.2 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/joblib/joblib.git@c60d263fcc71ba9f4532010b732cde42e437039b#egg=joblib more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work nose==1.3.7 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: joblib channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==6.2 - nose==1.3.7 prefix: /opt/conda/envs/joblib
[ "joblib/test/test_func_inspect.py::test_filter_args_python_3", "joblib/test/test_memory.py::test_memory_func_with_kwonly_args", "joblib/test/test_memory.py::test_memory_func_with_signature" ]
[]
[ "joblib/test/test_func_inspect.py::test_filter_args_method", "joblib/test/test_func_inspect.py::test_filter_kwargs", "joblib/test/test_func_inspect.py::test_filter_args_2", "joblib/test/test_func_inspect.py::test_func_inspect_errors", "joblib/test/test_func_inspect.py::test_bound_methods", "joblib/test/test_func_inspect.py::test_filter_args_error_msg", "joblib/test/test_func_inspect.py::test_clean_win_chars", "joblib/test/test_func_inspect.py::test_format_signature", "joblib/test/test_func_inspect.py::test_special_source_encoding", "joblib/test/test_func_inspect.py::test_func_code_consistency", "joblib/test/test_memory.py::test_memory_warning_lambda_collisions", "joblib/test/test_memory.py::test_argument_change", "joblib/test/test_memory.py::test_call_and_shelve", "joblib/test/test_memory.py::test_memorized_pickling", "joblib/test/test_memory.py::test_memorized_repr", "joblib/test/test_memory.py::test_memory_file_modification", "joblib/test/test_memory.py::test_memory_in_memory_function_code_change", "joblib/test/test_memory.py::test_clear_memory_with_none_cachedir" ]
[]
BSD 3-Clause "New" or "Revised" License
328
1,681
[ "joblib/func_inspect.py" ]
Shopify__shopify_python_api-129
28c00a110c23edc5287d6e8f90f0e36f0eb5d1b3
2015-12-11 18:31:45
c29e0ecbed9de67dd923f980a3ac053922dab75e
diff --git a/shopify/resources/__init__.py b/shopify/resources/__init__.py index 2de7499..adacc08 100644 --- a/shopify/resources/__init__.py +++ b/shopify/resources/__init__.py @@ -46,5 +46,6 @@ from .policy import Policy from .smart_collection import SmartCollection from .gift_card import GiftCard from .discount import Discount +from .shipping_zone import ShippingZone from ..base import ShopifyResource diff --git a/shopify/resources/shipping_zone.py b/shopify/resources/shipping_zone.py new file mode 100644 index 0000000..49cd647 --- /dev/null +++ b/shopify/resources/shipping_zone.py @@ -0,0 +1,5 @@ +from ..base import ShopifyResource + + +class ShippingZone(ShopifyResource): + pass
Add support for the new Shipping Zone resource. As per https://ecommerce.shopify.com/c/api-announcements/t/shipping-zones-api-and-changes-to-the-countries-api-307687.
Shopify/shopify_python_api
diff --git a/test/fixtures/shipping_zones.json b/test/fixtures/shipping_zones.json new file mode 100644 index 0000000..f07b8ff --- /dev/null +++ b/test/fixtures/shipping_zones.json @@ -0,0 +1,114 @@ +{ + "shipping_zones": [ + { + "id": 1, + "name": "Some zone", + "countries": [ + { + "id": 817138619, + "name": "United States", + "tax": 0.0, + "code": "US", + "tax_name": "Federal Tax", + "provinces": [ + { + "id": 1013111685, + "country_id": 817138619, + "name": "New York", + "code": "NY", + "tax": 0.04, + "tax_name": "Tax", + "tax_type": null, + "shipping_zone_id": 1, + "tax_percentage": 4.0 + }, + { + "id": 1069646654, + "country_id": 817138619, + "name": "Ohio", + "code": "OH", + "tax": 0.0, + "tax_name": "State Tax", + "tax_type": null, + "shipping_zone_id": 1, + "tax_percentage": 0.0 + } + ] + }, + { + "id": 879921427, + "name": "Canada", + "tax": 0.05, + "code": "CA", + "tax_name": "GST", + "provinces": [ + { + "id": 702530425, + "country_id": 879921427, + "name": "Ontario", + "code": "ON", + "tax": 0.08, + "tax_name": "Tax", + "tax_type": null, + "shipping_zone_id": 1, + "tax_percentage": 8.0 + }, + { + "id": 224293623, + "country_id": 879921427, + "name": "Quebec", + "code": "QC", + "tax": 0.09, + "tax_name": "HST", + "tax_type": "compounded", + "shipping_zone_id": 1, + "tax_percentage": 9.0 + } + ] + }, + { + "id": 988409122, + "name": "Yemen", + "tax": 0.0, + "code": "YE", + "tax_name": "GST", + "provinces": [ + ] + } + ], + "weight_based_shipping_rates": [ + { + "id": 760465697, + "weight_low": 1.2, + "weight_high": 10.0, + "name": "Austria Express Heavy Shipping", + "price": "40.00", + "shipping_zone_id": 1 + } + ], + "price_based_shipping_rates": [ + { + "id": 583276424, + "name": "Standard Shipping", + "min_order_subtotal": "0.00", + "price": "10.99", + "max_order_subtotal": "2000.00", + "shipping_zone_id": 1 + } + ], + "carrier_shipping_rate_providers": [ + { + "id": 972083812, + "country_id": null, + "carrier_service_id": 61629186, + "flat_modifier": "0.00", + "percent_modifier": 0, + "service_filter": { + "*": "+" + }, + "shipping_zone_id": 1 + } + ] + } + ] +} \ No newline at end of file diff --git a/test/shipping_zone_test.py b/test/shipping_zone_test.py new file mode 100644 index 0000000..e81cfe6 --- /dev/null +++ b/test/shipping_zone_test.py @@ -0,0 +1,11 @@ +import shopify +from test.test_helper import TestCase + +class ShippingZoneTest(TestCase): + def test_get_shipping_zones(self): + self.fake("shipping_zones", method='GET', body=self.load_fixture('shipping_zones')) + shipping_zones = shopify.ShippingZone.find() + self.assertEqual(1,len(shipping_zones)) + self.assertEqual(shipping_zones[0].name,"Some zone") + self.assertEqual(3,len(shipping_zones[0].countries)) +
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": [], "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pyactiveresource==2.2.2 pytest==8.3.5 PyYAML==6.0.2 -e git+https://github.com/Shopify/shopify_python_api.git@28c00a110c23edc5287d6e8f90f0e36f0eb5d1b3#egg=ShopifyAPI six==1.17.0 tomli==2.2.1
name: shopify_python_api channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pyactiveresource==2.2.2 - pytest==8.3.5 - pyyaml==6.0.2 - six==1.17.0 - tomli==2.2.1 prefix: /opt/conda/envs/shopify_python_api
[ "test/shipping_zone_test.py::ShippingZoneTest::test_get_shipping_zones" ]
[]
[]
[]
MIT License
332
213
[ "shopify/resources/__init__.py" ]
jupyter-incubator__sparkmagic-73
d9662c5c5b089976810dfe863437d86ae72ccf82
2015-12-18 01:53:03
d9662c5c5b089976810dfe863437d86ae72ccf82
diff --git a/remotespark/RemoteSparkMagics.py b/remotespark/RemoteSparkMagics.py index 361b91b..5271de0 100644 --- a/remotespark/RemoteSparkMagics.py +++ b/remotespark/RemoteSparkMagics.py @@ -55,30 +55,40 @@ class RemoteSparkMagics(Magics): Constants.context_name_sql, Constants.context_name_hive, Constants.context_name_spark)) - @argument("-e", "--endpoint", help="The name of the Livy endpoint to use. " - "If only one endpoint has been created, there's no need to specify one.") + @argument("-s", "--session", help="The name of the Livy session to use. " + "If only one session has been created, there's no need to specify one.") @argument("-t", "--chart", type=str, default="area", help='Chart type to use: table, area, line, bar.') @argument("command", type=str, default=[""], nargs="*", help="Commands to execute.") @line_cell_magic def spark(self, line, cell=""): - """Magic to execute spark remotely. - If invoked with no subcommand, the code will be executed against the specified endpoint. + """Magic to execute spark remotely. + + This magic allows you to create a Livy Scala or Python session against a Livy endpoint. Every session can + be used to execute either Spark code or SparkSQL code by executing against the SQL context in the session. + When the SQL context is used, the result will be a Pandas dataframe of a sample of the results. + + If invoked with no subcommand, the cell will be executed against the specified session. Subcommands ----------- info - Display the mode and available Livy endpoints. + Display the mode and available Livy sessions. add - Add a Livy endpoint. First argument is the friendly name of the endpoint, second argument - is the language, and third argument is the connection string. A fourth argument specifying if - endpoint can be skipped if already present is optional: "skip" or empty. + Add a Livy session. First argument is the name of the session, second argument + is the language, and third argument is the connection string of the Livy endpoint. + A fourth argument specifying if session creation can be skipped if it already exists is optional: + "skip" or empty. e.g. `%%spark add test python url=https://sparkcluster.example.net/livy;username=admin;password=MyPassword skip` or e.g. `%%spark add test python url=https://sparkcluster.example.net/livy;username=admin;password=MyPassword` + run + Run Spark code against a session. + e.g. `%%spark -e testsession` will execute the cell code against the testsession previously created + e.g. `%%spark -e testsession -c sql` will execute the SQL code against the testsession previously created delete - Delete a Livy endpoint. Argument is the friendly name of the endpoint to be deleted. + Delete a Livy session. Argument is the name of the session to be deleted. e.g. `%%spark delete defaultlivy` cleanup - Delete all Livy endpoints. No arguments required. + Delete all Livy sessions created by the notebook. No arguments required. e.g. `%%spark cleanup` """ usage = "Please look at usage of %spark by executing `%spark?`." @@ -102,13 +112,13 @@ class RemoteSparkMagics(Magics): skip = args.command[4].lower() == "skip" else: skip = False - self.spark_controller.add_endpoint(name, language, connection_string, skip) + self.spark_controller.add_session(name, language, connection_string, skip) # delete elif subcommand == "delete": if len(args.command) != 2: raise ValueError("Subcommand 'delete' requires an argument. {}".format(usage)) name = args.command[1].lower() - self.spark_controller.delete_endpoint(name) + self.spark_controller.delete_session(name) # cleanup elif subcommand == "cleanup": self.spark_controller.cleanup() @@ -116,7 +126,7 @@ class RemoteSparkMagics(Magics): elif len(subcommand) == 0: if args.context == Constants.context_name_spark: (success, out) = self.spark_controller.run_cell(cell, - args.endpoint) + args.session) if success: self.ipython.write(out) else: @@ -124,13 +134,13 @@ class RemoteSparkMagics(Magics): elif args.context == Constants.context_name_sql: try: return self.spark_controller.run_cell_sql(cell, - args.endpoint) + args.session) except DataFrameParseException as e: self.ipython.write_err(e.out) elif args.context == Constants.context_name_hive: try: return self.spark_controller.run_cell_hive(cell, - args.endpoint) + args.session) except DataFrameParseException as e: self.ipython.write_err(e.out) else: diff --git a/remotespark/livyclientlib/clientmanager.py b/remotespark/livyclientlib/clientmanager.py index d6466ae..e253735 100644 --- a/remotespark/livyclientlib/clientmanager.py +++ b/remotespark/livyclientlib/clientmanager.py @@ -41,12 +41,12 @@ class ClientManager(object): def _serialize_state(self): self._serializer.serialize_state(self._livy_clients) - def get_endpoints_list(self): + def get_sessions_list(self): return list(self._livy_clients.keys()) def add_client(self, name, livy_client): - if name in self.get_endpoints_list(): - raise ValueError("Endpoint with name '{}' already exists. Please delete the endpoint" + if name in self.get_sessions_list(): + raise ValueError("Session with name '{}' already exists. Please delete the session" " first if you intend to replace it.".format(name)) self._livy_clients[name] = livy_client @@ -54,34 +54,34 @@ class ClientManager(object): def get_any_client(self): number_of_sessions = len(self._livy_clients) if number_of_sessions == 1: - key = self.get_endpoints_list()[0] + key = self.get_sessions_list()[0] return self._livy_clients[key] elif number_of_sessions == 0: raise AssertionError("You need to have at least 1 client created to execute commands.") else: - raise AssertionError("Please specify the client to use. Possible endpoints are {}".format( - self.get_endpoints_list())) + raise AssertionError("Please specify the client to use. Possible sessions are {}".format( + self.get_sessions_list())) def get_client(self, name): - if name in self.get_endpoints_list(): + if name in self.get_sessions_list(): return self._livy_clients[name] - raise ValueError("Could not find '{}' endpoint in list of saved endpoints. Possible endpoints are {}".format( - name, self.get_endpoints_list())) + raise ValueError("Could not find '{}' session in list of saved sessions. Possible sessions are {}".format( + name, self.get_sessions_list())) def delete_client(self, name): - self._remove_endpoint(name) + self._remove_session(name) def clean_up_all(self): - for name in self.get_endpoints_list(): - self._remove_endpoint(name) + for name in self.get_sessions_list(): + self._remove_session(name) if self._serializer is not None: self._serialize_state() - def _remove_endpoint(self, name): - if name in self.get_endpoints_list(): + def _remove_session(self, name): + if name in self.get_sessions_list(): self._livy_clients[name].close_session() del self._livy_clients[name] else: - raise ValueError("Could not find '{}' endpoint in list of saved endpoints. Possible endpoints are {}" - .format(name, self.get_endpoints_list())) + raise ValueError("Could not find '{}' session in list of saved sessions. Possible sessions are {}" + .format(name, self.get_sessions_list())) diff --git a/remotespark/livyclientlib/livyclient.py b/remotespark/livyclientlib/livyclient.py index 87fb395..dedefbb 100644 --- a/remotespark/livyclientlib/livyclient.py +++ b/remotespark/livyclientlib/livyclient.py @@ -7,7 +7,7 @@ from .constants import Constants class LivyClient(object): - """Spark client for Livy endpoint""" + """Spark client for Livy session""" def __init__(self, session): self.logger = Log("LivyClient") diff --git a/remotespark/livyclientlib/livyclientfactory.py b/remotespark/livyclientlib/livyclientfactory.py index 85443b3..2b89045 100644 --- a/remotespark/livyclientlib/livyclientfactory.py +++ b/remotespark/livyclientlib/livyclientfactory.py @@ -11,7 +11,7 @@ from .linearretrypolicy import LinearRetryPolicy class LivyClientFactory(object): - """Spark client for Livy endpoint""" + """Spark client factory""" def __init__(self): self.logger = Log("LivyClientFactory") diff --git a/remotespark/livyclientlib/pandaslivyclientbase.py b/remotespark/livyclientlib/pandaslivyclientbase.py index 692c5d0..72852f1 100644 --- a/remotespark/livyclientlib/pandaslivyclientbase.py +++ b/remotespark/livyclientlib/pandaslivyclientbase.py @@ -5,7 +5,7 @@ from .livyclient import LivyClient from .dataframeparseexception import DataFrameParseException class PandasLivyClientBase(LivyClient): - """Spark client for Livy endpoint that produces pandas df for sql and hive commands.""" + """Spark client for Livy session that produces pandas df for sql and hive commands.""" def __init__(self, session, max_take_rows): super(PandasLivyClientBase, self).__init__(session) self.max_take_rows = max_take_rows diff --git a/remotespark/livyclientlib/pandaspysparklivyclient.py b/remotespark/livyclientlib/pandaspysparklivyclient.py index edf6abb..81c5123 100644 --- a/remotespark/livyclientlib/pandaspysparklivyclient.py +++ b/remotespark/livyclientlib/pandaspysparklivyclient.py @@ -7,7 +7,7 @@ import json from .pandaslivyclientbase import PandasLivyClientBase class PandasPysparkLivyClient(PandasLivyClientBase): - """Spark client for Livy endpoint in PySpark""" + """Spark client for Livy session in PySpark""" def __init__(self, session, max_take_rows): super(PandasPysparkLivyClient, self).__init__(session, max_take_rows) diff --git a/remotespark/livyclientlib/pandasscalalivyclient.py b/remotespark/livyclientlib/pandasscalalivyclient.py index 5b9e031..8bb1ea8 100644 --- a/remotespark/livyclientlib/pandasscalalivyclient.py +++ b/remotespark/livyclientlib/pandasscalalivyclient.py @@ -8,7 +8,7 @@ import re from .pandaslivyclientbase import PandasLivyClientBase class PandasScalaLivyClient(PandasLivyClientBase): - """Spark client for Livy endpoint in Scala""" + """Spark client for Livy session in Scala""" def __init__(self, session, max_take_rows): super(PandasScalaLivyClient, self).__init__(session, max_take_rows) diff --git a/remotespark/livyclientlib/sparkcontroller.py b/remotespark/livyclientlib/sparkcontroller.py index 4ab4dd2..d736011 100644 --- a/remotespark/livyclientlib/sparkcontroller.py +++ b/remotespark/livyclientlib/sparkcontroller.py @@ -1,6 +1,3 @@ -"""Runs Scala, PySpark and SQL statement through Spark using a REST endpoint in remote cluster. -Provides the %spark magic.""" - # Copyright (c) 2015 [email protected] # Distributed under the terms of the Modified BSD License. @@ -38,12 +35,12 @@ class SparkController(object): def cleanup(self): self.client_manager.clean_up_all() - def delete_endpoint(self, name): + def delete_session(self, name): self.client_manager.delete_client(name) - def add_endpoint(self, name, language, connection_string, skip_if_exists): - if skip_if_exists and (name in self.client_manager.get_endpoints_list()): - self.logger.debug("Skipping {} because it already exists in list of endpoints.".format(name)) + def add_session(self, name, language, connection_string, skip_if_exists): + if skip_if_exists and (name in self.client_manager.get_sessions_list()): + self.logger.debug("Skipping {} because it already exists in list of sessions.".format(name)) return session = self.client_factory.create_session(language, connection_string, "-1", False) @@ -52,7 +49,7 @@ class SparkController(object): self.client_manager.add_client(name, livy_client) def get_client_keys(self): - return self.client_manager.get_endpoints_list() + return self.client_manager.get_sessions_list() def get_client_by_name_or_default(self, client_name): if client_name is None: diff --git a/remotespark/sparkkernelbase.py b/remotespark/sparkkernelbase.py index b842b76..d8074f7 100644 --- a/remotespark/sparkkernelbase.py +++ b/remotespark/sparkkernelbase.py @@ -81,11 +81,11 @@ class SparkKernelBase(IPythonKernel): self.already_ran_once = True - add_endpoint_code = "%spark add {} {} {} skip".format( + add_session_code = "%spark add {} {} {} skip".format( self.client_name, self.session_language, connection_string) - self._execute_cell(add_endpoint_code, True, False, shutdown_if_error=True, + self._execute_cell(add_session_code, True, False, shutdown_if_error=True, log_if_error="Failed to create a Livy session.") - self.logger.debug("Added endpoint.") + self.logger.debug("Added session.") def _get_configuration(self): try:
Rename --endpoint param to magics to --session Make -e be -s
jupyter-incubator/sparkmagic
diff --git a/tests/test_clientmanager.py b/tests/test_clientmanager.py index 3376082..b1ef425 100644 --- a/tests/test_clientmanager.py +++ b/tests/test_clientmanager.py @@ -18,13 +18,13 @@ def test_deserialize_on_creation(): serializer.deserialize_state.return_value = [("py", None), ("sc", None)] manager = ClientManager(serializer) - assert "py" in manager.get_endpoints_list() - assert "sc" in manager.get_endpoints_list() + assert "py" in manager.get_sessions_list() + assert "sc" in manager.get_sessions_list() serializer = MagicMock() manager = ClientManager(serializer) - assert len(manager.get_endpoints_list()) == 0 + assert len(manager.get_sessions_list()) == 0 def test_serialize_periodically(): @@ -82,7 +82,7 @@ def test_client_names_returned(): manager.add_client("name0", client) manager.add_client("name1", client) - assert_equals({"name0", "name1"}, set(manager.get_endpoints_list())) + assert_equals({"name0", "name1"}, set(manager.get_sessions_list())) def test_get_any_client(): diff --git a/tests/test_remotesparkmagics.py b/tests/test_remotesparkmagics.py index 363849f..22a70b4 100644 --- a/tests/test_remotesparkmagics.py +++ b/tests/test_remotesparkmagics.py @@ -32,10 +32,10 @@ def test_info_command_parses(): @with_setup(_setup, _teardown) -def test_add_endpoint_command_parses(): +def test_add_sessions_command_parses(): # Do not skip - add_endpoint_mock = MagicMock() - spark_controller.add_endpoint = add_endpoint_mock + add_sessions_mock = MagicMock() + spark_controller.add_session = add_sessions_mock command = "add" name = "name" language = "python" @@ -44,11 +44,11 @@ def test_add_endpoint_command_parses(): magic.spark(line) - add_endpoint_mock.assert_called_once_with(name, language, connection_string, False) + add_sessions_mock.assert_called_once_with(name, language, connection_string, False) # Skip - add_endpoint_mock = MagicMock() - spark_controller.add_endpoint = add_endpoint_mock + add_sessions_mock = MagicMock() + spark_controller.add_session = add_sessions_mock command = "add" name = "name" language = "python" @@ -57,13 +57,13 @@ def test_add_endpoint_command_parses(): magic.spark(line) - add_endpoint_mock.assert_called_once_with(name, language, connection_string, True) + add_sessions_mock.assert_called_once_with(name, language, connection_string, True) @with_setup(_setup, _teardown) -def test_delete_endpoint_command_parses(): +def test_delete_sessions_command_parses(): mock_method = MagicMock() - spark_controller.delete_endpoint = mock_method + spark_controller.delete_session = mock_method command = "delete" name = "name" line = " ".join([command, name]) @@ -98,8 +98,8 @@ def test_run_cell_command_parses(): run_cell_method.return_value = (True, "") spark_controller.run_cell = run_cell_method - command = "-e" - name = "endpoint_name" + command = "-s" + name = "sessions_name" line = " ".join([command, name]) cell = "cell code" diff --git a/tests/test_sparkcontroller.py b/tests/test_sparkcontroller.py index 9dea184..4a20537 100644 --- a/tests/test_sparkcontroller.py +++ b/tests/test_sparkcontroller.py @@ -25,7 +25,7 @@ def _teardown(): @with_setup(_setup, _teardown) -def test_add_endpoint(): +def test_add_session(): name = "name" language = "python" connection_string = "url=http://location:port;username=name;password=word" @@ -34,7 +34,7 @@ def test_add_endpoint(): client_factory.create_session = MagicMock(return_value=session) client_factory.build_client = MagicMock(return_value=client) - controller.add_endpoint(name, language, connection_string, False) + controller.add_session(name, language, connection_string, False) client_factory.create_session.assert_called_once_with(language, connection_string, "-1", False) client_factory.build_client.assert_called_once_with(language, session) @@ -43,7 +43,7 @@ def test_add_endpoint(): @with_setup(_setup, _teardown) -def test_add_endpoint_skip(): +def test_add_session_skip(): name = "name" language = "python" connection_string = "url=http://location:port;username=name;password=word" @@ -52,8 +52,8 @@ def test_add_endpoint_skip(): client_factory.create_session = MagicMock(return_value=session) client_factory.build_client = MagicMock(return_value=client) - client_manager.get_endpoints_list.return_value = [name] - controller.add_endpoint(name, language, connection_string, True) + client_manager.get_sessions_list.return_value = [name] + controller.add_session(name, language, connection_string, True) assert client_factory.create_session.call_count == 0 assert client_factory.build_client.call_count == 0 @@ -62,10 +62,10 @@ def test_add_endpoint_skip(): @with_setup(_setup, _teardown) -def test_delete_endpoint(): +def test_delete_session(): name = "name" - controller.delete_endpoint(name) + controller.delete_session(name) client_manager.delete_client.assert_called_once_with(name) @@ -83,7 +83,7 @@ def test_run_cell(): default_client.execute = chosen_client.execute = MagicMock(return_value=(True,"")) client_manager.get_any_client = MagicMock(return_value=default_client) client_manager.get_client = MagicMock(return_value=chosen_client) - name = "endpoint_name" + name = "session_name" cell = "cell code" controller.run_cell(cell, name) @@ -107,4 +107,4 @@ def test_run_cell(): @with_setup(_setup, _teardown) def test_get_client_keys(): controller.get_client_keys() - client_manager.get_endpoints_list.assert_called_once_with() + client_manager.get_sessions_list.assert_called_once_with()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 9 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "mkdir ~/.sparkmagic", "cp remotespark/default_config.json ~/.sparkmagic/config.json" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
anyio==4.9.0 argon2-cffi==23.1.0 argon2-cffi-bindings==21.2.0 arrow==1.3.0 async-lru==2.0.5 attrs==25.3.0 babel==2.17.0 beautifulsoup4==4.13.3 bleach==6.2.0 certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 comm==0.2.2 decorator==5.2.1 defusedxml==0.7.1 exceptiongroup==1.2.2 fastjsonschema==2.21.1 fqdn==1.5.1 h11==0.14.0 httpcore==1.0.7 httpx==0.28.1 idna==3.10 importlib_metadata==8.6.1 iniconfig==2.1.0 ipykernel==4.1.1 ipython==4.0.0 ipython-genutils==0.2.0 ipywidgets==7.8.5 isoduration==20.11.0 Jinja2==3.1.6 json5==0.10.0 jsonpointer==3.0.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 jupyter-events==0.12.0 jupyter-lsp==2.2.5 jupyter_client==8.6.3 jupyter_core==5.7.2 jupyter_server==2.15.0 jupyter_server_terminals==0.5.3 jupyterlab==4.1.5 jupyterlab_pygments==0.3.0 jupyterlab_server==2.27.3 jupyterlab_widgets==1.1.11 MarkupSafe==3.0.2 mistune==3.1.3 mock==5.2.0 narwhals==1.32.0 nbclient==0.10.2 nbconvert==7.16.6 nbformat==5.10.4 nose==1.3.7 notebook==7.1.3 notebook_shim==0.2.4 numpy==2.0.2 overrides==7.7.0 packaging==24.2 pandas==2.2.3 pandocfilters==1.5.1 pexpect==4.9.0 pickleshare==0.7.5 platformdirs==4.3.7 plotly==6.0.1 pluggy==1.5.0 prometheus_client==0.21.1 ptyprocess==0.7.0 pycparser==2.22 Pygments==2.19.1 pytest==8.3.5 python-dateutil==2.9.0.post0 python-json-logger==3.3.0 pytz==2025.2 PyYAML==6.0.2 pyzmq==26.3.0 referencing==0.36.2 -e git+https://github.com/jupyter-incubator/sparkmagic.git@d9662c5c5b089976810dfe863437d86ae72ccf82#egg=remotespark requests==2.32.3 rfc3339-validator==0.1.4 rfc3986-validator==0.1.1 rpds-py==0.24.0 Send2Trash==1.8.3 simplegeneric==0.8.1 six==1.17.0 sniffio==1.3.1 soupsieve==2.6 terminado==0.18.1 tinycss2==1.4.0 tomli==2.2.1 tornado==6.4.2 traitlets==5.14.3 types-python-dateutil==2.9.0.20241206 typing_extensions==4.13.0 tzdata==2025.2 uri-template==1.3.0 urllib3==2.3.0 webcolors==24.11.1 webencodings==0.5.1 websocket-client==1.8.0 widgetsnbextension==3.6.10 zipp==3.21.0
name: sparkmagic channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - anyio==4.9.0 - argon2-cffi==23.1.0 - argon2-cffi-bindings==21.2.0 - arrow==1.3.0 - async-lru==2.0.5 - attrs==25.3.0 - babel==2.17.0 - beautifulsoup4==4.13.3 - bleach==6.2.0 - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - comm==0.2.2 - decorator==5.2.1 - defusedxml==0.7.1 - exceptiongroup==1.2.2 - fastjsonschema==2.21.1 - fqdn==1.5.1 - h11==0.14.0 - httpcore==1.0.7 - httpx==0.28.1 - idna==3.10 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - ipykernel==4.1.1 - ipython==4.0.0 - ipython-genutils==0.2.0 - ipywidgets==7.8.5 - isoduration==20.11.0 - jinja2==3.1.6 - json5==0.10.0 - jsonpointer==3.0.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - jupyter-client==8.6.3 - jupyter-core==5.7.2 - jupyter-events==0.12.0 - jupyter-lsp==2.2.5 - jupyter-server==2.15.0 - jupyter-server-terminals==0.5.3 - jupyterlab==4.1.5 - jupyterlab-pygments==0.3.0 - jupyterlab-server==2.27.3 - jupyterlab-widgets==1.1.11 - markupsafe==3.0.2 - mistune==3.1.3 - mock==5.2.0 - narwhals==1.32.0 - nbclient==0.10.2 - nbconvert==7.16.6 - nbformat==5.10.4 - nose==1.3.7 - notebook==7.1.3 - notebook-shim==0.2.4 - numpy==2.0.2 - overrides==7.7.0 - packaging==24.2 - pandas==2.2.3 - pandocfilters==1.5.1 - pexpect==4.9.0 - pickleshare==0.7.5 - platformdirs==4.3.7 - plotly==6.0.1 - pluggy==1.5.0 - prometheus-client==0.21.1 - ptyprocess==0.7.0 - pycparser==2.22 - pygments==2.19.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-json-logger==3.3.0 - pytz==2025.2 - pyyaml==6.0.2 - pyzmq==26.3.0 - referencing==0.36.2 - requests==2.32.3 - rfc3339-validator==0.1.4 - rfc3986-validator==0.1.1 - rpds-py==0.24.0 - send2trash==1.8.3 - simplegeneric==0.8.1 - six==1.17.0 - sniffio==1.3.1 - soupsieve==2.6 - terminado==0.18.1 - tinycss2==1.4.0 - tomli==2.2.1 - tornado==6.4.2 - traitlets==5.14.3 - types-python-dateutil==2.9.0.20241206 - typing-extensions==4.13.0 - tzdata==2025.2 - uri-template==1.3.0 - urllib3==2.3.0 - webcolors==24.11.1 - webencodings==0.5.1 - websocket-client==1.8.0 - widgetsnbextension==3.6.10 - zipp==3.21.0 prefix: /opt/conda/envs/sparkmagic
[ "tests/test_clientmanager.py::test_deserialize_on_creation", "tests/test_clientmanager.py::test_client_names_returned" ]
[ "tests/test_remotesparkmagics.py::test_info_command_parses", "tests/test_remotesparkmagics.py::test_add_sessions_command_parses", "tests/test_remotesparkmagics.py::test_delete_sessions_command_parses", "tests/test_remotesparkmagics.py::test_cleanup_command_parses", "tests/test_remotesparkmagics.py::test_bad_command_throws_exception", "tests/test_remotesparkmagics.py::test_run_cell_command_parses", "tests/test_sparkcontroller.py::test_add_session", "tests/test_sparkcontroller.py::test_add_session_skip", "tests/test_sparkcontroller.py::test_delete_session", "tests/test_sparkcontroller.py::test_cleanup", "tests/test_sparkcontroller.py::test_run_cell", "tests/test_sparkcontroller.py::test_get_client_keys" ]
[ "tests/test_clientmanager.py::test_get_client_throws_when_client_not_exists", "tests/test_clientmanager.py::test_serialize_periodically", "tests/test_clientmanager.py::test_get_client", "tests/test_clientmanager.py::test_delete_client", "tests/test_clientmanager.py::test_delete_client_throws_when_client_not_exists", "tests/test_clientmanager.py::test_add_client_throws_when_client_exists", "tests/test_clientmanager.py::test_get_any_client", "tests/test_clientmanager.py::test_get_any_client_raises_exception_with_no_client", "tests/test_clientmanager.py::test_get_any_client_raises_exception_with_two_clients", "tests/test_clientmanager.py::test_clean_up", "tests/test_clientmanager.py::test_clean_up_serializer" ]
[]
Modified BSD License
340
3,432
[ "remotespark/RemoteSparkMagics.py", "remotespark/livyclientlib/clientmanager.py", "remotespark/livyclientlib/livyclient.py", "remotespark/livyclientlib/livyclientfactory.py", "remotespark/livyclientlib/pandaslivyclientbase.py", "remotespark/livyclientlib/pandaspysparklivyclient.py", "remotespark/livyclientlib/pandasscalalivyclient.py", "remotespark/livyclientlib/sparkcontroller.py", "remotespark/sparkkernelbase.py" ]
joke2k__faker-314
9f338881f582807fd9d1339b6148b039f8141bb3
2015-12-18 19:49:49
883576c2d718ad7f604415e02a898f1f917d5b86
diff --git a/faker/providers/misc/__init__.py b/faker/providers/misc/__init__.py index 32531a60..9b318691 100644 --- a/faker/providers/misc/__init__.py +++ b/faker/providers/misc/__init__.py @@ -88,13 +88,33 @@ class Provider(BaseProvider): @param lower_case: Boolean. Whether to use lower letters @return: String. Random password """ - chars = "" + choices = "" + required_tokens = [] if special_chars: - chars += "!@#$%^&*()_+" + required_tokens.append(random.choice("!@#$%^&*()_+")) + choices += "!@#$%^&*()_+" if digits: - chars += string.digits + required_tokens.append(random.choice(string.digits)) + choices += string.digits if upper_case: - chars += string.ascii_uppercase + required_tokens.append(random.choice(string.ascii_uppercase)) + choices += string.ascii_uppercase if lower_case: - chars += string.ascii_lowercase - return ''.join(random.choice(chars) for x in range(length)) + required_tokens.append(random.choice(string.ascii_lowercase)) + choices += string.ascii_lowercase + + assert len(required_tokens) <= length, "Required length is shorter than required characters" + + # Generate a first version of the password + chars = [random.choice(choices) for x in range(length)] + + # Pick some unique locations + random_indexes = set() + while len(random_indexes) < len(required_tokens): + random_indexes.add(random.randint(0, len(chars) - 1)) + + # Replace them with the required characters + for i, index in enumerate(random_indexes): + chars[index] = required_tokens[i] + + return ''.join(chars)
Param switches on faker.password() don't guarantee valid password The format switches on `faker.password()` (`special_chars, digits, upper_case, lower_case`) don't always return passwords matching those rules. This is problematic as when using generated passwords in unit tests, where passwords must conform to validity rules (e.g. "must contain numbers"), tests can randomly fail. I expected that these switches would guarantee the function returns a conforming password. e.g. `faker.password(digits=True)` always returns a password containing digits, but this is not the case.
joke2k/faker
diff --git a/faker/tests/__init__.py b/faker/tests/__init__.py index 4eeaa3c7..6502a448 100644 --- a/faker/tests/__init__.py +++ b/faker/tests/__init__.py @@ -9,6 +9,7 @@ import json import os import time import unittest +import string import sys try: @@ -458,6 +459,22 @@ class FactoryTestCase(unittest.TestCase): datetime.datetime.now(utc).replace(second=0, microsecond=0) ) + def test_password(self): + from faker.providers.misc import Provider + + def in_string(char, _str): + return char in _str + + for _ in range(999): + password = Provider.password() + + self.assertTrue(any([in_string(char, password) for char in "!@#$%^&*()_+"])) + self.assertTrue(any([in_string(char, password) for char in string.digits])) + self.assertTrue(any([in_string(char, password) for char in string.ascii_uppercase])) + self.assertTrue(any([in_string(char, password) for char in string.ascii_lowercase])) + + self.assertRaises(AssertionError, Provider.password, length=2) + def test_prefix_suffix_always_string(self): # Locales known to contain `*_male` and `*_female`. for locale in ("bg_BG", "dk_DK", "en", "ru_RU", "tr_TR"):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "faker/tests/requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
dnspython==2.7.0 email_validator==2.2.0 exceptiongroup==1.2.2 -e git+https://github.com/joke2k/faker.git@9f338881f582807fd9d1339b6148b039f8141bb3#egg=fake_factory idna==3.10 iniconfig==2.1.0 mock==1.0.1 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 six==1.17.0 tomli==2.2.1 UkPostcodeParser==1.0.3
name: faker channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - dnspython==2.7.0 - email-validator==2.2.0 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - mock==1.0.1 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - six==1.17.0 - tomli==2.2.1 - ukpostcodeparser==1.0.3 prefix: /opt/conda/envs/faker
[ "faker/tests/__init__.py::FactoryTestCase::test_password" ]
[]
[ "faker/tests/__init__.py::ShimsTestCase::test_counter", "faker/tests/__init__.py::UtilsTestCase::test_add_dicts", "faker/tests/__init__.py::UtilsTestCase::test_choice_distribution", "faker/tests/__init__.py::UtilsTestCase::test_find_available_locales", "faker/tests/__init__.py::UtilsTestCase::test_find_available_providers", "faker/tests/__init__.py::FactoryTestCase::test_add_provider_gives_priority_to_newly_added_provider", "faker/tests/__init__.py::FactoryTestCase::test_command", "faker/tests/__init__.py::FactoryTestCase::test_command_custom_provider", "faker/tests/__init__.py::FactoryTestCase::test_date_time_between_dates", "faker/tests/__init__.py::FactoryTestCase::test_date_time_between_dates_with_tzinfo", "faker/tests/__init__.py::FactoryTestCase::test_date_time_this_period", "faker/tests/__init__.py::FactoryTestCase::test_date_time_this_period_with_tzinfo", "faker/tests/__init__.py::FactoryTestCase::test_datetime_safe", "faker/tests/__init__.py::FactoryTestCase::test_datetimes_with_and_without_tzinfo", "faker/tests/__init__.py::FactoryTestCase::test_documentor", "faker/tests/__init__.py::FactoryTestCase::test_format_calls_formatter_on_provider", "faker/tests/__init__.py::FactoryTestCase::test_format_transfers_arguments_to_formatter", "faker/tests/__init__.py::FactoryTestCase::test_get_formatter_returns_callable", "faker/tests/__init__.py::FactoryTestCase::test_get_formatter_returns_correct_formatter", "faker/tests/__init__.py::FactoryTestCase::test_get_formatter_throws_exception_on_incorrect_formatter", "faker/tests/__init__.py::FactoryTestCase::test_magic_call_calls_format", "faker/tests/__init__.py::FactoryTestCase::test_magic_call_calls_format_with_arguments", "faker/tests/__init__.py::FactoryTestCase::test_no_words_paragraph", "faker/tests/__init__.py::FactoryTestCase::test_no_words_sentence", "faker/tests/__init__.py::FactoryTestCase::test_parse_returns_same_string_when_it_contains_no_curly_braces", "faker/tests/__init__.py::FactoryTestCase::test_parse_returns_string_with_tokens_replaced_by_formatters", "faker/tests/__init__.py::FactoryTestCase::test_prefix_suffix_always_string", "faker/tests/__init__.py::FactoryTestCase::test_random_element", "faker/tests/__init__.py::FactoryTestCase::test_slugify", "faker/tests/__init__.py::FactoryTestCase::test_timezone_conversion", "faker/tests/__init__.py::FactoryTestCase::test_us_ssn_valid", "faker/tests/__init__.py::GeneratorTestCase::test_random_seed_doesnt_seed_system_random" ]
[]
MIT License
341
426
[ "faker/providers/misc/__init__.py" ]
mogproject__color-ssh-11
9adb19916b0205fd6a88beddcd8669114edc449c
2015-12-23 11:42:42
8ef23299ceb4e19e5d33562edb0066686eead51d
diff --git a/src/color_ssh/__init__.py b/src/color_ssh/__init__.py index b794fd4..df9144c 100644 --- a/src/color_ssh/__init__.py +++ b/src/color_ssh/__init__.py @@ -1,1 +1,1 @@ -__version__ = '0.1.0' +__version__ = '0.1.1' diff --git a/src/color_ssh/color_cat.py b/src/color_ssh/color_cat.py index a9d1412..036ced8 100644 --- a/src/color_ssh/color_cat.py +++ b/src/color_ssh/color_cat.py @@ -68,8 +68,9 @@ def main(argv=sys.argv, stdin=io2bytes(sys.stdin), stdout=io2bytes(sys.stdout), """ setting = Setting().parse_args(argv, stdout) - # Note: Do not use 'fileinput' module because it causes a buffering problem. - try: + @exception_handler(lambda e: stderr.write(('%s: %s\n' % (e.__class__.__name__, e)).encode('utf-8', 'ignore'))) + def f(): + # Note: Do not use 'fileinput' module because it causes a buffering problem. for path in setting.paths: fh = stdin if path is None else io.open(path, 'rb', 0) try: @@ -79,9 +80,6 @@ def main(argv=sys.argv, stdin=io2bytes(sys.stdin), stdout=io2bytes(sys.stdout), finally: if fh is not stdin: fh.close() + return 0 - except Exception as e: - stderr.write(('%s: %s\n' % (e.__class__.__name__, e)).encode('utf-8', 'ignore')) - return 1 - - return 0 + return f() diff --git a/src/color_ssh/color_ssh.py b/src/color_ssh/color_ssh.py index f8d82d8..1d2e798 100644 --- a/src/color_ssh/color_ssh.py +++ b/src/color_ssh/color_ssh.py @@ -106,7 +106,12 @@ def run_task(args): prefix = ['color-cat', '-l', label] - try: + def exc_func(e): + msg = '%s: %s\nlabel=%s, command=%s\n' % (e.__class__.__name__, e, label, command) + stderr.write(msg.encode('utf-8', 'ignore')) + + @exception_handler(exc_func) + def f(): proc_stdout = subprocess.Popen(prefix, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr) proc_stderr = subprocess.Popen(prefix + ['-s', '+'], stdin=subprocess.PIPE, stdout=stderr, stderr=stderr) ret = subprocess.call(command, stdin=None, stdout=proc_stdout.stdin, stderr=proc_stderr.stdin) @@ -116,11 +121,9 @@ def run_task(args): proc_stdout.wait() proc_stderr.wait() - except Exception as e: - msg = '%s: %s\nlabel=%s, command=%s\n' % (e.__class__.__name__, e, label, command) - stderr.write(msg.encode('utf-8', 'ignore')) - return 1 - return ret + return ret + + return f() def main(argv=sys.argv, stdout=io2bytes(sys.stdout), stderr=io2bytes(sys.stderr)): @@ -128,7 +131,8 @@ def main(argv=sys.argv, stdout=io2bytes(sys.stdout), stderr=io2bytes(sys.stderr) Main function """ - try: + @exception_handler(lambda e: stderr.write(('%s: %s\n' % (e.__class__.__name__, e)).encode('utf-8', 'ignore'))) + def f(): setting = Setting().parse_args(argv, stdout) n = min(len(setting.tasks), setting.parallelism) if n <= 1: @@ -136,9 +140,6 @@ def main(argv=sys.argv, stdout=io2bytes(sys.stdout), stderr=io2bytes(sys.stderr) else: pool = Pool(n) ret = pool.map(run_task, setting.tasks) - except Exception as e: - msg = '%s: %s\n' % (e.__class__.__name__, e) - stderr.write(msg.encode('utf-8', 'ignore')) - return 1 + return max(ret) - return max(ret) + return f() diff --git a/src/color_ssh/util/util.py b/src/color_ssh/util/util.py index e1cdb8a..8bdea63 100644 --- a/src/color_ssh/util/util.py +++ b/src/color_ssh/util/util.py @@ -3,7 +3,7 @@ from __future__ import division, print_function, absolute_import, unicode_litera import sys import os -__all__ = ['PY3', 'arg2bytes', 'io2bytes', 'distribute'] +__all__ = ['PY3', 'arg2bytes', 'io2bytes', 'distribute', 'exception_handler'] PY3 = sys.version_info >= (3,) @@ -37,3 +37,24 @@ def distribute(num_workers, tasks): ret.append(tasks[j:j + k]) j += k return ret + + +# +# Decorators +# +def exception_handler(exception_func): + def f(func): + import functools + + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except KeyboardInterrupt: + return 130 + except Exception as e: + exception_func(e) + return 1 + + return wrapper + return f
Kill all processes when interrupted by keyboard
mogproject/color-ssh
diff --git a/tests/color_ssh/util/__init__.py b/tests/color_ssh/util/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/color_ssh/util/test_util.py b/tests/color_ssh/util/test_util.py new file mode 100644 index 0000000..50082dc --- /dev/null +++ b/tests/color_ssh/util/test_util.py @@ -0,0 +1,13 @@ +from __future__ import division, print_function, absolute_import, unicode_literals + +from mog_commons.unittest import TestCase +from color_ssh.util.util import exception_handler + + +class TestUtil(TestCase): + def test_exception_handler(self): + @exception_handler(lambda e: e) + def f(): + raise KeyboardInterrupt + + self.assertEqual(f(), 130)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 4 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pep8", "coverage", "six", "mog-commons" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 -e git+https://github.com/mogproject/color-ssh.git@9adb19916b0205fd6a88beddcd8669114edc449c#egg=color_ssh coverage==6.2 importlib-metadata==4.8.3 iniconfig==1.1.1 Jinja2==3.0.3 MarkupSafe==2.0.1 mog-commons==0.2.3 packaging==21.3 pep8==1.7.1 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: color-ssh channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==6.2 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jinja2==3.0.3 - markupsafe==2.0.1 - mog-commons==0.2.3 - packaging==21.3 - pep8==1.7.1 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/color-ssh
[ "tests/color_ssh/util/test_util.py::TestUtil::test_exception_handler" ]
[]
[]
[]
null
351
1,327
[ "src/color_ssh/__init__.py", "src/color_ssh/color_cat.py", "src/color_ssh/color_ssh.py", "src/color_ssh/util/util.py" ]
mogproject__color-ssh-12
b39783565319ee50b34988c29193f02a90122e2c
2015-12-26 06:06:56
8ef23299ceb4e19e5d33562edb0066686eead51d
diff --git a/src/color_ssh/__init__.py b/src/color_ssh/__init__.py index df9144c..10939f0 100644 --- a/src/color_ssh/__init__.py +++ b/src/color_ssh/__init__.py @@ -1,1 +1,1 @@ -__version__ = '0.1.1' +__version__ = '0.1.2' diff --git a/src/color_ssh/color_ssh.py b/src/color_ssh/color_ssh.py index 1d2e798..e575962 100644 --- a/src/color_ssh/color_ssh.py +++ b/src/color_ssh/color_ssh.py @@ -4,6 +4,7 @@ import sys import io import shlex import subprocess +import re from optparse import OptionParser from multiprocessing.pool import Pool from color_ssh.util.util import * @@ -64,20 +65,25 @@ class Setting(object): stdout.write(arg2bytes(parser.format_help().encode('utf-8'))) parser.exit(2) - prefix = shlex.split(option.ssh) - if not hosts: hosts = args[:1] del args[0] - # distribute args + # parse hosts + parsed_hosts = [self._parse_host(h) for h in hosts] + + tasks = [] if option.distribute: + # distribute args dist_prefix = shlex.split(option.distribute) d = distribute(len(hosts), args) - tasks = [(option.label or self._extract_label(host), - prefix + [host] + dist_prefix + d[i]) for i, host in enumerate(hosts) if d[i]] + for i, (user, host, port) in enumerate(parsed_hosts): + if d[i]: + label = option.label or host + tasks.append((label, self._ssh_args(option.ssh, user, host, port) + dist_prefix + d[i])) else: - tasks = [(option.label or self._extract_label(host), prefix + [host] + args) for host in hosts] + for user, host, port in parsed_hosts: + tasks.append((option.label or host, self._ssh_args(option.ssh, user, host, port) + args)) self.parallelism = option.parallelism self.tasks = tasks @@ -93,8 +99,20 @@ class Setting(object): return list(filter(lambda x: x, (line.strip() for line in lines))) @staticmethod - def _extract_label(host): - return host.rsplit('@', 1)[-1] + def _parse_host(s): + """ + :param s: string : [user@]host[:port] + :return: tuple of (user, host, port) + """ + ret = re.match('^(?:([^:@]+)@)?([^:@]+)(?::(\d+))?$', s) + if not ret: + raise ValueError('Illegal format: %s' % s) + return ret.groups() + + @staticmethod + def _ssh_args(ssh_cmd, user, host, port): + user_host = [('' if user is None else '%s@' % user) + host] + return shlex.split(ssh_cmd) + ([] if port is None else ['-p', port]) + user_host def run_task(args):
Support port option in host list and host string
mogproject/color-ssh
diff --git a/tests/color_ssh/test_color_ssh.py b/tests/color_ssh/test_color_ssh.py index 67684f8..e2fc45a 100644 --- a/tests/color_ssh/test_color_ssh.py +++ b/tests/color_ssh/test_color_ssh.py @@ -62,14 +62,15 @@ class TestSetting(TestCase): ('server-4', ['ssh', 'server-4', 'pwd']), ('server-5', ['ssh', 'server-5', 'pwd']), ('server-6', ['ssh', 'server-6', 'pwd']), - ('server-7', ['ssh', 'server-7', 'pwd']), - ('server-8', ['ssh', 'server-8', 'pwd']), + ('server-7', ['ssh', '-p', '22', 'server-7', 'pwd']), + ('server-8', ['ssh', '-p', '1022', 'server-8', 'pwd']), ('server-9', ['ssh', 'root@server-9', 'pwd']), - ('server-10', ['ssh', 'root@server-10', 'pwd']), + ('server-10', ['ssh', '-p', '1022', 'root@server-10', 'pwd']), ]) - self._check(self._parse(['-H', 'server-11 root@server-12', 'pwd']), [ + self._check(self._parse(['-H', 'server-11 root@server-12 root@server-13:1022', 'pwd']), [ ('server-11', ['ssh', 'server-11', 'pwd']), ('server-12', ['ssh', 'root@server-12', 'pwd']), + ('server-13', ['ssh', '-p', '1022', 'root@server-13', 'pwd']), ]) self._check(self._parse(['--hosts', hosts_path, '--host', 'server-11 root@server-12', 'pwd']), [ ('server-1', ['ssh', 'server-1', 'pwd']), @@ -78,10 +79,10 @@ class TestSetting(TestCase): ('server-4', ['ssh', 'server-4', 'pwd']), ('server-5', ['ssh', 'server-5', 'pwd']), ('server-6', ['ssh', 'server-6', 'pwd']), - ('server-7', ['ssh', 'server-7', 'pwd']), - ('server-8', ['ssh', 'server-8', 'pwd']), + ('server-7', ['ssh', '-p', '22', 'server-7', 'pwd']), + ('server-8', ['ssh', '-p', '1022', 'server-8', 'pwd']), ('server-9', ['ssh', 'root@server-9', 'pwd']), - ('server-10', ['ssh', 'root@server-10', 'pwd']), + ('server-10', ['ssh', '-p', '1022', 'root@server-10', 'pwd']), ('server-11', ['ssh', 'server-11', 'pwd']), ('server-12', ['ssh', 'root@server-12', 'pwd']), ]) @@ -103,6 +104,16 @@ class TestSetting(TestCase): self.assertSystemExit(2, Setting().parse_args, ['color-ssh', '--label', 'x'], out) self.assertSystemExit(2, Setting().parse_args, ['color-ssh', '--host', ' ', 'pwd'], out) + def test_parse_host_error(self): + self.assertRaises(ValueError, Setting._parse_host, '') + self.assertRaises(ValueError, Setting._parse_host, '@') + self.assertRaises(ValueError, Setting._parse_host, ':') + self.assertRaises(ValueError, Setting._parse_host, 'a:') + self.assertRaises(ValueError, Setting._parse_host, 'a:b') + self.assertRaises(ValueError, Setting._parse_host, '@a:0') + self.assertRaises(ValueError, Setting._parse_host, 'a:b@c:0') + self.assertRaises(ValueError, Setting._parse_host, 'a@@c:0') + class TestMain(TestCase): def test_main_single_proc(self): diff --git a/tests/resources/test_color_ssh_hosts.txt b/tests/resources/test_color_ssh_hosts.txt index 3b9d2dd..f91ff9f 100644 --- a/tests/resources/test_color_ssh_hosts.txt +++ b/tests/resources/test_color_ssh_hosts.txt @@ -4,7 +4,7 @@ server-3 server-4 server-5 server-6 -server-7 -server-8 +server-7:22 +server-8:1022 root@server-9 -root@server-10 \ No newline at end of file +root@server-10:1022 \ No newline at end of file
{ "commit_name": "head_commit", "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, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 2 }
0.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "six", "mog-commons>=0.2.2" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/mogproject/color-ssh.git@b39783565319ee50b34988c29193f02a90122e2c#egg=color_ssh coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 mog-commons==0.2.3 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 six==1.17.0 tomli==2.2.1
name: color-ssh channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - mog-commons==0.2.3 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - six==1.17.0 - tomli==2.2.1 prefix: /opt/conda/envs/color-ssh
[ "tests/color_ssh/test_color_ssh.py::TestSetting::test_parse_args", "tests/color_ssh/test_color_ssh.py::TestSetting::test_parse_host_error" ]
[]
[ "tests/color_ssh/test_color_ssh.py::TestSetting::test_parse_args_error", "tests/color_ssh/test_color_ssh.py::TestMain::test_main_load_error", "tests/color_ssh/test_color_ssh.py::TestMain::test_main_multi_proc", "tests/color_ssh/test_color_ssh.py::TestMain::test_main_single_proc", "tests/color_ssh/test_color_ssh.py::TestMain::test_main_task_error" ]
[]
null
352
766
[ "src/color_ssh/__init__.py", "src/color_ssh/color_ssh.py" ]
ntoll__uflash-9
28bc481b67d67cc20aacc1191c87ac1e4c59bb34
2016-01-04 21:42:12
28bc481b67d67cc20aacc1191c87ac1e4c59bb34
ntoll: I'll try to get this reviewed and merged this evening. funkyHat: I've pushed another branch which fixes the test coverage (although one of the new tests is a bit of a beast...) Also removed `uflash help` as mentioned above: https://github.com/funkyHat/uflash/tree/unhexlify-plus ntoll: Can you merge the new branch into this one and I can do a final review..? funkyHat: Done. Want me to squash it into a single commit? ntoll: Please do... :-)
diff --git a/uflash.py b/uflash.py index 61fe83d..f5cd8a6 100644 --- a/uflash.py +++ b/uflash.py @@ -3,6 +3,7 @@ This module contains functions for turning a Python script into a .hex file and flashing it onto a BBC micro:bit. """ +import argparse import sys import os import struct @@ -19,8 +20,6 @@ _SCRIPT_ADDR = 0x3e000 _HELP_TEXT = """ Flash Python onto the BBC micro:bit -Usage: uflash [path_to_script.py] [path_to_microbit] - If no path to the micro:bit is provided uflash will attempt to autodetect the correct path to the device. If no path to the Python script is provided uflash will flash the unmodified MicroPython firmware onto the device. @@ -72,6 +71,23 @@ def hexlify(script): return '\n'.join(output) +def unhexlify(blob): + """ + Takes a hexlified script and turns it back into Python code. + """ + lines = blob.split('\n')[1:] + output = [] + for line in lines: + # Discard the address, length etc. and reverse the hexlification + output.append(binascii.unhexlify(line[9:-2])) + # Strip off "MP<size>" from the start + output[0] = output[0][4:] + # and strip any null bytes from the end + output[-1] = output[-1].strip(b'\x00') + script = b''.join(output) + return script + + def embed_hex(runtime_hex, python_hex=None): """ Given a string representing the MicroPython runtime hex, will embed a @@ -98,6 +114,28 @@ def embed_hex(runtime_hex, python_hex=None): return '\n'.join(embedded_list) + '\n' +def extract_script(embedded_hex): + """ + Given a hex file containing the MicroPython runtime and an embedded Python + script, will extract the original script. + + Returns a string containing the original embedded script. + """ + hex_lines = embedded_hex.split('\n') + # Find the marker in the hex that comes just before the script + try: + start_line = hex_lines.index(':08058000193901005D150000AE') + 1 + except ValueError as e: + raise ValueError('Bad input hex file:', e) + # Recombine the lines after that, but leave out the last 3 lines + blob = '\n'.join(hex_lines[start_line:-3]) + if blob == '': + # If the result is the empty string, there was no embedded script + return b'' + # Pass the extracted hex through unhexlify + return unhexlify(blob) + + def find_microbit(): """ Returns a path on the filesystem that represents the plugged in BBC @@ -179,6 +217,8 @@ def flash(path_to_python=None, path_to_microbit=None): # Grab the Python script (if needed). python_hex = '' if path_to_python: + if not path_to_python.endswith('.py'): + raise ValueError('Python files must end in ".py".') with open(path_to_python, 'rb') as python_script: python_hex = hexlify(python_script.read()) # Generate the resulting hex file. @@ -195,6 +235,20 @@ def flash(path_to_python=None, path_to_microbit=None): raise IOError('Unable to find micro:bit. Is it plugged in?') +def extract(path_to_hex=None, output_path=None): + """ + Given a hex file this function will attempt to extract the embedded script + from it and save it either to output_path or stdout + """ + with open(path_to_hex, 'r') as hex_file: + python_script = extract_script(hex_file.read()) + if output_path is not None: + with open(output_path, 'w') as output_file: + output_file.write(python_script) + else: + print(python_script.decode('utf-8')) + + def main(argv=None): """ Entry point for the command line tool 'uflash'. @@ -210,20 +264,21 @@ def main(argv=None): """ if not argv: argv = sys.argv[1:] - arg_len = len(argv) try: - if arg_len == 0: - flash() - elif arg_len >= 1: - if argv[0] == 'help': - print(_HELP_TEXT) - return - if not argv[0].lower().endswith('.py'): - raise ValueError('Python files must end in ".py".') - if arg_len == 1: - flash(argv[0]) - elif arg_len > 1: - flash(argv[0], argv[1]) + parser = argparse.ArgumentParser(description=_HELP_TEXT) + parser.add_argument('source', nargs='?', default=None) + parser.add_argument('target', nargs='?', default=None) + parser.add_argument('-e', '--extract', + action='store_true', + help="""Extract python source from a hex file + instead of creating the hex file""", + ) + args = parser.parse_args(argv) + + if args.extract: + extract(args.source, args.target) + else: + flash(args.source, args.target) except Exception as ex: # The exception of no return. Print the exception information. print(ex)
Add ability to extract Python code from a .hex file. Because sometimes, you don't save the source file... ;-)
ntoll/uflash
diff --git a/tests/test_uflash.py b/tests/test_uflash.py index 5434084..eb0c87c 100644 --- a/tests/test_uflash.py +++ b/tests/test_uflash.py @@ -39,6 +39,15 @@ def test_hexlify(): assert len(lines) == 5 +def test_unhexlify(): + """ + Ensure that we can get the script back out using unhexlify + """ + hexlified = uflash.hexlify(TEST_SCRIPT) + unhexlified = uflash.unhexlify(hexlified) + assert unhexlified == TEST_SCRIPT + + def test_hexlify_empty_script(): """ The function returns an empty string if the script is empty. @@ -84,6 +93,32 @@ def test_embed_no_runtime(): assert ex.value.args[0] == 'MicroPython runtime hex required.' +def test_extract(): + """ + The script should be returned if there is one + """ + python = uflash.hexlify(TEST_SCRIPT) + result = uflash.embed_hex(uflash._RUNTIME, python) + extracted = uflash.extract_script(result) + assert extracted == TEST_SCRIPT + + +def test_extract_not_valid_hex(): + """ + Return a sensible message if the hex file isn't valid + """ + with pytest.raises(ValueError) as e: + uflash.extract_script('invalid input') + assert 'Bad input hex file' in e.value.args[0] + + +def test_extract_no_python(): + """ + What to do here? + """ + assert uflash.extract_script(uflash._RUNTIME) == b'' + + def test_find_microbit_posix_exists(): """ Simulate being on os.name == 'posix' and a call to "mount" returns a @@ -278,8 +313,7 @@ def test_main_no_args(): with mock.patch('sys.argv', ['uflash', ]): with mock.patch('uflash.flash') as mock_flash: uflash.main() - assert mock_flash.call_count == 1 - assert mock_flash.call_args == () + assert mock_flash.called_once_with(None, None) def test_main_first_arg_python(): @@ -322,11 +356,55 @@ def test_main_two_args(): assert mock_flash.called_once_with('foo.py', '/media/foo/bar') -def test_main_extra_args_ignored(): +def test_extract_command(): """ - Any arguments more than two are ignored, with only the first two passed - into the flash() function. + Test the command-line script extract feature """ - with mock.patch('uflash.flash') as mock_flash: - uflash.main(argv=['foo.py', '/media/foo/bar', 'baz', 'quux']) - assert mock_flash.called_once_with('foo.py', '/media/foo/bar') + with mock.patch('uflash.extract') as mock_extract: + uflash.main(argv=['-e', 'hex.hex', 'foo.py']) + assert mock_extract.called_once_with('hex.hex', 'foo.py') + + +def test_extract_paths(): + """ + Test the different paths of the extract() function. + It should open and extract the contents of the file (input arg) + When called with only an input it should print the output of extract_script + When called with two arguments it should write the output to the output arg + """ + mock_e = mock.MagicMock(return_value=mock.sentinel.script) + mock_o = mock.MagicMock() + mock_o.return_value.__enter__ = lambda s: s + mock_o.return_value.__exit__ = mock.Mock() + mock_o.return_value.read.return_value = 'script' + mock_o.return_value.write = mock.Mock() + + with mock.patch('uflash.extract_script', mock_e) as mock_extract_script, \ + mock.patch('builtins.print') as mock_print, \ + mock.patch('builtins.open', mock_o) as mock_open: + uflash.extract('foo.hex') + assert mock_open.called_once_with('foo.hex') + assert mock_extract_script.called_once_with(mock.sentinel.file_handle) + assert mock_print.called_once_with(mock.sentinel.script) + + uflash.extract('foo.hex', 'out.py') + assert mock_open.call_count == 3 + assert mock_open.called_with('out.py', 'w') + assert mock_open.return_value.write.call_count == 1 + + +def test_extract_command_source_only(): + """ + If there is no target file the extract command should write to stdout + """ + with mock.patch('uflash.extract') as mock_extract: + uflash.main(argv=['hex.hex']) + assert mock_extract.called_once_with('hex.hex') + + +def test_extract_command_no_source(): + """ + If there is no source file the extract command should complain + """ + with pytest.raises(TypeError): + uflash.extract(None, None)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 babel==2.17.0 certifi==2025.1.31 charset-normalizer==3.4.1 coverage==7.8.0 docutils==0.21.2 exceptiongroup==1.2.2 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 Jinja2==3.1.6 MarkupSafe==3.0.2 packaging==24.2 pep8==1.7.1 pluggy==1.5.0 pyflakes==3.3.1 Pygments==2.19.1 pytest==8.3.5 pytest-cov==6.0.0 requests==2.32.3 snowballstemmer==2.2.0 Sphinx==7.4.7 sphinxcontrib-applehelp==2.0.0 sphinxcontrib-devhelp==2.0.0 sphinxcontrib-htmlhelp==2.1.0 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==2.0.0 sphinxcontrib-serializinghtml==2.0.0 tomli==2.2.1 -e git+https://github.com/ntoll/uflash.git@28bc481b67d67cc20aacc1191c87ac1e4c59bb34#egg=uflash urllib3==2.3.0 zipp==3.21.0
name: uflash channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - alabaster==0.7.16 - babel==2.17.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - coverage==7.8.0 - docutils==0.21.2 - exceptiongroup==1.2.2 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jinja2==3.1.6 - markupsafe==3.0.2 - packaging==24.2 - pep8==1.7.1 - pluggy==1.5.0 - pyflakes==3.3.1 - pygments==2.19.1 - pytest==8.3.5 - pytest-cov==6.0.0 - requests==2.32.3 - snowballstemmer==2.2.0 - sphinx==7.4.7 - sphinxcontrib-applehelp==2.0.0 - sphinxcontrib-devhelp==2.0.0 - sphinxcontrib-htmlhelp==2.1.0 - sphinxcontrib-jsmath==1.0.1 - sphinxcontrib-qthelp==2.0.0 - sphinxcontrib-serializinghtml==2.0.0 - tomli==2.2.1 - urllib3==2.3.0 - zipp==3.21.0 prefix: /opt/conda/envs/uflash
[ "tests/test_uflash.py::test_unhexlify", "tests/test_uflash.py::test_extract", "tests/test_uflash.py::test_extract_not_valid_hex", "tests/test_uflash.py::test_extract_no_python", "tests/test_uflash.py::test_extract_command", "tests/test_uflash.py::test_extract_paths", "tests/test_uflash.py::test_extract_command_source_only", "tests/test_uflash.py::test_extract_command_no_source" ]
[]
[ "tests/test_uflash.py::test_get_version", "tests/test_uflash.py::test_hexlify", "tests/test_uflash.py::test_hexlify_empty_script", "tests/test_uflash.py::test_embed_hex", "tests/test_uflash.py::test_embed_no_python", "tests/test_uflash.py::test_embed_no_runtime", "tests/test_uflash.py::test_find_microbit_posix_exists", "tests/test_uflash.py::test_find_microbit_posix_missing", "tests/test_uflash.py::test_find_microbit_nt_exists", "tests/test_uflash.py::test_find_microbit_nt_missing", "tests/test_uflash.py::test_find_microbit_unknown_os", "tests/test_uflash.py::test_save_hex", "tests/test_uflash.py::test_save_hex_no_hex", "tests/test_uflash.py::test_save_hex_path_not_to_hex_file", "tests/test_uflash.py::test_flash_no_args", "tests/test_uflash.py::test_flash_has_python_no_path_to_microbit", "tests/test_uflash.py::test_flash_with_paths", "tests/test_uflash.py::test_flash_cannot_find_microbit", "tests/test_uflash.py::test_flash_wrong_python", "tests/test_uflash.py::test_main_no_args", "tests/test_uflash.py::test_main_first_arg_python", "tests/test_uflash.py::test_main_first_arg_help", "tests/test_uflash.py::test_main_first_arg_not_python", "tests/test_uflash.py::test_main_two_args" ]
[]
MIT License
368
1,292
[ "uflash.py" ]
m-lab__bigsanity-17
7bb4df0ddb204026af693e91f33e13a039f66a3d
2016-01-11 18:53:45
7bb4df0ddb204026af693e91f33e13a039f66a3d
diff --git a/bigsanity/query_construct.py b/bigsanity/query_construct.py index 58e1b2d..cead3cd 100644 --- a/bigsanity/query_construct.py +++ b/bigsanity/query_construct.py @@ -102,6 +102,26 @@ def _project_has_intermediate_snapshots(project): project == constants.PROJECT_ID_NPAD) +def _project_to_time_field(project): + """Returns the appropriate test log time field for the project type. + + Returns the appropriate test log time field for a test given its project + type. All web100 M-Lab tests use 'web100_log_entry.log_time', while Paris + Traceroute uses 'log_time'. + + Args: + project: The numeric ID of the project (e.g. NDT = 0). + + Returns: + The string name of the log time field for the given project in the + BigQuery dataset schema. + """ + if project == constants.PROJECT_ID_PARIS_TRACEROUTE: + return 'log_time' + else: + return 'web100_log_entry.log_time' + + class TableEquivalenceQueryGenerator(object): """Generates queries to test the equivalence of two M-Lab tables.""" @@ -153,17 +173,18 @@ class TableEquivalenceQueryGenerator(object): return _construct_test_id_subquery(tables, conditions) def _format_time_range_condition(self): + time_field = _project_to_time_field(self._project) start_time = _to_unix_timestamp(self._time_range_start) start_time_human = _to_human_readable_date(self._time_range_start) end_time = _to_unix_timestamp(self._time_range_end) end_time_human = _to_human_readable_date(self._time_range_end) - return ( - '((web100_log_entry.log_time >= {start_time}) AND -- {start_time_human}' - '\n (web100_log_entry.log_time < {end_time})) -- {end_time_human}' - ).format(start_time=start_time, - start_time_human=start_time_human, - end_time=end_time, - end_time_human=end_time_human) + return ('(({time_field} >= {start_time}) AND -- {start_time_human}' + '\n ({time_field} < {end_time})) -- {end_time_human}' + ).format(time_field=time_field, + start_time=start_time, + start_time_human=start_time_human, + end_time=end_time, + end_time_human=end_time_human) class TableEquivalenceQueryGeneratorFactory(object):
paris_traceroute uses log_time paris_traceroute data uses `log_time` rather than `web100_log_entry.log_time` since Paris Traceroute is not web100 based. We need to adjust the query construction to address this.
m-lab/bigsanity
diff --git a/tests/test_query_construct.py b/tests/test_query_construct.py index 22441d3..a64f523 100644 --- a/tests/test_query_construct.py +++ b/tests/test_query_construct.py @@ -284,8 +284,8 @@ class TableEquivalenceQueryGeneratorTest(unittest.TestCase): plx.google:m_lab.2015_01.all WHERE project = 3 - AND ((web100_log_entry.log_time >= 1419724800) AND -- 2014-12-28 - (web100_log_entry.log_time < 1420243200)) -- 2015-01-03 + AND ((log_time >= 1419724800) AND -- 2014-12-28 + (log_time < 1420243200)) -- 2015-01-03 ) AS per_month FULL OUTER JOIN EACH ( @@ -294,8 +294,8 @@ class TableEquivalenceQueryGeneratorTest(unittest.TestCase): FROM plx.google:m_lab.paris_traceroute.all WHERE - ((web100_log_entry.log_time >= 1419724800) AND -- 2014-12-28 - (web100_log_entry.log_time < 1420243200)) -- 2015-01-03 + ((log_time >= 1419724800) AND -- 2014-12-28 + (log_time < 1420243200)) -- 2015-01-03 ) AS per_project ON per_month.test_id=per_project.test_id
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -r requirements.txt && pip install -r test-requirements.txt", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt", "test-requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 python-dateutil==2.9.0.post0 six==1.17.0 tomli==2.2.1
name: bigsanity channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - python-dateutil==2.9.0.post0 - six==1.17.0 - tomli==2.2.1 prefix: /opt/conda/envs/bigsanity
[ "tests/test_query_construct.py::TableEquivalenceQueryGeneratorTest::test_correct_query_generation_for_paris_traceroute" ]
[]
[ "tests/test_query_construct.py::TableEquivalenceQueryGeneratorTest::test_correct_query_generation_for_ndt_across_months", "tests/test_query_construct.py::TableEquivalenceQueryGeneratorTest::test_correct_query_generation_for_ndt_full_month", "tests/test_query_construct.py::TableEquivalenceQueryGeneratorTest::test_correct_query_generation_for_ndt_within_single_month", "tests/test_query_construct.py::TableEquivalenceQueryGeneratorTest::test_correct_query_generation_for_npad", "tests/test_query_construct.py::TableEquivalenceQueryGeneratorTest::test_correct_query_generation_for_sidestream" ]
[]
Apache License 2.0
373
599
[ "bigsanity/query_construct.py" ]
Pylons__webob-230
9400c049d05c8ba350daf119aa16ded24ece31f6
2016-01-12 17:50:01
9400c049d05c8ba350daf119aa16ded24ece31f6
diff --git a/webob/exc.py b/webob/exc.py index 57a81b5..044c00a 100644 --- a/webob/exc.py +++ b/webob/exc.py @@ -165,10 +165,12 @@ References: """ +import json from string import Template import re import sys +from webob.acceptparse import Accept from webob.compat import ( class_types, text_, @@ -250,7 +252,7 @@ ${body}''') empty_body = False def __init__(self, detail=None, headers=None, comment=None, - body_template=None, **kw): + body_template=None, json_formatter=None, **kw): Response.__init__(self, status='%s %s' % (self.code, self.title), **kw) @@ -265,6 +267,8 @@ ${body}''') if self.empty_body: del self.content_type del self.content_length + if json_formatter is not None: + self.json_formatter = json_formatter def __str__(self): return self.detail or self.explanation @@ -300,14 +304,31 @@ ${body}''') return self.html_template_obj.substitute(status=self.status, body=body) + def json_formatter(self, body, status, title, environ): + return {'message': body, + 'code': status, + 'title': title} + + def json_body(self, environ): + body = self._make_body(environ, no_escape) + jsonbody = self.json_formatter(body=body, status=self.status, + title=self.title, environ=environ) + return json.dumps(jsonbody) + def generate_response(self, environ, start_response): if self.content_length is not None: del self.content_length headerlist = list(self.headerlist) - accept = environ.get('HTTP_ACCEPT', '') - if accept and 'html' in accept or '*/*' in accept: + accept_value = environ.get('HTTP_ACCEPT', '') + accept = Accept(accept_value) + match = accept.best_match(['application/json', 'text/html', + 'text/plain'], default_match='text/plain') + if match == 'text/html': content_type = 'text/html' body = self.html_body(environ) + elif match == 'application/json': + content_type = 'application/json' + body = self.json_body(environ) else: content_type = 'text/plain' body = self.plain_body(environ)
Allow for JSON Exception Bodies I'm currently working on several projects that provide a JSON API using WebOb. Currently, however, whenever we use a `webob.exc` exception to return an error to the user (e.g., `webob.exc.HTTPBadRequest`) the body of that message is always in a content-type other than what they're expecting (HTML if they don't specify an Accept header, plain-text otherwise). There doesn't seem to be a pleasant, convenient, or simple way to make it use JSON beyond something like (the untested) following code: ```py import string import webob.exc class WSGIHTTPException(webob.exc.WSGIHTTPException): body_template_obj = string.Template('{"code", ${status}, "message": "${body}", "title": "${title}"}' plain_template_obj = string.Template('{"error": ${body}}') class HTTPBadRequest(webob.exc.HTTPBadRequest, WSGIHTTPException): pass class HTTPUnauthored(webob.exc.HTTPBadRequest, WSGIHTTPException): pass # etc. ``` This is particularly problematic because we have to redefine all of the exceptions we want to use to doubly inherit from our new sub-classed `WSGIHTTPException` and the original. It also doesn't handle the fact that we have to basically copy and paste [generate_response][] into our subclass so that we set the appropriate content-type header. Is it too much to ask to either: A) Add support for JSON response bodies in `WSGIHTTPException`s, or B) Make `WSGIHTTPException` slightly more modular so we can only override parts we need? [generate_response]: https://github.com/Pylons/webob/blob/7f98f694e7c1a569f53fb4085d084430ee8b2cc2/webob/exc.py#L302..L323 Thanks in advance,
Pylons/webob
diff --git a/tests/test_exc.py b/tests/test_exc.py index dcb1fed..8204783 100644 --- a/tests/test_exc.py +++ b/tests/test_exc.py @@ -1,3 +1,5 @@ +import json + from webob.request import Request from webob.dec import wsgify from webob import exc as webob_exc @@ -119,6 +121,57 @@ def test_WSGIHTTPException_html_body_w_comment(): '</html>' ) +def test_WSGIHTTPException_json_body_no_comment(): + class ValidationError(webob_exc.WSGIHTTPException): + code = '422' + title = 'Validation Failed' + explanation = 'Validation of an attribute failed.' + + exc = ValidationError(detail='Attribute "xyz" is invalid.') + body = exc.json_body({}) + eq_(json.loads(body), { + "code": "422 Validation Failed", + "title": "Validation Failed", + "message": "Validation of an attribute failed.<br /><br />\nAttribute" + ' "xyz" is invalid.\n\n', + }) + +def test_WSGIHTTPException_respects_application_json(): + class ValidationError(webob_exc.WSGIHTTPException): + code = '422' + title = 'Validation Failed' + explanation = 'Validation of an attribute failed.' + def start_response(status, headers, exc_info=None): + pass + + exc = ValidationError(detail='Attribute "xyz" is invalid.') + resp = exc.generate_response(environ={ + 'wsgi.url_scheme': 'HTTP', + 'SERVER_NAME': 'localhost', + 'SERVER_PORT': '80', + 'REQUEST_METHOD': 'PUT', + 'HTTP_ACCEPT': 'application/json', + }, start_response=start_response) + eq_(json.loads(resp[0].decode('utf-8')), { + "code": "422 Validation Failed", + "title": "Validation Failed", + "message": "Validation of an attribute failed.<br /><br />\nAttribute" + ' "xyz" is invalid.\n\n', + }) + +def test_WSGIHTTPException_allows_custom_json_formatter(): + def json_formatter(body, status, title, environ): + return {"fake": True} + class ValidationError(webob_exc.WSGIHTTPException): + code = '422' + title = 'Validation Failed' + explanation = 'Validation of an attribute failed.' + + exc = ValidationError(detail='Attribute "xyz" is invalid.', + json_formatter=json_formatter) + body = exc.json_body({}) + eq_(json.loads(body), {"fake": True}) + def test_WSGIHTTPException_generate_response(): def start_response(status, headers, exc_info=None): pass
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 1 }, "num_modified_files": 1 }
1.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[testing]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work nose==1.3.7 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work -e git+https://github.com/Pylons/webob.git@9400c049d05c8ba350daf119aa16ded24ece31f6#egg=WebOb
name: webob channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - nose==1.3.7 prefix: /opt/conda/envs/webob
[ "tests/test_exc.py::test_WSGIHTTPException_json_body_no_comment", "tests/test_exc.py::test_WSGIHTTPException_respects_application_json", "tests/test_exc.py::test_WSGIHTTPException_allows_custom_json_formatter" ]
[]
[ "tests/test_exc.py::test_noescape_null", "tests/test_exc.py::test_noescape_not_basestring", "tests/test_exc.py::test_noescape_unicode", "tests/test_exc.py::test_strip_tags_empty", "tests/test_exc.py::test_strip_tags_newline_to_space", "tests/test_exc.py::test_strip_tags_zaps_carriage_return", "tests/test_exc.py::test_strip_tags_br_to_newline", "tests/test_exc.py::test_strip_tags_zaps_comments", "tests/test_exc.py::test_strip_tags_zaps_tags", "tests/test_exc.py::test_HTTPException", "tests/test_exc.py::test_exception_with_unicode_data", "tests/test_exc.py::test_WSGIHTTPException_headers", "tests/test_exc.py::test_WSGIHTTPException_w_body_template", "tests/test_exc.py::test_WSGIHTTPException_w_empty_body", "tests/test_exc.py::test_WSGIHTTPException___str__", "tests/test_exc.py::test_WSGIHTTPException_plain_body_no_comment", "tests/test_exc.py::test_WSGIHTTPException_html_body_w_comment", "tests/test_exc.py::test_WSGIHTTPException_generate_response", "tests/test_exc.py::test_WSGIHTTPException_call_w_body", "tests/test_exc.py::test_WSGIHTTPException_wsgi_response", "tests/test_exc.py::test_WSGIHTTPException_exception_newstyle", "tests/test_exc.py::test_WSGIHTTPException_exception_no_newstyle", "tests/test_exc.py::test_HTTPOk_head_of_proxied_head", "tests/test_exc.py::test_HTTPMove", "tests/test_exc.py::test_HTTPMove_location_not_none", "tests/test_exc.py::test_HTTPMove_location_newlines", "tests/test_exc.py::test_HTTPMove_add_slash_and_location", "tests/test_exc.py::test_HTTPMove_call_add_slash", "tests/test_exc.py::test_HTTPMove_call_query_string", "tests/test_exc.py::test_HTTPExceptionMiddleware_ok", "tests/test_exc.py::test_HTTPExceptionMiddleware_exception", "tests/test_exc.py::test_HTTPExceptionMiddleware_exception_exc_info_none", "tests/test_exc.py::test_status_map_is_deterministic" ]
[]
null
376
596
[ "webob/exc.py" ]
wong2__pick-3
38bab1f33ff03936906435d5458765493e4c2c1c
2016-01-20 08:40:03
38bab1f33ff03936906435d5458765493e4c2c1c
diff --git a/example/scroll.py b/example/scroll.py new file mode 100644 index 0000000..6f34b22 --- /dev/null +++ b/example/scroll.py @@ -0,0 +1,10 @@ +#-*-coding:utf-8-*- + +from __future__ import print_function + +from pick import pick + +title = 'Select:' +options = ['foo.bar%s.baz' % x for x in range(1, 71)] +option, index = pick(options, title) +print(option, index) diff --git a/pick/__init__.py b/pick/__init__.py index 1f8ccfc..f004b84 100644 --- a/pick/__init__.py +++ b/pick/__init__.py @@ -49,14 +49,13 @@ class Picker(object): """ return self.options[self.index], self.index - def draw(self): - """draw the curses ui on the screen""" - self.screen.clear() - - x, y = 1, 1 + def get_title_lines(self): if self.title: - self.screen.addstr(y, x, self.title) - y += 2 + return self.title.split('\n') + [''] + return [] + + def get_option_lines(self): + lines = [] for index, option in enumerate(self.options): if index == self.index: @@ -64,13 +63,53 @@ class Picker(object): else: prefix = len(self.indicator) * ' ' line = '{0} {1}'.format(prefix, option) + lines.append(line) + + return lines + + def get_lines(self): + title_lines = self.get_title_lines() + option_lines = self.get_option_lines() + lines = title_lines + option_lines + current_line = self.index + len(title_lines) + 1 + return lines, current_line + + def draw(self): + """draw the curses ui on the screen, handle scroll if needed""" + self.screen.clear() + + x, y = 1, 1 # start point + max_y, max_x = self.screen.getmaxyx() + max_rows = max_y - y # the max rows we can draw + + lines, current_line = self.get_lines() + + # calculate how many lines we should scroll, relative to the top + scroll_top = getattr(self, 'scroll_top', 0) + if current_line <= scroll_top: + scroll_top = 0 + elif current_line - scroll_top > max_rows: + scroll_top = current_line - max_rows + self.scroll_top = scroll_top + + lines_to_draw = lines[scroll_top:scroll_top+max_rows] + + for line in lines_to_draw: self.screen.addstr(y, x, line) y += 1 self.screen.refresh() - def start(self): - return curses.wrapper(self.run_loop) + def run_loop(self): + while True: + self.draw() + c = self.screen.getch() + if c in KEYS_UP: + self.move_up() + elif c in KEYS_DOWN: + self.move_down() + elif c in KEYS_ENTER: + return self.get_selected() def config_curses(self): # use the default colors of the terminal @@ -78,21 +117,13 @@ class Picker(object): # hide the cursor curses.curs_set(0) - def run_loop(self, screen): - self.config_curses() + def _start(self, screen): self.screen = screen - self.draw() + self.config_curses() + return self.run_loop() - while True: - c = self.screen.getch() - if c in KEYS_UP: - self.move_up() - self.draw() - elif c in KEYS_DOWN: - self.move_down() - self.draw() - elif c in KEYS_ENTER: - return self.get_selected() + def start(self): + return curses.wrapper(self._start) def pick(options, title=None, indicator='*', default_index=0):
Long lists issue I have an issue with `pick` while passing a long list, here is an example you can try it: ```python from pick import pick title = 'Select: ' options = ['foo.bar1.baz', 'foo.bar2.baz', 'foo.bar3.baz', 'foo.bar4.baz', 'foo.bar5.baz', 'foo.bar6.baz', 'foo.bar7.baz','foo.bar8.baz', 'foo.bar9.baz', 'foo.bar10.baz','foo.bar11.baz', 'foo.bar12.baz', 'foo.bar13.baz', 'foo.bar14.baz', 'foo.bar15.baz', 'foo.bar16.baz', 'foo.bar17.baz','foo.bar18.baz', 'foo.bar19.baz', 'foo.bar20.baz','foo.bar21.baz', 'foo.bar22.baz', 'foo.bar23.baz', 'foo.bar24.baz', 'foo.bar25.baz', 'foo.bar26.baz', 'foo.bar27.baz','foo.bar28.baz', 'foo.bar29.baz', 'foo.bar30.baz','foo.bar31.baz', 'foo.bar32.baz', 'foo.bar33.baz', 'foo.bar34.baz', 'foo.bar35.baz', 'foo.bar36.baz', 'foo.bar37.baz','foo.bar38.baz', 'foo.bar39.baz', 'foo.bar40.baz','foo.bar41.baz', 'foo.bar42.baz', 'foo.bar43.baz', 'foo.bar44.baz', 'foo.bar45.baz', 'foo.bar46.baz', 'foo.bar47.baz','foo.bar48.baz', 'foo.bar49.baz', 'foo.bar50.baz','foo.bar51.baz', 'foo.bar52.baz', 'foo.bar53.baz', 'foo.bar54.baz', 'foo.bar55.baz', 'foo.bar56.baz', 'foo.bar57.baz','foo.bar58.baz', 'foo.bar59.baz', 'foo.bar60.baz'] option, index = pick(options, title) ``` the result will be: ``` Traceback (most recent call last): File "pick_test.py", line 5, in <module> option, index = pick(options, title) File "/usr/lib/python2.7/site-packages/pick/__init__.py", line 109, in pick return picker.start() File "/usr/lib/python2.7/site-packages/pick/__init__.py", line 73, in start return curses.wrapper(self.run_loop) File "/usr/lib64/python2.7/curses/wrapper.py", line 43, in wrapper return func(stdscr, *args, **kwds) File "/usr/lib/python2.7/site-packages/pick/__init__.py", line 84, in run_loop self.draw() File "/usr/lib/python2.7/site-packages/pick/__init__.py", line 67, in draw self.screen.addstr(y, x, line) _curses.error: addstr() returned ERR ```
wong2/pick
diff --git a/tests/test_pick.py b/tests/test_pick.py index f5b7dd4..21eecc4 100644 --- a/tests/test_pick.py +++ b/tests/test_pick.py @@ -1,12 +1,12 @@ #-*-coding:utf-8-*- import unittest -from pick import pick, Picker +from pick import Picker class TestPick(unittest.TestCase): - def test_pick(self): + def test_move_up_down(self): title = 'Please choose an option: ' options = ['option1', 'option2', 'option3'] picker = Picker(options, title) @@ -16,6 +16,26 @@ class TestPick(unittest.TestCase): picker.move_down() assert picker.get_selected() == ('option2', 1) + def test_default_index(self): + title = 'Please choose an option: ' + options = ['option1', 'option2', 'option3'] + picker = Picker(options, title, default_index=1) + assert picker.get_selected() == ('option2', 1) + + def test_get_lines(self): + title = 'Please choose an option: ' + options = ['option1', 'option2', 'option3'] + picker = Picker(options, title, indicator='*') + lines, current_line = picker.get_lines() + assert lines == [title, '', '* option1', ' option2', ' option3'] + assert current_line == 3 + + def test_no_title(self): + options = ['option1', 'option2', 'option3'] + picker = Picker(options) + lines, current_line = picker.get_lines() + assert current_line == 1 + if __name__ == '__main__': unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work nose==1.3.7 packaging @ file:///croot/packaging_1734472117206/work -e git+https://github.com/wong2/pick.git@38bab1f33ff03936906435d5458765493e4c2c1c#egg=pick pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: pick channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - nose==1.3.7 prefix: /opt/conda/envs/pick
[ "tests/test_pick.py::TestPick::test_get_lines", "tests/test_pick.py::TestPick::test_no_title" ]
[]
[ "tests/test_pick.py::TestPick::test_default_index", "tests/test_pick.py::TestPick::test_move_up_down" ]
[]
MIT License
390
976
[ "pick/__init__.py" ]
joke2k__faker-325
326e22d5752e0a28baee59c57ed0f49935de9059
2016-01-22 19:57:09
883576c2d718ad7f604415e02a898f1f917d5b86
diff --git a/faker/providers/lorem/__init__.py b/faker/providers/lorem/__init__.py index 5f07712d..dea4dd36 100644 --- a/faker/providers/lorem/__init__.py +++ b/faker/providers/lorem/__init__.py @@ -8,7 +8,8 @@ class Provider(BaseProvider): @classmethod def word(cls): """ - :example 'Lorem' + Generate a random word + :example 'lorem' """ return cls.random_element(cls.word_list) diff --git a/faker/providers/python/__init__.py b/faker/providers/python/__init__.py index 0b452478..4e5477b8 100644 --- a/faker/providers/python/__init__.py +++ b/faker/providers/python/__init__.py @@ -25,7 +25,7 @@ class Provider(BaseProvider): @classmethod def pystr(cls, max_chars=20): - return Lorem.text(max_chars) + return "".join(cls.random_letter() for i in range(max_chars)) @classmethod def pyfloat(cls, left_digits=None, right_digits=None, positive=False):
Add ability to generate lorem characters without punctuation Sometimes I want to generate a string of characters of a specific length without any punctuation or capitalization but the lorem provider currently does not allow for this.
joke2k/faker
diff --git a/faker/tests/__init__.py b/faker/tests/__init__.py index 8c20e3d5..802bee4c 100644 --- a/faker/tests/__init__.py +++ b/faker/tests/__init__.py @@ -499,6 +499,20 @@ class FactoryTestCase(unittest.TestCase): sentence = provider.sentence(0) self.assertEqual(sentence, '') + def test_random_pystr_characters(self): + from faker.providers.python import Provider + provider = Provider(None) + + characters = provider.pystr() + self.assertEqual(len(characters), 20) + characters = provider.pystr(max_chars=255) + self.assertEqual(len(characters), 255) + characters = provider.pystr(max_chars=0) + self.assertEqual(characters, '') + characters = provider.pystr(max_chars=-10) + self.assertEqual(characters, '') + + def test_us_ssn_valid(self): from faker.providers.ssn.en_US import Provider
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 3 }, "num_modified_files": 2 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 -e git+https://github.com/joke2k/faker.git@326e22d5752e0a28baee59c57ed0f49935de9059#egg=fake_factory iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 six==1.17.0 tomli==2.2.1
name: faker channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - six==1.17.0 - tomli==2.2.1 prefix: /opt/conda/envs/faker
[ "faker/tests/__init__.py::FactoryTestCase::test_random_pystr_characters" ]
[]
[ "faker/tests/__init__.py::ShimsTestCase::test_counter", "faker/tests/__init__.py::UtilsTestCase::test_add_dicts", "faker/tests/__init__.py::UtilsTestCase::test_choice_distribution", "faker/tests/__init__.py::UtilsTestCase::test_find_available_locales", "faker/tests/__init__.py::UtilsTestCase::test_find_available_providers", "faker/tests/__init__.py::FactoryTestCase::test_add_provider_gives_priority_to_newly_added_provider", "faker/tests/__init__.py::FactoryTestCase::test_command", "faker/tests/__init__.py::FactoryTestCase::test_command_custom_provider", "faker/tests/__init__.py::FactoryTestCase::test_date_time_between_dates", "faker/tests/__init__.py::FactoryTestCase::test_date_time_between_dates_with_tzinfo", "faker/tests/__init__.py::FactoryTestCase::test_date_time_this_period", "faker/tests/__init__.py::FactoryTestCase::test_date_time_this_period_with_tzinfo", "faker/tests/__init__.py::FactoryTestCase::test_datetime_safe", "faker/tests/__init__.py::FactoryTestCase::test_datetimes_with_and_without_tzinfo", "faker/tests/__init__.py::FactoryTestCase::test_documentor", "faker/tests/__init__.py::FactoryTestCase::test_email", "faker/tests/__init__.py::FactoryTestCase::test_format_calls_formatter_on_provider", "faker/tests/__init__.py::FactoryTestCase::test_format_transfers_arguments_to_formatter", "faker/tests/__init__.py::FactoryTestCase::test_get_formatter_returns_callable", "faker/tests/__init__.py::FactoryTestCase::test_get_formatter_returns_correct_formatter", "faker/tests/__init__.py::FactoryTestCase::test_get_formatter_throws_exception_on_incorrect_formatter", "faker/tests/__init__.py::FactoryTestCase::test_magic_call_calls_format", "faker/tests/__init__.py::FactoryTestCase::test_magic_call_calls_format_with_arguments", "faker/tests/__init__.py::FactoryTestCase::test_no_words_paragraph", "faker/tests/__init__.py::FactoryTestCase::test_no_words_sentence", "faker/tests/__init__.py::FactoryTestCase::test_parse_returns_same_string_when_it_contains_no_curly_braces", "faker/tests/__init__.py::FactoryTestCase::test_parse_returns_string_with_tokens_replaced_by_formatters", "faker/tests/__init__.py::FactoryTestCase::test_password", "faker/tests/__init__.py::FactoryTestCase::test_prefix_suffix_always_string", "faker/tests/__init__.py::FactoryTestCase::test_random_element", "faker/tests/__init__.py::FactoryTestCase::test_slugify", "faker/tests/__init__.py::FactoryTestCase::test_timezone_conversion", "faker/tests/__init__.py::FactoryTestCase::test_us_ssn_valid", "faker/tests/__init__.py::GeneratorTestCase::test_get_random", "faker/tests/__init__.py::GeneratorTestCase::test_random_seed_doesnt_seed_system_random" ]
[]
MIT License
393
287
[ "faker/providers/lorem/__init__.py", "faker/providers/python/__init__.py" ]
docker__docker-py-911
446e6d08dd569194a27bb354a184b7d94ecf5e48
2016-01-29 00:27:19
4c34be5d4ab8a5a017950712e9c96b56d78d1c58
diff --git a/docker/client.py b/docker/client.py index fb186cc7..7d1f7c46 100644 --- a/docker/client.py +++ b/docker/client.py @@ -45,17 +45,17 @@ class Client( timeout=constants.DEFAULT_TIMEOUT_SECONDS, tls=False): super(Client, self).__init__() - if tls and (not base_url or not base_url.startswith('https://')): + if tls and not base_url: raise errors.TLSParameterError( - 'If using TLS, the base_url argument must begin with ' - '"https://".') + 'If using TLS, the base_url argument must be provided.' + ) self.base_url = base_url self.timeout = timeout self._auth_configs = auth.load_config() - base_url = utils.parse_host(base_url, sys.platform) + base_url = utils.parse_host(base_url, sys.platform, tls=bool(tls)) if base_url.startswith('http+unix://'): self._custom_adapter = unixconn.UnixAdapter(base_url, timeout) self.mount('http+docker://', self._custom_adapter) diff --git a/docker/utils/utils.py b/docker/utils/utils.py index 1ce1867c..dc46f1ef 100644 --- a/docker/utils/utils.py +++ b/docker/utils/utils.py @@ -345,7 +345,7 @@ def parse_repository_tag(repo_name): # fd:// protocol unsupported (for obvious reasons) # Added support for http and https # Protocol translation: tcp -> http, unix -> http+unix -def parse_host(addr, platform=None): +def parse_host(addr, platform=None, tls=False): proto = "http+unix" host = DEFAULT_HTTP_HOST port = None @@ -381,7 +381,7 @@ def parse_host(addr, platform=None): raise errors.DockerException( "Invalid bind address protocol: {0}".format(addr) ) - proto = "http" + proto = "https" if tls else "http" if proto != "http+unix" and ":" in addr: host_parts = addr.split(':')
Problem when using the DOCKER_HOST variable in combination with docker-compose and https:// Hi, I'm trying to use docker & docker-compose with the DOCKER_HOST env-variable to control a remote docker-host. at first I configured the variables on the docker client machine as follows: export DOCKER_CERT_PATH=/vagrant/docker export DOCKER_TLS_VERIFY=1 export DOCKER_HOST=my-docker-vm.cloudapp.azure.com:2376 This lead to an error in docker-compose as discussed in this issue docker/compose#2634 Once I added the `https://` protocol prefix to the hostname the connection problem with docker-compose went away... export DOCKER_HOST=https://my-docker-vm.cloudapp.azure.com:2376 But with this format of the DOCKER_HOST variable now the docker CLI is complaining about the format... docker ps Invalid bind address format: https://my-docker-vm.cloudapp.azure.com:2376 I think this error is triggered here: https://github.com/docker/docker-py/blob/62d9964cc1881f6f3cd021594cd40fd80a8fc855/docker/utils/utils.py#L388 The code is not expecting to find two occurrences of double-dots `:` in the host variable, but for some reason it does. PS: also the ambiguity of the two error messages in `utils.py` could be improved, since at L368 & at L388 both errors emit the same message, but for different reasons ;) Thanks & Regards, Wolfgang
docker/docker-py
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py index 83d2a98d..63ea10e7 100644 --- a/tests/unit/utils_test.py +++ b/tests/unit/utils_test.py @@ -360,6 +360,11 @@ class ParseHostTest(base.BaseTestCase): assert parse_host(val, 'win32') == tcp_port + def test_parse_host_tls(self): + host_value = 'myhost.docker.net:3348' + expected_result = 'https://myhost.docker.net:3348' + self.assertEqual(parse_host(host_value, None, True), expected_result) + class ParseRepositoryTagTest(base.BaseTestCase): sha = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
1.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/docker/docker-py.git@446e6d08dd569194a27bb354a184b7d94ecf5e48#egg=docker_py exceptiongroup==1.2.2 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 requests==2.5.3 six==1.17.0 tomli==2.2.1 websocket_client==0.32.0
name: docker-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - requests==2.5.3 - six==1.17.0 - tomli==2.2.1 - websocket-client==0.32.0 prefix: /opt/conda/envs/docker-py
[ "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls" ]
[]
[ "tests/unit/utils_test.py::HostConfigTest::test_create_endpoint_config_with_aliases", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_kill_disable", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/unit/utils_test.py::UlimitTest::test_ulimit_invalid_type", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_compact", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_complete", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_empty", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_list", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_no_mode", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_bytes_input", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_unicode_input", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_commented_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_invalid_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_proper", "tests/unit/utils_test.py::ParseHostTest::test_parse_host", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_empty_value", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_tag", "tests/unit/utils_test.py::ParseDeviceTest::test_dict", "tests/unit/utils_test.py::ParseDeviceTest::test_full_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_hybrid_list", "tests/unit/utils_test.py::ParseDeviceTest::test_partial_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_permissionless_string_definition", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_float", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_invalid", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_maxint", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_valid", "tests/unit/utils_test.py::UtilsTest::test_convert_filters", "tests/unit/utils_test.py::UtilsTest::test_create_ipam_config", "tests/unit/utils_test.py::UtilsTest::test_decode_json_header", "tests/unit/utils_test.py::SplitCommandTest::test_split_command_with_unicode", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/unit/utils_test.py::PortsTest::test_host_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/unit/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/unit/utils_test.py::PortsTest::test_port_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_split_port_invalid", "tests/unit/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/unit/utils_test.py::ExcludePathsTest::test_directory", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/unit/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/unit/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/unit/utils_test.py::ExcludePathsTest::test_question_mark", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception", "tests/unit/utils_test.py::TarTest::test_tar_with_directory_symlinks", "tests/unit/utils_test.py::TarTest::test_tar_with_empty_directory", "tests/unit/utils_test.py::TarTest::test_tar_with_excludes", "tests/unit/utils_test.py::TarTest::test_tar_with_file_symlinks" ]
[]
Apache License 2.0
401
492
[ "docker/client.py", "docker/utils/utils.py" ]
networkx__networkx-1963
ec6dfae2aaebbbbf0a4620002ab795efa6430c25
2016-01-29 18:00:19
ec6dfae2aaebbbbf0a4620002ab795efa6430c25
diff --git a/networkx/algorithms/core.py b/networkx/algorithms/core.py index 2091bb97f..c98c7d77c 100644 --- a/networkx/algorithms/core.py +++ b/networkx/algorithms/core.py @@ -4,30 +4,41 @@ # Pieter Swart <[email protected]> # All rights reserved. # BSD license. +# +# Authors: Dan Schult ([email protected]) +# Jason Grout ([email protected]) +# Aric Hagberg ([email protected]) """ Find the k-cores of a graph. The k-core is found by recursively pruning nodes with degrees less than k. -See the following reference for details: +See the following references for details: An O(m) Algorithm for Cores Decomposition of Networks Vladimir Batagelj and Matjaz Zaversnik, 2003. http://arxiv.org/abs/cs.DS/0310049 -""" - -__author__ = "\n".join(['Dan Schult ([email protected])', - 'Jason Grout ([email protected])', - 'Aric Hagberg ([email protected])']) +Generalized Cores +Vladimir Batagelj and Matjaz Zaversnik, 2002. +http://arxiv.org/pdf/cs/0202039 -__all__ = ['core_number','k_core','k_shell','k_crust','k_corona','find_cores'] +For directed graphs a more general notion is that of D-cores which +looks at (k, l) restrictions on (in, out) degree. The (k, k) D-core +is the k-core. +D-cores: Measuring Collaboration of Directed Graphs Based on Degeneracy +Christos Giatsidis, Dimitrios M. Thilikos, Michalis Vazirgiannis, ICDM 2011. +http://www.graphdegeneracy.org/dcores_ICDM_2011.pdf +""" import networkx as nx -from networkx import all_neighbors from networkx.exception import NetworkXError from networkx.utils import not_implemented_for +__all__ = ['core_number', 'find_cores', 'k_core', + 'k_shell', 'k_crust', 'k_corona'] + + @not_implemented_for('multigraph') def core_number(G): """Return the core number for each vertex. @@ -50,7 +61,8 @@ def core_number(G): Raises ------ NetworkXError - The k-core is not defined for graphs with self loops or parallel edges. + The k-core is not implemented for graphs with self loops + or parallel edges. Notes ----- @@ -66,9 +78,9 @@ def core_number(G): http://arxiv.org/abs/cs.DS/0310049 """ if G.number_of_selfloops() > 0: - raise NetworkXError( - 'Input graph has self loops; the core number is not defined.' - ' Consider using G.remove_edges_from(G.selfloop_edges()).') + msg = ('Input graph has self loops which is not permitted; ' + 'Consider using G.remove_edges_from(G.selfloop_edges()).') + raise NetworkXError(msg) degrees = dict(G.degree()) # Sort nodes by degree. nodes = sorted(degrees, key=degrees.get) @@ -81,7 +93,7 @@ def core_number(G): node_pos = {v: pos for pos, v in enumerate(nodes)} # The initial guess for the core number of a node is its degree. core = degrees - nbrs = {v: set(all_neighbors(G, v)) for v in G} + nbrs = {v: list(nx.all_neighbors(G, v)) for v in G} for v in nodes: for u in nbrs[v]: if core[u] > core[v]: @@ -99,34 +111,34 @@ def core_number(G): find_cores = core_number -def _core_helper(G, func, k=None, core=None): - """Returns the subgraph induced by all nodes for which ``func`` - returns ``True``. - - ``G`` is a NetworkX graph. - - ``func`` is a function that takes three inputs: a node of ``G``, the - maximum core value, and the core number of the graph. The function - must return a Boolean value. +def _core_subgraph(G, k_filter, k=None, core=None): + """Returns the subgraph induced by nodes passing filter ``k_filter``. - ``k`` is the order of the core. If not specified, the maximum over - all core values will be returned. - - ``core`` is a dictionary mapping node to core numbers for that - node. If you have already computed it, you should provide it - here. If not specified, the core numbers will be computed from the - graph. + Parameters + ---------- + G : NetworkX graph + The graph or directed graph to process + k_filter : filter function + This function filters the nodes chosen. It takes three inputs: + A node of G, the filter's cutoff, and the core dict of the graph. + The function should return a Boolean value. + k : int, optional + The order of the core. If not specified use the max core number. + This value is used as the cutoff for the filter. + core : dict, optional + Precomputed core numbers keyed by node for the graph ``G``. + If not specified, the core numbers will be computed from ``G``. """ if core is None: core = core_number(G) if k is None: k = max(core.values()) - nodes = [v for v in core if func(v, k, core)] + nodes = (v for v in core if k_filter(v, k, core)) return G.subgraph(nodes).copy() -def k_core(G,k=None,core_number=None): +def k_core(G, k=None, core_number=None): """Return the k-core of G. A k-core is a maximal subgraph that contains nodes of degree k or more. @@ -171,21 +183,23 @@ def k_core(G,k=None,core_number=None): Vladimir Batagelj and Matjaz Zaversnik, 2003. http://arxiv.org/abs/cs.DS/0310049 """ - func = lambda v, k, core_number: core_number[v] >= k - return _core_helper(G, func, k, core_number) + def k_filter(v, k, c): + return c[v] >= k + return _core_subgraph(G, k_filter, k, core_number) -def k_shell(G,k=None,core_number=None): +def k_shell(G, k=None, core_number=None): """Return the k-shell of G. - The k-shell is the subgraph of nodes in the k-core but not in the (k+1)-core. + The k-shell is the subgraph induced by nodes with core number k. + That is, nodes in the k-core that are not in the (k+1)-core. Parameters ---------- G : NetworkX graph A graph or directed graph. k : int, optional - The order of the shell. If not specified return the main shell. + The order of the shell. If not specified return the outer shell. core_number : dictionary, optional Precomputed core numbers for the graph G. @@ -198,7 +212,8 @@ def k_shell(G,k=None,core_number=None): Raises ------ NetworkXError - The k-shell is not defined for graphs with self loops or parallel edges. + The k-shell is not implemented for graphs with self loops + or parallel edges. Notes ----- @@ -225,11 +240,12 @@ def k_shell(G,k=None,core_number=None): and Eran Shir, PNAS July 3, 2007 vol. 104 no. 27 11150-11154 http://www.pnas.org/content/104/27/11150.full """ - func = lambda v, k, core_number: core_number[v] == k - return _core_helper(G, func, k, core_number) + def k_filter(v, k, c): + return c[v] == k + return _core_subgraph(G, k_filter, k, core_number) -def k_crust(G,k=None,core_number=None): +def k_crust(G, k=None, core_number=None): """Return the k-crust of G. The k-crust is the graph G with the k-core removed. @@ -251,7 +267,8 @@ def k_crust(G,k=None,core_number=None): Raises ------ NetworkXError - The k-crust is not defined for graphs with self loops or parallel edges. + The k-crust is not implemented for graphs with self loops + or parallel edges. Notes ----- @@ -276,16 +293,14 @@ def k_crust(G,k=None,core_number=None): and Eran Shir, PNAS July 3, 2007 vol. 104 no. 27 11150-11154 http://www.pnas.org/content/104/27/11150.full """ - func = lambda v, k, core_number: core_number[v] <= k - # HACK These two checks are done in _core_helper, but this function - # requires k to be one less than the maximum core value instead of - # just the maximum. Therefore we duplicate the checks here. A better - # solution should exist... + # Default for k is one less than in _core_subgraph, so just inline. + # Filter is c[v] <= k if core_number is None: - core_number = nx.core_number(G) + core_number = find_cores(G) if k is None: k = max(core_number.values()) - 1 - return _core_helper(G, func, k, core_number) + nodes = (v for v in core_number if core_number[v] <= k) + return G.subgraph(nodes).copy() def k_corona(G, k, core_number=None): @@ -335,5 +350,6 @@ def k_corona(G, k, core_number=None): Phys. Rev. E 73, 056101 (2006) http://link.aps.org/doi/10.1103/PhysRevE.73.056101 """ - func = lambda v, k, c: c[v] == k and sum(1 for w in G[v] if c[w] >= k) == k - return _core_helper(G, func, k, core_number) + def func(v, k, c): + return c[v] == k and k == sum(1 for w in G[v] if c[w] >= k) + return _core_subgraph(G, func, k, core_number)
k-core algorithm produces incorrect output for DiGraph As per title, calling `nx.k_core(G, k = x)` does not return the x-core of a graph, if `G` is a `DiGraph`. See attached file. [6954_2011.txt](https://github.com/networkx/networkx/files/105086/6954_2011.txt) To reproduce, run: ```python import networkx as nx G = nx.DiGraph() with open("6954_2011.txt", 'r') as f: for line in f: fields = line.strip().split('\t') G.add_edge(fields[0], fields[1]) core = nx.k_core(G, k = 12) core.number_of_nodes() # Outputs "24"; expected output: "12" ``` There are only 12 nodes with (in+out) degree 12 once you remove recursively all those which don't qualify. These are: IND AUT CHE BEL USA ESP CHN FRA NLD GBR ITA DEU While ```python core.nodes() ``` says `['BEL', 'SWE', 'DEU', 'GBR', 'KOR', 'USA', 'SGP', 'MYS', 'POL', 'NLD', 'HKG', 'FRA', 'CHE', 'ESP', 'CHN', 'AUT', 'THA', 'JPN', 'TUR', 'ITA', 'IND', 'RUS', 'NOR', 'CZE']` The method seems to work ok for `nx.Graph`, or at least I've yet to find a counter-example.
networkx/networkx
diff --git a/networkx/algorithms/tests/test_core.py b/networkx/algorithms/tests/test_core.py index 48399aeed..7119159c8 100644 --- a/networkx/algorithms/tests/test_core.py +++ b/networkx/algorithms/tests/test_core.py @@ -2,8 +2,8 @@ from nose.tools import * import networkx as nx -class TestCore: +class TestCore: def setUp(self): # G is the example graph in Figure 1 from Batagelj and # Zaversnik's paper titled An O(m) Algorithm for Cores @@ -12,103 +12,114 @@ class TestCore: # shown, the 3-core is given by nodes 1-8, the 2-core by nodes # 9-16, the 1-core by nodes 17-20 and node 21 is in the # 0-core. - t1=nx.convert_node_labels_to_integers(nx.tetrahedral_graph(),1) - t2=nx.convert_node_labels_to_integers(t1,5) - G=nx.union(t1,t2) - G.add_edges_from( [(3,7), (2,11), (11,5), (11,12), (5,12), (12,19), - (12,18), (3,9), (7,9), (7,10), (9,10), (9,20), - (17,13), (13,14), (14,15), (15,16), (16,13)]) + t1 = nx.convert_node_labels_to_integers(nx.tetrahedral_graph(), 1) + t2 = nx.convert_node_labels_to_integers(t1, 5) + G = nx.union(t1, t2) + G.add_edges_from([(3, 7), (2, 11), (11, 5), (11, 12), (5, 12), + (12, 19), (12, 18), (3, 9), (7, 9), (7, 10), + (9, 10), (9, 20), (17, 13), (13, 14), (14, 15), + (15, 16), (16, 13)]) G.add_node(21) - self.G=G + self.G = G # Create the graph H resulting from the degree sequence - # [0,1,2,2,2,2,3] when using the Havel-Hakimi algorithm. + # [0, 1, 2, 2, 2, 2, 3] when using the Havel-Hakimi algorithm. - degseq=[0,1,2,2,2,2,3] + degseq = [0, 1, 2, 2, 2, 2, 3] H = nx.havel_hakimi_graph(degseq) - mapping = {6:0, 0:1, 4:3, 5:6, 3:4, 1:2, 2:5 } + mapping = {6: 0, 0: 1, 4: 3, 5: 6, 3: 4, 1: 2, 2: 5} self.H = nx.relabel_nodes(H, mapping) def test_trivial(self): """Empty graph""" G = nx.Graph() - assert_equal(nx.find_cores(G),{}) + assert_equal(nx.find_cores(G), {}) def test_find_cores(self): - cores=nx.find_cores(self.G) - nodes_by_core=[] - for val in [0,1,2,3]: - nodes_by_core.append( sorted([k for k in cores if cores[k]==val])) - assert_equal(nodes_by_core[0],[21]) - assert_equal(nodes_by_core[1],[17, 18, 19, 20]) - assert_equal(nodes_by_core[2],[9, 10, 11, 12, 13, 14, 15, 16]) + core = nx.find_cores(self.G) + nodes_by_core = [sorted([n for n in core if core[n] == val]) + for val in range(4)] + assert_equal(nodes_by_core[0], [21]) + assert_equal(nodes_by_core[1], [17, 18, 19, 20]) + assert_equal(nodes_by_core[2], [9, 10, 11, 12, 13, 14, 15, 16]) assert_equal(nodes_by_core[3], [1, 2, 3, 4, 5, 6, 7, 8]) def test_core_number(self): # smoke test real name - cores=nx.core_number(self.G) + cores = nx.core_number(self.G) def test_find_cores2(self): - cores=nx.find_cores(self.H) - nodes_by_core=[] - for val in [0,1,2]: - nodes_by_core.append( sorted([k for k in cores if cores[k]==val])) - assert_equal(nodes_by_core[0],[0]) - assert_equal(nodes_by_core[1],[1, 3]) - assert_equal(nodes_by_core[2],[2, 4, 5, 6]) + core = nx.find_cores(self.H) + nodes_by_core = [sorted([n for n in core if core[n] == val]) + for val in range(3)] + assert_equal(nodes_by_core[0], [0]) + assert_equal(nodes_by_core[1], [1, 3]) + assert_equal(nodes_by_core[2], [2, 4, 5, 6]) + + def test_directed_find_cores(Self): + '''core number had a bug for directed graphs found in issue #1959''' + # small example where too timid edge removal can make cn[2] = 3 + G = nx.DiGraph() + edges = [(1, 2), (2, 1), (2, 3), (2, 4), (3, 4), (4, 3)] + G.add_edges_from(edges) + assert_equal(nx.core_number(G), {1: 2, 2: 2, 3: 2, 4: 2}) + # small example where too aggressive edge removal can make cn[2] = 2 + more_edges = [(1, 5), (3, 5), (4, 5), (3, 6), (4, 6), (5, 6)] + G.add_edges_from(more_edges) + assert_equal(nx.core_number(G), {1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3}) def test_main_core(self): - main_core_subgraph=nx.k_core(self.H) - assert_equal(sorted(main_core_subgraph.nodes()),[2,4,5,6]) + main_core_subgraph = nx.k_core(self.H) + assert_equal(sorted(main_core_subgraph.nodes()), [2, 4, 5, 6]) def test_k_core(self): # k=0 - k_core_subgraph=nx.k_core(self.H,k=0) - assert_equal(sorted(k_core_subgraph.nodes()),sorted(self.H.nodes())) + k_core_subgraph = nx.k_core(self.H, k=0) + assert_equal(sorted(k_core_subgraph.nodes()), sorted(self.H.nodes())) # k=1 - k_core_subgraph=nx.k_core(self.H,k=1) - assert_equal(sorted(k_core_subgraph.nodes()),[1,2,3,4,5,6]) - # k=2 - k_core_subgraph=nx.k_core(self.H,k=2) - assert_equal(sorted(k_core_subgraph.nodes()),[2,4,5,6]) + k_core_subgraph = nx.k_core(self.H, k=1) + assert_equal(sorted(k_core_subgraph.nodes()), [1, 2, 3, 4, 5, 6]) + # k = 2 + k_core_subgraph = nx.k_core(self.H, k=2) + assert_equal(sorted(k_core_subgraph.nodes()), [2, 4, 5, 6]) def test_main_crust(self): - main_crust_subgraph=nx.k_crust(self.H) - assert_equal(sorted(main_crust_subgraph.nodes()),[0,1,3]) + main_crust_subgraph = nx.k_crust(self.H) + assert_equal(sorted(main_crust_subgraph.nodes()), [0, 1, 3]) def test_k_crust(self): - # k=0 - k_crust_subgraph=nx.k_crust(self.H,k=2) - assert_equal(sorted(k_crust_subgraph.nodes()),sorted(self.H.nodes())) + # k = 0 + k_crust_subgraph = nx.k_crust(self.H, k=2) + assert_equal(sorted(k_crust_subgraph.nodes()), sorted(self.H.nodes())) # k=1 - k_crust_subgraph=nx.k_crust(self.H,k=1) - assert_equal(sorted(k_crust_subgraph.nodes()),[0,1,3]) + k_crust_subgraph = nx.k_crust(self.H, k=1) + assert_equal(sorted(k_crust_subgraph.nodes()), [0, 1, 3]) # k=2 - k_crust_subgraph=nx.k_crust(self.H,k=0) - assert_equal(sorted(k_crust_subgraph.nodes()),[0]) + k_crust_subgraph = nx.k_crust(self.H, k=0) + assert_equal(sorted(k_crust_subgraph.nodes()), [0]) def test_main_shell(self): - main_shell_subgraph=nx.k_shell(self.H) - assert_equal(sorted(main_shell_subgraph.nodes()),[2,4,5,6]) + main_shell_subgraph = nx.k_shell(self.H) + assert_equal(sorted(main_shell_subgraph.nodes()), [2, 4, 5, 6]) def test_k_shell(self): # k=0 - k_shell_subgraph=nx.k_shell(self.H,k=2) - assert_equal(sorted(k_shell_subgraph.nodes()),[2,4,5,6]) + k_shell_subgraph = nx.k_shell(self.H, k=2) + assert_equal(sorted(k_shell_subgraph.nodes()), [2, 4, 5, 6]) # k=1 - k_shell_subgraph=nx.k_shell(self.H,k=1) - assert_equal(sorted(k_shell_subgraph.nodes()),[1,3]) + k_shell_subgraph = nx.k_shell(self.H, k=1) + assert_equal(sorted(k_shell_subgraph.nodes()), [1, 3]) # k=2 - k_shell_subgraph=nx.k_shell(self.H,k=0) - assert_equal(sorted(k_shell_subgraph.nodes()),[0]) + k_shell_subgraph = nx.k_shell(self.H, k=0) + assert_equal(sorted(k_shell_subgraph.nodes()), [0]) def test_k_corona(self): # k=0 - k_corona_subgraph=nx.k_corona(self.H,k=2) - assert_equal(sorted(k_corona_subgraph.nodes()),[2,4,5,6]) + k_corona_subgraph = nx.k_corona(self.H, k=2) + assert_equal(sorted(k_corona_subgraph.nodes()), [2, 4, 5, 6]) # k=1 - k_corona_subgraph=nx.k_corona(self.H,k=1) - assert_equal(sorted(k_corona_subgraph.nodes()),[1]) + k_corona_subgraph = nx.k_corona(self.H, k=1) + assert_equal(sorted(k_corona_subgraph.nodes()), [1]) # k=2 - k_corona_subgraph=nx.k_corona(self.H,k=0) - assert_equal(sorted(k_corona_subgraph.nodes()),[0]) + k_corona_subgraph = nx.k_corona(self.H, k=0) + assert_equal(sorted(k_corona_subgraph.nodes()), [0])
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.112
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y libgdal-dev graphviz" ], "python": "3.6", "reqs_path": [ "requirements/default.txt", "requirements/test.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 decorator==5.1.1 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/networkx/networkx.git@ec6dfae2aaebbbbf0a4620002ab795efa6430c25#egg=networkx nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: networkx channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - decorator==5.1.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/networkx
[ "networkx/algorithms/tests/test_core.py::TestCore::test_directed_find_cores" ]
[ "networkx/algorithms/tests/test_core.py::TestCore::test_find_cores", "networkx/algorithms/tests/test_core.py::TestCore::test_core_number", "networkx/algorithms/tests/test_core.py::TestCore::test_find_cores2", "networkx/algorithms/tests/test_core.py::TestCore::test_main_core", "networkx/algorithms/tests/test_core.py::TestCore::test_k_core", "networkx/algorithms/tests/test_core.py::TestCore::test_main_crust", "networkx/algorithms/tests/test_core.py::TestCore::test_k_crust", "networkx/algorithms/tests/test_core.py::TestCore::test_main_shell", "networkx/algorithms/tests/test_core.py::TestCore::test_k_shell", "networkx/algorithms/tests/test_core.py::TestCore::test_k_corona" ]
[ "networkx/algorithms/tests/test_core.py::TestCore::test_trivial" ]
[]
BSD 3-Clause
403
2,654
[ "networkx/algorithms/core.py" ]
ifosch__accloudtant-52
71d752b9244ff84978a83413be84035a92d5c077
2016-01-30 11:16:12
71d752b9244ff84978a83413be84035a92d5c077
diff --git a/accloudtant/aws/reports.py b/accloudtant/aws/reports.py index 26af2d1..905018e 100644 --- a/accloudtant/aws/reports.py +++ b/accloudtant/aws/reports.py @@ -16,10 +16,13 @@ class Reports(object): def find_reserved_instance(self): for instance in self.instances: - instance.current = float(self.prices.prices[instance.key][instance.region][instance.size]['od']) + instance_region = self.prices.prices[instance.key][instance.region] + instance_size = instance_region[instance.size] + instance.current = float(instance_size['od']) if instance.state == 'stopped': instance.current = 0.0 - instance.best = float(self.prices.prices[instance.key][instance.region][instance.size]['ri']['yrTerm3']['allUpfront']['effectiveHourly']) + instance_allUpfront = instance_size['ri']['yrTerm3']['allUpfront'] + instance.best = float(instance_allUpfront['effectiveHourly']) for reserved in self.reserved_instances['ReservedInstances']: if 'InstancesLeft' not in reserved.keys(): reserved['InstancesLeft'] = reserved['InstanceCount'] @@ -39,6 +42,8 @@ class Reports(object): 'State', 'Launch time', 'Reserved', + 'Current hourly price', + 'Renewed hourly price', ] table = [] for instance in self.instances: @@ -51,6 +56,8 @@ class Reports(object): instance.state, instance.launch_time.strftime('%Y-%m-%d %H:%M:%S'), instance.reserved, + instance.current, + instance.best, ] table.append(row) return tabulate(table, headers)
Add price information to EC2 instances information <!--- @huboard:{"order":6.0732421875,"milestone_order":0.09375,"custom_state":""} -->
ifosch/accloudtant
diff --git a/tests/aws/report_expected.txt b/tests/aws/report_expected.txt index 928efa2..f2bbb8b 100644 --- a/tests/aws/report_expected.txt +++ b/tests/aws/report_expected.txt @@ -1,9 +1,9 @@ -Id Name Type AZ OS State Launch time Reserved ----------- --------- ---------- ---------- ------------------------ ------- ------------------- ---------- -i-912a4392 web1 c3.8xlarge us-east-1c Windows running 2015-10-22 14:15:10 Yes -i-1840273e app1 r2.8xlarge us-east-1b Red Hat Enterprise Linux running 2015-10-22 14:15:10 Yes -i-9840273d app2 r2.8xlarge us-east-1c SUSE Linux running 2015-10-22 14:15:10 Yes -i-1840273d database1 r2.8xlarge us-east-1c Linux/UNIX stopped 2015-10-22 14:15:10 No -i-1840273c database2 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes -i-1840273b database3 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes -i-912a4393 test t1.micro us-east-1c Linux/UNIX running 2015-10-22 14:15:10 No +Id Name Type AZ OS State Launch time Reserved Current hourly price Renewed hourly price +---------- --------- ---------- ---------- ------------------------ ------- ------------------- ---------- ---------------------- ---------------------- +i-912a4392 web1 c3.8xlarge us-east-1c Windows running 2015-10-22 14:15:10 Yes 0.5121 0.3894 +i-1840273e app1 r2.8xlarge us-east-1b Red Hat Enterprise Linux running 2015-10-22 14:15:10 Yes 0.3894 0.3794 +i-9840273d app2 r2.8xlarge us-east-1c SUSE Linux running 2015-10-22 14:15:10 Yes 0.5225 0.389 +i-1840273d database1 r2.8xlarge us-east-1c Linux/UNIX stopped 2015-10-22 14:15:10 No 0 0.379 +i-1840273c database2 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379 +i-1840273b database3 r2.8xlarge us-east-1c Linux/UNIX running 2015-10-22 14:15:10 Yes 0.611 0.379 +i-912a4393 test t1.micro us-east-1c Linux/UNIX running 2015-10-22 14:15:10 No 0.767 0.3892
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/ifosch/accloudtant.git@71d752b9244ff84978a83413be84035a92d5c077#egg=accloudtant boto3==1.37.23 botocore==1.37.23 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 jmespath==1.0.1 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 requests==2.32.3 s3transfer==0.11.4 six==1.17.0 tabulate==0.9.0 tomli==2.2.1 urllib3==1.26.20
name: accloudtant channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - boto3==1.37.23 - botocore==1.37.23 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==8.1.8 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - jmespath==1.0.1 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - requests==2.32.3 - s3transfer==0.11.4 - six==1.17.0 - tabulate==0.9.0 - tomli==2.2.1 - urllib3==1.26.20 prefix: /opt/conda/envs/accloudtant
[ "tests/aws/test_reports.py::test_reports" ]
[]
[ "tests/aws/test_instance.py::test_instance", "tests/aws/test_instance.py::test_guess_os", "tests/aws/test_instance.py::test_match_reserved_instance", "tests/aws/test_prices.py::test_process_ec2", "tests/aws/test_prices.py::test_process_model", "tests/aws/test_prices.py::test_process_generic", "tests/aws/test_prices.py::test_process_on_demand", "tests/aws/test_prices.py::test_process_reserved", "tests/aws/test_prices.py::test_process_data_transfer", "tests/aws/test_prices.py::test_process_ebs", "tests/aws/test_prices.py::test_process_eip", "tests/aws/test_prices.py::test_process_cw", "tests/aws/test_prices.py::test_process_elb", "tests/aws/test_prices.py::test_print_prices", "tests/aws/test_prices.py::test_prices", "tests/aws/test_prices.py::test_prices_with_warning", "tests/test_utils.py::test_fix_lazy_json" ]
[]
null
405
406
[ "accloudtant/aws/reports.py" ]
guykisel__inline-plz-28
59cb7f9721ca3390fa31c48583e786e3728e8f1a
2016-01-31 22:54:38
59cb7f9721ca3390fa31c48583e786e3728e8f1a
diff --git a/inlineplz/linters/__init__.py b/inlineplz/linters/__init__.py index f4b0a73..420508e 100644 --- a/inlineplz/linters/__init__.py +++ b/inlineplz/linters/__init__.py @@ -13,7 +13,7 @@ from inlineplz import parsers LINTERS = { 'prospector': { 'install': ['pip', 'install', 'prospector'], - 'run': ['prospector', '--zero-exit'], + 'run': ['prospector', '--zero-exit', '-o', 'json'], 'dotfiles': ['.prospector.yaml'], 'parser': parsers.ProspectorParser }, diff --git a/inlineplz/parsers/prospector.py b/inlineplz/parsers/prospector.py index 68acb07..8146c2a 100644 --- a/inlineplz/parsers/prospector.py +++ b/inlineplz/parsers/prospector.py @@ -1,43 +1,31 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import +from collections import OrderedDict +import json + from inlineplz.parsers.base import ParserBase from inlineplz.message import Message class ProspectorParser(ParserBase): - """Parse default prospector output.""" + """Parse json prospector output.""" def parse(self, lint_data): messages = [] - current_message = None - current_filename = '' - current_line = '' - - messages_found = False - - for line in lint_data.split('\n'): - # check for message block - if not line.strip(): - continue - if not messages_found: - if line.strip() == 'Messages': - messages_found = True - continue - # check for end of message block - elif line.strip() == 'Check Information': - break - # new filename - if not line.startswith(' '): - current_filename = line.strip() - continue - # new line number - elif not line.startswith(' '): - current_line = int(line.replace(' Line: ', '').strip()) - current_message = Message(current_filename, current_line) - messages.append(current_message) - continue - # new content - current_message.comments.append(line.lstrip()) - + for msgdata in json.loads( + lint_data, + object_pairs_hook=OrderedDict + ).get('messages'): + msg = Message( + msgdata['location']['path'], + msgdata['location']['line'] + ) + msgbody = '{0}: {1} ({2})'.format( + msgdata['source'], + msgdata['message'], + msgdata['code'] + ) + msg.comments.append(msgbody) + messages.append(msg) return messages
refactor prospector parser to use json formatter
guykisel/inline-plz
diff --git a/tests/parsers/test_prospector.py b/tests/parsers/test_prospector.py index f673b81..fbba037 100644 --- a/tests/parsers/test_prospector.py +++ b/tests/parsers/test_prospector.py @@ -17,14 +17,12 @@ prospector_path = os.path.join( def test_prospector(): with open(prospector_path) as inputfile: messages = prospector.ProspectorParser().parse(inputfile.read()) - assert messages[0].content == '`pylint: syntax-error / invalid syntax`' - assert messages[0].line_number == 34 - assert messages[0].path == 'docs/conf.py' - assert messages[1].content == '`pylint: unused-import / Unused Message imported from message`' - assert messages[1].line_number == 4 - assert messages[1].path == 'inline-plz/parsers/base.py' - assert messages[9].content == ('```\npylint: misplaced-comparison-constant / Comparison ' - 'should be __name__ == \'__main__\' (col 3)\npylint: ' - 'pretend this is a real message\n```') - assert messages[9].line_number == 113 - assert len(messages) == 11 + assert messages[0].content == '`pep257: Missing docstring in public package (D104)`' + assert messages[0].line_number == 1 + assert messages[0].path == 'inlineplz/util/__init__.py' + assert messages[1].content == '`pep257: Missing docstring in public package (D104)`' + assert messages[1].line_number == 1 + assert messages[1].path == 'inlineplz/parsers/__init__.py' + assert messages[9].content == ('`pep257: One-line docstring should fit on one line with quotes (found 2) (D200)`') + assert messages[9].line_number == 1 + assert len(messages) == 32 diff --git a/tests/testdata/parsers/prospector.txt b/tests/testdata/parsers/prospector.txt index 7c9ed99..c6ec9f7 100644 --- a/tests/testdata/parsers/prospector.txt +++ b/tests/testdata/parsers/prospector.txt @@ -1,48 +1,407 @@ -Messages -======== - -docs\conf.py - Line: 34 - pylint: syntax-error / invalid syntax - -inline-plz\parsers\base.py - Line: 4 - pylint: unused-import / Unused Message imported from message - Line: 9 - pylint: redefined-builtin / Redefining built-in 'input' (col 20) - -inline-plz\parsers\prospector.py - Line: 5 - pylint: unused-import / Unused Message imported from message - Line: 8 - pylint: redefined-builtin / Redefining built-in 'input' (col 20) - Line: 17 - pylint: undefined-variable / Undefined variable 'message' (col 32) - Line: 24 - pylint: undefined-variable / Undefined variable 'message' (col 32) - Line: 25 - pylint: redefined-variable-type / Redefinition of current_line type from str to int (col 16) - -travis_pypi_setup.py - Line: 20 - pylint: bare-except / No exception type(s) specified - Line: 113 - pylint: misplaced-comparison-constant / Comparison should be __name__ == '__main__' (col 3) - pylint: pretend this is a real message - Line: 114 - pylint: wrong-import-position / Import "import argparse" should be placed at the top of the module (col 4) - - - -Check Information -================= - Started: 2016-01-09 12:50:17.649090 - Finished: 2016-01-09 12:50:19.027461 - Time Taken: 1.38 seconds - Formatter: grouped - Profiles: default, no_doc_warnings, no_test_warnings, strictness_medium, strictness_high, strictness_veryhigh, no_member_warnings - Strictness: None - Libraries Used: - Tools Run: dodgy, mccabe, pep8, profile-validator, pyflakes, pylint - Messages Found: 11 - +{ + "messages": [ + { + "source": "pep257", + "location": { + "character": 0, + "line": 1, + "path": "inlineplz\\util\\__init__.py", + "module": null, + "function": null + }, + "code": "D104", + "message": "Missing docstring in public package" + }, + { + "source": "pep257", + "location": { + "character": 0, + "line": 1, + "path": "inlineplz\\parsers\\__init__.py", + "module": null, + "function": null + }, + "code": "D104", + "message": "Missing docstring in public package" + }, + { + "source": "pylint", + "location": { + "character": 0, + "line": 9, + "path": "inlineplz\\main.py", + "module": "inlineplz.main", + "function": null + }, + "code": "unused-import", + "message": "Unused parsers imported from inlineplz" + }, + { + "source": "pep257", + "location": { + "character": 0, + "line": 11, + "path": "inlineplz\\message.py", + "module": null, + "function": null + }, + "code": "D105", + "message": "Missing docstring in magic method" + }, + { + "source": "pylint", + "location": { + "character": 4, + "line": 8, + "path": "setup.py", + "module": "setup", + "function": null + }, + "code": "import-error", + "message": "Unable to import 'distutils.core'" + }, + { + "source": "pylint", + "location": { + "character": 0, + "line": 17, + "path": "setup.py", + "module": "setup", + "function": null + }, + "code": "invalid-name", + "message": "Invalid constant name \"requirements\"" + }, + { + "source": "pylint", + "location": { + "character": 0, + "line": 23, + "path": "setup.py", + "module": "setup", + "function": null + }, + "code": "invalid-name", + "message": "Invalid constant name \"test_requirements\"" + }, + { + "source": "pylint", + "location": { + "character": 4, + "line": 12, + "path": "setup.py", + "module": "setup", + "function": null + }, + "code": "invalid-name", + "message": "Invalid constant name \"readme\"" + }, + { + "source": "pylint", + "location": { + "character": 4, + "line": 15, + "path": "setup.py", + "module": "setup", + "function": null + }, + "code": "invalid-name", + "message": "Invalid constant name \"history\"" + }, + { + "source": "pep257", + "location": { + "character": 0, + "line": 1, + "path": "travis_pypi_setup.py", + "module": null, + "function": null + }, + "code": "D200", + "message": "One-line docstring should fit on one line with quotes (found 2)" + }, + { + "source": "pylint", + "location": { + "character": 4, + "line": 115, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": null + }, + "code": "invalid-name", + "message": "Invalid constant name \"parser\"" + }, + { + "source": "pep257", + "location": { + "character": 0, + "line": 69, + "path": "travis_pypi_setup.py", + "module": null, + "function": null + }, + "code": "D200", + "message": "One-line docstring should fit on one line with quotes (found 2)" + }, + { + "source": "pylint", + "location": { + "character": 27, + "line": 72, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": "prepend_line" + }, + "code": "invalid-name", + "message": "Invalid variable name \"f\"" + }, + { + "source": "pylint", + "location": { + "character": 9, + "line": 106, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": "main" + }, + "code": "redefined-outer-name", + "message": "Redefining name 'args' from outer scope (line 121)" + }, + { + "source": "pylint", + "location": { + "character": 32, + "line": 77, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": "prepend_line" + }, + "code": "invalid-name", + "message": "Invalid variable name \"f\"" + }, + { + "source": "pylint", + "location": { + "character": 3, + "line": 113, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": null + }, + "code": "misplaced-comparison-constant", + "message": "Comparison should be __name__ == '__main__'" + }, + { + "source": "pylint", + "location": { + "character": 27, + "line": 82, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": "load_yaml_config" + }, + "code": "invalid-name", + "message": "Invalid variable name \"f\"" + }, + { + "source": "pylint", + "location": { + "character": 4, + "line": 19, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": null + }, + "code": "wrong-import-order", + "message": "standard import \"from urllib import urlopen\" comes before \"import yaml\"" + }, + { + "source": "pylint", + "location": { + "character": 0, + "line": 20, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": null + }, + "code": "bare-except", + "message": "No exception type(s) specified" + }, + { + "source": "pylint", + "location": { + "character": 4, + "line": 21, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": null + }, + "code": "wrong-import-order", + "message": "standard import \"from urllib.request import urlopen\" comes before \"import yaml\"" + }, + { + "source": "pylint", + "location": { + "character": 32, + "line": 87, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": "save_yaml_config" + }, + "code": "invalid-name", + "message": "Invalid variable name \"f\"" + }, + { + "source": "pylint", + "location": { + "character": 4, + "line": 121, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": null + }, + "code": "invalid-name", + "message": "Invalid constant name \"args\"" + }, + { + "source": "pylint", + "location": { + "character": 4, + "line": 114, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": null + }, + "code": "wrong-import-order", + "message": "standard import \"import argparse\" comes before \"import yaml\"" + }, + { + "source": "pylint", + "location": { + "character": 4, + "line": 114, + "path": "travis_pypi_setup.py", + "module": "travis_pypi_setup", + "function": null + }, + "code": "wrong-import-position", + "message": "Import \"import argparse\" should be placed at the top of the module" + }, + { + "source": "pep257", + "location": { + "character": 0, + "line": 1, + "path": "inlineplz\\interfaces\\__init__.py", + "module": null, + "function": null + }, + "code": "D104", + "message": "Missing docstring in public package" + }, + { + "source": "pylint", + "location": { + "character": 16, + "line": 36, + "path": "inlineplz\\parsers\\prospector.py", + "module": "inlineplz.parsers.prospector", + "function": "ProspectorParser.parse" + }, + "code": "redefined-variable-type", + "message": "Redefinition of current_line type from str to int" + }, + { + "source": "pylint", + "location": { + "character": 12, + "line": 16, + "path": "inlineplz\\interfaces\\github.py", + "module": "inlineplz.interfaces.github", + "function": "GitHubInterface.__init__" + }, + "code": "invalid-name", + "message": "Invalid attribute name \"gh\"" + }, + { + "source": "pylint", + "location": { + "character": 12, + "line": 18, + "path": "inlineplz\\interfaces\\github.py", + "module": "inlineplz.interfaces.github", + "function": "GitHubInterface.__init__" + }, + "code": "redefined-variable-type", + "message": "Redefinition of self.gh type from github3.github.GitHub to github3.github.GitHubEnterprise" + }, + { + "source": "pylint", + "location": { + "character": 0, + "line": 4, + "path": "inlineplz\\interfaces\\github.py", + "module": "inlineplz.interfaces.github", + "function": null + }, + "code": "unused-import", + "message": "Unused import os.path" + }, + { + "source": "pylint", + "location": { + "character": 20, + "line": 58, + "path": "inlineplz\\interfaces\\github.py", + "module": "inlineplz.interfaces.github", + "function": "GitHubInterface.position" + }, + "code": "unused-variable", + "message": "Unused variable 'hunk_no'" + }, + { + "source": "pylint", + "location": { + "character": 4, + "line": 14, + "path": "inlineplz\\interfaces\\github.py", + "module": "inlineplz.interfaces.github", + "function": "GitHubInterface.__init__" + }, + "code": "too-many-arguments", + "message": "Too many arguments (6/5)" + }, + { + "source": "pep257", + "location": { + "character": 0, + "line": 1, + "path": "inlineplz\\__init__.py", + "module": null, + "function": null + }, + "code": "D104", + "message": "Missing docstring in public package" + } + ], + "summary": { + "strictness": "from profile", + "tools": [ + "dodgy", + "mccabe", + "pep257", + "pep8", + "profile-validator", + "pyflakes", + "pylint" + ], + "formatter": "json", + "started": "2016-01-31 14:43:39.317922", + "profiles": ".prospector.yaml, full_pep8, doc_warnings, no_test_warnings, strictness_veryhigh, no_member_warnings", + "time_taken": "3.94", + "completed": "2016-01-31 14:43:43.256803", + "libraries": [], + "message_count": 32 + } +}
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "numpy>=1.16.0", "pandas>=1.0.0", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 cryptography==44.0.2 exceptiongroup==1.2.2 github3.py==4.0.1 idna==3.10 iniconfig==2.1.0 -e git+https://github.com/guykisel/inline-plz.git@59cb7f9721ca3390fa31c48583e786e3728e8f1a#egg=inlineplz numpy==2.0.2 packaging==24.2 pandas==2.2.3 pluggy==1.5.0 pycparser==2.22 PyJWT==2.10.1 pytest==8.3.5 python-dateutil==2.9.0.post0 pytz==2025.2 requests==2.32.3 six==1.17.0 tomli==2.2.1 tzdata==2025.2 unidiff==0.7.5 uritemplate==4.1.1 urllib3==2.3.0 xmltodict==0.14.2
name: inline-plz channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - cryptography==44.0.2 - exceptiongroup==1.2.2 - github3-py==4.0.1 - idna==3.10 - iniconfig==2.1.0 - numpy==2.0.2 - packaging==24.2 - pandas==2.2.3 - pluggy==1.5.0 - pycparser==2.22 - pyjwt==2.10.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pytz==2025.2 - requests==2.32.3 - six==1.17.0 - tomli==2.2.1 - tzdata==2025.2 - unidiff==0.7.5 - uritemplate==4.1.1 - urllib3==2.3.0 - xmltodict==0.14.2 prefix: /opt/conda/envs/inline-plz
[ "tests/parsers/test_prospector.py::test_prospector" ]
[]
[]
[]
ISC License
407
679
[ "inlineplz/linters/__init__.py", "inlineplz/parsers/prospector.py" ]
JonathonReinhart__scuba-42
9aa705d7d0419f1930ae034e2210d69f66f5bf2a
2016-02-01 13:01:13
9aa705d7d0419f1930ae034e2210d69f66f5bf2a
diff --git a/scuba/__main__.py b/scuba/__main__.py index 57f8671..4a54fae 100755 --- a/scuba/__main__.py +++ b/scuba/__main__.py @@ -217,7 +217,7 @@ def main(argv=None): if g_verbose or scuba_args.dry_run: appmsg('Docker command line:') - print(format_cmdline(run_args)) + print('$ ' + format_cmdline(run_args)) if scuba_args.dry_run: appmsg('Exiting for dry run. Temporary files not removed:') diff --git a/scuba/utils.py b/scuba/utils.py index f4d742b..0bd2e0e 100644 --- a/scuba/utils.py +++ b/scuba/utils.py @@ -3,13 +3,33 @@ try: except ImportError: from pipes import quote as shell_quote + def format_cmdline(args, maxwidth=80): + '''Format args into a shell-quoted command line. + + The result will be wrapped to maxwidth characters where possible, + not breaking a single long argument. + ''' + + # Leave room for the space and backslash at the end of each line + maxwidth -= 2 + def lines(): line = '' for a in (shell_quote(a) for a in args): - if len(line) + len(a) > maxwidth: + # If adding this argument will make the line too long, + # yield the current line, and start a new one. + if len(line) + len(a) + 1 > maxwidth: yield line line = '' - line += ' ' + a - return '$' + ' \\\n'.join(lines()) + # Append this argument to the current line, separating + # it by a space from the existing arguments. + if line: + line += ' ' + a + else: + line = a + + yield line + + return ' \\\n'.join(lines())
utils.format_cmdline misses last line It appears that utils.format_cmdline fails to yield the last accumulated line. This also means that a better test could be written, which splits the result back out, and compares it to the list of input arguments.
JonathonReinhart/scuba
diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..ff9ad97 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,49 @@ +from __future__ import print_function + +from nose.tools import * +from unittest import TestCase + +import logging +import shlex +from itertools import chain + +from .utils import * + +import scuba.utils + + +class TestUtils(TestCase): + + def _parse_cmdline(self, cmdline): + # Strip the formatting and whitespace + lines = [l.rstrip('\\').strip() for l in cmdline.splitlines()] + + # Split each line, and return a flattened list of arguments + return chain.from_iterable(map(shlex.split, lines)) + + def _test_format_cmdline(self, args): + + # Call the unit-under-test to get the formatted command line + result = scuba.utils.format_cmdline(args) + + # Parse the result back out to a list of arguments + out_args = self._parse_cmdline(result) + + # Verify that they match + assert_seq_equal(out_args, args) + + + def test_basic(self): + '''format_cmdline works as expected''' + + self._test_format_cmdline([ + 'something', + '-a', + '-b', + '--long', 'option text', + '-s', 'hort', + 'a very long argument here that will end up on its own line because it is so wide and nothing else will fit at the default width', + 'and now', + 'some', 'more', 'stuff', + 'and even more stuff', + ])
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 2 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 coverage==3.7.1 importlib-metadata==4.8.3 iniconfig==1.1.1 nose==1.3.7 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 -e git+https://github.com/JonathonReinhart/scuba.git@9aa705d7d0419f1930ae034e2210d69f66f5bf2a#egg=SCUBA tomli==1.2.3 typing_extensions==4.1.1 zipp==3.6.0
name: scuba channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - coverage==3.7.1 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/scuba
[ "tests/test_utils.py::TestUtils::test_basic" ]
[]
[]
[]
MIT License
409
483
[ "scuba/__main__.py", "scuba/utils.py" ]
scieloorg__xylose-88
09b42b365b375904f5d7102277e3f4e4a3d59e7f
2016-02-12 14:15:41
09b42b365b375904f5d7102277e3f4e4a3d59e7f
diff --git a/setup.py b/setup.py index 7516cbd..d1e1950 100755 --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ except ImportError: setup( name="xylose", - version='0.42', + version='0.43', description="A SciELO library to abstract a JSON data structure that is a product of the ISIS2JSON conversion using the ISIS2JSON type 3 data model.", author="SciELO", author_email="[email protected]", diff --git a/xylose/scielodocument.py b/xylose/scielodocument.py index 03c2510..9b4cf43 100644 --- a/xylose/scielodocument.py +++ b/xylose/scielodocument.py @@ -195,10 +195,8 @@ class Journal(object): This method retrieves the original language of the given article. This method deals with the legacy fields (v400). """ - if not 'v400' in self.data: - return None - return self.data['v400'][0]['_'] + return self.data.get('v400', [{'_': None}])[0]['_'] def url(self, language='en'): """ @@ -235,15 +233,6 @@ class Journal(object): if 'v854' in self.data: return [area['_'] for area in self.data['v854']] - @property - def abbreviated_title(self): - """ - This method retrieves the journal abbreviated title of the given article, if it exists. - This method deals with the legacy fields (150). - """ - if 'v150' in self.data: - return self.data['v150'][0]['_'] - @property def wos_citation_indexes(self): """ @@ -273,8 +262,7 @@ class Journal(object): This method deals with the legacy fields (480). """ - if 'v480' in self.data: - return self.data['v480'][0]['_'] + return self.data.get('v480', [{'_': None}])[0]['_'] @property def publisher_loc(self): @@ -284,8 +272,7 @@ class Journal(object): This method deals with the legacy fields (490). """ - if 'v490' in self.data: - return self.data['v490'][0]['_'] + return self.data.get('v490', [{'_': None}])[0]['_'] @property def title(self): @@ -295,8 +282,30 @@ class Journal(object): This method deals with the legacy fields (100). """ - if 'v100' in self.data: - return self.data['v100'][0]['_'] + return self.data.get('v100', [{'_': None}])[0]['_'] + + @property + def subtitle(self): + """ + This method retrieves the journal subtitle. + This method deals with the legacy fields (v110). + """ + + return self.data.get('v110', [{'_': None}])[0]['_'] + + @property + def fulltitle(self): + """ + This method retrieves the join of the journal title plus the subtitle. + This method deals with the legacy fields (v100, v110). + """ + + data = [] + + data.append(self.title) + data.append(self.subtitle) + + return ' - '.join([i for i in data if i]) @property def title_nlm(self): @@ -306,8 +315,25 @@ class Journal(object): This method deals with the legacy fields (421). """ - if 'v421' in self.data: - return self.data['v421'][0]['_'] + return self.data.get('v421', [{'_': None}])[0]['_'] + + @property + def abbreviated_title(self): + """ + This method retrieves the journal abbreviated title of the given article, if it exists. + This method deals with the legacy fields (150). + """ + + return self.data.get('v150', [{'_': None}])[0]['_'] + + @property + def abbreviated_iso_title(self): + """ + This method retrieves the journal abbreviated title of the given article, if it exists. + This method deals with the legacy fields (151). + """ + + return self.data.get('v151', [{'_': None}])[0]['_'] @property def acronym(self): @@ -317,8 +343,7 @@ class Journal(object): This method deals with the legacy fields (68). """ - if 'v68' in self.data: - return self.data['v68'][0]['_'].lower() + return self.data.get('v68', [{'_': None}])[0]['_'] @property def periodicity(self): @@ -401,6 +426,7 @@ class Journal(object): return tools.get_date(self.data['v941'][0]['_']) + class Article(object): def __init__(self, data, iso_format=None):
Incluir metodo para recuperar subtitulo do periódico v110 Incluir metodo para recuperar subtitulo do periódico v110 (subtitle) Incluir metodo para recuperar titulo do periódico concatenado com subtitulo do periódico v110 (full_title)
scieloorg/xylose
diff --git a/tests/test_document.py b/tests/test_document.py index 6ade9eb..7405ad9 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -623,11 +623,47 @@ class JournalTests(unittest.TestCase): def test_journal_title_nlm(self): self.fulldoc['title']['v421'] = [{u'_': u'Acta Limnologica Brasiliensia NLM'}] - + journal = Journal(self.fulldoc['title']) self.assertEqual(journal.title_nlm, u'Acta Limnologica Brasiliensia NLM') + def test_journal_fulltitle(self): + self.fulldoc['title']['v100'] = [{u'_': u'Title'}] + self.fulldoc['title']['v110'] = [{u'_': u'SubTitle'}] + + journal = Journal(self.fulldoc['title']) + + self.assertEqual(journal.fulltitle, u'Title - SubTitle') + + def test_journal_fulltitle_without_title(self): + del(self.fulldoc['title']['v100']) + self.fulldoc['title']['v110'] = [{u'_': u'SubTitle'}] + + journal = Journal(self.fulldoc['title']) + + self.assertEqual(journal.fulltitle, u'SubTitle') + + def test_journal_fulltitle_without_subtitle(self): + self.fulldoc['title']['v100'] = [{u'_': u'Title'}] + + journal = Journal(self.fulldoc['title']) + + self.assertEqual(journal.fulltitle, u'Title') + + def test_journal_subtitle(self): + self.fulldoc['title']['v110'] = [{u'_': u'SubTitle'}] + + journal = Journal(self.fulldoc['title']) + + self.assertEqual(journal.subtitle, u'SubTitle') + + def test_journal_without_subtitle(self): + + journal = Journal(self.fulldoc['title']) + + self.assertEqual(journal.subtitle, None) + def test_without_journal_title_nlm(self): journal = self.journal
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 2 }
0.42
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc pandoc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 tomli==2.2.1 -e git+https://github.com/scieloorg/xylose.git@09b42b365b375904f5d7102277e3f4e4a3d59e7f#egg=xylose
name: xylose channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - tomli==2.2.1 prefix: /opt/conda/envs/xylose
[ "tests/test_document.py::JournalTests::test_journal_fulltitle", "tests/test_document.py::JournalTests::test_journal_fulltitle_without_subtitle", "tests/test_document.py::JournalTests::test_journal_fulltitle_without_title", "tests/test_document.py::JournalTests::test_journal_subtitle", "tests/test_document.py::JournalTests::test_journal_without_subtitle" ]
[]
[ "tests/test_document.py::ToolsTests::test_get_date_wrong_day", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_month", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_month_not_int", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_not_int", "tests/test_document.py::ToolsTests::test_get_date_wrong_month_not_int", "tests/test_document.py::ToolsTests::test_get_date_year", "tests/test_document.py::ToolsTests::test_get_date_year_day", "tests/test_document.py::ToolsTests::test_get_date_year_month", "tests/test_document.py::ToolsTests::test_get_date_year_month_day", "tests/test_document.py::ToolsTests::test_get_date_year_month_day_31", "tests/test_document.py::ToolsTests::test_get_language_iso639_1_defined", "tests/test_document.py::ToolsTests::test_get_language_iso639_1_undefined", "tests/test_document.py::ToolsTests::test_get_language_iso639_2_defined", "tests/test_document.py::ToolsTests::test_get_language_iso639_2_undefined", "tests/test_document.py::ToolsTests::test_get_language_without_iso_format", "tests/test_document.py::JournalTests::test_any_issn_priority_electronic", "tests/test_document.py::JournalTests::test_any_issn_priority_electronic_without_electronic", "tests/test_document.py::JournalTests::test_any_issn_priority_print", "tests/test_document.py::JournalTests::test_any_issn_priority_print_without_print", "tests/test_document.py::JournalTests::test_collection_acronym", "tests/test_document.py::JournalTests::test_creation_date", "tests/test_document.py::JournalTests::test_current_status", "tests/test_document.py::JournalTests::test_current_status_lots_of_changes_study_case_1", "tests/test_document.py::JournalTests::test_current_status_some_changes", "tests/test_document.py::JournalTests::test_current_without_v51", "tests/test_document.py::JournalTests::test_journal", "tests/test_document.py::JournalTests::test_journal_abbreviated_title", "tests/test_document.py::JournalTests::test_journal_acronym", "tests/test_document.py::JournalTests::test_journal_title", "tests/test_document.py::JournalTests::test_journal_title_nlm", "tests/test_document.py::JournalTests::test_journal_url", "tests/test_document.py::JournalTests::test_languages", "tests/test_document.py::JournalTests::test_languages_without_v350", "tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_with_v935_without_v35", "tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_without_v935_without_v35", "tests/test_document.py::JournalTests::test_periodicity", "tests/test_document.py::JournalTests::test_periodicity_out_of_choices", "tests/test_document.py::JournalTests::test_permission_id", "tests/test_document.py::JournalTests::test_permission_t0", "tests/test_document.py::JournalTests::test_permission_t1", "tests/test_document.py::JournalTests::test_permission_t2", "tests/test_document.py::JournalTests::test_permission_t3", "tests/test_document.py::JournalTests::test_permission_t4", "tests/test_document.py::JournalTests::test_permission_text", "tests/test_document.py::JournalTests::test_permission_url", "tests/test_document.py::JournalTests::test_permission_without_v540", "tests/test_document.py::JournalTests::test_permission_without_v540_t", "tests/test_document.py::JournalTests::test_publisher_loc", "tests/test_document.py::JournalTests::test_publisher_name", "tests/test_document.py::JournalTests::test_scielo_issn", "tests/test_document.py::JournalTests::test_status", "tests/test_document.py::JournalTests::test_status_lots_of_changes", "tests/test_document.py::JournalTests::test_status_lots_of_changes_study_case_1", "tests/test_document.py::JournalTests::test_status_lots_of_changes_with_reason", "tests/test_document.py::JournalTests::test_status_some_changes", "tests/test_document.py::JournalTests::test_status_without_v51", "tests/test_document.py::JournalTests::test_subject_areas", "tests/test_document.py::JournalTests::test_update_date", "tests/test_document.py::JournalTests::test_without_journal_abbreviated_title", "tests/test_document.py::JournalTests::test_without_journal_acronym", "tests/test_document.py::JournalTests::test_without_journal_title", "tests/test_document.py::JournalTests::test_without_journal_title_nlm", "tests/test_document.py::JournalTests::test_without_journal_url", "tests/test_document.py::JournalTests::test_without_periodicity", "tests/test_document.py::JournalTests::test_without_publisher_loc", "tests/test_document.py::JournalTests::test_without_publisher_name", "tests/test_document.py::JournalTests::test_without_scielo_domain", "tests/test_document.py::JournalTests::test_without_scielo_domain_title_v690", "tests/test_document.py::JournalTests::test_without_subject_areas", "tests/test_document.py::JournalTests::test_without_wos_citation_indexes", "tests/test_document.py::JournalTests::test_without_wos_subject_areas", "tests/test_document.py::JournalTests::test_wos_citation_indexes", "tests/test_document.py::JournalTests::test_wos_subject_areas", "tests/test_document.py::ArticleTests::test_acceptance_date", "tests/test_document.py::ArticleTests::test_affiliation_just_with_affiliation_name", "tests/test_document.py::ArticleTests::test_affiliation_without_affiliation_name", "tests/test_document.py::ArticleTests::test_affiliations", "tests/test_document.py::ArticleTests::test_ahead_publication_date", "tests/test_document.py::ArticleTests::test_article", "tests/test_document.py::ArticleTests::test_author_with_two_affiliations", "tests/test_document.py::ArticleTests::test_author_with_two_role", "tests/test_document.py::ArticleTests::test_author_without_affiliations", "tests/test_document.py::ArticleTests::test_author_without_surname_and_given_names", "tests/test_document.py::ArticleTests::test_authors", "tests/test_document.py::ArticleTests::test_collection_acronym", "tests/test_document.py::ArticleTests::test_collection_acronym_priorizing_collection", "tests/test_document.py::ArticleTests::test_collection_acronym_retrieving_v992", "tests/test_document.py::ArticleTests::test_collection_name_brazil", "tests/test_document.py::ArticleTests::test_collection_name_undefined", "tests/test_document.py::ArticleTests::test_corporative_authors", "tests/test_document.py::ArticleTests::test_creation_date", "tests/test_document.py::ArticleTests::test_creation_date_1", "tests/test_document.py::ArticleTests::test_creation_date_2", "tests/test_document.py::ArticleTests::test_document_type", "tests/test_document.py::ArticleTests::test_doi", "tests/test_document.py::ArticleTests::test_doi_clean_1", "tests/test_document.py::ArticleTests::test_doi_clean_2", "tests/test_document.py::ArticleTests::test_doi_v237", "tests/test_document.py::ArticleTests::test_e_location", "tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_1", "tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_2", "tests/test_document.py::ArticleTests::test_end_page_loaded_through_xml", "tests/test_document.py::ArticleTests::test_file_code", "tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_1", "tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_2", "tests/test_document.py::ArticleTests::test_first_author", "tests/test_document.py::ArticleTests::test_first_author_without_author", "tests/test_document.py::ArticleTests::test_fulltexts_field_fulltexts", "tests/test_document.py::ArticleTests::test_fulltexts_without_field_fulltexts", "tests/test_document.py::ArticleTests::test_html_url", "tests/test_document.py::ArticleTests::test_invalid_document_type", "tests/test_document.py::ArticleTests::test_is_ahead", "tests/test_document.py::ArticleTests::test_issue", "tests/test_document.py::ArticleTests::test_issue_label_field_v4", "tests/test_document.py::ArticleTests::test_issue_label_without_field_v4", "tests/test_document.py::ArticleTests::test_issue_url", "tests/test_document.py::ArticleTests::test_journal_abbreviated_title", "tests/test_document.py::ArticleTests::test_journal_acronym", "tests/test_document.py::ArticleTests::test_journal_title", "tests/test_document.py::ArticleTests::test_keywords", "tests/test_document.py::ArticleTests::test_keywords_iso639_2", "tests/test_document.py::ArticleTests::test_keywords_with_undefined_language", "tests/test_document.py::ArticleTests::test_keywords_without_subfield_k", "tests/test_document.py::ArticleTests::test_keywords_without_subfield_l", "tests/test_document.py::ArticleTests::test_languages_field_fulltexts", "tests/test_document.py::ArticleTests::test_languages_field_v40", "tests/test_document.py::ArticleTests::test_last_page", "tests/test_document.py::ArticleTests::test_mixed_affiliations_1", "tests/test_document.py::ArticleTests::test_normalized_affiliations", "tests/test_document.py::ArticleTests::test_normalized_affiliations_undefined_ISO_3166_CODE", "tests/test_document.py::ArticleTests::test_normalized_affiliations_without_p", "tests/test_document.py::ArticleTests::test_order", "tests/test_document.py::ArticleTests::test_original_abstract_with_just_one_language_defined", "tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined", "tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined_but_different_of_the_article_original_language", "tests/test_document.py::ArticleTests::test_original_abstract_without_language_defined", "tests/test_document.py::ArticleTests::test_original_html_field_body", "tests/test_document.py::ArticleTests::test_original_language_invalid_iso639_2", "tests/test_document.py::ArticleTests::test_original_language_iso639_2", "tests/test_document.py::ArticleTests::test_original_language_original", "tests/test_document.py::ArticleTests::test_original_section_field_v49", "tests/test_document.py::ArticleTests::test_original_title_subfield_t", "tests/test_document.py::ArticleTests::test_original_title_with_just_one_language_defined", "tests/test_document.py::ArticleTests::test_original_title_with_language_defined", "tests/test_document.py::ArticleTests::test_original_title_with_language_defined_but_different_of_the_article_original_language", "tests/test_document.py::ArticleTests::test_original_title_without_language_defined", "tests/test_document.py::ArticleTests::test_pdf_url", "tests/test_document.py::ArticleTests::test_processing_date", "tests/test_document.py::ArticleTests::test_processing_date_1", "tests/test_document.py::ArticleTests::test_project_name", "tests/test_document.py::ArticleTests::test_project_sponsors", "tests/test_document.py::ArticleTests::test_publication_contract", "tests/test_document.py::ArticleTests::test_publication_date", "tests/test_document.py::ArticleTests::test_publisher_id", "tests/test_document.py::ArticleTests::test_publisher_loc", "tests/test_document.py::ArticleTests::test_publisher_name", "tests/test_document.py::ArticleTests::test_receive_date", "tests/test_document.py::ArticleTests::test_review_date", "tests/test_document.py::ArticleTests::test_secion_code_field_v49", "tests/test_document.py::ArticleTests::test_section_code_nd_field_v49", "tests/test_document.py::ArticleTests::test_section_code_without_field_v49", "tests/test_document.py::ArticleTests::test_section_field_v49", "tests/test_document.py::ArticleTests::test_section_nd_field_v49", "tests/test_document.py::ArticleTests::test_section_without_field_v49", "tests/test_document.py::ArticleTests::test_start_page", "tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_1", "tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_2", "tests/test_document.py::ArticleTests::test_start_page_loaded_through_xml", "tests/test_document.py::ArticleTests::test_subject_areas", "tests/test_document.py::ArticleTests::test_supplement_issue", "tests/test_document.py::ArticleTests::test_supplement_volume", "tests/test_document.py::ArticleTests::test_thesis_degree", "tests/test_document.py::ArticleTests::test_thesis_organization", "tests/test_document.py::ArticleTests::test_thesis_organization_and_division", "tests/test_document.py::ArticleTests::test_thesis_organization_without_name", "tests/test_document.py::ArticleTests::test_translated_abstracts", "tests/test_document.py::ArticleTests::test_translated_abstracts_without_v83", "tests/test_document.py::ArticleTests::test_translated_abtracts_iso639_2", "tests/test_document.py::ArticleTests::test_translated_htmls_field_body", "tests/test_document.py::ArticleTests::test_translated_section_field_v49", "tests/test_document.py::ArticleTests::test_translated_titles", "tests/test_document.py::ArticleTests::test_translated_titles_iso639_2", "tests/test_document.py::ArticleTests::test_translated_titles_without_v12", "tests/test_document.py::ArticleTests::test_update_date", "tests/test_document.py::ArticleTests::test_update_date_1", "tests/test_document.py::ArticleTests::test_update_date_2", "tests/test_document.py::ArticleTests::test_update_date_3", "tests/test_document.py::ArticleTests::test_volume", "tests/test_document.py::ArticleTests::test_whitwout_acceptance_date", "tests/test_document.py::ArticleTests::test_whitwout_ahead_publication_date", "tests/test_document.py::ArticleTests::test_whitwout_receive_date", "tests/test_document.py::ArticleTests::test_whitwout_review_date", "tests/test_document.py::ArticleTests::test_without_affiliations", "tests/test_document.py::ArticleTests::test_without_authors", "tests/test_document.py::ArticleTests::test_without_citations", "tests/test_document.py::ArticleTests::test_without_collection_acronym", "tests/test_document.py::ArticleTests::test_without_corporative_authors", "tests/test_document.py::ArticleTests::test_without_document_type", "tests/test_document.py::ArticleTests::test_without_doi", "tests/test_document.py::ArticleTests::test_without_e_location", "tests/test_document.py::ArticleTests::test_without_html_url", "tests/test_document.py::ArticleTests::test_without_issue", "tests/test_document.py::ArticleTests::test_without_issue_url", "tests/test_document.py::ArticleTests::test_without_journal_abbreviated_title", "tests/test_document.py::ArticleTests::test_without_journal_acronym", "tests/test_document.py::ArticleTests::test_without_journal_title", "tests/test_document.py::ArticleTests::test_without_keywords", "tests/test_document.py::ArticleTests::test_without_last_page", "tests/test_document.py::ArticleTests::test_without_normalized_affiliations", "tests/test_document.py::ArticleTests::test_without_order", "tests/test_document.py::ArticleTests::test_without_original_abstract", "tests/test_document.py::ArticleTests::test_without_original_title", "tests/test_document.py::ArticleTests::test_without_pages", "tests/test_document.py::ArticleTests::test_without_pdf_url", "tests/test_document.py::ArticleTests::test_without_processing_date", "tests/test_document.py::ArticleTests::test_without_project_name", "tests/test_document.py::ArticleTests::test_without_project_sponsor", "tests/test_document.py::ArticleTests::test_without_publication_contract", "tests/test_document.py::ArticleTests::test_without_publication_date", "tests/test_document.py::ArticleTests::test_without_publisher_id", "tests/test_document.py::ArticleTests::test_without_publisher_loc", "tests/test_document.py::ArticleTests::test_without_publisher_name", "tests/test_document.py::ArticleTests::test_without_scielo_domain", "tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69", "tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69_and_with_title_v690", "tests/test_document.py::ArticleTests::test_without_scielo_domain_title_v690", "tests/test_document.py::ArticleTests::test_without_start_page", "tests/test_document.py::ArticleTests::test_without_subject_areas", "tests/test_document.py::ArticleTests::test_without_suplement_issue", "tests/test_document.py::ArticleTests::test_without_supplement_volume", "tests/test_document.py::ArticleTests::test_without_thesis_degree", "tests/test_document.py::ArticleTests::test_without_thesis_organization", "tests/test_document.py::ArticleTests::test_without_volume", "tests/test_document.py::ArticleTests::test_without_wos_citation_indexes", "tests/test_document.py::ArticleTests::test_without_wos_subject_areas", "tests/test_document.py::ArticleTests::test_wos_citation_indexes", "tests/test_document.py::ArticleTests::test_wos_subject_areas", "tests/test_document.py::CitationTest::test_a_link_access_date", "tests/test_document.py::CitationTest::test_analytic_institution_for_a_article_citation", "tests/test_document.py::CitationTest::test_analytic_institution_for_a_book_citation", "tests/test_document.py::CitationTest::test_article_title", "tests/test_document.py::CitationTest::test_article_without_title", "tests/test_document.py::CitationTest::test_authors_article", "tests/test_document.py::CitationTest::test_authors_book", "tests/test_document.py::CitationTest::test_authors_link", "tests/test_document.py::CitationTest::test_authors_thesis", "tests/test_document.py::CitationTest::test_book_chapter_title", "tests/test_document.py::CitationTest::test_book_edition", "tests/test_document.py::CitationTest::test_book_volume", "tests/test_document.py::CitationTest::test_book_without_chapter_title", "tests/test_document.py::CitationTest::test_citation_sample_congress", "tests/test_document.py::CitationTest::test_citation_sample_link", "tests/test_document.py::CitationTest::test_citation_sample_link_without_comment", "tests/test_document.py::CitationTest::test_conference_edition", "tests/test_document.py::CitationTest::test_conference_name", "tests/test_document.py::CitationTest::test_conference_sponsor", "tests/test_document.py::CitationTest::test_conference_without_name", "tests/test_document.py::CitationTest::test_conference_without_sponsor", "tests/test_document.py::CitationTest::test_date", "tests/test_document.py::CitationTest::test_doi", "tests/test_document.py::CitationTest::test_editor", "tests/test_document.py::CitationTest::test_elocation_14", "tests/test_document.py::CitationTest::test_elocation_514", "tests/test_document.py::CitationTest::test_end_page_14", "tests/test_document.py::CitationTest::test_end_page_514", "tests/test_document.py::CitationTest::test_end_page_withdout_data", "tests/test_document.py::CitationTest::test_first_author_article", "tests/test_document.py::CitationTest::test_first_author_book", "tests/test_document.py::CitationTest::test_first_author_link", "tests/test_document.py::CitationTest::test_first_author_thesis", "tests/test_document.py::CitationTest::test_first_author_without_monographic_authors", "tests/test_document.py::CitationTest::test_first_author_without_monographic_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_index_number", "tests/test_document.py::CitationTest::test_institutions_all_fields", "tests/test_document.py::CitationTest::test_institutions_v11", "tests/test_document.py::CitationTest::test_institutions_v17", "tests/test_document.py::CitationTest::test_institutions_v29", "tests/test_document.py::CitationTest::test_institutions_v50", "tests/test_document.py::CitationTest::test_institutions_v58", "tests/test_document.py::CitationTest::test_invalid_edition", "tests/test_document.py::CitationTest::test_isbn", "tests/test_document.py::CitationTest::test_isbn_but_not_a_book", "tests/test_document.py::CitationTest::test_issn", "tests/test_document.py::CitationTest::test_issn_but_not_an_article", "tests/test_document.py::CitationTest::test_issue_part", "tests/test_document.py::CitationTest::test_issue_title", "tests/test_document.py::CitationTest::test_journal_issue", "tests/test_document.py::CitationTest::test_journal_volume", "tests/test_document.py::CitationTest::test_link", "tests/test_document.py::CitationTest::test_link_title", "tests/test_document.py::CitationTest::test_link_without_title", "tests/test_document.py::CitationTest::test_monographic_authors", "tests/test_document.py::CitationTest::test_monographic_first_author", "tests/test_document.py::CitationTest::test_pages_14", "tests/test_document.py::CitationTest::test_pages_514", "tests/test_document.py::CitationTest::test_pages_withdout_data", "tests/test_document.py::CitationTest::test_publication_type_article", "tests/test_document.py::CitationTest::test_publication_type_book", "tests/test_document.py::CitationTest::test_publication_type_conference", "tests/test_document.py::CitationTest::test_publication_type_link", "tests/test_document.py::CitationTest::test_publication_type_thesis", "tests/test_document.py::CitationTest::test_publication_type_undefined", "tests/test_document.py::CitationTest::test_publisher", "tests/test_document.py::CitationTest::test_publisher_address", "tests/test_document.py::CitationTest::test_publisher_address_without_e", "tests/test_document.py::CitationTest::test_series_book", "tests/test_document.py::CitationTest::test_series_but_neither_journal_book_or_conference_citation", "tests/test_document.py::CitationTest::test_series_conference", "tests/test_document.py::CitationTest::test_series_journal", "tests/test_document.py::CitationTest::test_source_book_title", "tests/test_document.py::CitationTest::test_source_journal", "tests/test_document.py::CitationTest::test_source_journal_without_journal_title", "tests/test_document.py::CitationTest::test_sponsor", "tests/test_document.py::CitationTest::test_start_page_14", "tests/test_document.py::CitationTest::test_start_page_514", "tests/test_document.py::CitationTest::test_start_page_withdout_data", "tests/test_document.py::CitationTest::test_thesis_institution", "tests/test_document.py::CitationTest::test_thesis_title", "tests/test_document.py::CitationTest::test_thesis_without_title", "tests/test_document.py::CitationTest::test_title_when_article_citation", "tests/test_document.py::CitationTest::test_title_when_conference_citation", "tests/test_document.py::CitationTest::test_title_when_link_citation", "tests/test_document.py::CitationTest::test_title_when_thesis_citation", "tests/test_document.py::CitationTest::test_with_volume_but_not_a_journal_article_neither_a_book", "tests/test_document.py::CitationTest::test_without_analytic_institution", "tests/test_document.py::CitationTest::test_without_authors", "tests/test_document.py::CitationTest::test_without_date", "tests/test_document.py::CitationTest::test_without_doi", "tests/test_document.py::CitationTest::test_without_edition", "tests/test_document.py::CitationTest::test_without_editor", "tests/test_document.py::CitationTest::test_without_first_author", "tests/test_document.py::CitationTest::test_without_index_number", "tests/test_document.py::CitationTest::test_without_institutions", "tests/test_document.py::CitationTest::test_without_issue", "tests/test_document.py::CitationTest::test_without_issue_part", "tests/test_document.py::CitationTest::test_without_issue_title", "tests/test_document.py::CitationTest::test_without_link", "tests/test_document.py::CitationTest::test_without_monographic_authors", "tests/test_document.py::CitationTest::test_without_monographic_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_without_publisher", "tests/test_document.py::CitationTest::test_without_publisher_address", "tests/test_document.py::CitationTest::test_without_series", "tests/test_document.py::CitationTest::test_without_sponsor", "tests/test_document.py::CitationTest::test_without_thesis_institution", "tests/test_document.py::CitationTest::test_without_volume" ]
[]
BSD 2-Clause "Simplified" License
426
1,301
[ "setup.py", "xylose/scielodocument.py" ]
harlowja__fasteners-23
8b63aafd5a9cde3e506810b5df52174d016edd2d
2016-02-15 22:24:40
8b63aafd5a9cde3e506810b5df52174d016edd2d
diff --git a/fasteners/process_lock.py b/fasteners/process_lock.py index b5b7405..72e4f4d 100644 --- a/fasteners/process_lock.py +++ b/fasteners/process_lock.py @@ -214,30 +214,44 @@ class _InterProcessLock(object): return os.path.exists(self.path) def trylock(self): - raise NotImplementedError() + self._trylock(self.lockfile) def unlock(self): + self._unlock(self.lockfile) + + @staticmethod + def _trylock(): + raise NotImplementedError() + + @staticmethod + def _unlock(): raise NotImplementedError() class _WindowsLock(_InterProcessLock): """Interprocess lock implementation that works on windows systems.""" - def trylock(self): - msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_NBLCK, 1) + @staticmethod + def _trylock(lockfile): + fileno = lockfile.fileno() + msvcrt.locking(fileno, msvcrt.LK_NBLCK, 1) - def unlock(self): - msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_UNLCK, 1) + @staticmethod + def _unlock(lockfile): + fileno = lockfile.fileno() + msvcrt.locking(fileno, msvcrt.LK_UNLCK, 1) class _FcntlLock(_InterProcessLock): """Interprocess lock implementation that works on posix systems.""" - def trylock(self): - fcntl.lockf(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) + @staticmethod + def _trylock(lockfile): + fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) - def unlock(self): - fcntl.lockf(self.lockfile, fcntl.LOCK_UN) + @staticmethod + def _unlock(lockfile): + fcntl.lockf(lockfile, fcntl.LOCK_UN) if os.name == 'nt':
Process Lock tests assume POSIX The `test_process_lock` module assumes we're on a POSIX system. It *looks* like it can be fixed pretty easily, but I really don't know much about the details of locking on various platforms. Here we import `fcntl`: https://github.com/harlowja/fasteners/blob/master/fasteners/tests/test_process_lock.py#L19 And here we use it: https://github.com/harlowja/fasteners/blob/master/fasteners/tests/test_process_lock.py#L127 And here it looks like we could be using this instead: https://github.com/harlowja/fasteners/blob/master/fasteners/process_lock.py#L227
harlowja/fasteners
diff --git a/fasteners/tests/test_process_lock.py b/fasteners/tests/test_process_lock.py index 9e96589..d31632d 100644 --- a/fasteners/tests/test_process_lock.py +++ b/fasteners/tests/test_process_lock.py @@ -15,12 +15,12 @@ # License for the specific language governing permissions and limitations # under the License. +import contextlib import errno -import fcntl import multiprocessing import os import shutil -import signal +import sys import tempfile import threading import time @@ -28,6 +28,8 @@ import time from fasteners import process_lock as pl from fasteners import test +WIN32 = os.name == 'nt' + class BrokenLock(pl.InterProcessLock): def __init__(self, name, errno_code): @@ -43,6 +45,87 @@ class BrokenLock(pl.InterProcessLock): raise err [email protected] +def scoped_child_processes(children, timeout=0.1, exitcode=0): + for child in children: + child.daemon = True + child.start() + yield + start = time.time() + timed_out = 0 + + for child in children: + child.join(max(timeout - (time.time() - start), 0)) + if child.is_alive(): + timed_out += 1 + child.terminate() + + if timed_out: + msg = "{} child processes killed due to timeout\n".format(timed_out) + sys.stderr.write(msg) + + if exitcode is not None: + for child in children: + c_code = child.exitcode + msg = "Child exitcode {} != {}" + assert c_code == exitcode, msg.format(c_code, exitcode) + + +def try_lock(lock_file): + try: + my_lock = pl.InterProcessLock(lock_file) + my_lock.lockfile = open(lock_file, 'w') + my_lock.trylock() + my_lock.unlock() + os._exit(1) + except IOError: + os._exit(0) + + +def lock_files(lock_path, handles_dir, num_handles=50): + with pl.InterProcessLock(lock_path): + + # Open some files we can use for locking + handles = [] + for n in range(num_handles): + path = os.path.join(handles_dir, ('file-%s' % n)) + handles.append(open(path, 'w')) + + # Loop over all the handles and try locking the file + # without blocking, keep a count of how many files we + # were able to lock and then unlock. If the lock fails + # we get an IOError and bail out with bad exit code + count = 0 + for handle in handles: + try: + pl.InterProcessLock._trylock(handle) + count += 1 + pl.InterProcessLock._unlock(handle) + except IOError: + os._exit(2) + finally: + handle.close() + + # Check if we were able to open all files + if count != num_handles: + raise AssertionError("Unable to open all handles") + + +def inter_processlock_helper(lockname, lock_filename, pipe): + lock2 = pl.InterProcessLock(lockname) + lock2.lockfile = open(lock_filename, 'w') + have_lock = False + while not have_lock: + try: + lock2.trylock() + have_lock = True + except IOError: + pass + # Hold the lock and wait for the parent + pipe.send(None) + pipe.recv() + + class ProcessLockTest(test.TestCase): def setUp(self): super(ProcessLockTest, self).setUp() @@ -59,27 +142,13 @@ class ProcessLockTest(test.TestCase): lock_file = os.path.join(self.lock_dir, 'lock') lock = pl.InterProcessLock(lock_file) - def try_lock(): - try: - my_lock = pl.InterProcessLock(lock_file) - my_lock.lockfile = open(lock_file, 'w') - my_lock.trylock() - my_lock.unlock() - os._exit(1) - except IOError: - os._exit(0) - def attempt_acquire(count): - children = [] - for i in range(count): - child = multiprocessing.Process(target=try_lock) - child.start() - children.append(child) - exit_codes = [] - for child in children: - child.join() - exit_codes.append(child.exitcode) - return sum(exit_codes) + children = [ + multiprocessing.Process(target=try_lock, args=(lock_file,)) + for i in range(count)] + with scoped_child_processes(children, timeout=10, exitcode=None): + pass + return sum(c.exitcode for c in children) self.assertTrue(lock.acquire()) try: @@ -108,49 +177,17 @@ class ProcessLockTest(test.TestCase): def _do_test_lock_externally(self, lock_dir): lock_path = os.path.join(lock_dir, "lock") - def lock_files(handles_dir): - with pl.InterProcessLock(lock_path): - - # Open some files we can use for locking - handles = [] - for n in range(50): - path = os.path.join(handles_dir, ('file-%s' % n)) - handles.append(open(path, 'w')) - - # Loop over all the handles and try locking the file - # without blocking, keep a count of how many files we - # were able to lock and then unlock. If the lock fails - # we get an IOError and bail out with bad exit code - count = 0 - for handle in handles: - try: - fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) - count += 1 - fcntl.flock(handle, fcntl.LOCK_UN) - except IOError: - os._exit(2) - finally: - handle.close() - - # Check if we were able to open all files - self.assertEqual(50, count) - handles_dir = tempfile.mkdtemp() self.tmp_dirs.append(handles_dir) - children = [] - for n in range(50): - pid = os.fork() - if pid: - children.append(pid) - else: - try: - lock_files(handles_dir) - finally: - os._exit(0) - for child in children: - (pid, status) = os.waitpid(child, 0) - if pid: - self.assertEqual(0, status) + + num_handles = 50 + num_processes = 50 + args = [lock_path, handles_dir, num_handles] + children = [multiprocessing.Process(target=lock_files, args=args) + for _ in range(num_processes)] + + with scoped_child_processes(children, timeout=30, exitcode=0): + pass def test_lock_externally(self): self._do_test_lock_externally(self.lock_dir) @@ -180,16 +217,20 @@ class ProcessLockTest(test.TestCase): def test_interprocess_lock(self): lock_file = os.path.join(self.lock_dir, 'lock') + lock_name = 'foo' + + child_pipe, them = multiprocessing.Pipe() + child = multiprocessing.Process( + target=inter_processlock_helper, args=(lock_name, lock_file, them)) + + with scoped_child_processes((child,)): - pid = os.fork() - if pid: # Make sure the child grabs the lock first + if not child_pipe.poll(5): + self.fail('Timed out waiting for child to grab lock') + start = time.time() - while not os.path.exists(lock_file): - if time.time() - start > 5: - self.fail('Timed out waiting for child to grab lock') - time.sleep(0) - lock1 = pl.InterProcessLock('foo') + lock1 = pl.InterProcessLock(lock_name) lock1.lockfile = open(lock_file, 'w') # NOTE(bnemec): There is a brief window between when the lock file # is created and when it actually becomes locked. If we happen to @@ -206,26 +247,10 @@ class ProcessLockTest(test.TestCase): break else: self.fail('Never caught expected lock exception') - # We don't need to wait for the full sleep in the child here - os.kill(pid, signal.SIGKILL) - else: - try: - lock2 = pl.InterProcessLock('foo') - lock2.lockfile = open(lock_file, 'w') - have_lock = False - while not have_lock: - try: - lock2.trylock() - have_lock = True - except IOError: - pass - finally: - # NOTE(bnemec): This is racy, but I don't want to add any - # synchronization primitives that might mask a problem - # with the one we're trying to test here. - time.sleep(.5) - os._exit(0) + child_pipe.send(None) + + @test.testtools.skipIf(WIN32, "Windows cannot open file handles twice") def test_non_destructive(self): lock_file = os.path.join(self.lock_dir, 'not-destroyed') with open(lock_file, 'w') as f:
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
0.14
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "testtools", "pytest" ], "pre_install": null, "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 -e git+https://github.com/harlowja/fasteners.git@8b63aafd5a9cde3e506810b5df52174d016edd2d#egg=fasteners fixtures==4.0.1 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work monotonic==1.6 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work nose==1.3.7 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pbr==6.1.1 pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 six==1.17.0 testtools==2.6.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: fasteners channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - fixtures==4.0.1 - monotonic==1.6 - nose==1.3.7 - pbr==6.1.1 - six==1.17.0 - testtools==2.6.0 prefix: /opt/conda/envs/fasteners
[ "fasteners/tests/test_process_lock.py::ProcessLockTest::test_lock_externally", "fasteners/tests/test_process_lock.py::ProcessLockTest::test_lock_externally_lock_dir_not_exist" ]
[]
[ "fasteners/tests/test_process_lock.py::ProcessLockTest::test_bad_acquire", "fasteners/tests/test_process_lock.py::ProcessLockTest::test_bad_release", "fasteners/tests/test_process_lock.py::ProcessLockTest::test_interprocess_lock", "fasteners/tests/test_process_lock.py::ProcessLockTest::test_lock_acquire_release_file_lock", "fasteners/tests/test_process_lock.py::ProcessLockTest::test_lock_file_exists", "fasteners/tests/test_process_lock.py::ProcessLockTest::test_nested_synchronized_external_works", "fasteners/tests/test_process_lock.py::ProcessLockTest::test_non_destructive" ]
[]
Apache License 2.0
434
483
[ "fasteners/process_lock.py" ]
nose-devs__nose2-268
bbf5897eb1aa224100e86ba594042e4399fd2f5f
2016-02-16 09:53:50
bbf5897eb1aa224100e86ba594042e4399fd2f5f
little-dude: It's still failing when using the `uses` decorator. Added a test for this.
diff --git a/nose2/suite.py b/nose2/suite.py index b52e0cb..f107489 100644 --- a/nose2/suite.py +++ b/nose2/suite.py @@ -22,6 +22,7 @@ class LayerSuite(unittest.BaseTestSuite): self.wasSetup = False def run(self, result): + self.handle_previous_test_teardown(result) if not self._safeMethodCall(self.setUp, result): return try: @@ -37,6 +38,21 @@ class LayerSuite(unittest.BaseTestSuite): if self.wasSetup: self._safeMethodCall(self.tearDown, result) + def handle_previous_test_teardown(self, result): + try: + prev = result._previousTestClass + except AttributeError: + return + layer_attr = getattr(prev, 'layer', None) + if isinstance(layer_attr, LayerSuite): + return + try: + suite_obj = unittest.suite.TestSuite() + suite_obj._tearDownPreviousClass(None, result) + suite_obj._handleModuleTearDown(result) + finally: + delattr(result, '_previousTestClass') + def setUp(self): if self.layer is None: return
such and normal test cases: mixed up call order of it.has_setup and setUpClass As it is a little bit complicated to explain, I have created a working example as a gist: https://gist.github.com/jrast/109f70f9b4c52bab4252 I have several "normal" UnitTestCases and a few such tests. The problem is that the setUpClass calls are mixed up with the setup calls in such tests, as can be seen in the log file. The documentation states that I can not use Layer and setUpClass functions in the same TestCase, but it does not state that I cant use them side by side wich is the case in my example. So the question is: is this a bug or is there a missing hint in the documentation. Either way I think this is a dangerous behaviour because test fixtures made in a setup call can be modified from outside of the current test case wich can lead to very unpredictable behaviour and wrong test results. One example of wrong behaviour is shown with the UniqueResource class wich is locked in the setup functions and unlocked in the teardown functions. As soon as the calls get mixed up a exception is thrown because the resource is already locked. I realy hope this is not just a missing hint/warning in the docs, otherwise I have to rethink about how to structure my tests...
nose-devs/nose2
diff --git a/nose2/tests/functional/support/scenario/layers_and_non_layers/__init__.py b/nose2/tests/functional/support/scenario/layers_and_non_layers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nose2/tests/functional/support/scenario/layers_and_non_layers/common.py b/nose2/tests/functional/support/scenario/layers_and_non_layers/common.py new file mode 100644 index 0000000..ae24633 --- /dev/null +++ b/nose2/tests/functional/support/scenario/layers_and_non_layers/common.py @@ -0,0 +1,60 @@ +import unittest +import logging +log = logging.getLogger(__name__) + + +class UniqueResource(object): + _instance = None + used = False + + def __new__(cls, *args, **kwargs): + if not cls._instance: + cls._instance = super(UniqueResource, cls).__new__( + cls, *args, **kwargs) + return cls._instance + + def lock(self): + if not self.used: + self.used = True + else: + raise Exception("Resource allready used") + + def unlock(self): + if self.used: + self.used = False + else: + raise Exception("Resource already unlocked") + + +class NormalTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + log.info("Called setUpClass in NormalTest") + cls.unique_resource = UniqueResource() + cls.unique_resource.lock() + + @classmethod + def tearDownClass(cls): + log.info("Called tearDownClass in NormalTest") + cls.unique_resource.unlock() + + def test(self): + self.assertTrue(self.unique_resource.used) + + +class NormalTestTwo(unittest.TestCase): + + @classmethod + def setUpClass(cls): + log.info("Called setUpClass in NormalTestTwo") + cls.unique_resource = UniqueResource() + cls.unique_resource.lock() + + @classmethod + def tearDownClass(cls): + log.info("Called tearDownClass in NormalTestTwo") + cls.unique_resource.unlock() + + def test(self): + self.assertTrue(self.unique_resource.used) diff --git a/nose2/tests/functional/support/scenario/layers_and_non_layers/test_layers.py b/nose2/tests/functional/support/scenario/layers_and_non_layers/test_layers.py new file mode 100644 index 0000000..4fb9c8c --- /dev/null +++ b/nose2/tests/functional/support/scenario/layers_and_non_layers/test_layers.py @@ -0,0 +1,67 @@ +import unittest +import logging +from .common import UniqueResource, NormalTest, NormalTestTwo +log = logging.getLogger(__name__) + + +class Layer1(object): + + @classmethod + def setUp(cls): + log.info("Called setup in layer 1") + cls.unique_resource = UniqueResource() + cls.unique_resource.lock() + + @classmethod + def tearDown(cls): + log.info("Called teardown in layer 2") + cls.unique_resource.unlock() + + +class Layer2(object): + + @classmethod + def setUp(cls): + log.info("Called setup in layer 2") + cls.unique_resource = UniqueResource() + cls.unique_resource.lock() + + @classmethod + def tearDown(cls): + log.info("Called teardown in layer 2") + cls.unique_resource.unlock() + + +class Layer3(Layer2): + + @classmethod + def setUp(cls): + log.info("Called setup in layer 3") + + @classmethod + def tearDown(cls): + log.info("Called teardown in layer 3") + + +class LayerTest1(unittest.TestCase): + + layer = Layer1 + + def test(self): + self.assertTrue(self.layer.unique_resource.used) + + +class LayerTest2(unittest.TestCase): + + layer = Layer2 + + def test(self): + self.assertTrue(self.layer.unique_resource.used) + + +class LayerTest3(unittest.TestCase): + + layer = Layer2 + + def test(self): + self.assertTrue(self.layer.unique_resource.used) diff --git a/nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_has_setup.py b/nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_has_setup.py new file mode 100644 index 0000000..14268fe --- /dev/null +++ b/nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_has_setup.py @@ -0,0 +1,24 @@ +from nose2.tools import such +import logging +from .common import UniqueResource, NormalTest, NormalTestTwo +log = logging.getLogger(__name__) + + +with such.A('system with setup') as it: + + @it.has_setup + def setup(): + log.info("Called setup in such test") + it.unique_resource = UniqueResource() + it.unique_resource.lock() + + @it.has_teardown + def teardown(): + log.info("Called teardown in such test") + it.unique_resource.unlock() + + @it.should('do something') + def test(case): + it.assertTrue(it.unique_resource.used) + +it.createTests(globals()) diff --git a/nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_uses_decorator.py b/nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_uses_decorator.py new file mode 100644 index 0000000..ee15921 --- /dev/null +++ b/nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_uses_decorator.py @@ -0,0 +1,51 @@ +from nose2.tools import such +import logging +from .common import UniqueResource, NormalTest, NormalTestTwo +log = logging.getLogger(__name__) + + +class Layer1(object): + + description = 'Layer1' + + @classmethod + def setUp(cls): + log.info("Called setup in layer 1") + it.unique_resource = UniqueResource() + it.unique_resource.lock() + + @classmethod + def tearDown(cls): + log.info("Called teardown in layer 2") + it.unique_resource.unlock() + + +class Layer2(object): + + description = 'Layer2' + + @classmethod + def setUp(cls): + log.info("Called setup in layer 2") + + @classmethod + def tearDown(cls): + log.info("Called teardown in layer 2") + +with such.A('system with setup') as it: + + it.uses(Layer1) + + @it.should('do something') + def test(case): + it.assertTrue(it.unique_resource.used) + + with it.having('another setup'): + + it.uses(Layer2) + + @it.should('do something else') + def test(case): + it.assertTrue(it.unique_resource.used) + +it.createTests(globals()) diff --git a/nose2/tests/functional/test_layers_plugin.py b/nose2/tests/functional/test_layers_plugin.py index e072854..9666dba 100644 --- a/nose2/tests/functional/test_layers_plugin.py +++ b/nose2/tests/functional/test_layers_plugin.py @@ -120,3 +120,14 @@ Base self.assertTestRunOutputMatches(proc, stderr='ERROR: LayerSuite') self.assertTestRunOutputMatches(proc, stderr='FAIL') self.assertTestRunOutputMatches(proc, stderr='Bad Error in Layer setUp!') + + def test_layers_and_non_layers(self): + proc = self.runIn( + 'scenario/', + 'layers_and_non_layers', + '-v', + '--plugin=nose2.plugins.layers', + ) + self.assertTestRunOutputMatches(proc, stderr='Ran 12 tests in') + self.assertTestRunOutputMatches(proc, stderr='OK') + self.assertEqual(proc.poll(), 0)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose2", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cov-core==1.15.0 coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/nose-devs/nose2.git@bbf5897eb1aa224100e86ba594042e4399fd2f5f#egg=nose2 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 six==1.17.0 tomli==2.2.1
name: nose2 channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cov-core==1.15.0 - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - six==1.17.0 - tomli==2.2.1 prefix: /opt/conda/envs/nose2
[ "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layers_and_non_layers" ]
[ "nose2/tests/functional/support/scenario/layers_and_non_layers/test_layers.py::LayerTest1::test", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_layers.py::LayerTest2::test", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_layers.py::LayerTest3::test", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_has_setup.py::A", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_uses_decorator.py::Layer1", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_uses_decorator.py::A", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_uses_decorator.py::having" ]
[ "nose2/tests/functional/support/scenario/layers_and_non_layers/common.py::NormalTest::test", "nose2/tests/functional/support/scenario/layers_and_non_layers/common.py::NormalTestTwo::test", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_layers.py::NormalTest::test", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_layers.py::NormalTestTwo::test", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_has_setup.py::NormalTest::test", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_has_setup.py::NormalTestTwo::test", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_uses_decorator.py::NormalTest::test", "nose2/tests/functional/support/scenario/layers_and_non_layers/test_such_with_uses_decorator.py::NormalTestTwo::test", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layer_reporter_error_output", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layer_reporter_output", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_layers_and_attributes", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_methods_run_once_per_class", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_runs_layer_fixtures", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_scenario_fails_without_plugin", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_setup_fail", "nose2/tests/functional/test_layers_plugin.py::TestLayers::test_teardown_fail" ]
[]
BSD
435
294
[ "nose2/suite.py" ]
typesafehub__conductr-cli-111
76f795642d4d2220be0eddf75bcf8e933a7b6821
2016-02-23 01:04:09
76f795642d4d2220be0eddf75bcf8e933a7b6821
diff --git a/conductr_cli/resolvers/bintray_resolver.py b/conductr_cli/resolvers/bintray_resolver.py index 8f892b1..cfb0ce9 100644 --- a/conductr_cli/resolvers/bintray_resolver.py +++ b/conductr_cli/resolvers/bintray_resolver.py @@ -10,6 +10,7 @@ import requests BINTRAY_API_BASE_URL = 'https://api.bintray.com' BINTRAY_DOWNLOAD_BASE_URL = 'https://dl.bintray.com' +BINTRAY_DOWNLOAD_REALM = 'Bintray' BINTRAY_CREDENTIAL_FILE_PATH = '{}/.bintray/.credentials'.format(os.path.expanduser('~')) @@ -22,7 +23,8 @@ def resolve_bundle(cache_dir, uri): bundle_download_url = bintray_download_url(bintray_username, bintray_password, org, repo, package_name, compatibility_version, digest) if bundle_download_url: - return uri_resolver.resolve_bundle(cache_dir, bundle_download_url) + auth = (BINTRAY_DOWNLOAD_REALM, bintray_username, bintray_password) if bintray_username else None + return uri_resolver.resolve_bundle(cache_dir, bundle_download_url, auth) else: return False, None, None except MalformedBundleUriError: diff --git a/conductr_cli/resolvers/uri_resolver.py b/conductr_cli/resolvers/uri_resolver.py index 45a12df..8207d26 100644 --- a/conductr_cli/resolvers/uri_resolver.py +++ b/conductr_cli/resolvers/uri_resolver.py @@ -6,9 +6,10 @@ from conductr_cli import screen_utils import os import logging import shutil +import urllib -def resolve_bundle(cache_dir, uri): +def resolve_bundle(cache_dir, uri, auth=None): log = logging.getLogger(__name__) if not os.path.exists(cache_dir): @@ -23,7 +24,7 @@ def resolve_bundle(cache_dir, uri): if os.path.exists(tmp_download_path): os.remove(tmp_download_path) - download_bundle(log, bundle_url, tmp_download_path) + download_bundle(log, bundle_url, tmp_download_path, auth) shutil.move(tmp_download_path, cached_file) return True, bundle_name, cached_file @@ -62,12 +63,22 @@ def cache_path(cache_dir, uri): return '{}/{}'.format(cache_dir, basename) -def download_bundle(log, bundle_url, tmp_download_path): +def download_bundle(log, bundle_url, tmp_download_path, auth): log.info('Retrieving {}'.format(bundle_url)) parsed = urlparse(bundle_url, scheme='file') is_http_download = parsed.scheme == 'http' or parsed.scheme == 'https' + if is_http_download and auth: + realm, username, password = auth + authinfo = urllib.request.HTTPBasicAuthHandler() + authinfo.add_password(realm=realm, + uri=bundle_url, + user=username, + passwd=password) + opener = urllib.request.build_opener(authinfo) + urllib.request.install_opener(opener) + if log.is_progress_enabled() and is_http_download: urlretrieve(bundle_url, tmp_download_path, reporthook=show_progress(log)) else:
Unable to access non-default org and repo with bintray resolver Note how the URL duplicates the org and file name, even when you don't specify an org. `conduct load typesafe/internal-bundle/typesafe-website` ``` Retrieving https://dl.bintray.com/typesafe/internal-bundle/typesafe/typesafe-website/v1-075dbb07a7c6271164c2a429b06f5908bc3d416d18c5813d3d4d718aa6470f2e/typesafe-website-v1-075dbb07a7c6271164c2a429b06f5908bc3d416d18c5813d3d4d718aa6470f2e.zip Error: Bundle not found: Unable to resolve bundle using typesafe/internal-bundle/typesafe-website ``` ` conduct load internal-bundle/typesafe-website` ``` Resolving bundle typesafe/internal-bundle/typesafe-website Retrieving https://dl.bintray.com/typesafe/internal-bundle/typesafe/typesafe-website/v1-d31c136feef7a7c0a43a0bdf4a2179491e40161ee3a7a37335bcda1c13c5612f/typesafe-website-v1-d31c136feef7a7c0a43a0bdf4a2179491e40161ee3a7a37335bcda1c13c5612f.zip Error: Bundle not found: Unable to resolve bundle using internal-bundle/typesafe-website ```
typesafehub/conductr-cli
diff --git a/conductr_cli/resolvers/test/test_bintray_resolver.py b/conductr_cli/resolvers/test/test_bintray_resolver.py index cf68b72..2c8a77b 100644 --- a/conductr_cli/resolvers/test/test_bintray_resolver.py +++ b/conductr_cli/resolvers/test/test_bintray_resolver.py @@ -32,7 +32,8 @@ class TestResolveBundle(TestCase): parse_mock.assert_called_with('bundle-name:v1') bintray_download_url_mock.assert_called_with('username', 'password', 'typesafe', 'bundle', 'bundle-name', 'v1', 'digest') - resolve_bundle_mock.assert_called_with('/cache-dir', 'https://dl.bintray.com/download.zip') + resolve_bundle_mock.assert_called_with('/cache-dir', 'https://dl.bintray.com/download.zip', + ('Bintray', 'username', 'password')) def test_bintray_version_not_found(self): load_bintray_credentials_mock = MagicMock(return_value=('username', 'password'))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
0.24
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "pytest", "flake8" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
argcomplete==3.6.1 arrow==1.3.0 certifi==2025.1.31 charset-normalizer==3.4.1 -e git+https://github.com/typesafehub/conductr-cli.git@76f795642d4d2220be0eddf75bcf8e933a7b6821#egg=conductr_cli exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work flake8==7.2.0 idna==3.10 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mccabe==0.7.0 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pycodestyle==2.13.0 pyflakes==3.3.1 pyhocon==0.2.1 pyparsing==2.0.3 pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 requests==2.32.3 six==1.17.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work types-python-dateutil==2.9.0.20241206 urllib3==2.3.0
name: conductr-cli channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - argcomplete==3.6.1 - arrow==1.3.0 - certifi==2025.1.31 - charset-normalizer==3.4.1 - flake8==7.2.0 - idna==3.10 - mccabe==0.7.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pyhocon==0.2.1 - pyparsing==2.0.3 - python-dateutil==2.9.0.post0 - requests==2.32.3 - six==1.17.0 - types-python-dateutil==2.9.0.20241206 - urllib3==2.3.0 prefix: /opt/conda/envs/conductr-cli
[ "conductr_cli/resolvers/test/test_bintray_resolver.py::TestResolveBundle::test_bintray_version_found" ]
[]
[ "conductr_cli/resolvers/test/test_bintray_resolver.py::TestResolveBundle::test_bintray_version_not_found", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestResolveBundle::test_failure_http_error", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestResolveBundle::test_failure_malformed_bundle_uri", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestLoadFromCache::test_bintray_version_found", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestLoadFromCache::test_bintray_version_not_found", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestLoadFromCache::test_failure_http_error", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestLoadFromCache::test_failure_malformed_bundle_uri", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestBintrayDownloadUrl::test_failure_multiple_versions_found", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestBintrayDownloadUrl::test_failure_version_not_found", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestBintrayDownloadUrl::test_success", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestBintrayDownloadUrlLatest::test_failure_latest_version_malformed", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestBintrayDownloadUrlLatest::test_latest_version_from_attribute_names", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestBintrayDownloadUrlLatest::test_latest_version_from_attribute_names_not_found", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestBintrayDownloadUrlLatest::test_success", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestBintrayDownloadUrlLatestCompatibilityVersion::test_no_version", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestBintrayDownloadUrlLatestCompatibilityVersion::test_success", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestLoadBintrayCredentials::test_credential_file_not_having_username_password", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestLoadBintrayCredentials::test_missing_credential_file", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestLoadBintrayCredentials::test_success", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestGetJson::test_get_json", "conductr_cli/resolvers/test/test_bintray_resolver.py::TestGetJson::test_get_json_no_credentials" ]
[]
Apache License 2.0
448
753
[ "conductr_cli/resolvers/bintray_resolver.py", "conductr_cli/resolvers/uri_resolver.py" ]
scieloorg__xylose-96
df12890d7e4d8d986f33844513b9d4f68a148fda
2016-02-25 18:06:10
df12890d7e4d8d986f33844513b9d4f68a148fda
fabiobatalha: Puesdes escribir un testcase para eso. swarzesherz: Actualizado con testcase fabiobatalha: Desculpe não ter comentado antes. Acho que seria legal também incluir no retorno do Xylose a version ISO do país, quando existir e for válida. swarzesherz: Actualizado, agregue affdict['country_iso_3166'] = aff['p']
diff --git a/xylose/scielodocument.py b/xylose/scielodocument.py index 0b42e3e..c71e5b2 100644 --- a/xylose/scielodocument.py +++ b/xylose/scielodocument.py @@ -1309,6 +1309,7 @@ class Article(object): continue normalized[aff['index']]['normalized'] = True normalized[aff['index']]['country'] = aff.get('country', '') + normalized[aff['index']]['country_iso_3166'] = aff.get('country_iso_3166', '') normalized[aff['index']]['institution'] = aff.get('institution', '') normalized[aff['index']]['state'] = aff.get('state', '') @@ -1335,8 +1336,7 @@ class Article(object): if 'p' in aff and aff['p'] in choices.ISO_3166: affdict['country'] = choices.ISO_3166[aff['p']] - if aff['p'] in choices.ISO_3166: - affdict['country_iso_3166'] = aff['p'] + affdict['country_iso_3166'] = aff['p'] if 's' in aff: affdict['state'] = aff['s'] @@ -1369,6 +1369,9 @@ class Article(object): affdict['state'] = html_decode(aff['s']) if 'p' in aff: affdict['country'] = html_decode(aff['p']) + if 'p' in aff and 'q' in aff and aff['p'] in choices.ISO_3166: + affdict['country'] = choices.ISO_3166[aff['p']] + affdict['country_iso_3166'] = aff['p'] if 'e' in aff: affdict['email'] = html_decode(aff['e']) if 'd' in aff:
Asignación incorrecta de country en afiliaciones no normalizadas (v70) En versiones de PC-Programs anteriores a: https://github.com/scieloorg/PC-Programs/commit/5e494a031cabb9d718970a6201f3ee6c9847b942 se realizaba la asignación del campo ```p```de la siguiente forma: ``` a['p'] = item.country if item.i_country is None else item.i_country a['q'] = item.country if item.i_country is not None else None ``` Por lo que aunque el campo no este normalizado se asignaba el valor correspondiente al código ISO_3166, lo cual trae problemas en aplicaciones como articles_meta en donde encontramos combinados datos de códigos ISO_3166 con nombres del país: http://articlemeta.scielo.org/api/v1/article/?code=S1665-70632015000300102&format=xmlwos ![screen shot 2016-02-25 at 12 02 39](https://cloud.githubusercontent.com/assets/197827/13329058/906141b6-dbb7-11e5-8428-225d4bd89945.png)
scieloorg/xylose
diff --git a/tests/test_document.py b/tests/test_document.py index 758d7b8..6e6b1d6 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -1751,6 +1751,13 @@ class ArticleTests(unittest.TestCase): u"p": u"US", u"s": u"São Paulo", u"_": u"University of Florida Not Normalized" + }, + { + u"i": u"A04", + u"q": u"Mexico", + u"p": u"MX", + u"s": u"Yucatán", + u"_": u"Secretaría de Salud de Yucatán" } ] @@ -1758,13 +1765,15 @@ class ArticleTests(unittest.TestCase): result_index = u''.join([i['index'] for i in sorted(amc, key=lambda k: k['index'])]) result_country = u''.join([i['country'] for i in sorted(amc, key=lambda k: k['index'])]) + result_country_iso = u''.join([i['country_iso_3166'] for i in sorted(amc, key=lambda k: k['index']) if 'country_iso_3166' in i]) result_status = u''.join([str(i['normalized']) for i in sorted(amc, key=lambda k: k['index'])]) result_state = u''.join([i['state'] for i in sorted(amc, key=lambda k: k['index'])]) - self.assertEqual(result_index, u'A01A02A03') - self.assertEqual(result_country, u'BrazilBrazilUS') - self.assertEqual(result_status, u'TrueTrueFalse') - self.assertEqual(result_state, u'São PauloSão Paulo') + self.assertEqual(result_index, u'A01A02A03A04') + self.assertEqual(result_country, u'BrazilBrazilUSMexico') + self.assertEqual(result_country_iso, u'BRBRMX') + self.assertEqual(result_status, u'TrueTrueFalseFalse') + self.assertEqual(result_state, u'São PauloSão PauloYucatán') def test_without_normalized_affiliations(self): article = self.article @@ -1992,6 +2001,41 @@ class ArticleTests(unittest.TestCase): self.assertEqual(article.affiliations, expected) + def test_affiliation_with_country_iso_3166(self): + + article = self.article + + del(article.data['article']['v70']) + + article.data['article']['v70'] = [ + { + u"1": u"Escuela Nacional de Enfermería y Obstetricia", + u"2": u"División de Estudios de Posgrado e Investigación", + u"q": u"Mexico", + u"c": u"México", + u"i": u"A01", + u"l": u"a", + u"p": u"MX", + u"s": u"D.F.", + u"_": u"Universidad Nacional Autónoma de México" + } + ] + + expected = [ + { + 'index': u'A01', + 'city': u'México', + 'state': u'D.F.', + 'country': u'Mexico', + 'country_iso_3166': u'MX', + 'orgdiv1': u'Escuela Nacional de Enfermería y Obstetricia', + 'orgdiv2': u'División de Estudios de Posgrado e Investigación', + 'institution': u'Universidad Nacional Autónoma de México' + } + ] + + self.assertEqual(article.affiliations, expected) + def test_without_scielo_domain(self): article = self.article
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_media" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "coverage", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work nose==1.3.7 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work -e git+https://github.com/scieloorg/xylose.git@df12890d7e4d8d986f33844513b9d4f68a148fda#egg=xylose
name: xylose channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - nose==1.3.7 prefix: /opt/conda/envs/xylose
[ "tests/test_document.py::ArticleTests::test_affiliation_with_country_iso_3166", "tests/test_document.py::ArticleTests::test_mixed_affiliations_1" ]
[]
[ "tests/test_document.py::ToolsTests::test_get_date_wrong_day", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_month", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_month_not_int", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_not_int", "tests/test_document.py::ToolsTests::test_get_date_wrong_month_not_int", "tests/test_document.py::ToolsTests::test_get_date_year", "tests/test_document.py::ToolsTests::test_get_date_year_day", "tests/test_document.py::ToolsTests::test_get_date_year_month", "tests/test_document.py::ToolsTests::test_get_date_year_month_day", "tests/test_document.py::ToolsTests::test_get_date_year_month_day_31", "tests/test_document.py::ToolsTests::test_get_language_iso639_1_defined", "tests/test_document.py::ToolsTests::test_get_language_iso639_1_undefined", "tests/test_document.py::ToolsTests::test_get_language_iso639_2_defined", "tests/test_document.py::ToolsTests::test_get_language_iso639_2_undefined", "tests/test_document.py::ToolsTests::test_get_language_without_iso_format", "tests/test_document.py::IssueTests::test_collection_acronym", "tests/test_document.py::IssueTests::test_is_ahead", "tests/test_document.py::IssueTests::test_is_ahead_1", "tests/test_document.py::IssueTests::test_issue", "tests/test_document.py::IssueTests::test_issue_label_field_v4", "tests/test_document.py::IssueTests::test_issue_label_without_field_v4", "tests/test_document.py::IssueTests::test_issue_url", "tests/test_document.py::IssueTests::test_order", "tests/test_document.py::IssueTests::test_supplement_number", "tests/test_document.py::IssueTests::test_supplement_volume", "tests/test_document.py::IssueTests::test_volume", "tests/test_document.py::IssueTests::test_without_issue", "tests/test_document.py::IssueTests::test_without_suplement_number", "tests/test_document.py::IssueTests::test_without_supplement_volume", "tests/test_document.py::IssueTests::test_without_volume", "tests/test_document.py::JournalTests::test_any_issn_priority_electronic", "tests/test_document.py::JournalTests::test_any_issn_priority_electronic_without_electronic", "tests/test_document.py::JournalTests::test_any_issn_priority_print", "tests/test_document.py::JournalTests::test_any_issn_priority_print_without_print", "tests/test_document.py::JournalTests::test_collection_acronym", "tests/test_document.py::JournalTests::test_creation_date", "tests/test_document.py::JournalTests::test_current_status", "tests/test_document.py::JournalTests::test_current_status_lots_of_changes_study_case_1", "tests/test_document.py::JournalTests::test_current_status_some_changes", "tests/test_document.py::JournalTests::test_current_without_v51", "tests/test_document.py::JournalTests::test_journal", "tests/test_document.py::JournalTests::test_journal_abbreviated_title", "tests/test_document.py::JournalTests::test_journal_acronym", "tests/test_document.py::JournalTests::test_journal_fulltitle", "tests/test_document.py::JournalTests::test_journal_fulltitle_without_subtitle", "tests/test_document.py::JournalTests::test_journal_fulltitle_without_title", "tests/test_document.py::JournalTests::test_journal_subtitle", "tests/test_document.py::JournalTests::test_journal_title", "tests/test_document.py::JournalTests::test_journal_title_nlm", "tests/test_document.py::JournalTests::test_journal_url", "tests/test_document.py::JournalTests::test_journal_without_subtitle", "tests/test_document.py::JournalTests::test_languages", "tests/test_document.py::JournalTests::test_languages_without_v350", "tests/test_document.py::JournalTests::test_load_issn_with_v435", "tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_with_v935_without_v35", "tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_without_v935_without_v35", "tests/test_document.py::JournalTests::test_periodicity", "tests/test_document.py::JournalTests::test_periodicity_in_months", "tests/test_document.py::JournalTests::test_periodicity_in_months_out_of_choices", "tests/test_document.py::JournalTests::test_periodicity_out_of_choices", "tests/test_document.py::JournalTests::test_permission_id", "tests/test_document.py::JournalTests::test_permission_t0", "tests/test_document.py::JournalTests::test_permission_t1", "tests/test_document.py::JournalTests::test_permission_t2", "tests/test_document.py::JournalTests::test_permission_t3", "tests/test_document.py::JournalTests::test_permission_t4", "tests/test_document.py::JournalTests::test_permission_text", "tests/test_document.py::JournalTests::test_permission_url", "tests/test_document.py::JournalTests::test_permission_without_v540", "tests/test_document.py::JournalTests::test_permission_without_v540_t", "tests/test_document.py::JournalTests::test_publisher_loc", "tests/test_document.py::JournalTests::test_publisher_name", "tests/test_document.py::JournalTests::test_scielo_issn", "tests/test_document.py::JournalTests::test_status", "tests/test_document.py::JournalTests::test_status_lots_of_changes", "tests/test_document.py::JournalTests::test_status_lots_of_changes_study_case_1", "tests/test_document.py::JournalTests::test_status_lots_of_changes_with_reason", "tests/test_document.py::JournalTests::test_status_some_changes", "tests/test_document.py::JournalTests::test_status_without_v51", "tests/test_document.py::JournalTests::test_subject_areas", "tests/test_document.py::JournalTests::test_update_date", "tests/test_document.py::JournalTests::test_without_journal_abbreviated_title", "tests/test_document.py::JournalTests::test_without_journal_acronym", "tests/test_document.py::JournalTests::test_without_journal_title", "tests/test_document.py::JournalTests::test_without_journal_title_nlm", "tests/test_document.py::JournalTests::test_without_journal_url", "tests/test_document.py::JournalTests::test_without_periodicity", "tests/test_document.py::JournalTests::test_without_periodicity_in_months", "tests/test_document.py::JournalTests::test_without_publisher_loc", "tests/test_document.py::JournalTests::test_without_publisher_name", "tests/test_document.py::JournalTests::test_without_scielo_domain", "tests/test_document.py::JournalTests::test_without_scielo_domain_title_v690", "tests/test_document.py::JournalTests::test_without_subject_areas", "tests/test_document.py::JournalTests::test_without_wos_citation_indexes", "tests/test_document.py::JournalTests::test_without_wos_subject_areas", "tests/test_document.py::JournalTests::test_wos_citation_indexes", "tests/test_document.py::JournalTests::test_wos_subject_areas", "tests/test_document.py::ArticleTests::test_acceptance_date", "tests/test_document.py::ArticleTests::test_affiliation_just_with_affiliation_name", "tests/test_document.py::ArticleTests::test_affiliation_without_affiliation_name", "tests/test_document.py::ArticleTests::test_affiliations", "tests/test_document.py::ArticleTests::test_ahead_publication_date", "tests/test_document.py::ArticleTests::test_article", "tests/test_document.py::ArticleTests::test_author_with_two_affiliations", "tests/test_document.py::ArticleTests::test_author_with_two_role", "tests/test_document.py::ArticleTests::test_author_without_affiliations", "tests/test_document.py::ArticleTests::test_author_without_surname_and_given_names", "tests/test_document.py::ArticleTests::test_authors", "tests/test_document.py::ArticleTests::test_collection_acronym", "tests/test_document.py::ArticleTests::test_collection_acronym_priorizing_collection", "tests/test_document.py::ArticleTests::test_collection_acronym_retrieving_v992", "tests/test_document.py::ArticleTests::test_collection_name_brazil", "tests/test_document.py::ArticleTests::test_collection_name_undefined", "tests/test_document.py::ArticleTests::test_corporative_authors", "tests/test_document.py::ArticleTests::test_creation_date", "tests/test_document.py::ArticleTests::test_creation_date_1", "tests/test_document.py::ArticleTests::test_creation_date_2", "tests/test_document.py::ArticleTests::test_data_model_version_html", "tests/test_document.py::ArticleTests::test_data_model_version_html_1", "tests/test_document.py::ArticleTests::test_data_model_version_xml", "tests/test_document.py::ArticleTests::test_document_type", "tests/test_document.py::ArticleTests::test_doi", "tests/test_document.py::ArticleTests::test_doi_clean_1", "tests/test_document.py::ArticleTests::test_doi_clean_2", "tests/test_document.py::ArticleTests::test_doi_v237", "tests/test_document.py::ArticleTests::test_e_location", "tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_1", "tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_2", "tests/test_document.py::ArticleTests::test_end_page_loaded_through_xml", "tests/test_document.py::ArticleTests::test_file_code", "tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_1", "tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_2", "tests/test_document.py::ArticleTests::test_first_author", "tests/test_document.py::ArticleTests::test_first_author_without_author", "tests/test_document.py::ArticleTests::test_fulltexts_field_fulltexts", "tests/test_document.py::ArticleTests::test_fulltexts_without_field_fulltexts", "tests/test_document.py::ArticleTests::test_html_url", "tests/test_document.py::ArticleTests::test_invalid_document_type", "tests/test_document.py::ArticleTests::test_issue_url", "tests/test_document.py::ArticleTests::test_journal_abbreviated_title", "tests/test_document.py::ArticleTests::test_journal_acronym", "tests/test_document.py::ArticleTests::test_journal_title", "tests/test_document.py::ArticleTests::test_keywords", "tests/test_document.py::ArticleTests::test_keywords_iso639_2", "tests/test_document.py::ArticleTests::test_keywords_with_undefined_language", "tests/test_document.py::ArticleTests::test_keywords_without_subfield_k", "tests/test_document.py::ArticleTests::test_keywords_without_subfield_l", "tests/test_document.py::ArticleTests::test_languages_field_fulltexts", "tests/test_document.py::ArticleTests::test_languages_field_v40", "tests/test_document.py::ArticleTests::test_last_page", "tests/test_document.py::ArticleTests::test_normalized_affiliations", "tests/test_document.py::ArticleTests::test_normalized_affiliations_undefined_ISO_3166_CODE", "tests/test_document.py::ArticleTests::test_normalized_affiliations_without_p", "tests/test_document.py::ArticleTests::test_order", "tests/test_document.py::ArticleTests::test_original_abstract_with_just_one_language_defined", "tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined", "tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined_but_different_of_the_article_original_language", "tests/test_document.py::ArticleTests::test_original_abstract_without_language_defined", "tests/test_document.py::ArticleTests::test_original_html_field_body", "tests/test_document.py::ArticleTests::test_original_language_invalid_iso639_2", "tests/test_document.py::ArticleTests::test_original_language_iso639_2", "tests/test_document.py::ArticleTests::test_original_language_original", "tests/test_document.py::ArticleTests::test_original_section_field_v49", "tests/test_document.py::ArticleTests::test_original_title_subfield_t", "tests/test_document.py::ArticleTests::test_original_title_with_just_one_language_defined", "tests/test_document.py::ArticleTests::test_original_title_with_language_defined", "tests/test_document.py::ArticleTests::test_original_title_with_language_defined_but_different_of_the_article_original_language", "tests/test_document.py::ArticleTests::test_original_title_without_language_defined", "tests/test_document.py::ArticleTests::test_pdf_url", "tests/test_document.py::ArticleTests::test_processing_date", "tests/test_document.py::ArticleTests::test_processing_date_1", "tests/test_document.py::ArticleTests::test_project_name", "tests/test_document.py::ArticleTests::test_project_sponsors", "tests/test_document.py::ArticleTests::test_publication_contract", "tests/test_document.py::ArticleTests::test_publication_date", "tests/test_document.py::ArticleTests::test_publisher_id", "tests/test_document.py::ArticleTests::test_publisher_loc", "tests/test_document.py::ArticleTests::test_publisher_name", "tests/test_document.py::ArticleTests::test_receive_date", "tests/test_document.py::ArticleTests::test_review_date", "tests/test_document.py::ArticleTests::test_secion_code_field_v49", "tests/test_document.py::ArticleTests::test_section_code_nd_field_v49", "tests/test_document.py::ArticleTests::test_section_code_without_field_v49", "tests/test_document.py::ArticleTests::test_section_field_v49", "tests/test_document.py::ArticleTests::test_section_nd_field_v49", "tests/test_document.py::ArticleTests::test_section_without_field_v49", "tests/test_document.py::ArticleTests::test_start_page", "tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_1", "tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_2", "tests/test_document.py::ArticleTests::test_start_page_loaded_through_xml", "tests/test_document.py::ArticleTests::test_subject_areas", "tests/test_document.py::ArticleTests::test_thesis_degree", "tests/test_document.py::ArticleTests::test_thesis_organization", "tests/test_document.py::ArticleTests::test_thesis_organization_and_division", "tests/test_document.py::ArticleTests::test_thesis_organization_without_name", "tests/test_document.py::ArticleTests::test_translated_abstracts", "tests/test_document.py::ArticleTests::test_translated_abstracts_without_v83", "tests/test_document.py::ArticleTests::test_translated_abtracts_iso639_2", "tests/test_document.py::ArticleTests::test_translated_htmls_field_body", "tests/test_document.py::ArticleTests::test_translated_section_field_v49", "tests/test_document.py::ArticleTests::test_translated_titles", "tests/test_document.py::ArticleTests::test_translated_titles_iso639_2", "tests/test_document.py::ArticleTests::test_translated_titles_without_v12", "tests/test_document.py::ArticleTests::test_update_date", "tests/test_document.py::ArticleTests::test_update_date_1", "tests/test_document.py::ArticleTests::test_update_date_2", "tests/test_document.py::ArticleTests::test_update_date_3", "tests/test_document.py::ArticleTests::test_whitwout_acceptance_date", "tests/test_document.py::ArticleTests::test_whitwout_ahead_publication_date", "tests/test_document.py::ArticleTests::test_whitwout_receive_date", "tests/test_document.py::ArticleTests::test_whitwout_review_date", "tests/test_document.py::ArticleTests::test_without_affiliations", "tests/test_document.py::ArticleTests::test_without_authors", "tests/test_document.py::ArticleTests::test_without_citations", "tests/test_document.py::ArticleTests::test_without_collection_acronym", "tests/test_document.py::ArticleTests::test_without_corporative_authors", "tests/test_document.py::ArticleTests::test_without_document_type", "tests/test_document.py::ArticleTests::test_without_doi", "tests/test_document.py::ArticleTests::test_without_e_location", "tests/test_document.py::ArticleTests::test_without_html_url", "tests/test_document.py::ArticleTests::test_without_issue_url", "tests/test_document.py::ArticleTests::test_without_journal_abbreviated_title", "tests/test_document.py::ArticleTests::test_without_journal_acronym", "tests/test_document.py::ArticleTests::test_without_journal_title", "tests/test_document.py::ArticleTests::test_without_keywords", "tests/test_document.py::ArticleTests::test_without_last_page", "tests/test_document.py::ArticleTests::test_without_normalized_affiliations", "tests/test_document.py::ArticleTests::test_without_order", "tests/test_document.py::ArticleTests::test_without_original_abstract", "tests/test_document.py::ArticleTests::test_without_original_title", "tests/test_document.py::ArticleTests::test_without_pages", "tests/test_document.py::ArticleTests::test_without_pdf_url", "tests/test_document.py::ArticleTests::test_without_processing_date", "tests/test_document.py::ArticleTests::test_without_project_name", "tests/test_document.py::ArticleTests::test_without_project_sponsor", "tests/test_document.py::ArticleTests::test_without_publication_contract", "tests/test_document.py::ArticleTests::test_without_publication_date", "tests/test_document.py::ArticleTests::test_without_publisher_id", "tests/test_document.py::ArticleTests::test_without_publisher_loc", "tests/test_document.py::ArticleTests::test_without_publisher_name", "tests/test_document.py::ArticleTests::test_without_scielo_domain", "tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69", "tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69_and_with_title_v690", "tests/test_document.py::ArticleTests::test_without_scielo_domain_title_v690", "tests/test_document.py::ArticleTests::test_without_start_page", "tests/test_document.py::ArticleTests::test_without_subject_areas", "tests/test_document.py::ArticleTests::test_without_thesis_degree", "tests/test_document.py::ArticleTests::test_without_thesis_organization", "tests/test_document.py::ArticleTests::test_without_wos_citation_indexes", "tests/test_document.py::ArticleTests::test_without_wos_subject_areas", "tests/test_document.py::ArticleTests::test_wos_citation_indexes", "tests/test_document.py::ArticleTests::test_wos_subject_areas", "tests/test_document.py::CitationTest::test_a_link_access_date", "tests/test_document.py::CitationTest::test_analytic_institution_for_a_article_citation", "tests/test_document.py::CitationTest::test_analytic_institution_for_a_book_citation", "tests/test_document.py::CitationTest::test_article_title", "tests/test_document.py::CitationTest::test_article_without_title", "tests/test_document.py::CitationTest::test_authors_article", "tests/test_document.py::CitationTest::test_authors_book", "tests/test_document.py::CitationTest::test_authors_link", "tests/test_document.py::CitationTest::test_authors_thesis", "tests/test_document.py::CitationTest::test_book_chapter_title", "tests/test_document.py::CitationTest::test_book_edition", "tests/test_document.py::CitationTest::test_book_volume", "tests/test_document.py::CitationTest::test_book_without_chapter_title", "tests/test_document.py::CitationTest::test_citation_sample_congress", "tests/test_document.py::CitationTest::test_citation_sample_link", "tests/test_document.py::CitationTest::test_citation_sample_link_without_comment", "tests/test_document.py::CitationTest::test_conference_edition", "tests/test_document.py::CitationTest::test_conference_name", "tests/test_document.py::CitationTest::test_conference_sponsor", "tests/test_document.py::CitationTest::test_conference_without_name", "tests/test_document.py::CitationTest::test_conference_without_sponsor", "tests/test_document.py::CitationTest::test_date", "tests/test_document.py::CitationTest::test_doi", "tests/test_document.py::CitationTest::test_editor", "tests/test_document.py::CitationTest::test_elocation_14", "tests/test_document.py::CitationTest::test_elocation_514", "tests/test_document.py::CitationTest::test_end_page_14", "tests/test_document.py::CitationTest::test_end_page_514", "tests/test_document.py::CitationTest::test_end_page_withdout_data", "tests/test_document.py::CitationTest::test_first_author_article", "tests/test_document.py::CitationTest::test_first_author_book", "tests/test_document.py::CitationTest::test_first_author_link", "tests/test_document.py::CitationTest::test_first_author_thesis", "tests/test_document.py::CitationTest::test_first_author_without_monographic_authors", "tests/test_document.py::CitationTest::test_first_author_without_monographic_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_index_number", "tests/test_document.py::CitationTest::test_institutions_all_fields", "tests/test_document.py::CitationTest::test_institutions_v11", "tests/test_document.py::CitationTest::test_institutions_v17", "tests/test_document.py::CitationTest::test_institutions_v29", "tests/test_document.py::CitationTest::test_institutions_v50", "tests/test_document.py::CitationTest::test_institutions_v58", "tests/test_document.py::CitationTest::test_invalid_edition", "tests/test_document.py::CitationTest::test_isbn", "tests/test_document.py::CitationTest::test_isbn_but_not_a_book", "tests/test_document.py::CitationTest::test_issn", "tests/test_document.py::CitationTest::test_issn_but_not_an_article", "tests/test_document.py::CitationTest::test_issue_part", "tests/test_document.py::CitationTest::test_issue_title", "tests/test_document.py::CitationTest::test_journal_issue", "tests/test_document.py::CitationTest::test_journal_volume", "tests/test_document.py::CitationTest::test_link", "tests/test_document.py::CitationTest::test_link_title", "tests/test_document.py::CitationTest::test_link_without_title", "tests/test_document.py::CitationTest::test_monographic_authors", "tests/test_document.py::CitationTest::test_monographic_first_author", "tests/test_document.py::CitationTest::test_pages_14", "tests/test_document.py::CitationTest::test_pages_514", "tests/test_document.py::CitationTest::test_pages_withdout_data", "tests/test_document.py::CitationTest::test_publication_type_article", "tests/test_document.py::CitationTest::test_publication_type_book", "tests/test_document.py::CitationTest::test_publication_type_conference", "tests/test_document.py::CitationTest::test_publication_type_link", "tests/test_document.py::CitationTest::test_publication_type_thesis", "tests/test_document.py::CitationTest::test_publication_type_undefined", "tests/test_document.py::CitationTest::test_publisher", "tests/test_document.py::CitationTest::test_publisher_address", "tests/test_document.py::CitationTest::test_publisher_address_without_e", "tests/test_document.py::CitationTest::test_series_book", "tests/test_document.py::CitationTest::test_series_but_neither_journal_book_or_conference_citation", "tests/test_document.py::CitationTest::test_series_conference", "tests/test_document.py::CitationTest::test_series_journal", "tests/test_document.py::CitationTest::test_source_book_title", "tests/test_document.py::CitationTest::test_source_journal", "tests/test_document.py::CitationTest::test_source_journal_without_journal_title", "tests/test_document.py::CitationTest::test_sponsor", "tests/test_document.py::CitationTest::test_start_page_14", "tests/test_document.py::CitationTest::test_start_page_514", "tests/test_document.py::CitationTest::test_start_page_withdout_data", "tests/test_document.py::CitationTest::test_thesis_institution", "tests/test_document.py::CitationTest::test_thesis_title", "tests/test_document.py::CitationTest::test_thesis_without_title", "tests/test_document.py::CitationTest::test_title_when_article_citation", "tests/test_document.py::CitationTest::test_title_when_conference_citation", "tests/test_document.py::CitationTest::test_title_when_link_citation", "tests/test_document.py::CitationTest::test_title_when_thesis_citation", "tests/test_document.py::CitationTest::test_with_volume_but_not_a_journal_article_neither_a_book", "tests/test_document.py::CitationTest::test_without_analytic_institution", "tests/test_document.py::CitationTest::test_without_authors", "tests/test_document.py::CitationTest::test_without_date", "tests/test_document.py::CitationTest::test_without_doi", "tests/test_document.py::CitationTest::test_without_edition", "tests/test_document.py::CitationTest::test_without_editor", "tests/test_document.py::CitationTest::test_without_first_author", "tests/test_document.py::CitationTest::test_without_index_number", "tests/test_document.py::CitationTest::test_without_institutions", "tests/test_document.py::CitationTest::test_without_issue", "tests/test_document.py::CitationTest::test_without_issue_part", "tests/test_document.py::CitationTest::test_without_issue_title", "tests/test_document.py::CitationTest::test_without_link", "tests/test_document.py::CitationTest::test_without_monographic_authors", "tests/test_document.py::CitationTest::test_without_monographic_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_without_publisher", "tests/test_document.py::CitationTest::test_without_publisher_address", "tests/test_document.py::CitationTest::test_without_series", "tests/test_document.py::CitationTest::test_without_sponsor", "tests/test_document.py::CitationTest::test_without_thesis_institution", "tests/test_document.py::CitationTest::test_without_volume" ]
[]
BSD 2-Clause "Simplified" License
452
472
[ "xylose/scielodocument.py" ]
scieloorg__xylose-108
9d72bccf95503133b6fe7ef55ec88f9cf9b50a71
2016-02-29 21:07:48
743d8ca8a32b6e6e82b1ed0fc97f7d240c85cba5
diff --git a/xylose/scielodocument.py b/xylose/scielodocument.py index 8f9703d..8676c4a 100644 --- a/xylose/scielodocument.py +++ b/xylose/scielodocument.py @@ -866,6 +866,24 @@ class Journal(object): return missions + @property + def publisher_country(self): + """ + This method retrieves the publisher country of journal. + This method return a tuple: ('US', u'United States'), otherwise + return None. + """ + if 'v310' not in self.data: + return None + + country_code = self.data.get('v310', [{'_': None}])[0]['_'] + country_name = choices.ISO_3166.get(country_code, None) + + if not country_code or not country_name: + return None + + return (country_code, country_name) + @property def copyright(self): """
Adicionar o campo ``publisher_country`` a classe Journal Para que possamos cadastrar o publisher_country no processamento inicial do Site, precisamos que esse atributo esteja no Xylose.
scieloorg/xylose
diff --git a/tests/test_document.py b/tests/test_document.py index 282c34f..30996d5 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -1085,6 +1085,26 @@ class JournalTests(unittest.TestCase): self.assertIsNone(journal.mission) + def test_journal_publisher_country(self): + journal = self.journal + + expected = ('BR', 'Brazil') + + self.assertEqual(journal.publisher_country, expected) + + def test_journal_publisher_country_without_country(self): + journal = self.journal + + del(journal.data['v310']) + + self.assertIsNone(journal.publisher_country) + + def test_journal_publisher_country_not_findable_code(self): + self.fulldoc['title']['v310'] = [{"_": "BRX"}] + journal = Journal(self.fulldoc['title']) + + self.assertIsNone(journal.publisher_country) + def test_journal_copyright(self): journal = self.journal
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements-test.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 mocker==1.1.1 nose==1.0.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-cov==6.0.0 pytest-mock==3.14.0 tomli==2.2.1 -e git+https://github.com/scieloorg/xylose.git@9d72bccf95503133b6fe7ef55ec88f9cf9b50a71#egg=xylose
name: xylose channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - mocker==1.1.1 - nose==1.0.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-mock==3.14.0 - tomli==2.2.1 prefix: /opt/conda/envs/xylose
[ "tests/test_document.py::JournalTests::test_journal_publisher_country", "tests/test_document.py::JournalTests::test_journal_publisher_country_not_findable_code", "tests/test_document.py::JournalTests::test_journal_publisher_country_without_country" ]
[]
[ "tests/test_document.py::ToolsTests::test_get_date_wrong_day", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_month", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_month_not_int", "tests/test_document.py::ToolsTests::test_get_date_wrong_day_not_int", "tests/test_document.py::ToolsTests::test_get_date_wrong_month_not_int", "tests/test_document.py::ToolsTests::test_get_date_year", "tests/test_document.py::ToolsTests::test_get_date_year_day", "tests/test_document.py::ToolsTests::test_get_date_year_month", "tests/test_document.py::ToolsTests::test_get_date_year_month_day", "tests/test_document.py::ToolsTests::test_get_date_year_month_day_31", "tests/test_document.py::ToolsTests::test_get_language_iso639_1_defined", "tests/test_document.py::ToolsTests::test_get_language_iso639_1_undefined", "tests/test_document.py::ToolsTests::test_get_language_iso639_2_defined", "tests/test_document.py::ToolsTests::test_get_language_iso639_2_undefined", "tests/test_document.py::ToolsTests::test_get_language_without_iso_format", "tests/test_document.py::IssueTests::test_collection_acronym", "tests/test_document.py::IssueTests::test_is_ahead", "tests/test_document.py::IssueTests::test_is_ahead_1", "tests/test_document.py::IssueTests::test_issue", "tests/test_document.py::IssueTests::test_issue_label", "tests/test_document.py::IssueTests::test_issue_url", "tests/test_document.py::IssueTests::test_order", "tests/test_document.py::IssueTests::test_processing_date", "tests/test_document.py::IssueTests::test_processing_date_1", "tests/test_document.py::IssueTests::test_publication_date", "tests/test_document.py::IssueTests::test_supplement_number", "tests/test_document.py::IssueTests::test_supplement_volume", "tests/test_document.py::IssueTests::test_type_regular", "tests/test_document.py::IssueTests::test_type_supplement_1", "tests/test_document.py::IssueTests::test_type_supplement_2", "tests/test_document.py::IssueTests::test_volume", "tests/test_document.py::IssueTests::test_without_issue", "tests/test_document.py::IssueTests::test_without_processing_date", "tests/test_document.py::IssueTests::test_without_publication_date", "tests/test_document.py::IssueTests::test_without_suplement_number", "tests/test_document.py::IssueTests::test_without_supplement_volume", "tests/test_document.py::IssueTests::test_without_volume", "tests/test_document.py::JournalTests::test_any_issn_priority_electronic", "tests/test_document.py::JournalTests::test_any_issn_priority_electronic_without_electronic", "tests/test_document.py::JournalTests::test_any_issn_priority_print", "tests/test_document.py::JournalTests::test_any_issn_priority_print_without_print", "tests/test_document.py::JournalTests::test_cnn_code", "tests/test_document.py::JournalTests::test_collection_acronym", "tests/test_document.py::JournalTests::test_creation_date", "tests/test_document.py::JournalTests::test_ctrl_vocabulary", "tests/test_document.py::JournalTests::test_ctrl_vocabulary_out_of_choices", "tests/test_document.py::JournalTests::test_current_status", "tests/test_document.py::JournalTests::test_current_status_lots_of_changes_study_case_1", "tests/test_document.py::JournalTests::test_current_status_some_changes", "tests/test_document.py::JournalTests::test_current_without_v51", "tests/test_document.py::JournalTests::test_first_number", "tests/test_document.py::JournalTests::test_first_number_1", "tests/test_document.py::JournalTests::test_first_volume", "tests/test_document.py::JournalTests::test_first_volume_1", "tests/test_document.py::JournalTests::test_first_year", "tests/test_document.py::JournalTests::test_first_year_1", "tests/test_document.py::JournalTests::test_journal", "tests/test_document.py::JournalTests::test_journal_abbreviated_title", "tests/test_document.py::JournalTests::test_journal_acronym", "tests/test_document.py::JournalTests::test_journal_copyright", "tests/test_document.py::JournalTests::test_journal_copyright_without_copyright", "tests/test_document.py::JournalTests::test_journal_fulltitle", "tests/test_document.py::JournalTests::test_journal_fulltitle_without_subtitle", "tests/test_document.py::JournalTests::test_journal_fulltitle_without_title", "tests/test_document.py::JournalTests::test_journal_mission", "tests/test_document.py::JournalTests::test_journal_mission_without_language_key", "tests/test_document.py::JournalTests::test_journal_mission_without_mission", "tests/test_document.py::JournalTests::test_journal_mission_without_mission_text", "tests/test_document.py::JournalTests::test_journal_mission_without_mission_text_and_language", "tests/test_document.py::JournalTests::test_journal_subtitle", "tests/test_document.py::JournalTests::test_journal_title", "tests/test_document.py::JournalTests::test_journal_title_nlm", "tests/test_document.py::JournalTests::test_journal_url", "tests/test_document.py::JournalTests::test_journal_without_subtitle", "tests/test_document.py::JournalTests::test_languages", "tests/test_document.py::JournalTests::test_languages_without_v350", "tests/test_document.py::JournalTests::test_last_cnn_code_1", "tests/test_document.py::JournalTests::test_last_number", "tests/test_document.py::JournalTests::test_last_number_1", "tests/test_document.py::JournalTests::test_last_volume", "tests/test_document.py::JournalTests::test_last_volume_1", "tests/test_document.py::JournalTests::test_last_year", "tests/test_document.py::JournalTests::test_last_year_1", "tests/test_document.py::JournalTests::test_load_issn_with_v435", "tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_with_v935_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_with_v935_equal_v400_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_with_v935_without_v35", "tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_ONLINE", "tests/test_document.py::JournalTests::test_load_issn_without_v935_and_v35_PRINT", "tests/test_document.py::JournalTests::test_load_issn_without_v935_without_v35", "tests/test_document.py::JournalTests::test_periodicity", "tests/test_document.py::JournalTests::test_periodicity_in_months", "tests/test_document.py::JournalTests::test_periodicity_in_months_out_of_choices", "tests/test_document.py::JournalTests::test_periodicity_out_of_choices", "tests/test_document.py::JournalTests::test_permission_id", "tests/test_document.py::JournalTests::test_permission_t0", "tests/test_document.py::JournalTests::test_permission_t1", "tests/test_document.py::JournalTests::test_permission_t2", "tests/test_document.py::JournalTests::test_permission_t3", "tests/test_document.py::JournalTests::test_permission_t4", "tests/test_document.py::JournalTests::test_permission_text", "tests/test_document.py::JournalTests::test_permission_url", "tests/test_document.py::JournalTests::test_permission_without_v540", "tests/test_document.py::JournalTests::test_permission_without_v540_t", "tests/test_document.py::JournalTests::test_plevel", "tests/test_document.py::JournalTests::test_plevel_out_of_choices", "tests/test_document.py::JournalTests::test_publisher_loc", "tests/test_document.py::JournalTests::test_publisher_name", "tests/test_document.py::JournalTests::test_scielo_issn", "tests/test_document.py::JournalTests::test_secs_code", "tests/test_document.py::JournalTests::test_standard", "tests/test_document.py::JournalTests::test_standard_out_of_choices", "tests/test_document.py::JournalTests::test_status", "tests/test_document.py::JournalTests::test_status_lots_of_changes", "tests/test_document.py::JournalTests::test_status_lots_of_changes_study_case_1", "tests/test_document.py::JournalTests::test_status_lots_of_changes_with_reason", "tests/test_document.py::JournalTests::test_status_some_changes", "tests/test_document.py::JournalTests::test_status_without_v51", "tests/test_document.py::JournalTests::test_subject_areas", "tests/test_document.py::JournalTests::test_subject_descriptors", "tests/test_document.py::JournalTests::test_subject_index_coverage", "tests/test_document.py::JournalTests::test_submission_url", "tests/test_document.py::JournalTests::test_update_date", "tests/test_document.py::JournalTests::test_without_ctrl_vocabulary", "tests/test_document.py::JournalTests::test_without_index_coverage", "tests/test_document.py::JournalTests::test_without_journal_abbreviated_title", "tests/test_document.py::JournalTests::test_without_journal_acronym", "tests/test_document.py::JournalTests::test_without_journal_title", "tests/test_document.py::JournalTests::test_without_journal_title_nlm", "tests/test_document.py::JournalTests::test_without_journal_url", "tests/test_document.py::JournalTests::test_without_periodicity", "tests/test_document.py::JournalTests::test_without_periodicity_in_months", "tests/test_document.py::JournalTests::test_without_plevel", "tests/test_document.py::JournalTests::test_without_publisher_loc", "tests/test_document.py::JournalTests::test_without_publisher_name", "tests/test_document.py::JournalTests::test_without_scielo_domain", "tests/test_document.py::JournalTests::test_without_scielo_domain_title_v690", "tests/test_document.py::JournalTests::test_without_secs_code", "tests/test_document.py::JournalTests::test_without_standard", "tests/test_document.py::JournalTests::test_without_subject_areas", "tests/test_document.py::JournalTests::test_without_subject_descriptors", "tests/test_document.py::JournalTests::test_without_wos_citation_indexes", "tests/test_document.py::JournalTests::test_without_wos_subject_areas", "tests/test_document.py::JournalTests::test_wos_citation_indexes", "tests/test_document.py::JournalTests::test_wos_subject_areas", "tests/test_document.py::ArticleTests::test_acceptance_date", "tests/test_document.py::ArticleTests::test_affiliation_just_with_affiliation_name", "tests/test_document.py::ArticleTests::test_affiliation_with_country_iso_3166", "tests/test_document.py::ArticleTests::test_affiliation_without_affiliation_name", "tests/test_document.py::ArticleTests::test_affiliations", "tests/test_document.py::ArticleTests::test_ahead_publication_date", "tests/test_document.py::ArticleTests::test_article", "tests/test_document.py::ArticleTests::test_author_with_two_affiliations", "tests/test_document.py::ArticleTests::test_author_with_two_role", "tests/test_document.py::ArticleTests::test_author_without_affiliations", "tests/test_document.py::ArticleTests::test_author_without_surname_and_given_names", "tests/test_document.py::ArticleTests::test_authors", "tests/test_document.py::ArticleTests::test_collection_acronym", "tests/test_document.py::ArticleTests::test_collection_acronym_priorizing_collection", "tests/test_document.py::ArticleTests::test_collection_acronym_retrieving_v992", "tests/test_document.py::ArticleTests::test_collection_name_brazil", "tests/test_document.py::ArticleTests::test_collection_name_undefined", "tests/test_document.py::ArticleTests::test_corporative_authors", "tests/test_document.py::ArticleTests::test_creation_date", "tests/test_document.py::ArticleTests::test_creation_date_1", "tests/test_document.py::ArticleTests::test_creation_date_2", "tests/test_document.py::ArticleTests::test_data_model_version_html", "tests/test_document.py::ArticleTests::test_data_model_version_html_1", "tests/test_document.py::ArticleTests::test_data_model_version_xml", "tests/test_document.py::ArticleTests::test_document_type", "tests/test_document.py::ArticleTests::test_doi", "tests/test_document.py::ArticleTests::test_doi_clean_1", "tests/test_document.py::ArticleTests::test_doi_clean_2", "tests/test_document.py::ArticleTests::test_doi_v237", "tests/test_document.py::ArticleTests::test_e_location", "tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_1", "tests/test_document.py::ArticleTests::test_end_page_loaded_crazy_legacy_way_2", "tests/test_document.py::ArticleTests::test_end_page_loaded_through_xml", "tests/test_document.py::ArticleTests::test_file_code", "tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_1", "tests/test_document.py::ArticleTests::test_file_code_crazy_slashs_2", "tests/test_document.py::ArticleTests::test_first_author", "tests/test_document.py::ArticleTests::test_first_author_without_author", "tests/test_document.py::ArticleTests::test_fulltexts_field_fulltexts", "tests/test_document.py::ArticleTests::test_fulltexts_without_field_fulltexts", "tests/test_document.py::ArticleTests::test_html_url", "tests/test_document.py::ArticleTests::test_invalid_document_type", "tests/test_document.py::ArticleTests::test_issue_url", "tests/test_document.py::ArticleTests::test_journal_abbreviated_title", "tests/test_document.py::ArticleTests::test_journal_acronym", "tests/test_document.py::ArticleTests::test_journal_title", "tests/test_document.py::ArticleTests::test_keywords", "tests/test_document.py::ArticleTests::test_keywords_iso639_2", "tests/test_document.py::ArticleTests::test_keywords_with_undefined_language", "tests/test_document.py::ArticleTests::test_keywords_without_subfield_k", "tests/test_document.py::ArticleTests::test_keywords_without_subfield_l", "tests/test_document.py::ArticleTests::test_languages_field_fulltexts", "tests/test_document.py::ArticleTests::test_languages_field_v40", "tests/test_document.py::ArticleTests::test_last_page", "tests/test_document.py::ArticleTests::test_mixed_affiliations_1", "tests/test_document.py::ArticleTests::test_normalized_affiliations", "tests/test_document.py::ArticleTests::test_normalized_affiliations_undefined_ISO_3166_CODE", "tests/test_document.py::ArticleTests::test_normalized_affiliations_without_p", "tests/test_document.py::ArticleTests::test_order", "tests/test_document.py::ArticleTests::test_original_abstract_with_just_one_language_defined", "tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined", "tests/test_document.py::ArticleTests::test_original_abstract_with_language_defined_but_different_of_the_article_original_language", "tests/test_document.py::ArticleTests::test_original_abstract_without_language_defined", "tests/test_document.py::ArticleTests::test_original_html_field_body", "tests/test_document.py::ArticleTests::test_original_language_invalid_iso639_2", "tests/test_document.py::ArticleTests::test_original_language_iso639_2", "tests/test_document.py::ArticleTests::test_original_language_original", "tests/test_document.py::ArticleTests::test_original_section_field_v49", "tests/test_document.py::ArticleTests::test_original_title_subfield_t", "tests/test_document.py::ArticleTests::test_original_title_with_just_one_language_defined", "tests/test_document.py::ArticleTests::test_original_title_with_language_defined", "tests/test_document.py::ArticleTests::test_original_title_with_language_defined_but_different_of_the_article_original_language", "tests/test_document.py::ArticleTests::test_original_title_without_language_defined", "tests/test_document.py::ArticleTests::test_pdf_url", "tests/test_document.py::ArticleTests::test_processing_date", "tests/test_document.py::ArticleTests::test_processing_date_1", "tests/test_document.py::ArticleTests::test_project_name", "tests/test_document.py::ArticleTests::test_project_sponsors", "tests/test_document.py::ArticleTests::test_publication_contract", "tests/test_document.py::ArticleTests::test_publication_date", "tests/test_document.py::ArticleTests::test_publisher_id", "tests/test_document.py::ArticleTests::test_publisher_loc", "tests/test_document.py::ArticleTests::test_publisher_name", "tests/test_document.py::ArticleTests::test_receive_date", "tests/test_document.py::ArticleTests::test_review_date", "tests/test_document.py::ArticleTests::test_secion_code_field_v49", "tests/test_document.py::ArticleTests::test_section_code_nd_field_v49", "tests/test_document.py::ArticleTests::test_section_code_without_field_v49", "tests/test_document.py::ArticleTests::test_section_field_v49", "tests/test_document.py::ArticleTests::test_section_nd_field_v49", "tests/test_document.py::ArticleTests::test_section_without_field_v49", "tests/test_document.py::ArticleTests::test_start_page", "tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_1", "tests/test_document.py::ArticleTests::test_start_page_loaded_crazy_legacy_way_2", "tests/test_document.py::ArticleTests::test_start_page_loaded_through_xml", "tests/test_document.py::ArticleTests::test_subject_areas", "tests/test_document.py::ArticleTests::test_thesis_degree", "tests/test_document.py::ArticleTests::test_thesis_organization", "tests/test_document.py::ArticleTests::test_thesis_organization_and_division", "tests/test_document.py::ArticleTests::test_thesis_organization_without_name", "tests/test_document.py::ArticleTests::test_translated_abstracts", "tests/test_document.py::ArticleTests::test_translated_abstracts_without_v83", "tests/test_document.py::ArticleTests::test_translated_abtracts_iso639_2", "tests/test_document.py::ArticleTests::test_translated_htmls_field_body", "tests/test_document.py::ArticleTests::test_translated_section_field_v49", "tests/test_document.py::ArticleTests::test_translated_titles", "tests/test_document.py::ArticleTests::test_translated_titles_iso639_2", "tests/test_document.py::ArticleTests::test_translated_titles_without_v12", "tests/test_document.py::ArticleTests::test_update_date", "tests/test_document.py::ArticleTests::test_update_date_1", "tests/test_document.py::ArticleTests::test_update_date_2", "tests/test_document.py::ArticleTests::test_update_date_3", "tests/test_document.py::ArticleTests::test_whitwout_acceptance_date", "tests/test_document.py::ArticleTests::test_whitwout_ahead_publication_date", "tests/test_document.py::ArticleTests::test_whitwout_receive_date", "tests/test_document.py::ArticleTests::test_whitwout_review_date", "tests/test_document.py::ArticleTests::test_without_affiliations", "tests/test_document.py::ArticleTests::test_without_authors", "tests/test_document.py::ArticleTests::test_without_citations", "tests/test_document.py::ArticleTests::test_without_collection_acronym", "tests/test_document.py::ArticleTests::test_without_corporative_authors", "tests/test_document.py::ArticleTests::test_without_document_type", "tests/test_document.py::ArticleTests::test_without_doi", "tests/test_document.py::ArticleTests::test_without_e_location", "tests/test_document.py::ArticleTests::test_without_html_url", "tests/test_document.py::ArticleTests::test_without_issue_url", "tests/test_document.py::ArticleTests::test_without_journal_abbreviated_title", "tests/test_document.py::ArticleTests::test_without_journal_acronym", "tests/test_document.py::ArticleTests::test_without_journal_title", "tests/test_document.py::ArticleTests::test_without_keywords", "tests/test_document.py::ArticleTests::test_without_last_page", "tests/test_document.py::ArticleTests::test_without_normalized_affiliations", "tests/test_document.py::ArticleTests::test_without_order", "tests/test_document.py::ArticleTests::test_without_original_abstract", "tests/test_document.py::ArticleTests::test_without_original_title", "tests/test_document.py::ArticleTests::test_without_pages", "tests/test_document.py::ArticleTests::test_without_pdf_url", "tests/test_document.py::ArticleTests::test_without_processing_date", "tests/test_document.py::ArticleTests::test_without_project_name", "tests/test_document.py::ArticleTests::test_without_project_sponsor", "tests/test_document.py::ArticleTests::test_without_publication_contract", "tests/test_document.py::ArticleTests::test_without_publication_date", "tests/test_document.py::ArticleTests::test_without_publisher_id", "tests/test_document.py::ArticleTests::test_without_publisher_loc", "tests/test_document.py::ArticleTests::test_without_publisher_name", "tests/test_document.py::ArticleTests::test_without_scielo_domain", "tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69", "tests/test_document.py::ArticleTests::test_without_scielo_domain_article_v69_and_with_title_v690", "tests/test_document.py::ArticleTests::test_without_scielo_domain_title_v690", "tests/test_document.py::ArticleTests::test_without_start_page", "tests/test_document.py::ArticleTests::test_without_subject_areas", "tests/test_document.py::ArticleTests::test_without_thesis_degree", "tests/test_document.py::ArticleTests::test_without_thesis_organization", "tests/test_document.py::ArticleTests::test_without_wos_citation_indexes", "tests/test_document.py::ArticleTests::test_without_wos_subject_areas", "tests/test_document.py::ArticleTests::test_wos_citation_indexes", "tests/test_document.py::ArticleTests::test_wos_subject_areas", "tests/test_document.py::CitationTest::test_a_link_access_date", "tests/test_document.py::CitationTest::test_analytic_institution_for_a_article_citation", "tests/test_document.py::CitationTest::test_analytic_institution_for_a_book_citation", "tests/test_document.py::CitationTest::test_article_title", "tests/test_document.py::CitationTest::test_article_without_title", "tests/test_document.py::CitationTest::test_authors_article", "tests/test_document.py::CitationTest::test_authors_book", "tests/test_document.py::CitationTest::test_authors_link", "tests/test_document.py::CitationTest::test_authors_thesis", "tests/test_document.py::CitationTest::test_book_chapter_title", "tests/test_document.py::CitationTest::test_book_edition", "tests/test_document.py::CitationTest::test_book_volume", "tests/test_document.py::CitationTest::test_book_without_chapter_title", "tests/test_document.py::CitationTest::test_citation_sample_congress", "tests/test_document.py::CitationTest::test_citation_sample_link", "tests/test_document.py::CitationTest::test_citation_sample_link_without_comment", "tests/test_document.py::CitationTest::test_conference_edition", "tests/test_document.py::CitationTest::test_conference_name", "tests/test_document.py::CitationTest::test_conference_sponsor", "tests/test_document.py::CitationTest::test_conference_without_name", "tests/test_document.py::CitationTest::test_conference_without_sponsor", "tests/test_document.py::CitationTest::test_date", "tests/test_document.py::CitationTest::test_doi", "tests/test_document.py::CitationTest::test_editor", "tests/test_document.py::CitationTest::test_elocation_14", "tests/test_document.py::CitationTest::test_elocation_514", "tests/test_document.py::CitationTest::test_end_page_14", "tests/test_document.py::CitationTest::test_end_page_514", "tests/test_document.py::CitationTest::test_end_page_withdout_data", "tests/test_document.py::CitationTest::test_first_author_article", "tests/test_document.py::CitationTest::test_first_author_book", "tests/test_document.py::CitationTest::test_first_author_link", "tests/test_document.py::CitationTest::test_first_author_thesis", "tests/test_document.py::CitationTest::test_first_author_without_monographic_authors", "tests/test_document.py::CitationTest::test_first_author_without_monographic_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_index_number", "tests/test_document.py::CitationTest::test_institutions_all_fields", "tests/test_document.py::CitationTest::test_institutions_v11", "tests/test_document.py::CitationTest::test_institutions_v17", "tests/test_document.py::CitationTest::test_institutions_v29", "tests/test_document.py::CitationTest::test_institutions_v50", "tests/test_document.py::CitationTest::test_institutions_v58", "tests/test_document.py::CitationTest::test_invalid_edition", "tests/test_document.py::CitationTest::test_isbn", "tests/test_document.py::CitationTest::test_isbn_but_not_a_book", "tests/test_document.py::CitationTest::test_issn", "tests/test_document.py::CitationTest::test_issn_but_not_an_article", "tests/test_document.py::CitationTest::test_issue_part", "tests/test_document.py::CitationTest::test_issue_title", "tests/test_document.py::CitationTest::test_journal_issue", "tests/test_document.py::CitationTest::test_journal_volume", "tests/test_document.py::CitationTest::test_link", "tests/test_document.py::CitationTest::test_link_title", "tests/test_document.py::CitationTest::test_link_without_title", "tests/test_document.py::CitationTest::test_monographic_authors", "tests/test_document.py::CitationTest::test_monographic_first_author", "tests/test_document.py::CitationTest::test_pages_14", "tests/test_document.py::CitationTest::test_pages_514", "tests/test_document.py::CitationTest::test_pages_withdout_data", "tests/test_document.py::CitationTest::test_publication_type_article", "tests/test_document.py::CitationTest::test_publication_type_book", "tests/test_document.py::CitationTest::test_publication_type_conference", "tests/test_document.py::CitationTest::test_publication_type_link", "tests/test_document.py::CitationTest::test_publication_type_thesis", "tests/test_document.py::CitationTest::test_publication_type_undefined", "tests/test_document.py::CitationTest::test_publisher", "tests/test_document.py::CitationTest::test_publisher_address", "tests/test_document.py::CitationTest::test_publisher_address_without_e", "tests/test_document.py::CitationTest::test_series_book", "tests/test_document.py::CitationTest::test_series_but_neither_journal_book_or_conference_citation", "tests/test_document.py::CitationTest::test_series_conference", "tests/test_document.py::CitationTest::test_series_journal", "tests/test_document.py::CitationTest::test_source_book_title", "tests/test_document.py::CitationTest::test_source_journal", "tests/test_document.py::CitationTest::test_source_journal_without_journal_title", "tests/test_document.py::CitationTest::test_sponsor", "tests/test_document.py::CitationTest::test_start_page_14", "tests/test_document.py::CitationTest::test_start_page_514", "tests/test_document.py::CitationTest::test_start_page_withdout_data", "tests/test_document.py::CitationTest::test_thesis_institution", "tests/test_document.py::CitationTest::test_thesis_title", "tests/test_document.py::CitationTest::test_thesis_without_title", "tests/test_document.py::CitationTest::test_title_when_article_citation", "tests/test_document.py::CitationTest::test_title_when_conference_citation", "tests/test_document.py::CitationTest::test_title_when_link_citation", "tests/test_document.py::CitationTest::test_title_when_thesis_citation", "tests/test_document.py::CitationTest::test_with_volume_but_not_a_journal_article_neither_a_book", "tests/test_document.py::CitationTest::test_without_analytic_institution", "tests/test_document.py::CitationTest::test_without_authors", "tests/test_document.py::CitationTest::test_without_date", "tests/test_document.py::CitationTest::test_without_doi", "tests/test_document.py::CitationTest::test_without_edition", "tests/test_document.py::CitationTest::test_without_editor", "tests/test_document.py::CitationTest::test_without_first_author", "tests/test_document.py::CitationTest::test_without_index_number", "tests/test_document.py::CitationTest::test_without_institutions", "tests/test_document.py::CitationTest::test_without_issue", "tests/test_document.py::CitationTest::test_without_issue_part", "tests/test_document.py::CitationTest::test_without_issue_title", "tests/test_document.py::CitationTest::test_without_link", "tests/test_document.py::CitationTest::test_without_monographic_authors", "tests/test_document.py::CitationTest::test_without_monographic_authors_but_not_a_book_citation", "tests/test_document.py::CitationTest::test_without_publisher", "tests/test_document.py::CitationTest::test_without_publisher_address", "tests/test_document.py::CitationTest::test_without_series", "tests/test_document.py::CitationTest::test_without_sponsor", "tests/test_document.py::CitationTest::test_without_thesis_institution", "tests/test_document.py::CitationTest::test_without_volume" ]
[]
BSD 2-Clause "Simplified" License
455
248
[ "xylose/scielodocument.py" ]
DataDog__datadogpy-118
c8bc9d6cce1caebea0be16366f2cd0c3efb47571
2016-03-01 18:46:54
ef81785f880925467b9eeccf5ebd5b226a05d32f
yannmh: @JohnLZeller can you take a pass on it ? JohnLZeller: :+1: looks good once conflicts are resolved.
diff --git a/datadog/dogstatsd/base.py b/datadog/dogstatsd/base.py index 7e0e11d..2f7725c 100644 --- a/datadog/dogstatsd/base.py +++ b/datadog/dogstatsd/base.py @@ -22,7 +22,7 @@ log = logging.getLogger('dogstatsd') class DogStatsd(object): OK, WARNING, CRITICAL, UNKNOWN = (0, 1, 2, 3) - def __init__(self, host='localhost', port=8125, max_buffer_size=50, + def __init__(self, host='localhost', port=8125, max_buffer_size=50, namespace=None, constant_tags=None, use_ms=False): """ Initialize a DogStatsd object. @@ -39,7 +39,10 @@ class DogStatsd(object): if sending metrics in batch :type max_buffer_size: integer - :param constant_tags: Tags to attach to every metric reported by this client + :param namepace: Namespace to prefix all metric names + :type namepace: string + + :param constant_tags: Tags to attach to all metrics :type constant_tags: list of strings :param use_ms: Report timed values in milliseconds instead of seconds (default False) @@ -58,6 +61,7 @@ class DogStatsd(object): if constant_tags is None: constant_tags = [] self.constant_tags = constant_tags + env_tags + self.namespace = namespace self.use_ms = use_ms def __enter__(self): @@ -222,24 +226,37 @@ class DogStatsd(object): self._report(metric, 's', value, tags, sample_rate) def _report(self, metric, metric_type, value, tags, sample_rate): + """ + Create a metric packet and send it. + + More information about the packets' format: http://docs.datadoghq.com/guides/dogstatsd/ + """ if sample_rate != 1 and random() > sample_rate: return - payload = [metric, ":", value, "|", metric_type] - if sample_rate != 1: - payload.extend(["|@", sample_rate]) + payload = [] - # Append all client level tags to every metric + # Resolve the full tag list if self.constant_tags: if tags: tags = tags + self.constant_tags else: tags = self.constant_tags + # Create/format the metric packet + if self.namespace: + payload.extend([self.namespace, "."]) + payload.extend([metric, ":", value, "|", metric_type]) + + if sample_rate != 1: + payload.extend(["|@", sample_rate]) + if tags: payload.extend(["|#", ",".join(tags)]) encoded = "".join(imap(str, payload)) + + # Send it self._send(encoded) def _send_to_server(self, packet): diff --git a/datadog/threadstats/base.py b/datadog/threadstats/base.py index 89bbfc9..40aed00 100644 --- a/datadog/threadstats/base.py +++ b/datadog/threadstats/base.py @@ -23,7 +23,7 @@ log = logging.getLogger('dd.datadogpy') class ThreadStats(object): - def __init__(self, constant_tags=None): + def __init__(self, namespace="", constant_tags=None): """ Initialize a dogstats object. @@ -33,13 +33,16 @@ class ThreadStats(object): :envvar DATADOG_TAGS: Tags to attach to every metric reported by ThreadStats client :type constant_tags: list of strings """ - # Don't collect until start is called. - self._disabled = True + # Parameters + self.namespace = namespace env_tags = [tag for tag in os.environ.get('DATADOG_TAGS', '').split(',') if tag] if constant_tags is None: constant_tags = [] self.constant_tags = constant_tags + env_tags + # State + self._disabled = True + def start(self, flush_interval=10, roll_up_interval=10, device=None, flush_in_thread=True, flush_in_greenlet=False, disabled=False): """ @@ -307,23 +310,31 @@ class ThreadStats(object): self._is_flush_in_progress = False def _get_aggregate_metrics(self, flush_time=None): + """ + Get, format and return the rolled up metrics from the aggregator. + """ # Get rolled up metrics rolled_up_metrics = self._metric_aggregator.flush(flush_time) # FIXME: emit a dictionary from the aggregator metrics = [] for timestamp, value, name, tags, host in rolled_up_metrics: - # Append all client level tags to every metric metric_tags = tags + metric_name = name + # Append all client level tags to every metric if self.constant_tags: if tags: metric_tags = tags + self.constant_tags else: metric_tags = self.constant_tags + # Resolve the metric name + if self.namespace: + metric_name = self.namespace + "." + name + metric = { - 'metric': name, + 'metric': metric_name, 'points': [[timestamp, value]], 'type': MetricType.Gauge, 'host': host,
Prefix support Please, add prefix support like Java and C#: https://github.com/DataDog/dogstatsd-csharp-client/blob/master/src/StatsdClient/StatsdConfig.cs#L8 https://github.com/indeedeng/java-dogstatsd-client/blob/master/src/main/java/com/timgroup/statsd/NonBlockingStatsDClient.java#L120
DataDog/datadogpy
diff --git a/tests/unit/dogstatsd/test_statsd.py b/tests/unit/dogstatsd/test_statsd.py index dacf09d..8473b87 100644 --- a/tests/unit/dogstatsd/test_statsd.py +++ b/tests/unit/dogstatsd/test_statsd.py @@ -149,6 +149,14 @@ class TestDogStatsd(object): u'_sc|my_check.name|{0}|d:{1}|h:i-abcd1234|#key1:val1,key2:val2|m:{2}' .format(self.statsd.WARNING, now, u"♬ †øU \\n†øU ¥ºu|m\: T0µ ♪"), self.recv()) + def test_metric_namespace(self): + """ + Namespace prefixes all metric names. + """ + self.statsd.namespace = "foo" + self.statsd.gauge('gauge', 123.4) + t.assert_equal('foo.gauge:123.4|g', self.recv()) + # Test Client level contant tags def test_gauge_constant_tags(self): self.statsd.constant_tags=['bar:baz', 'foo'] diff --git a/tests/unit/threadstats/test_threadstats.py b/tests/unit/threadstats/test_threadstats.py index eaa0658..6f2e90b 100644 --- a/tests/unit/threadstats/test_threadstats.py +++ b/tests/unit/threadstats/test_threadstats.py @@ -2,18 +2,19 @@ Tests for the ThreadStats class, using HTTP mode """ -import os +# stdlib import logging +import os import random import time -import threading +import unittest +# 3p +from mock import patch import nose.tools as nt -from nose.plugins.skip import SkipTest +# datadog from datadog import ThreadStats -from datadog.api.exceptions import ApiNotInitialized - from tests.util.contextmanagers import preserve_environment_variable @@ -22,12 +23,10 @@ logger = logging.getLogger('dd.datadogpy') logger.setLevel(logging.ERROR) -# -# Test fixtures. -# - class MemoryReporter(object): - """ A reporting class that reports to memory for testing. """ + """ + A reporting class that reports to memory for testing. + """ def __init__(self): self.metrics = [] @@ -40,14 +39,20 @@ class MemoryReporter(object): self.events += events -# -# Unit tests. -# -class TestUnitThreadStats(object): - """ Unit tests for the dog stats api. """ +class TestUnitThreadStats(unittest.TestCase): + """ + Unit tests for ThreadStats. + """ + def setUp(self): + """ + Set a mocked reporter. + """ + self.reporter = MemoryReporter() def sort_metrics(self, metrics): - """ Sort metrics by timestamp of first point and then name """ + """ + Sort metrics by timestamp of first point and then name. + """ def sort(metric): tags = metric['tags'] or [] host = metric['host'] or '' @@ -55,6 +60,39 @@ class TestUnitThreadStats(object): metric['points'][0][1]) return sorted(metrics, key=sort) + def assertMetric(self, name=None, value=None, tags=None, count=None): + """ + Helper, to make assertions on metrics. + """ + matching_metrics = [] + + for metric in self.reporter.metrics: + if name and name != metric['metric']: + continue + if value and value != metric['points'][0][1]: + continue + if tags and tags != metric['tags']: + continue + matching_metrics.append(metric) + + if count: + self.assertEquals( + len(matching_metrics), count, + u"Candidate size assertion failure: expected {expected}, found {count}. " + u"Metric name={name}, value={value}, tags={tags}.".format( + expected=count, count=len(matching_metrics), + name=name, value=value, tags=tags + ) + ) + else: + self.assertTrue( + len(matching_metrics) > 0, + u"Candidate size assertion failure: no matching metric found. " + u"Metric name={name}, value={value}, tags={tags}.".format( + name=name, value=value, tags=tags + ) + ) + def test_timed_decorator(self): dog = ThreadStats() dog.start(roll_up_interval=1, flush_in_thread=False) @@ -393,51 +431,75 @@ class TestUnitThreadStats(object): nt.assert_equal(g3['points'][0][1], 20) def test_constant_tags(self): - dog = ThreadStats(constant_tags=['type:constant']) - dog.start(roll_up_interval=10, flush_in_thread=False) - reporter = dog.reporter = MemoryReporter() + """ + Constant tags are attached to all metrics. + """ + dog = ThreadStats(constant_tags=["type:constant"]) + dog.start(roll_up_interval=1, flush_in_thread=False) + dog.reporter = self.reporter # Post the same metric with different tags. - dog.gauge('gauge', 10, timestamp=100.0) - dog.gauge('gauge', 15, timestamp=100.0, tags=['env:production', 'db']) - dog.gauge('gauge', 20, timestamp=100.0, tags=['env:staging']) + dog.gauge("gauge", 10, timestamp=100.0) + dog.gauge("gauge", 15, timestamp=100.0, tags=["env:production", 'db']) + dog.gauge("gauge", 20, timestamp=100.0, tags=["env:staging"]) - dog.increment('counter', timestamp=100.0) - dog.increment('counter', timestamp=100.0, tags=['env:production', 'db']) - dog.increment('counter', timestamp=100.0, tags=['env:staging']) + dog.increment("counter", timestamp=100.0) + dog.increment("counter", timestamp=100.0, tags=["env:production", 'db']) + dog.increment("counter", timestamp=100.0, tags=["env:staging"]) dog.flush(200.0) - metrics = self.sort_metrics(reporter.metrics) - nt.assert_equal(len(metrics), 6) + # Assertions on all metrics + self.assertMetric(count=6) - [c1, c2, c3, g1, g2, g3] = metrics - (nt.assert_equal(c['metric'], 'counter') for c in [c1, c2, c3]) - nt.assert_equal(c1['tags'], ['env:production', 'db', 'type:constant']) - nt.assert_equal(c1['points'][0][1], 1) - nt.assert_equal(c2['tags'], ['env:staging', 'type:constant']) - nt.assert_equal(c2['points'][0][1], 1) - nt.assert_equal(c3['tags'], ['type:constant']) - nt.assert_equal(c3['points'][0][1], 1) + # Assertions on gauges + self.assertMetric(name='gauge', value=10, tags=["type:constant"], count=1) + self.assertMetric(name="gauge", value=15, tags=["env:production", "db", "type:constant"], count=1) # noqa + self.assertMetric(name="gauge", value=20, tags=["env:staging", "type:constant"], count=1) - (nt.assert_equal(c['metric'], 'gauge') for c in [g1, g2, g3]) - nt.assert_equal(g1['tags'], ['env:production', 'db', 'type:constant']) - nt.assert_equal(g1['points'][0][1], 15) - nt.assert_equal(g2['tags'], ['env:staging', 'type:constant']) - nt.assert_equal(g2['points'][0][1], 20) - nt.assert_equal(g3['tags'], ['type:constant']) - nt.assert_equal(g3['points'][0][1], 10) + # Assertions on counters + self.assertMetric(name="counter", value=1, tags=["type:constant"], count=1) + self.assertMetric(name="counter", value=1, tags=["env:production", "db", "type:constant"], count=1) # noqa + self.assertMetric(name="counter", value=1, tags=["env:staging", "type:constant"], count=1) # Ensure histograms work as well. @dog.timed('timed', tags=['version:1']) - def test(): + def do_nothing(): + """ + A function that does nothing, but being timed. + """ pass - test() + + with patch("datadog.threadstats.base.time", return_value=300): + do_nothing() + dog.histogram('timed', 20, timestamp=300.0, tags=['db', 'version:2']) - reporter.metrics = [] - dog.flush(400) - for metric in reporter.metrics: - assert metric['tags'] # this is enough + + self.reporter.metrics = [] + dog.flush(400.0) + + # Histograms, and related metric types, produce 8 different metrics + self.assertMetric(tags=["version:1", "type:constant"], count=8) + self.assertMetric(tags=["db", "version:2", "type:constant"], count=8) + + def test_metric_namespace(self): + """ + Namespace prefixes all metric names. + """ + # Set up ThreadStats with a namespace + dog = ThreadStats(namespace="foo") + dog.start(roll_up_interval=1, flush_in_thread=False) + dog.reporter = self.reporter + + # Send a few metrics + dog.gauge("gauge", 20, timestamp=100.0) + dog.increment("counter", timestamp=100.0) + dog.flush(200.0) + + # Metric names are prefixed with the namespace + self.assertMetric(count=2) + self.assertMetric(name="foo.gauge", count=1) + self.assertMetric(name="foo.counter", count=1) def test_host(self): dog = ThreadStats()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 2 }
0.10
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "nose", "six", "mock", "pytest" ], "pre_install": null, "python": "3.4", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work certifi==2021.5.30 charset-normalizer==2.0.12 -e git+https://github.com/DataDog/datadogpy.git@c8bc9d6cce1caebea0be16366f2cd0c3efb47571#egg=datadog decorator==5.1.1 idna==3.10 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mock==5.2.0 more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work nose==1.3.7 packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work py @ file:///opt/conda/conda-bld/py_1644396412707/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 requests==2.27.1 simplejson==3.20.1 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3==1.26.20 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: datadogpy channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - attrs=21.4.0=pyhd3eb1b0_0 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - importlib-metadata=4.8.1=py36h06a4308_0 - importlib_metadata=4.8.1=hd3eb1b0_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - more-itertools=8.12.0=pyhd3eb1b0_0 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pip=21.2.2=py36h06a4308_0 - pluggy=0.13.1=py36h06a4308_0 - py=1.11.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pytest=6.2.4=py36h06a4308_2 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - toml=0.10.2=pyhd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zipp=3.6.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - pip: - charset-normalizer==2.0.12 - decorator==5.1.1 - idna==3.10 - mock==5.2.0 - nose==1.3.7 - requests==2.27.1 - simplejson==3.20.1 - six==1.17.0 - urllib3==1.26.20 prefix: /opt/conda/envs/datadogpy
[ "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_metric_namespace" ]
[ "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_set", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_gauge", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_counter", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_histogram", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_tagged_gauge", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_tagged_counter", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_tagged_histogram", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_sample_rate", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_tags_and_samples", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_timing", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_event", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_event_constant_tags", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_service_check", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_metric_namespace", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_gauge_constant_tags", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_counter_constant_tag_with_metric_level_tags", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_gauge_constant_tags_with_metric_level_tags_twice", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_socket_error", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_timed", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_timed_in_ms", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_timed_no_metric", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_timed_context", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_timed_context_exception", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_timed_context_no_metric_exception", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_batched" ]
[ "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_initialization", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_context_manager", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_batched_buffer_autoflush", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_module_level_instance", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_instantiating_does_not_connect", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_accessing_socket_opens_socket", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_accessing_socket_multiple_times_returns_same_socket", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_tags_from_environment", "tests/unit/dogstatsd/test_statsd.py::TestDogStatsd::test_tags_from_environment_and_constant", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_constant_tags", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_counter", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_custom_host_and_device", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_default_host_and_device", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_disabled_mode", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_event", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_event_constant_tags", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_gauge", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_histogram", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_histogram_percentiles", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_host", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_stop", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_tags", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_tags_from_environment", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_tags_from_environment_and_constant", "tests/unit/threadstats/test_threadstats.py::TestUnitThreadStats::test_timed_decorator" ]
[]
BSD-3-Clause
457
1,266
[ "datadog/dogstatsd/base.py", "datadog/threadstats/base.py" ]
falconry__falcon-723
ac03888ad750598175fa1591ef11ec8ae31b0dc0
2016-03-03 01:33:46
b78ffaac7c412d3b3d6cd3c70dd05024d79d2cce
kgriffs: Routing tree from the test: https://github.com/falconry/falcon/pull/723 jmvrbanac: Interesting. Seems to look good to me. kgriffs: Sorry, I had the wrong link for the routing tree. Updated. jmvrbanac: Outside of of @fxfitz's suggestion, :+1:
diff --git a/falcon/routing/compiled.py b/falcon/routing/compiled.py index 5f8f951..9177edb 100644 --- a/falcon/routing/compiled.py +++ b/falcon/routing/compiled.py @@ -95,7 +95,7 @@ class CompiledRouter(object): else: return None, None, None - def _compile_tree(self, nodes, indent=1, level=0): + def _compile_tree(self, nodes, indent=1, level=0, fast_return=True): """Generates Python code for a routing tree or subtree.""" def line(text, indent_offset=0): @@ -119,6 +119,18 @@ class CompiledRouter(object): nodes, key=lambda node: node.is_var + (node.is_var and not node.is_complex)) + # NOTE(kgriffs): Down to this branch in the tree, we can do a + # fast 'return None'. See if the nodes at this branch are + # all still simple, meaning there is only one possible path. + if fast_return: + if len(nodes) > 1: + # NOTE(kgriffs): There's the possibility of more than + # one path. + var_nodes = [node for node in nodes if node.is_var] + found_var_nodes = bool(var_nodes) + + fast_return = not found_var_nodes + for node in nodes: if node.is_var: if node.is_complex: @@ -162,10 +174,11 @@ class CompiledRouter(object): resource_idx = len(self._return_values) self._return_values.append(node) - self._compile_tree(node.children, indent, level + 1) + self._compile_tree(node.children, indent, level + 1, fast_return) if node.resource is None: - line('return None') + if fast_return: + line('return None') else: # NOTE(kgriffs): Make sure that we have consumed all of # the segments for the requested route; otherwise we could @@ -173,11 +186,12 @@ class CompiledRouter(object): line('if path_len == %d:' % (level + 1)) line('return return_values[%d]' % resource_idx, 1) - line('return None') + if fast_return: + line('return None') indent = level_indent - if not found_simple: + if not found_simple and fast_return: line('return None') def _compile(self):
Path segment in one route's URI template masks the field expression in another route The following test demonstrates the issue. The assertion fails since the resulting status code is 404, rather than 200. "/v2.0/thing" should route to `/{version}/thing` instead of `/v2.0`. ```py def test_string_vs_var(self): self.api.add_route('/v2.0', self.resource) self.simulate_request('/v2.0') self.api.add_route('/{version}/thing', testing.TestResource()) self.simulate_request('/v2.0/thing') self.assertEqual(self.srmock.status, falcon.HTTP_200) ``` ``` /{version}/foo/bar /v1.0 ```
falconry/falcon
diff --git a/tests/test_default_router.py b/tests/test_default_router.py index 9dc5ecd..84af78f 100644 --- a/tests/test_default_router.py +++ b/tests/test_default_router.py @@ -1,5 +1,6 @@ import ddt +from falcon.routing import DefaultRouter import falcon.testing as testing @@ -14,66 +15,115 @@ class ResourceWithId(object): resp.body = self.resource_id -def setup_routes(router_interface): - router_interface.add_route( - '/repos', {}, ResourceWithId(1)) - router_interface.add_route( - '/repos/{org}', {}, ResourceWithId(2)) - router_interface.add_route( - '/repos/{org}/{repo}', {}, ResourceWithId(3)) - router_interface.add_route( - '/repos/{org}/{repo}/commits', {}, ResourceWithId(4)) - router_interface.add_route( - '/repos/{org}/{repo}/compare/{usr0}:{branch0}...{usr1}:{branch1}', - {}, ResourceWithId(5)) - router_interface.add_route( - '/teams/{id}', {}, ResourceWithId(6)) - router_interface.add_route( - '/teams/{id}/members', {}, ResourceWithId(7)) - router_interface.add_route( - '/user/memberships', {}, ResourceWithId(8)) - router_interface.add_route( - '/emojis', {}, ResourceWithId(9)) - router_interface.add_route( - '/repos/{org}/{repo}/compare/{usr0}:{branch0}...{usr1}:{branch1}/full', - {}, ResourceWithId(10)) - router_interface.add_route( - '/repos/{org}/{repo}/compare/all', {}, ResourceWithId(11)) - - # NOTE(kgriffs): The ordering of these calls is significant; we - # need to test that the {id} field does not match the other routes, - # regardless of the order they are added. - router_interface.add_route( - '/emojis/signs/0', {}, ResourceWithId(12)) - router_interface.add_route( - '/emojis/signs/{id}', {}, ResourceWithId(13)) - router_interface.add_route( - '/emojis/signs/42', {}, ResourceWithId(14)) - router_interface.add_route( - '/emojis/signs/42/small', {}, ResourceWithId(14.1)) - router_interface.add_route( - '/emojis/signs/78/small', {}, ResourceWithId(14.1)) - - router_interface.add_route( - '/repos/{org}/{repo}/compare/{usr0}:{branch0}...{usr1}:{branch1}/part', - {}, ResourceWithId(15)) - router_interface.add_route( - '/repos/{org}/{repo}/compare/{usr0}:{branch0}', - {}, ResourceWithId(16)) - router_interface.add_route( - '/repos/{org}/{repo}/compare/{usr0}:{branch0}/full', - {}, ResourceWithId(17)) - - router_interface.add_route( - '/gists/{id}/raw', {}, ResourceWithId(18)) +class TestRegressionCases(testing.TestBase): + """Test specific repros reported by users of the framework.""" + + def before(self): + self.router = DefaultRouter() + + def test_versioned_url(self): + self.router.add_route('/{version}/messages', {}, ResourceWithId(2)) + + resource, method_map, params = self.router.find('/v2/messages') + self.assertEqual(resource.resource_id, 2) + + self.router.add_route('/v2', {}, ResourceWithId(1)) + + resource, method_map, params = self.router.find('/v2') + self.assertEqual(resource.resource_id, 1) + + resource, method_map, params = self.router.find('/v2/messages') + self.assertEqual(resource.resource_id, 2) + + resource, method_map, params = self.router.find('/v1/messages') + self.assertEqual(resource.resource_id, 2) + + resource, method_map, params = self.router.find('/v1') + self.assertIs(resource, None) + + def test_recipes(self): + self.router.add_route( + '/recipes/{activity}/{type_id}', {}, ResourceWithId(1)) + self.router.add_route( + '/recipes/baking', {}, ResourceWithId(2)) + + resource, method_map, params = self.router.find('/recipes/baking/4242') + self.assertEqual(resource.resource_id, 1) + + resource, method_map, params = self.router.find('/recipes/baking') + self.assertEqual(resource.resource_id, 2) + + resource, method_map, params = self.router.find('/recipes/grilling') + self.assertIs(resource, None) @ddt.ddt -class TestStandaloneRouter(testing.TestBase): +class TestComplexRouting(testing.TestBase): def before(self): - from falcon.routing import DefaultRouter self.router = DefaultRouter() - setup_routes(self.router) + + self.router.add_route( + '/repos', {}, ResourceWithId(1)) + self.router.add_route( + '/repos/{org}', {}, ResourceWithId(2)) + self.router.add_route( + '/repos/{org}/{repo}', {}, ResourceWithId(3)) + self.router.add_route( + '/repos/{org}/{repo}/commits', {}, ResourceWithId(4)) + self.router.add_route( + '/repos/{org}/{repo}/compare/{usr0}:{branch0}...{usr1}:{branch1}', + {}, ResourceWithId(5)) + + self.router.add_route( + '/teams/{id}', {}, ResourceWithId(6)) + self.router.add_route( + '/teams/{id}/members', {}, ResourceWithId(7)) + + self.router.add_route( + '/teams/default', {}, ResourceWithId(19)) + self.router.add_route( + '/teams/default/members/thing', {}, ResourceWithId(19)) + + self.router.add_route( + '/user/memberships', {}, ResourceWithId(8)) + self.router.add_route( + '/emojis', {}, ResourceWithId(9)) + self.router.add_route( + '/repos/{org}/{repo}/compare/{usr0}:{branch0}...{usr1}:{branch1}/full', + {}, ResourceWithId(10)) + self.router.add_route( + '/repos/{org}/{repo}/compare/all', {}, ResourceWithId(11)) + + # NOTE(kgriffs): The ordering of these calls is significant; we + # need to test that the {id} field does not match the other routes, + # regardless of the order they are added. + self.router.add_route( + '/emojis/signs/0', {}, ResourceWithId(12)) + self.router.add_route( + '/emojis/signs/{id}', {}, ResourceWithId(13)) + self.router.add_route( + '/emojis/signs/42', {}, ResourceWithId(14)) + self.router.add_route( + '/emojis/signs/42/small', {}, ResourceWithId(14.1)) + self.router.add_route( + '/emojis/signs/78/small', {}, ResourceWithId(22)) + + self.router.add_route( + '/repos/{org}/{repo}/compare/{usr0}:{branch0}...{usr1}:{branch1}/part', + {}, ResourceWithId(15)) + self.router.add_route( + '/repos/{org}/{repo}/compare/{usr0}:{branch0}', + {}, ResourceWithId(16)) + self.router.add_route( + '/repos/{org}/{repo}/compare/{usr0}:{branch0}/full', + {}, ResourceWithId(17)) + + self.router.add_route( + '/gists/{id}/{representation}', {}, ResourceWithId(21)) + self.router.add_route( + '/gists/{id}/raw', {}, ResourceWithId(18)) + self.router.add_route( + '/gists/first', {}, ResourceWithId(20)) @ddt.data( '/teams/{collision}', # simple vs simple @@ -103,20 +153,6 @@ class TestStandaloneRouter(testing.TestBase): resource, method_map, params = self.router.find('/emojis/signs/0') self.assertEqual(resource.resource_id, -1) - def test_missing(self): - resource, method_map, params = self.router.find('/this/does/not/exist') - self.assertIs(resource, None) - - resource, method_map, params = self.router.find('/user/bogus') - self.assertIs(resource, None) - - resource, method_map, params = self.router.find('/teams/1234/bogus') - self.assertIs(resource, None) - - resource, method_map, params = self.router.find( - '/repos/racker/falcon/compare/johndoe:master...janedoe:dev/bogus') - self.assertIs(resource, None) - def test_literal_segment(self): resource, method_map, params = self.router.find('/emojis/signs/0') self.assertEqual(resource.resource_id, 12) @@ -167,6 +203,54 @@ class TestStandaloneRouter(testing.TestBase): resource, method_map, params = self.router.find('/gists/42/raw') self.assertEqual(params, {'id': '42'}) + @ddt.data( + ('/teams/default', 19), + ('/teams/default/members', 7), + ('/teams/foo', 6), + ('/teams/foo/members', 7), + ('/gists/first', 20), + ('/gists/first/raw', 18), + ('/gists/first/pdf', 21), + ('/gists/1776/pdf', 21), + ('/emojis/signs/78', 13), + ('/emojis/signs/78/small', 22), + ) + @ddt.unpack + def test_literal_vs_variable(self, path, expected_id): + resource, method_map, params = self.router.find(path) + self.assertEqual(resource.resource_id, expected_id) + + @ddt.data( + # Misc. + '/this/does/not/exist', + '/user/bogus', + '/repos/racker/falcon/compare/johndoe:master...janedoe:dev/bogus', + + # Literal vs variable (teams) + '/teams', + '/teams/42/members/undefined', + '/teams/42/undefined', + '/teams/42/undefined/segments', + '/teams/default/members/undefined', + '/teams/default/members/thing/undefined', + '/teams/default/members/thing/undefined/segments', + '/teams/default/undefined', + '/teams/default/undefined/segments', + + # Literal vs variable (emojis) + '/emojis/signs', + '/emojis/signs/0/small', + '/emojis/signs/0/undefined', + '/emojis/signs/0/undefined/segments', + '/emojis/signs/20/small', + '/emojis/signs/20/undefined', + '/emojis/signs/42/undefined', + '/emojis/signs/78/undefined', + ) + def test_not_found(self, path): + resource, method_map, params = self.router.find(path) + self.assertIs(resource, None) + def test_subsegment_not_found(self): resource, method_map, params = self.router.find('/emojis/signs/0/x') self.assertIs(resource, None) @@ -195,7 +279,7 @@ class TestStandaloneRouter(testing.TestBase): 'usr0': 'johndoe', 'branch0': 'master', 'usr1': 'janedoe', - 'branch1': 'dev' + 'branch1': 'dev', }) @ddt.data(('', 16), ('/full', 17))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.3
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "nose", "tox", "coveralls", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.5", "reqs_path": [ "tools/test-requires" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 charset-normalizer==2.0.12 coverage==6.2 coveralls==3.3.1 ddt==1.7.2 distlib==0.3.9 docopt==0.6.2 -e git+https://github.com/falconry/falcon.git@ac03888ad750598175fa1591ef11ec8ae31b0dc0#egg=falcon filelock==3.4.1 fixtures==4.0.1 idna==3.10 importlib-metadata==4.8.3 importlib-resources==5.4.0 iniconfig==1.1.1 nose==1.3.7 packaging==21.3 pbr==6.1.1 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 python-mimeparse==1.6.0 PyYAML==6.0.1 requests==2.27.1 six==1.17.0 testtools==2.6.0 toml==0.10.2 tomli==1.2.3 tox==3.28.0 typing_extensions==4.1.1 urllib3==1.26.20 virtualenv==20.17.1 zipp==3.6.0
name: falcon channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - charset-normalizer==2.0.12 - coverage==6.2 - coveralls==3.3.1 - ddt==1.7.2 - distlib==0.3.9 - docopt==0.6.2 - filelock==3.4.1 - fixtures==4.0.1 - idna==3.10 - importlib-metadata==4.8.3 - importlib-resources==5.4.0 - iniconfig==1.1.1 - nose==1.3.7 - packaging==21.3 - pbr==6.1.1 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - python-mimeparse==1.6.0 - pyyaml==6.0.1 - requests==2.27.1 - six==1.17.0 - testtools==2.6.0 - toml==0.10.2 - tomli==1.2.3 - tox==3.28.0 - typing-extensions==4.1.1 - urllib3==1.26.20 - virtualenv==20.17.1 - zipp==3.6.0 prefix: /opt/conda/envs/falcon
[ "tests/test_default_router.py::TestRegressionCases::test_recipes", "tests/test_default_router.py::TestRegressionCases::test_versioned_url", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_02____teams_default_members___7_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_06____gists_first_raw___18_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_07____gists_first_pdf___21_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_09____emojis_signs_78___13_" ]
[]
[ "tests/test_default_router.py::TestComplexRouting::test_collision_1__teams__collision_", "tests/test_default_router.py::TestComplexRouting::test_collision_2__emojis_signs__id_too_", "tests/test_default_router.py::TestComplexRouting::test_collision_3__repos__org___repo__compare__complex___vs_____complex2___collision_", "tests/test_default_router.py::TestComplexRouting::test_complex_1______5_", "tests/test_default_router.py::TestComplexRouting::test_complex_2____full___10_", "tests/test_default_router.py::TestComplexRouting::test_complex_3____part___15_", "tests/test_default_router.py::TestComplexRouting::test_complex_alt_1______16_", "tests/test_default_router.py::TestComplexRouting::test_complex_alt_2____full___17_", "tests/test_default_router.py::TestComplexRouting::test_dead_segment_1__teams", "tests/test_default_router.py::TestComplexRouting::test_dead_segment_2__emojis_signs", "tests/test_default_router.py::TestComplexRouting::test_dead_segment_3__gists", "tests/test_default_router.py::TestComplexRouting::test_dead_segment_4__gists_42", "tests/test_default_router.py::TestComplexRouting::test_dump", "tests/test_default_router.py::TestComplexRouting::test_literal", "tests/test_default_router.py::TestComplexRouting::test_literal_segment", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_01____teams_default___19_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_03____teams_foo___6_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_04____teams_foo_members___7_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_05____gists_first___20_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_08____gists_1776_pdf___21_", "tests/test_default_router.py::TestComplexRouting::test_literal_vs_variable_10____emojis_signs_78_small___22_", "tests/test_default_router.py::TestComplexRouting::test_malformed_pattern", "tests/test_default_router.py::TestComplexRouting::test_multivar", "tests/test_default_router.py::TestComplexRouting::test_non_collision_1__repos__org___repo__compare__simple_vs_complex_", "tests/test_default_router.py::TestComplexRouting::test_non_collision_2__repos__complex___vs___simple_", "tests/test_default_router.py::TestComplexRouting::test_non_collision_3__repos__org___repo__compare__complex___vs_____complex2__full", "tests/test_default_router.py::TestComplexRouting::test_not_found_01__this_does_not_exist", "tests/test_default_router.py::TestComplexRouting::test_not_found_02__user_bogus", "tests/test_default_router.py::TestComplexRouting::test_not_found_03__repos_racker_falcon_compare_johndoe_master___janedoe_dev_bogus", "tests/test_default_router.py::TestComplexRouting::test_not_found_04__teams", "tests/test_default_router.py::TestComplexRouting::test_not_found_05__teams_42_members_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_06__teams_42_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_07__teams_42_undefined_segments", "tests/test_default_router.py::TestComplexRouting::test_not_found_08__teams_default_members_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_09__teams_default_members_thing_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_10__teams_default_members_thing_undefined_segments", "tests/test_default_router.py::TestComplexRouting::test_not_found_11__teams_default_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_12__teams_default_undefined_segments", "tests/test_default_router.py::TestComplexRouting::test_not_found_13__emojis_signs", "tests/test_default_router.py::TestComplexRouting::test_not_found_14__emojis_signs_0_small", "tests/test_default_router.py::TestComplexRouting::test_not_found_15__emojis_signs_0_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_16__emojis_signs_0_undefined_segments", "tests/test_default_router.py::TestComplexRouting::test_not_found_17__emojis_signs_20_small", "tests/test_default_router.py::TestComplexRouting::test_not_found_18__emojis_signs_20_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_19__emojis_signs_42_undefined", "tests/test_default_router.py::TestComplexRouting::test_not_found_20__emojis_signs_78_undefined", "tests/test_default_router.py::TestComplexRouting::test_override", "tests/test_default_router.py::TestComplexRouting::test_subsegment_not_found", "tests/test_default_router.py::TestComplexRouting::test_variable" ]
[]
Apache License 2.0
458
593
[ "falcon/routing/compiled.py" ]
dask__dask-1028
6dc9229362f2d3b1dfa466a8a63831c3c832b4be
2016-03-03 21:56:25
6dc9229362f2d3b1dfa466a8a63831c3c832b4be
diff --git a/dask/array/reductions.py b/dask/array/reductions.py index a29003285..c0b12cd08 100644 --- a/dask/array/reductions.py +++ b/dask/array/reductions.py @@ -466,6 +466,13 @@ def arg_agg(func, argfunc, data, axis=None, **kwargs): return _arg_combine(data, axis, argfunc, keepdims=False)[0] +def nanarg_agg(func, argfunc, data, axis=None, **kwargs): + arg, vals = _arg_combine(data, axis, argfunc, keepdims=False) + if np.any(np.isnan(vals)): + raise ValueError("All NaN slice encountered") + return arg + + def arg_reduction(x, chunk, combine, agg, axis=None, split_every=None): """Generic function for argreduction. @@ -514,7 +521,7 @@ def arg_reduction(x, chunk, combine, agg, axis=None, split_every=None): return _tree_reduce(tmp, agg, axis, False, np.int64, split_every, combine) -def make_arg_reduction(func, argfunc): +def make_arg_reduction(func, argfunc, is_nan_func=False): """Create a argreduction callable. Parameters @@ -526,17 +533,34 @@ def make_arg_reduction(func, argfunc): """ chunk = partial(arg_chunk, func, argfunc) combine = partial(arg_combine, func, argfunc) - agg = partial(arg_agg, func, argfunc) + if is_nan_func: + agg = partial(nanarg_agg, func, argfunc) + else: + agg = partial(arg_agg, func, argfunc) @wraps(argfunc) def _(x, axis=None, split_every=None): return arg_reduction(x, chunk, combine, agg, axis, split_every) return _ +def _nanargmin(x, axis, **kwargs): + try: + return chunk.nanargmin(x, axis, **kwargs) + except ValueError: + return chunk.nanargmin(np.where(np.isnan(x), np.inf, x), axis, **kwargs) + + +def _nanargmax(x, axis, **kwargs): + try: + return chunk.nanargmax(x, axis, **kwargs) + except ValueError: + return chunk.nanargmax(np.where(np.isnan(x), -np.inf, x), axis, **kwargs) + + argmin = make_arg_reduction(chunk.min, chunk.argmin) argmax = make_arg_reduction(chunk.max, chunk.argmax) -nanargmin = make_arg_reduction(chunk.nanmin, chunk.nanargmin) -nanargmax = make_arg_reduction(chunk.nanmax, chunk.nanargmax) +nanargmin = make_arg_reduction(chunk.nanmin, _nanargmin, True) +nanargmax = make_arg_reduction(chunk.nanmax, _nanargmax, True) def cumreduction(func, binop, ident, x, axis, dtype=None):
da.nanargmax fails when it encounters an all-NaN slice in a chunk Follow up on #776 ``` In [1]: import numpy as np In [2]: import dask.array as da In [3]: x = np.array([[1.0, np.nan], [np.nan, 2.0]]) In [4]: da.nanmax(da.from_array(x, chunks=1), axis=1).compute() /Users/shoyer/miniconda/envs/dask-dev/lib/python2.7/site-packages/numpy/lib/nanfunctions.py:319: RuntimeWarning: All-NaN slice encountered warnings.warn("All-NaN slice encountered", RuntimeWarning) Out[4]: array([ 1., 2.]) In [5]: da.nanargmax(da.from_array(x, chunks=1), axis=1).compute() --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-403b812e207c> in <module>() ----> 1 da.nanargmax(da.from_array(x, chunks=1), axis=1).compute() /Users/shoyer/dev/dask/dask/base.pyc in compute(self, **kwargs) 29 30 def compute(self, **kwargs): ---> 31 return compute(self, **kwargs)[0] 32 33 @classmethod /Users/shoyer/dev/dask/dask/base.pyc in compute(*args, **kwargs) 97 for opt, val in groups.items()]) 98 keys = [arg._keys() for arg in args] ---> 99 results = get(dsk, keys, **kwargs) 100 return tuple(a._finalize(a, r) for a, r in zip(args, results)) 101 /Users/shoyer/dev/dask/dask/threaded.pyc in get(dsk, result, cache, num_workers, **kwargs) 55 results = get_async(pool.apply_async, len(pool._pool), dsk, result, 56 cache=cache, queue=queue, get_id=_thread_get_id, ---> 57 **kwargs) 58 59 return results /Users/shoyer/dev/dask/dask/async.pyc in get_async(apply_async, num_workers, dsk, result, cache, queue, get_id, raise_on_exception, rerun_exceptions_locally, callbacks, **kwargs) 480 _execute_task(task, data) # Re-execute locally 481 else: --> 482 raise(remote_exception(res, tb)) 483 state['cache'][key] = res 484 finish_task(dsk, key, state, results, keyorder.get) ValueError: All-NaN slice encountered Traceback --------- File "dask/async.py", line 262, in execute_task result = _execute_task(task, data) File "dask/async.py", line 245, in _execute_task return func(*args2) File "dask/array/reductions.py", line 367, in argreduce return (func(x, axis=axis), argfunc(x, axis=axis)) File "dask/array/chunk.py", line 25, in keepdims_wrapped_callable r = a_callable(x, axis=axis, *args, **kwargs) File "/Users/shoyer/miniconda/envs/dask-dev/lib/python2.7/site-packages/numpy/lib/nanfunctions.py", line 420, in nanargmax raise ValueError("All-NaN slice encountered") ```
dask/dask
diff --git a/dask/array/tests/test_reductions.py b/dask/array/tests/test_reductions.py index 7b734416f..2b1a08437 100644 --- a/dask/array/tests/test_reductions.py +++ b/dask/array/tests/test_reductions.py @@ -162,6 +162,26 @@ def test_arg_reductions(dfunc, func): assert eq(dfunc(a2, 0, split_every=2), func(x2, 0)) [email protected](['dfunc', 'func'], + [(da.nanargmin, np.nanargmin), (da.nanargmax, np.nanargmax)]) +def test_nanarg_reductions(dfunc, func): + x = np.random.random((10, 10, 10)) + x[5] = np.nan + a = da.from_array(x, chunks=(3, 4, 5)) + assert eq(dfunc(a), func(x)) + assert eq(dfunc(a, 0), func(x, 0)) + with pytest.raises(ValueError): + dfunc(a, 1).compute() + + with pytest.raises(ValueError): + dfunc(a, 2).compute() + + x[:] = np.nan + a = da.from_array(x, chunks=(3, 4, 5)) + with pytest.raises(ValueError): + dfunc(a).compute() + + def test_reductions_2D_nans(): # chunks are a mix of some/all/no NaNs x = np.full((4, 4), np.nan) @@ -189,17 +209,18 @@ def test_reductions_2D_nans(): reduction_2d_test(da.nanmin, a, np.nanmin, x, False, False) reduction_2d_test(da.nanmax, a, np.nanmax, x, False, False) - # TODO: fix these tests, which fail with this error from NumPy: - # ValueError("All-NaN slice encountered"), because some of the chunks - # (not all) have all NaN values. - # assert eq(da.argmax(a, axis=0), np.argmax(x, axis=0)) - # assert eq(da.argmin(a, axis=0), np.argmin(x, axis=0)) - # assert eq(da.nanargmax(a, axis=0), np.nanargmax(x, axis=0)) - # assert eq(da.nanargmin(a, axis=0), np.nanargmin(x, axis=0)) - # assert eq(da.argmax(a, axis=1), np.argmax(x, axis=1)) - # assert eq(da.argmin(a, axis=1), np.argmin(x, axis=1)) - # assert eq(da.nanargmax(a, axis=1), np.nanargmax(x, axis=1)) - # assert eq(da.nanargmin(a, axis=1), np.nanargmin(x, axis=1)) + assert eq(da.argmax(a), np.argmax(x)) + assert eq(da.argmin(a), np.argmin(x)) + assert eq(da.nanargmax(a), np.nanargmax(x)) + assert eq(da.nanargmin(a), np.nanargmin(x)) + assert eq(da.argmax(a, axis=0), np.argmax(x, axis=0)) + assert eq(da.argmin(a, axis=0), np.argmin(x, axis=0)) + assert eq(da.nanargmax(a, axis=0), np.nanargmax(x, axis=0)) + assert eq(da.nanargmin(a, axis=0), np.nanargmin(x, axis=0)) + assert eq(da.argmax(a, axis=1), np.argmax(x, axis=1)) + assert eq(da.argmin(a, axis=1), np.argmin(x, axis=1)) + assert eq(da.nanargmax(a, axis=1), np.nanargmax(x, axis=1)) + assert eq(da.nanargmin(a, axis=1), np.nanargmin(x, axis=1)) def test_moment():
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
1.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[complete]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "numpy>=1.16.0 pandas>=1.0.0 cloudpickle partd distributed s3fs toolz psutil pytables bokeh bcolz scipy h5py ipython", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y graphviz liblzma-dev" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
aiobotocore @ file:///opt/conda/conda-bld/aiobotocore_1643638228694/work aiohttp @ file:///tmp/build/80754af9/aiohttp_1632748060317/work aioitertools @ file:///tmp/build/80754af9/aioitertools_1607109665762/work async-timeout==3.0.1 attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work backcall @ file:///home/ktietz/src/ci/backcall_1611930011877/work bcolz==1.2.1 bokeh @ file:///tmp/build/80754af9/bokeh_1620710048147/work botocore @ file:///opt/conda/conda-bld/botocore_1642672735464/work brotlipy==0.7.0 certifi==2021.5.30 cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work chardet @ file:///tmp/build/80754af9/chardet_1607706739153/work click==8.0.3 cloudpickle @ file:///tmp/build/80754af9/cloudpickle_1632508026186/work contextvars==2.4 cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work cytoolz==0.11.0 -e git+https://github.com/dask/dask.git@6dc9229362f2d3b1dfa466a8a63831c3c832b4be#egg=dask decorator @ file:///opt/conda/conda-bld/decorator_1643638310831/work distributed @ file:///tmp/build/80754af9/distributed_1615054599257/work fsspec @ file:///opt/conda/conda-bld/fsspec_1642510437511/work h5py==2.10.0 HeapDict @ file:///Users/ktietz/demo/mc3/conda-bld/heapdict_1630598515714/work idna @ file:///tmp/build/80754af9/idna_1637925883363/work idna-ssl @ file:///tmp/build/80754af9/idna_ssl_1611752490495/work immutables @ file:///tmp/build/80754af9/immutables_1628888996840/work importlib-metadata==4.8.3 iniconfig==1.1.1 ipython @ file:///tmp/build/80754af9/ipython_1593447367857/work ipython-genutils @ file:///tmp/build/80754af9/ipython_genutils_1606773439826/work jedi @ file:///tmp/build/80754af9/jedi_1606932572482/work Jinja2 @ file:///opt/conda/conda-bld/jinja2_1647436528585/work jmespath @ file:///Users/ktietz/demo/mc3/conda-bld/jmespath_1630583964805/work locket==0.2.1 MarkupSafe @ file:///tmp/build/80754af9/markupsafe_1621528150516/work mock @ file:///tmp/build/80754af9/mock_1607622725907/work msgpack @ file:///tmp/build/80754af9/msgpack-python_1612287171716/work multidict @ file:///tmp/build/80754af9/multidict_1607367768400/work numexpr @ file:///tmp/build/80754af9/numexpr_1618853194344/work numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work olefile @ file:///Users/ktietz/demo/mc3/conda-bld/olefile_1629805411829/work packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work pandas==1.1.5 parso==0.7.0 partd @ file:///opt/conda/conda-bld/partd_1647245470509/work pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work pickleshare @ file:///tmp/build/80754af9/pickleshare_1606932040724/work Pillow @ file:///tmp/build/80754af9/pillow_1625670622947/work pluggy==1.0.0 prompt-toolkit @ file:///tmp/build/80754af9/prompt-toolkit_1633440160888/work psutil @ file:///tmp/build/80754af9/psutil_1612297621795/work ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl py==1.11.0 pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work Pygments @ file:///opt/conda/conda-bld/pygments_1644249106324/work pyOpenSSL @ file:///opt/conda/conda-bld/pyopenssl_1643788558760/work pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work PySocks @ file:///tmp/build/80754af9/pysocks_1605305763431/work pytest==7.0.1 python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work pytz==2021.3 PyYAML==5.4.1 s3fs @ file:///opt/conda/conda-bld/s3fs_1643701468749/work scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work six @ file:///tmp/build/80754af9/six_1644875935023/work sortedcontainers @ file:///tmp/build/80754af9/sortedcontainers_1623949099177/work tables==3.6.1 tblib @ file:///Users/ktietz/demo/mc3/conda-bld/tblib_1629402031467/work tomli==1.2.3 toolz @ file:///tmp/build/80754af9/toolz_1636545406491/work tornado @ file:///tmp/build/80754af9/tornado_1606942266872/work traitlets @ file:///tmp/build/80754af9/traitlets_1632746497744/work typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work urllib3 @ file:///opt/conda/conda-bld/urllib3_1643638302206/work wcwidth @ file:///Users/ktietz/demo/mc3/conda-bld/wcwidth_1629357192024/work wrapt==1.12.1 yarl @ file:///tmp/build/80754af9/yarl_1606939915466/work zict==2.0.0 zipp==3.6.0
name: dask channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - aiobotocore=2.1.0=pyhd3eb1b0_0 - aiohttp=3.7.4.post0=py36h7f8727e_2 - aioitertools=0.7.1=pyhd3eb1b0_0 - async-timeout=3.0.1=py36h06a4308_0 - attrs=21.4.0=pyhd3eb1b0_0 - backcall=0.2.0=pyhd3eb1b0_0 - bcolz=1.2.1=py36h04863e7_0 - blas=1.0=openblas - blosc=1.21.3=h6a678d5_0 - bokeh=2.3.2=py36h06a4308_0 - botocore=1.23.24=pyhd3eb1b0_0 - brotlipy=0.7.0=py36h27cfd23_1003 - bzip2=1.0.8=h5eee18b_6 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - cffi=1.14.6=py36h400218f_0 - chardet=4.0.0=py36h06a4308_1003 - click=8.0.3=pyhd3eb1b0_0 - cloudpickle=2.0.0=pyhd3eb1b0_0 - contextvars=2.4=py_0 - cryptography=35.0.0=py36hd23ed53_0 - cytoolz=0.11.0=py36h7b6447c_0 - decorator=5.1.1=pyhd3eb1b0_0 - distributed=2021.3.0=py36h06a4308_0 - freetype=2.12.1=h4a9f257_0 - fsspec=2022.1.0=pyhd3eb1b0_0 - giflib=5.2.2=h5eee18b_0 - h5py=2.10.0=py36h7918eee_0 - hdf5=1.10.4=hb1b8bf9_0 - heapdict=1.0.1=pyhd3eb1b0_0 - idna=3.3=pyhd3eb1b0_0 - idna_ssl=1.1.0=py36h06a4308_0 - immutables=0.16=py36h7f8727e_0 - ipython=7.16.1=py36h5ca1d4c_0 - ipython_genutils=0.2.0=pyhd3eb1b0_1 - jedi=0.17.2=py36h06a4308_1 - jinja2=3.0.3=pyhd3eb1b0_0 - jmespath=0.10.0=pyhd3eb1b0_0 - jpeg=9e=h5eee18b_3 - lcms2=2.16=hb9589c4_0 - ld_impl_linux-64=2.40=h12ee557_0 - lerc=4.0.0=h6a678d5_0 - libdeflate=1.22=h5eee18b_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgfortran-ng=7.5.0=ha8ba4b0_17 - libgfortran4=7.5.0=ha8ba4b0_17 - libgomp=11.2.0=h1234567_1 - libopenblas=0.3.18=hf726d26_0 - libpng=1.6.39=h5eee18b_0 - libstdcxx-ng=11.2.0=h1234567_1 - libtiff=4.5.1=hffd6297_1 - libwebp=1.2.4=h11a3e52_1 - libwebp-base=1.2.4=h5eee18b_1 - locket=0.2.1=py36h06a4308_1 - lz4-c=1.9.4=h6a678d5_1 - lzo=2.10=h7b6447c_2 - markupsafe=2.0.1=py36h27cfd23_0 - mock=4.0.3=pyhd3eb1b0_0 - msgpack-python=1.0.2=py36hff7bd54_1 - multidict=5.1.0=py36h27cfd23_2 - ncurses=6.4=h6a678d5_0 - numexpr=2.7.3=py36h4be448d_1 - numpy=1.19.2=py36h6163131_0 - numpy-base=1.19.2=py36h75fe3a5_0 - olefile=0.46=pyhd3eb1b0_0 - openssl=1.1.1w=h7f8727e_0 - packaging=21.3=pyhd3eb1b0_0 - pandas=1.1.5=py36ha9443f7_0 - parso=0.7.0=py_0 - partd=1.2.0=pyhd3eb1b0_1 - pexpect=4.8.0=pyhd3eb1b0_3 - pickleshare=0.7.5=pyhd3eb1b0_1003 - pillow=8.3.1=py36h5aabda8_0 - pip=21.2.2=py36h06a4308_0 - prompt-toolkit=3.0.20=pyhd3eb1b0_0 - psutil=5.8.0=py36h27cfd23_1 - ptyprocess=0.7.0=pyhd3eb1b0_2 - pycparser=2.21=pyhd3eb1b0_0 - pygments=2.11.2=pyhd3eb1b0_0 - pyopenssl=22.0.0=pyhd3eb1b0_0 - pyparsing=3.0.4=pyhd3eb1b0_0 - pysocks=1.7.1=py36h06a4308_0 - pytables=3.6.1=py36h71ec239_0 - python=3.6.13=h12debd9_1 - python-dateutil=2.8.2=pyhd3eb1b0_0 - pytz=2021.3=pyhd3eb1b0_0 - pyyaml=5.4.1=py36h27cfd23_1 - readline=8.2=h5eee18b_0 - s3fs=2022.1.0=pyhd3eb1b0_0 - scipy=1.5.2=py36habc2bb6_0 - setuptools=58.0.4=py36h06a4308_0 - six=1.16.0=pyhd3eb1b0_1 - sortedcontainers=2.4.0=pyhd3eb1b0_0 - sqlite=3.45.3=h5eee18b_0 - tblib=1.7.0=pyhd3eb1b0_0 - tk=8.6.14=h39e8969_0 - toolz=0.11.2=pyhd3eb1b0_0 - tornado=6.1=py36h27cfd23_0 - traitlets=4.3.3=py36h06a4308_0 - typing-extensions=4.1.1=hd3eb1b0_0 - typing_extensions=4.1.1=pyh06a4308_0 - urllib3=1.26.8=pyhd3eb1b0_0 - wcwidth=0.2.5=pyhd3eb1b0_0 - wheel=0.37.1=pyhd3eb1b0_0 - wrapt=1.12.1=py36h7b6447c_1 - xz=5.6.4=h5eee18b_1 - yaml=0.2.5=h7b6447c_0 - yarl=1.6.3=py36h27cfd23_0 - zict=2.0.0=pyhd3eb1b0_0 - zlib=1.2.13=h5eee18b_1 - zstd=1.5.6=hc292b87_0 - pip: - importlib-metadata==4.8.3 - iniconfig==1.1.1 - pluggy==1.0.0 - py==1.11.0 - pytest==7.0.1 - tomli==1.2.3 - zipp==3.6.0 prefix: /opt/conda/envs/dask
[ "dask/array/tests/test_reductions.py::test_arg_reductions[_nanargmin-nanargmin]", "dask/array/tests/test_reductions.py::test_arg_reductions[_nanargmax-nanargmax]", "dask/array/tests/test_reductions.py::test_nanarg_reductions[_nanargmin-nanargmin]", "dask/array/tests/test_reductions.py::test_nanarg_reductions[_nanargmax-nanargmax]", "dask/array/tests/test_reductions.py::test_reductions_2D_nans" ]
[ "dask/array/tests/test_reductions.py::test_reductions_2D[f4]", "dask/array/tests/test_reductions.py::test_reductions_2D[i4]" ]
[ "dask/array/tests/test_reductions.py::test_reductions_1D[f4]", "dask/array/tests/test_reductions.py::test_reductions_1D[i4]", "dask/array/tests/test_reductions.py::test_arg_reductions[argmin-argmin]", "dask/array/tests/test_reductions.py::test_arg_reductions[argmax-argmax]", "dask/array/tests/test_reductions.py::test_moment", "dask/array/tests/test_reductions.py::test_reductions_with_negative_axes", "dask/array/tests/test_reductions.py::test_nan", "dask/array/tests/test_reductions.py::test_0d_array", "dask/array/tests/test_reductions.py::test_reduction_on_scalar", "dask/array/tests/test_reductions.py::test_tree_reduce_depth", "dask/array/tests/test_reductions.py::test_tree_reduce_set_options" ]
[]
BSD 3-Clause "New" or "Revised" License
461
684
[ "dask/array/reductions.py" ]
MITLibraries__slingshot-11
755a842371e63a1c70fde8568523b9b5db0d304e
2016-03-07 17:04:21
755a842371e63a1c70fde8568523b9b5db0d304e
diff --git a/slingshot/cli.py b/slingshot/cli.py index 55efcf6..047d98e 100644 --- a/slingshot/cli.py +++ b/slingshot/cli.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import +from datetime import datetime import os import shutil @@ -58,4 +59,8 @@ def run(layers, store, url, namespace, username, password): submit(zf, url, auth) except Exception as e: shutil.rmtree(bag, ignore_errors=True) + click.echo("%sZ: %s failed with %r" % + (datetime.utcnow().isoformat(), data_layer, e)) raise e + click.echo("%sZ: %s uploaded" % (datetime.utcnow().isoformat(), + data_layer))
Add logging
MITLibraries/slingshot
diff --git a/tests/test_cli.py b/tests/test_cli.py index 1aff724..61eca94 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -59,3 +59,21 @@ def test_run_uses_authentication(runner, layers_dir): '--username', 'foo', '--password', 'bar']) assert m.request_history[0].headers['Authorization'] == \ 'Basic Zm9vOmJhcg==' + + +def test_run_logs_uploaded_layers_to_stdout(runner, layers_dir): + with requests_mock.Mocker() as m: + store = tempfile.mkdtemp() + m.post('http://localhost') + res = runner.invoke(main, ['run', layers_dir, store, + 'http://localhost']) + assert 'SDE_DATA_BD_A8GNS_2003.zip uploaded' in res.output + + +def test_run_logs_failed_layers_to_stdout(runner, layers_dir): + with requests_mock.Mocker() as m: + store = tempfile.mkdtemp() + m.post('http://localhost', status_code=500) + res = runner.invoke(main, ['run', layers_dir, store, + 'http://localhost']) + assert 'SDE_DATA_BD_A8GNS_2003.zip failed' in res.output
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 1 }, "num_modified_files": 1 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "mock", "requests_mock" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
bagit==1.5.4 certifi==2025.1.31 charset-normalizer==3.4.1 click==6.3 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 requests==2.32.3 requests-mock==1.12.1 -e git+https://github.com/MITLibraries/slingshot.git@755a842371e63a1c70fde8568523b9b5db0d304e#egg=slingshot tomli==2.2.1 urllib3==2.3.0
name: slingshot channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - bagit==1.5.4 - certifi==2025.1.31 - charset-normalizer==3.4.1 - click==6.3 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - requests==2.32.3 - requests-mock==1.12.1 - tomli==2.2.1 - urllib3==2.3.0 - wheel==0.26.0 prefix: /opt/conda/envs/slingshot
[ "tests/test_cli.py::test_run_logs_uploaded_layers_to_stdout", "tests/test_cli.py::test_run_logs_failed_layers_to_stdout" ]
[]
[ "tests/test_cli.py::test_run_submits_bags", "tests/test_cli.py::test_run_leaves_bag_on_success", "tests/test_cli.py::test_run_removes_bag_on_failure", "tests/test_cli.py::test_run_uses_supplied_namespace", "tests/test_cli.py::test_run_uses_authentication" ]
[]
Apache License 2.0
464
203
[ "slingshot/cli.py" ]
BrandonLMorris__auacm-cli-11
5c13a4843e281aa1470d2bd28fe39c07f4e39e92
2016-03-11 15:15:59
5c13a4843e281aa1470d2bd28fe39c07f4e39e92
diff --git a/src/auacm/competition.py b/src/auacm/competition.py index f2d9561..794f8a4 100644 --- a/src/auacm/competition.py +++ b/src/auacm/competition.py @@ -1,6 +1,6 @@ """Subcommands related to competitions""" -import auacm, requests, textwrap +import auacm, requests, textwrap, argparse from datetime import datetime from auacm.utils import subcommand from auacm.exceptions import CompetitionNotFoundError @@ -10,7 +10,7 @@ from auacm.exceptions import CompetitionNotFoundError def get_comps(args=None): """Retrieve one or more competitions from the server""" if args: - return _get_one_comp(args) + return get_one_comp(args) response = requests.get(auacm.BASE_URL + 'competitions') @@ -35,13 +35,30 @@ def get_comps(args=None): {} ''').format(current, upcoming, past).strip() -def _get_one_comp(args): +def get_one_comp(args): """Retrieve info on one specific competition""" - response = requests.get(auacm.BASE_URL + 'competitions/' + str(args[0])) + parser = argparse.ArgumentParser( + add_help=False, + usage='competition [-i/--id] <competition>' + ) + parser.add_argument('-i', '--id', action='store_true') + parser.add_argument('competition') + args = parser.parse_args(args) + + if not args.id: + cid = _cid_from_name(args.competition) + if cid == -1: + raise CompetitionNotFoundError( + 'Could not find a competition with the name ' + + args.competition) + else: + cid = args.competition + + response = requests.get(auacm.BASE_URL + 'competitions/' + str(cid)) if not response.ok or response.status_code == 404: raise CompetitionNotFoundError( - 'Could not find competition with id: ' + str(args[0])) + 'Could not find competition with id: ' + str(args.competition)) comp = response.json()['data'] @@ -62,6 +79,21 @@ def _get_one_comp(args): {} ''').format(comp_str, teams, problems) +def _cid_from_name(comp_name): + """Return the competition of an id based on it's name""" + comps = requests.get(auacm.BASE_URL + 'competitions').json()['data'] + for comp in comps['upcoming']: + if comp_name.lower() in comp['name'].lower(): + return int(comp['cid']) + for comp in comps['ongoing']: + if comp_name.lower() in comp['name'].lower(): + return int(comp['cid']) + for comp in comps['past']: + if comp_name.lower() in comp['name'].lower(): + return int(comp['cid']) + + return -1 + def _format_comps(comps): """Return a formatted string for a list of competitions""" result = list() @@ -85,7 +117,7 @@ def _format_teams(teams): def _format_problems(probs): """Return a formatted string of the problems passed in""" result = '' - for label, prob in probs.items(): + for label, prob in sorted(probs.items()): result += '{}\t{} ({})\n'.format(label, prob['name'], prob['pid']) return result.strip() diff --git a/src/auacm/main.py b/src/auacm/main.py index 32d55e0..35e463b 100644 --- a/src/auacm/main.py +++ b/src/auacm/main.py @@ -7,7 +7,7 @@ The central entry point of the auacm app. import requests, sys, textwrap import auacm import auacm.utils as utils -from auacm.exceptions import ConnectionError, ProblemNotFoundError, UnauthorizedException, InvalidSubmission +from auacm.exceptions import ConnectionError, ProblemNotFoundError, UnauthorizedException, InvalidSubmission, CompetitionNotFoundError def main(args): """ @@ -44,7 +44,8 @@ def main(args): print(utils.callbacks[args[0]](args[1:]) or '') except (ProblemNotFoundError, UnauthorizedException, - InvalidSubmission) as exp: + InvalidSubmission, + CompetitionNotFoundError) as exp: print(exp.message) exit(1) except (requests.exceptions.ConnectionError, ConnectionError):
List recent and ongoing competitions A `comp[etition]` command that will simply list (chronologically) the recent and ongoing competitions.
BrandonLMorris/auacm-cli
diff --git a/tests/competition_tests.py b/tests/competition_tests.py index 7f7c381..b89e62e 100644 --- a/tests/competition_tests.py +++ b/tests/competition_tests.py @@ -21,16 +21,38 @@ class CompetitionTests(unittest.TestCase): self.assertTrue('past fake mock' in result.lower()) @patch('requests.get') - def testGetOneCompetition(self, mock_get): - """Successfully get one competition by it's id""" + def testGetOneCompetitionById(self, mock_get): + """Successfully get one competition by its id""" mock_get.return_value = MockResponse(json=COMPETITION_DETAIL) - result = auacm.competition.get_comps(['2']) + result = auacm.competition.get_comps(['-i', '2']) self.assertTrue('ongoing fake mock' in result.lower()) self.assertTrue('fake problem a' in result.lower()) self.assertTrue('brando the mando' in result.lower()) + @patch('requests.get') + def testGetOneCompetitionByName(self, mock_get): + """Successfully get one competition by its name""" + mock_get.side_effect = [ + MockResponse(json=COMPETITIONS_RESPONSE), + MockResponse(json=COMPETITION_DETAIL)] + + result = auacm.competition.get_comps(['ongoing']) + + self.assertTrue('ongoing fake mock' in result.lower()) + self.assertTrue('fake problem a' in result.lower()) + self.assertTrue('brando the mando' in result.lower()) + + @patch('requests.get') + def testGetOneCompetitionBadName(self, mock_get): + """Attempt to get a competition that doesn't exist by name""" + mock_get.side_effect = [ + MockResponse(json=COMPETITIONS_RESPONSE)] + + self.assertRaises( + auacm.exceptions.CompetitionNotFoundError, + auacm.competition.get_comps, ['not real']) @patch('requests.get') def testGetOneCompetitionBad(self, mock_get): @@ -39,7 +61,7 @@ class CompetitionTests(unittest.TestCase): self.assertRaises( auacm.exceptions.CompetitionNotFoundError, - auacm.competition.get_comps, ['99999999']) + auacm.competition.get_comps, ['-i', '99999999']) if __name__ == '__main__':
{ "commit_name": "head_commit", "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, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 2 }
0.2
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requests", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
-e git+https://github.com/BrandonLMorris/auacm-cli.git@5c13a4843e281aa1470d2bd28fe39c07f4e39e92#egg=auacm Brotli @ file:///croot/brotli-split_1736182456865/work certifi @ file:///croot/certifi_1738623731865/work/certifi charset-normalizer @ file:///croot/charset-normalizer_1721748349566/work exceptiongroup==1.2.2 idna @ file:///croot/idna_1714398848350/work iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 PySocks @ file:///tmp/build/80754af9/pysocks_1605305812635/work pytest==8.3.5 requests @ file:///croot/requests_1730999120400/work tomli==2.2.1 urllib3 @ file:///croot/urllib3_1737133630106/work
name: auacm-cli channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - brotli-python=1.0.9=py39h6a678d5_9 - ca-certificates=2025.2.25=h06a4308_0 - certifi=2025.1.31=py39h06a4308_0 - charset-normalizer=3.3.2=pyhd3eb1b0_0 - idna=3.7=py39h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - pysocks=1.7.1=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - requests=2.32.3=py39h06a4308_1 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - urllib3=2.3.0=py39h06a4308_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/auacm-cli
[ "tests/competition_tests.py::CompetitionTests::testGetOneCompetitionBadName", "tests/competition_tests.py::CompetitionTests::testGetOneCompetitionByName" ]
[]
[ "tests/competition_tests.py::CompetitionTests::testGetAllCompetitons", "tests/competition_tests.py::CompetitionTests::testGetOneCompetitionBad", "tests/competition_tests.py::CompetitionTests::testGetOneCompetitionById" ]
[]
MIT License
471
1,044
[ "src/auacm/competition.py", "src/auacm/main.py" ]
docker__docker-py-988
fa7068cb7cf2ae1efcc2b3b99f24f4c7aa29e989
2016-03-11 20:04:00
4c34be5d4ab8a5a017950712e9c96b56d78d1c58
diff --git a/docker/utils/utils.py b/docker/utils/utils.py index bc26ce82..d4393d58 100644 --- a/docker/utils/utils.py +++ b/docker/utils/utils.py @@ -460,16 +460,16 @@ def kwargs_from_env(ssl_version=None, assert_hostname=None): tls_verify = os.environ.get('DOCKER_TLS_VERIFY') if tls_verify == '': tls_verify = False - enable_tls = True else: tls_verify = tls_verify is not None - enable_tls = cert_path or tls_verify + enable_tls = cert_path or tls_verify params = {} if host: - params['base_url'] = (host.replace('tcp://', 'https://') - if enable_tls else host) + params['base_url'] = ( + host.replace('tcp://', 'https://') if enable_tls else host + ) if not enable_tls: return params
Certificate error in docker ci for test-docker-py https://jenkins.dockerproject.org/job/Docker-PRs/24848/console for detail. in docker-py, when checkout to the commit of 387db11009f4b4f64a4f2c6fd64d3eeb01828585,the error appears,if I remove the commit ,we will not have the error. ``` ==================================== ERRORS ==================================== _________________ ERROR at setup of InformationTest.test_info __________________ /docker-py/tests/integration/conftest.py:17: in setup_test_session c = docker_client() /docker-py/tests/helpers.py:61: in docker_client return docker.Client(**docker_client_kwargs(**kwargs)) /docker-py/tests/helpers.py:65: in docker_client_kwargs client_kwargs = docker.utils.kwargs_from_env(assert_hostname=False) /docker-py/docker/utils/utils.py:486: in kwargs_from_env assert_fingerprint=tls_verify) /docker-py/docker/tls.py:47: in __init__ 'Path to a certificate and key files must be provided' E TLSParameterError: Path to a certificate and key files must be provided through the client_config param. TLS configurations should map the Docker CLI client configurations. See https://docs.docker.com/engine/articles/https/ for API details. ________________ ERROR at setup of InformationTest.test_search _________________ ... ```
docker/docker-py
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py index 87796d11..65b7cf8a 100644 --- a/tests/unit/utils_test.py +++ b/tests/unit/utils_test.py @@ -228,19 +228,7 @@ class KwargsFromEnvTest(base.BaseTestCase): DOCKER_TLS_VERIFY='') os.environ.pop('DOCKER_CERT_PATH', None) kwargs = kwargs_from_env(assert_hostname=True) - self.assertEqual('https://192.168.59.103:2376', kwargs['base_url']) - self.assertTrue('ca.pem' in kwargs['tls'].ca_cert) - self.assertTrue('cert.pem' in kwargs['tls'].cert[0]) - self.assertTrue('key.pem' in kwargs['tls'].cert[1]) - self.assertEqual(True, kwargs['tls'].assert_hostname) - self.assertEqual(False, kwargs['tls'].verify) - try: - client = Client(**kwargs) - self.assertEqual(kwargs['base_url'], client.base_url) - self.assertEqual(kwargs['tls'].cert, client.cert) - self.assertFalse(kwargs['tls'].verify) - except TypeError as e: - self.fail(e) + self.assertEqual('tcp://192.168.59.103:2376', kwargs['base_url']) def test_kwargs_from_env_no_cert_path(self): try:
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.7", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi -e git+https://github.com/docker/docker-py.git@fa7068cb7cf2ae1efcc2b3b99f24f4c7aa29e989#egg=docker_py exceptiongroup==1.2.2 importlib-metadata==6.7.0 iniconfig==2.0.0 packaging==24.0 pluggy==1.2.0 pytest==7.4.4 requests==2.5.3 six==1.17.0 tomli==2.0.1 typing_extensions==4.7.1 websocket-client==0.32.0 zipp==3.15.0
name: docker-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2022.12.7=py37h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=22.3.1=py37h06a4308_0 - python=3.7.16=h7a1cb2a_0 - readline=8.2=h5eee18b_0 - setuptools=65.6.3=py37h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.38.4=py37h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - exceptiongroup==1.2.2 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - requests==2.5.3 - six==1.17.0 - tomli==2.0.1 - typing-extensions==4.7.1 - websocket-client==0.32.0 - zipp==3.15.0 prefix: /opt/conda/envs/docker-py
[ "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false_no_cert" ]
[ "tests/unit/utils_test.py::SSLAdapterTest::test_only_uses_tls" ]
[ "tests/unit/utils_test.py::HostConfigTest::test_create_endpoint_config_with_aliases", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_invalid_cpu_cfs_types", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_no_options_newer_api_version", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_period", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_cpu_quota", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_oom_kill_disable", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size", "tests/unit/utils_test.py::HostConfigTest::test_create_host_config_with_shm_size_in_mb", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_dict_ulimit_capitals", "tests/unit/utils_test.py::UlimitTest::test_create_host_config_obj_ulimit", "tests/unit/utils_test.py::UlimitTest::test_ulimit_invalid_type", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_dict_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_create_host_config_obj_logconfig", "tests/unit/utils_test.py::LogConfigTest::test_logconfig_invalid_config_type", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_empty", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_no_cert_path", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls", "tests/unit/utils_test.py::KwargsFromEnvTest::test_kwargs_from_env_tls_verify_false", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_compact", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_complete", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_empty", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_list", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_no_mode", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_bytes_input", "tests/unit/utils_test.py::ConverVolumeBindsTest::test_convert_volume_binds_unicode_unicode_input", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_commented_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_invalid_line", "tests/unit/utils_test.py::ParseEnvFileTest::test_parse_env_file_proper", "tests/unit/utils_test.py::ParseHostTest::test_parse_host", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_empty_value", "tests/unit/utils_test.py::ParseHostTest::test_parse_host_tls", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_index_user_image_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_no_tag", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_sha", "tests/unit/utils_test.py::ParseRepositoryTagTest::test_private_reg_image_tag", "tests/unit/utils_test.py::ParseDeviceTest::test_dict", "tests/unit/utils_test.py::ParseDeviceTest::test_full_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_hybrid_list", "tests/unit/utils_test.py::ParseDeviceTest::test_partial_string_definition", "tests/unit/utils_test.py::ParseDeviceTest::test_permissionless_string_definition", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_float", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_invalid", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_maxint", "tests/unit/utils_test.py::ParseBytesTest::test_parse_bytes_valid", "tests/unit/utils_test.py::UtilsTest::test_convert_filters", "tests/unit/utils_test.py::UtilsTest::test_create_ipam_config", "tests/unit/utils_test.py::UtilsTest::test_decode_json_header", "tests/unit/utils_test.py::SplitCommandTest::test_split_command_with_unicode", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_matching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_port_ranges", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_nonmatching_internal_ports", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_one_port", "tests/unit/utils_test.py::PortsTest::test_build_port_bindings_with_port_range", "tests/unit/utils_test.py::PortsTest::test_host_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_non_matching_length_port_ranges", "tests/unit/utils_test.py::PortsTest::test_port_and_range_invalid", "tests/unit/utils_test.py::PortsTest::test_port_only_with_colon", "tests/unit/utils_test.py::PortsTest::test_split_port_invalid", "tests/unit/utils_test.py::PortsTest::test_split_port_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_no_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_range_with_protocol", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_ip_no_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_host_port", "tests/unit/utils_test.py::PortsTest::test_split_port_with_protocol", "tests/unit/utils_test.py::ExcludePathsTest::test_directory", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_single_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_subdir_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_directory_with_wildcard_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_custom_dockerfile", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_child", "tests/unit/utils_test.py::ExcludePathsTest::test_exclude_dockerfile_dockerignore", "tests/unit/utils_test.py::ExcludePathsTest::test_no_dupes", "tests/unit/utils_test.py::ExcludePathsTest::test_no_excludes", "tests/unit/utils_test.py::ExcludePathsTest::test_question_mark", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_filename_trailing_slash", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_single_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_subdirectory", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_exclude", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_end", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_filename_start", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_single_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_subdir_wildcard_filename", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_exception", "tests/unit/utils_test.py::ExcludePathsTest::test_wildcard_with_wildcard_exception", "tests/unit/utils_test.py::TarTest::test_tar_with_directory_symlinks", "tests/unit/utils_test.py::TarTest::test_tar_with_empty_directory", "tests/unit/utils_test.py::TarTest::test_tar_with_excludes", "tests/unit/utils_test.py::TarTest::test_tar_with_file_symlinks" ]
[]
Apache License 2.0
472
224
[ "docker/utils/utils.py" ]
dpkp__kafka-python-611
d81963a919fa8161c94b5bef5e6de0697b91c4a6
2016-03-23 17:29:58
810f08b7996a15e65cdd8af6c1a7167c28f94646
coveralls: [![Coverage Status](https://coveralls.io/builds/5522917/badge)](https://coveralls.io/builds/5522917) Changes Unknown when pulling **bb2548705a3be822be9e17ea6eb824061fc9fb8f on sock_send_bytes** into ** on master**. coveralls: [![Coverage Status](https://coveralls.io/builds/5664292/badge)](https://coveralls.io/builds/5664292) Changes Unknown when pulling **7af174fe0a6bcc5962a8c8008d66e0b3b05e5fc2 on sock_send_bytes** into ** on master**.
diff --git a/kafka/conn.py b/kafka/conn.py index 2b82b6d..ffc839e 100644 --- a/kafka/conn.py +++ b/kafka/conn.py @@ -188,10 +188,12 @@ class BrokerConnection(object): # and send bytes asynchronously. For now, just block # sending each request payload self._sock.setblocking(True) - sent_bytes = self._sock.send(size) - assert sent_bytes == len(size) - sent_bytes = self._sock.send(message) - assert sent_bytes == len(message) + for data in (size, message): + total_sent = 0 + while total_sent < len(data): + sent_bytes = self._sock.send(data[total_sent:]) + total_sent += sent_bytes + assert total_sent == len(data) self._sock.setblocking(False) except (AssertionError, ConnectionError) as e: log.exception("Error sending %s to %s", request, self) diff --git a/kafka/future.py b/kafka/future.py index 06b8c3a..c7e0b14 100644 --- a/kafka/future.py +++ b/kafka/future.py @@ -15,10 +15,10 @@ class Future(object): self._errbacks = [] def succeeded(self): - return self.is_done and not self.exception + return self.is_done and not bool(self.exception) def failed(self): - return self.is_done and self.exception + return self.is_done and bool(self.exception) def retriable(self): try:
kafka.common.ConnectionError on big messages + gevent i'm getting kafka.common.ConnectionError trying to send big message. Code below ```python from gevent.monkey import patch_all; patch_all() from kafka import KafkaProducer producer = KafkaProducer(bootstrap_servers=xxxxxxxx, buffer_memory=10 * 1024 * 1024, max_request_size=10 * 1024 * 1024,) producer.send('test', 'a' * 1024 * 1024 * 3, ).get(timeout=60) producer.flush() ``` causing this ``` 2016-03-23 11:50:58,147 - kafka.conn - ERROR - Error sending ProduceRequest(required_acks=1, timeout=30000, topics=[(topic='test2', partitions=[(1, <_io.BytesIO object at 0x7fe64edc2950>)])]) to <BrokerConnection host=127.0.0.1 port=9093> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/kafka/conn.py", line 187, in send assert sent_bytes == len(message) AssertionError 2016-03-23 11:50:58,150 - kafka.producer.sender - DEBUG - Error sending produce request to node 2: 2016-03-23 11:50:58,150 - kafka.producer.record_accumulator - DEBUG - Produced messages to topic-partition TopicPartition(topic='test2', partition=1) with base offset -1 and error . 2016-03-23 11:50:58,150 - kafka.client - DEBUG - Initializing connection to node 2 for metadata request Traceback (most recent call last): File "test_producer.py", line 15, in <module> producer.send('test2', 'a' * 1024 * 1024 * 3, ).get(timeout=60) File "/usr/local/lib/python2.7/dist-packages/kafka/producer/future.py", line 50, in get raise self.exception # pylint: disable-msg=raising-bad-type kafka.common.ConnectionError ``` this works well if i comment out **patch_all()** line Fixing kafka.conn.BrokerConnection.send() method solved it, but i'm not sure about side effects. ```python def send() ..... ..... size = Int32.encode(len(message)) try: self._sock.setblocking(True) sent_bytes = self._sock.send(size) assert sent_bytes == len(size) total_sent = 0 while total_sent < len(message): # sending in loop sent_bytes = self._sock.send(message[total_sent:]) assert sent_bytes total_sent += sent_bytes self._sock.setblocking(False) except (AssertionError, ConnectionError) as e: log.exception("Error sending %s to %s", request, self) .... ``` Any chances to have similar fix in master branch?
dpkp/kafka-python
diff --git a/test/test_conn.py b/test/test_conn.py index d394f74..5432ebd 100644 --- a/test/test_conn.py +++ b/test/test_conn.py @@ -2,12 +2,15 @@ from __future__ import absolute_import from errno import EALREADY, EINPROGRESS, EISCONN, ECONNRESET -import socket import time import pytest from kafka.conn import BrokerConnection, ConnectionStates +from kafka.protocol.api import RequestHeader +from kafka.protocol.metadata import MetadataRequest + +import kafka.common as Errors @pytest.fixture @@ -20,6 +23,7 @@ def socket(mocker): @pytest.fixture def conn(socket): + from socket import AF_INET conn = BrokerConnection('localhost', 9092, socket.AF_INET) return conn @@ -61,22 +65,111 @@ def test_connect_timeout(socket, conn): def test_blacked_out(conn): - assert not conn.blacked_out() + assert conn.blacked_out() is False conn.last_attempt = time.time() - assert conn.blacked_out() + assert conn.blacked_out() is True def test_connected(conn): - assert not conn.connected() + assert conn.connected() is False conn.state = ConnectionStates.CONNECTED - assert conn.connected() + assert conn.connected() is True def test_connecting(conn): - assert not conn.connecting() + assert conn.connecting() is False + conn.state = ConnectionStates.CONNECTING + assert conn.connecting() is True + conn.state = ConnectionStates.CONNECTED + assert conn.connecting() is False + + +def test_send_disconnected(conn): + conn.state = ConnectionStates.DISCONNECTED + f = conn.send('foobar') + assert f.failed() is True + assert isinstance(f.exception, Errors.ConnectionError) + + +def test_send_connecting(conn): conn.state = ConnectionStates.CONNECTING - assert conn.connecting() + f = conn.send('foobar') + assert f.failed() is True + assert isinstance(f.exception, Errors.NodeNotReadyError) + + +def test_send_max_ifr(conn): conn.state = ConnectionStates.CONNECTED - assert not conn.connecting() + max_ifrs = conn.config['max_in_flight_requests_per_connection'] + for _ in range(max_ifrs): + conn.in_flight_requests.append('foo') + f = conn.send('foobar') + assert f.failed() is True + assert isinstance(f.exception, Errors.TooManyInFlightRequests) + + +def test_send_no_response(socket, conn): + conn.connect() + assert conn.state is ConnectionStates.CONNECTED + req = MetadataRequest([]) + header = RequestHeader(req, client_id=conn.config['client_id']) + payload_bytes = len(header.encode()) + len(req.encode()) + third = payload_bytes // 3 + remainder = payload_bytes % 3 + socket.send.side_effect = [4, third, third, third, remainder] + + assert len(conn.in_flight_requests) == 0 + f = conn.send(req, expect_response=False) + assert f.succeeded() is True + assert f.value is None + assert len(conn.in_flight_requests) == 0 + + +def test_send_response(socket, conn): + conn.connect() + assert conn.state is ConnectionStates.CONNECTED + req = MetadataRequest([]) + header = RequestHeader(req, client_id=conn.config['client_id']) + payload_bytes = len(header.encode()) + len(req.encode()) + third = payload_bytes // 3 + remainder = payload_bytes % 3 + socket.send.side_effect = [4, third, third, third, remainder] + + assert len(conn.in_flight_requests) == 0 + f = conn.send(req) + assert f.is_done is False + assert len(conn.in_flight_requests) == 1 + + +def test_send_error(socket, conn): + conn.connect() + assert conn.state is ConnectionStates.CONNECTED + req = MetadataRequest([]) + header = RequestHeader(req, client_id=conn.config['client_id']) + try: + error = ConnectionError + except NameError: + from socket import error + socket.send.side_effect = error + f = conn.send(req) + assert f.failed() is True + assert isinstance(f.exception, Errors.ConnectionError) + assert socket.close.call_count == 1 + assert conn.state is ConnectionStates.DISCONNECTED + + +def test_can_send_more(conn): + assert conn.can_send_more() is True + max_ifrs = conn.config['max_in_flight_requests_per_connection'] + for _ in range(max_ifrs): + assert conn.can_send_more() is True + conn.in_flight_requests.append('foo') + assert conn.can_send_more() is False + + +def test_recv(socket, conn): + pass # TODO + -# TODO: test_send, test_recv, test_can_send_more, test_close +def test_close(conn): + pass # TODO
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-catchlog", "pytest-pylint", "pytest-sugar", "pytest-mock", "mock", "python-snappy", "lz4tools", "xxhash" ], "pre_install": [ "apt-get update", "apt-get install -y libsnappy-dev" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==2.11.7 attrs==22.2.0 certifi==2021.5.30 coverage==6.2 cramjam==2.5.0 dill==0.3.4 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 -e git+https://github.com/dpkp/kafka-python.git@d81963a919fa8161c94b5bef5e6de0697b91c4a6#egg=kafka_python lazy-object-proxy==1.7.1 lz4tools==1.3.1.2 mccabe==0.7.0 mock==5.2.0 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pylint==2.13.9 pyparsing==3.1.4 pytest==7.0.1 pytest-catchlog==1.2.2 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-pylint==0.18.0 pytest-sugar==0.9.6 python-snappy==0.7.3 six==1.17.0 termcolor==1.1.0 toml==0.10.2 tomli==1.2.3 typed-ast==1.5.5 typing_extensions==4.1.1 wrapt==1.16.0 xxhash==3.2.0 zipp==3.6.0
name: kafka-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==2.11.7 - attrs==22.2.0 - coverage==6.2 - cramjam==2.5.0 - dill==0.3.4 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - lz4tools==1.3.1.2 - mccabe==0.7.0 - mock==5.2.0 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pylint==2.13.9 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-catchlog==1.2.2 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-pylint==0.18.0 - pytest-sugar==0.9.6 - python-snappy==0.7.3 - six==1.17.0 - termcolor==1.1.0 - toml==0.10.2 - tomli==1.2.3 - typed-ast==1.5.5 - typing-extensions==4.1.1 - wrapt==1.16.0 - xxhash==3.2.0 - zipp==3.6.0 prefix: /opt/conda/envs/kafka-python
[ "test/test_conn.py::test_send_disconnected", "test/test_conn.py::test_send_connecting", "test/test_conn.py::test_send_max_ifr", "test/test_conn.py::test_send_no_response", "test/test_conn.py::test_send_response", "test/test_conn.py::test_send_error" ]
[]
[ "test/test_conn.py::test_connect[states0]", "test/test_conn.py::test_connect[states1]", "test/test_conn.py::test_connect[states2]", "test/test_conn.py::test_connect[states3]", "test/test_conn.py::test_connect[states4]", "test/test_conn.py::test_connect_timeout", "test/test_conn.py::test_blacked_out", "test/test_conn.py::test_connected", "test/test_conn.py::test_connecting", "test/test_conn.py::test_can_send_more", "test/test_conn.py::test_recv", "test/test_conn.py::test_close" ]
[]
Apache License 2.0
485
386
[ "kafka/conn.py", "kafka/future.py" ]
dpkp__kafka-python-620
b96f4ccf070109a022deb98b569e61d23e4e75b9
2016-04-03 16:29:40
810f08b7996a15e65cdd8af6c1a7167c28f94646
diff --git a/kafka/coordinator/consumer.py b/kafka/coordinator/consumer.py index a5e3067..b2ef1ea 100644 --- a/kafka/coordinator/consumer.py +++ b/kafka/coordinator/consumer.py @@ -91,8 +91,10 @@ class ConsumerCoordinator(BaseCoordinator): log.warning('Broker version (%s) does not support offset' ' commits; disabling auto-commit.', self.config['api_version']) + self.config['enable_auto_commit'] = False elif self.config['group_id'] is None: log.warning('group_id is None: disabling auto-commit.') + self.config['enable_auto_commit'] = False else: interval = self.config['auto_commit_interval_ms'] / 1000.0 self._auto_commit_task = AutoCommitTask(weakref.proxy(self), interval) @@ -192,7 +194,7 @@ class ConsumerCoordinator(BaseCoordinator): assignor.on_assignment(assignment) # restart the autocommit task if needed - if self.config['enable_auto_commit']: + if self._auto_commit_task: self._auto_commit_task.enable() assigned = set(self._subscription.assigned_partitions()) @@ -364,27 +366,27 @@ class ConsumerCoordinator(BaseCoordinator): time.sleep(self.config['retry_backoff_ms'] / 1000.0) def _maybe_auto_commit_offsets_sync(self): - if self.config['api_version'] < (0, 8, 1): + if self._auto_commit_task is None: return - if self.config['enable_auto_commit']: - # disable periodic commits prior to committing synchronously. note that they will - # be re-enabled after a rebalance completes - self._auto_commit_task.disable() - try: - self.commit_offsets_sync(self._subscription.all_consumed_offsets()) - - # The three main group membership errors are known and should not - # require a stacktrace -- just a warning - except (Errors.UnknownMemberIdError, - Errors.IllegalGenerationError, - Errors.RebalanceInProgressError): - log.warning("Offset commit failed: group membership out of date" - " This is likely to cause duplicate message" - " delivery.") - except Exception: - log.exception("Offset commit failed: This is likely to cause" - " duplicate message delivery") + # disable periodic commits prior to committing synchronously. note that they will + # be re-enabled after a rebalance completes + self._auto_commit_task.disable() + + try: + self.commit_offsets_sync(self._subscription.all_consumed_offsets()) + + # The three main group membership errors are known and should not + # require a stacktrace -- just a warning + except (Errors.UnknownMemberIdError, + Errors.IllegalGenerationError, + Errors.RebalanceInProgressError): + log.warning("Offset commit failed: group membership out of date" + " This is likely to cause duplicate message" + " delivery.") + except Exception: + log.exception("Offset commit failed: This is likely to cause" + " duplicate message delivery") def _send_offset_commit_request(self, offsets): """Commit offsets for the specified list of topics and partitions.
Consumer exception on close when group id is None Following the conversation in #601, setting the `group_id` to `None` in a Consumer causes an exception to be raised when the consumer is closed. ``` >>> from kafka import KafkaConsumer >>> k = KafkaConsumer('example', bootstrap_servers=['server'], group_id=None) >>> k.close() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/madisonb/.local/share/virtualenvs/scrapy-cluster/lib/python2.7/site-packages/kafka/consumer/group.py", line 257, in close self._coordinator.close() File "/Users/madisonb/.local/share/virtualenvs/scrapy-cluster/lib/python2.7/site-packages/kafka/coordinator/consumer.py", line 306, in close self._maybe_auto_commit_offsets_sync() File "/Users/madisonb/.local/share/virtualenvs/scrapy-cluster/lib/python2.7/site-packages/kafka/coordinator/consumer.py", line 372, in _maybe_auto_commit_offsets_sync self._auto_commit_task.disable() AttributeError: 'NoneType' object has no attribute 'disable' >>> k = KafkaConsumer('example', bootstrap_servers=['server'], group_id='stuff') >>> k.close() >>> ```
dpkp/kafka-python
diff --git a/test/test_coordinator.py b/test/test_coordinator.py index 847cbc1..44db808 100644 --- a/test/test_coordinator.py +++ b/test/test_coordinator.py @@ -52,12 +52,16 @@ def test_init(conn): @pytest.mark.parametrize("api_version", [(0, 8, 0), (0, 8, 1), (0, 8, 2), (0, 9)]) def test_autocommit_enable_api_version(conn, api_version): - coordinator = ConsumerCoordinator( - KafkaClient(), SubscriptionState(), api_version=api_version) + coordinator = ConsumerCoordinator(KafkaClient(), SubscriptionState(), + enable_auto_commit=True, + group_id='foobar', + api_version=api_version) if api_version < (0, 8, 1): assert coordinator._auto_commit_task is None + assert coordinator.config['enable_auto_commit'] is False else: assert coordinator._auto_commit_task is not None + assert coordinator.config['enable_auto_commit'] is True def test_protocol_type(coordinator): @@ -349,28 +353,40 @@ def test_commit_offsets_sync(mocker, coordinator, offsets): @pytest.mark.parametrize( - 'api_version,enable,error,task_disable,commit_offsets,warn,exc', [ - ((0, 8), True, None, False, False, False, False), - ((0, 9), False, None, False, False, False, False), - ((0, 9), True, Errors.UnknownMemberIdError(), True, True, True, False), - ((0, 9), True, Errors.IllegalGenerationError(), True, True, True, False), - ((0, 9), True, Errors.RebalanceInProgressError(), True, True, True, False), - ((0, 9), True, Exception(), True, True, False, True), - ((0, 9), True, None, True, True, False, False), + 'api_version,group_id,enable,error,has_auto_commit,commit_offsets,warn,exc', [ + ((0, 8), 'foobar', True, None, False, False, True, False), + ((0, 9), 'foobar', False, None, False, False, False, False), + ((0, 9), 'foobar', True, Errors.UnknownMemberIdError(), True, True, True, False), + ((0, 9), 'foobar', True, Errors.IllegalGenerationError(), True, True, True, False), + ((0, 9), 'foobar', True, Errors.RebalanceInProgressError(), True, True, True, False), + ((0, 9), 'foobar', True, Exception(), True, True, False, True), + ((0, 9), 'foobar', True, None, True, True, False, False), + ((0, 9), None, True, None, False, False, True, False), ]) -def test_maybe_auto_commit_offsets_sync(mocker, coordinator, - api_version, enable, error, task_disable, - commit_offsets, warn, exc): - auto_commit_task = mocker.patch.object(coordinator, '_auto_commit_task') - commit_sync = mocker.patch.object(coordinator, 'commit_offsets_sync', - side_effect=error) +def test_maybe_auto_commit_offsets_sync(mocker, api_version, group_id, enable, + error, has_auto_commit, commit_offsets, + warn, exc): mock_warn = mocker.patch('kafka.coordinator.consumer.log.warning') mock_exc = mocker.patch('kafka.coordinator.consumer.log.exception') + coordinator = ConsumerCoordinator(KafkaClient(), SubscriptionState(), + api_version=api_version, + enable_auto_commit=enable, + group_id=group_id) + commit_sync = mocker.patch.object(coordinator, 'commit_offsets_sync', + side_effect=error) + if has_auto_commit: + assert coordinator._auto_commit_task is not None + coordinator._auto_commit_task.enable() + assert coordinator._auto_commit_task._enabled is True + else: + assert coordinator._auto_commit_task is None - coordinator.config['api_version'] = api_version - coordinator.config['enable_auto_commit'] = enable assert coordinator._maybe_auto_commit_offsets_sync() is None - assert auto_commit_task.disable.call_count == (1 if task_disable else 0) + + if has_auto_commit: + assert coordinator._auto_commit_task is not None + assert coordinator._auto_commit_task._enabled is False + assert commit_sync.call_count == (1 if commit_offsets else 0) assert mock_warn.call_count == (1 if warn else 0) assert mock_exc.call_count == (1 if exc else 0)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_issue_reference" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 1 }
1.0
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "pytest-catchlog", "pytest-pylint", "pytest-sugar", "pytest-mock", "mock", "python-snappy", "lz4tools", "xxhash" ], "pre_install": [ "apt-get update", "apt-get install -y libsnappy-dev" ], "python": "3.5", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==2.11.7 attrs==22.2.0 certifi==2021.5.30 coverage==6.2 cramjam==2.5.0 dill==0.3.4 importlib-metadata==4.8.3 iniconfig==1.1.1 isort==5.10.1 -e git+https://github.com/dpkp/kafka-python.git@b96f4ccf070109a022deb98b569e61d23e4e75b9#egg=kafka_python lazy-object-proxy==1.7.1 lz4tools==1.3.1.2 mccabe==0.7.0 mock==5.2.0 packaging==21.3 platformdirs==2.4.0 pluggy==1.0.0 py==1.11.0 pylint==2.13.9 pyparsing==3.1.4 pytest==7.0.1 pytest-catchlog==1.2.2 pytest-cov==4.0.0 pytest-mock==3.6.1 pytest-pylint==0.18.0 pytest-sugar==0.9.6 python-snappy==0.7.3 six==1.17.0 termcolor==1.1.0 toml==0.10.2 tomli==1.2.3 typed-ast==1.5.5 typing_extensions==4.1.1 wrapt==1.16.0 xxhash==3.2.0 zipp==3.6.0
name: kafka-python channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==2.11.7 - attrs==22.2.0 - coverage==6.2 - cramjam==2.5.0 - dill==0.3.4 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - isort==5.10.1 - lazy-object-proxy==1.7.1 - lz4tools==1.3.1.2 - mccabe==0.7.0 - mock==5.2.0 - packaging==21.3 - platformdirs==2.4.0 - pluggy==1.0.0 - py==1.11.0 - pylint==2.13.9 - pyparsing==3.1.4 - pytest==7.0.1 - pytest-catchlog==1.2.2 - pytest-cov==4.0.0 - pytest-mock==3.6.1 - pytest-pylint==0.18.0 - pytest-sugar==0.9.6 - python-snappy==0.7.3 - six==1.17.0 - termcolor==1.1.0 - toml==0.10.2 - tomli==1.2.3 - typed-ast==1.5.5 - typing-extensions==4.1.1 - wrapt==1.16.0 - xxhash==3.2.0 - zipp==3.6.0 prefix: /opt/conda/envs/kafka-python
[ "test/test_coordinator.py::test_autocommit_enable_api_version[api_version0]", "test/test_coordinator.py::test_maybe_auto_commit_offsets_sync[api_version7-None-True-None-False-False-True-False]" ]
[ "test/test_coordinator.py::test_handle_offset_commit_response[response10-InvalidTopicError-False-False]" ]
[ "test/test_coordinator.py::test_init", "test/test_coordinator.py::test_autocommit_enable_api_version[api_version1]", "test/test_coordinator.py::test_autocommit_enable_api_version[api_version2]", "test/test_coordinator.py::test_autocommit_enable_api_version[api_version3]", "test/test_coordinator.py::test_protocol_type", "test/test_coordinator.py::test_group_protocols", "test/test_coordinator.py::test_pattern_subscription[api_version0]", "test/test_coordinator.py::test_pattern_subscription[api_version1]", "test/test_coordinator.py::test_pattern_subscription[api_version2]", "test/test_coordinator.py::test_pattern_subscription[api_version3]", "test/test_coordinator.py::test_lookup_assignor", "test/test_coordinator.py::test_join_complete", "test/test_coordinator.py::test_subscription_listener", "test/test_coordinator.py::test_subscription_listener_failure", "test/test_coordinator.py::test_perform_assignment", "test/test_coordinator.py::test_on_join_prepare", "test/test_coordinator.py::test_need_rejoin", "test/test_coordinator.py::test_refresh_committed_offsets_if_needed", "test/test_coordinator.py::test_fetch_committed_offsets", "test/test_coordinator.py::test_close", "test/test_coordinator.py::test_commit_offsets_async", "test/test_coordinator.py::test_commit_offsets_sync", "test/test_coordinator.py::test_maybe_auto_commit_offsets_sync[api_version0-foobar-True-None-False-False-True-False]", "test/test_coordinator.py::test_maybe_auto_commit_offsets_sync[api_version1-foobar-False-None-False-False-False-False]", "test/test_coordinator.py::test_maybe_auto_commit_offsets_sync[api_version2-foobar-True-error2-True-True-True-False]", "test/test_coordinator.py::test_maybe_auto_commit_offsets_sync[api_version3-foobar-True-error3-True-True-True-False]", "test/test_coordinator.py::test_maybe_auto_commit_offsets_sync[api_version4-foobar-True-error4-True-True-True-False]", "test/test_coordinator.py::test_maybe_auto_commit_offsets_sync[api_version5-foobar-True-error5-True-True-False-True]", "test/test_coordinator.py::test_maybe_auto_commit_offsets_sync[api_version6-foobar-True-None-True-True-False-False]", "test/test_coordinator.py::test_send_offset_commit_request_fail", "test/test_coordinator.py::test_send_offset_commit_request_versions[api_version0-OffsetCommitRequest_v0]", "test/test_coordinator.py::test_send_offset_commit_request_versions[api_version1-OffsetCommitRequest_v1]", "test/test_coordinator.py::test_send_offset_commit_request_versions[api_version2-OffsetCommitRequest_v2]", "test/test_coordinator.py::test_send_offset_commit_request_failure", "test/test_coordinator.py::test_send_offset_commit_request_success", "test/test_coordinator.py::test_handle_offset_commit_response[response0-GroupAuthorizationFailedError-False-False]", "test/test_coordinator.py::test_handle_offset_commit_response[response1-OffsetMetadataTooLargeError-False-False]", "test/test_coordinator.py::test_handle_offset_commit_response[response2-InvalidCommitOffsetSizeError-False-False]", "test/test_coordinator.py::test_handle_offset_commit_response[response3-GroupLoadInProgressError-False-False]", "test/test_coordinator.py::test_handle_offset_commit_response[response4-GroupCoordinatorNotAvailableError-True-False]", "test/test_coordinator.py::test_handle_offset_commit_response[response5-NotCoordinatorForGroupError-True-False]", "test/test_coordinator.py::test_handle_offset_commit_response[response6-RequestTimedOutError-True-False]", "test/test_coordinator.py::test_handle_offset_commit_response[response7-UnknownMemberIdError-False-True]", "test/test_coordinator.py::test_handle_offset_commit_response[response8-IllegalGenerationError-False-True]", "test/test_coordinator.py::test_handle_offset_commit_response[response9-RebalanceInProgressError-False-True]", "test/test_coordinator.py::test_handle_offset_commit_response[response11-TopicAuthorizationFailedError-False-False]", "test/test_coordinator.py::test_send_offset_fetch_request_fail", "test/test_coordinator.py::test_send_offset_fetch_request_versions[api_version0-OffsetFetchRequest_v0]", "test/test_coordinator.py::test_send_offset_fetch_request_versions[api_version1-OffsetFetchRequest_v1]", "test/test_coordinator.py::test_send_offset_fetch_request_versions[api_version2-OffsetFetchRequest_v1]", "test/test_coordinator.py::test_send_offset_fetch_request_failure", "test/test_coordinator.py::test_send_offset_fetch_request_success", "test/test_coordinator.py::test_handle_offset_fetch_response[response0-GroupLoadInProgressError-False-False]", "test/test_coordinator.py::test_handle_offset_fetch_response[response1-NotCoordinatorForGroupError-True-False]", "test/test_coordinator.py::test_handle_offset_fetch_response[response2-UnknownMemberIdError-False-True]", "test/test_coordinator.py::test_handle_offset_fetch_response[response3-IllegalGenerationError-False-True]", "test/test_coordinator.py::test_handle_offset_fetch_response[response4-TopicAuthorizationFailedError-False-False]", "test/test_coordinator.py::test_handle_offset_fetch_response[response5-None-False-False]", "test/test_coordinator.py::test_heartbeat" ]
[]
Apache License 2.0
491
737
[ "kafka/coordinator/consumer.py" ]
docker__docker-py-1022
e743254b42080e6d199fc10f4812a42ecb8d536f
2016-04-05 19:54:10
299ffadb95c90eb7134b9cee2648fb683912c303
dnephin: LGTM when build is green. Not sure why they all failed, maybe just a jenkins issue?
diff --git a/docker/auth/auth.py b/docker/auth/auth.py index eedb7944..d23e6f3c 100644 --- a/docker/auth/auth.py +++ b/docker/auth/auth.py @@ -117,7 +117,7 @@ def parse_auth(entries, raise_on_error=False): conf = {} for registry, entry in six.iteritems(entries): - if not (isinstance(entry, dict) and 'auth' in entry): + if not isinstance(entry, dict): log.debug( 'Config entry for key {0} is not auth config'.format(registry) ) @@ -130,6 +130,16 @@ def parse_auth(entries, raise_on_error=False): 'Invalid configuration for registry {0}'.format(registry) ) return {} + if 'auth' not in entry: + # Starting with engine v1.11 (API 1.23), an empty dictionary is + # a valid value in the auths config. + # https://github.com/docker/compose/issues/3265 + log.debug( + 'Auth data for {0} is absent. Client might be using a ' + 'credentials store instead.' + ) + return {} + username, password = decode_auth(entry['auth']) log.debug( 'Found entry (registry={0}, username={1})' @@ -189,6 +199,9 @@ def load_config(config_path=None): if data.get('HttpHeaders'): log.debug("Found 'HttpHeaders' section") res.update({'HttpHeaders': data['HttpHeaders']}) + if data.get('credsStore'): + log.debug("Found 'credsStore' section") + res.update({'credsStore': data['credsStore']}) if res: return res else:
Empty auth dictionary should be valid docker/compose#3265
docker/docker-py
diff --git a/tests/unit/auth_test.py b/tests/unit/auth_test.py index 921aae00..4ea40477 100644 --- a/tests/unit/auth_test.py +++ b/tests/unit/auth_test.py @@ -459,6 +459,5 @@ class LoadConfigTest(base.Cleanup, base.BaseTestCase): with open(dockercfg_path, 'w') as f: json.dump(config, f) - self.assertRaises( - errors.InvalidConfigFile, auth.load_config, dockercfg_path - ) + cfg = auth.load_config(dockercfg_path) + assert cfg == {}
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 3, "test_score": 2 }, "num_modified_files": 1 }
1.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.4", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 certifi==2021.5.30 -e git+https://github.com/docker/docker-py.git@e743254b42080e6d199fc10f4812a42ecb8d536f#egg=docker_py importlib-metadata==4.8.3 iniconfig==1.1.1 packaging==21.3 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pytest==7.0.1 requests==2.5.3 six==1.17.0 tomli==1.2.3 typing_extensions==4.1.1 websocket-client==0.32.0 zipp==3.6.0
name: docker-py channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pytest==7.0.1 - requests==2.5.3 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - websocket-client==0.32.0 - zipp==3.6.0 prefix: /opt/conda/envs/docker-py
[ "tests/unit/auth_test.py::LoadConfigTest::test_load_config_invalid_auth_dict" ]
[]
[ "tests/unit/auth_test.py::RegressionTest::test_803_urlsafe_encode", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_explicit_hub_index_library_image", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_explicit_legacy_hub_index_library_image", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_invalid_index_name", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_dotted_hub_library_image", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_hub_image", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_hub_library_image", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_localhost", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_localhost_with_username", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_no_dots_but_port", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_no_dots_but_port_and_username", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_private_registry", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_private_registry_with_port", "tests/unit/auth_test.py::ResolveRepositoryNameTest::test_resolve_repository_name_private_registry_with_username", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_default_explicit_none", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_default_registry", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_fully_explicit", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_hostname_only", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_legacy_config", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_match", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_trailing_slash", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_wrong_insecure_proto", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_path_wrong_secure_proto", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_no_protocol", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_authconfig_path_wrong_proto", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_explicit_hub", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_explicit_legacy_hub", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_hub_image", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_library_image", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_private_registry", "tests/unit/auth_test.py::ResolveAuthTest::test_resolve_registry_and_auth_unauthenticated_registry", "tests/unit/auth_test.py::LoadConfigTest::test_load_config", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env_utf8", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env_with_auths", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_custom_config_env_with_headers", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_no_file", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_unknown_keys", "tests/unit/auth_test.py::LoadConfigTest::test_load_config_with_random_name" ]
[]
Apache License 2.0
493
414
[ "docker/auth/auth.py" ]
juju-solutions__charms.reactive-65
3540030b9b142787f3f7fd16a14ed33d18b4d7a1
2016-04-12 16:08:23
59b07bd9447d8a4cb027ea2515089216b8d20549
diff --git a/charms/reactive/bus.py b/charms/reactive/bus.py index 9676244..885e498 100644 --- a/charms/reactive/bus.py +++ b/charms/reactive/bus.py @@ -267,7 +267,10 @@ class Handler(object): """ Lazily evaluate the args. """ - return list(chain.from_iterable(self._args)) + if not hasattr(self, '_args_evaled'): + # cache the args in case handler is re-invoked due to states change + self._args_evaled = list(chain.from_iterable(self._args)) + return self._args_evaled def invoke(self): """
Handler args are dropped if called more than once per hook Because the args are implemented as generators, any time the list is evaluated after the first it ends up being empty, leading to an "missing arg" error: ``` 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined Traceback (most recent call last): 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined File "/var/lib/juju/agents/unit-nn-0/charm/hooks/namenode-cluster-relation-joined", line 19, in <module> 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined main() 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined File "/usr/local/lib/python3.4/dist-packages/charms/reactive/__init__.py", line 73, in main 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined bus.dispatch() 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined File "/usr/local/lib/python3.4/dist-packages/charms/reactive/bus.py", line 418, in dispatch 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined _invoke(other_handlers) 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined File "/usr/local/lib/python3.4/dist-packages/charms/reactive/bus.py", line 401, in _invoke 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined handler.invoke() 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined File "/usr/local/lib/python3.4/dist-packages/charms/reactive/bus.py", line 277, in invoke 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined self._action(*args) 2016-04-12 15:15:51 INFO namenode-cluster-relation-joined TypeError: report_status() missing 1 required positional argument: 'datanode' ```
juju-solutions/charms.reactive
diff --git a/tests/test_decorators.py b/tests/test_decorators.py index 836753a..fdbb512 100644 --- a/tests/test_decorators.py +++ b/tests/test_decorators.py @@ -103,6 +103,11 @@ class TestReactiveDecorators(unittest.TestCase): action.assert_called_once_with('rel') self.assertEqual(reactive.bus.Handler._CONSUMED_STATES, set(['foo', 'bar', 'qux'])) + action.reset_mock() + assert handler.test() + handler.invoke() + action.assert_called_once_with('rel') + @mock.patch.object(reactive.decorators, 'when_all') def test_when(self, when_all): @reactive.when('foo', 'bar', 'qux')
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 1 }, "num_modified_files": 1 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "coverage", "mock", "nose", "flake8", "ipython", "ipdb", "pytest" ], "pre_install": null, "python": "3.6", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
attrs==22.2.0 backcall==0.2.0 certifi==2021.5.30 charmhelpers==1.2.1 -e git+https://github.com/juju-solutions/charms.reactive.git@3540030b9b142787f3f7fd16a14ed33d18b4d7a1#egg=charms.reactive coverage==6.2 decorator==5.1.1 flake8==5.0.4 importlib-metadata==4.2.0 importlib-resources==5.4.0 iniconfig==1.1.1 ipdb==0.13.13 ipython==7.16.3 ipython-genutils==0.2.0 jedi==0.17.2 Jinja2==3.0.3 MarkupSafe==2.0.1 mccabe==0.7.0 mock==5.2.0 netaddr==0.10.1 nose==1.3.7 packaging==21.3 parso==0.7.1 pbr==6.1.1 pexpect==4.9.0 pickleshare==0.7.5 pluggy==1.0.0 prompt-toolkit==3.0.36 ptyprocess==0.7.0 py==1.11.0 pyaml==23.5.8 pycodestyle==2.9.1 pyflakes==2.5.0 Pygments==2.14.0 pyparsing==3.1.4 pytest==7.0.1 PyYAML==6.0.1 six==1.17.0 tomli==1.2.3 traitlets==4.3.3 typing_extensions==4.1.1 wcwidth==0.2.13 zipp==3.6.0
name: charms.reactive channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - certifi=2021.5.30=py36h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.3=he6710b0_2 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=1.1.1w=h7f8727e_0 - pip=21.2.2=py36h06a4308_0 - python=3.6.13=h12debd9_1 - readline=8.2=h5eee18b_0 - setuptools=58.0.4=py36h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - wheel=0.37.1=pyhd3eb1b0_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - attrs==22.2.0 - backcall==0.2.0 - charmhelpers==1.2.1 - coverage==6.2 - decorator==5.1.1 - flake8==5.0.4 - importlib-metadata==4.2.0 - importlib-resources==5.4.0 - iniconfig==1.1.1 - ipdb==0.13.13 - ipython==7.16.3 - ipython-genutils==0.2.0 - jedi==0.17.2 - jinja2==3.0.3 - markupsafe==2.0.1 - mccabe==0.7.0 - mock==5.2.0 - netaddr==0.10.1 - nose==1.3.7 - packaging==21.3 - parso==0.7.1 - pbr==6.1.1 - pexpect==4.9.0 - pickleshare==0.7.5 - pluggy==1.0.0 - prompt-toolkit==3.0.36 - ptyprocess==0.7.0 - py==1.11.0 - pyaml==23.5.8 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pygments==2.14.0 - pyparsing==3.1.4 - pytest==7.0.1 - pyyaml==6.0.1 - six==1.17.0 - tomli==1.2.3 - traitlets==4.3.3 - typing-extensions==4.1.1 - wcwidth==0.2.13 - zipp==3.6.0 prefix: /opt/conda/envs/charms.reactive
[ "tests/test_decorators.py::TestReactiveDecorators::test_when_all" ]
[]
[ "tests/test_decorators.py::TestReactiveDecorators::test_multi", "tests/test_decorators.py::TestReactiveDecorators::test_not_unless", "tests/test_decorators.py::TestReactiveDecorators::test_only_once", "tests/test_decorators.py::TestReactiveDecorators::test_when", "tests/test_decorators.py::TestReactiveDecorators::test_when_any", "tests/test_decorators.py::TestReactiveDecorators::test_when_file_changed", "tests/test_decorators.py::TestReactiveDecorators::test_when_none", "tests/test_decorators.py::TestReactiveDecorators::test_when_not", "tests/test_decorators.py::TestReactiveDecorators::test_when_not_all" ]
[ "tests/test_decorators.py::TestReactiveDecorators::test_hook" ]
Apache License 2.0
501
170
[ "charms/reactive/bus.py" ]
guykisel__inline-plz-129
a7c89d5b65df2486ccf78f43fcffdc18dff76bd7
2016-04-15 01:05:40
a7c89d5b65df2486ccf78f43fcffdc18dff76bd7
raphaelcastaneda: Hmm... https://travis-ci.org/guykisel/inline-plz/jobs/123219118#L726 ` File "/home/travis/build/guykisel/inline-plz/inlineplz/linters/__init__.py", line 364, in lint linter_messages = config.get('parser')().parse(output) File "/home/travis/build/guykisel/inline-plz/inlineplz/parsers/rflint.py", line 14, in parse for line in lint_data.split('\n'): AttributeError: 'list' object has no attribute 'split'`
diff --git a/inlineplz/linters/__init__.py b/inlineplz/linters/__init__.py index 16cce9f..5cafd13 100644 --- a/inlineplz/linters/__init__.py +++ b/inlineplz/linters/__init__.py @@ -175,13 +175,13 @@ LINTERS = { 'rflint': { 'install': [['pip', 'install', 'robotframework-lint']], 'help': ['rflint', '--help'], - 'run': ['rflint', '.'], - 'rundefault': ['rflint', '-A', '{config_dir}/.rflint', '.'], + 'run': ['rflint'], + 'rundefault': ['rflint', '-A', '{config_dir}/.rflint'], 'dotfiles': ['.rflint'], 'parser': parsers.RobotFrameworkLintParser, 'language': 'robotframework', 'autorun': True, - 'run_per_file': False + 'run_per_file': True }, } diff --git a/inlineplz/parsers/rflint.py b/inlineplz/parsers/rflint.py index 56206ae..c4e8500 100644 --- a/inlineplz/parsers/rflint.py +++ b/inlineplz/parsers/rflint.py @@ -11,16 +11,17 @@ class RobotFrameworkLintParser(ParserBase): def parse(self, lint_data): messages = set() current_file = None - for line in lint_data.split('\n'): - try: - if line.startswith('+'): - current_file = line.split(' ')[1].strip() - continue - else: - _, position, message = line.split(':') - line_number, _ = position.split(',') - messages.add((current_file, int(line_number), message.strip())) - except ValueError: - pass + for _, output in lint_data: + for line in output.split('\n'): + try: + if line.startswith('+'): + current_file = line[2:] + continue + else: + _, position, message = line.split(':') + line_number, _ = position.split(',') + messages.add((current_file, int(line_number), message.strip())) + except ValueError: + pass return messages
rflint is running against all file types ``` Message: Path: node_modules/stylint/node_modules/yargs/node_modules/cliui/node_modules/wordwrap/test/idleness.txt Line number: 19 Content: set([u'rflint: Line is too long (exceeds 250 characters) (LineTooLong)']) ``` fyi @raphaelcastaneda
guykisel/inline-plz
diff --git a/tests/parsers/test_rflint.py b/tests/parsers/test_rflint.py index fcee628..7d164ea 100644 --- a/tests/parsers/test_rflint.py +++ b/tests/parsers/test_rflint.py @@ -17,7 +17,14 @@ rflint_path = os.path.join( def test_rflint(): with codecs.open(rflint_path, encoding='utf-8', errors='replace') as inputfile: - messages = sorted(list(rflint.RobotFrameworkLintParser().parse(inputfile.read()))) - assert messages[-1][2] == 'Too few steps (1) in keyword (TooFewKeywordSteps)' - assert messages[-1][1] == 30 - assert messages[-1][0] == './Functional_Requirements/keywords.robot' + test_data = inputfile.readlines() + test_filename = '' + test_input = [] + for line in test_data: + if line.startswith('+'): + test_filename = line.split(' ')[-1].strip() + test_input.append((test_filename, line)) + messages = sorted(list(rflint.RobotFrameworkLintParser().parse(test_input))) + assert messages[-1][2] == 'Too few steps (1) in keyword (TooFewKeywordSteps)' + assert messages[-1][1] == 30 + assert messages[-1][0] == './Functional_Requirements/keywords.robot'
{ "commit_name": "merge_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 2 }
0.12
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 cffi==1.17.1 charset-normalizer==3.4.1 cryptography==44.0.2 exceptiongroup==1.2.2 github3.py==4.0.1 idna==3.10 iniconfig==2.1.0 -e git+https://github.com/guykisel/inline-plz.git@a7c89d5b65df2486ccf78f43fcffdc18dff76bd7#egg=inlineplz packaging==24.2 pluggy==1.5.0 pycparser==2.22 PyJWT==2.10.1 pytest==8.3.5 python-dateutil==2.9.0.post0 PyYAML==6.0.2 requests==2.32.3 scandir==1.10.0 six==1.17.0 tomli==2.2.1 unidiff==0.7.5 uritemplate==4.1.1 urllib3==2.3.0 xmltodict==0.14.2
name: inline-plz channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - certifi==2025.1.31 - cffi==1.17.1 - charset-normalizer==3.4.1 - cryptography==44.0.2 - exceptiongroup==1.2.2 - github3-py==4.0.1 - idna==3.10 - iniconfig==2.1.0 - packaging==24.2 - pluggy==1.5.0 - pycparser==2.22 - pyjwt==2.10.1 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - pyyaml==6.0.2 - requests==2.32.3 - scandir==1.10.0 - six==1.17.0 - tomli==2.2.1 - unidiff==0.7.5 - uritemplate==4.1.1 - urllib3==2.3.0 - xmltodict==0.14.2 prefix: /opt/conda/envs/inline-plz
[ "tests/parsers/test_rflint.py::test_rflint" ]
[]
[]
[]
ISC License
503
560
[ "inlineplz/linters/__init__.py", "inlineplz/parsers/rflint.py" ]
pysmt__pysmt-243
2abfb4538fa93379f9b2671bce30f27967dedbcf
2016-04-15 16:24:27
2abfb4538fa93379f9b2671bce30f27967dedbcf
diff --git a/pysmt/formula.py b/pysmt/formula.py index 0a4dcd3..4fdcbfe 100644 --- a/pysmt/formula.py +++ b/pysmt/formula.py @@ -477,7 +477,7 @@ class FormulaManager(object): A -> !(B \/ C) B -> !(C) """ - args = list(*args) + args = self._polymorph_args_to_tuple(args) return self.And(self.Or(*args), self.AtMostOne(*args))
issue in processing arguments for ExactlyOne() Hi, I noticed that instantiating shortcuts.ExactlyOne() throws e.g. TypeError: list() takes at most 1 argument (3 given) at formula.py, line 480. I believe args shouldn't be unpacked in the list constructor. Martin
pysmt/pysmt
diff --git a/pysmt/test/test_formula.py b/pysmt/test/test_formula.py index 0ddbec4..924328a 100644 --- a/pysmt/test/test_formula.py +++ b/pysmt/test/test_formula.py @@ -494,6 +494,16 @@ class TestFormulaManager(TestCase): self.assertEqual(c, self.mgr.Bool(False), "ExactlyOne should not allow 2 symbols to be True") + s1 = self.mgr.Symbol("x") + s2 = self.mgr.Symbol("x") + f1 = self.mgr.ExactlyOne((s for s in [s1,s2])) + f2 = self.mgr.ExactlyOne([s1,s2]) + f3 = self.mgr.ExactlyOne(s1,s2) + + self.assertEqual(f1,f2) + self.assertEqual(f2,f3) + + @skipIfNoSolverForLogic(QF_BOOL) def test_exactly_one_is_sat(self): symbols = [ self.mgr.Symbol("s%d"%i, BOOL) for i in range(5) ] diff --git a/pysmt/test/test_regressions.py b/pysmt/test/test_regressions.py index 2fecd04..67bfc3d 100644 --- a/pysmt/test/test_regressions.py +++ b/pysmt/test/test_regressions.py @@ -311,6 +311,14 @@ class TestRegressions(TestCase): close_l = get_closer_smtlib_logic(logics.BOOL) self.assertEqual(close_l, logics.LRA) + def test_exactly_one_unpacking(self): + s1,s2 = Symbol("x"), Symbol("y") + f1 = ExactlyOne((s for s in [s1,s2])) + f2 = ExactlyOne([s1,s2]) + f3 = ExactlyOne(s1,s2) + + self.assertEqual(f1,f2) + self.assertEqual(f2,f3) if __name__ == "__main__": main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
0.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest", "pytest-cov", "nose", "nose-cov" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cov-core==1.15.0 coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 nose==1.3.7 nose-cov==1.6 packaging==24.2 pluggy==1.5.0 -e git+https://github.com/pysmt/pysmt.git@2abfb4538fa93379f9b2671bce30f27967dedbcf#egg=PySMT pytest==8.3.5 pytest-cov==6.0.0 six==1.17.0 tomli==2.2.1
name: pysmt channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cov-core==1.15.0 - coverage==7.8.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - nose==1.3.7 - nose-cov==1.6 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - six==1.17.0 - tomli==2.2.1 prefix: /opt/conda/envs/pysmt
[ "pysmt/test/test_formula.py::TestFormulaManager::test_exactly_one", "pysmt/test/test_regressions.py::TestRegressions::test_exactly_one_unpacking" ]
[ "pysmt/test/test_regressions.py::TestRegressions::test_parse_define_fun", "pysmt/test/test_regressions.py::TestRegressions::test_parse_define_fun_bind" ]
[ "pysmt/test/test_formula.py::TestFormulaManager::test_0arity_function", "pysmt/test/test_formula.py::TestFormulaManager::test_all_different", "pysmt/test/test_formula.py::TestFormulaManager::test_and_node", "pysmt/test/test_formula.py::TestFormulaManager::test_at_most_one", "pysmt/test/test_formula.py::TestFormulaManager::test_bconstant", "pysmt/test/test_formula.py::TestFormulaManager::test_constant", "pysmt/test/test_formula.py::TestFormulaManager::test_div_node", "pysmt/test/test_formula.py::TestFormulaManager::test_div_non_linear", "pysmt/test/test_formula.py::TestFormulaManager::test_equals", "pysmt/test/test_formula.py::TestFormulaManager::test_equals_or_iff", "pysmt/test/test_formula.py::TestFormulaManager::test_formula_in_formula_manager", "pysmt/test/test_formula.py::TestFormulaManager::test_function", "pysmt/test/test_formula.py::TestFormulaManager::test_ge_node", "pysmt/test/test_formula.py::TestFormulaManager::test_ge_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_get_or_create_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_get_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_gt_node", "pysmt/test/test_formula.py::TestFormulaManager::test_gt_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_iff_node", "pysmt/test/test_formula.py::TestFormulaManager::test_implies_node", "pysmt/test/test_formula.py::TestFormulaManager::test_infix", "pysmt/test/test_formula.py::TestFormulaManager::test_infix_extended", "pysmt/test/test_formula.py::TestFormulaManager::test_is_term", "pysmt/test/test_formula.py::TestFormulaManager::test_ite", "pysmt/test/test_formula.py::TestFormulaManager::test_le_node", "pysmt/test/test_formula.py::TestFormulaManager::test_le_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_lt_node", "pysmt/test/test_formula.py::TestFormulaManager::test_lt_node_type", "pysmt/test/test_formula.py::TestFormulaManager::test_max", "pysmt/test/test_formula.py::TestFormulaManager::test_min", "pysmt/test/test_formula.py::TestFormulaManager::test_minus_node", "pysmt/test/test_formula.py::TestFormulaManager::test_new_fresh_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_not_node", "pysmt/test/test_formula.py::TestFormulaManager::test_or_node", "pysmt/test/test_formula.py::TestFormulaManager::test_pickling", "pysmt/test/test_formula.py::TestFormulaManager::test_plus_node", "pysmt/test/test_formula.py::TestFormulaManager::test_symbol", "pysmt/test/test_formula.py::TestFormulaManager::test_times_node", "pysmt/test/test_formula.py::TestFormulaManager::test_toReal", "pysmt/test/test_formula.py::TestFormulaManager::test_typing", "pysmt/test/test_formula.py::TestFormulaManager::test_xor", "pysmt/test/test_formula.py::TestShortcuts::test_shortcut_is_using_global_env", "pysmt/test/test_regressions.py::TestRegressions::test_cnf_as_set", "pysmt/test/test_regressions.py::TestRegressions::test_dependencies_not_includes_toreal", "pysmt/test/test_regressions.py::TestRegressions::test_determinism", "pysmt/test/test_regressions.py::TestRegressions::test_empty_string_symbol", "pysmt/test/test_regressions.py::TestRegressions::test_exactlyone_w_generator", "pysmt/test/test_regressions.py::TestRegressions::test_infix_notation_wrong_le", "pysmt/test/test_regressions.py::TestRegressions::test_is_one", "pysmt/test/test_regressions.py::TestRegressions::test_multiple_declaration_w_same_functiontype", "pysmt/test/test_regressions.py::TestRegressions::test_multiple_exit", "pysmt/test/test_regressions.py::TestRegressions::test_qf_bool_smt2", "pysmt/test/test_regressions.py::TestRegressions::test_simplifying_int_plus_changes_type_of_expression", "pysmt/test/test_regressions.py::TestRegressions::test_smtlib_info_quoting", "pysmt/test/test_regressions.py::TestRegressions::test_substitute_memoization", "pysmt/test/test_regressions.py::TestRegressions::test_substitute_to_real" ]
[]
Apache License 2.0
504
132
[ "pysmt/formula.py" ]
Shopify__shopify_python_api-136
a78109e725cf9e400f955062399767f36f3a1f44
2016-04-18 03:46:33
c29e0ecbed9de67dd923f980a3ac053922dab75e
diff --git a/shopify/mixins.py b/shopify/mixins.py index 9d3c179..c7806a0 100644 --- a/shopify/mixins.py +++ b/shopify/mixins.py @@ -11,8 +11,15 @@ class Countable(object): class Metafields(object): - def metafields(self): - return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id) + def metafields(self, _options=None, **kwargs): + if _options is None: + _options = kwargs + return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id, **_options) + + def metafields_count(self, _options=None, **kwargs): + if _options is None: + _options = kwargs + return int(self.get("metafields/count", **_options)) def add_metafield(self, metafield): if self.is_new():
metafields() method should be able to take options parameters for limit and page ``` import shopify product = shopify.Product.find(5972485446) metafields = product.metafields() print(len(metafields)) > 50 metafields = product.metafields(limit=250) > TypeError: metafields() got an unexpected keyword argument 'limit' ``` I looked into the code, and it seems like it may be a simple fix. If I come up with something I'll submit a pull request, if I can't I'll let it be known here so somebody else can try tackling it.
Shopify/shopify_python_api
diff --git a/test/fixtures/metafields_count.json b/test/fixtures/metafields_count.json new file mode 100644 index 0000000..a113c32 --- /dev/null +++ b/test/fixtures/metafields_count.json @@ -0,0 +1,1 @@ +{"count":2} diff --git a/test/product_test.py b/test/product_test.py index c48962a..dcc9ae7 100644 --- a/test/product_test.py +++ b/test/product_test.py @@ -28,6 +28,26 @@ class ProductTest(TestCase): for field in metafields: self.assertTrue(isinstance(field, shopify.Metafield)) + def test_get_metafields_for_product_with_params(self): + self.fake("products/632910392/metafields.json?limit=2", extension=False, body=self.load_fixture('metafields')) + + metafields = self.product.metafields(limit=2) + self.assertEqual(2, len(metafields)) + for field in metafields: + self.assertTrue(isinstance(field, shopify.Metafield)) + + def test_get_metafields_for_product_count(self): + self.fake("products/632910392/metafields/count", body=self.load_fixture('metafields_count')) + + metafields_count = self.product.metafields_count() + self.assertEqual(2, metafields_count) + + def test_get_metafields_for_product_count_with_params(self): + self.fake("products/632910392/metafields/count.json?value_type=string", extension=False, body=self.load_fixture('metafields_count')) + + metafields_count = self.product.metafields_count(value_type="string") + self.assertEqual(2, metafields_count) + def test_update_loaded_variant(self): self.fake("products/632910392/variants/808950810", method='PUT', code=200, body=self.load_fixture('variant'))
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 1, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
2.1
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "pytest", "pip_packages": [ "mock>=1.0.1", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work mock==5.2.0 packaging @ file:///croot/packaging_1734472117206/work pluggy @ file:///croot/pluggy_1733169602837/work pyactiveresource==2.2.2 pytest @ file:///croot/pytest_1738938843180/work PyYAML==6.0.2 -e git+https://github.com/Shopify/shopify_python_api.git@a78109e725cf9e400f955062399767f36f3a1f44#egg=ShopifyAPI six==1.17.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: shopify_python_api channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - exceptiongroup=1.2.0=py39h06a4308_0 - iniconfig=1.1.1=pyhd3eb1b0_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - packaging=24.2=py39h06a4308_0 - pip=25.0=py39h06a4308_0 - pluggy=1.5.0=py39h06a4308_0 - pytest=8.3.4=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tomli=2.0.1=py39h06a4308_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - mock==5.2.0 - pyactiveresource==2.2.2 - pyyaml==6.0.2 - six==1.17.0 prefix: /opt/conda/envs/shopify_python_api
[ "test/product_test.py::ProductTest::test_get_metafields_for_product_count", "test/product_test.py::ProductTest::test_get_metafields_for_product_count_with_params", "test/product_test.py::ProductTest::test_get_metafields_for_product_with_params" ]
[]
[ "test/product_test.py::ProductTest::test_add_metafields_to_product", "test/product_test.py::ProductTest::test_add_variant_to_product", "test/product_test.py::ProductTest::test_get_metafields_for_product", "test/product_test.py::ProductTest::test_update_loaded_variant" ]
[]
MIT License
507
231
[ "shopify/mixins.py" ]
terryyin__lizard-120
bdcc784bd22d8e48db22884dfeb42647ffb67fbf
2016-05-08 06:41:31
bdcc784bd22d8e48db22884dfeb42647ffb67fbf
rakhimov: Hi @terryyin, do not yet merge this PR. I sense there are bugs in implementation of C++ ``current_nesting_level``. The initial code works with Python, for which the nesting level metric is producing what is expected. However, the C++ ``current_nesting_level`` doesn't seem to be fully conformant. Your suggestions are welcome.
diff --git a/lizard.py b/lizard.py index 4d21e8a..cac8020 100755 --- a/lizard.py +++ b/lizard.py @@ -316,7 +316,7 @@ class NestingStack(object): self.pending_function = None self.nesting_stack.append(Namespace(token)) - def start_new_funciton_nesting(self, function): + def start_new_function_nesting(self, function): self.pending_function = function def _create_nesting(self): @@ -386,7 +386,7 @@ class FileInfoBuilder(object): self.fileinfo.filename, self.current_line) self.current_function.top_nesting_level = self.current_nesting_level - self.start_new_funciton_nesting(self.current_function) + self.start_new_function_nesting(self.current_function) def add_condition(self, inc=1): self.current_function.cyclomatic_complexity += inc diff --git a/lizard_ext/lizardns.py b/lizard_ext/lizardns.py index e057e73..4ee09bf 100644 --- a/lizard_ext/lizardns.py +++ b/lizard_ext/lizardns.py @@ -1,13 +1,16 @@ """ This extension counts nested control structures within a function. -The extension is implemented with C++ in mind. + +The extension is implemented with C++ and Python in mind, +but it is expected to work with other languages supported by Lizard +with its language reader implementing 'nesting_level' metric for tokens. The code borrows heavily from implementation of Nesting Depth extension originally written by Mehrdad Meh and Terry Yin. """ -from lizard import FileInfoBuilder, FunctionInfo -from lizard_ext.lizardnd import patch, patch_append_method +from lizard import FunctionInfo +from lizard_ext.lizardnd import patch_append_method DEFAULT_NS_THRESHOLD = 3 @@ -32,106 +35,90 @@ class LizardExtension(object): # pylint: disable=R0903 def __call__(self, tokens, reader): """The intent of the code is to detect control structures as entities. - The complexity arises from tracking of - control structures without brackets. - The termination of such control structures in C-like languages - is the next statement or control structure with a compound statement. - - Moreover, control structures with two or more tokens complicates - the proper counting, for example, 'else if'. + The implementation relies on nesting level metric for tokens + provided by language readers. + If the following contract for the nesting level metric does not hold, + this implementation of nested structure counting is invalid. - In Python with meaningful indentation, - tracking the indentation levels becomes crucial - to identify boundaries of the structures. - The following code is not designed for Python. - """ - structures = set(['if', 'else', 'foreach', 'for', 'while', 'do', - 'try', 'catch', 'switch']) + If a control structure has started its block (eg. '{'), + and its level is **less** than the next structure, + the next structure is nested. - structure_indicator = "{" - structure_end = "}" - indent_indicator = ";" - - for token in tokens: - if reader.context.is_within_structure(): - if token == "(": - reader.context.add_parentheses(1) - elif token == ")": - reader.context.add_parentheses(-1) + If a control structure has *not* started its block, + and its level is **no more** than the next structure, + the next structure is nested (compound statement). - if not reader.context.is_within_parentheses(): - if token in structures: - reader.context.add_nested_structure(token) + If a control structure level is **higher** than the next structure, + it is considered closed. - elif token == structure_indicator: - reader.context.add_brace() - - elif token == structure_end: - reader.context.pop_brace() - reader.context.pop_nested_structure() - - elif token == indent_indicator: - reader.context.pop_nested_structure() - - yield token + If a control structure has started its block, + and its level is **equal** to the next structure, + it is considered closed. - -# TODO: Some weird false positive from pylint. # pylint: disable=fixme -# pylint: disable=E1101 -class NSFileInfoAddition(FileInfoBuilder): - - def add_nested_structure(self, token): - """Conditionally adds nested structures.""" - # Handle compound else-if. - if token == "if" and self.current_function.structure_stack: - prev_token, br_state = self.current_function.structure_stack[-1] - if (prev_token == "else" and - br_state == self.current_function.brace_count): + The level of any non-structure tokens is treated + with the same logic as for the next structures + for control block **starting** and **closing** purposes. + """ + # TODO: Delegate this to language readers # pylint: disable=fixme + structures = set(['if', 'else', 'elif', 'for', 'foreach', 'while', 'do', + 'try', 'catch', 'switch', 'finally', 'except', + 'with']) + + cur_level = 0 + start_structure = [False] # Just to make it mutable. + structure_stack = [] # [(token, ns_level)] + + def add_nested_structure(token): + """Conditionally adds nested structures.""" + if structure_stack: + prev_token, ns_level = structure_stack[-1] + if cur_level == ns_level: + if (token == "if" and prev_token == "else" and + not start_structure[0]): + return # Compound 'else if' in C-like languages. + if start_structure[0]: + structure_stack.pop() + elif cur_level < ns_level: + while structure_stack and ns_level >= cur_level: + _, ns_level = structure_stack.pop() + + structure_stack.append((token, cur_level)) + start_structure[0] = False # Starts on the next level with body. + + ns_cur = len(structure_stack) + if reader.context.current_function.max_nested_structures < ns_cur: + reader.context.current_function.max_nested_structures = ns_cur + + def pop_nested_structure(): + """Conditionally pops the nested structures if levels match.""" + if not structure_stack: return - self.current_function.structure_stack.append( - (token, self.current_function.brace_count)) - - ns_cur = len(self.current_function.structure_stack) - if self.current_function.max_nested_structures < ns_cur: - self.current_function.max_nested_structures = ns_cur + _, ns_level = structure_stack[-1] - def pop_nested_structure(self): - """Conditionally pops the structure count if braces match.""" - if not self.current_function.structure_stack: - return + if cur_level > ns_level: + start_structure[0] = True - _, br_state = self.current_function.structure_stack[-1] - if br_state == self.current_function.brace_count: - self.current_function.structure_stack.pop() + elif cur_level < ns_level: + while structure_stack and ns_level >= cur_level: + _, ns_level = structure_stack.pop() + start_structure[0] = bool(structure_stack) - def add_brace(self): - self.current_function.brace_count += 1 + elif start_structure[0]: + structure_stack.pop() - def pop_brace(self): - # pylint: disable=fixme - # TODO: For some reason, brace count goes negative. - # assert self.current_function.brace_count > 0 - self.current_function.brace_count -= 1 - - def add_parentheses(self, inc): - """Dual purpose parentheses manipulator.""" - self.current_function.paren_count += inc - - def is_within_parentheses(self): - assert self.current_function.paren_count >= 0 - return self.current_function.paren_count != 0 + for token in tokens: + cur_level = reader.context.current_nesting_level + if token in structures: + add_nested_structure(token) + else: + pop_nested_structure() - def is_within_structure(self): - return bool(self.current_function.structure_stack) + yield token def _init_nested_structure_data(self, *_): self.max_nested_structures = 0 - self.brace_count = 0 - self.paren_count = 0 - self.structure_stack = [] -patch(NSFileInfoAddition, FileInfoBuilder) patch_append_method(_init_nested_structure_data, FunctionInfo, "__init__")
Detection of Deeply Nested Control Structures This metric may not apply to the whole function, but the maximum 'nestedness' (nesting for-loops, if-statements, etc.) may be an interesting metric to detect code smell. It closely relates to indentation. Got this from the Linux kernel coding style: >The answer to that is that if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program.
terryyin/lizard
diff --git a/test/testNestedStructures.py b/test/testNestedStructures.py old mode 100755 new mode 100644 index 7eee514..1a2d826 --- a/test/testNestedStructures.py +++ b/test/testNestedStructures.py @@ -1,5 +1,7 @@ import unittest -from .testHelpers import get_cpp_function_list_with_extnesion + +from .testHelpers import get_cpp_function_list_with_extnesion, \ + get_python_function_list_with_extnesion from lizard_ext.lizardns import LizardExtension as NestedStructure @@ -7,6 +9,10 @@ def process_cpp(source): return get_cpp_function_list_with_extnesion(source, NestedStructure()) +def process_python(source): + return get_python_function_list_with_extnesion(source, NestedStructure()) + + class TestCppNestedStructures(unittest.TestCase): def test_no_structures(self): @@ -209,3 +215,122 @@ class TestCppNestedStructures(unittest.TestCase): } """) self.assertEqual(3, result[0].max_nested_structures) + + +class TestPythonNestedStructures(unittest.TestCase): + + def test_no_structures(self): + result = process_python("def fun():\n pass") + self.assertEqual(0, result[0].max_nested_structures) + + def test_if_structure(self): + result = process_python("def fun():\n if a:\n return") + self.assertEqual(1, result[0].max_nested_structures) + + def test_for_structure(self): + result = process_python("def fun():\n for a in b:\n foo()") + self.assertEqual(1, result[0].max_nested_structures) + + def test_condition_in_if_structure(self): + result = process_python("def fun():\n if a and b:\n return") + self.assertEqual(1, result[0].max_nested_structures) + + def test_elif(self): + result = process_python(""" + def c(): + if a: + baz() + elif c: + foo() + """) + self.assertEqual(1, result[0].max_nested_structures) + + def test_nested_if_structures(self): + result = process_python(""" + def c(): + if a: + if b: + baz() + else: + foo() + """) + self.assertEqual(2, result[0].max_nested_structures) + + def test_equal_metric_structures(self): + result = process_python(""" + def c(): + if a: + if b: + baz() + else: + foo() + + for a in b: + if c: + bar() + """) + self.assertEqual(2, result[0].max_nested_structures) + + def test_while(self): + result = process_python(""" + def c(): + while a: + baz() + """) + self.assertEqual(1, result[0].max_nested_structures) + + def test_try_catch(self): + result = process_python(""" + def c(): + try: + f.open() + catch Exception as err: + print(err) + finally: + f.close() + """) + self.assertEqual(1, result[0].max_nested_structures) + + def test_two_functions(self): + result = process_python(""" + def c(): + try: + if a: + foo() + catch Exception as err: + print(err) + + def d(): + for a in b: + for x in y: + if i: + return j + """) + self.assertEqual(2, result[0].max_nested_structures) + self.assertEqual(3, result[1].max_nested_structures) + + def test_nested_functions(self): + result = process_python(""" + def c(): + def d(): + for a in b: + for x in y: + if i: + return j + try: + if a: + foo() + catch Exception as err: + print(err) + + """) + self.assertEqual(3, result[0].max_nested_structures) + self.assertEqual(2, result[1].max_nested_structures) + + def test_with_structure(self): + result = process_python(""" + def c(): + with open(f) as input_file: + foo(f) + """) + self.assertEqual(1, result[0].max_nested_structures)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 1, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 2 }
unknown
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[dev]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements/base.txt", "dev_requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
astroid==3.3.9 dill==0.3.9 exceptiongroup==1.2.2 iniconfig==2.1.0 isort==6.0.1 -e git+https://github.com/terryyin/lizard.git@bdcc784bd22d8e48db22884dfeb42647ffb67fbf#egg=lizard mccabe==0.7.0 mock==5.2.0 nose==1.3.7 packaging==24.2 pep8==1.7.1 platformdirs==4.3.7 pluggy==1.5.0 pylint==3.3.6 pytest==8.3.5 tomli==2.2.1 tomlkit==0.13.2 typing_extensions==4.13.0
name: lizard channels: - defaults - https://repo.anaconda.com/pkgs/main - https://repo.anaconda.com/pkgs/r - conda-forge dependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - ca-certificates=2025.2.25=h06a4308_0 - ld_impl_linux-64=2.40=h12ee557_0 - libffi=3.4.4=h6a678d5_1 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libstdcxx-ng=11.2.0=h1234567_1 - ncurses=6.4=h6a678d5_0 - openssl=3.0.16=h5eee18b_0 - pip=25.0=py39h06a4308_0 - python=3.9.21=he870216_1 - readline=8.2=h5eee18b_0 - setuptools=75.8.0=py39h06a4308_0 - sqlite=3.45.3=h5eee18b_0 - tk=8.6.14=h39e8969_0 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - astroid==3.3.9 - dill==0.3.9 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - isort==6.0.1 - mccabe==0.7.0 - mock==5.2.0 - nose==1.3.7 - packaging==24.2 - pep8==1.7.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pylint==3.3.6 - pytest==8.3.5 - tomli==2.2.1 - tomlkit==0.13.2 - typing-extensions==4.13.0 prefix: /opt/conda/envs/lizard
[ "test/testNestedStructures.py::TestPythonNestedStructures::test_equal_metric_structures", "test/testNestedStructures.py::TestPythonNestedStructures::test_nested_functions", "test/testNestedStructures.py::TestPythonNestedStructures::test_nested_if_structures", "test/testNestedStructures.py::TestPythonNestedStructures::test_try_catch", "test/testNestedStructures.py::TestPythonNestedStructures::test_two_functions", "test/testNestedStructures.py::TestPythonNestedStructures::test_with_structure" ]
[]
[ "test/testNestedStructures.py::TestCppNestedStructures::test_and_condition_in_if_structure", "test/testNestedStructures.py::TestCppNestedStructures::test_do", "test/testNestedStructures.py::TestCppNestedStructures::test_forever_loop", "test/testNestedStructures.py::TestCppNestedStructures::test_if_structure", "test/testNestedStructures.py::TestCppNestedStructures::test_nested_if_structures", "test/testNestedStructures.py::TestCppNestedStructures::test_nested_loop_mixed_brackets", "test/testNestedStructures.py::TestCppNestedStructures::test_no_structures", "test/testNestedStructures.py::TestCppNestedStructures::test_non_r_value_ref_in_body", "test/testNestedStructures.py::TestCppNestedStructures::test_scope", "test/testNestedStructures.py::TestCppNestedStructures::test_switch_case", "test/testNestedStructures.py::TestCppNestedStructures::test_terminator_in_parentheses", "test/testNestedStructures.py::TestCppNestedStructures::test_ternary_operator", "test/testNestedStructures.py::TestCppNestedStructures::test_try_catch", "test/testNestedStructures.py::TestCppNestedStructures::test_while", "test/testNestedStructures.py::TestPythonNestedStructures::test_condition_in_if_structure", "test/testNestedStructures.py::TestPythonNestedStructures::test_elif", "test/testNestedStructures.py::TestPythonNestedStructures::test_for_structure", "test/testNestedStructures.py::TestPythonNestedStructures::test_if_structure", "test/testNestedStructures.py::TestPythonNestedStructures::test_no_structures", "test/testNestedStructures.py::TestPythonNestedStructures::test_while" ]
[ "test/testNestedStructures.py::TestCppNestedStructures::test_else_if", "test/testNestedStructures.py::TestCppNestedStructures::test_equal_metric_structures", "test/testNestedStructures.py::TestCppNestedStructures::test_gotcha_if_else" ]
MIT License
525
2,001
[ "lizard.py", "lizard_ext/lizardns.py" ]