instance_id
stringlengths
10
57
base_commit
stringlengths
40
40
created_at
stringdate
2014-04-30 14:58:36
2025-04-30 20:14:11
environment_setup_commit
stringlengths
40
40
hints_text
stringlengths
0
273k
patch
stringlengths
251
7.06M
problem_statement
stringlengths
11
52.5k
repo
stringlengths
7
53
test_patch
stringlengths
231
997k
meta
dict
version
stringclasses
851 values
install_config
dict
requirements
stringlengths
93
34.2k
environment
stringlengths
760
20.5k
FAIL_TO_PASS
listlengths
1
9.39k
FAIL_TO_FAIL
listlengths
0
2.69k
PASS_TO_PASS
listlengths
0
7.87k
PASS_TO_FAIL
listlengths
0
192
license_name
stringclasses
55 values
__index_level_0__
int64
0
21.4k
before_filepaths
listlengths
1
105
after_filepaths
listlengths
1
105
jubatus__jubatus-python-client-36
8cc1289e7ecb5729a951c55d6783122fd6fa2434
2014-04-30 14:58:36
8cc1289e7ecb5729a951c55d6783122fd6fa2434
diff --git a/jubatus/common/__init__.py b/jubatus/common/__init__.py index 8775c9c..04ebbc0 100644 --- a/jubatus/common/__init__.py +++ b/jubatus/common/__init__.py @@ -1,7 +1,7 @@ -from message_string_generator import MessageStringGenerator -from datum import Datum -from types import TInt, TFloat, TBool, TString, TRaw, TNullable, TList, TMap, TTuple, TUserDef, TObject -from client import Client, ClientBase, TypeMismatch, UnknownMethod +from .message_string_generator import MessageStringGenerator +from .datum import Datum +from .types import TInt, TFloat, TBool, TString, TRaw, TNullable, TList, TMap, TTuple, TUserDef, TObject +from .client import Client, ClientBase, TypeMismatch, UnknownMethod from contextlib import contextmanager diff --git a/jubatus/common/client.py b/jubatus/common/client.py index 29b197c..f965fe3 100644 --- a/jubatus/common/client.py +++ b/jubatus/common/client.py @@ -1,5 +1,5 @@ import msgpackrpc -from types import * +from .types import * class InterfaceMismatch(Exception): pass @@ -43,7 +43,7 @@ class Client(object): class ClientBase(object): def __init__(self, host, port, name, timeout=10): address = msgpackrpc.Address(host, port) - self.client = msgpackrpc.Client(address, timeout=timeout) + self.client = msgpackrpc.Client(address, timeout=timeout, unpack_encoding='utf-8') self.jubatus_client = Client(self.client, name) def get_client(self): diff --git a/jubatus/common/compat.py b/jubatus/common/compat.py new file mode 100644 index 0000000..1ee57fa --- /dev/null +++ b/jubatus/common/compat.py @@ -0,0 +1,23 @@ +import sys + +if sys.version_info >= (3, 0): + int_types = (int, ) + string_types = (str, ) + binary_types = (bytes, ) + + def u(s): + return s + + def b(s): + return s.encode() + +else: + int_types = (int, long) + string_types = (str, unicode) + binary_types = (str, ) + + def u(s): + return unicode(s) + + def b(s): + return s diff --git a/jubatus/common/datum.py b/jubatus/common/datum.py index 16aacd3..b2aafbd 100644 --- a/jubatus/common/datum.py +++ b/jubatus/common/datum.py @@ -1,5 +1,6 @@ -from message_string_generator import MessageStringGenerator -from types import * +from .message_string_generator import MessageStringGenerator +from .types import * +from .compat import int_types, string_types, binary_types class Datum: TYPE = TTuple(TList(TTuple(TString(), TString())), @@ -11,41 +12,41 @@ class Datum: self.num_values = [] self.binary_values = [] - for (k, v) in values.iteritems(): - if not isinstance(k, (str, unicode)): + for (k, v) in values.items(): + if not isinstance(k, string_types): raise TypeError - if isinstance(v, (str, unicode)): + if isinstance(v, string_types): self.string_values.append([k, v]) elif isinstance(v, float): self.num_values.append([k, v]) - elif isinstance(v, int): + elif isinstance(v, int_types): self.num_values.append([k, float(v)]) else: raise TypeError def add_string(self, key, value): - if not isinstance(key, (str, unicode)): + if not isinstance(key, string_types): raise TypeError - if isinstance(value, (str, unicode)): + if isinstance(value, string_types): self.string_values.append([key, value]) else: raise TypeError def add_number(self, key, value): - if not isinstance(key, (str, unicode)): + if not isinstance(key, string_types): raise TypeError if isinstance(value, float): self.num_values.append([key, value]) - elif isinstance(value, int): + elif isinstance(value, int_types): self.num_values.append([key, float(value)]) else: raise TypeError def add_binary(self, key, value): - if not isinstance(key, (str, unicode)): + if not isinstance(key, string_types): raise TypeError - if isinstance(value, str): + if isinstance(value, binary_types): self.binary_values.append([key, value]) else: raise TypeError diff --git a/jubatus/common/types.py b/jubatus/common/types.py index 9c909c4..91fa5bd 100644 --- a/jubatus/common/types.py +++ b/jubatus/common/types.py @@ -1,3 +1,5 @@ +from .compat import int_types, string_types, binary_types + def check_type(value, typ): if not isinstance(value, typ): raise TypeError('type %s is expected, but %s is given' % (typ, type(value))) @@ -23,20 +25,20 @@ class TPrimitive(object): class TInt(object): def __init__(self, signed, byts): if signed: - self.max = (1L << (8 * byts - 1)) - 1 - self.min = - (1L << (8 * byts - 1)) + self.max = (1 << (8 * byts - 1)) - 1 + self.min = - (1 << (8 * byts - 1)) else: - self.max = (1L << 8 * byts) - 1 + self.max = (1 << 8 * byts) - 1 self.min = 0 def from_msgpack(self, m): - check_types(m, (int, long)) + check_types(m, int_types) if not (self.min <= m and m <= self.max): raise ValueError('int value must be in (%d, %d), but %d is given' % (self.min, self.max, m)) return m def to_msgpack(self, m): - check_types(m, (int, long)) + check_types(m, int_types) if not (self.min <= m and m <= self.max): raise ValueError('int value must be in (%d, %d), but %d is given' % (self.min, self.max, m)) return m @@ -49,23 +51,32 @@ class TBool(TPrimitive): def __init__(self): super(TBool, self).__init__((bool,)) -class TString(TPrimitive): - def __init__(self): - super(TString, self).__init__((str, unicode)) +class TString(object): + def to_msgpack(self, m): + check_types(m, string_types) + return m + def from_msgpack(self, m): + check_types(m, string_types) + return m + # if isinstance(m, str): + # return m + # elif isinstance(m, bytes): + # return m.decode() + class TDatum(object): def from_msgpack(self, m): - from datum import Datum + from .datum import Datum return Datum.from_msgpack(m) def to_msgpack(self, m): - from datum import Datum + from .datum import Datum check_type(m, Datum) return m.to_msgpack() class TRaw(TPrimitive): def __init__(self): - super(TRaw, self).__init__((str,)) + super(TRaw, self).__init__(binary_types) class TNullable(object): def __init__(self, type): @@ -89,11 +100,11 @@ class TList(object): def from_msgpack(self, m): check_types(m, (list, tuple)) - return map(self.type.from_msgpack, m) + return list(map(self.type.from_msgpack, m)) def to_msgpack(self, m): check_types(m, (list, tuple)) - return map(self.type.to_msgpack, m) + return list(map(self.type.to_msgpack, m)) class TMap(object): def __init__(self, key, value): @@ -103,7 +114,7 @@ class TMap(object): def from_msgpack(self, m): check_type(m, dict) dic = {} - for k, v in m.iteritems(): + for k, v in m.items(): dic[self.key.from_msgpack(k)] = self.value.from_msgpack(v) return dic @@ -165,13 +176,13 @@ class TEnum(object): self.values = values def from_msgpack(self, m): - check_types(m, (int, long)) + check_types(m, int_types) if m not in self.values: raise ValueError return m def to_msgpack(self, m): - check_types(m, (int, long)) + check_types(m, int_types) if m not in self.values: raise ValueError return m diff --git a/setup.py b/setup.py index 83a96f8..9d09aa8 100644 --- a/setup.py +++ b/setup.py @@ -43,5 +43,5 @@ setup(name='jubatus', 'Topic :: Scientific/Engineering :: Information Analysis' ], - test_suite='jubatus_test', + test_suite='jubatus_test.suite', )
Support python3 Now jubatus doesn't work in py3 environment
jubatus/jubatus-python-client
diff --git a/test/__init__.py b/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/test/jubatus_test/__init__.py b/test/jubatus_test/__init__.py index e69de29..d28802b 100644 --- a/test/jubatus_test/__init__.py +++ b/test/jubatus_test/__init__.py @@ -0,0 +1,4 @@ +import unittest + +def suite(): + return unittest.defaultTestLoader.discover('.') diff --git a/test/jubatus_test/common/client_test.py b/test/jubatus_test/common/test_client.py similarity index 96% rename from test/jubatus_test/common/client_test.py rename to test/jubatus_test/common/test_client.py index b390e29..0e929f8 100644 --- a/test/jubatus_test/common/client_test.py +++ b/test/jubatus_test/common/test_client.py @@ -64,7 +64,7 @@ class ClientTest(unittest.TestCase): def test_wrong_number_of_arguments(self): c = jubatus.common.Client(Echo(), "name") - self.assertEquals("test", c.call("test", [], AnyType(), [])) + self.assertEqual("test", c.call("test", [], AnyType(), [])) self.assertRaises(TypeError, c.call, "test", [1], AnyType(), []) if __name__ == '__main__': diff --git a/test/jubatus_test/common/datum_test.py b/test/jubatus_test/common/test_datum.py similarity index 63% rename from test/jubatus_test/common/datum_test.py rename to test/jubatus_test/common/test_datum.py index c17d077..ef2d8c2 100644 --- a/test/jubatus_test/common/datum_test.py +++ b/test/jubatus_test/common/test_datum.py @@ -1,27 +1,28 @@ from jubatus.common import Datum import unittest import msgpack +from jubatus.common.compat import b, u class DatumTest(unittest.TestCase): def test_pack(self): - self.assertEquals( + self.assertEqual( msgpack.packb(([['name', 'Taro']], [['age', 20.0]], [])), msgpack.packb(Datum({'name': 'Taro', 'age': 20}).to_msgpack())) def test_unpack(self): - d = Datum.from_msgpack(([['name', 'Taro']], [['age', 20.0]], [['img', '0101']])) - self.assertEquals( + d = Datum.from_msgpack(([['name', 'Taro']], [['age', 20.0]], [['img', b('0101')]])) + self.assertEqual( [('name', 'Taro')], d.string_values) - self.assertEquals( + self.assertEqual( [('age', 20.0)], d.num_values) - self.assertEquals( - [('img', '0101')], + self.assertEqual( + [('img', b('0101'))], d.binary_values) def test_empty(self): - self.assertEquals( + self.assertEqual( msgpack.packb(([], [], [])), msgpack.packb(Datum().to_msgpack())) @@ -35,13 +36,13 @@ class DatumTest(unittest.TestCase): def test_add_string(self): d = Datum() d.add_string('key', 'value') - self.assertEquals(Datum({'key': 'value'}).to_msgpack(), - d.to_msgpack()) + self.assertEqual(Datum({'key': 'value'}).to_msgpack(), + d.to_msgpack()) d = Datum() - d.add_string(u'key', u'value') - self.assertEquals(Datum({'key': 'value'}).to_msgpack(), - d.to_msgpack()) + d.add_string(u('key'), u('value')) + self.assertEqual(Datum({'key': 'value'}).to_msgpack(), + d.to_msgpack()) def test_invalid_add_string(self): d = Datum() @@ -51,14 +52,14 @@ class DatumTest(unittest.TestCase): def test_add_number(self): d = Datum() d.add_number('key', 1.0) - self.assertEquals(Datum({'key': 1.0}).to_msgpack(), - d.to_msgpack()) + self.assertEqual(Datum({'key': 1.0}).to_msgpack(), + d.to_msgpack()) def test_add_int(self): d = Datum() d.add_number('key', 1) - self.assertEquals(Datum({'key': 1.0}).to_msgpack(), - d.to_msgpack()) + self.assertEqual(Datum({'key': 1.0}).to_msgpack(), + d.to_msgpack()) def test_invalid_add_number(self): d = Datum() @@ -67,9 +68,9 @@ class DatumTest(unittest.TestCase): def test_add_binary(self): d = Datum() - d.add_binary('key', 'value') - self.assertEquals( - ([], [], [['key', 'value']]), + d.add_binary('key', b('value')) + self.assertEqual( + ([], [], [['key', b('value')]]), d.to_msgpack()) def test_invalid_add_binary(self): @@ -81,9 +82,9 @@ class DatumTest(unittest.TestCase): d = Datum() d.add_string('name', 'john') d.add_number('age', 20) - d.add_binary('image', '0101') - self.assertEquals('datum{string_values: [[\'name\', \'john\']], num_values: [[\'age\', 20.0]], binary_values: [[\'image\', \'0101\']]}', - str(d)) + d.add_binary('image', b('0101')) + s = str(d) + self.assertTrue('datum{string_values: [[\'name\', \'john\']], num_values: [[\'age\', 20.0]], binary_values: [[\'image\', \'0101\']]}' == s or 'datum{string_values: [[\'name\', \'john\']], num_values: [[\'age\', 20.0]], binary_values: [[\'image\', b\'0101\']]}' == s) if __name__ == '__main__': unittest.main() diff --git a/test/jubatus_test/common/message_string_generator_test.py b/test/jubatus_test/common/test_message_string_generator.py similarity index 75% rename from test/jubatus_test/common/message_string_generator_test.py rename to test/jubatus_test/common/test_message_string_generator.py index 567e7ab..a096917 100644 --- a/test/jubatus_test/common/message_string_generator_test.py +++ b/test/jubatus_test/common/test_message_string_generator.py @@ -8,14 +8,14 @@ class MessageStringGeneratorTest(unittest.TestCase): gen = MessageStringGenerator() gen.open("test") gen.close() - self.assertEquals("test{}", gen.to_string()) + self.assertEqual("test{}", gen.to_string()) def testOne(self): gen = MessageStringGenerator() gen.open("test") gen.add("k1", "v1") gen.close() - self.assertEquals("test{k1: v1}", gen.to_string()) + self.assertEqual("test{k1: v1}", gen.to_string()) def testTwo(self): gen = MessageStringGenerator() @@ -23,14 +23,14 @@ class MessageStringGeneratorTest(unittest.TestCase): gen.add("k1", "v1") gen.add("k2", "v2") gen.close() - self.assertEquals("test{k1: v1, k2: v2}", gen.to_string()) + self.assertEqual("test{k1: v1, k2: v2}", gen.to_string()) def testNumber(self): gen = MessageStringGenerator() gen.open("test") gen.add("k1", 1) gen.close() - self.assertEquals("test{k1: 1}", gen.to_string()) + self.assertEqual("test{k1: 1}", gen.to_string()) if __name__ == '__main__': unittest.main() diff --git a/test/jubatus_test/common/types_test.py b/test/jubatus_test/common/test_types.py similarity index 83% rename from test/jubatus_test/common/types_test.py rename to test/jubatus_test/common/test_types.py index 41d6d6a..39a2f54 100644 --- a/test/jubatus_test/common/types_test.py +++ b/test/jubatus_test/common/test_types.py @@ -1,10 +1,11 @@ from jubatus.common import * +from jubatus.common.compat import u, b import unittest class TypeCheckTest(unittest.TestCase): def assertTypeOf(self, type, value): - self.assertEquals(value, type.from_msgpack(value)) - self.assertEquals(value, type.to_msgpack(value)) + self.assertEqual(value, type.from_msgpack(value)) + self.assertEqual(value, type.to_msgpack(value)) def assertTypeError(self, type, value): self.assertRaises(TypeError, lambda: type.from_msgpack(value)) @@ -19,14 +20,20 @@ class TypeCheckTest(unittest.TestCase): self.assertTypeError(TInt(True, 1), None) self.assertTypeError(TInt(True, 1), "") self.assertValueError(TInt(True, 1), 128) + self.assertValueError(TInt(True, 1), 1 << 40) self.assertValueError(TInt(True, 1), -129) self.assertValueError(TInt(False, 1), 256) self.assertValueError(TInt(False, 1), -1) + def testLong(self): + self.assertTypeOf(TInt(True, 8), 1) + self.assertTypeOf(TInt(True, 8), 1 << 40) + def testFloat(self): self.assertTypeOf(TFloat(), 1.3) self.assertTypeError(TFloat(), None) self.assertTypeError(TFloat(), 1) + self.assertTypeError(TFloat(), 1 << 40) def testBool(self): self.assertTypeOf(TBool(), True) @@ -34,13 +41,13 @@ class TypeCheckTest(unittest.TestCase): self.assertTypeError(TBool(), 1) def testString(self): + #self.assertTypeOf(TString(), b("test")) self.assertTypeOf(TString(), "test") - self.assertTypeOf(TString(), u"test") self.assertTypeError(TString(), 1) def testRaw(self): - self.assertTypeOf(TRaw(), "test") - self.assertTypeError(TRaw(), u"test") + self.assertTypeOf(TRaw(), b("test")) + self.assertTypeError(TRaw(), u("test")) self.assertTypeError(TRaw(), 1) def testNullable(self): @@ -61,10 +68,10 @@ class TypeCheckTest(unittest.TestCase): def testTuple(self): typ = TTuple(TInt(True, 8), TTuple(TString(), TInt(True, 8))) - self.assertEquals( + self.assertEqual( [1, ["test", 1]], typ.to_msgpack((1, ("test", 1)))) - self.assertEquals( + self.assertEqual( (1, ("test", 1)), typ.from_msgpack((1, ("test", 1)))) self.assertTypeError(TTuple(TInt(True, 8)), ("test", )) @@ -90,7 +97,7 @@ class TypeCheckTest(unittest.TestCase): typ = TUserDef(MyType) obj = typ.from_msgpack(("hoge", 1.0)) self.assertTrue(isinstance(obj, MyType)) - self.assertEquals(["hoge", 1.0], typ.to_msgpack(obj)) + self.assertEqual(["hoge", 1.0], typ.to_msgpack(obj)) self.assertTypeError(typ, 1) self.assertTypeError(typ, []) diff --git a/test/jubatus_test/test_util.py b/test/jubatus_test/test_util.py index 7de706d..8009a22 100644 --- a/test/jubatus_test/test_util.py +++ b/test/jubatus_test/test_util.py @@ -19,7 +19,7 @@ class TestUtil: try: cli.call("dummy") raise Exception("dummy rpc succeeded") - except RPCError, e: + except RPCError as e: if e.args[0] == 1: # "no such method" return True # ... means server is fully up return False @@ -34,7 +34,7 @@ class TestUtil: return if proc.poll(): stderr = proc.stderr.read() - raise Exception('Cannot run server process: \n' + stderr) + raise Exception('Cannot run server process: \n{0}'.format(stderr)) sleep_time *= 2; raise Exception("cannot connect") @@ -53,7 +53,7 @@ class TestUtil: raise Exception('Cannot run server process: \n' + stderr) return proc except OSError as error: - print 'Unable to fork. Error: %d (%s)' % (error.errno, error.strerror) + print('Unable to fork. Error: {0} ({1})'.format(error.errno, error.strerror)) raise error @staticmethod
{ "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": 2, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 5 }
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": null, "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
exceptiongroup==1.2.2 iniconfig==2.1.0 -e git+https://github.com/jubatus/jubatus-python-client.git@8cc1289e7ecb5729a951c55d6783122fd6fa2434#egg=jubatus msgpack-python==0.5.6 msgpack-rpc-python==0.4.1 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1 tornado==4.5.3
name: jubatus-python-client 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 - msgpack-python==0.5.6 - msgpack-rpc-python==0.4.1 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 - tornado==4.5.3 prefix: /opt/conda/envs/jubatus-python-client
[ "test/jubatus_test/common/test_client.py::ClientTest::test_remote_error", "test/jubatus_test/common/test_client.py::ClientTest::test_type_mismatch", "test/jubatus_test/common/test_client.py::ClientTest::test_unknown_method", "test/jubatus_test/common/test_client.py::ClientTest::test_wrong_number_of_arguments", "test/jubatus_test/common/test_datum.py::DatumTest::test_add_binary", "test/jubatus_test/common/test_datum.py::DatumTest::test_add_int", "test/jubatus_test/common/test_datum.py::DatumTest::test_add_number", "test/jubatus_test/common/test_datum.py::DatumTest::test_add_string", "test/jubatus_test/common/test_datum.py::DatumTest::test_empty", "test/jubatus_test/common/test_datum.py::DatumTest::test_invalid_add_binary", "test/jubatus_test/common/test_datum.py::DatumTest::test_invalid_add_number", "test/jubatus_test/common/test_datum.py::DatumTest::test_invalid_add_string", "test/jubatus_test/common/test_datum.py::DatumTest::test_invalid_key", "test/jubatus_test/common/test_datum.py::DatumTest::test_invalid_value", "test/jubatus_test/common/test_datum.py::DatumTest::test_pack", "test/jubatus_test/common/test_datum.py::DatumTest::test_str", "test/jubatus_test/common/test_datum.py::DatumTest::test_unpack", "test/jubatus_test/common/test_message_string_generator.py::MessageStringGeneratorTest::testEmpty", "test/jubatus_test/common/test_message_string_generator.py::MessageStringGeneratorTest::testNumber", "test/jubatus_test/common/test_message_string_generator.py::MessageStringGeneratorTest::testOne", "test/jubatus_test/common/test_message_string_generator.py::MessageStringGeneratorTest::testTwo", "test/jubatus_test/common/test_types.py::TypeCheckTest::testBool", "test/jubatus_test/common/test_types.py::TypeCheckTest::testFloat", "test/jubatus_test/common/test_types.py::TypeCheckTest::testInt", "test/jubatus_test/common/test_types.py::TypeCheckTest::testList", "test/jubatus_test/common/test_types.py::TypeCheckTest::testLong", "test/jubatus_test/common/test_types.py::TypeCheckTest::testMap", "test/jubatus_test/common/test_types.py::TypeCheckTest::testNullable", "test/jubatus_test/common/test_types.py::TypeCheckTest::testRaw", "test/jubatus_test/common/test_types.py::TypeCheckTest::testString", "test/jubatus_test/common/test_types.py::TypeCheckTest::testTuple", "test/jubatus_test/common/test_types.py::TypeCheckTest::testUserDef" ]
[]
[]
[]
MIT License
0
[ "jubatus/common/client.py", "jubatus/common/types.py", "setup.py", "jubatus/common/compat.py", "jubatus/common/__init__.py", "jubatus/common/datum.py" ]
[ "jubatus/common/client.py", "jubatus/common/types.py", "setup.py", "jubatus/common/compat.py", "jubatus/common/__init__.py", "jubatus/common/datum.py" ]
msgpack__msgpack-python-105
c43fb48724049dc35c34fd389091e384dec46bb8
2014-06-23 13:48:00
0e2021d3a3d1218ca191f4e802df0af3bbfaa51f
diff --git a/.travis.yml b/.travis.yml index b9d19c1..dad7e87 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,6 +7,13 @@ language: python python: - 2.7 +env: + - TOXENV=py26-c,py27-c + - TOXENV=py32-c,py33-c,py34-c + - TOXENV=py26-pure,py27-pure + - TOXENV=py32-pure,py33-pure,py34-pure + - TOXENV=pypy-pure,pypy3-pure + install: - pip install wheel tox - ls -la wheelhouse diff --git a/msgpack/_unpacker.pyx b/msgpack/_unpacker.pyx index 16de40f..f5e7d95 100644 --- a/msgpack/_unpacker.pyx +++ b/msgpack/_unpacker.pyx @@ -28,6 +28,11 @@ cdef extern from "unpack.h": PyObject* ext_hook char *encoding char *unicode_errors + Py_ssize_t max_str_len + Py_ssize_t max_bin_len + Py_ssize_t max_array_len + Py_ssize_t max_map_len + Py_ssize_t max_ext_len ctypedef struct unpack_context: msgpack_user user @@ -46,10 +51,18 @@ cdef extern from "unpack.h": cdef inline init_ctx(unpack_context *ctx, object object_hook, object object_pairs_hook, object list_hook, object ext_hook, - bint use_list, char* encoding, char* unicode_errors): + bint use_list, char* encoding, char* unicode_errors, + Py_ssize_t max_str_len, Py_ssize_t max_bin_len, + Py_ssize_t max_array_len, Py_ssize_t max_map_len, + Py_ssize_t max_ext_len): unpack_init(ctx) ctx.user.use_list = use_list ctx.user.object_hook = ctx.user.list_hook = <PyObject*>NULL + ctx.user.max_str_len = max_str_len + ctx.user.max_bin_len = max_bin_len + ctx.user.max_array_len = max_array_len + ctx.user.max_map_len = max_map_len + ctx.user.max_ext_len = max_ext_len if object_hook is not None and object_pairs_hook is not None: raise TypeError("object_pairs_hook and object_hook are mutually exclusive.") @@ -85,7 +98,12 @@ def default_read_extended_type(typecode, data): def unpackb(object packed, object object_hook=None, object list_hook=None, bint use_list=1, encoding=None, unicode_errors="strict", - object_pairs_hook=None, ext_hook=ExtType): + object_pairs_hook=None, ext_hook=ExtType, + Py_ssize_t max_str_len=2147483647, # 2**32-1 + Py_ssize_t max_bin_len=2147483647, + Py_ssize_t max_array_len=2147483647, + Py_ssize_t max_map_len=2147483647, + Py_ssize_t max_ext_len=2147483647): """ Unpack packed_bytes to object. Returns an unpacked object. @@ -115,7 +133,8 @@ def unpackb(object packed, object object_hook=None, object list_hook=None, cerr = PyBytes_AsString(unicode_errors) init_ctx(&ctx, object_hook, object_pairs_hook, list_hook, ext_hook, - use_list, cenc, cerr) + use_list, cenc, cerr, + max_str_len, max_bin_len, max_array_len, max_map_len, max_ext_len) ret = unpack_construct(&ctx, buf, buf_len, &off) if ret == 1: obj = unpack_data(&ctx) @@ -144,8 +163,7 @@ def unpack(object stream, object object_hook=None, object list_hook=None, cdef class Unpacker(object): - """ - Streaming unpacker. + """Streaming unpacker. arguments: @@ -183,6 +201,19 @@ cdef class Unpacker(object): Raises `BufferFull` exception when it is insufficient. You shoud set this parameter when unpacking data from untrasted source. + :param int max_str_len: + Limits max length of str. (default: 2**31-1) + + :param int max_bin_len: + Limits max length of bin. (default: 2**31-1) + + :param int max_array_len: + Limits max length of array. (default: 2**31-1) + + :param int max_map_len: + Limits max length of map. (default: 2**31-1) + + example of streaming deserialize from file-like object:: unpacker = Unpacker(file_like) @@ -220,8 +251,13 @@ cdef class Unpacker(object): def __init__(self, file_like=None, Py_ssize_t read_size=0, bint use_list=1, object object_hook=None, object object_pairs_hook=None, object list_hook=None, - str encoding=None, str unicode_errors='strict', int max_buffer_size=0, - object ext_hook=ExtType): + encoding=None, unicode_errors='strict', int max_buffer_size=0, + object ext_hook=ExtType, + Py_ssize_t max_str_len=2147483647, # 2**32-1 + Py_ssize_t max_bin_len=2147483647, + Py_ssize_t max_array_len=2147483647, + Py_ssize_t max_map_len=2147483647, + Py_ssize_t max_ext_len=2147483647): cdef char *cenc=NULL, cdef char *cerr=NULL @@ -253,19 +289,25 @@ cdef class Unpacker(object): if encoding is not None: if isinstance(encoding, unicode): self.encoding = encoding.encode('ascii') - else: + elif isinstance(encoding, bytes): self.encoding = encoding + else: + raise TypeError("encoding should be bytes or unicode") cenc = PyBytes_AsString(self.encoding) if unicode_errors is not None: if isinstance(unicode_errors, unicode): self.unicode_errors = unicode_errors.encode('ascii') - else: + elif isinstance(unicode_errors, bytes): self.unicode_errors = unicode_errors + else: + raise TypeError("unicode_errors should be bytes or unicode") cerr = PyBytes_AsString(self.unicode_errors) init_ctx(&self.ctx, object_hook, object_pairs_hook, list_hook, - ext_hook, use_list, cenc, cerr) + ext_hook, use_list, cenc, cerr, + max_str_len, max_bin_len, max_array_len, + max_map_len, max_ext_len) def feed(self, object next_bytes): """Append `next_bytes` to internal buffer.""" @@ -365,7 +407,7 @@ cdef class Unpacker(object): raise ValueError("Unpack failed: error = %d" % (ret,)) def read_bytes(self, Py_ssize_t nbytes): - """read a specified number of raw bytes from the stream""" + """Read a specified number of raw bytes from the stream""" cdef size_t nread nread = min(self.buf_tail - self.buf_head, nbytes) ret = PyBytes_FromStringAndSize(self.buf + self.buf_head, nread) @@ -375,8 +417,7 @@ cdef class Unpacker(object): return ret def unpack(self, object write_bytes=None): - """ - unpack one object + """Unpack one object If write_bytes is not None, it will be called with parts of the raw message as it is unpacked. @@ -386,8 +427,7 @@ cdef class Unpacker(object): return self._unpack(unpack_construct, write_bytes) def skip(self, object write_bytes=None): - """ - read and ignore one object, returning None + """Read and ignore one object, returning None If write_bytes is not None, it will be called with parts of the raw message as it is unpacked. diff --git a/msgpack/fallback.py b/msgpack/fallback.py index 71fa7be..d1f39d1 100644 --- a/msgpack/fallback.py +++ b/msgpack/fallback.py @@ -102,62 +102,84 @@ def unpackb(packed, **kwargs): class Unpacker(object): - """ - Streaming unpacker. + """Streaming unpacker. + + arguments: - `file_like` is a file-like object having a `.read(n)` method. - When `Unpacker` is initialized with a `file_like`, `.feed()` is not - usable. + :param file_like: + File-like object having `.read(n)` method. + If specified, unpacker reads serialized data from it and :meth:`feed()` is not usable. - `read_size` is used for `file_like.read(read_size)`. + :param int read_size: + Used as `file_like.read(read_size)`. (default: `min(1024**2, max_buffer_size)`) - If `use_list` is True (default), msgpack lists are deserialized to Python - lists. Otherwise they are deserialized to tuples. + :param bool use_list: + If true, unpack msgpack array to Python list. + Otherwise, unpack to Python tuple. (default: True) - `object_hook` is the same as in simplejson. If it is not None, it should - be callable and Unpacker calls it with a dict argument after deserializing - a map. + :param callable object_hook: + When specified, it should be callable. + Unpacker calls it with a dict argument after unpacking msgpack map. + (See also simplejson) - `object_pairs_hook` is the same as in simplejson. If it is not None, it - should be callable and Unpacker calls it with a list of key-value pairs - after deserializing a map. + :param callable object_pairs_hook: + When specified, it should be callable. + Unpacker calls it with a list of key-value pairs after unpacking msgpack map. + (See also simplejson) - `ext_hook` is callback for ext (User defined) type. It called with two - arguments: (code, bytes). default: `msgpack.ExtType` + :param str encoding: + Encoding used for decoding msgpack raw. + If it is None (default), msgpack raw is deserialized to Python bytes. - `encoding` is the encoding used for decoding msgpack bytes. If it is - None (default), msgpack bytes are deserialized to Python bytes. + :param str unicode_errors: + Used for decoding msgpack raw with *encoding*. + (default: `'strict'`) - `unicode_errors` is used for decoding bytes. + :param int max_buffer_size: + Limits size of data waiting unpacked. 0 means system's INT_MAX (default). + Raises `BufferFull` exception when it is insufficient. + You shoud set this parameter when unpacking data from untrasted source. - `max_buffer_size` limits the buffer size. 0 means INT_MAX (default). + :param int max_str_len: + Limits max length of str. (default: 2**31-1) - Raises `BufferFull` exception when it is unsufficient. + :param int max_bin_len: + Limits max length of bin. (default: 2**31-1) - You should set this parameter when unpacking data from an untrustred source. + :param int max_array_len: + Limits max length of array. (default: 2**31-1) - example of streaming deserialization from file-like object:: + :param int max_map_len: + Limits max length of map. (default: 2**31-1) + + + example of streaming deserialize from file-like object:: unpacker = Unpacker(file_like) for o in unpacker: - do_something(o) + process(o) - example of streaming deserialization from socket:: + example of streaming deserialize from socket:: unpacker = Unpacker() - while 1: - buf = sock.recv(1024*2) + while True: + buf = sock.recv(1024**2) if not buf: break unpacker.feed(buf) for o in unpacker: - do_something(o) + process(o) """ def __init__(self, file_like=None, read_size=0, use_list=True, object_hook=None, object_pairs_hook=None, list_hook=None, encoding=None, unicode_errors='strict', max_buffer_size=0, - ext_hook=ExtType): + ext_hook=ExtType, + max_str_len=2147483647, # 2**32-1 + max_bin_len=2147483647, + max_array_len=2147483647, + max_map_len=2147483647, + max_ext_len=2147483647): if file_like is None: self._fb_feeding = True else: @@ -185,6 +207,11 @@ class Unpacker(object): self._object_hook = object_hook self._object_pairs_hook = object_pairs_hook self._ext_hook = ext_hook + self._max_str_len = max_str_len + self._max_bin_len = max_bin_len + self._max_array_len = max_array_len + self._max_map_len = max_map_len + self._max_ext_len = max_ext_len if list_hook is not None and not callable(list_hook): raise TypeError('`list_hook` is not callable') @@ -316,12 +343,18 @@ class Unpacker(object): n = b & 0b00011111 obj = self._fb_read(n, write_bytes) typ = TYPE_RAW + if n > self._max_str_len: + raise ValueError("%s exceeds max_str_len(%s)", n, self._max_str_len) elif b & 0b11110000 == 0b10010000: n = b & 0b00001111 typ = TYPE_ARRAY + if n > self._max_array_len: + raise ValueError("%s exceeds max_array_len(%s)", n, self._max_array_len) elif b & 0b11110000 == 0b10000000: n = b & 0b00001111 typ = TYPE_MAP + if n > self._max_map_len: + raise ValueError("%s exceeds max_map_len(%s)", n, self._max_map_len) elif b == 0xc0: obj = None elif b == 0xc2: @@ -331,26 +364,38 @@ class Unpacker(object): elif b == 0xc4: typ = TYPE_BIN n = struct.unpack("B", self._fb_read(1, write_bytes))[0] + if n > self._max_bin_len: + raise ValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len)) obj = self._fb_read(n, write_bytes) elif b == 0xc5: typ = TYPE_BIN n = struct.unpack(">H", self._fb_read(2, write_bytes))[0] + if n > self._max_bin_len: + raise ValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len)) obj = self._fb_read(n, write_bytes) elif b == 0xc6: typ = TYPE_BIN n = struct.unpack(">I", self._fb_read(4, write_bytes))[0] + if n > self._max_bin_len: + raise ValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len)) obj = self._fb_read(n, write_bytes) elif b == 0xc7: # ext 8 typ = TYPE_EXT L, n = struct.unpack('Bb', self._fb_read(2, write_bytes)) + if L > self._max_ext_len: + raise ValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len)) obj = self._fb_read(L, write_bytes) elif b == 0xc8: # ext 16 typ = TYPE_EXT L, n = struct.unpack('>Hb', self._fb_read(3, write_bytes)) + if L > self._max_ext_len: + raise ValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len)) obj = self._fb_read(L, write_bytes) elif b == 0xc9: # ext 32 typ = TYPE_EXT L, n = struct.unpack('>Ib', self._fb_read(5, write_bytes)) + if L > self._max_ext_len: + raise ValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len)) obj = self._fb_read(L, write_bytes) elif b == 0xca: obj = struct.unpack(">f", self._fb_read(4, write_bytes))[0] @@ -374,42 +419,66 @@ class Unpacker(object): obj = struct.unpack(">q", self._fb_read(8, write_bytes))[0] elif b == 0xd4: # fixext 1 typ = TYPE_EXT + if self._max_ext_len < 1: + raise ValueError("%s exceeds max_ext_len(%s)" % (1, self._max_ext_len)) n, obj = struct.unpack('b1s', self._fb_read(2, write_bytes)) elif b == 0xd5: # fixext 2 typ = TYPE_EXT + if self._max_ext_len < 2: + raise ValueError("%s exceeds max_ext_len(%s)" % (2, self._max_ext_len)) n, obj = struct.unpack('b2s', self._fb_read(3, write_bytes)) elif b == 0xd6: # fixext 4 typ = TYPE_EXT + if self._max_ext_len < 4: + raise ValueError("%s exceeds max_ext_len(%s)" % (4, self._max_ext_len)) n, obj = struct.unpack('b4s', self._fb_read(5, write_bytes)) elif b == 0xd7: # fixext 8 typ = TYPE_EXT + if self._max_ext_len < 8: + raise ValueError("%s exceeds max_ext_len(%s)" % (8, self._max_ext_len)) n, obj = struct.unpack('b8s', self._fb_read(9, write_bytes)) elif b == 0xd8: # fixext 16 typ = TYPE_EXT + if self._max_ext_len < 16: + raise ValueError("%s exceeds max_ext_len(%s)" % (16, self._max_ext_len)) n, obj = struct.unpack('b16s', self._fb_read(17, write_bytes)) elif b == 0xd9: typ = TYPE_RAW n = struct.unpack("B", self._fb_read(1, write_bytes))[0] + if n > self._max_str_len: + raise ValueError("%s exceeds max_str_len(%s)", n, self._max_str_len) obj = self._fb_read(n, write_bytes) elif b == 0xda: typ = TYPE_RAW n = struct.unpack(">H", self._fb_read(2, write_bytes))[0] + if n > self._max_str_len: + raise ValueError("%s exceeds max_str_len(%s)", n, self._max_str_len) obj = self._fb_read(n, write_bytes) elif b == 0xdb: typ = TYPE_RAW n = struct.unpack(">I", self._fb_read(4, write_bytes))[0] + if n > self._max_str_len: + raise ValueError("%s exceeds max_str_len(%s)", n, self._max_str_len) obj = self._fb_read(n, write_bytes) elif b == 0xdc: n = struct.unpack(">H", self._fb_read(2, write_bytes))[0] + if n > self._max_array_len: + raise ValueError("%s exceeds max_array_len(%s)", n, self._max_array_len) typ = TYPE_ARRAY elif b == 0xdd: n = struct.unpack(">I", self._fb_read(4, write_bytes))[0] + if n > self._max_array_len: + raise ValueError("%s exceeds max_array_len(%s)", n, self._max_array_len) typ = TYPE_ARRAY elif b == 0xde: n = struct.unpack(">H", self._fb_read(2, write_bytes))[0] + if n > self._max_map_len: + raise ValueError("%s exceeds max_map_len(%s)", n, self._max_map_len) typ = TYPE_MAP elif b == 0xdf: n = struct.unpack(">I", self._fb_read(4, write_bytes))[0] + if n > self._max_map_len: + raise ValueError("%s exceeds max_map_len(%s)", n, self._max_map_len) typ = TYPE_MAP else: raise UnpackValueError("Unknown header: 0x%x" % b) diff --git a/msgpack/unpack.h b/msgpack/unpack.h index 24045d5..5deb7cd 100644 --- a/msgpack/unpack.h +++ b/msgpack/unpack.h @@ -27,6 +27,7 @@ typedef struct unpack_user { PyObject *ext_hook; const char *encoding; const char *unicode_errors; + Py_ssize_t max_str_len, max_bin_len, max_array_len, max_map_len, max_ext_len; } unpack_user; typedef PyObject* msgpack_unpack_object; @@ -68,7 +69,7 @@ static inline int unpack_callback_uint64(unpack_user* u, uint64_t d, msgpack_unp if (d > LONG_MAX) { p = PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)d); } else { - p = PyInt_FromLong((long)d); + p = PyInt_FromSize_t((size_t)d); } if (!p) return -1; @@ -132,6 +133,10 @@ static inline int unpack_callback_false(unpack_user* u, msgpack_unpack_object* o static inline int unpack_callback_array(unpack_user* u, unsigned int n, msgpack_unpack_object* o) { + if (n > u->max_array_len) { + PyErr_Format(PyExc_ValueError, "%u exceeds max_array_len(%zd)", n, u->max_array_len); + return -1; + } PyObject *p = u->use_list ? PyList_New(n) : PyTuple_New(n); if (!p) @@ -163,6 +168,10 @@ static inline int unpack_callback_array_end(unpack_user* u, msgpack_unpack_objec static inline int unpack_callback_map(unpack_user* u, unsigned int n, msgpack_unpack_object* o) { + if (n > u->max_map_len) { + PyErr_Format(PyExc_ValueError, "%u exceeds max_map_len(%zd)", n, u->max_map_len); + return -1; + } PyObject *p; if (u->has_pairs_hook) { p = PyList_New(n); // Or use tuple? @@ -210,6 +219,11 @@ static inline int unpack_callback_map_end(unpack_user* u, msgpack_unpack_object* static inline int unpack_callback_raw(unpack_user* u, const char* b, const char* p, unsigned int l, msgpack_unpack_object* o) { + if (l > u->max_str_len) { + PyErr_Format(PyExc_ValueError, "%u exceeds max_str_len(%zd)", l, u->max_str_len); + return -1; + } + PyObject *py; if(u->encoding) { py = PyUnicode_Decode(p, l, u->encoding, u->unicode_errors); @@ -224,6 +238,11 @@ static inline int unpack_callback_raw(unpack_user* u, const char* b, const char* static inline int unpack_callback_bin(unpack_user* u, const char* b, const char* p, unsigned int l, msgpack_unpack_object* o) { + if (l > u->max_bin_len) { + PyErr_Format(PyExc_ValueError, "%u exceeds max_bin_len(%zd)", l, u->max_bin_len); + return -1; + } + PyObject *py = PyBytes_FromStringAndSize(p, l); if (!py) return -1; @@ -232,7 +251,7 @@ static inline int unpack_callback_bin(unpack_user* u, const char* b, const char* } static inline int unpack_callback_ext(unpack_user* u, const char* base, const char* pos, - unsigned int lenght, msgpack_unpack_object* o) + unsigned int length, msgpack_unpack_object* o) { PyObject *py; int8_t typecode = (int8_t)*pos++; @@ -240,11 +259,15 @@ static inline int unpack_callback_ext(unpack_user* u, const char* base, const ch PyErr_SetString(PyExc_AssertionError, "u->ext_hook cannot be NULL"); return -1; } - // length also includes the typecode, so the actual data is lenght-1 + if (length-1 > u->max_ext_len) { + PyErr_Format(PyExc_ValueError, "%u exceeds max_ext_len(%zd)", length, u->max_ext_len); + return -1; + } + // length also includes the typecode, so the actual data is length-1 #if PY_MAJOR_VERSION == 2 - py = PyObject_CallFunction(u->ext_hook, "(is#)", typecode, pos, lenght-1); + py = PyObject_CallFunction(u->ext_hook, "(is#)", typecode, pos, length-1); #else - py = PyObject_CallFunction(u->ext_hook, "(iy#)", typecode, pos, lenght-1); + py = PyObject_CallFunction(u->ext_hook, "(iy#)", typecode, pos, length-1); #endif if (!py) return -1; diff --git a/tox.ini b/tox.ini index 7971dc7..15feb51 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = {py26,py27,py32,py33,py34}-{c,pure},{pypy,pypy3}-pure +envlist = {py26,py27,py32,py33,py34}-{c,pure},{pypy,pypy3}-pure,py27-x86,py34-x86 [variants:pure] setenv= @@ -11,6 +11,29 @@ deps= changedir=test commands= - c: python -c 'from msgpack import _packer, _unpacker' - c: py.test + c,x86: python -c 'from msgpack import _packer, _unpacker' + c,x86: py.test pure: py.test + +[testenv:py27-x86] +basepython=python2.7-x86 +deps= + pytest + +changedir=test +commands= + python -c 'import sys; print(hex(sys.maxsize))' + python -c 'from msgpack import _packer, _unpacker' + py.test + +[testenv:py34-x86] +basepython=python3.4-x86 +deps= + pytest + +changedir=test +commands= + python -c 'import sys; print(hex(sys.maxsize))' + python -c 'from msgpack import _packer, _unpacker' + py.test +
msgpack.loads hangs for a long time on invalid input Minimal reproducible example: ``` from msgpack import loads # ---------------------- Array 32 # | ----------- Large number # | | --- No other data # | | | # v v v s = "\xdd\xff\x00\x00\x00" loads(s) ``` Function `loads` in this example consumes a lot of memory and will have failed years later. And looks like `str 32` and `map 32` are not affected.
msgpack/msgpack-python
diff --git a/test/test_limits.py b/test/test_limits.py index 1cfa2d6..3c1cf2a 100644 --- a/test/test_limits.py +++ b/test/test_limits.py @@ -3,7 +3,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals import pytest -from msgpack import packb, unpackb, Packer +from msgpack import packb, unpackb, Packer, Unpacker, ExtType def test_integer(): @@ -32,6 +32,77 @@ def test_map_header(): packer.pack_array_header(2**32) +def test_max_str_len(): + d = 'x' * 3 + packed = packb(d) + + unpacker = Unpacker(max_str_len=3, encoding='utf-8') + unpacker.feed(packed) + assert unpacker.unpack() == d + + unpacker = Unpacker(max_str_len=2, encoding='utf-8') + with pytest.raises(ValueError): + unpacker.feed(packed) + unpacker.unpack() + + +def test_max_bin_len(): + d = b'x' * 3 + packed = packb(d, use_bin_type=True) + + unpacker = Unpacker(max_bin_len=3) + unpacker.feed(packed) + assert unpacker.unpack() == d + + unpacker = Unpacker(max_bin_len=2) + with pytest.raises(ValueError): + unpacker.feed(packed) + unpacker.unpack() + + +def test_max_array_len(): + d = [1,2,3] + packed = packb(d) + + unpacker = Unpacker(max_array_len=3) + unpacker.feed(packed) + assert unpacker.unpack() == d + + unpacker = Unpacker(max_array_len=2) + with pytest.raises(ValueError): + unpacker.feed(packed) + unpacker.unpack() + + +def test_max_map_len(): + d = {1: 2, 3: 4, 5: 6} + packed = packb(d) + + unpacker = Unpacker(max_map_len=3) + unpacker.feed(packed) + assert unpacker.unpack() == d + + unpacker = Unpacker(max_map_len=2) + with pytest.raises(ValueError): + unpacker.feed(packed) + unpacker.unpack() + + +def test_max_ext_len(): + d = ExtType(42, b"abc") + packed = packb(d) + + unpacker = Unpacker(max_ext_len=3) + unpacker.feed(packed) + assert unpacker.unpack() == d + + unpacker = Unpacker(max_ext_len=2) + with pytest.raises(ValueError): + unpacker.feed(packed) + unpacker.unpack() + + + # PyPy fails following tests because of constant folding? # https://bugs.pypy.org/issue1721 #@pytest.mark.skipif(True, reason="Requires very large memory.")
{ "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": 3 }, "num_modified_files": 5 }
0.4
{ "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" }
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work -e git+https://github.com/msgpack/msgpack-python.git@c43fb48724049dc35c34fd389091e384dec46bb8#egg=msgpack_python 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: msgpack-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 - 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/msgpack-python
[ "test/test_limits.py::test_max_str_len", "test/test_limits.py::test_max_bin_len", "test/test_limits.py::test_max_array_len", "test/test_limits.py::test_max_map_len", "test/test_limits.py::test_max_ext_len" ]
[]
[ "test/test_limits.py::test_integer", "test/test_limits.py::test_array_header", "test/test_limits.py::test_map_header" ]
[]
Apache License 2.0
1
[ "msgpack/unpack.h", "msgpack/_unpacker.pyx", ".travis.yml", "tox.ini", "msgpack/fallback.py" ]
[ "msgpack/unpack.h", "msgpack/_unpacker.pyx", ".travis.yml", "tox.ini", "msgpack/fallback.py" ]
softlayer__softlayer-python-457
08336ac6742088cb1da14313a6579e3a47eb83e7
2014-11-24 20:17:17
200787d4c3bf37bc4e701caf6a52e24dd07d18a3
sudorandom: @underscorephil, @allmightyspiff Let me know your thoughts on this.
diff --git a/SoftLayer/CLI/routes.py b/SoftLayer/CLI/routes.py index 1ab13021..8c2f7a24 100644 --- a/SoftLayer/CLI/routes.py +++ b/SoftLayer/CLI/routes.py @@ -142,7 +142,6 @@ ('server:detail', 'SoftLayer.CLI.server.detail:cli'), ('server:edit', 'SoftLayer.CLI.server.edit:cli'), ('server:list', 'SoftLayer.CLI.server.list:cli'), - ('server:list-chassis', 'SoftLayer.CLI.server.list_chassis:cli'), ('server:nic-edit', 'SoftLayer.CLI.server.nic_edit:cli'), ('server:power-cycle', 'SoftLayer.CLI.server.power:power_cycle'), ('server:power-off', 'SoftLayer.CLI.server.power:power_off'), diff --git a/SoftLayer/CLI/server/__init__.py b/SoftLayer/CLI/server/__init__.py index 0482f419..72e2e2ff 100644 --- a/SoftLayer/CLI/server/__init__.py +++ b/SoftLayer/CLI/server/__init__.py @@ -1,209 +1,1 @@ """Hardware servers.""" -import re - - -def get_create_options(ds_options, section, pretty=True): - """Parse bare metal instance creation options. - - This method can be used to parse the bare metal instance creation - options into different sections. This can be useful for data validation - as well as printing the options on a help screen. - - :param dict ds_options: The instance options to parse. Must come from - the .get_bare_metal_create_options() function - in the HardwareManager. - :param string section: The section to parse out. - :param bool pretty: If true, it will return the results in a 'pretty' - format that's easier to print. - """ - return_value = None - - if 'datacenter' == section: - datacenters = [loc['keyname'] - for loc in ds_options['locations']] - return_value = [('datacenter', datacenters)] - elif 'cpu' == section and 'server' in ds_options['categories']: - results = [] - - for item in ds_options['categories']['server']['items']: - results.append(( - item['description'], - item['price_id'] - )) - - return_value = results - elif 'memory' == section and 'ram' in ds_options['categories']: - ram = [] - for option in ds_options['categories']['ram']['items']: - ram.append((int(option['capacity']), option['price_id'])) - - return_value = [('memory', ram)] - elif ('server_core' == section - and 'server_core' in ds_options['categories']): - mem_options = {} - cpu_regex = re.compile(r'(\d+) x ') - memory_regex = re.compile(r' - (\d+) GB Ram', re.I) - - for item in ds_options['categories']['server_core']['items']: - cpu = cpu_regex.search(item['description']).group(1) - memory = memory_regex.search(item['description']).group(1) - - if cpu and memory: - if memory not in mem_options: - mem_options[memory] = [] - - mem_options[memory].append((cpu, item['price_id'])) - - results = [] - for memory in sorted(mem_options.keys(), key=int): - key = memory - - if pretty: - key = memory - - results.append((key, mem_options[memory])) - - return_value = results - elif 'os' == section: - os_regex = re.compile(r'(^[A-Za-z\s\/\-]+) ([\d\.]+)') - bit_regex = re.compile(r' \((\d+)\s*bit') - extra_regex = re.compile(r' - (.+)\(') - - os_list = {} - flat_list = [] - - # Loop through the operating systems and get their OS codes - for opsys in ds_options['categories']['os']['items']: - if 'Windows Server' in opsys['description']: - os_code = _generate_windows_code(opsys['description']) - else: - os_results = os_regex.search(opsys['description']) - - # Skip this operating system if it's not parsable - if os_results is None: - continue - - name = os_results.group(1) - version = os_results.group(2) - bits = bit_regex.search(opsys['description']) - extra_info = extra_regex.search(opsys['description']) - - if bits: - bits = bits.group(1) - if extra_info: - extra_info = extra_info.group(1) - - os_code = _generate_os_code(name, version, bits, extra_info) - - name = os_code.split('_')[0] - - if name not in os_list: - os_list[name] = [] - - os_list[name].append((os_code, opsys['price_id'])) - flat_list.append((os_code, opsys['price_id'])) - - if pretty: - results = [] - for opsys in sorted(os_list.keys()): - results.append(('os (%s)' % opsys, os_list[opsys])) - - return_value = results - else: - return_value = [('os', flat_list)] - - elif 'disk' == section: - disks = [] - type_regex = re.compile(r'^[\d\.\s]+[GT]B\s+(.+)$') - for disk in ds_options['categories']['disk0']['items']: - disk_type = 'SATA' - if type_regex.match(disk['description']) is not None: - disk_type = type_regex.match(disk['description']).group(1) - disk_type = disk_type.replace('RPM', '').strip() - disk_type = disk_type.replace(' ', '_').upper() - disk_type = str(int(disk['capacity'])) + '_' + disk_type - disks.append((disk_type, disk['price_id'], disk['id'])) - - return_value = [('disk', disks)] - elif 'nic' == section: - single = [] - dual = [] - - for item in ds_options['categories']['port_speed']['items']: - if 'dual' in item['description'].lower(): - dual.append((str(int(item['capacity'])) + '_DUAL', - item['price_id'])) - else: - single.append((str(int(item['capacity'])), - item['price_id'])) - - return_value = [('single nic', single), ('dual nic', dual)] - elif 'disk_controller' == section: - options = [] - for item in ds_options['categories']['disk_controller']['items']: - text = item['description'].replace(' ', '') - - if 'Non-RAID' == text: - text = 'None' - - options.append((text, item['price_id'])) - - return_value = [('disk_controllers', options)] - - return return_value - - -def _generate_os_code(name, version, bits, extra_info): - """Encapsulates the code for generating the operating system code.""" - name = name.replace(' Linux', '') - name = name.replace('Enterprise', '') - name = name.replace('GNU/Linux', '') - - os_code = name.strip().replace(' ', '_').upper() - - if os_code.startswith('RED_HAT'): - os_code = 'REDHAT' - - if 'UBUNTU' in os_code: - version = re.sub(r'\.\d+', '', version) - - os_code += '_' + version.replace('.0', '') - - if bits: - os_code += '_' + bits - - if extra_info: - garbage = ['Install', '(32 bit)', '(64 bit)'] - - for obj in garbage: - extra_info = extra_info.replace(obj, '') - - os_code += '_' + extra_info.strip().replace(' ', '_').upper() - - return os_code - - -def _generate_windows_code(description): - """Generates OS codes for windows.""" - version_check = re.search(r'Windows Server (\d+)', description) - version = version_check.group(1) - - os_code = 'WIN_' + version - - if 'Datacenter' in description: - os_code += '-DC' - elif 'Enterprise' in description: - os_code += '-ENT' - else: - os_code += '-STD' - - if 'ith R2' in description: - os_code += '-R2' - elif 'ith Hyper-V' in description: - os_code += '-HYPERV' - - bit_check = re.search(r'\((\d+)\s*bit', description) - if bit_check: - os_code += '_' + bit_check.group(1) - - return os_code diff --git a/SoftLayer/CLI/server/create.py b/SoftLayer/CLI/server/create.py index 156f8cf2..f1f67de3 100644 --- a/SoftLayer/CLI/server/create.py +++ b/SoftLayer/CLI/server/create.py @@ -6,63 +6,25 @@ from SoftLayer.CLI import exceptions from SoftLayer.CLI import formatting from SoftLayer.CLI import helpers -from SoftLayer.CLI import server from SoftLayer.CLI import template import click [email protected](epilog="""See 'sl server list-chassis' and - 'sl server create-options' for valid options.""") [email protected]('--domain', '-D', - help="Domain portion of the FQDN") [email protected]('--hostname', '-H', - help="Host portion of the FQDN") [email protected]('--chassis', - required=True, - help="The chassis to use for the new server") [email protected]('--cpu', '-c', - help="Number of CPU cores", - type=click.INT) [email protected]('--memory', '-m', - help="Memory in mebibytes", - type=click.INT) [email protected]('--os', '-o', - help="OS install code. Tip: you can specify <OS>_LATEST") [email protected](epilog="""See 'sl server create-options' for valid options.""") [email protected]('--domain', '-D', help="Domain portion of the FQDN") [email protected]('--hostname', '-H', help="Host portion of the FQDN") [email protected]('--size', '-s', help="Hardware size") [email protected]('--os', '-o', help="OS install code") [email protected]('--datacenter', '-d', help="Datacenter shortname") [email protected]('--port-speed', type=click.INT, help="Port speeds") @click.option('--billing', type=click.Choice(['hourly', 'monthly']), - default='monthly', - help="""Billing rate. -The hourly rate is only available on bare metal instances""") [email protected]('--datacenter', '-d', help="Datacenter shortname") [email protected]('--dedicated/--public', - is_flag=True, - help="Create a dedicated Virtual Server (Private Node)") [email protected]('--san', - is_flag=True, - help="Use SAN storage instead of local disk.") [email protected]('--test', - is_flag=True, - help="Do not actually create the virtual server") [email protected]('--export', - type=click.Path(writable=True, resolve_path=True), - help="Exports options to a template file") + default='hourly', + help="Billing rate") @click.option('--postinstall', '-i', help="Post-install script to download") @helpers.multi_option('--key', '-k', help="SSH keys to add to the root user") [email protected]_option('--disk', help="Disk sizes") [email protected]('--controller', help="The RAID configuration for the server") [email protected]('--private', - is_flag=True, - help="Forces the VS to only have access the private network") [email protected]('--network', '-n', help="Network port speed in Mbps") [email protected]('--template', '-t', - help="A template file that defaults the command-line options", - type=click.Path(exists=True, readable=True, resolve_path=True)) [email protected]('--userdata', '-u', help="User defined metadata string") [email protected]('--userfile', '-F', - help="Read userdata from file", - type=click.Path(exists=True, readable=True, resolve_path=True)) @click.option('--vlan-public', help="The ID of the public VLAN on which you want the virtual " "server placed", @@ -71,6 +33,16 @@ help="The ID of the private VLAN on which you want the virtual " "server placed", type=click.INT) [email protected]_option('--extra', '-e', help="Extra options") [email protected]('--test', + is_flag=True, + help="Do not actually create the virtual server") [email protected]('--template', '-t', + help="A template file that defaults the command-line options", + type=click.Path(exists=True, readable=True, resolve_path=True)) [email protected]('--export', + type=click.Path(writable=True, resolve_path=True), + help="Exports options to a template file") @click.option('--wait', type=click.INT, help="Wait until the server is finished provisioning for up to " @@ -79,12 +51,31 @@ def cli(env, **args): """Order/create a dedicated server.""" - template.update_with_template_args(args, list_args=['disk', 'key']) + template.update_with_template_args(args, list_args=['key']) mgr = SoftLayer.HardwareManager(env.client) - ds_options = mgr.get_dedicated_server_create_options(args['chassis']) + # Get the SSH keys + ssh_keys = [] + for key in args.get('key'): + resolver = SoftLayer.SshKeyManager(env.client).resolve_ids + key_id = helpers.resolve_id(resolver, key, 'SshKey') + ssh_keys.append(key_id) - order = _process_args(env, args, ds_options) + order = { + 'hostname': args['hostname'], + 'domain': args['domain'], + 'size': args['size'], + 'public_vlan': args.get('vlan_public'), + 'private_vlan': args.get('vlan_private'), + 'location': args.get('datacenter'), + 'ssh_keys': ssh_keys, + 'post_uri': args.get('postinstall'), + 'os': args['os'], + 'hourly': args.get('billing') == 'hourly', + 'port_speed': args.get('port_speed'), + 'no_public': args.get('no_public') or False, + 'extras': args.get('extra'), + } # Do not create hardware server with --test or --export do_create = not (args['export'] or args['test']) @@ -134,158 +125,3 @@ def cli(env, **args): output = table return output - - -def _process_args(env, args, ds_options): - """Convert CLI arguments to VSManager.create_hardware arguments.""" - mgr = SoftLayer.HardwareManager(env.client) - - order = { - 'hostname': args['hostname'], - 'domain': args['domain'], - 'bare_metal': False, - 'package_id': args['chassis'], - } - - # Determine if this is a "Bare Metal Instance" or regular server - bmc = False - if args['chassis'] == str(mgr.get_bare_metal_package_id()): - bmc = True - - # Convert the OS code back into a price ID - os_price = _get_price_id_from_options(ds_options, 'os', args['os']) - - if os_price: - order['os'] = os_price - else: - raise exceptions.CLIAbort('Invalid operating system specified.') - - order['location'] = args['datacenter'] - - if bmc: - order['server'] = _get_cpu_and_memory_price_ids(ds_options, - args['cpu'], - args['memory']) - order['bare_metal'] = True - - if args['billing'] == 'hourly': - order['hourly'] = True - else: - order['server'] = args['cpu'] - order['ram'] = _get_price_id_from_options( - ds_options, 'memory', int(args['memory'])) - - # Set the disk sizes - disk_prices = [] - disk_number = 0 - for disk in args.get('disk'): - disk_price = _get_disk_price(ds_options, disk, disk_number) - disk_number += 1 - if disk_price: - disk_prices.append(disk_price) - - if not disk_prices: - disk_prices.append(_get_default_value(ds_options, 'disk0')) - - order['disks'] = disk_prices - - # Set the disk controller price - if not bmc: - if args.get('controller'): - dc_price = _get_price_id_from_options(ds_options, - 'disk_controller', - args.get('controller')) - else: - dc_price = _get_price_id_from_options(ds_options, - 'disk_controller', - 'None') - - order['disk_controller'] = dc_price - - # Set the port speed - port_speed = args.get('network') - - nic_price = _get_price_id_from_options(ds_options, 'nic', port_speed) - - if nic_price: - order['port_speed'] = nic_price - else: - raise exceptions.CLIAbort('Invalid NIC speed specified.') - - if args.get('postinstall'): - order['post_uri'] = args.get('postinstall') - - # Get the SSH keys - if args.get('key'): - keys = [] - for key in args.get('key'): - resolver = SoftLayer.SshKeyManager(env.client).resolve_ids - key_id = helpers.resolve_id(resolver, key, 'SshKey') - keys.append(key_id) - order['ssh_keys'] = keys - - if args.get('vlan_public'): - order['public_vlan'] = args['vlan_public'] - - if args.get('vlan_private'): - order['private_vlan'] = args['vlan_private'] - - return order - - -def _get_default_value(ds_options, option): - """Returns a 'free' price id given an option.""" - if option not in ds_options['categories']: - return - - for item in ds_options['categories'][option]['items']: - if not any([ - float(item.get('setupFee', 0)), - float(item.get('recurringFee', 0)), - float(item.get('hourlyRecurringFee', 0)), - float(item.get('oneTimeFee', 0)), - float(item.get('laborFee', 0)), - ]): - return item['price_id'] - - -def _get_disk_price(ds_options, value, number): - """Returns a price id that matches a given disk config.""" - if not number: - return _get_price_id_from_options(ds_options, 'disk', value) - # This will get the item ID for the matching identifier string, which - # we can then use to get the price ID for our specific disk - item_id = _get_price_id_from_options(ds_options, 'disk', value, True) - key = 'disk' + str(number) - if key in ds_options['categories']: - for item in ds_options['categories'][key]['items']: - if item['id'] == item_id: - return item['price_id'] - - -def _get_cpu_and_memory_price_ids(ds_options, cpu_value, memory_value): - """Returns a price id for a cpu/memory pair in pre-configured servers. - - (formerly known as BMC). - """ - for memory, options in server.get_create_options(ds_options, - 'server_core', - False): - if int(memory) == int(memory_value): - for cpu_size, price_id in options: - if int(cpu_size) == int(cpu_value): - return price_id - - raise exceptions.CLIAbort('No price found for CPU/Memory combination') - - -def _get_price_id_from_options(ds_options, option, value, item_id=False): - """Returns a price_id for a given option and value.""" - - for _, options in server.get_create_options(ds_options, option, False): - for item_options in options: - if item_options[0] == value: - if not item_id: - return item_options[1] - return item_options[2] - raise exceptions.CLIAbort('No price found for %s' % option) diff --git a/SoftLayer/CLI/server/create_options.py b/SoftLayer/CLI/server/create_options.py index d1d266c5..5e0ce7f1 100644 --- a/SoftLayer/CLI/server/create_options.py +++ b/SoftLayer/CLI/server/create_options.py @@ -1,106 +1,55 @@ """Server order options for a given chassis.""" # :license: MIT, see LICENSE for more details. -import os - -import SoftLayer from SoftLayer.CLI import environment -from SoftLayer.CLI import exceptions from SoftLayer.CLI import formatting -from SoftLayer.CLI import server +from SoftLayer.managers import hardware import click @click.command() [email protected]('chassis-id') @environment.pass_env -def cli(env, chassis_id): +def cli(env): """Server order options for a given chassis.""" - mgr = SoftLayer.HardwareManager(env.client) - - table = formatting.KeyValueTable(['Name', 'Value']) - table.align['Name'] = 'r' - table.align['Value'] = 'l' - - found = False - for chassis in mgr.get_available_dedicated_server_packages(): - if chassis_id == str(chassis[0]): - found = True - break - - if not found: - raise exceptions.CLIAbort('Invalid chassis specified.') - - ds_options = mgr.get_dedicated_server_create_options(chassis_id) - - # Determine if this is a "Bare Metal Instance" or regular server - bmc = False - if chassis_id == str(mgr.get_bare_metal_package_id()): - bmc = True - - results = server.get_create_options(ds_options, 'datacenter')[0] - table.add_row([results[0], formatting.listing(sorted(results[1]))]) - - # BMC options - if bmc: - # CPU and memory options - results = server.get_create_options(ds_options, 'server_core') - memory_cpu_table = formatting.Table(['memory', 'cpu']) - for result in results: - memory_cpu_table.add_row([ - result[0], - formatting.listing( - [item[0] for item in sorted( - result[1], key=lambda x: int(x[0]) - )])]) - table.add_row(['memory/cpu', memory_cpu_table]) - - # Normal hardware options - else: - # CPU options - results = server.get_create_options(ds_options, 'cpu') - cpu_table = formatting.Table(['ID', 'Description']) - cpu_table.align['ID'] = 'r' - cpu_table.align['Description'] = 'l' - - for result in sorted(results, key=lambda x: x[1]): - cpu_table.add_row([result[1], result[0]]) - table.add_row(['cpu', cpu_table]) - - # Memory options - results = server.get_create_options(ds_options, 'memory')[0] - table.add_row([results[0], formatting.listing( - item[0] for item in sorted(results[1]))]) - - # Disk controller options - results = server.get_create_options(ds_options, 'disk_controller')[0] - table.add_row([results[0], formatting.listing( - item[0] for item in sorted(results[1],))]) - - # Disk options - results = server.get_create_options(ds_options, 'disk')[0] - table.add_row([ - results[0], - formatting.listing( - [item[0] for item in sorted(results[1])], - separator=os.linesep - )]) - - # Operating system options - results = server.get_create_options(ds_options, 'os') - for result in results: - table.add_row([ - result[0], - formatting.listing( - [item[0] for item in sorted(result[1])], - separator=os.linesep - )]) - - # NIC options - results = server.get_create_options(ds_options, 'nic') - for result in results: - table.add_row([result[0], formatting.listing( - item[0] for item in sorted(result[1],))]) - - return table + hardware_manager = hardware.HardwareManager(env.client) + options = hardware_manager.get_create_options() + + tables = [] + + # Datacenters + dc_table = formatting.Table(['datacenter', 'value']) + dc_table.sortby = 'value' + for location in options['locations']: + dc_table.add_row([location['name'], location['key']]) + tables.append(dc_table) + + # Presets + preset_table = formatting.Table(['size', 'value']) + preset_table.sortby = 'value' + for size in options['sizes']: + preset_table.add_row([size['name'], size['key']]) + tables.append(preset_table) + + # Operating systems + os_table = formatting.Table(['operating_system', 'value']) + os_table.sortby = 'value' + for operating_system in options['operating_systems']: + os_table.add_row([operating_system['name'], operating_system['key']]) + tables.append(os_table) + + # Port speed + port_speed_table = formatting.Table(['port_speed', 'value']) + port_speed_table.sortby = 'value' + for speed in options['port_speeds']: + port_speed_table.add_row([speed['name'], speed['key']]) + tables.append(port_speed_table) + + # Extras + extras_table = formatting.Table(['extras', 'value']) + extras_table.sortby = 'value' + for extra in options['extras']: + extras_table.add_row([extra['name'], extra['key']]) + tables.append(extras_table) + + return formatting.listing(tables, separator='\n') diff --git a/SoftLayer/CLI/server/list_chassis.py b/SoftLayer/CLI/server/list_chassis.py deleted file mode 100644 index 638c9e5e..00000000 --- a/SoftLayer/CLI/server/list_chassis.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Display a list of available chassis.""" -# :license: MIT, see LICENSE for more details. - -import SoftLayer -from SoftLayer.CLI import environment -from SoftLayer.CLI import formatting - -import click - - [email protected]() [email protected]_env -def cli(env): - """Display a list of available chassis.""" - - table = formatting.Table(['code', 'chassis']) - table.align['code'] = 'r' - table.align['chassis'] = 'l' - - mgr = SoftLayer.HardwareManager(env.client) - chassis_list = mgr.get_available_dedicated_server_packages() - - for code, name, _ in chassis_list: - table.add_row([code, name]) - - return table diff --git a/SoftLayer/CLI/virt/create.py b/SoftLayer/CLI/virt/create.py index 369b33b2..0bf4fca1 100644 --- a/SoftLayer/CLI/virt/create.py +++ b/SoftLayer/CLI/virt/create.py @@ -25,7 +25,7 @@ @click.option('--billing', type=click.Choice(['hourly', 'monthly']), default='hourly', - help="""Billing rate""") + help="Billing rate") @click.option('--datacenter', '-d', help="Datacenter shortname") @click.option('--dedicated/--public', is_flag=True, @@ -114,7 +114,7 @@ def cli(env, **args): total = total_monthly billing_rate = 'monthly' - if args.get('hourly'): + if args.get('billing') == 'hourly': billing_rate = 'hourly' table.add_row(['Total %s cost' % billing_rate, "%.2f" % total]) output.append(table) diff --git a/SoftLayer/managers/hardware.py b/SoftLayer/managers/hardware.py index 434890e2..1a1e350f 100644 --- a/SoftLayer/managers/hardware.py +++ b/SoftLayer/managers/hardware.py @@ -7,11 +7,16 @@ """ import socket +import SoftLayer from SoftLayer.managers import ordering from SoftLayer import utils # Invalid names are ignored due to long method names and short argument names # pylint: disable=invalid-name, no-self-use +EXTRA_CATEGORIES = ['pri_ipv6_addresses', + 'static_ipv6_addresses', + 'sec_ip_addresses'] + class HardwareManager(utils.IdentifierMixin, object): """Manage hardware devices. @@ -169,86 +174,6 @@ def list_hardware(self, tags=None, cpus=None, memory=None, hostname=None, kwargs['filter'] = _filter.to_dict() return self.account.getHardware(**kwargs) - def get_bare_metal_create_options(self): - """Retrieves the available options for creating a bare metal server. - - :returns: A dictionary of creation options. The categories to order are - contained within the 'categories' key. See - :func:`_parse_package_data` for detailed information. - - .. note:: - - The information for ordering bare metal instances comes from - multiple API calls. In order to make the process easier, this - function will make those calls and reformat the results into a - dictionary that's easier to manage. It's recommended that you cache - these results with a reasonable lifetime for performance reasons. - """ - hw_id = self.get_bare_metal_package_id() - - if not hw_id: - return None - - return self._parse_package_data(hw_id) - - def get_bare_metal_package_id(self): - """Return the bare metal package id.""" - ordering_manager = self.ordering_manager - mask = "mask[id,name,description,type[keyName]]" - package = ordering_manager.get_package_by_type('BARE_METAL_CORE', mask) - - return package['id'] - - def get_available_dedicated_server_packages(self): - """Retrieves a list of packages for ordering dedicated servers. - - :returns: A list of tuples of available dedicated server packages in - the form (id, name, description) - """ - available_packages = [] - ordering_manager = self.ordering_manager - - mask = 'id,name,description,type,isActive' - package_types = ['BARE_METAL_CPU', - 'BARE_METAL_CORE'] - - packages = ordering_manager.get_packages_of_type(package_types, - mask) - # We only want packages that are active (we can place new orders for) - # and non-outlet. - # Outlet packages require specialized logic and we don't want to deal - # with them right now. - packages = ordering_manager.get_only_active_packages(packages) - packages = ordering_manager.filter_outlet_packages(packages) - - for package in packages: - available_packages.append((package['id'], package['name'], - package.get('description', None))) - - return available_packages - - def get_dedicated_server_create_options(self, package_id): - """Returns chassis-specific options for creating a dedicated server. - - The chassis is based on package ID. - - :param int package_id: The package ID to retrieve the creation options - for. This should come from - :func:`get_available_dedicated_server_packages`. - :returns: A dictionary of creation options. The categories to order are - contained within the 'categories' key. See - :func:`_parse_package_data` for detailed information. - - .. note:: - - The information for ordering dedicated servers comes from multiple - API calls. In order to make the process simpler, this function will - make those calls and reformat the results into a dictionary that's - easier to manage. It's recommended that you cache these results with - a reasonable lifetime for performance reasons. - """ - return self._parse_package_data(package_id) - def get_hardware(self, hardware_id, **kwargs): """Get details about a hardware device. @@ -345,104 +270,24 @@ def change_port_speed(self, hardware_id, public, speed): def place_order(self, **kwargs): """Places an order for a piece of hardware. - Translates a list of arguments into a dictionary necessary for creating - a server. - - .. warning:: - All items here must be price IDs, NOT quantities! - - :param int server: The identification string for the server to - order. This will either be the CPU/Memory - combination ID for bare metal instances or the - CPU model for dedicated servers. - :param string hostname: The hostname to use for the new server. - :param string domain: The domain to use for the new server. - :param bool hourly: Flag to indicate if this server should be billed - hourly (default) or monthly. Only applies to bare - metal instances. - :param string location: The location string (data center) for the - server - :param int os: The operating system to use - :param array disks: An array of disks for the server. Disks will be - added in the order specified. - :param int port_speed: The port speed for the server. - :param bool bare_metal: Flag to indicate if this is a bare metal server - or a dedicated server (default). - :param int ram: The amount of RAM to order. Only applies to dedicated - servers. - :param int package_id: The package_id to use for the server. This - should either be a chassis ID for dedicated - servers or the bare metal instance package ID, - which can be obtained by calling - get_bare_metal_package_id - :param int disk_controller: The disk controller to use. - :param list ssh_keys: The SSH keys to add to the root user - :param int public_vlan: The ID of the public VLAN on which you want - this server placed. - :param int private_vlan: The ID of the public VLAN on which you want - this server placed. + See get_create_options() for valid arguments. + + :param string size: server size name + :param string hostname: server hostname + :param string domain: server domain name + :param string location: location (datacenter) name + :param string os: operating system name + :param int port_speed: Port speed in Mbps + :param list ssh_keys: list of ssh key ids + :param int public_vlan: public vlan id + :param int private_vlan: private vlan id :param string post_uri: The URI of the post-install script to run after reload - - .. warning:: - Due to how the ordering structure currently works, all ordering - takes place using price IDs rather than quantities. See the - following sample for an example of using HardwareManager functions - for ordering a basic server. - - :: - - # client is assumed to be an initialized SoftLayer.API.Client object - mgr = HardwareManager(client) - - # Package ID 32 corresponds to the 'Quad Processor, Quad Core Intel' - # package. This information can be obtained from the - # :func:`get_available_dedicated_server_packages` function. - options = mgr.get_dedicated_server_create_options(32) - - # Review the contents of options to find the information that - # applies to your order. For the sake of this example, we assume - # that your selections are a series of item IDs for each category - # organized into a key-value dictionary. - - # This contains selections for all required categories - selections = { - 'server': 542, # Quad Processor Quad Core Intel 7310 - 1.60GHz - 'pri_ip_addresses': 15, # 1 IP Address - 'notification': 51, # Email and Ticket - 'ram': 280, # 16 GB FB-DIMM Registered 533/667 - 'bandwidth': 173, # 5000 GB Bandwidth - 'lockbox': 45, # 1 GB Lockbox - 'monitoring': 49, # Host Ping - 'disk0': 14, # 500GB SATA II (for the first disk) - 'response': 52, # Automated Notification - 'port_speed': 187, # 100 Mbps Public & Private Networks - 'power_supply': 469, # Redundant Power Supplies - 'disk_controller': 487, # Non-RAID - 'vulnerability_scanner': 307, # Nessus - 'vpn_management': 309, # Unlimited SSL VPN Users - 'remote_management': 504, # Reboot / KVM over IP - 'os': 4166, # Ubuntu Linux 12.04 LTS Precise Pangolin (64 bit) - } - - args = { - 'location': 'FIRST_AVAILABLE', # Pick the first available DC - 'packageId': 32, # From above - 'disks': [], - } - - for cat, item_id in selections: - for item in options['categories'][cat]['items'].items(): - if item['id'] == item_id: - if 'disk' not in cat or 'disk_controller' == cat: - args[cat] = item['price_id'] - else: - args['disks'].append(item['price_id']) - - # You can call :func:`verify_order` here to test the order instead - # of actually placing it if you prefer. - result = mgr.place_order(**args) - + :param boolean hourly: True if using hourly pricing (default). + False for monthly. + :param boolean no_public: True if this server should only have private + interfaces + :param list extras: List of extra feature names """ create_options = self._generate_create_dict(**kwargs) return self.client['Product_Order'].placeOrder(create_options) @@ -474,53 +319,127 @@ def get_cancellation_reasons(self): 'moving': 'Moving to competitor', } - def _generate_create_dict( - self, server=None, hostname=None, domain=None, hourly=False, - location=None, os=None, disks=None, port_speed=None, - bare_metal=None, ram=None, package_id=None, disk_controller=None, - ssh_keys=None, public_vlan=None, private_vlan=None, post_uri=None): - """Translates arguments into a dictionary for creating a server. - - .. warning:: - All items here must be price IDs, NOT quantities! - - :param int server: The identification string for the server to - order. This will either be the CPU/Memory - combination ID for bare metal instances or the - CPU model for dedicated servers. - :param string hostname: The hostname to use for the new server. - :param string domain: The domain to use for the new server. - :param bool hourly: Flag to indicate if this server should be billed - hourly (default) or monthly. Only applies to bare - metal instances. - :param string location: The location string (data center) for the - server - :param int os: The operating system to use - :param array disks: An array of disks for the server. Disks will be - added in the order specified. - :param int port_speed: The port speed for the server. - :param bool bare_metal: Flag to indicate if this is a bare metal server - or a dedicated server (default). - :param int ram: The amount of RAM to order. Only applies to dedicated - servers. - :param int package_id: The package_id to use for the server. This - should either be a chassis ID for dedicated - servers or the bare metal instance package ID, - which can be obtained by calling - get_bare_metal_package_id - :param int disk_controller: The disk controller to use. - :param list ssh_keys: The SSH keys to add to the root user - :param int public_vlan: The ID of the public VLAN on which you want - this server placed. - :param int private_vlan: The ID of the public VLAN on which you want - this server placed. - """ - arguments = ['server', 'hostname', 'domain', 'location', 'os', 'disks', - 'port_speed', 'bare_metal', 'ram', 'package_id', - 'disk_controller', 'server_core', 'disk0'] + def get_create_options(self): + """Returns valid options for ordering hardware.""" + + package = self._get_package() + + # Locations + locations = [] + for region in package['regions']: + locations.append({ + 'name': region['location']['location']['longName'], + 'key': region['location']['location']['name'], + }) + + # Sizes + sizes = [] + for preset in package['activePresets']: + sizes.append({ + 'name': preset['description'], + 'key': preset['keyName'] + }) + + # Operating systems + operating_systems = [] + for item in package['items']: + if item['itemCategory']['categoryCode'] == 'os': + operating_systems.append({ + 'name': item['softwareDescription']['longDescription'], + 'key': item['softwareDescription']['referenceCode'], + }) + + # Port speeds + port_speeds = [] + for item in package['items']: + if all([item['itemCategory']['categoryCode'] == 'port_speed', + not _is_private_port_speed_item(item)]): + port_speeds.append({ + 'name': item['description'], + 'key': item['capacity'], + }) + + # Extras + extras = [] + for item in package['items']: + if item['itemCategory']['categoryCode'] in EXTRA_CATEGORIES: + extras.append({ + 'name': item['description'], + 'key': item['keyName'] + }) + + return { + 'locations': locations, + 'sizes': sizes, + 'operating_systems': operating_systems, + 'port_speeds': port_speeds, + 'extras': extras, + } + + def _get_package(self): + """Get the package related to simple hardware ordering.""" + mask = ''' +items[ + keyName, + capacity, + description, + attributes[id,attributeTypeKeyName], + itemCategory[id,categoryCode], + softwareDescription[id,referenceCode,longDescription], + prices +], +activePresets, +regions[location[location]] +''' + + package_type = 'BARE_METAL_CPU_FAST_PROVISION' + packages = self.ordering_manager.get_packages_of_type([package_type], + mask=mask) + if len(packages) != 1: + raise SoftLayer.SoftLayerError("Ordering package not found") + + return packages[0] + + def _generate_create_dict(self, + size=None, + hostname=None, + domain=None, + location=None, + os=None, + port_speed=None, + ssh_keys=None, + public_vlan=None, + private_vlan=None, + post_uri=None, + hourly=True, + no_public=False, + extras=None): + """Translates arguments into a dictionary for creating a server.""" + + extras = extras or [] + + package = self._get_package() + + prices = [] + for category in ['pri_ip_addresses', + 'vpn_management', + 'remote_management']: + prices.append(_get_default_price_id(package['items'], + category, + hourly)) + + prices.append(_get_os_price_id(package['items'], os)) + prices.append(_get_bandwidth_price_id(package['items'], + hourly=hourly, + no_public=no_public)) + prices.append(_get_port_speed_price_id(package['items'], + port_speed, + no_public)) + + for extra in extras: + prices.append(_get_extra_price_id(package['items'], extra, hourly)) hardware = { - 'bareMetalInstanceFlag': bare_metal, 'hostname': hostname, 'domain': domain, } @@ -534,8 +453,11 @@ def _generate_create_dict( order = { 'hardware': [hardware], - 'location': location, - 'prices': [], + 'location': _get_location_key(package, location), + 'prices': [{'id': price} for price in prices], + 'packageId': package['id'], + 'presetId': _get_preset_id(package, size), + 'useHourlyPricing': hourly, } if post_uri: @@ -544,49 +466,6 @@ def _generate_create_dict( if ssh_keys: order['sshKeys'] = [{'sshKeyIds': ssh_keys}] - if bare_metal: - order['packageId'] = self.get_bare_metal_package_id() - order['prices'].append({'id': int(server)}) - p_options = self.get_bare_metal_create_options() - if hourly: - order['useHourlyPricing'] = True - else: - order['packageId'] = package_id - order['prices'].append({'id': int(server)}) - p_options = self.get_dedicated_server_create_options(package_id) - - if disks: - for disk in disks: - order['prices'].append({'id': int(disk)}) - - if os: - order['prices'].append({'id': int(os)}) - - if port_speed: - order['prices'].append({'id': int(port_speed)}) - - if ram: - order['prices'].append({'id': int(ram)}) - - if disk_controller: - order['prices'].append({'id': int(disk_controller)}) - - # Find all remaining required categories so we can auto-default them - required_fields = [] - for category, data in p_options['categories'].items(): - if data.get('is_required') and category not in arguments: - if 'disk' in category: - # This block makes sure that we can default unspecified - # disks if the user hasn't specified enough. - disk_count = int(category.replace('disk', '')) - if len(disks) >= disk_count + 1: - continue - required_fields.append(category) - - for category in required_fields: - price = get_default_value(p_options, category, hourly=hourly) - order['prices'].append({'id': price}) - return order def _get_ids_from_hostname(self, hostname): @@ -611,108 +490,6 @@ def _get_ids_from_ip(self, ip): if results: return [result['id'] for result in results] - def _parse_package_data(self, package_id): - """Parses data from the specified package into a consistent dictionary. - - The data returned by the API varies significantly from one package - to another, which means that consuming it can make your program more - complicated than desired. This function will make all necessary API - calls for the specified package ID and build the results into a - consistently formatted dictionary like so: - - result = { - 'locations': [{'delivery_information': <string>, - 'keyname': <string>, - 'long_name': <string>}], - 'categories': { - 'category_code': { - 'sort': <int>, - 'step': <int>, - 'is_required': <bool>, - 'name': <string>, - 'group': <string>, - 'items': [ - { - 'id': <int>, - 'description': <string>, - 'sort': <int>, - 'price_id': <int>, - 'recurring_fee': <float>, - 'setup_fee': <float>, - 'hourly_recurring_fee': <float>, - 'one_time_fee': <float>, - 'labor_fee': <float>, - 'capacity': <float>, - } - ] - } - } - } - - Your code can rely upon each of those elements always being present. - Each list will contain at least one entry as well, though most will - contain more than one. - """ - package = self.client['Product_Package'] - - results = { - 'categories': {}, - 'locations': [] - } - - # First pull the list of available locations. We do it with the - # getObject() call so that we get access to the delivery time info. - object_data = package.getRegions(id=package_id) - - for loc in object_data: - details = loc['location']['locationPackageDetails'][0] - - results['locations'].append({ - 'delivery_information': details.get('deliveryTimeInformation'), - 'keyname': loc['keyname'], - 'long_name': loc['description'], - }) - - mask = 'mask[itemCategory[group]]' - - for config in package.getConfiguration(id=package_id, mask=mask): - code = config['itemCategory']['categoryCode'] - group = utils.NestedDict(config['itemCategory']) or {} - category = { - 'sort': config['sort'], - 'step': config['orderStepId'], - 'is_required': config['isRequired'], - 'name': config['itemCategory']['name'], - 'group': group['group']['name'], - 'items': [], - } - - results['categories'][code] = category - - # Now pull in the available package item - for category in package.getCategories(id=package_id): - code = category['categoryCode'] - items = [] - - for group in category['groups']: - for price in group['prices']: - items.append({ - 'id': price['itemId'], - 'description': price['item']['description'], - 'sort': price['sort'], - 'price_id': price['id'], - 'recurring_fee': price.get('recurringFee'), - 'setup_fee': price.get('setupFee'), - 'hourly_recurring_fee': - price.get('hourlyRecurringFee'), - 'one_time_fee': price.get('oneTimeFee'), - 'labor_fee': price.get('laborFee'), - 'capacity': float(price['item'].get('capacity', 0)), - }) - results['categories'][code]['items'] = items - - return results - def edit(self, hardware_id, userdata=None, hostname=None, domain=None, notes=None): """Edit hostname, domain name, notes, user data of the hardware. @@ -769,36 +546,131 @@ def update_firmware(self, id=hardware_id) -def get_default_value(package_options, category, hourly=False): - """Returns the default price ID for the specified category. +def _get_extra_price_id(items, key_name, hourly): + """Returns a price id attached to item with the given key_name.""" - This determination is made by parsing the items in the package_options - argument and finding the first item that has zero specified for every fee - field. + for item in items: + if not utils.lookup(item, 'keyName') == key_name: + continue - .. note:: - If the category has multiple items with no fee, this will return the - first it finds and then short circuit. This may not match the default - value presented on the SoftLayer ordering portal. Additionally, this - method will return None if there are no free items in the category. + for price in item['prices']: + if _matches_billing(price, hourly): + return price['id'] - :returns: Returns the price ID of the first free item it finds or None - if there are no free items. - """ - if category not in package_options['categories']: - return + raise SoftLayer.SoftLayerError( + "Could not find valid price for extra option, '%s'" % key_name) - for item in package_options['categories'][category]['items']: - if hourly: - if item.get('hourly_recurring_fee') is None: - continue - else: - if item.get('recurring_fee') is None: - continue - - if not any([float(item.get('setup_fee') or 0), - float(item.get('recurring_fee') or 0), - float(item.get('hourly_recurring_fee') or 0), - float(item.get('one_time_fee') or 0), - float(item.get('labor_fee') or 0)]): - return item['price_id'] + +def _get_default_price_id(items, option, hourly): + """Returns a 'free' price id given an option.""" + + for item in items: + if not utils.lookup(item, 'itemCategory', 'categoryCode') == option: + continue + + for price in item['prices']: + if all([float(price.get('hourlyRecurringFee', 0)) == 0.0, + float(price.get('recurringFee', 0)) == 0.0, + _matches_billing(price, hourly)]): + return price['id'] + + raise SoftLayer.SoftLayerError( + "Could not find valid price for '%s' option" % option) + + +def _get_bandwidth_price_id(items, hourly=True, no_public=False): + """Choose a valid price id for bandwidth.""" + + # Prefer pay-for-use data transfer with hourly + for item in items: + + capacity = float(item.get('capacity', 0)) + # Hourly and private only do pay-as-you-go bandwidth + if any([not utils.lookup(item, + 'itemCategory', + 'categoryCode') == 'bandwidth', + (hourly or no_public) and capacity != 0.0, + not (hourly or no_public) and capacity == 0.0]): + continue + + for price in item['prices']: + if _matches_billing(price, hourly): + return price['id'] + + raise SoftLayer.SoftLayerError( + "Could not find valid price for bandwidth option") + + +def _get_os_price_id(items, os): + """Returns the price id matching.""" + + for item in items: + if any([not utils.lookup(item, + 'itemCategory', + 'categoryCode') == 'os', + not utils.lookup(item, + 'softwareDescription', + 'referenceCode') == os]): + continue + + for price in item['prices']: + return price['id'] + + raise SoftLayer.SoftLayerError("Could not find valid price for os: '%s'" % + os) + + +def _get_port_speed_price_id(items, port_speed, no_public): + """Choose a valid price id for port speed.""" + + for item in items: + if not utils.lookup(item, + 'itemCategory', + 'categoryCode') == 'port_speed': + continue + + # Check for correct capacity and if the item matches private only + if any([int(utils.lookup(item, 'capacity')) != port_speed, + _is_private_port_speed_item(item) != no_public]): + continue + + for price in item['prices']: + return price['id'] + + raise SoftLayer.SoftLayerError( + "Could not find valid price for port speed: '%s'" % port_speed) + + +def _matches_billing(price, hourly): + """Return if the price object is hourly and/or monthly.""" + return any([hourly and price.get('hourlyRecurringFee') is not None, + not hourly and price.get('recurringFee') is not None]) + + +def _is_private_port_speed_item(item): + """Determine if the port speed item is private network only.""" + for attribute in item['attributes']: + if attribute['attributeTypeKeyName'] == 'IS_PRIVATE_NETWORK_ONLY': + return True + + return False + + +def _get_location_key(package, location): + """Get the longer key with a short location name.""" + for region in package['regions']: + if region['location']['location']['name'] == location: + return region['keyname'] + + raise SoftLayer.SoftLayerError("Could not find valid location for: '%s'" + % location) + + +def _get_preset_id(package, size): + """Get the preset id given the keyName of the preset.""" + for preset in package['activePresets']: + if preset['keyName'] == size: + return preset['id'] + + raise SoftLayer.SoftLayerError("Could not find valid size for: '%s'" + % size)
Hardware ordering with v4 There are now 3 different methods for ordering hardware (4, if you count Hardware_Server::createObject). They are enumerated below: * **Normal Hardware Ordering** - uses packages to define different chassis which have different CPU and memory options. Currently, prices inside the package are used to determine which numerical option (ex. 4 CPU cores) matches which price object. The package type is "BARE_METAL_CPU". * **Bare metal cloud (bmc)** - A limited set of options that was made to (ideally) be more reliable in terms of stock. Hardware_Server::createObject and Hardware_Server::getCreateObjectOptions were made to support bare metal cloud. However, in order to share as much of the existing hardware ordering code that already existed, those interfaces are not used for the CLI/Manager implementation. There are conditionals for BMC servers for ordering, option lookup and canceling. The package type is "BARE_METAL_CORE". * **Fast hardware provisioning** - Like bare metal cloud, has a limited set of options. However, this is done in a different way than BMC with the concept of order "presets". The suite of presets has its own package (200) and its own package type (BARE_METAL_CPU_FAST_PROVISION). This is currently **not** implemented in the CLI. Here are some API calls that I've found useful: ```python client['Product_Package'].getActivePresets(id=200) client['Product_Package_Preset'].getLowestPresetServerPrice(id=68) # 68 is one of the presets from the previous call. ``` This issue is to track the discussion with the goal of defining what hardware ordering should look like for the version 4 CLI. My primary question is: **Should we support all three ways of hardware ordering in the CLI and in the managers?** Would it be sufficient to only support the fast provisioning servers? Will the fast server provisioning options be implemented with createObject and getCreateObjectOptions? If we're going to support the normal way of ordering hardware, can the manager interface take more of the burden in regard to looking up price ids? Because of the way the interface is, it's impossible to improve upon the implementation without breaking things both in the python and API side.
softlayer/softlayer-python
diff --git a/SoftLayer/testing/fixtures/SoftLayer_Product_Package.py b/SoftLayer/testing/fixtures/SoftLayer_Product_Package.py index f2621766..b60b9eaa 100644 --- a/SoftLayer/testing/fixtures/SoftLayer_Product_Package.py +++ b/SoftLayer/testing/fixtures/SoftLayer_Product_Package.py @@ -1,1039 +1,186 @@ -getAllObjects = [ - {'id': 13, 'name': 'Mock Testing Package', 'description': 'a thing', - 'type': {'keyName': 'BARE_METAL_CPU'}, 'isActive': 1}, - {'id': 15, 'name': 'Inactive package', 'description': 'a cool server', - 'type': {'keyName': 'BARE_METAL_CPU'}, 'isActive': 0}, - {'id': 27, 'name': 'An additional testing category', - 'description': 'Another thing - OUTLET', - 'type': {'keyName': 'BARE_METAL_CPU'}, 'isActive': 1}, - {'id': 28, 'name': 'An outlet package', - 'description': 'Super fun package', - 'type': {'keyName': 'BARE_METAL_CPU'}, 'isActive': 1}, - {'id': 46, 'name': 'Virtual Servers', - 'description': 'Bare Metal Instance', - 'type': {'keyName': 'VIRTUAL_SERVER_INSTANCE'}, 'isActive': 1}, - {'id': 50, 'name': 'Bare Metal Instance', - 'description': 'Bare Metal Instance', - 'type': {'keyName': 'BARE_METAL_CORE'}, 'isActive': 1}, -] -getObject = getAllObjects[0] +HARDWARE_ITEMS = [ + {'attributes': [], + 'capacity': '999', + 'description': 'Unknown', + 'itemCategory': {'categoryCode': 'unknown', 'id': 325}, + 'keyName': 'UNKNOWN', + 'prices': [{'accountRestrictions': [], + 'currentPriceFlag': '', + 'hourlyRecurringFee': '0', + 'id': 1245172, + 'itemId': 935954, + 'laborFee': '0', + 'onSaleFlag': '', + 'oneTimeFee': '0', + 'quantity': '', + 'recurringFee': '0', + 'setupFee': '0', + 'sort': 0}]}, + {'attributes': [], + 'capacity': '64', + 'description': '1 IPv6 Address', + 'itemCategory': {'categoryCode': 'pri_ipv6_addresses', + 'id': 325}, + 'keyName': '1_IPV6_ADDRESS', + 'prices': [{'accountRestrictions': [], + 'currentPriceFlag': '', + 'hourlyRecurringFee': '0', + 'id': 17129, + 'itemId': 4097, + 'laborFee': '0', + 'onSaleFlag': '', + 'oneTimeFee': '0', + 'quantity': '', + 'recurringFee': '0', + 'setupFee': '0', + 'sort': 0}]}, + {'attributes': [], + 'capacity': '10', + 'description': '10 Mbps Public & Private Network Uplinks', + 'itemCategory': {'categoryCode': 'port_speed', 'id': 26}, + 'keyName': '10_MBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS', + 'prices': [{'accountRestrictions': [], + 'currentPriceFlag': '', + 'hourlyRecurringFee': '0', + 'id': 272, + 'itemId': 186, + 'laborFee': '0', + 'onSaleFlag': '', + 'oneTimeFee': '0', + 'quantity': '', + 'recurringFee': '0', + 'setupFee': '0', + 'sort': 5}]}, + {'attributes': [], + 'capacity': '0', + 'description': 'Ubuntu Linux 14.04 LTS Trusty Tahr (64 bit)', + 'itemCategory': {'categoryCode': 'os', 'id': 12}, + 'keyName': 'OS_UBUNTU_14_04_LTS_TRUSTY_TAHR_64_BIT', + 'prices': [{'accountRestrictions': [], + 'currentPriceFlag': '', + 'hourlyRecurringFee': '0', + 'id': 37650, + 'itemId': 4702, + 'laborFee': '0', + 'onSaleFlag': '', + 'oneTimeFee': '0', + 'quantity': '', + 'recurringFee': '0', + 'setupFee': '0', + 'sort': 9}], + 'softwareDescription': {'id': 1362, + 'longDescription': 'Ubuntu / 14.04-64', + 'referenceCode': 'UBUNTU_14_64'}}, + {'attributes': [], + 'capacity': '1', + 'description': '1 IP Address', + 'itemCategory': {'categoryCode': 'pri_ip_addresses', 'id': 13}, + 'keyName': '1_IP_ADDRESS', + 'prices': [{'accountRestrictions': [], + 'currentPriceFlag': '', + 'hourlyRecurringFee': '0', + 'id': 21, + 'itemId': 15, + 'laborFee': '0', + 'onSaleFlag': '', + 'oneTimeFee': '0', + 'quantity': '', + 'recurringFee': '0', + 'setupFee': '0', + 'sort': 0}]}, + {'attributes': [{'attributeTypeKeyName': 'RECLAIM_BYPASS', + 'id': 1014}], + 'description': 'Unlimited SSL VPN Users', + 'itemCategory': {'categoryCode': 'vpn_management', 'id': 31}, + 'keyName': 'SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT', + 'prices': [{'accountRestrictions': [], + 'currentPriceFlag': '', + 'hourlyRecurringFee': '0', + 'id': 420, + 'itemId': 309, + 'laborFee': '0', + 'onSaleFlag': '', + 'oneTimeFee': '0', + 'quantity': '', + 'recurringFee': '0', + 'setupFee': '0', + 'sort': 0}]}, + {'attributes': [], + 'description': 'Reboot / KVM over IP', + 'itemCategory': {'categoryCode': 'remote_management', + 'id': 46}, + 'keyName': 'REBOOT_KVM_OVER_IP', + 'prices': [{'accountRestrictions': [], + 'currentPriceFlag': '', + 'hourlyRecurringFee': '0', + 'id': 906, + 'itemId': 504, + 'laborFee': '0', + 'onSaleFlag': '', + 'oneTimeFee': '0', + 'quantity': '', + 'recurringFee': '0', + 'setupFee': '0', + 'sort': 0}]}, + {'attributes': [], + 'capacity': '0', + 'description': '0 GB Bandwidth', + 'itemCategory': {'categoryCode': 'bandwidth', 'id': 10}, + 'keyName': 'BANDWIDTH_0_GB', + 'prices': [{'accountRestrictions': [], + 'currentPriceFlag': '', + 'id': 22505, + 'itemId': 4481, + 'laborFee': '0', + 'onSaleFlag': '', + 'oneTimeFee': '0', + 'quantity': '', + 'recurringFee': '0', + 'setupFee': '0', + 'sort': 98}]}, + {'attributes': [], + 'capacity': '0', + 'description': '0 GB Bandwidth', + 'itemCategory': {'categoryCode': 'bandwidth', 'id': 10}, + 'keyName': 'BANDWIDTH_0_GB_2', + 'prices': [{'accountRestrictions': [], + 'currentPriceFlag': '', + 'hourlyRecurringFee': '0', + 'id': 1800, + 'itemId': 439, + 'laborFee': '0', + 'onSaleFlag': '', + 'oneTimeFee': '0', + 'quantity': '', + 'setupFee': '0', + 'sort': 99}]}] -getConfiguration = [ - { - 'sort': 1, - 'orderStepId': 1, - 'itemCategory': { - 'categoryCode': 'server_core', - 'name': 'Bare Metal Instance' - }, - 'isRequired': 0, - }, - { - 'itemCategory': { - 'categoryCode': 'os', - 'name': 'Operating System', - }, - 'sort': 0, - 'orderStepId': 1, - 'isRequired': 1, - }, - { - 'itemCategory': { - 'categoryCode': 'disk0', - 'name': 'First Hard Drive', - }, - 'sort': 0, - 'orderStepId': 1, - 'isRequired': 1, - }, - { - 'itemCategory': { - 'categoryCode': 'port_speed', - 'name': 'Uplink Port Speeds' - }, - 'sort': 0, - 'orderStepId': 1, - 'isRequired': 1, - }, -] + [ - { - 'itemCategory': { - 'categoryCode': 'random', - 'name': 'Random Category', - }, - 'sort': 0, - 'orderStepId': 1, - 'isRequired': 0, - }, - { - 'itemCategory': { - 'categoryCode': 'disk0', - 'name': 'First Disk', - }, - 'sort': 0, - 'orderStepId': 1, - 'isRequired': 1, - }, - { - 'itemCategory': { - 'categoryCode': 'disk1', - 'name': 'Second Disk', - }, - 'sort': 0, - 'orderStepId': 1, - 'isRequired': 1, - }, - { - 'itemCategory': { - 'categoryCode': 'os', - 'name': 'Operating System', - }, - 'sort': 0, - 'orderStepId': 1, - 'isRequired': 1, - }, - { - 'itemCategory': { - 'categoryCode': 'port_speed', - 'name': 'Uplink Port Speeds', - }, - 'sort': 2, - 'orderStepId': 1, - 'isRequired': 1, - }, - { - 'itemCategory': { - 'categoryCode': 'ram', - 'name': 'RAM', - }, - 'sort': 2, - 'orderStepId': 1, - 'isRequired': 1, - }, - { - 'itemCategory': { - 'categoryCode': 'disk_controller', - 'name': 'Disk Controller', - }, - 'sort': 2, - 'orderStepId': 1, - 'isRequired': 1, - }, - { - 'itemCategory': { - 'categoryCode': 'server', - 'name': 'Server', - }, - 'sort': 2, - 'orderStepId': 1, - 'isRequired': 1, - }, -] -getRegions = [{ - 'location': { - 'locationPackageDetails': [{ - 'deliveryTimeInformation': 'Typically 2-4 hours', - }], - }, - 'keyname': 'RANDOM_LOCATION', - 'description': 'Random unit testing location', -}] - -CATEGORY = { - 'categoryCode': 'random', - 'name': 'Random Category', -} - - -def get_server_categories_mock(): - prices = [{ - 'itemId': 888, - 'id': 1888, - 'sort': 0, - 'setupFee': 0, - 'recurringFee': 0, - 'hourlyRecurringFee': 0, - 'oneTimeFee': 0, - 'laborFee': 0, - 'item': { - 'id': 888, - 'description': 'Some item', - 'capacity': 0, - } - }] - disk0_prices = [{ - 'itemId': 2000, - 'id': 12000, - 'sort': 0, - 'setupFee': 0, - 'recurringFee': 0, - 'hourlyRecurringFee': 0, - 'oneTimeFee': 0, - 'laborFee': 0, - 'item': { - 'id': 2000, - 'description': '1TB Drive', - 'capacity': 1000, - } - }] - - disk1_prices = [{ - 'itemId': 2000, - 'id': 12000, - 'sort': 0, - 'setupFee': 0, - 'recurringFee': 0, - 'hourlyRecurringFee': 0, - 'oneTimeFee': 0, - 'laborFee': 0, - 'item': { - 'id': 2000, - 'description': '1TB Drive', - 'capacity': 1000, - } - }] - - centos_prices = [ - { - 'itemId': 3907, - 'setupFee': '0', - 'recurringFee': '0', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 0, - 'item': { - 'description': 'CentOS 6.0 (64 bit)', - 'id': 3907 - }, - 'id': 13942, - }, - ] - - debian_prices = [ - { - 'itemId': 3967, - 'setupFee': '0', - 'recurringFee': '0', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 6, - 'item': { - 'description': 'Debian GNU/Linux 6.0 Squeeze/Stable (32 bit)', - 'id': 3967 - }, - 'id': 14046, - }, - ] - - ubuntu_prices = [ - { - 'itemId': 4170, - 'setupFee': '0', - 'recurringFee': '0', - 'hourlyRecurringFee': '0', - 'oneTimeFee': '0', - 'id': 17438, - 'sort': 9, - 'item': { - 'description': 'Ubuntu Linux 12.04 LTS Precise Pangolin - ' - 'Minimal Install (64 bit)', - 'id': 4170 - }, - 'laborFee': '0', - }, - { - 'itemId': 4166, - 'setupFee': '0', - 'recurringFee': '0', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 9, - 'item': { - 'description': 'Ubuntu Linux 12.04 LTS Precise Pangolin ' - '(64 bit)', - 'id': 4166 - }, - 'id': 17430, - }, - ] - - windows_prices = [ - { - 'itemId': 977, - 'setupFee': '0', - 'recurringFee': '40', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 15, - 'item': { - 'description': 'Windows Server 2008 R2 Standard Edition ' - '(64bit)', - 'id': 977 - }, - 'id': 1858, - }, - { - 'itemId': 978, - 'setupFee': '0', - 'recurringFee': '100', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 15, - 'item': { - 'description': 'Windows Server 2008 R2 Enterprise Edition ' - '(64bit)', - 'id': 978 - }, - 'id': 1861, - }, - { - 'itemId': 980, - 'setupFee': '0', - 'recurringFee': '150', - 'hourlyRecurringFee': '.21', - 'oneTimeFee': '0', - 'id': 1867, - 'sort': 15, - 'item': { - 'description': 'Windows Server 2008 R2 Datacenter Edition ' - 'With Hyper-V (64bit)', - 'id': 980 - }, - 'laborFee': '0', - }, - { - 'itemId': 422, - 'setupFee': '0', - 'recurringFee': '40', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 18, - 'item': { - 'description': 'Windows Server 2003 Standard SP2 with R2 ' - '(64 bit)', - 'id': 422 - }, - 'id': 692, - }, - ] - - redhat_prices = [ - { - 'itemId': 3841, - 'setupFee': '0', - 'recurringFee': '0', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 10, - 'item': { - 'description': 'Red Hat Enterprise Linux - 6 (64 bit)', - 'id': 3841 - }, - 'id': 13800, - } - ] - - ram_prices = [ - { - 'itemId': 254, - 'setupFee': '0', - 'recurringFee': '0', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 0, - 'item': { - 'capacity': '4', - 'description': '4 GB DIMM Registered 533/667', - 'id': 254 - }, - 'id': 1023, - }, - { - 'itemId': 255, - 'setupFee': '0', - 'recurringFee': '30', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 0, - 'item': { - 'capacity': '6', - 'description': '6 GB DIMM Registered 533/667', - 'id': 255 - }, - 'id': 702, - }] - - server_prices = [ - { - 'itemId': 300, - 'setupFee': '0', - 'recurringFee': '125', - 'laborFee': '0', - 'oneTimeFee': '0', - 'currentPriceFlag': '', - 'sort': 2, - 'item': { - 'description': 'Dual Quad Core Pancake 200 - 1.60GHz', - 'id': 300 - }, - 'id': 723 - }, - { - 'itemId': 303, - 'setupFee': '0', - 'recurringFee': '279', - 'laborFee': '0', - 'oneTimeFee': '0', - 'currentPriceFlag': '', - 'sort': 2, - 'item': { - 'description': 'Dual Quad Core Pancake 200 - 1.80GHz', - 'id': 303 - }, - 'id': 724, - } - ] - - single_nic_prices = [ - { - 'itemId': 187, - 'setupFee': '0', - 'recurringFee': '0', - 'hourlyRecurringFee': '0', - 'oneTimeFee': '0', - 'id': 273, - 'sort': 0, - 'item': { - 'capacity': '100', - 'description': '100 Mbps Public & Private Networks', - 'id': 187 - }, - 'laborFee': '0', - }, - { - 'itemId': 188, - 'setupFee': '0', - 'recurringFee': '20', - 'hourlyRecurringFee': '.04', - 'oneTimeFee': '0', - 'id': 274, - 'sort': 0, - 'item': { - 'capacity': '1000', - 'description': '1 Gbps Public & Private Networks', - 'id': 188 - }, - 'laborFee': '0', - } - ] - - dual_nic_prices = [ - { - 'itemId': 4332, - 'setupFee': '0', - 'recurringFee': '10', - 'hourlyRecurringFee': '.02', - 'oneTimeFee': '0', - 'id': 21509, - 'sort': 5, - 'item': { - 'capacity': '10', - 'description': '10 Mbps Dual Public & Private Networks ' - '(up to 20 Mbps)', - 'id': 4332 - }, - 'laborFee': '0', - }, - { - 'itemId': 4336, - 'setupFee': '0', - 'recurringFee': '20', - 'hourlyRecurringFee': '.03', - 'oneTimeFee': '0', - 'id': 21513, - 'sort': 5, - 'item': { - 'capacity': '100', - 'description': '100 Mbps Dual Public & Private Networks ' - '(up to 200 Mbps)', - 'id': 4336 - }, - 'laborFee': '0', - } - ] - - controller_prices = [ - { - 'itemId': 487, - 'setupFee': '0', - 'recurringFee': '0', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 0, - 'item': { - 'description': 'Non-RAID', - 'id': 487 - }, - 'id': 876, - }, - { - 'itemId': 488, - 'setupFee': '0', - 'recurringFee': '50', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 0, - 'item': { - 'description': 'RAID 0', - 'id': 488 - }, - 'id': 877, - } - ] - - return [ - { - 'categoryCode': CATEGORY['categoryCode'], - 'name': CATEGORY['name'], - 'id': 1000, - 'groups': [{ - 'sort': 0, - 'prices': prices, - 'itemCategoryId': 1000, - 'packageId': 13, - }], - }, - { - 'categoryCode': 'ram', - 'id': 3, - 'name': 'Ram', - 'groups': [{ - 'sort': 0, - 'prices': ram_prices, - 'itemCategoryId': 3, - 'packageId': 13 - }], - }, - { - 'categoryCode': 'server', - 'id': 1, - 'name': 'Server', - 'groups': [{ - 'sort': 2, - 'prices': server_prices, - 'itemCategoryId': 1, - 'packageId': 13 - }], - }, - { - 'categoryCode': 'disk0', - 'name': 'First Disk', - 'isRequired': 1, - 'id': 1001, - 'groups': [{ - 'sort': 0, - 'prices': disk0_prices, - 'itemCategoryId': 1001, - 'packageId': 13, - }], - }, - { - 'categoryCode': 'disk1', - 'name': 'Second Disk', - 'isRequired': 1, - 'id': 1002, - 'groups': [{ - 'sort': 0, - 'prices': disk1_prices, - 'itemCategoryId': 1002, - 'packageId': 13, - }], - }, - { - 'categoryCode': 'os', - 'id': 12, - 'name': 'Operating System', - 'groups': [ - { - 'sort': 0, - 'prices': centos_prices, - 'itemCategoryId': 12, - 'packageId': 13, - 'title': 'CentOS', - }, - { - 'sort': 0, - 'prices': debian_prices, - 'itemCategoryId': 12, - 'packageId': 13, - 'title': 'Debian', - }, - { - 'sort': 0, - 'prices': ubuntu_prices, - 'itemCategoryId': 12, - 'packageId': 13, - 'title': 'Ubuntu', - }, - { - 'sort': 0, - 'prices': windows_prices, - 'itemCategoryId': 12, - 'packageId': 13, - 'title': 'Microsoft', - }, - { - 'sort': 10, - 'prices': redhat_prices, - 'itemCategoryId': 12, - 'packageId': 13, - 'title': 'Redhat' - }, - ], - }, - { - 'categoryCode': 'port_speed', - 'id': 26, - 'name': 'Uplink Port Speeds', - 'groups': [ - { - 'sort': 0, - 'prices': single_nic_prices, - 'itemCategoryId': 26, - 'packageId': 13, - }, - { - 'sort': 5, - 'prices': dual_nic_prices, - 'itemCategoryId': 26, - 'packageId': 13, - }, - ], - }, - { - 'categoryCode': 'disk_controller', - 'id': 11, - 'groups': [{ - 'sort': 0, - 'prices': controller_prices, - 'itemCategoryId': 11, - 'packageId': 13}], - 'name': 'Disk Controller' - }, - ] - - -def get_bmc_categories_mock(): - server_core_prices = [ - { - 'itemId': 1013, - 'setupFee': '0', - 'recurringFee': '159', - 'hourlyRecurringFee': '.5', - 'oneTimeFee': '0', - 'id': 1921, - 'sort': 0, - 'item': { - 'capacity': '2', - 'description': '2 x 2.0 GHz Core Bare Metal Instance - ' - '2 GB Ram', - 'id': 1013 - }, - 'laborFee': '0', - }, - { - 'itemId': 1014, - 'setupFee': '0', - 'recurringFee': '199', - 'hourlyRecurringFee': '.75', - 'oneTimeFee': '0', - 'id': 1922, - 'sort': 0, - 'item': { - 'capacity': '4', - 'description': '4 x 2.0 GHz Core Bare Metal Instance - ' - '4 GB Ram', - 'id': 1014 - }, - 'laborFee': '0', - }, - { - 'itemId': 1015, - 'setupFee': '0', - 'recurringFee': '149', - 'hourlyRecurringFee': '.75', - 'oneTimeFee': '0', - 'id': 1923, - 'sort': 0, - 'item': { - 'capacity': '2', - 'description': '2 x 2.0 GHz Core Bare Metal Instance - ' - '4 GB Ram', - 'id': 1014 - }, - 'laborFee': '0', - } - ] - - centos_prices = [ - { - 'itemId': 3921, - 'setupFee': '0', - 'recurringFee': '0', - 'hourlyRecurringFee': '0', - 'oneTimeFee': '0', - 'id': 13963, - 'sort': 0, - 'item': { - 'description': 'CentOS 6.0 - Minimal Install (64 bit)', - 'id': 3921 - }, - 'laborFee': '0', - }, - { - 'itemId': 3919, - 'setupFee': '0', - 'recurringFee': '0', - 'hourlyRecurringFee': '0', - 'oneTimeFee': '0', - 'id': 13961, - 'sort': 0, - 'item': { - 'description': 'CentOS 6.0 - LAMP Install (64 bit)', - 'id': 3919 - }, - 'laborFee': '0', - }, - ] - - redhat_prices = [ - { - 'itemId': 3838, - 'setupFee': '0', - 'recurringFee': '20', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 1, - 'item': { - 'description': 'Red Hat Enterprise Linux 6 - Minimal Install ' - '(64 bit)', - 'id': 3838 - }, - 'id': 13798, - }, - { - 'itemId': 3834, - 'setupFee': '0', - 'recurringFee': '20', - 'laborFee': '0', - 'oneTimeFee': '0', - 'sort': 1, - 'item': { - 'description': 'Red Hat Enterprise Linux 6 - LAMP Install ' - '(64 bit)', - 'id': 3834 - }, - 'id': 13795, - } - ] - - ubuntu_prices = [ - { - 'itemId': 4170, - 'setupFee': '0', - 'recurringFee': '0', - 'hourlyRecurringFee': '0', - 'oneTimeFee': '0', - 'id': 17438, - 'sort': 9, - 'item': { - 'description': 'Ubuntu Linux 12.04 LTS Precise Pangolin - ' - 'Minimal Install (64 bit)', - 'id': 4170 - }, - 'laborFee': '0', - }, - { - 'itemId': 4168, - 'setupFee': '0', - 'recurringFee': '0', - 'hourlyRecurringFee': '0', - 'oneTimeFee': '0', - 'id': 17434, - 'sort': 9, - 'item': { - 'description': 'Ubuntu Linux 12.04 LTS Precise Pangolin - ' - 'LAMP Install (64 bit)', - 'id': 4168 - }, - 'laborFee': '0', - }, - ] - - windows_prices = [ - { - 'itemId': 936, - 'setupFee': '0', - 'recurringFee': '20', - 'hourlyRecurringFee': '.05', - 'oneTimeFee': '0', - 'id': 1752, - 'sort': 16, - 'item': { - 'description': 'Windows Server 2008 Standard Edition SP2 ' - '(64bit)', - 'id': 936 - }, - 'laborFee': '0', - }, - { - 'itemId': 938, - 'setupFee': '0', - 'recurringFee': '50', - 'hourlyRecurringFee': '.1', - 'oneTimeFee': '0', - 'id': 1761, - 'sort': 16, - 'item': { - 'description': 'Windows Server 2008 Enterprise Edition SP2 ' - '(64bit)', - 'id': 938 - }, - 'laborFee': '0', - }, - { - 'itemId': 940, - 'setupFee': '0', - 'recurringFee': '75', - 'hourlyRecurringFee': '.15', - 'oneTimeFee': '0', - 'id': 1770, - 'sort': 16, - 'item': { - 'description': 'Windows Server 2008 Datacenter Edition SP2 ' - '(64bit)', - 'id': 940 - }, - 'laborFee': '0', - }, - { - 'itemId': 4247, - 'setupFee': '0', - 'recurringFee': '75', - 'hourlyRecurringFee': '.15', - 'oneTimeFee': '0', - 'id': 21060, - 'sort': 17, - 'item': { - 'description': 'Windows Server 2012 Datacenter Edition With ' - 'Hyper-V (64bit)', - 'id': 4247 - }, - 'laborFee': '0', - }, - { - 'itemId': 4248, - 'setupFee': '0', - 'recurringFee': '20', - 'hourlyRecurringFee': '.05', - 'oneTimeFee': '0', - 'id': 21074, - 'sort': 15, - 'item': { - 'description': 'Windows Server 2008 Standard SP1 with R2 ' - '(64 bit)', - 'id': 4248 - }, - 'laborFee': '0', - }, - ] - - disk_prices1 = [ - { - 'itemId': 14, - 'setupFee': '0', - 'recurringFee': '0', - 'hourlyRecurringFee': '0', - 'oneTimeFee': '0', - 'id': 1267, - 'sort': 0, - 'item': { - 'capacity': '500', - 'description': '500GB SATA II', - 'id': 14 - }, - 'laborFee': '0', - }, - ] - - disk_prices2 = [ - { - 'itemId': 2000, - 'setupFee': '0', - 'recurringFee': '0', - 'hourlyRecurringFee': '0', - 'oneTimeFee': '0', - 'id': 19, - 'sort': 99, - 'item': { - 'capacity': '250', - 'description': '250GB SATA II', - 'id': 2000 - }, - 'laborFee': '0', - } - ] - - single_nic_prices = [ - { - 'itemId': 187, - 'setupFee': '0', - 'recurringFee': '0', - 'hourlyRecurringFee': '0', - 'oneTimeFee': '0', - 'id': 273, - 'sort': 0, - 'item': { - 'capacity': '100', - 'description': '100 Mbps Public & Private Networks', - 'id': 187 - }, - 'laborFee': '0', - }, - { - 'itemId': 188, - 'setupFee': '0', - 'recurringFee': '20', - 'hourlyRecurringFee': '.04', - 'oneTimeFee': '0', - 'id': 274, - 'sort': 0, - 'item': { - 'capacity': '1000', - 'description': '1 Gbps Public & Private Networks', - 'id': 188 - }, - 'laborFee': '0', - } - ] - - dual_nic_prices = [ - { - 'itemId': 4332, - 'setupFee': '0', - 'recurringFee': '10', - 'hourlyRecurringFee': '.02', - 'oneTimeFee': '0', - 'id': 21509, - 'sort': 5, - 'item': { - 'capacity': '10', - 'description': '10 Mbps Dual Public & Private Networks ' - '(up to 20 Mbps)', - 'id': 4332 - }, - 'laborFee': '0', - }, - { - 'itemId': 4336, - 'setupFee': '0', - 'recurringFee': '20', - 'hourlyRecurringFee': '.03', - 'oneTimeFee': '0', - 'id': 21513, - 'sort': 5, - 'item': { - 'capacity': '100', - 'description': '100 Mbps Dual Public & Private Networks ' - '(up to 200 Mbps)', - 'id': 4336 - }, - 'laborFee': '0', - 'quantity': '' - }, - { - 'itemId': 1284, - 'setupFee': '0', - 'recurringFee': '40', - 'hourlyRecurringFee': '.05', - 'oneTimeFee': '0', - 'id': 2314, - 'sort': 5, - 'item': { - 'capacity': '1000', - 'description': '1 Gbps Dual Public & Private Networks ' - '(up to 2 Gbps)', - 'id': 1284 - }, - 'laborFee': '0', - } - ] - - return [ - { - 'categoryCode': 'server_core', - 'id': 110, - 'groups': [{ - 'sort': 0, - 'prices': server_core_prices, - 'itemCategoryId': 110, - 'packageId': 50 - }], - 'name': 'Bare Metal Instance' - }, - { - 'categoryCode': 'os', - 'id': 12, - 'groups': [ - {'sort': 0, 'prices': centos_prices, 'title': 'CentOS'}, - {'sort': 0, 'prices': redhat_prices, 'title': 'Redhat'}, - {'sort': 9, 'prices': ubuntu_prices, 'title': 'Ubuntu'}, - {'sort': 14, 'prices': windows_prices, 'title': 'Microsoft'} - ], - 'name': 'Operating System' - }, - { - 'categoryCode': 'disk0', - 'id': 4, - 'groups': [ - { - 'sort': 0, - 'prices': disk_prices1, - 'itemCategoryId': 4, - 'packageId': 50 - }, - { - 'sort': 99, - 'prices': disk_prices2, - 'itemCategoryId': 4, - 'packageId': 50 - } - ], - 'name': 'First Hard Drive', - }, - { - 'categoryCode': 'port_speed', - 'id': 26, - 'groups': [ - { - 'sort': 0, - 'prices': single_nic_prices, - 'itemCategoryId': 26, - 'packageId': 50 - }, - { - 'sort': 5, - 'prices': dual_nic_prices, - 'itemCategoryId': 26, - 'packageId': 50 - } - ], - 'name': 'Uplink Port Speeds', - }, - ] +getAllObjects = [{ + 'activePresets': [{ + 'description': 'Single Xeon 1270, 8GB Ram, 2x1TB SATA disks, Non-RAID', + 'id': 64, + 'isActive': '1', + 'keyName': 'S1270_8GB_2X1TBSATA_NORAID', + 'name': 'S1270 8GB 2X1TBSATA NORAID', + 'packageId': 200 + }], + 'description': 'Bare Metal Server', + 'firstOrderStepId': 1, + 'id': 200, + 'isActive': 1, + 'items': HARDWARE_ITEMS, + 'name': 'Bare Metal Server', + 'regions': [{'description': 'WDC01 - Washington, DC - East Coast U.S.', + 'keyname': 'WASHINGTON_DC', + 'location': {'location': {'id': 37473, + 'longName': 'Washington 1', + 'name': 'wdc01'}}, + 'sortOrder': 10}], + 'subDescription': 'Bare Metal Server', + 'unitSize': 1, +}] -getCategories = get_server_categories_mock() + get_bmc_categories_mock() getItems = [ { 'id': 1234, @@ -1138,6 +285,8 @@ def get_bmc_categories_mock(): 'itemCategory': {'categoryCode': 'global_ipv6'}, 'prices': [{'id': 611}], }] + + getItemPrices = [ { 'currentPriceFlag': '', diff --git a/SoftLayer/tests/CLI/modules/server_tests.py b/SoftLayer/tests/CLI/modules/server_tests.py index 675fae24..acbab824 100644 --- a/SoftLayer/tests/CLI/modules/server_tests.py +++ b/SoftLayer/tests/CLI/modules/server_tests.py @@ -11,7 +11,6 @@ import mock from SoftLayer.CLI import exceptions -from SoftLayer.CLI.server import create from SoftLayer import testing import json @@ -26,79 +25,6 @@ def test_server_cancel_reasons(self): self.assertEqual(result.exit_code, 0) self.assertEqual(len(output), 10) - @mock.patch('SoftLayer.HardwareManager' - '.get_available_dedicated_server_packages') - def test_server_create_options(self, packages): - - packages.return_value = [(999, 'Chassis 999')] - - result = self.run_command(['server', 'create-options', '999']) - - expected = { - 'cpu': [ - {'Description': 'Dual Quad Core Pancake 200 - 1.60GHz', - 'ID': 723}, - {'Description': 'Dual Quad Core Pancake 200 - 1.80GHz', - 'ID': 724}], - 'datacenter': ['RANDOM_LOCATION'], - 'disk': ['250_SATA_II', '500_SATA_II'], - 'disk_controllers': ['None', 'RAID0'], - 'dual nic': ['1000_DUAL', '100_DUAL', '10_DUAL'], - 'memory': [4, 6], - 'os (CENTOS)': ['CENTOS_6_64_LAMP', 'CENTOS_6_64_MINIMAL'], - 'os (REDHAT)': ['REDHAT_6_64_LAMP', 'REDHAT_6_64_MINIMAL'], - 'os (UBUNTU)': ['UBUNTU_12_64_LAMP', 'UBUNTU_12_64_MINIMAL'], - 'os (WIN)': [ - 'WIN_2008-DC_64', - 'WIN_2008-ENT_64', - 'WIN_2008-STD-R2_64', - 'WIN_2008-STD_64', - 'WIN_2012-DC-HYPERV_64'], - 'single nic': ['100', '1000']} - - self.assertEqual(result.exit_code, 0) - self.assertEqual(json.loads(result.output), expected) - - @mock.patch('SoftLayer.HardwareManager' - '.get_available_dedicated_server_packages') - def test_server_create_options_with_invalid_chassis(self, packages): - packages.return_value = [(998, 'Legacy Chassis')] - result = self.run_command(['server', 'create-options', '999']) - - self.assertEqual(result.exit_code, 2) - self.assertIsInstance(result.exception, exceptions.CLIAbort) - - @mock.patch('SoftLayer.HardwareManager' - '.get_available_dedicated_server_packages') - @mock.patch('SoftLayer.HardwareManager.get_bare_metal_package_id') - def test_server_create_options_for_bmc(self, bmpi, packages): - packages.return_value = [(1099, 'Bare Metal Instance')] - bmpi.return_value = '1099' - - result = self.run_command(['server', 'create-options', '1099']) - - expected = { - 'memory/cpu': [ - {'cpu': ['2'], 'memory': '2'}, - {'cpu': ['2', '4'], 'memory': '4'}, - ], - 'datacenter': ['RANDOM_LOCATION'], - 'disk': ['250_SATA_II', '500_SATA_II'], - 'dual nic': ['1000_DUAL', '100_DUAL', '10_DUAL'], - 'os (CENTOS)': ['CENTOS_6_64_LAMP', 'CENTOS_6_64_MINIMAL'], - 'os (REDHAT)': ['REDHAT_6_64_LAMP', 'REDHAT_6_64_MINIMAL'], - 'os (UBUNTU)': ['UBUNTU_12_64_LAMP', 'UBUNTU_12_64_MINIMAL'], - 'os (WIN)': [ - 'WIN_2008-DC_64', - 'WIN_2008-ENT_64', - 'WIN_2008-STD-R2_64', - 'WIN_2008-STD_64', - 'WIN_2012-DC-HYPERV_64'], - 'single nic': ['100', '1000']} - - self.assertEqual(result.exit_code, 0) - self.assertEqual(json.loads(result.output), expected) - def test_server_details(self): result = self.run_command(['server', 'detail', '1234', '--passwords', '--price']) @@ -280,19 +206,6 @@ def test_nic_edit_server(self): args=(100,), identifier=12345) - @mock.patch('SoftLayer.HardwareManager' - '.get_available_dedicated_server_packages') - def test_list_chassis_server(self, packages): - packages.return_value = [(1, 'Chassis 1', 'Some chassis'), - (2, 'Chassis 2', 'Another chassis')] - result = self.run_command(['server', 'list-chassis']) - - expected = [{'chassis': 'Chassis 1', 'code': 1}, - {'chassis': 'Chassis 2', 'code': 2}] - - self.assertEqual(result.exit_code, 0) - self.assertEqual(json.loads(result.output), expected) - @mock.patch('SoftLayer.HardwareManager.verify_order') def test_create_server_test_flag(self, verify_mock): verify_mock.return_value = { @@ -309,26 +222,17 @@ def test_create_server_test_flag(self, verify_mock): } ] } - result = self.run_command(['server', 'create', - '--chassis=999', + + result = self.run_command(['--really', 'server', 'create', + '--size=S1270_8GB_2X1TBSATA_NORAID', '--hostname=test', '--domain=example.com', '--datacenter=TEST00', - '--cpu=4', - '--network=100', - '--disk=250_SATA_II', - '--disk=250_SATA_II', - '--os=UBUNTU_12_64_MINIMAL', - '--memory=4', - '--controller=RAID0', - '--test', - '--key=1234', - '--key=456', + '--port-speed=100', + '--os=UBUNTU_12_64', '--vlan-public=10234', '--vlan-private=20468', - '--postinstall=' - 'http://somescript.foo/myscript.sh', - ], + '--test'], fmt='raw') self.assertEqual(result.exit_code, 0) @@ -336,78 +240,20 @@ def test_create_server_test_flag(self, verify_mock): self.assertIn("Second Item", result.output) self.assertIn("Total monthly cost", result.output) - @mock.patch('SoftLayer.HardwareManager.verify_order') - def test_create_server_test_no_disk(self, verify_mock): - - verify_mock.return_value = { - 'prices': [ - { - 'recurringFee': 0.0, - 'setupFee': 0.0, - 'item': {'description': 'First Item'}, - }, - { - 'recurringFee': 25.0, - 'setupFee': 0.0, - 'item': {'description': 'Second Item'}, - } - ] - } - result = self.run_command(['server', 'create', - '--chassis=999', - '--hostname=test', - '--domain=example.com', - '--datacenter=TEST00', - '--cpu=4', - '--network=100', - '--os=UBUNTU_12_64_MINIMAL', - '--memory=4', - '--controller=RAID0', - '--test', - '--key=1234', - '--key=456', - '--vlan-public=10234', - '--vlan-private=20468', - '--postinstall=' - 'http://somescript.foo/myscript.sh', - ], - fmt='raw') - - self.assertEqual(result.exit_code, 0) - - @mock.patch('SoftLayer.HardwareManager.verify_order') - def test_create_server_test_no_disk_no_raid(self, verify_mock): - verify_mock.return_value = { - 'prices': [ - { - 'recurringFee': 0.0, - 'setupFee': 0.0, - 'item': {'description': 'First Item'}, - }, - { - 'recurringFee': 25.0, - 'setupFee': 0.0, - 'item': {'description': 'Second Item'}, - } - ] - } - - result = self.run_command(['server', 'create', - '--chassis=999', - '--hostname=test', - '--domain=example.com', - '--datacenter=TEST00', - '--cpu=4', - '--network=100', - '--os=UBUNTU_12_64_MINIMAL', - '--memory=4', - '--test', - '--vlan-public=10234', - '--vlan-private=20468', - ], - fmt='raw') + def test_create_options(self): + result = self.run_command(['server', 'create-options']) self.assertEqual(result.exit_code, 0) + expected = [ + [{'datacenter': 'Washington 1', 'value': 'wdc01'}], + [{'size': 'Single Xeon 1270, 8GB Ram, 2x1TB SATA disks, Non-RAID', + 'value': 'S1270_8GB_2X1TBSATA_NORAID'}], + [{'operating_system': 'Ubuntu / 14.04-64', + 'value': 'UBUNTU_14_64'}], + [{'port_speed': '10 Mbps Public & Private Network Uplinks', + 'value': '10'}], + [{'extras': '1 IPv6 Address', 'value': '1_IPV6_ADDRESS'}]] + self.assertEqual(json.loads(result.output), expected) @mock.patch('SoftLayer.HardwareManager.place_order') def test_create_server(self, order_mock): @@ -417,16 +263,15 @@ def test_create_server(self, order_mock): } result = self.run_command(['--really', 'server', 'create', - '--chassis=999', + '--size=S1270_8GB_2X1TBSATA_NORAID', '--hostname=test', '--domain=example.com', '--datacenter=TEST00', - '--cpu=4', - '--network=100', - '--os=UBUNTU_12_64_MINIMAL', - '--memory=4', + '--port-speed=100', + '--os=UBUNTU_12_64', '--vlan-public=10234', '--vlan-private=20468', + '--key=10', ]) self.assertEqual(result.exit_code, 0) @@ -441,141 +286,47 @@ def test_create_server_missing_required(self): '--hostname=test', '--domain=example.com', '--datacenter=TEST00', - '--cpu=4', '--network=100', '--os=UBUNTU_12_64_MINIMAL', - '--memory=4', ]) self.assertEqual(result.exit_code, 2) self.assertIsInstance(result.exception, SystemExit) @mock.patch('SoftLayer.CLI.template.export_to_template') - def test_create_server_with_export(self, export_to_template): - result = self.run_command(['server', 'create', - # Note: no chassis id - '--chassis=999', - '--hostname=test', - '--domain=example.com', - '--datacenter=TEST00', - '--cpu=4', - '--memory=4', - '--network=100', - '--os=UBUNTU_12_64_MINIMAL', - '--key=1234', - '--export=/path/to/test_file.txt', - ]) - - self.assertEqual(result.exit_code, 0) - self.assertIn("Successfully exported options to a template file.", - result.output) - export_to_template.assert_called_with('/path/to/test_file.txt', - {'domain': 'example.com', - 'san': False, - 'dedicated': False, - 'private': False, - 'disk': (), - 'userdata': None, - 'network': '100', - 'billing': 'monthly', - 'userfile': None, - 'hostname': 'test', - 'template': None, - 'memory': 4, - 'test': False, - 'postinstall': None, - 'controller': None, - 'chassis': '999', - 'key': ('1234',), - 'vlan_private': None, - 'wait': None, - 'datacenter': 'TEST00', - 'os': 'UBUNTU_12_64_MINIMAL', - 'cpu': 4, - 'vlan_public': None}, - exclude=['wait', 'test']) - - @mock.patch('SoftLayer.HardwareManager' - '.get_available_dedicated_server_packages') - @mock.patch('SoftLayer.HardwareManager.get_bare_metal_package_id') - @mock.patch('SoftLayer.HardwareManager.verify_order') - def test_create_server_test_for_bmc(self, verify_mock, bmpi, packages): - packages.return_value = [(1099, 'Bare Metal Instance', 'BMC')] - bmpi.return_value = '1099' - - # First, test the --test flag - verify_mock.return_value = { - 'prices': [ - { - 'recurringFee': 0.0, - 'setupFee': 0.0, - 'item': {'description': 'First Item'}, - }, - { - 'recurringFee': 25.0, - 'setupFee': 0.0, - 'item': {'description': 'Second Item'}, - } - ] - } - - result = self.run_command(['server', 'create', - '--chassis=1099', - '--hostname=test', - '--domain=example.com', - '--datacenter=TEST00', - '--cpu=2', - '--memory=2', - '--network=100', - '--disk=250_SATA_II', - '--disk=250_SATA_II', - '--os=UBUNTU_12_64_MINIMAL', - '--vlan-public=10234', - '--vlan-private=20468', - '--key=1234', - '--key=456', - '--test', - '--postinstall=' - 'http://somescript.foo/myscript.sh', - '--billing=hourly', - ]) - - self.assertEqual(result.exit_code, 0) - self.assertIn("First Item", result.output) - self.assertIn("Second Item", result.output) - self.assertIn("Total monthly cost", result.output) - - @mock.patch('SoftLayer.HardwareManager' - '.get_available_dedicated_server_packages') - @mock.patch('SoftLayer.HardwareManager.get_bare_metal_package_id') - @mock.patch('SoftLayer.HardwareManager.place_order') - def test_create_server_for_bmc(self, order_mock, bmpi, packages): - order_mock.return_value = { - 'orderId': 98765, - 'orderDate': '2013-08-02 15:23:47' - } - + def test_create_server_with_export(self, export_mock): result = self.run_command(['--really', 'server', 'create', - '--chassis=1099', + '--size=S1270_8GB_2X1TBSATA_NORAID', '--hostname=test', '--domain=example.com', '--datacenter=TEST00', - '--cpu=4', - '--memory=4', - '--network=100', - '--disk=250_SATA_II', - '--disk=250_SATA_II', - '--os=UBUNTU_12_64_MINIMAL', + '--port-speed=100', + '--os=UBUNTU_12_64', '--vlan-public=10234', '--vlan-private=20468', - '--key=1234', - '--key=456', - '--billing=hourly', - ]) + '--export=/path/to/test_file.txt'], + fmt='raw') self.assertEqual(result.exit_code, 0) - self.assertEqual(json.loads(result.output), - {'id': 98765, 'created': '2013-08-02 15:23:47'}) + self.assertIn("Successfully exported options to a template file.", + result.output) + export_mock.assert_called_with('/path/to/test_file.txt', + {'billing': 'hourly', + 'datacenter': 'TEST00', + 'domain': 'example.com', + 'extra': (), + 'hostname': 'test', + 'key': (), + 'os': 'UBUNTU_12_64', + 'port_speed': 100, + 'postinstall': None, + 'size': 'S1270_8GB_2X1TBSATA_NORAID', + 'test': False, + 'vlan_private': 20468, + 'vlan_public': 10234, + 'wait': None, + 'template': None}, + exclude=['wait', 'test']) def test_edit_server_userdata_and_file(self): # Test both userdata and userfile at once @@ -632,11 +383,6 @@ def test_edit_server_userfile(self): args=(['some data'],), identifier=1000) - def test_get_default_value_returns_none_for_unknown_category(self): - option_mock = {'categories': {'cat1': []}} - output = create._get_default_value(option_mock, 'nope') - self.assertEqual(None, output) - @mock.patch('SoftLayer.CLI.formatting.confirm') def test_update_firmware(self, confirm_mock): confirm_mock.return_value = True diff --git a/SoftLayer/tests/managers/hardware_tests.py b/SoftLayer/tests/managers/hardware_tests.py index 5044e247..283598c9 100644 --- a/SoftLayer/tests/managers/hardware_tests.py +++ b/SoftLayer/tests/managers/hardware_tests.py @@ -4,19 +4,37 @@ :license: MIT, see LICENSE for more details. """ +import copy + import mock import SoftLayer -from SoftLayer.managers import hardware +from SoftLayer import managers from SoftLayer import testing from SoftLayer.testing import fixtures +MINIMAL_TEST_CREATE_ARGS = { + 'size': 'S1270_8GB_2X1TBSATA_NORAID', + 'hostname': 'unicorn', + 'domain': 'giggles.woo', + 'location': 'wdc01', + 'os': 'UBUNTU_14_64', + 'port_speed': 10, +} + + class HardwareTests(testing.TestCase): def set_up(self): self.hardware = SoftLayer.HardwareManager(self.client) + def test_init_with_ordering_manager(self): + ordering_manager = SoftLayer.OrderingManager(self.client) + mgr = SoftLayer.HardwareManager(self.client, ordering_manager) + + self.assertEqual(mgr.ordering_manager, ordering_manager) + def test_list_hardware(self): results = self.hardware.list_hardware() @@ -96,132 +114,112 @@ def test_reload(self): 'sshKeyIds': [1701]}), identifier=1) - def test_get_bare_metal_create_options_returns_none_on_error(self): - mock = self.set_mock('SoftLayer_Product_Package', 'getAllObjects') - mock.return_value = [{ - 'id': 0, - 'name': 'No Matching Instances', - 'description': 'Nothing' - }] + def test_get_create_options(self): + options = self.hardware.get_create_options() + + expected = { + 'extras': [{'key': '1_IPV6_ADDRESS', 'name': '1 IPv6 Address'}], + 'locations': [{'key': 'wdc01', 'name': 'Washington 1'}], + 'operating_systems': [{'key': 'UBUNTU_14_64', + 'name': 'Ubuntu / 14.04-64'}], + 'port_speeds': [{ + 'key': '10', + 'name': '10 Mbps Public & Private Network Uplinks' + }], + 'sizes': [{ + 'key': 'S1270_8GB_2X1TBSATA_NORAID', + 'name': 'Single Xeon 1270, 8GB Ram, 2x1TB SATA disks, Non-RAID' + }] + } + + self.assertEqual(options, expected) - self.assertIsNone(self.hardware.get_bare_metal_create_options()) + def test_get_create_options_package_missing(self): + packages = self.set_mock('SoftLayer_Product_Package', 'getAllObjects') + packages.return_value = [] - def test_get_bare_metal_create_options(self): - result = self.hardware.get_bare_metal_create_options() + ex = self.assertRaises(SoftLayer.SoftLayerError, + self.hardware.get_create_options) + self.assertEqual("Ordering package not found", str(ex)) - self.assertEqual(len(result['categories']['disk0']['items']), 2) - self.assertEqual(len(result['categories']['disk1']['items']), 1) - self.assertEqual(len(result['categories']['disk1']['items']), 1) - self.assertEqual(len(result['categories']['disk_controller']['items']), - 2) - self.assertEqual(len(result['categories']['os']['items']), 11) - self.assertEqual(len(result['categories']['port_speed']['items']), 5) - self.assertEqual(len(result['categories']['ram']['items']), 2) - self.assertEqual(len(result['categories']['random']['items']), 1) - self.assertEqual(len(result['categories']['server']['items']), 2) - self.assertEqual(len(result['categories']['server_core']['items']), 3) - self.assertEqual(len(result['locations']), 1) + def test_generate_create_dict_no_items(self): + packages = self.set_mock('SoftLayer_Product_Package', 'getAllObjects') + packages_copy = copy.deepcopy( + fixtures.SoftLayer_Product_Package.getAllObjects) + packages_copy[0]['items'] = [] + packages.return_value = packages_copy - self.assert_called_with('SoftLayer_Product_Package', 'getRegions', - identifier=50) + ex = self.assertRaises(SoftLayer.SoftLayerError, + self.hardware._generate_create_dict) + self.assertIn("Could not find valid price", str(ex)) - self.assert_called_with('SoftLayer_Product_Package', - 'getConfiguration', - identifier=50, - mask='mask[itemCategory[group]]') + def test_generate_create_dict_no_regions(self): + packages = self.set_mock('SoftLayer_Product_Package', 'getAllObjects') + packages_copy = copy.deepcopy( + fixtures.SoftLayer_Product_Package.getAllObjects) + packages_copy[0]['regions'] = [] + packages.return_value = packages_copy - self.assert_called_with('SoftLayer_Product_Package', 'getCategories', - identifier=50) + ex = self.assertRaises(SoftLayer.SoftLayerError, + self.hardware._generate_create_dict, + **MINIMAL_TEST_CREATE_ARGS) + self.assertIn("Could not find valid location for: 'wdc01'", str(ex)) - def test_generate_create_dict_with_all_bare_metal_options(self): + def test_generate_create_dict_invalid_size(self): args = { - 'server': 100, + 'size': 'UNKNOWN_SIZE', 'hostname': 'unicorn', 'domain': 'giggles.woo', - 'disks': [500], - 'location': 'Wyrmshire', - 'os': 200, - 'port_speed': 600, - 'bare_metal': True, - 'hourly': True, - 'public_vlan': 10234, - 'private_vlan': 20468, + 'location': 'wdc01', + 'os': 'UBUNTU_14_64', + 'port_speed': 10, } - expected = { - 'hardware': [ - { - 'domain': 'giggles.woo', - 'bareMetalInstanceFlag': True, - 'hostname': 'unicorn', - 'primaryBackendNetworkComponent': - {'networkVlan': {'id': 20468}}, - 'primaryNetworkComponent': - {'networkVlan': {'id': 10234}}, - } - ], - 'prices': [ - {'id': 100}, - {'id': 500}, - {'id': 200}, - {'id': 600}, - {'id': 12000} - ], - 'useHourlyPricing': True, - 'location': 'Wyrmshire', 'packageId': 50 - } + ex = self.assertRaises(SoftLayer.SoftLayerError, + self.hardware._generate_create_dict, **args) + self.assertIn("Could not find valid size for: 'UNKNOWN_SIZE'", str(ex)) - data = self.hardware._generate_create_dict(**args) - - self.assertEqual(expected, data) - - def test_generate_create_dict_with_all_dedicated_server_options(self): + def test_generate_create_dict(self): args = { - 'server': 100, + 'size': 'S1270_8GB_2X1TBSATA_NORAID', 'hostname': 'unicorn', 'domain': 'giggles.woo', - 'disks': [1000, 1000, 1000, 1000], - 'location': 'Wyrmshire', - 'os': 200, - 'port_speed': 600, - 'bare_metal': False, - 'package_id': 13, - 'ram': 1400, - 'disk_controller': 1500, - 'ssh_keys': [3000, 3001], + 'location': 'wdc01', + 'os': 'UBUNTU_14_64', + 'port_speed': 10, + 'hourly': True, 'public_vlan': 10234, 'private_vlan': 20468, - 'post_uri': 'http://somescript.foo/myscript.sh', + 'extras': ['1_IPV6_ADDRESS'], + 'post_uri': 'http://example.com/script.php', + 'ssh_keys': [10], } expected = { - 'hardware': [ - { - 'domain': 'giggles.woo', - 'bareMetalInstanceFlag': False, - 'hostname': 'unicorn', - 'primaryBackendNetworkComponent': - {'networkVlan': {'id': 20468}}, - 'primaryNetworkComponent': - {'networkVlan': {'id': 10234}}, - } - ], - 'prices': [ - {'id': 100}, - {'id': 1000}, - {'id': 1000}, - {'id': 1000}, - {'id': 1000}, - {'id': 200}, - {'id': 600}, - {'id': 1400}, - {'id': 1500}], - 'sshKeys': [{'sshKeyIds': [3000, 3001]}], - 'location': 'Wyrmshire', 'packageId': 13, - 'provisionScripts': ['http://somescript.foo/myscript.sh'], + 'hardware': [{ + 'domain': 'giggles.woo', + 'hostname': 'unicorn', + 'primaryBackendNetworkComponent': { + 'networkVlan': {'id': 20468} + }, + 'primaryNetworkComponent': {'networkVlan': {'id': 10234}}}], + 'location': 'WASHINGTON_DC', + 'packageId': 200, + 'presetId': 64, + 'prices': [{'id': 21}, + {'id': 420}, + {'id': 906}, + {'id': 37650}, + {'id': 1800}, + {'id': 272}, + {'id': 17129}], + 'useHourlyPricing': True, + 'provisionScripts': ['http://example.com/script.php'], + 'sshKeys': [{'sshKeyIds': [10]}], } data = self.hardware._generate_create_dict(**args) + self.assertEqual(expected, data) @mock.patch('SoftLayer.managers.hardware.HardwareManager' @@ -313,135 +311,6 @@ def test_change_port_speed_private(self): identifier=2, args=(10,)) - def test_get_available_dedicated_server_packages(self): - self.hardware.get_available_dedicated_server_packages() - - _filter = { - 'type': { - 'keyName': { - 'operation': 'in', - 'options': [{ - 'name': 'data', - 'value': ['BARE_METAL_CPU', - 'BARE_METAL_CORE'] - }] - } - } - } - self.assert_called_with('SoftLayer_Product_Package', 'getAllObjects', - filter=_filter, - mask='id,name,description,type,isActive') - - def test_get_server_packages_with_ordering_manager_provided(self): - self.hardware = SoftLayer.HardwareManager( - self.client, SoftLayer.OrderingManager(self.client)) - self.test_get_available_dedicated_server_packages() - - def test_get_dedicated_server_options(self): - result = self.hardware.get_dedicated_server_create_options(13) - - self.assertEqual(len(result['categories']['disk0']['items']), 2) - self.assertEqual(len(result['categories']['disk1']['items']), 1) - self.assertEqual(len(result['categories']['disk1']['items']), 1) - self.assertEqual(len(result['categories']['disk_controller']['items']), - 2) - self.assertEqual(len(result['categories']['os']['items']), 11) - self.assertEqual(len(result['categories']['port_speed']['items']), 5) - self.assertEqual(len(result['categories']['ram']['items']), 2) - self.assertEqual(len(result['categories']['random']['items']), 1) - self.assertEqual(len(result['categories']['server']['items']), 2) - self.assertEqual(len(result['categories']['server_core']['items']), 3) - self.assertEqual(len(result['locations']), 1) - - self.assert_called_with('SoftLayer_Product_Package', 'getRegions', - identifier=13) - - self.assert_called_with('SoftLayer_Product_Package', - 'getConfiguration', - identifier=13, - mask='mask[itemCategory[group]]') - - self.assert_called_with('SoftLayer_Product_Package', 'getCategories', - identifier=13) - - def test_get_default_value_returns_none_for_unknown_category(self): - package_options = {'categories': ['Cat1', 'Cat2']} - - self.assertEqual(None, hardware.get_default_value(package_options, - 'Unknown Category')) - - def test_get_default_value(self): - price_id = 9876 - package_options = {'categories': - {'Cat1': { - 'items': [{'setup_fee': 0, - 'recurring_fee': 0, - 'hourly_recurring_fee': 0, - 'one_time_fee': 0, - 'labor_fee': 0, - 'price_id': price_id}] - }}} - - self.assertEqual(price_id, - hardware.get_default_value(package_options, 'Cat1')) - - def test_get_default_value_none_free(self): - package_options = {'categories': {}} - self.assertEqual(None, - hardware.get_default_value(package_options, 'Cat1')) - - package_options = {'categories': - {'Cat1': { - 'items': [{'setup_fee': 10, - 'recurring_fee': 0, - 'hourly_recurring_fee': 0, - 'one_time_fee': 0, - 'labor_fee': 0, - 'price_id': 1234}] - }}} - self.assertEqual(None, - hardware.get_default_value(package_options, 'Cat1')) - - def test_get_default_value_hourly(self): - package_options = {'categories': - {'Cat1': { - 'items': [{'setup_fee': 0, - 'recurring_fee': 0, - 'hourly_recurring_fee': None, - 'one_time_fee': 0, - 'labor_fee': 0, - 'price_id': 1234}, - {'setup_fee': 0, - 'recurring_fee': None, - 'hourly_recurring_fee': 0, - 'one_time_fee': 0, - 'labor_fee': 0, - 'price_id': 4321}] - }}} - result = hardware.get_default_value(package_options, 'Cat1', - hourly=True) - self.assertEqual(4321, result) - - def test_get_default_value_monthly(self): - package_options = {'categories': - {'Cat1': { - 'items': [{'setup_fee': 0, - 'recurring_fee': None, - 'hourly_recurring_fee': 0, - 'one_time_fee': 0, - 'labor_fee': 0, - 'price_id': 4321}, - {'setup_fee': 0, - 'recurring_fee': 0, - 'hourly_recurring_fee': None, - 'one_time_fee': 0, - 'labor_fee': 0, - 'price_id': 1234}] - }}} - result = hardware.get_default_value(package_options, 'Cat1', - hourly=False) - self.assertEqual(1234, result) - def test_edit_meta(self): # Test editing user data self.hardware.edit(100, userdata='my data') @@ -497,3 +366,56 @@ def test_update_firmware_selective(self): self.assert_called_with('SoftLayer_Hardware_Server', 'createFirmwareUpdateTransaction', identifier=100, args=(0, 1, 1, 0)) + + +class HardwareHelperTests(testing.TestCase): + def test_get_extra_price_id_no_items(self): + ex = self.assertRaises(SoftLayer.SoftLayerError, + managers.hardware._get_extra_price_id, + [], 'test', True) + self.assertEqual("Could not find valid price for extra option, 'test'", + str(ex)) + + def test_get_default_price_id_item_not_first(self): + items = [{ + 'itemCategory': {'categoryCode': 'unknown', 'id': 325}, + 'keyName': 'UNKNOWN', + 'prices': [{'accountRestrictions': [], + 'currentPriceFlag': '', + 'hourlyRecurringFee': '10.0', + 'id': 1245172, + 'recurringFee': '1.0'}], + }] + ex = self.assertRaises(SoftLayer.SoftLayerError, + managers.hardware._get_default_price_id, + items, 'unknown', True) + self.assertEqual("Could not find valid price for 'unknown' option", + str(ex)) + + def test_get_default_price_id_no_items(self): + ex = self.assertRaises(SoftLayer.SoftLayerError, + managers.hardware._get_default_price_id, + [], 'test', True) + self.assertEqual("Could not find valid price for 'test' option", + str(ex)) + + def test_get_bandwidth_price_id_no_items(self): + ex = self.assertRaises(SoftLayer.SoftLayerError, + managers.hardware._get_bandwidth_price_id, + [], hourly=True, no_public=False) + self.assertEqual("Could not find valid price for bandwidth option", + str(ex)) + + def test_get_os_price_id_no_items(self): + ex = self.assertRaises(SoftLayer.SoftLayerError, + managers.hardware._get_os_price_id, + [], 'UBUNTU_14_64') + self.assertEqual("Could not find valid price for os: 'UBUNTU_14_64'", + str(ex)) + + def test_get_port_speed_price_id_no_items(self): + ex = self.assertRaises(SoftLayer.SoftLayerError, + managers.hardware._get_port_speed_price_id, + [], 10, True) + self.assertEqual("Could not find valid price for port speed: '10'", + str(ex))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_removed_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 6 }
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@08336ac6742088cb1da14313a6579e3a47eb83e7#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/server_tests.py::ServerCLITests::test_create_options", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_test_flag", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_with_export", "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::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" ]
[]
[ "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_cancel_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_missing_required", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_failed", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata_and_file", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userfile", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_list_servers", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_nic_edit_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_cancel_reasons", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_details", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle_negative", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_off", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_on", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_default", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_hard", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_negative", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_soft", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reload", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_update_firmware", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_hardware_on_bmc", "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_cancel_metal_immediately", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_metal_on_anniversary", "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_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" ]
[]
MIT License
2
[ "SoftLayer/CLI/routes.py", "SoftLayer/CLI/server/create.py", "SoftLayer/CLI/server/__init__.py", "SoftLayer/CLI/server/list_chassis.py", "SoftLayer/CLI/server/create_options.py", "SoftLayer/CLI/virt/create.py", "SoftLayer/managers/hardware.py" ]
[ "SoftLayer/CLI/routes.py", "SoftLayer/CLI/server/create.py", "SoftLayer/CLI/server/__init__.py", "SoftLayer/CLI/server/list_chassis.py", "SoftLayer/CLI/server/create_options.py", "SoftLayer/CLI/virt/create.py", "SoftLayer/managers/hardware.py" ]
uqfoundation__dill-72
678f1e3b2511b9022774e5c6b4973d409e235261
2014-12-08 09:43:48
f998fc8ad029f728398c8ee5817656644a75f452
mmckerns: There is also an approach like this quick hack… it should be general, but it's messy… and as is, it breaks the namespace. ``` >>> import m >>> import dill >>> x = dill.dumps(compile(dill.source.importable(m.A.B, source=True), '<string>', 'exec')) >>> exec(dill.loads(x)) >>> B <class __main__.B at 0x10860c9a8> ``` mmckerns: Note (as a follow-up from issue #132): ``` >>> import collections >>> X = collections.namedtuple('Y', ['a','b']) >>> Xi = X(0,1) >>> import dill >>> dill.detect.errors(Xi) PicklingError("Can't pickle <class '__main__.Y'>: it's not found as __main__.Y",) ``` Should this be the expected behavior? As demonstrated in `test_classdef.py`, one could conceivably pickle a badly named `namedtuple` by messing with the `__name__` (or `__qualname__`). However, one shouldn't need to do that. I believe that the PR for this issue will enable pickling of a badly named `namedtuple`... and is a good solution. matsjoyce: Do you want me to rebase this? mmckerns: Yes, if you don't mind. matsjoyce: OK, updated. I've also changed the behaviour so that it will serialize assuming that the name is bad but on deserialize it will try to find the type, and if it fails recreate it. ```py3 >>> import collections, dill >>> X=collections.namedtuple("Y", ("a", "b")) >>> Z=collections.namedtuple("Z", ("a", "b")) >>> x=X(1,2) >>> z=Z(1,2) >>> x2=dill.copy(x) >>> z2=dill.copy(z) >>> type(x2) <class '__main__.Y'> >>> type(z2) <class '__main__.Z'> >>> type(x2) is X False >>> type(z2) is Z True ``` matsjoyce: Ooo, CI works. I'm looking at the failure.
diff --git a/dill/dill.py b/dill/dill.py index e4f2b56..e941c7d 100644 --- a/dill/dill.py +++ b/dill/dill.py @@ -717,6 +717,18 @@ def _create_array(f, args, state, npdict=None): array.__dict__.update(npdict) return array +def _create_namedtuple(name, fieldnames, modulename): + mod = _import_module(modulename, safe=True) + if mod is not None: + try: + return getattr(mod, name) + except: + pass + import collections + t = collections.namedtuple(name, fieldnames) + t.__module__ = modulename + return t + def _getattr(objclass, name, repr_str): # hack to grab the reference directly try: #XXX: works only for __builtin__ ? @@ -1087,7 +1099,7 @@ def _proxy_helper(obj): # a dead proxy returns a reference to None return id(None) if _str == _repr: return id(obj) # it's a repr try: # either way, it's a proxy from here - address = int(_str.rstrip('>').split(' at ')[-1], base=16) + address = int(_str.rstrip('>').split(' at ')[-1], base=16) except ValueError: # special case: proxy of a 'type' if not IS_PYPY: address = int(_repr.rstrip('>').split(' at ')[-1], base=16) @@ -1198,15 +1210,13 @@ def save_type(pickler, obj): log.info("T1: %s" % obj) pickler.save_reduce(_load_type, (_typemap[obj],), obj=obj) log.info("# T1") + elif issubclass(obj, tuple) and all([hasattr(obj, attr) for attr in ('_fields','_asdict','_make','_replace')]): + # special case: namedtuples + log.info("T6: %s" % obj) + pickler.save_reduce(_create_namedtuple, (getattr(obj, "__qualname__", obj.__name__), obj._fields, obj.__module__), obj=obj) + log.info("# T6") + return elif obj.__module__ == '__main__': - try: # use StockPickler for special cases [namedtuple,] - [getattr(obj, attr) for attr in ('_fields','_asdict', - '_make','_replace')] - log.info("T6: %s" % obj) - StockPickler.save_global(pickler, obj) - log.info("# T6") - return - except AttributeError: pass if issubclass(type(obj), type): # try: # used when pickling the class as code (or the interpreter) if is_dill(pickler) and not pickler._byref:
pickling nested namedtuples While dill pickles nested classes without problem, the same cannot be said of namedtuples defined within another class: ``` In [1]: import dill In [2]: from collections import namedtuple In [3]: class T: class A: pass B = namedtuple("B", "") ...: In [4]: dill.dumps(T.A) Out[4]: <elided> In [5]: dill.dumps(T.B) <oops!> ``` I would be OK if fixing this required manually setting some attribute on `B` to indicate where it lives, if that could help.
uqfoundation/dill
diff --git a/tests/test_classdef.py b/tests/test_classdef.py index 0e47473..21a99c9 100644 --- a/tests/test_classdef.py +++ b/tests/test_classdef.py @@ -93,20 +93,24 @@ if hex(sys.hexversion) >= '0x20600f0': Z = namedtuple("Z", ['a','b']) Zi = Z(0,1) X = namedtuple("Y", ['a','b']) - if hex(sys.hexversion) >= '0x30500f0': + X.__name__ = "X" + if hex(sys.hexversion) >= '0x30300f0': X.__qualname__ = "X" #XXX: name must 'match' or fails to pickle - else: - X.__name__ = "X" Xi = X(0,1) + Bad = namedtuple("FakeName", ['a','b']) + Badi = Bad(0,1) else: - Z = Zi = X = Xi = None + Z = Zi = X = Xi = Bad = Badi = None # test namedtuple def test_namedtuple(): - assert Z == dill.loads(dill.dumps(Z)) + assert Z is dill.loads(dill.dumps(Z)) assert Zi == dill.loads(dill.dumps(Zi)) - assert X == dill.loads(dill.dumps(X)) + assert X is dill.loads(dill.dumps(X)) assert Xi == dill.loads(dill.dumps(Xi)) + assert Bad is not dill.loads(dill.dumps(Bad)) + assert Bad._fields == dill.loads(dill.dumps(Bad))._fields + assert tuple(Badi) == tuple(dill.loads(dill.dumps(Badi))) def test_array_subclass(): try: @@ -115,7 +119,7 @@ def test_array_subclass(): class TestArray(np.ndarray): def __new__(cls, input_array, color): obj = np.asarray(input_array).view(cls) - obj.color = color + obj.color = color return obj def __array_finalize__(self, obj): if obj is None:
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 3 }, "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": "pytest", "pip_packages": [ "pytest" ], "pre_install": [], "python": "3.6", "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/uqfoundation/dill.git@678f1e3b2511b9022774e5c6b4973d409e235261#egg=dill 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 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: dill 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/dill
[ "tests/test_classdef.py::test_namedtuple" ]
[ "tests/test_classdef.py::test_class_objects", "tests/test_classdef.py::test_method_decorator" ]
[ "tests/test_classdef.py::test_class_instances", "tests/test_classdef.py::test_none", "tests/test_classdef.py::test_array_subclass", "tests/test_classdef.py::test_slots" ]
[]
BSD License
3
[ "dill/dill.py" ]
[ "dill/dill.py" ]
Pylons__webob-183
d396a514a22761103b7fdb05994ac7eb2eb75e36
2014-12-23 20:42:59
9b79f5f913fb1f07c68102a2279ed757a2a9abf6
diff --git a/webob/request.py b/webob/request.py index c38cf3c..370eb7e 100644 --- a/webob/request.py +++ b/webob/request.py @@ -220,7 +220,7 @@ class BaseRequest(object): ) if content_type == 'application/x-www-form-urlencoded': - r.body = bytes_(t.transcode_query(native_(r.body))) + r.body = bytes_(t.transcode_query(native_(self.body))) return r elif content_type != 'multipart/form-data': return r
Request.decode tries to read from an already consumed stream When building a request multiple times (for example different WSGI middlewares) it is not possible to call decode on the built requests apart from the first one. Can be replicated with something like: ```python from io import BytesIO from webob import Request body = 'something'.encode('latin-1') environ = {'wsgi.input': BytesIO(body), 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=latin-1', 'CONTENT_LENGTH': len(body), 'REQUEST_METHOD': 'POST'} r = Request(environ) r = r.decode('latin-1') r = Request(environ) r = r.decode('latin-1') ``` The second call to decode will crash due to the fact that it tries to read again the wsgi.input. This is due to the fact that Request.decode performs: ```python if content_type == 'application/x-www-form-urlencoded': r.body = bytes_(t.transcode_query(native_(r.body))) ```` which causes setup of the request body from scratch while it already got parsed by the request that we are decoding. Is this expected? Changing it to use *self.body* in place of *r.body* seems to solve the issue by using the already read body: ```python if content_type == 'application/x-www-form-urlencoded': r.body = bytes_(t.transcode_query(native_(self.body))) ````
Pylons/webob
diff --git a/tests/test_request.py b/tests/test_request.py index 24c7aa0..d3ced91 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -2596,6 +2596,22 @@ class TestRequest_functional(unittest.TestCase): self.assertTrue(req.body_file_raw is old_body_file) self.assertTrue(req.body_file is old_body_file) + def test_already_consumed_stream(self): + from webob.request import Request + body = 'something'.encode('latin-1') + content_type = 'application/x-www-form-urlencoded; charset=latin-1' + environ = { + 'wsgi.input': BytesIO(body), + 'CONTENT_TYPE': content_type, + 'CONTENT_LENGTH': len(body), + 'REQUEST_METHOD': 'POST' + } + req = Request(environ) + req = req.decode('latin-1') + req2 = Request(environ) + req2 = req2.decode('latin-1') + self.assertEqual(body, req2.body) + def test_broken_seek(self): # copy() should work even when the input has a broken seek method req = self._blankOne('/', method='POST',
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "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": "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@d396a514a22761103b7fdb05994ac7eb2eb75e36#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_request.py::TestRequest_functional::test_already_consumed_stream" ]
[]
[ "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_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_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
5
[ "webob/request.py" ]
[ "webob/request.py" ]
nose-devs__nose2-232
dea5854cb40f1327989933004a8835e3766b33fd
2015-01-04 15:33:10
bbf5897eb1aa224100e86ba594042e4399fd2f5f
diff --git a/nose2/plugins/loader/discovery.py b/nose2/plugins/loader/discovery.py index 1ec69d6..73aa0fa 100644 --- a/nose2/plugins/loader/discovery.py +++ b/nose2/plugins/loader/discovery.py @@ -194,8 +194,8 @@ class Discoverer(object): return if module_name is None: - module_name = util.name_from_path(full_path) - + module_name, package_path = util.name_from_path(full_path) + util.ensure_importable(package_path) try: module = util.module_from_name(module_name) except: diff --git a/nose2/util.py b/nose2/util.py index dbc14ab..7b615a9 100644 --- a/nose2/util.py +++ b/nose2/util.py @@ -59,7 +59,15 @@ def valid_module_name(path): def name_from_path(path): - """Translate path into module name""" + """Translate path into module name + + Returns a two-element tuple. The first element is a dotted + module name that can be used in import statement, + e.g. pkg1.test.test_things. + The second element is a full path to filesystem directory + that must be on sys.path in order for the import to succeed. + + """ # back up to find module root parts = [] path = os.path.normpath(path) @@ -72,7 +80,7 @@ def name_from_path(path): parts.append(top) else: break - return '.'.join(reversed(parts)) + return '.'.join(reversed(parts)), candidate def module_from_name(name): @@ -156,7 +164,7 @@ def ispackage(path): def ensure_importable(dirname): """Ensure a directory is on sys.path""" - if not dirname in sys.path: + if dirname not in sys.path: sys.path.insert(0, dirname)
nose2 cant import tests from package I have set up a virtual env and have a test structure that looks something like this: <path>/test_package/__init__.py test_foo.py:test_bar test_bar is a really simple test, it just passes. When I stand in "<path>/test_package" and run "nose2" I get an error: "ImportError: No module named test_package.test_foo" But it works with nosetests. And if I stand in "<path>" and run "nose2 test_package" it works, and it also works if I remove the __init__.py I know that the collection of tests work a little different than in nosetests, but I think that it would be good to make this work since it would make it easier to create a test package and run it.
nose-devs/nose2
diff --git a/nose2/plugins/doctests.py b/nose2/plugins/doctests.py index 0e8aa35..b78df2b 100644 --- a/nose2/plugins/doctests.py +++ b/nose2/plugins/doctests.py @@ -41,7 +41,8 @@ class DocTestLoader(Plugin): elif not util.valid_module_name(os.path.basename(path)): return - name = util.name_from_path(path) + name, package_path = util.name_from_path(path) + util.ensure_importable(package_path) try: module = util.module_from_name(name) except Exception: diff --git a/nose2/plugins/loader/loadtests.py b/nose2/plugins/loader/loadtests.py index c2b3e10..216c5d0 100644 --- a/nose2/plugins/loader/loadtests.py +++ b/nose2/plugins/loader/loadtests.py @@ -67,7 +67,7 @@ class LoadTestsLoader(events.Plugin): if (self._match(event.name, event.pattern) and util.ispackage(event.path)): - name = util.name_from_path(event.path) + name, _package_path = util.name_from_path(event.path) module = util.module_from_name(name) load_tests = getattr(module, 'load_tests', None) diff --git a/nose2/tests/functional/support/scenario/doctests/docs.py b/nose2/tests/functional/support/scenario/doctests/docs.py new file mode 100644 index 0000000..9741ac0 --- /dev/null +++ b/nose2/tests/functional/support/scenario/doctests/docs.py @@ -0,0 +1,4 @@ +""" +>>> 2 == 2 +True +""" diff --git a/nose2/tests/functional/support/scenario/doctests/docs.rst b/nose2/tests/functional/support/scenario/doctests/docs.rst new file mode 100644 index 0000000..1c0deeb --- /dev/null +++ b/nose2/tests/functional/support/scenario/doctests/docs.rst @@ -0,0 +1,2 @@ +>>> 1 == 1 +True diff --git a/nose2/tests/functional/support/scenario/doctests/docs.txt b/nose2/tests/functional/support/scenario/doctests/docs.txt new file mode 100644 index 0000000..05fe5dc --- /dev/null +++ b/nose2/tests/functional/support/scenario/doctests/docs.txt @@ -0,0 +1,4 @@ +>>> 2 == 2 +True +>>> 3 == 2 +False diff --git a/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/__init__.py b/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/docs1.py b/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/docs1.py new file mode 100644 index 0000000..9741ac0 --- /dev/null +++ b/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/docs1.py @@ -0,0 +1,4 @@ +""" +>>> 2 == 2 +True +""" diff --git a/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/docs1.rst b/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/docs1.rst new file mode 100644 index 0000000..1c0deeb --- /dev/null +++ b/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/docs1.rst @@ -0,0 +1,2 @@ +>>> 1 == 1 +True diff --git a/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/docs1.txt b/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/docs1.txt new file mode 100644 index 0000000..05fe5dc --- /dev/null +++ b/nose2/tests/functional/support/scenario/doctests/doctests_pkg1/docs1.txt @@ -0,0 +1,4 @@ +>>> 2 == 2 +True +>>> 3 == 2 +False diff --git a/nose2/tests/functional/test_doctests_plugin.py b/nose2/tests/functional/test_doctests_plugin.py new file mode 100644 index 0000000..9a78db0 --- /dev/null +++ b/nose2/tests/functional/test_doctests_plugin.py @@ -0,0 +1,60 @@ +from nose2.tests._common import FunctionalTestCase, support_file + + +class TestDoctestsPlugin(FunctionalTestCase): + + def test_simple(self): + proc = self.runIn( + 'scenario/doctests', + '-v', + '--plugin=nose2.plugins.doctests', + '--with-doctest', + ) + self.assertTestRunOutputMatches(proc, stderr='Ran 6 tests') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: docs ... ok') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: docs.rst ... ok') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: docs.txt ... ok') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: doctests_pkg1.docs1 ... ok') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: docs1.rst ... ok') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: docs1.txt ... ok') + self.assertEqual(proc.poll(), 0) + + def test_start_directory_inside_package(self): + proc = self.runIn( + 'scenario/doctests/doctests_pkg1', + '-v', + '--plugin=nose2.plugins.doctests', + '--with-doctest', + '-t', + support_file('scenario/doctests') + ) + self.assertTestRunOutputMatches(proc, stderr='Ran 3 tests') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: doctests_pkg1.docs1 ... ok') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: docs1.rst ... ok') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: docs1.txt ... ok') + self.assertEqual(proc.poll(), 0) + + def test_project_directory_inside_package(self): + proc = self.runIn( + 'scenario/doctests/doctests_pkg1', + '-v', + '--plugin=nose2.plugins.doctests', + '--with-doctest', + ) + self.assertTestRunOutputMatches(proc, stderr='Ran 3 tests') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: doctests_pkg1.docs1 ... ok') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: docs1.rst ... ok') + self.assertTestRunOutputMatches( + proc, stderr='Doctest: docs1.txt ... ok') + self.assertEqual(proc.poll(), 0) diff --git a/nose2/tests/functional/test_loading.py b/nose2/tests/functional/test_loading.py index e33029f..c169539 100644 --- a/nose2/tests/functional/test_loading.py +++ b/nose2/tests/functional/test_loading.py @@ -22,6 +22,22 @@ from nose2.tests._common import FunctionalTestCase, support_file class TestLoadTestsFromPackage(FunctionalTestCase): + def test_start_directory_inside_package(self): + proc = self.runIn( + 'scenario/tests_in_package/pkg1/test', + '-v', + '-t', + support_file('scenario/tests_in_package')) + self.assertTestRunOutputMatches(proc, stderr='Ran 25 tests') + self.assertEqual(proc.poll(), 1) + + def test_project_directory_inside_package(self): + proc = self.runIn( + 'scenario/tests_in_package/pkg1/test', + '-v') + self.assertTestRunOutputMatches(proc, stderr='Ran 25 tests') + self.assertEqual(proc.poll(), 1) + def test_module_name(self): proc = self.runIn( 'scenario/tests_in_package', diff --git a/nose2/tests/functional/test_loadtests_plugin.py b/nose2/tests/functional/test_loadtests_plugin.py index 8063711..a559113 100644 --- a/nose2/tests/functional/test_loadtests_plugin.py +++ b/nose2/tests/functional/test_loadtests_plugin.py @@ -29,3 +29,14 @@ class TestLoadTestsPlugin(FunctionalTestCase): proc, stderr='test..ltpkg.tests.test_find_these.Test') self.assertTestRunOutputMatches( proc, stderr='test..ltpkg2.tests.Test') + + def test_project_directory_inside_package(self): + proc = self.runIn( + 'scenario/load_tests_pkg/ltpkg/tests', + '-v', + '-c=' + 'nose2/tests/functional/support/scenario/load_tests_pkg/unittest.cfg', + '--plugin=nose2.plugins.loader.loadtests') + self.assertTestRunOutputMatches(proc, stderr='Ran 1 test') + self.assertTestRunOutputMatches( + proc, stderr='test..ltpkg.tests.test_find_these.Test') diff --git a/nose2/tests/functional/test_util.py b/nose2/tests/functional/test_util.py index db4326d..d0d215d 100644 --- a/nose2/tests/functional/test_util.py +++ b/nose2/tests/functional/test_util.py @@ -5,5 +5,9 @@ from nose2 import util class UtilTests(TestCase): def test_name_from_path(self): + test_module = support_file('scenario/tests_in_package/pkg1/test/test_things.py') + test_package_path = support_file('scenario/tests_in_package') self.assertEqual( - util.name_from_path(support_file('scenario/tests_in_package/pkg1/test/test_things.py')), 'pkg1.test.test_things') + util.name_from_path(test_module), + ('pkg1.test.test_things', test_package_path) + ) diff --git a/nose2/tests/unit/test_util.py b/nose2/tests/unit/test_util.py new file mode 100644 index 0000000..e1deace --- /dev/null +++ b/nose2/tests/unit/test_util.py @@ -0,0 +1,16 @@ +import os +import sys + +from nose2.tests._common import TestCase +from nose2 import util + + +class UtilTests(TestCase): + _RUN_IN_TEMP = True + + def test_ensure_importable(self): + test_dir = os.path.join(self._work_dir, 'test_dir') + # Make sure test data is suitable for the test + self.assertNotIn(test_dir, sys.path) + util.ensure_importable(test_dir) + self.assertEqual(test_dir, sys.path[0])
{ "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": 2, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
0.5
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[coverage_plugin]", "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@dea5854cb40f1327989933004a8835e3766b33fd#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_doctests_plugin.py::TestDoctestsPlugin::test_project_directory_inside_package", "nose2/tests/functional/test_doctests_plugin.py::TestDoctestsPlugin::test_simple", "nose2/tests/functional/test_doctests_plugin.py::TestDoctestsPlugin::test_start_directory_inside_package", "nose2/tests/functional/test_util.py::UtilTests::test_name_from_path" ]
[ "nose2/tests/functional/test_loadtests_plugin.py::TestLoadTestsPlugin::test_package" ]
[ "nose2/tests/functional/support/scenario/doctests/docs.rst::docs.rst", "nose2/tests/functional/support/scenario/doctests/doctests_pkg1/docs1.rst::docs1.rst", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_function_name", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_generator_function_index", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_generator_function_index_1_based", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_generator_function_name", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_generator_method", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_generator_method_index", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_module_name", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_module_name_with_start_dir", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_package_name", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_package_name_with_start_dir", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_parameterized_func", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_parameterized_func_index", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_parameterized_method", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_parameterized_method_index", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_project_directory_inside_package", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_start_directory_inside_package", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_testcase_method", "nose2/tests/functional/test_loading.py::TestLoadTestsFromPackage::test_testcase_name", "nose2/tests/functional/test_loading.py::TestLoadTestsOutsideOfPackage::test_function_name", "nose2/tests/functional/test_loading.py::TestLoadTestsOutsideOfPackage::test_module_name", "nose2/tests/functional/test_loading.py::TestLoadTestsOutsideOfPackage::test_module_name_with_start_dir", "nose2/tests/functional/test_loading.py::TestLoadingErrors::test_import_error_func", "nose2/tests/functional/test_loading.py::TestLoadingErrors::test_import_error_module", "nose2/tests/functional/test_loading.py::TestLoadingErrors::test_import_error_testcase", "nose2/tests/functional/test_loading.py::TestLoadingErrors::test_import_error_testcase_method", "nose2/tests/functional/test_loading.py::TestTestClassLoading::test_class_level_fixtures_supported", "nose2/tests/functional/test_loading.py::TestTestClassLoading::test_error_in_test_class", "nose2/tests/functional/test_loading.py::TestTestClassLoading::test_expected_failures", "nose2/tests/functional/test_loading.py::TestTestClassLoading::test_load_testclass_by_name", "nose2/tests/functional/test_loading.py::TestTestClassLoading::test_load_testclass_generator_method_by_name", "nose2/tests/functional/test_loading.py::TestTestClassLoading::test_load_testclass_method_by_name", "nose2/tests/functional/test_loading.py::TestTestClassLoading::test_load_testclass_params_method_by_name", "nose2/tests/functional/test_loadtests_plugin.py::TestLoadTestsPlugin::test_project_directory_inside_package", "nose2/tests/functional/test_loadtests_plugin.py::TestLoadTestsPlugin::test_simple", "nose2/tests/unit/test_util.py::UtilTests::test_ensure_importable" ]
[]
BSD
10
[ "nose2/util.py", "nose2/plugins/loader/discovery.py" ]
[ "nose2/util.py", "nose2/plugins/loader/discovery.py" ]
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
[ "setup.py", "jwt/algorithms.py", "jwt/utils.py", "jwt/__init__.py" ]
[ "setup.py", "jwt/algorithms.py", "jwt/utils.py", "jwt/__init__.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
[ "tinydb/database.py" ]
[ "tinydb/database.py" ]
gabrielfalcao__HTTPretty-207
ac839f7b5a1a09e61e343f87cb399d2d8825bfb1
2015-01-07 15:39:14
2471cd11fe14d8a9384abc53fc1fe0f1b1daecb7
diff --git a/httpretty/core.py b/httpretty/core.py index 25926a0..a1b2469 100644 --- a/httpretty/core.py +++ b/httpretty/core.py @@ -290,9 +290,18 @@ class fakesock(object): self.type = type def connect(self, address): - self._address = (self._host, self._port) = address self._closed = False - self.is_http = self._port in POTENTIAL_HTTP_PORTS | POTENTIAL_HTTPS_PORTS + + try: + self._address = (self._host, self._port) = address + except ValueError: + # We get here when the address is just a string pointing to a + # unix socket path/file + # + # See issue #206 + self.is_http = False + else: + self.is_http = self._port in POTENTIAL_HTTP_PORTS | POTENTIAL_HTTPS_PORTS if not self.is_http: if self.truesock:
httpretty crashes if program uses unix sockets ``` def connect(self, address): self._address = (self._host, self._port) = address ``` Crashes with `too many values to unpack` because unix socket addresses are just files. Working on a PR.
gabrielfalcao/HTTPretty
diff --git a/tests/unit/test_httpretty.py b/tests/unit/test_httpretty.py index d26caf4..3059c12 100644 --- a/tests/unit/test_httpretty.py +++ b/tests/unit/test_httpretty.py @@ -353,6 +353,18 @@ def test_fake_socket_passes_through_shutdown(): expect(s.shutdown).called_with(socket.SHUT_RD).should_not.throw(AttributeError) s.truesock.shutdown.assert_called_with(socket.SHUT_RD) +def test_unix_socket(): + import socket + HTTPretty.enable() + + # Create a UDS socket + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + server_address = './not-exist-socket' + try: + sock.connect(server_address) + except socket.error: + # We expect this, since the server_address does not exist + pass def test_HTTPrettyRequest_json_body(): """ A content-type of application/json should parse a valid json body """
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 2 }, "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": [ "nose", "coverage", "mock", "sure", "httplib2", "requests", "tornado", "pytest" ], "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==3.7.1 exceptiongroup==1.2.2 httplib2==0.8 -e git+https://github.com/gabrielfalcao/HTTPretty.git@ac839f7b5a1a09e61e343f87cb399d2d8825bfb1#egg=httpretty iniconfig==2.1.0 mock==1.0.1 nose==1.3.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 requests==2.15.1 sure==1.2.3 tomli==2.2.1 tornado==3.2 urllib3==1.7.1
name: HTTPretty 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==3.7.1 - exceptiongroup==1.2.2 - httplib2==0.8 - iniconfig==2.1.0 - mock==1.0.1 - nose==1.3.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - requests==2.15.1 - sure==1.2.3 - tomli==2.2.1 - tornado==3.2 - urllib3==1.7.1 prefix: /opt/conda/envs/HTTPretty
[ "tests/unit/test_httpretty.py::test_unix_socket" ]
[]
[ "tests/unit/test_httpretty.py::test_httpretty_should_raise_proper_exception_on_inconsistent_length", "tests/unit/test_httpretty.py::test_httpretty_should_raise_on_socket_send_when_uri_registered", "tests/unit/test_httpretty.py::test_httpretty_should_not_raise_on_socket_send_when_uri_not_registered", "tests/unit/test_httpretty.py::test_does_not_have_last_request_by_default", "tests/unit/test_httpretty.py::test_status_codes", "tests/unit/test_httpretty.py::test_uri_info_full_url", "tests/unit/test_httpretty.py::test_uri_info_eq_ignores_case", "tests/unit/test_httpretty.py::test_global_boolean_enabled", "tests/unit/test_httpretty.py::test_py3kobject_implements_valid__repr__based_on__str__", "tests/unit/test_httpretty.py::test_Entry_class_normalizes_headers", "tests/unit/test_httpretty.py::test_Entry_class_counts_multibyte_characters_in_bytes", "tests/unit/test_httpretty.py::test_fake_socket_passes_through_setblocking", "tests/unit/test_httpretty.py::test_fake_socket_passes_through_fileno", "tests/unit/test_httpretty.py::test_fake_socket_passes_through_getsockopt", "tests/unit/test_httpretty.py::test_fake_socket_passes_through_bind", "tests/unit/test_httpretty.py::test_fake_socket_passes_through_connect_ex", "tests/unit/test_httpretty.py::test_fake_socket_passes_through_listen", "tests/unit/test_httpretty.py::test_fake_socket_passes_through_getpeername", "tests/unit/test_httpretty.py::test_fake_socket_passes_through_getsockname", "tests/unit/test_httpretty.py::test_fake_socket_passes_through_gettimeout", "tests/unit/test_httpretty.py::test_fake_socket_passes_through_shutdown", "tests/unit/test_httpretty.py::test_HTTPrettyRequest_json_body", "tests/unit/test_httpretty.py::test_HTTPrettyRequest_invalid_json_body", "tests/unit/test_httpretty.py::test_HTTPrettyRequest_queryparam", "tests/unit/test_httpretty.py::test_HTTPrettyRequest_arbitrarypost" ]
[]
MIT License
13
[ "httpretty/core.py" ]
[ "httpretty/core.py" ]
bokeh__bokeh-1641
f531eea62a0c5713575a72fc0e309b8fd9d3aaa9
2015-01-07 18:45:52
06016265b60f9cd6dba0fcf9bb7a5bf64b096244
diff --git a/bokeh/resources.py b/bokeh/resources.py index b78021b7a..3fdf39ebf 100644 --- a/bokeh/resources.py +++ b/bokeh/resources.py @@ -245,7 +245,7 @@ class Resources(object): def pad(text, n=4): return "\n".join([ " "*n + line for line in text.split("\n") ]) - wrapper = lambda code: '$(function() {\n%s\n});' % pad(code) + wrapper = lambda code: 'Bokeh.$(function() {\n%s\n});' % pad(code) if self.dev: js_wrapper = lambda code: 'require(["jquery", "main"], function($, Bokeh) {\nBokeh.set_log_level("%s");\n%s\n});' % (self.log_level, pad(wrapper(code)))
$ can get overridden in the Notebook It is (evidently) possible for other libraries to override `$`, and then our use of `$(function() ...)` as `js_wrapper` here: https://github.com/bokeh/bokeh/blob/master/bokeh/resources.py#L248 is fragile, and can cause problems, specifically plots not reloading. This was reported here: https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/7CJxL7cKxXs @mattpap just changing to `Bokeh.$` seems to work fine. Do you have any other input?
bokeh/bokeh
diff --git a/bokeh/tests/test_resources.py b/bokeh/tests/test_resources.py index a94b08daf..3d6858293 100644 --- a/bokeh/tests/test_resources.py +++ b/bokeh/tests/test_resources.py @@ -5,13 +5,13 @@ from os.path import join import bokeh import bokeh.resources as resources -WRAPPER = """$(function() { +WRAPPER = """Bokeh.$(function() { foo });""" WRAPPER_DEV = '''require(["jquery", "main"], function($, Bokeh) { Bokeh.set_log_level("info"); - $(function() { + Bokeh.$(function() { foo }); });'''
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
0.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install bokeh", "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" }
bokeh==3.4.3 contourpy==1.3.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pillow==11.1.0 pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 six==1.17.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tornado==6.4.2 tzdata==2025.2 xyzservices==2025.1.0
name: bokeh 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 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - bokeh==3.4.3 - contourpy==1.3.0 - jinja2==3.1.6 - markupsafe==3.0.2 - numpy==2.0.2 - pandas==2.2.3 - pillow==11.1.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - six==1.17.0 - tornado==6.4.2 - tzdata==2025.2 - xyzservices==2025.1.0 prefix: /opt/conda/envs/bokeh
[ "bokeh/tests/test_resources.py::TestResources::test_js_wrapper" ]
[ "bokeh/tests/test_resources.py::TestResources::test_inline", "bokeh/tests/test_resources.py::TestResources::test_log_level" ]
[ "bokeh/tests/test_resources.py::TestResources::test_absolute", "bokeh/tests/test_resources.py::TestResources::test_absolute_dev", "bokeh/tests/test_resources.py::TestResources::test_argument_checks", "bokeh/tests/test_resources.py::TestResources::test_basic", "bokeh/tests/test_resources.py::TestResources::test_cdn", "bokeh/tests/test_resources.py::TestResources::test_module_attrs", "bokeh/tests/test_resources.py::TestResources::test_relative", "bokeh/tests/test_resources.py::TestResources::test_relative_dev", "bokeh/tests/test_resources.py::TestResources::test_server", "bokeh/tests/test_resources.py::TestResources::test_server_dev" ]
[]
BSD 3-Clause "New" or "Revised" License
15
[ "bokeh/resources.py" ]
[ "bokeh/resources.py" ]
networkx__networkx-1328
c00cf03675a605dd687ef28f7ae312b90f83aedd
2015-01-10 15:27:34
965640e7399c669980243d8b162c4521339f294f
diff --git a/doc/source/developer/gitwash/forking_hell.rst b/doc/source/developer/gitwash/forking_hell.rst index 1e29fc800..26b802ca0 100644 --- a/doc/source/developer/gitwash/forking_hell.rst +++ b/doc/source/developer/gitwash/forking_hell.rst @@ -5,7 +5,7 @@ Making your own copy (fork) of networkx ====================================================== You need to do this only once. The instructions here are very similar -to the instructions at https://help.github.com/articles/fork-a-repo/ |emdash| please see +to the instructions at http://help.github.com/forking/ |emdash| please see that page for more detail. We're repeating some of it here just to give the specifics for the `networkx`_ project, and to suggest some default names. diff --git a/doc/source/developer/gitwash/git_links.inc b/doc/source/developer/gitwash/git_links.inc index 65ba945b1..8e628ae19 100644 --- a/doc/source/developer/gitwash/git_links.inc +++ b/doc/source/developer/gitwash/git_links.inc @@ -1,7 +1,7 @@ .. This (-*- rst -*-) format file contains commonly used link targets - and name substitutions. It may be included in many files, + and name substitutions. It may be included in many files, therefore it should only contain link targets and name - substitutions. Try grepping for "^\.\. _" to find plausible + substitutions. Try grepping for "^\.\. _" to find plausible candidates for this list. .. NOTE: reST targets are @@ -12,16 +12,20 @@ .. _git: http://git-scm.com/ .. _github: http://github.com .. _github help: http://help.github.com -.. _github more help: https://help.github.com/articles/what-are-other-good-resources-for-learning-git-and-github/ .. _msysgit: http://code.google.com/p/msysgit/downloads/list .. _git-osx-installer: http://code.google.com/p/git-osx-installer/downloads/list .. _subversion: http://subversion.tigris.org/ +.. _git cheat sheet: http://github.com/guides/git-cheat-sheet +.. _pro git book: http://progit.org/ .. _git svn crash course: http://git-scm.com/course/svn.html +.. _learn.github: http://learn.github.com/ .. _network graph visualizer: http://github.com/blog/39-say-hello-to-the-network-graph-visualizer .. _git user manual: http://schacon.github.com/git/user-manual.html .. _git tutorial: http://schacon.github.com/git/gittutorial.html -.. _Nick Quaranto: http://www.gitready.com/ -.. _Fernando Perez: http://www.fperez.org/py4science/git.html +.. _git community book: http://book.git-scm.com/ +.. _git ready: http://www.gitready.com/ +.. _git casts: http://www.gitcasts.com/ +.. _Fernando's git page: http://www.fperez.org/py4science/git.html .. _git magic: http://www-cs-students.stanford.edu/~blynn/gitmagic/index.html .. _git concepts: http://www.eecs.harvard.edu/~cduan/technical/git/ .. _git clone: http://schacon.github.com/git/git-clone.html @@ -40,7 +44,8 @@ .. _why the -a flag?: http://www.gitready.com/beginner/2009/01/18/the-staging-area.html .. _git staging area: http://www.gitready.com/beginner/2009/01/18/the-staging-area.html .. _tangled working copy problem: http://tomayko.com/writings/the-thing-about-git -.. _Linus Torvalds: http://www.mail-archive.com/[email protected]/msg39091.html +.. _git management: http://kerneltrap.org/Linux/Git_Management +.. _linux git workflow: http://www.mail-archive.com/[email protected]/msg39091.html .. _git parable: http://tom.preston-werner.com/2009/05/19/the-git-parable.html .. _git foundation: http://matthew-brett.github.com/pydagogue/foundation.html .. _deleting master on github: http://matthew-brett.github.com/pydagogue/gh_delete_master.html diff --git a/doc/source/developer/gitwash/git_resources.rst b/doc/source/developer/gitwash/git_resources.rst index 4ab41c4e5..ba7b275e0 100644 --- a/doc/source/developer/gitwash/git_resources.rst +++ b/doc/source/developer/gitwash/git_resources.rst @@ -7,22 +7,34 @@ git resources Tutorials and summaries ======================= -`github help`_ is Git's own help and tutorial site. `github more help`_ - lists more resources for learning Git and GitHub, including YouTube -channels. The list is constantly updated. In case you are used to subversion_ -, you can directly consult the `git svn crash course`_. - -To make full use of Git, you need to understand the concept behind Git. -The following pages might help you: - -* `git parable`_ |emdash| an easy read parable -* `git foundation`_ |emdash| more on the git parable +* `github help`_ has an excellent series of how-to guides. +* `learn.github`_ has an excellent series of tutorials +* The `pro git book`_ is a good in-depth book on git. +* A `git cheat sheet`_ is a page giving summaries of common commands. +* The `git user manual`_ +* The `git tutorial`_ +* The `git community book`_ +* `git ready`_ |emdash| a nice series of tutorials +* `git casts`_ |emdash| video snippets giving git how-tos. * `git magic`_ |emdash| extended introduction with intermediate detail -in many languages -* `git concepts`_ |emdash| a technical page on the concepts - -Other than that, many devlopers list their personal tips and tricks. -Among others there are `Fernando Perez`_, `Nick Quaranto`_ and `Linus Torvalds`_. +* The `git parable`_ is an easy read explaining the concepts behind git. +* `git foundation`_ expands on the `git parable`_. +* Fernando Perez' git page |emdash| `Fernando's git page`_ |emdash| many + links and tips +* A good but technical page on `git concepts`_ +* `git svn crash course`_: git for those of us used to subversion_ + +Advanced git workflow +===================== + +There are many ways of working with git; here are some posts on the +rules of thumb that other projects have come up with: + +* Linus Torvalds on `git management`_ +* Linus Torvalds on `linux git workflow`_ . Summary; use the git tools + to make the history of your edits as clean as possible; merge from + upstream edits as little as possible in branches where you are doing + active development. Manual pages online =================== diff --git a/networkx/__init__.py b/networkx/__init__.py index ef3f0baa4..1e03e8f58 100644 --- a/networkx/__init__.py +++ b/networkx/__init__.py @@ -50,18 +50,6 @@ __license__ = release.license __date__ = release.date __version__ = release.version -__bibtex__ = """@inproceedings{hagberg-2008-exploring, -author = {Aric A. Hagberg and Daniel A. Schult and Pieter J. Swart}, -title = {Exploring network structure, dynamics, and function using {NetworkX}}, -year = {2008}, -month = Aug, -urlpdf = {http://math.lanl.gov/~hagberg/Papers/hagberg-2008-exploring.pdf}, -booktitle = {Proceedings of the 7th Python in Science Conference (SciPy2008)}, -editors = {G\"{a}el Varoquaux, Travis Vaught, and Jarrod Millman}, -address = {Pasadena, CA USA}, -pages = {11--15} -}""" - #These are import orderwise from networkx.exception import * import networkx.external diff --git a/networkx/classes/digraph.py b/networkx/classes/digraph.py index 9f2a35921..9a5934675 100644 --- a/networkx/classes/digraph.py +++ b/networkx/classes/digraph.py @@ -399,8 +399,16 @@ class DiGraph(Graph): """ for n in nodes: + # keep all this inside try/except because + # CPython throws TypeError on n not in self.succ, + # while pre-2.7.5 ironpython throws on self.succ[n] try: - newnode=n not in self.succ + if n not in self.succ: + self.succ[n] = self.adjlist_dict_factory() + self.pred[n] = self.adjlist_dict_factory() + self.node[n] = attr.copy() + else: + self.node[n].update(attr) except TypeError: nn,ndict = n if nn not in self.succ: @@ -413,13 +421,6 @@ class DiGraph(Graph): olddict = self.node[nn] olddict.update(attr) olddict.update(ndict) - continue - if newnode: - self.succ[n] = self.adjlist_dict_factory() - self.pred[n] = self.adjlist_dict_factory() - self.node[n] = attr.copy() - else: - self.node[n].update(attr) def remove_node(self, n): """Remove node n. diff --git a/networkx/classes/graph.py b/networkx/classes/graph.py index 8d6a1afbf..24203f0d0 100644 --- a/networkx/classes/graph.py +++ b/networkx/classes/graph.py @@ -507,8 +507,15 @@ class Graph(object): """ for n in nodes: + # keep all this inside try/except because + # CPython throws TypeError on n not in self.succ, + # while pre-2.7.5 ironpython throws on self.succ[n] try: - newnode=n not in self.node + if n not in self.node: + self.adj[n] = self.adjlist_dict_factory() + self.node[n] = attr.copy() + else: + self.node[n].update(attr) except TypeError: nn,ndict = n if nn not in self.node: @@ -520,12 +527,6 @@ class Graph(object): olddict = self.node[nn] olddict.update(attr) olddict.update(ndict) - continue - if newnode: - self.adj[n] = self.adjlist_dict_factory() - self.node[n] = attr.copy() - else: - self.node[n].update(attr) def remove_node(self,n): """Remove node n. diff --git a/networkx/drawing/nx_pylab.py b/networkx/drawing/nx_pylab.py index d92a90e83..27eba1e4b 100644 --- a/networkx/drawing/nx_pylab.py +++ b/networkx/drawing/nx_pylab.py @@ -182,7 +182,7 @@ def draw_networkx(G, pos=None, with_labels=True, **kwds): marker, one of 'so^>v<dph8'. alpha : float, optional (default=1.0) - The node and edge transparency + The node transparency cmap : Matplotlib colormap, optional (default=None) Colormap for mapping intensities of nodes @@ -395,7 +395,7 @@ def draw_networkx_edges(G, pos, width=1.0, edge_color='k', style='solid', - alpha=1.0, + alpha=None, edge_cmap=None, edge_vmin=None, edge_vmax=None, diff --git a/networkx/readwrite/json_graph/node_link.py b/networkx/readwrite/json_graph/node_link.py index 4a89fb5a9..530560880 100644 --- a/networkx/readwrite/json_graph/node_link.py +++ b/networkx/readwrite/json_graph/node_link.py @@ -56,9 +56,8 @@ def node_link_data(G, attrs=_attrs): Notes ----- - Graph, node, and link attributes are stored in this format. Note that - attribute keys will be converted to strings in order to comply with - JSON. + Graph, node, and link attributes are stored in this format but keys + for attributes must be strings if you want to serialize with JSON. The default value of attrs will be changed in a future release of NetworkX. @@ -78,7 +77,7 @@ def node_link_data(G, attrs=_attrs): data = {} data['directed'] = G.is_directed() data['multigraph'] = multigraph - data['graph'] = G.graph + data['graph'] = list(G.graph.items()) data['nodes'] = [dict(chain(G.node[n].items(), [(id_, n)])) for n in G] if multigraph: data['links'] = [ @@ -130,7 +129,6 @@ def node_link_graph(data, directed=False, multigraph=True, attrs=_attrs): ----- The default value of attrs will be changed in a future release of NetworkX. - See Also -------- node_link_data, adjacency_data, tree_data @@ -149,7 +147,7 @@ def node_link_graph(data, directed=False, multigraph=True, attrs=_attrs): # Allow 'key' to be omitted from attrs if the graph is not a multigraph. key = None if not multigraph else attrs['key'] mapping = [] - graph.graph = data.get('graph', {}) + graph.graph = dict(data.get('graph', [])) c = count() for d in data['nodes']: node = d.get(id_, next(c))
(Di)Graph.add_nodes_from broken under IronPython It seems that #1314 breaks (Di)Graph.add_nodes_from in IronPython on Travis pretty badly (see https://travis-ci.org/networkx/networkx/jobs/46474504#L3452 for example). I think that I fixed those functions before. IIRC, that was due to `<dict> in <dict>` returning `false` instead of raising `TypeError` in IronPython. #1314 apparently [reintroduced the same logic](https://github.com/networkx/networkx/pull/1314/files#diff-4fe234273eebd1a251430097d68e9854R403). I am not sure if that has been fixed in IronPython, or if .travis.yml is picking up the correct release.
networkx/networkx
diff --git a/doc/source/developer/gitwash/following_latest.rst b/doc/source/developer/gitwash/following_latest.rst index 9498bc359..bfca30786 100644 --- a/doc/source/developer/gitwash/following_latest.rst +++ b/doc/source/developer/gitwash/following_latest.rst @@ -25,33 +25,12 @@ You now have a copy of the code tree in the new ``networkx`` directory. Updating the code ================= -From time to time you may want to pull down the latest code. It is necessary -to add the networkx repository as a remote to your configuration file. We call it -upstream. - - git remote set-url upstream https://github.com/networkx/networkx.git - -Now git knows where to fetch updates from. +From time to time you may want to pull down the latest code. Do this with:: cd networkx - git fetch upstream + git pull The tree in ``networkx`` will now have the latest changes from the initial -repository, unless you have made local changes in the meantime. In this case, you have to merge. - - git merge upstream/master - -It is also possible to update your local fork directly from GitHub: - -1. Open your fork on GitHub. -2. Click on 'Pull Requests'. -3. Click on 'New Pull Request'. By default, GitHub will compare the original with your fork. If -you didn’t make any changes, there is nothing to compare. -4. Click on 'Switching the base' or click 'Edit' and switch the base manually. Now GitHub will -compare your fork with the original, and you should see all the latest changes. -5. Click on 'Click to create a pull request for this comparison' and name your pull request. -6. Click on Send pull request. -7. Scroll down and click 'Merge pull request' and finally 'Confirm merge'. You will be able to merge -it automatically unless you didnot change you local repo. +repository. .. include:: links.inc diff --git a/networkx/readwrite/json_graph/tests/test_node_link.py b/networkx/readwrite/json_graph/tests/test_node_link.py index a9582b765..85c8fd1cb 100644 --- a/networkx/readwrite/json_graph/tests/test_node_link.py +++ b/networkx/readwrite/json_graph/tests/test_node_link.py @@ -23,10 +23,10 @@ class TestNodeLink: assert_equal(H.node[1]['color'],'red') assert_equal(H[1][2]['width'],7) - d = json.dumps(node_link_data(G)) + d=json.dumps(node_link_data(G)) H = node_link_graph(json.loads(d)) assert_equal(H.graph['foo'],'bar') - assert_equal(H.graph['1'],'one') + assert_equal(H.graph[1],'one') assert_equal(H.node[1]['color'],'red') assert_equal(H[1][2]['width'],7)
{ "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": 3, "test_score": 3 }, "num_modified_files": 8 }
1.9
{ "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@c00cf03675a605dd687ef28f7ae312b90f83aedd#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/readwrite/json_graph/tests/test_node_link.py::TestNodeLink::test_graph_attributes" ]
[]
[ "networkx/readwrite/json_graph/tests/test_node_link.py::TestNodeLink::test_graph", "networkx/readwrite/json_graph/tests/test_node_link.py::TestNodeLink::test_digraph", "networkx/readwrite/json_graph/tests/test_node_link.py::TestNodeLink::test_multigraph", "networkx/readwrite/json_graph/tests/test_node_link.py::TestNodeLink::test_unicode_keys", "networkx/readwrite/json_graph/tests/test_node_link.py::TestNodeLink::test_exception" ]
[]
BSD 3-Clause
19
[ "doc/source/developer/gitwash/git_links.inc", "networkx/classes/graph.py", "networkx/readwrite/json_graph/node_link.py", "networkx/classes/digraph.py", "networkx/drawing/nx_pylab.py", "networkx/__init__.py", "doc/source/developer/gitwash/git_resources.rst", "doc/source/developer/gitwash/forking_hell.rst" ]
[ "doc/source/developer/gitwash/git_links.inc", "networkx/classes/graph.py", "networkx/readwrite/json_graph/node_link.py", "networkx/classes/digraph.py", "networkx/drawing/nx_pylab.py", "networkx/__init__.py", "doc/source/developer/gitwash/git_resources.rst", "doc/source/developer/gitwash/forking_hell.rst" ]
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
[ "webapp_health_monitor/verificators/base.py" ]
[ "webapp_health_monitor/verificators/base.py" ]
Pylons__webob-185
ef371de5e78093efc82eb66117cbacca852c9afa
2015-01-14 17:49:34
9b79f5f913fb1f07c68102a2279ed757a2a9abf6
bertjwregeer: Would you be so kind as to add some extra tests that would add coverage for the changes, that would be fantastic.
diff --git a/webob/acceptparse.py b/webob/acceptparse.py index 42f2643..afa0d8f 100644 --- a/webob/acceptparse.py +++ b/webob/acceptparse.py @@ -274,7 +274,7 @@ class MIMEAccept(Accept): def parse(value): for mask, q in Accept.parse(value): try: - mask_major, mask_minor = map(lambda x: x.lower(), mask.split('/')) + mask_major, mask_minor = [x.lower() for x in mask.split('/')] except ValueError: continue if mask_major == '*' and mask_minor != '*': @@ -296,20 +296,62 @@ class MIMEAccept(Accept): accepts_html = property(accept_html) # note the plural + def _match(self, mask, offer): """ Check if the offer is covered by the mask + + ``offer`` may contain wildcards to facilitate checking if a + ``mask`` would match a 'permissive' offer. + + Wildcard matching forces the match to take place against the + type or subtype of the mask and offer (depending on where + the wildcard matches) """ - _check_offer(offer) - if '*' not in mask: - return offer.lower() == mask.lower() - elif mask == '*/*': + # Match if comparisons are the same or either is a complete wildcard + if (mask.lower() == offer.lower() or + '*/*' in (mask, offer) or + '*' == offer): return True - else: - assert mask.endswith('/*') - mask_major = mask[:-2].lower() - offer_major = offer.split('/', 1)[0].lower() - return offer_major == mask_major + + # Set mask type with wildcard subtype for malformed masks + try: + mask_type, mask_subtype = [x.lower() for x in mask.split('/')] + except ValueError: + mask_type = mask + mask_subtype = '*' + + # Set offer type with wildcard subtype for malformed offers + try: + offer_type, offer_subtype = [x.lower() for x in offer.split('/')] + except ValueError: + offer_type = offer + offer_subtype = '*' + + if mask_subtype == '*': + # match on type only + if offer_type == '*': + return True + else: + return mask_type.lower() == offer_type.lower() + + if mask_type == '*': + # match on subtype only + if offer_subtype == '*': + return True + else: + return mask_subtype.lower() == offer_subtype.lower() + + if offer_subtype == '*': + # match on type only + return mask_type.lower() == offer_type.lower() + + if offer_type == '*': + # match on subtype only + return mask_subtype.lower() == offer_subtype.lower() + + return offer.lower() == mask.lower() + class MIMENilAccept(NilAccept):
Accept matching against wildcard offers is not allowed Wildcards cannot be used in 'offered' content types to search for a match: ```python >>> from webob.acceptparse import MIMEAccept >>> accept = MIMEAccept('text/*') >>> 'text/plain' in accept True # Expect this to be True >>> 'text/*' in accept ValueError: The application should offer specific types, got 'text/*' >>> accept.best_match(['text/html', 'text/plain', 'text/json']) 'text/html' # Expect 'text/html' or 'text/plain' in the absence of quality parameter >>> accept.best_match(['text/*', 'text/html', 'text/plain']) ValueError: The application should offer specific types, got 'text/*' # Expect 'text/*' as the best match >>> accept.best_match(['text/*', 'foo/bar']) ValueError: The application should offer specific types, got 'text/*' ``` The behavior and error WebOb provides is explicit and it uses the same [check](https://github.com/Pylons/webob/blob/1.4/webob/acceptparse.py#L320) anywhere it is performing a match: ```python def _check_offer(offer): if '*' in offer: raise ValueError("The application should offer specific types, got %r" % offer) ``` This is not insensible, but it does cause an issue with Pyramid's [documented](http://docs.pylonsproject.org/projects/pyramid/en/latest/api/config.html) accept predicate handling: https://github.com/Pylons/pyramid/issues/1407 If you want to define a 'permissive' accept predicate like `text/*`, the Pyramid `AcceptPredicate` essentially boils down to: ```python return 'text/*' in request.accept ``` `request.accept` is a WebOb `MIMEAccept` instance, so this check will always fail.
Pylons/webob
diff --git a/tests/test_acceptparse.py b/tests/test_acceptparse.py index 9183e95..a5e8c15 100644 --- a/tests/test_acceptparse.py +++ b/tests/test_acceptparse.py @@ -271,7 +271,69 @@ def test_match(): assert mimeaccept._match('image/*', 'image/jpg') assert mimeaccept._match('*/*', 'image/jpg') assert not mimeaccept._match('text/html', 'image/jpg') - assert_raises(ValueError, mimeaccept._match, 'image/jpg', '*/*') + + mismatches = [ + ('B/b', 'A/a'), + ('B/b', 'B/a'), + ('B/b', 'A/b'), + ('A/a', 'B/b'), + ('B/a', 'B/b'), + ('A/b', 'B/b') + ] + for mask, offer in mismatches: + assert not mimeaccept._match(mask, offer) + + +def test_wildcard_matching(): + """ + Wildcard matching forces the match to take place against the type + or subtype of the mask and offer (depending on where the wildcard + matches) + """ + mimeaccept = MIMEAccept('type/subtype') + matches = [ + ('*/*', '*/*'), + ('*/*', 'A/*'), + ('*/*', '*/a'), + ('*/*', 'A/a'), + ('A/*', '*/*'), + ('A/*', 'A/*'), + ('A/*', '*/a'), + ('A/*', 'A/a'), + ('*/a', '*/*'), + ('*/a', 'A/*'), + ('*/a', '*/a'), + ('*/a', 'A/a'), + ('A/a', '*/*'), + ('A/a', 'A/*'), + ('A/a', '*/a'), + ('A/a', 'A/a'), + # Offers might not contain a subtype + ('*/*', '*'), + ('A/*', '*'), + ('*/a', '*')] + for mask, offer in matches: + assert mimeaccept._match(mask, offer) + # Test malformed mask and offer variants where either is missing + # a type or subtype + assert mimeaccept._match('A', offer) + assert mimeaccept._match(mask, 'a') + + mismatches = [ + ('B/b', 'A/*'), + ('B/*', 'A/a'), + ('B/*', 'A/*'), + ('*/b', '*/a')] + for mask, offer in mismatches: + assert not mimeaccept._match(mask, offer) + +def test_mimeaccept_contains(): + mimeaccept = MIMEAccept('A/a, B/b, C/c') + assert 'A/a' in mimeaccept + assert 'A/*' in mimeaccept + assert '*/a' in mimeaccept + assert not 'A/b' in mimeaccept + assert not 'B/a' in mimeaccept def test_accept_json(): mimeaccept = MIMEAccept('text/html, *; q=.2, */*; q=.2') diff --git a/tests/test_request.py b/tests/test_request.py index 24c7aa0..0e0ec9b 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -2444,7 +2444,6 @@ class TestRequest_functional(unittest.TestCase): self.assertTrue(not self._blankOne('/', headers={'Accept': ''}).accept) req = self._blankOne('/', headers={'Accept':'text/plain'}) self.assertTrue(req.accept) - self.assertRaises(ValueError, req.accept.best_match, ['*/*']) req = self._blankOne('/', accept=['*/*','text/*']) self.assertEqual( req.accept.best_match(['application/x-foo', 'text/plain']),
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 1 }
1.4
{ "env_vars": null, "env_yml_path": null, "install": "pip install -e .[testing]", "log_parser": "parse_log_pytest", "no_use_env": null, "packages": "requirements.txt", "pip_packages": [ "pytest pytest-cov", "pytest" ], "pre_install": null, "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 iniconfig==2.1.0 nose==1.3.7 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/Pylons/webob.git@ef371de5e78093efc82eb66117cbacca852c9afa#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 - 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 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-cov==6.0.0 - tomli==2.2.1 prefix: /opt/conda/envs/webob
[ "tests/test_acceptparse.py::test_wildcard_matching", "tests/test_acceptparse.py::test_mimeaccept_contains" ]
[]
[ "tests/test_acceptparse.py::test_parse_accept_badq", "tests/test_acceptparse.py::test_init_accept_content_type", "tests/test_acceptparse.py::test_init_accept_accept_charset", "tests/test_acceptparse.py::test_init_accept_accept_charset_mixedcase", "tests/test_acceptparse.py::test_init_accept_accept_charset_with_iso_8859_1", "tests/test_acceptparse.py::test_init_accept_accept_charset_wildcard", "tests/test_acceptparse.py::test_init_accept_accept_language", "tests/test_acceptparse.py::test_init_accept_invalid_value", "tests/test_acceptparse.py::test_init_accept_invalid_q_value", "tests/test_acceptparse.py::test_accept_repr", "tests/test_acceptparse.py::test_accept_str", "tests/test_acceptparse.py::test_zero_quality", "tests/test_acceptparse.py::test_accept_str_with_q_not_1", "tests/test_acceptparse.py::test_accept_str_with_q_not_1_multiple", "tests/test_acceptparse.py::test_accept_add_other_accept", "tests/test_acceptparse.py::test_accept_add_other_list_of_tuples", "tests/test_acceptparse.py::test_accept_add_other_dict", "tests/test_acceptparse.py::test_accept_add_other_empty_str", "tests/test_acceptparse.py::test_accept_with_no_value_add_other_str", "tests/test_acceptparse.py::test_contains", "tests/test_acceptparse.py::test_contains_not", "tests/test_acceptparse.py::test_quality", "tests/test_acceptparse.py::test_quality_not_found", "tests/test_acceptparse.py::test_best_match", "tests/test_acceptparse.py::test_best_match_with_one_lower_q", "tests/test_acceptparse.py::test_best_match_with_complex_q", "tests/test_acceptparse.py::test_accept_match", "tests/test_acceptparse.py::test_accept_match_lang", "tests/test_acceptparse.py::test_nil", "tests/test_acceptparse.py::test_nil_add", "tests/test_acceptparse.py::test_nil_radd", "tests/test_acceptparse.py::test_nil_radd_masterclass", "tests/test_acceptparse.py::test_nil_contains", "tests/test_acceptparse.py::test_nil_best_match", "tests/test_acceptparse.py::test_noaccept_contains", "tests/test_acceptparse.py::test_mime_init", "tests/test_acceptparse.py::test_accept_html", "tests/test_acceptparse.py::test_match", "tests/test_acceptparse.py::test_accept_json", "tests/test_acceptparse.py::test_accept_mixedcase", "tests/test_acceptparse.py::test_match_mixedcase", "tests/test_acceptparse.py::test_match_uppercase_q", "tests/test_acceptparse.py::test_accept_property_fget", "tests/test_acceptparse.py::test_accept_property_fget_nil", "tests/test_acceptparse.py::test_accept_property_fset", "tests/test_acceptparse.py::test_accept_property_fset_acceptclass", "tests/test_acceptparse.py::test_accept_property_fdel", "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_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_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
21
[ "webob/acceptparse.py" ]
[ "webob/acceptparse.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
[ "IPython/utils/io.py" ]
[ "IPython/utils/io.py" ]
wearpants__twiggy-49
e99fdc19049dd06efdbc6c48e133ea8856a491a7
2015-01-16 16:17:09
e99fdc19049dd06efdbc6c48e133ea8856a491a7
diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..28e0a81 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,15 @@ +language: python + +sudo: false +env: + - TOXENV=py26 + - TOXENV=py27 + - TOXENV=py33 + - TOXENV=py34 + - TOXENV=pypy + +install: + - travis_retry pip install tox + +script: + - tox diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..2e98e9e --- /dev/null +++ b/tox.ini @@ -0,0 +1,19 @@ +# Tox (http://tox.testrun.org/) is a tool for running tests +# in multiple virtualenvs. This configuration file will run the +# test suite on all supported python versions. To use it, "pip install tox" +# and then run "tox" from this directory. + +[tox] +envlist = py26, py27, pypy, py33, py34 + +[testenv] +setenv = + TWIGGY_UNDER_TEST=1 +commands = py.test {posargs:--tb=short tests/} +deps = + pytest + +[testenv:py26] +deps = + pytest + unittest2 diff --git a/twiggy/__init__.py b/twiggy/__init__.py index 56c73a4..0ae6a14 100644 --- a/twiggy/__init__.py +++ b/twiggy/__init__.py @@ -3,11 +3,11 @@ import time import sys import os -import logger -import filters -import formats -import outputs -import levels +from . import logger +from . import filters +from . import formats +from . import outputs +from . import levels ## globals creation is wrapped in a function so that we can do sane testing diff --git a/twiggy/compat.py b/twiggy/compat.py new file mode 100644 index 0000000..6bc97c4 --- /dev/null +++ b/twiggy/compat.py @@ -0,0 +1,652 @@ +"""Utilities for writing code that runs on Python 2 and 3""" + +# Copyright (c) 2010-2014 Benjamin Peterson +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import operator +import sys +import types + +__author__ = "Benjamin Peterson <[email protected]>" +__version__ = "1.6.1" + + +# Useful for very coarse version differentiation. +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] == 3 + +if PY3: + string_types = str, + integer_types = int, + class_types = type, + text_type = str + binary_type = bytes + + MAXSIZE = sys.maxsize +else: + string_types = basestring, + integer_types = (int, long) + class_types = (type, types.ClassType) + text_type = unicode + binary_type = str + + if sys.platform.startswith("java"): + # Jython always uses 32 bits. + MAXSIZE = int((1 << 31) - 1) + else: + # It's possible to have sizeof(long) != sizeof(Py_ssize_t). + class X(object): + def __len__(self): + return 1 << 31 + try: + len(X()) + except OverflowError: + # 32-bit + MAXSIZE = int((1 << 31) - 1) + else: + # 64-bit + MAXSIZE = int((1 << 63) - 1) + del X + + +def _add_doc(func, doc): + """Add documentation to a function.""" + func.__doc__ = doc + + +def _import_module(name): + """Import module, returning the module after the last dot.""" + __import__(name) + return sys.modules[name] + + +class _LazyDescr(object): + + def __init__(self, name): + self.name = name + + def __get__(self, obj, tp): + try: + result = self._resolve() + except ImportError: + # See the nice big comment in MovedModule.__getattr__. + raise AttributeError("%s could not be imported " % self.name) + setattr(obj, self.name, result) # Invokes __set__. + # This is a bit ugly, but it avoids running this again. + delattr(obj.__class__, self.name) + return result + + +class MovedModule(_LazyDescr): + + def __init__(self, name, old, new=None): + super(MovedModule, self).__init__(name) + if PY3: + if new is None: + new = name + self.mod = new + else: + self.mod = old + + def _resolve(self): + return _import_module(self.mod) + + def __getattr__(self, attr): + # It turns out many Python frameworks like to traverse sys.modules and + # try to load various attributes. This causes problems if this is a + # platform-specific module on the wrong platform, like _winreg on + # Unixes. Therefore, we silently pretend unimportable modules do not + # have any attributes. See issues #51, #53, #56, and #63 for the full + # tales of woe. + # + # First, if possible, avoid loading the module just to look at __file__, + # __name__, or __path__. + if (attr in ("__file__", "__name__", "__path__") and + self.mod not in sys.modules): + raise AttributeError(attr) + try: + _module = self._resolve() + except ImportError: + raise AttributeError(attr) + value = getattr(_module, attr) + setattr(self, attr, value) + return value + + +class _LazyModule(types.ModuleType): + + def __init__(self, name): + super(_LazyModule, self).__init__(name) + self.__doc__ = self.__class__.__doc__ + + def __dir__(self): + attrs = ["__doc__", "__name__"] + attrs += [attr.name for attr in self._moved_attributes] + return attrs + + # Subclasses should override this + _moved_attributes = [] + + +class MovedAttribute(_LazyDescr): + + def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): + super(MovedAttribute, self).__init__(name) + if PY3: + if new_mod is None: + new_mod = name + self.mod = new_mod + if new_attr is None: + if old_attr is None: + new_attr = name + else: + new_attr = old_attr + self.attr = new_attr + else: + self.mod = old_mod + if old_attr is None: + old_attr = name + self.attr = old_attr + + def _resolve(self): + module = _import_module(self.mod) + return getattr(module, self.attr) + + + +class _MovedItems(_LazyModule): + """Lazy loading of moved objects""" + + +_moved_attributes = [ + MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), + MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), + MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), + MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), + MovedAttribute("map", "itertools", "builtins", "imap", "map"), + MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("reload_module", "__builtin__", "imp", "reload"), + MovedAttribute("reduce", "__builtin__", "functools"), + MovedAttribute("StringIO", "StringIO", "io"), + MovedAttribute("UserString", "UserString", "collections"), + MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), + MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), + + MovedModule("builtins", "__builtin__"), + MovedModule("configparser", "ConfigParser"), + MovedModule("copyreg", "copy_reg"), + MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), + MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), + MovedModule("http_cookies", "Cookie", "http.cookies"), + MovedModule("html_entities", "htmlentitydefs", "html.entities"), + MovedModule("html_parser", "HTMLParser", "html.parser"), + MovedModule("http_client", "httplib", "http.client"), + MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), + MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), + MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), + MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), + MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), + MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), + MovedModule("cPickle", "cPickle", "pickle"), + MovedModule("queue", "Queue"), + MovedModule("reprlib", "repr"), + MovedModule("socketserver", "SocketServer"), + MovedModule("_thread", "thread", "_thread"), + MovedModule("tkinter", "Tkinter"), + MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), + MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), + MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), + MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), + MovedModule("tkinter_tix", "Tix", "tkinter.tix"), + MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), + MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), + MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), + MovedModule("tkinter_colorchooser", "tkColorChooser", + "tkinter.colorchooser"), + MovedModule("tkinter_commondialog", "tkCommonDialog", + "tkinter.commondialog"), + MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), + MovedModule("tkinter_font", "tkFont", "tkinter.font"), + MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), + MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", + "tkinter.simpledialog"), + MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), + MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), + MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), + MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), + MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), + MovedModule("xmlrpc_server", "xmlrpclib", "xmlrpc.server"), + MovedModule("winreg", "_winreg"), +] +for attr in _moved_attributes: + setattr(_MovedItems, attr.name, attr) + if isinstance(attr, MovedModule): + sys.modules[__name__ + ".moves." + attr.name] = attr +del attr + +_MovedItems._moved_attributes = _moved_attributes + +moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves") + + +class Module_six_moves_urllib_parse(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_parse""" + + +_urllib_parse_moved_attributes = [ + MovedAttribute("ParseResult", "urlparse", "urllib.parse"), + MovedAttribute("SplitResult", "urlparse", "urllib.parse"), + MovedAttribute("parse_qs", "urlparse", "urllib.parse"), + MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), + MovedAttribute("urldefrag", "urlparse", "urllib.parse"), + MovedAttribute("urljoin", "urlparse", "urllib.parse"), + MovedAttribute("urlparse", "urlparse", "urllib.parse"), + MovedAttribute("urlsplit", "urlparse", "urllib.parse"), + MovedAttribute("urlunparse", "urlparse", "urllib.parse"), + MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), + MovedAttribute("quote", "urllib", "urllib.parse"), + MovedAttribute("quote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote", "urllib", "urllib.parse"), + MovedAttribute("unquote_plus", "urllib", "urllib.parse"), + MovedAttribute("urlencode", "urllib", "urllib.parse"), + MovedAttribute("splitquery", "urllib", "urllib.parse"), +] +for attr in _urllib_parse_moved_attributes: + setattr(Module_six_moves_urllib_parse, attr.name, attr) +del attr + +Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes + +sys.modules[__name__ + ".moves.urllib_parse"] = sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse") + + +class Module_six_moves_urllib_error(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_error""" + + +_urllib_error_moved_attributes = [ + MovedAttribute("URLError", "urllib2", "urllib.error"), + MovedAttribute("HTTPError", "urllib2", "urllib.error"), + MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), +] +for attr in _urllib_error_moved_attributes: + setattr(Module_six_moves_urllib_error, attr.name, attr) +del attr + +Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes + +sys.modules[__name__ + ".moves.urllib_error"] = sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error") + + +class Module_six_moves_urllib_request(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_request""" + + +_urllib_request_moved_attributes = [ + MovedAttribute("urlopen", "urllib2", "urllib.request"), + MovedAttribute("install_opener", "urllib2", "urllib.request"), + MovedAttribute("build_opener", "urllib2", "urllib.request"), + MovedAttribute("pathname2url", "urllib", "urllib.request"), + MovedAttribute("url2pathname", "urllib", "urllib.request"), + MovedAttribute("getproxies", "urllib", "urllib.request"), + MovedAttribute("Request", "urllib2", "urllib.request"), + MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), + MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), + MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), + MovedAttribute("BaseHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), + MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), + MovedAttribute("FileHandler", "urllib2", "urllib.request"), + MovedAttribute("FTPHandler", "urllib2", "urllib.request"), + MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), + MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), + MovedAttribute("urlretrieve", "urllib", "urllib.request"), + MovedAttribute("urlcleanup", "urllib", "urllib.request"), + MovedAttribute("URLopener", "urllib", "urllib.request"), + MovedAttribute("FancyURLopener", "urllib", "urllib.request"), + MovedAttribute("proxy_bypass", "urllib", "urllib.request"), +] +for attr in _urllib_request_moved_attributes: + setattr(Module_six_moves_urllib_request, attr.name, attr) +del attr + +Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes + +sys.modules[__name__ + ".moves.urllib_request"] = sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request") + + +class Module_six_moves_urllib_response(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_response""" + + +_urllib_response_moved_attributes = [ + MovedAttribute("addbase", "urllib", "urllib.response"), + MovedAttribute("addclosehook", "urllib", "urllib.response"), + MovedAttribute("addinfo", "urllib", "urllib.response"), + MovedAttribute("addinfourl", "urllib", "urllib.response"), +] +for attr in _urllib_response_moved_attributes: + setattr(Module_six_moves_urllib_response, attr.name, attr) +del attr + +Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes + +sys.modules[__name__ + ".moves.urllib_response"] = sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response") + + +class Module_six_moves_urllib_robotparser(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_robotparser""" + + +_urllib_robotparser_moved_attributes = [ + MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), +] +for attr in _urllib_robotparser_moved_attributes: + setattr(Module_six_moves_urllib_robotparser, attr.name, attr) +del attr + +Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes + +sys.modules[__name__ + ".moves.urllib_robotparser"] = sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser") + + +class Module_six_moves_urllib(types.ModuleType): + """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" + parse = sys.modules[__name__ + ".moves.urllib_parse"] + error = sys.modules[__name__ + ".moves.urllib_error"] + request = sys.modules[__name__ + ".moves.urllib_request"] + response = sys.modules[__name__ + ".moves.urllib_response"] + robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"] + + def __dir__(self): + return ['parse', 'error', 'request', 'response', 'robotparser'] + + +sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib") + + +def add_move(move): + """Add an item to six.moves.""" + setattr(_MovedItems, move.name, move) + + +def remove_move(name): + """Remove item from six.moves.""" + try: + delattr(_MovedItems, name) + except AttributeError: + try: + del moves.__dict__[name] + except KeyError: + raise AttributeError("no such move, %r" % (name,)) + + +if PY3: + _meth_func = "__func__" + _meth_self = "__self__" + + _func_closure = "__closure__" + _func_code = "__code__" + _func_defaults = "__defaults__" + _func_globals = "__globals__" +else: + _meth_func = "im_func" + _meth_self = "im_self" + + _func_closure = "func_closure" + _func_code = "func_code" + _func_defaults = "func_defaults" + _func_globals = "func_globals" + + +try: + advance_iterator = next +except NameError: + def advance_iterator(it): + return it.next() +next = advance_iterator + + +try: + callable = callable +except NameError: + def callable(obj): + return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) + + +if PY3: + def get_unbound_function(unbound): + return unbound + + create_bound_method = types.MethodType + + Iterator = object +else: + def get_unbound_function(unbound): + return unbound.im_func + + def create_bound_method(func, obj): + return types.MethodType(func, obj, obj.__class__) + + class Iterator(object): + + def next(self): + return type(self).__next__(self) + + callable = callable +_add_doc(get_unbound_function, + """Get the function out of a possibly unbound function""") + + +get_method_function = operator.attrgetter(_meth_func) +get_method_self = operator.attrgetter(_meth_self) +get_function_closure = operator.attrgetter(_func_closure) +get_function_code = operator.attrgetter(_func_code) +get_function_defaults = operator.attrgetter(_func_defaults) +get_function_globals = operator.attrgetter(_func_globals) + + +if PY3: + def iterkeys(d, **kw): + return iter(d.keys(**kw)) + + def itervalues(d, **kw): + return iter(d.values(**kw)) + + def iteritems(d, **kw): + return iter(d.items(**kw)) + + def iterlists(d, **kw): + return iter(d.lists(**kw)) +else: + def iterkeys(d, **kw): + return iter(d.iterkeys(**kw)) + + def itervalues(d, **kw): + return iter(d.itervalues(**kw)) + + def iteritems(d, **kw): + return iter(d.iteritems(**kw)) + + def iterlists(d, **kw): + return iter(d.iterlists(**kw)) + +_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") +_add_doc(itervalues, "Return an iterator over the values of a dictionary.") +_add_doc(iteritems, + "Return an iterator over the (key, value) pairs of a dictionary.") +_add_doc(iterlists, + "Return an iterator over the (key, [values]) pairs of a dictionary.") + + +if PY3: + def b(s): + return s.encode("latin-1") + def u(s): + return s + unichr = chr + if sys.version_info[1] <= 1: + def int2byte(i): + return bytes((i,)) + else: + # This is about 2x faster than the implementation above on 3.2+ + int2byte = operator.methodcaller("to_bytes", 1, "big") + byte2int = operator.itemgetter(0) + indexbytes = operator.getitem + iterbytes = iter + import io + StringIO = io.StringIO + BytesIO = io.BytesIO +else: + def b(s): + return s + # Workaround for standalone backslash + def u(s): + return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") + unichr = unichr + int2byte = chr + def byte2int(bs): + return ord(bs[0]) + def indexbytes(buf, i): + return ord(buf[i]) + def iterbytes(buf): + return (ord(byte) for byte in buf) + import StringIO + StringIO = BytesIO = StringIO.StringIO +_add_doc(b, """Byte literal""") +_add_doc(u, """Text literal""") + + +if PY3: + exec_ = getattr(moves.builtins, "exec") + + + def reraise(tp, value, tb=None): + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + +else: + def exec_(_code_, _globs_=None, _locs_=None): + """Execute code in a namespace.""" + if _globs_ is None: + frame = sys._getframe(1) + _globs_ = frame.f_globals + if _locs_ is None: + _locs_ = frame.f_locals + del frame + elif _locs_ is None: + _locs_ = _globs_ + exec("""exec _code_ in _globs_, _locs_""") + + + exec_("""def reraise(tp, value, tb=None): + raise tp, value, tb +""") + + +print_ = getattr(moves.builtins, "print", None) +if print_ is None: + def print_(*args, **kwargs): + """The new-style print function for Python 2.4 and 2.5.""" + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + def write(data): + if not isinstance(data, basestring): + data = str(data) + # If the file has an encoding, encode unicode with it. + if (isinstance(fp, file) and + isinstance(data, unicode) and + fp.encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(fp.encoding, errors) + fp.write(data) + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) + +_add_doc(reraise, """Reraise an exception.""") + + +def with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + return meta("NewBase", bases, {}) + +def add_metaclass(metaclass): + """Class decorator for creating a class with a metaclass.""" + def wrapper(cls): + orig_vars = cls.__dict__.copy() + orig_vars.pop('__dict__', None) + orig_vars.pop('__weakref__', None) + slots = orig_vars.get('__slots__') + if slots is not None: + if isinstance(slots, str): + slots = [slots] + for slots_var in slots: + orig_vars.pop(slots_var) + return metaclass(cls.__name__, cls.__bases__, orig_vars) + return wrapper diff --git a/twiggy/filters.py b/twiggy/filters.py index 30247d3..d05890b 100644 --- a/twiggy/filters.py +++ b/twiggy/filters.py @@ -1,7 +1,10 @@ -import levels import fnmatch import re +from . import levels +from . import compat + + __re_type = type(re.compile('foo')) # XXX is there a canonical place for this? def msgFilter(x): @@ -11,7 +14,7 @@ def msgFilter(x): return lambda msg: True elif isinstance(x, bool): return lambda msg: x - elif isinstance(x, basestring): + elif isinstance(x, compat.string_types): return regex_wrapper(re.compile(x)) elif isinstance(x, __re_type): return regex_wrapper(x) diff --git a/twiggy/lib/converter.py b/twiggy/lib/converter.py index 3aeff8b..32199ce 100644 --- a/twiggy/lib/converter.py +++ b/twiggy/lib/converter.py @@ -1,5 +1,8 @@ import copy +from twiggy.compat import iterkeys + + class Converter(object): """Holder for `.ConversionTable` items @@ -69,7 +72,7 @@ class ConversionTable(list): # XXX I could be much faster & efficient! # XXX I have written this pattern at least 10 times converts = set(x.key for x in self) - avail = set(d.iterkeys()) + avail = set(iterkeys(d)) required = set(x.key for x in self if x.required) missing = required - avail diff --git a/twiggy/logger.py b/twiggy/logger.py index 81fdce9..41c5687 100644 --- a/twiggy/logger.py +++ b/twiggy/logger.py @@ -1,9 +1,11 @@ +from __future__ import print_function from .message import Message from .lib import iso8601time import twiggy as _twiggy -import levels -import outputs -import formats +from . import levels +from . import outputs +from . import formats +from .compat import iteritems import warnings import sys @@ -11,6 +13,8 @@ import time import traceback from functools import wraps +StandardError = Exception + def emit(level): """a decorator that emits at `level <.LogLevel>` after calling the method. The method should return a `.Logger` instance. @@ -138,8 +142,8 @@ class InternalLogger(BaseLogger): else: self.output.output(msg) except StandardError: - print>>sys.stderr, iso8601time(), "Error in twiggy internal log! Something is serioulsy broken." - print>>sys.stderr, "Offending message:", repr(msg) + print(iso8601time(), "Error in twiggy internal log! Something is serioulsy broken.", file=sys.stderr) + print("Offending message:", repr(msg), file=sys.stderr) traceback.print_exc(file = sys.stderr) class Logger(BaseLogger): @@ -229,7 +233,7 @@ class Logger(BaseLogger): # just continue emitting in face of filter error # XXX should we trap here too b/c of "Dictionary changed size during iteration" (or other rare errors?) - potential_emitters = [(name, emitter) for name, emitter in self._emitters.iteritems() + potential_emitters = [(name, emitter) for name, emitter in iteritems(self._emitters) if level >= emitter.min_level] if not potential_emitters: return diff --git a/twiggy/message.py b/twiggy/message.py index a40e41e..5879b7b 100644 --- a/twiggy/message.py +++ b/twiggy/message.py @@ -4,6 +4,9 @@ import sys import traceback from string import Template +from .compat import iteritems + + class Message(object): """A log message. All attributes are read-only.""" @@ -60,11 +63,11 @@ class Message(object): ## and substituting into `format_spec`. ## call any callables - for k, v in fields.iteritems(): + for k, v in iteritems(fields): if callable(v): fields[k] = v() - for k, v in kwargs.iteritems(): + for k, v in iteritems(kwargs): if callable(v): kwargs[k] = v()
0.4.x release with Python3 support I'm testing twiggy on an isolated environment with `Python3.4` using `virtualenvwrapper`, here's the scenario: ## Creating the isolated environment: ``` (twiggy) username@username-VirtualBox ~/Devel/twiggy $ mkproject -p /usr/bin/python3 twiggy Running virtualenv with interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in twiggy/bin/python3 Also creating executable in twiggy/bin/python Installing setuptools, pip...done. Creating /home/username/Devel/twiggy Setting project for twiggy to /home/username/Devel/twiggy ``` ## Installing `twiggy`: ``` (twiggy) username@username-VirtualBox ~/Devel/twiggy $ pip install twiggy Downloading/unpacking twiggy Downloading Twiggy-0.4.5.tar.gz (55kB): 55kB downloaded Running setup.py (path:/home/username/.virtualenvs/twiggy/build/twiggy/setup.py) egg_info for package twiggy Installing collected packages: twiggy Running setup.py install for twiggy Successfully installed twiggy Cleaning up... ``` ## Testing w/ Python3 interpreter: It first complains about a missing module (`logger`). ``` (twiggy) username@username-VirtualBox ~/Devel/twiggy $ python Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import twiggy Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/username/.virtualenvs/twiggy/lib/python3.4/site-packages/twiggy/__init__.py", line 6, in <module> import logger ImportError: No module named 'logger' >>> exit() ``` ## Let's install that `logger`: ``` (twiggy) username@username-VirtualBox ~/Devel/twiggy $ pip install logger Downloading/unpacking logger Downloading logger-1.4.tar.gz Running setup.py (path:/home/username/.virtualenvs/twiggy/build/logger/setup.py) egg_info for package logger Installing collected packages: logger Running setup.py install for logger Successfully installed logger Cleaning up... ``` ## Let's test it again: This time, it will complain about a missing module: `filters` ``` (twiggy) username@username-VirtualBox ~/Devel/twiggy $ python Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> pip install twiggy File "<stdin>", line 1 pip install twiggy ^ SyntaxError: invalid syntax >>> import twiggy Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/username/.virtualenvs/twiggy/lib/python3.4/site-packages/twiggy/__init__.py", line 7, in <module> import filters ImportError: No module named 'filters' >>> exit() ``` ## Let's try to install that missing module: ``` (twiggy) username@username-VirtualBox ~/Devel/twiggy $ pip install filters Downloading/unpacking filters Could not find any downloads that satisfy the requirement filters Cleaning up... No distributions at all found for filters Storing debug log for failure in /home/username/.pip/pip.log ``` Now we're stuck :)
wearpants/twiggy
diff --git a/tests/test_globals.py b/tests/test_globals.py index 94fff04..3185c2c 100644 --- a/tests/test_globals.py +++ b/tests/test_globals.py @@ -80,7 +80,7 @@ class GlobalsTestCase(unittest.TestCase): def test_quickSetup_file(self): fname = tempfile.mktemp() - print fname + print(fname) @self.addCleanup def cleanup(): diff --git a/tests/test_integration.py b/tests/test_integration.py index 3f19f05..4d99b49 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -1,3 +1,4 @@ +from __future__ import print_function import sys if sys.version_info >= (2, 7): import unittest @@ -7,10 +8,10 @@ else: except ImportError: raise RuntimeError("unittest2 is required for Python < 2.7") import twiggy -import StringIO import time from . import when +from twiggy.compat import StringIO def fake_gmtime(): return when @@ -25,9 +26,9 @@ class IntegrationTestCase(unittest.TestCase): twiggy._del_globals() def test_integration(self): - everything = twiggy.outputs.StreamOutput(stream=StringIO.StringIO(), format=twiggy.formats.line_format) - out1 = twiggy.outputs.StreamOutput(stream=StringIO.StringIO(), format=twiggy.formats.line_format) - out2 = twiggy.outputs.StreamOutput(stream=StringIO.StringIO(), format=twiggy.formats.line_format) + everything = twiggy.outputs.StreamOutput(stream=StringIO(), format=twiggy.formats.line_format) + out1 = twiggy.outputs.StreamOutput(stream=StringIO(), format=twiggy.formats.line_format) + out2 = twiggy.outputs.StreamOutput(stream=StringIO(), format=twiggy.formats.line_format) twiggy.addEmitters(('*', twiggy.levels.DEBUG, None, everything), ('first', twiggy.levels.INFO, None, out1), @@ -48,13 +49,13 @@ class IntegrationTestCase(unittest.TestCase): except: twiggy.log.trace().critical("Went boom") - print "***************** everything **********************" - print everything.stream.getvalue(), - print "****************** out 1 **************************" - print out1.stream.getvalue(), - print "****************** out 2 **************************" - print out2.stream.getvalue(), - print "***************************************************" + print("***************** everything **********************") + print(everything.stream.getvalue(), end=' ') + print("****************** out 1 **************************") + print(out1.stream.getvalue(), end=' ') + print("****************** out 2 **************************") + print(out2.stream.getvalue(), end=' ') + print("***************************************************") # XXX this should really be done with a regex, but I'm feeling lazy diff --git a/tests/test_logger.py b/tests/test_logger.py index 2aecd7e..f2b1970 100644 --- a/tests/test_logger.py +++ b/tests/test_logger.py @@ -1,3 +1,4 @@ +import re import sys if sys.version_info >= (2, 7): import unittest @@ -7,9 +8,9 @@ else: except ImportError: raise RuntimeError("unittest2 is required for Python < 2.7") import sys -import StringIO from twiggy import logger, outputs, levels, filters +from twiggy.compat import StringIO import twiggy as _twiggy class LoggerTestBase(object): @@ -125,7 +126,7 @@ class InternalLoggerTest(LoggerTestBase, unittest.TestCase): assert log.min_level == self.log.min_level def test_trap_msg(self): - sio = StringIO.StringIO() + sio = StringIO() def cleanup(stderr): sys.stderr = stderr @@ -152,7 +153,7 @@ class InternalLoggerTest(LoggerTestBase, unittest.TestCase): out = BorkedOutput(close_atexit = False) - sio = StringIO.StringIO() + sio = StringIO() def cleanup(stderr, output): sys.stderr = stderr @@ -270,16 +271,16 @@ class LoggerTrapTestCase(unittest.TestCase): assert len(self.internal_messages) == 1 m = self.internal_messages.pop() - print m.text - print m.traceback - print _twiggy.internal_log._options + print(m.text) + print(m.traceback) + print(_twiggy.internal_log._options) assert m.level == levels.INFO assert m.name == 'twiggy.internal' assert "Traceback" in m.traceback assert "THUNK" in m.traceback assert "Error in Logger filtering" in m.text - assert "<function bad_filter" in m.text + assert re.search("<function .*bad_filter", m.text) def test_trap_bad_msg(self): def go_boom(): @@ -291,16 +292,16 @@ class LoggerTrapTestCase(unittest.TestCase): assert len(self.internal_messages) == 1 m = self.internal_messages.pop() - print m.text - print m.traceback - print _twiggy.internal_log._options + print(m.text) + print(m.traceback) + print(_twiggy.internal_log._options) assert m.level == levels.INFO assert m.name == 'twiggy.internal' assert "Traceback" in m.traceback assert "BOOM" in m.traceback assert "Error formatting message" in m.text - assert "<function go_boom" in m.text + assert re.search("<function .*go_boom", m.text) def test_trap_output(self): class BorkedOutput(outputs.ListOutput): @@ -331,11 +332,13 @@ class LoggerTrapTestCase(unittest.TestCase): assert len(self.internal_messages) == 1 m = self.internal_messages.pop() - print m.text - print m.traceback + print(m.text) + print(m.traceback) assert m.level == levels.WARNING - assert "Error outputting with <tests.test_logger.BorkedOutput" in m.text + assert re.search( + "Error outputting with <tests.test_logger.*BorkedOutput", + m.text) assert "Traceback" in m.traceback assert "BORK" in m.traceback @@ -375,12 +378,12 @@ class LoggerTrapTestCase(unittest.TestCase): assert len(self.internal_messages) == 1 m = self.internal_messages.pop() - print m.text - print m.traceback + print(m.text) + print(m.traceback) assert m.level == levels.INFO assert "Error filtering with emitter before" in m.text - assert "<function go_boom" in m.text + assert re.search("<function .*go_boom", m.text) assert "Traceback" in m.traceback assert "BOOM" in m.traceback diff --git a/tests/test_message.py b/tests/test_message.py index 162a030..73e4e36 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -258,7 +258,7 @@ and shirt''' ) assert m.traceback.startswith('Traceback (most recent call last):') - assert m.traceback.endswith('ZeroDivisionError: integer division or modulo by zero\n') + assert 'ZeroDivisionError:' in m.traceback def test_trace_tuple(self): opts = Message._default_options.copy() @@ -276,4 +276,4 @@ and shirt''' ) assert m.traceback.startswith('Traceback (most recent call last):') - assert m.traceback.endswith('ZeroDivisionError: integer division or modulo by zero\n') + assert 'ZeroDivisionError:' in m.traceback diff --git a/tests/test_outputs.py b/tests/test_outputs.py index 766058f..f8f4414 100644 --- a/tests/test_outputs.py +++ b/tests/test_outputs.py @@ -8,9 +8,9 @@ else: raise RuntimeError("unittest2 is required for Python < 2.7") import tempfile import os -import StringIO from twiggy import outputs, formats +from twiggy.compat import StringIO from . import make_mesg, when @@ -41,7 +41,7 @@ class FileOutputTestCase(unittest.TestCase): def make_output(self, msg_buffer, locked): cls = outputs.FileOutput if locked else UnlockedFileOutput - return cls(name = self.fname, format = formats.shell_format, buffering = 0, + return cls(name = self.fname, format = formats.shell_format, buffering = 1, msg_buffer = msg_buffer, close_atexit=False) def test_sync(self): @@ -75,7 +75,7 @@ class FileOutputTestCase(unittest.TestCase): class StreamOutputTest(unittest.TestCase): def test_stream_output(self): - sio = StringIO.StringIO() + sio = StringIO() o = outputs.StreamOutput(formats.shell_format, sio) o.output(m) o.close()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 5 }
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": null, "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 pytest==8.3.5 tomli==2.2.1 -e git+https://github.com/wearpants/twiggy.git@e99fdc19049dd06efdbc6c48e133ea8856a491a7#egg=Twiggy
name: twiggy 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 - tomli==2.2.1 prefix: /opt/conda/envs/twiggy
[ "tests/test_logger.py::InternalLoggerTest::test_bad_options", "tests/test_logger.py::InternalLoggerTest::test_clone", "tests/test_logger.py::InternalLoggerTest::test_critical", "tests/test_logger.py::InternalLoggerTest::test_debug", "tests/test_logger.py::InternalLoggerTest::test_error", "tests/test_logger.py::InternalLoggerTest::test_fields", "tests/test_logger.py::InternalLoggerTest::test_fieldsDict", "tests/test_logger.py::InternalLoggerTest::test_info", "tests/test_logger.py::InternalLoggerTest::test_logger_min_level", "tests/test_logger.py::InternalLoggerTest::test_name", "tests/test_logger.py::InternalLoggerTest::test_options", "tests/test_logger.py::InternalLoggerTest::test_trace", "tests/test_logger.py::InternalLoggerTest::test_trap_msg", "tests/test_logger.py::InternalLoggerTest::test_trap_output", "tests/test_logger.py::InternalLoggerTest::test_warning", "tests/test_logger.py::LoggerTestCase::test_bad_options", "tests/test_logger.py::LoggerTestCase::test_critical", "tests/test_logger.py::LoggerTestCase::test_debug", "tests/test_logger.py::LoggerTestCase::test_error", "tests/test_logger.py::LoggerTestCase::test_fields", "tests/test_logger.py::LoggerTestCase::test_fieldsDict", "tests/test_logger.py::LoggerTestCase::test_filter_emitters", "tests/test_logger.py::LoggerTestCase::test_info", "tests/test_logger.py::LoggerTestCase::test_logger_filter", "tests/test_logger.py::LoggerTestCase::test_logger_min_level", "tests/test_logger.py::LoggerTestCase::test_min_level_emitters", "tests/test_logger.py::LoggerTestCase::test_name", "tests/test_logger.py::LoggerTestCase::test_no_emitters", "tests/test_logger.py::LoggerTestCase::test_options", "tests/test_logger.py::LoggerTestCase::test_structDict", "tests/test_logger.py::LoggerTestCase::test_trace", "tests/test_logger.py::LoggerTestCase::test_warning", "tests/test_message.py::MessageTestCase::test_bad_style", "tests/test_message.py::MessageTestCase::test_bad_trace", "tests/test_message.py::MessageTestCase::test_basic", "tests/test_message.py::MessageTestCase::test_callables", "tests/test_message.py::MessageTestCase::test_dollar_style", "tests/test_message.py::MessageTestCase::test_dollar_style_bad", "tests/test_message.py::MessageTestCase::test_empty_format_spec", "tests/test_message.py::MessageTestCase::test_level_property", "tests/test_message.py::MessageTestCase::test_name_property", "tests/test_message.py::MessageTestCase::test_no_args", "tests/test_message.py::MessageTestCase::test_no_args_no_kwargs", "tests/test_message.py::MessageTestCase::test_no_kwargs", "tests/test_message.py::MessageTestCase::test_percent_style_args", "tests/test_message.py::MessageTestCase::test_percent_style_both", "tests/test_message.py::MessageTestCase::test_percent_style_kwargs", "tests/test_message.py::MessageTestCase::test_suppress_newlines_false", "tests/test_message.py::MessageTestCase::test_suppress_newlines_true", "tests/test_message.py::MessageTestCase::test_trace_error_with_error", "tests/test_message.py::MessageTestCase::test_trace_error_without_error", "tests/test_message.py::MessageTestCase::test_trace_tuple", "tests/test_outputs.py::FileOutputTestCase::test_async", "tests/test_outputs.py::FileOutputTestCase::test_async_unlocked", "tests/test_outputs.py::FileOutputTestCase::test_sync", "tests/test_outputs.py::FileOutputTestCase::test_sync_unlocked", "tests/test_outputs.py::StreamOutputTest::test_stream_output", "tests/test_outputs.py::ListOutputTest::test_list_output" ]
[ "tests/test_globals.py::GlobalsTestCase::test_addEmitters", "tests/test_globals.py::GlobalsTestCase::test_globals", "tests/test_globals.py::GlobalsTestCase::test_populate_globals_twice", "tests/test_globals.py::GlobalsTestCase::test_quickSetup_None", "tests/test_globals.py::GlobalsTestCase::test_quickSetup_file", "tests/test_globals.py::GlobalsTestCase::test_quickSetup_stdout", "tests/test_integration.py::IntegrationTestCase::test_integration", "tests/test_logger.py::LoggerTrapTestCase::test_bad_logger_filter", "tests/test_logger.py::LoggerTrapTestCase::test_trap_bad_msg", "tests/test_logger.py::LoggerTrapTestCase::test_trap_filter", "tests/test_logger.py::LoggerTrapTestCase::test_trap_output" ]
[]
[]
BSD 3-Clause "New" or "Revised" License
24
[ "twiggy/message.py", "twiggy/logger.py", ".travis.yml", "twiggy/compat.py", "tox.ini", "twiggy/filters.py", "twiggy/__init__.py", "twiggy/lib/converter.py" ]
[ "twiggy/message.py", "twiggy/logger.py", ".travis.yml", "twiggy/compat.py", "tox.ini", "twiggy/filters.py", "twiggy/__init__.py", "twiggy/lib/converter.py" ]
miki725__importanize-22
2046972231a37055b5698d80153b08ff35e6864b
2015-01-18 03:46:10
623d48f8b1dbe3c9604fa22f24f940a6fb764cb6
diff --git a/HISTORY.rst b/HISTORY.rst index 2a6e41e..452409e 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -3,6 +3,13 @@ History ------- +0.3 (2015-01-18) +~~~~~~~~~~~~~~~~ + +* Using tokens to parse Python files. As a result this allows to + fix how comments are handled + (see `#21 <https://github.com/miki725/importanize/issues/21>`_ for example) + 0.2 (2014-10-30) ~~~~~~~~~~~~~~~~ diff --git a/Makefile b/Makefile index ef86e42..db3d1bc 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .PHONY: clean-pyc clean-build docs clean NOSE_FLAGS=-sv --with-doctest --rednose -COVER_CONFIG_FLAGS=--with-coverage --cover-package=importanize,tests --cover-tests +COVER_CONFIG_FLAGS=--with-coverage --cover-package=importanize,tests --cover-tests --cover-erase COVER_REPORT_FLAGS=--cover-html --cover-html-dir=htmlcov COVER_FLAGS=${COVER_CONFIG_FLAGS} ${COVER_REPORT_FLAGS} diff --git a/importanize/__init__.py b/importanize/__init__.py index 5e712ad..f1714eb 100755 --- a/importanize/__init__.py +++ b/importanize/__init__.py @@ -4,4 +4,4 @@ from __future__ import print_function, unicode_literals __author__ = 'Miroslav Shubernetskiy' __email__ = '[email protected]' -__version__ = '0.2' +__version__ = '0.3' diff --git a/importanize/groups.py b/importanize/groups.py index 98e9d98..7224ce1 100644 --- a/importanize/groups.py +++ b/importanize/groups.py @@ -16,7 +16,7 @@ class BaseImportGroup(object): self.config = config or {} self.statements = [] - self.artifacts = kwargs.get('artifacts', {}) + self.file_artifacts = kwargs.get('file_artifacts', {}) @property def unique_statements(self): @@ -58,12 +58,12 @@ class BaseImportGroup(object): return False def as_string(self): - sep = self.artifacts.get('sep', '\n') + sep = self.file_artifacts.get('sep', '\n') return sep.join(map(operator.methodcaller('as_string'), self.unique_statements)) def formatted(self): - sep = self.artifacts.get('sep', '\n') + sep = self.file_artifacts.get('sep', '\n') return sep.join(map(operator.methodcaller('formatted'), self.unique_statements)) @@ -111,7 +111,7 @@ GROUP_MAPPING = OrderedDict(( class ImportGroups(object): def __init__(self, **kwargs): self.groups = [] - self.artifacts = kwargs.get('artifacts', {}) + self.file_artifacts = kwargs.get('file_artifacts', {}) def all_line_numbers(self): return sorted(list(set(list( @@ -151,14 +151,14 @@ class ImportGroups(object): raise ValueError(msg) def as_string(self): - sep = self.artifacts.get('sep', '\n') * 2 + sep = self.file_artifacts.get('sep', '\n') * 2 return sep.join(filter( None, map(operator.methodcaller('as_string'), self.groups) )) def formatted(self): - sep = self.artifacts.get('sep', '\n') * 2 + sep = self.file_artifacts.get('sep', '\n') * 2 return sep.join(filter( None, map(operator.methodcaller('formatted'), self.groups) diff --git a/importanize/main.py b/importanize/main.py index bd02d60..0c239fa 100644 --- a/importanize/main.py +++ b/importanize/main.py @@ -12,7 +12,11 @@ import six from . import __version__ from .groups import ImportGroups -from .parser import find_imports_from_lines, get_artifacts, parse_statements +from .parser import ( + find_imports_from_lines, + get_file_artifacts, + parse_statements, +) from .utils import read @@ -73,16 +77,19 @@ parser.add_argument( nargs='*', default=['.'], help='Path either to a file or directory where ' - 'all Python import will be organized. ', + 'all Python files imports will be organized.', ) parser.add_argument( '-c', '--config', type=six.text_type, default=default_config, help='Path to importanize config json file. ' - 'If importanize.json is present, that config ' + 'If "{}" is present in either current folder ' + 'or any parent folder, that config ' 'will be used. Otherwise crude default pep8 ' - 'config will be used.{}'.format(found_default), + 'config will be used.{}' + ''.format(IMPORTANIZE_CONFIG, + found_default), ) parser.add_argument( '--print', @@ -113,7 +120,7 @@ def run_importanize(path, config, args): return False text = read(path) - artifacts = get_artifacts(path) + file_artifacts = get_file_artifacts(path) lines_iterator = enumerate(iter(text.splitlines())) imports = list(parse_statements(find_imports_from_lines(lines_iterator))) @@ -149,10 +156,10 @@ def run_importanize(path, config, args): + lines[first_import_line_number:] + ['']) - lines = artifacts.get('sep', '\n').join(lines) + lines = file_artifacts.get('sep', '\n').join(lines) if args.print: - print(lines.encode('utf-8')) + print(lines.encode('utf-8') if not six.PY3 else lines) else: with open(path, 'wb') as fid: fid.write(lines.encode('utf-8')) diff --git a/importanize/parser.py b/importanize/parser.py index 87df4c9..8763477 100644 --- a/importanize/parser.py +++ b/importanize/parser.py @@ -2,14 +2,41 @@ from __future__ import print_function, unicode_literals import re +import six + from .statements import DOTS, ImportLeaf, ImportStatement -from .utils import list_strip, read +from .utils import list_split, read + + +STATEMENT_COMMENTS = ('noqa',) +TOKEN_REGEX = re.compile(r' +|[\(\)]|([,\\])|(#.*)') +SPECIAL_TOKENS = (',', 'import', 'from', 'as') + +class Token(six.text_type): + def __new__(cls, value, **kwargs): + obj = six.text_type.__new__(cls, value) + obj.is_comment_first = False + for k, v in kwargs.items(): + setattr(obj, k, v) + return obj -CHARS = re.compile(r'[\\()]') + @property + def is_comment(self): + return self.startswith('#') + + @property + def normalized(self): + if not self.is_comment: + return self + else: + if self.startswith('# '): + return self[2:] + else: + return self[1:] -def get_artifacts(path): +def get_file_artifacts(path): """ Get artifacts for the given file. @@ -37,10 +64,7 @@ def get_artifacts(path): def find_imports_from_lines(iterator): """ - Find import statements as strings from - enumerated iterator of lines. - - Usually the iterator will of file lines. + Find only import statements from enumerated iterator of file files. Parameters ---------- @@ -51,28 +75,9 @@ def find_imports_from_lines(iterator): Returns ------- imports : generator - Iterator which yields normalized import - strings with line numbers from which the - import statement has been parsed from. - - Example - ------- - - :: - - >>> parsed = list(find_imports_from_lines(iter([ - ... (1, 'from __future__ import unicode_literals'), - ... (2, 'import os.path'), - ... (3, 'from datetime import ('), - ... (4, ' date,'), - ... (5, ' datetime,'), - ... (6, ')'), - ... ]))) - >>> assert parsed == [ - ... ('from __future__ import unicode_literals', [1]), - ... ('import os.path', [2]), - ... ('from datetime import date,datetime', [3, 4, 5, 6]) - ... ] + Iterator which yields tuple of lines strings composing + a single import statement as well as teh line numbers + on which the import statement was found. """ while True: @@ -121,47 +126,43 @@ def find_imports_from_lines(iterator): line_numbers.append(line_number) line_imports.append(line) - # remove unneeded characters - line_imports = map(lambda i: CHARS.sub('', i), line_imports) - - # now that extra characters are removed - # strip each line - line_imports = list_strip(line_imports) - - # handle line breaks which can cause - # incorrect syntax when recombined - # mostly these are cases when line break - # happens around either "import" or "as" - # e.g. from long.import.here \n import foo - # e.g. import package \n as foo - for word in ('import', 'as'): - kwargs = { - 'startswith': { - 'word': word, - 'pre': '', - 'post': ' ', - }, - 'endswith': { - 'word': word, - 'pre': ' ', - 'post': '', - } - } - for f, k in kwargs.items(): - line_imports = list(map( - lambda i: (i if not getattr(i, f)('{pre}{word}{post}' - ''.format(**k)) - else '{post}{i}{pre}'.format(i=i, **k)), - line_imports - )) - - import_line = ''.join(line_imports).strip() - - # strip ending comma if there - if import_line.endswith(','): - import_line = import_line[:-1] - - yield import_line, line_numbers + yield line_imports, line_numbers + + +def tokenize_import_lines(import_lines): + tokens = [] + + for n, line in enumerate(import_lines): + _tokens = [] + words = filter(None, TOKEN_REGEX.split(line)) + + for i, word in enumerate(words): + token = Token(word) + # tokenize same-line comments before "," to allow to associate + # a comment with specific import since pure Python + # syntax does not do that because # has to be after "," + # hence when tokenizing, comment will be associated + # with next import which is not desired + if token.is_comment and _tokens and _tokens[max(i - 1, 0)] == ',': + _tokens.insert(i - 1, token) + else: + _tokens.append(token) + + tokens.extend(_tokens) + + # combine tokens between \\ newline escape + segments = list_split(tokens, '\\') + tokens = [Token('')] + for i, segment in enumerate(segments): + # don't add to previous token if it is a "," + if all((tokens[-1] not in SPECIAL_TOKENS, + not i or segment[0] not in SPECIAL_TOKENS)): + tokens[-1] += segment[0] + else: + tokens.append(segment[0]) + tokens += segment[1:] + + return [Token(i) for i in tokens] def parse_import_statement(stem, line_numbers, **kwargs): @@ -232,24 +233,56 @@ def parse_statements(iterable, **kwargs): statements : generator Generator which yields ``ImportStatement`` instances. """ - for import_line, line_numbers in iterable: - - if import_line.startswith('import '): - stems = import_line.replace('import ', '').strip().split(',') - - for stem in stems: - yield parse_import_statement(stem.strip(), - line_numbers, - **kwargs) + get_comments = lambda j: filter(lambda i: i.is_comment, j) + get_not_comments = lambda j: filter(lambda i: not i.is_comment, j) + get_first_not_comment = lambda j: next( + iter(filter(lambda i: not i.is_comment, j)) + ) + + for import_lines, line_numbers in iterable: + tokens = tokenize_import_lines(import_lines) + + if tokens[0] == 'import': + for _tokens in list_split(tokens[1:], ','): + stem = ' '.join(get_not_comments(_tokens)) + comments = get_comments(_tokens) + yield parse_import_statement( + stem=stem, + line_numbers=line_numbers, + comments=list(comments), + **kwargs + ) else: - stem, leafs_string = list_strip( - import_line.replace('from ', '').split(' import ') + stem_tokens, leafs_tokens = list_split(tokens[1:], 'import') + stem = ' '.join(get_not_comments(stem_tokens)) + list_of_leafs = list(list_split(leafs_tokens, ',')) + statement_comments = set() + leafs = [] + + for leaf_list in list_of_leafs: + first_non_leaf_index = leaf_list.index( + get_first_not_comment(leaf_list) + ) + leaf_stem = ' '.join(get_not_comments(leaf_list)) + comments = [] + all_leaf_comments = filter(lambda i: i.is_comment, leaf_list) + + for comment in all_leaf_comments: + if comment.normalized in STATEMENT_COMMENTS: + statement_comments.add(comment) + else: + comment.is_comment_first = ( + leaf_list.index(comment) < first_non_leaf_index + ) + comments.append(comment) + + leafs.append(ImportLeaf(leaf_stem, comments=comments)) + + yield ImportStatement( + line_numbers=line_numbers, + stem=stem, + leafs=leafs, + comments=list(statement_comments), + **kwargs ) - leafs = filter(None, list_strip(leafs_string.split(','))) - leafs = list(map(ImportLeaf, leafs)) - - yield ImportStatement(line_numbers, - stem, - leafs, - **kwargs) diff --git a/importanize/statements.py b/importanize/statements.py index 0d7e24e..22eba49 100755 --- a/importanize/statements.py +++ b/importanize/statements.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals +import itertools import operator import re @@ -23,7 +24,7 @@ class ImportLeaf(ComparatorMixin): Also aliased modules are supported (e.g. using ``as``). """ - def __init__(self, name): + def __init__(self, name, comments=None): as_name = None if ' as ' in name: @@ -34,6 +35,7 @@ class ImportLeaf(ComparatorMixin): self.name = name self.as_name = as_name + self.comments = comments or [] def as_string(self): string = self.name @@ -100,11 +102,13 @@ class ImportStatement(ComparatorMixin): List of ``ImportLeaf`` instances """ - def __init__(self, line_numbers, stem, leafs=None, **kwargs): + def __init__(self, line_numbers, stem, leafs=None, + comments=None, **kwargs): self.line_numbers = line_numbers self.stem = stem self.leafs = leafs or [] - self.artifacts = kwargs.get('artifacts', {}) + self.comments = comments or [] + self.file_artifacts = kwargs.get('file_artifacts', {}) @property def unique_leafs(self): @@ -132,17 +136,58 @@ class ImportStatement(ComparatorMixin): ) def formatted(self): + leafs = self.unique_leafs string = self.as_string() - if len(string) > 80 and len(self.leafs) > 1: - sep = '{} '.format(self.artifacts.get('sep', '\n')) - string = ( - 'from {} import ({}{},{})' - ''.format(self.stem, sep, - (',{}'.format(sep) - .join(map(operator.methodcaller('as_string'), - self.unique_leafs))), - self.artifacts.get('sep', '\n')) - ) + get_normalized = lambda i: map( + operator.attrgetter('normalized'), i + ) + + all_comments = ( + self.comments + list(itertools.chain( + *list(map(operator.attrgetter('comments'), leafs)) + )) + ) + + if len(all_comments) == 1: + string += ' # {}'.format(' '.join(get_normalized(all_comments))) + + if any((len(string) > 80 and len(leafs) > 1, + len(all_comments) > 1)): + sep = '{} '.format(self.file_artifacts.get('sep', '\n')) + + string = 'from {} import ('.format(self.stem) + + if self.comments: + string += ' # {}'.format(' '.join( + get_normalized(self.comments) + )) + + for leaf in leafs: + string += sep + + first_comments = list(filter( + lambda i: i.is_comment_first, + leaf.comments + )) + if first_comments: + string += sep.join( + '# {}'.format(i) + for i in get_normalized(first_comments) + ) + sep + + string += '{},'.format(leaf.as_string()) + + inline_comments = list(filter( + lambda i: not i.is_comment_first, + leaf.comments + )) + if inline_comments: + string += ' # {}'.format( + ' '.join(get_normalized(inline_comments)) + ) + + string += '{})'.format(self.file_artifacts.get('sep', '\n')) + return string def __hash__(self): diff --git a/importanize/utils.py b/importanize/utils.py index 188b123..d81f20e 100644 --- a/importanize/utils.py +++ b/importanize/utils.py @@ -55,3 +55,17 @@ def list_strip(data): def read(path): with open(path, 'rb') as fid: return fid.read().decode('utf-8') + + +def list_split(iterable, split): + segment = [] + + for i in iterable: + if i == split: + yield segment + segment = [] + else: + segment.append(i) + + if segment: + yield segment diff --git a/setup.py b/setup.py index 7f1c331..4de6350 100755 --- a/setup.py +++ b/setup.py @@ -1,8 +1,9 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -from __future__ import unicode_literals, print_function +from __future__ import print_function, unicode_literals import os -from setuptools import setup, find_packages + +from setuptools import find_packages, setup from importanize import __author__, __version__
comments in import produce invalid syntax ``` from a import b, c # noqa ``` is transformed to: ``` from a import ( b, c # noqa, ) ``` which is of course invalid syntax
miki725/importanize
diff --git a/tests/test_data/normal.txt b/tests/test_data/input.txt similarity index 56% rename from tests/test_data/normal.txt rename to tests/test_data/input.txt index 553ab4d..8123578 100644 --- a/tests/test_data/normal.txt +++ b/tests/test_data/input.txt @@ -12,6 +12,13 @@ from a import b from a.b import c from a.b import d - +import something # with comment +from other.package.subpackage.module.submodule import CONSTANT, Klass, foo, bar, rainbows # noqa +from other import( + something, # something comment + something_else, # noqa + #lots of happy things below + and_rainbows +) # stuff here diff --git a/tests/test_data/normal_expected.txt b/tests/test_data/output.txt similarity index 54% rename from tests/test_data/normal_expected.txt rename to tests/test_data/output.txt index 63f1f74..e1c57e6 100644 --- a/tests/test_data/normal_expected.txt +++ b/tests/test_data/output.txt @@ -4,8 +4,22 @@ from __future__ import print_function, unicode_literals import datetime from os import path as ospath +import something # with comment from a import b from a.b import c, d +from other import ( # noqa + # lots of happy things below + and_rainbows, + something, # something comment + something_else, +) +from other.package.subpackage.module.submodule import ( # noqa + CONSTANT, + Klass, + bar, + foo, + rainbows, +) from package.subpackage.module.submodule import ( CONSTANT, Klass, diff --git a/tests/test_groups.py b/tests/test_groups.py index 7d1ec49..fb1e386 100644 --- a/tests/test_groups.py +++ b/tests/test_groups.py @@ -116,7 +116,7 @@ class TestBaseImportGroup(unittest.TestCase): ) def test_as_string_with_artifacts(self): - group = BaseImportGroup(artifacts={'sep': '\r\n'}) + group = BaseImportGroup(file_artifacts={'sep': '\r\n'}) group.statements = [ImportStatement([], 'b'), ImportStatement([], 'a')] @@ -145,12 +145,12 @@ class TestBaseImportGroup(unittest.TestCase): def test_formatted_with_artifacts(self): artifacts = {'sep': '\r\n'} - group = BaseImportGroup(artifacts=artifacts) + group = BaseImportGroup(file_artifacts=artifacts) group.statements = [ ImportStatement(list(), 'b' * 80, [ImportLeaf('c'), ImportLeaf('d')], - artifacts=artifacts), - ImportStatement([], 'a', artifacts=artifacts) + file_artifacts=artifacts), + ImportStatement([], 'a', file_artifacts=artifacts) ] self.assertEqual( @@ -298,17 +298,17 @@ class TestImportGroups(unittest.TestCase): def test_formatted_with_artifacts(self): artifacts = {'sep': '\r\n'} - groups = ImportGroups(artifacts=artifacts) + groups = ImportGroups(file_artifacts=artifacts) groups.groups = [ - RemainderGroup(artifacts=artifacts), - LocalGroup(artifacts=artifacts), + RemainderGroup(file_artifacts=artifacts), + LocalGroup(file_artifacts=artifacts), ] groups.add_statement_to_group( - ImportStatement([], '.a', artifacts=artifacts) + ImportStatement([], '.a', file_artifacts=artifacts) ) groups.add_statement_to_group( - ImportStatement([], 'foo', artifacts=artifacts) + ImportStatement([], 'foo', file_artifacts=artifacts) ) self.assertEqual( diff --git a/tests/test_main.py b/tests/test_main.py index c4992c3..d39935a 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1,11 +1,20 @@ # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals +import logging import os import unittest import mock - -from importanize.main import PEP8_CONFIG, run, run_importanize +import six + +from importanize.main import ( + PEP8_CONFIG, + find_config, + main, + parser, + run, + run_importanize, +) from importanize.utils import read @@ -27,11 +36,15 @@ class TestMain(unittest.TestCase): def test_run_importanize_print(self, mock_print): test_file = os.path.join(os.path.dirname(__file__), 'test_data', - 'normal.txt') + 'input.txt') expected_file = os.path.join(os.path.dirname(__file__), 'test_data', - 'normal_expected.txt') - expected = read(expected_file).encode('utf-8') + 'output.txt') + expected = ( + read(expected_file) + if six.PY3 + else read(expected_file).encode('utf-8') + ) self.assertTrue( run_importanize(test_file, @@ -44,10 +57,10 @@ class TestMain(unittest.TestCase): def test_run_importanize_write(self, mock_open): test_file = os.path.join(os.path.dirname(__file__), 'test_data', - 'normal.txt') + 'input.txt') expected_file = os.path.join(os.path.dirname(__file__), 'test_data', - 'normal_expected.txt') + 'output.txt') expected = read(expected_file).encode('utf-8') self.assertTrue( @@ -157,3 +170,81 @@ class TestMain(unittest.TestCase): conf, ) mock_parser.error.assert_called_once_with(mock.ANY) + + @mock.patch('os.path.exists') + @mock.patch('os.getcwd') + def test_find_config(self, mock_getcwd, mock_exists): + mock_getcwd.return_value = '/path/to/importanize' + mock_exists.side_effect = False, True + + config, found = find_config() + + self.assertEqual(config, '/path/to/.importanizerc') + self.assertTrue(bool(found)) + + @mock.patch(TESTING_MODULE + '.run') + @mock.patch('logging.getLogger') + @mock.patch.object(parser, 'parse_args') + def test_main_without_config(self, + mock_parse_args, + mock_get_logger, + mock_run): + args = mock.MagicMock( + verbose=1, + version=False, + path=['/path/../'], + config=None, + ) + mock_parse_args.return_value = args + + main() + + mock_parse_args.assert_called_once_with() + mock_get_logger.assert_called_once_with('') + mock_get_logger().setLevel.assert_called_once_with(logging.INFO) + mock_run.assert_called_once_with('/', PEP8_CONFIG, args) + + @mock.patch(TESTING_MODULE + '.read') + @mock.patch(TESTING_MODULE + '.run') + @mock.patch('json.loads') + @mock.patch('logging.getLogger') + @mock.patch.object(parser, 'parse_args') + def test_main_with_config(self, + mock_parse_args, + mock_get_logger, + mock_loads, + mock_run, + mock_read): + args = mock.MagicMock( + verbose=1, + version=False, + path=['/path/../'], + config=mock.sentinel.config, + ) + mock_parse_args.return_value = args + + main() + + mock_parse_args.assert_called_once_with() + mock_get_logger.assert_called_once_with('') + mock_get_logger().setLevel.assert_called_once_with(logging.INFO) + mock_read.assert_called_once_with(mock.sentinel.config) + mock_loads.assert_called_once_with(mock_read.return_value) + mock_run.assert_called_once_with('/', mock_loads.return_value, args) + + @mock.patch(TESTING_MODULE + '.print', create=True) + @mock.patch('sys.exit') + @mock.patch.object(parser, 'parse_args') + def test_main_version(self, mock_parse_args, mock_exit, mock_print): + mock_exit.side_effect = SystemExit + mock_parse_args.return_value = mock.MagicMock( + verbose=1, + version=True, + ) + + with self.assertRaises(SystemExit): + main() + + mock_parse_args.assert_called_once_with() + mock_exit.assert_called_once_with(0) + mock_print.assert_called_once_with(mock.ANY) diff --git a/tests/test_parser.py b/tests/test_parser.py index 3e6d828..3c8a22a 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -6,33 +6,47 @@ import mock import six from importanize.parser import ( + Token, find_imports_from_lines, - get_artifacts, + get_file_artifacts, parse_statements, + tokenize_import_lines, ) TESTING_MODULE = 'importanize.parser' +class TestToken(unittest.TestCase): + def test_is_comment(self): + self.assertTrue(Token('# noqa').is_comment) + self.assertFalse(Token('foo').is_comment) + + def test_normalized(self): + self.assertEqual(Token('foo').normalized, 'foo') + self.assertEqual(Token('#noqa').normalized, 'noqa') + self.assertEqual(Token('# noqa').normalized, 'noqa') + self.assertEqual(Token('# noqa').normalized, ' noqa') + + class TestParsing(unittest.TestCase): @mock.patch(TESTING_MODULE + '.read') - def test_get_artifacts(self, mock_read): + def test_get_file_artifacts(self, mock_read): mock_read.return_value = 'Hello\nWorld\n' - actual = get_artifacts(mock.sentinel.path) + actual = get_file_artifacts(mock.sentinel.path) self.assertDictEqual(actual, { 'sep': '\n', }) mock_read.assert_called_once_with(mock.sentinel.path) mock_read.return_value = 'Hello\r\nWorld\n' - actual = get_artifacts(mock.sentinel.path) + actual = get_file_artifacts(mock.sentinel.path) self.assertDictEqual(actual, { 'sep': '\r\n', }) mock_read.return_value = 'Hello' - actual = get_artifacts(mock.sentinel.path) + actual = get_file_artifacts(mock.sentinel.path) self.assertDictEqual(actual, { 'sep': '\n', }) @@ -46,68 +60,69 @@ class TestParsing(unittest.TestCase): def test_parsing(self): self._test_import_parsing( ('import a',), - ('import a', [0]), + (['import a'], [0]), ) self._test_import_parsing( ('import a, b',), - ('import a, b', [0]), + (['import a, b'], [0]), ) self._test_import_parsing( ('import a, b as c',), - ('import a, b as c', [0]), + (['import a, b as c'], [0]), ) self._test_import_parsing( ('from a import b',), - ('from a import b', [0]), + (['from a import b'], [0]), ) self._test_import_parsing( ('from a.b import c',), - ('from a.b import c', [0]), + (['from a.b import c'], [0]), ) self._test_import_parsing( ('from a.b import c,\\', ' d'), - ('from a.b import c,d', [0, 1]), + (['from a.b import c,\\', + ' d'], [0, 1]), ) self._test_import_parsing( ('from a.b import c, \\', ' d'), - ('from a.b import c,d', [0, 1]), + (['from a.b import c, \\', + ' d'], [0, 1]), ) self._test_import_parsing( ('from a.b \\', ' import c'), - ('from a.b import c', [0, 1]), + (['from a.b \\', + ' import c'], [0, 1]), ) self._test_import_parsing( ('import a.b \\', ' as c'), - ('import a.b as c', [0, 1]), + (['import a.b \\', + ' as c'], [0, 1]), ) self._test_import_parsing( ('from a.b import \\', ' c,\\', ' d,'), - ('from a.b import c,d', [0, 1, 2]), + (['from a.b import \\', + ' c,\\', + ' d,'], [0, 1, 2]), ) self._test_import_parsing( ('from a.b import (c,', ' d)'), - ('from a.b import c,d', [0, 1]), + (['from a.b import (c,', + ' d)'], [0, 1]), ) self._test_import_parsing( ('from a.b import (c, ', ' d', ')'), - ('from a.b import c,d', [0, 1, 2]), - ) - self._test_import_parsing( - ('from a.b import (', - ' c,', - ' d,', - ')', - 'foo'), - ('from a.b import c,d', [0, 1, 2, 3]), + (['from a.b import (c, ', + ' d', + ')'], [0, 1, 2]), ) self._test_import_parsing( ('"""', @@ -118,7 +133,10 @@ class TestParsing(unittest.TestCase): ' d,', ')', 'foo'), - ('from a.b import c,d', [3, 4, 5, 6]), + (['from a.b import (', + ' c,', + ' d,', + ')'], [3, 4, 5, 6]), ) self._test_import_parsing( ('""" from this shall not import """', @@ -127,7 +145,10 @@ class TestParsing(unittest.TestCase): ' d,', ')', 'foo'), - ('from a.b import c,d', [1, 2, 3, 4]), + (['from a.b import (', + ' c,', + ' d,', + ')'], [1, 2, 3, 4]), ) self._test_import_parsing( ('"""', @@ -145,10 +166,89 @@ class TestParsing(unittest.TestCase): tuple(), ) + def test_tokenize_import_lines(self): + data = ( + ( + ['import a.\\', + ' b'], + ['import', + 'a.b'] + ), + ( + ['from __future__ import unicode_literals,\\', + ' print_function'], + ['from', + '__future__', + 'import', + 'unicode_literals', + ',', + 'print_function'] + ), + ( + ['from a import b, # noqa', + ' c'], + ['from', + 'a', + 'import', + 'b', + '# noqa', + ',', + 'c'] + ), + ( + ['import a,\\', + ' b'], + ['import', + 'a', + ',', + 'b'] + ), + ( + ['from a import\\', + ' b'], + ['from', + 'a', + 'import', + 'b'] + ), + ( + ['from a\\', + ' import b'], + ['from', + 'a', + 'import', + 'b'] + ), + ( + ['import a\\', + ' as b'], + ['import', + 'a', + 'as', + 'b'] + ), + ( + ['from something import foo, bar # noqa'], + ['from', + 'something', + 'import', + 'foo', + ',', + 'bar', + '# noqa'] + ), + ) + for _data, expected in data: + self.assertListEqual( + tokenize_import_lines(iter(_data)), + expected + ) + def _test_import_string_matches(self, string, expected): + data = string if isinstance(string, (list, tuple)) else [string] self.assertEqual( six.text_type( - list(parse_statements([(string, [1])]))[0] + next(parse_statements([(data, [1])])) ), expected ) @@ -238,3 +338,10 @@ class TestParsing(unittest.TestCase): 'from a import b as e,d as g, c as c', 'from a import b as e, c, d as g', ) + self._test_import_string_matches( + ['from a import (', + ' b as e, # foo', + ' d as g # noqa', + ')'], + 'from a import b as e, d as g', + ) diff --git a/tests/test_statements.py b/tests/test_statements.py index 7d740fd..289f5bb 100644 --- a/tests/test_statements.py +++ b/tests/test_statements.py @@ -5,6 +5,7 @@ import unittest import mock import six +from importanize.parser import Token from importanize.statements import ImportLeaf, ImportStatement @@ -147,11 +148,15 @@ class TestImportStatement(unittest.TestCase): _test('a.b', ['e', 'c as d', 'e'], 'from a.b import c as d, e') def test_formatted(self): - def _test(stem, leafs, expected, sep='\n', **kwargs): + def _test(stem, leafs, expected, sep='\n', comments=None, **kwargs): statement = ImportStatement( list(), stem, - list(map(ImportLeaf, leafs)), + list(map((lambda i: + i if isinstance(i, ImportLeaf) + else ImportLeaf(i)), + leafs)), + comments=comments, **kwargs ) self.assertEqual(statement.formatted(), @@ -171,8 +176,29 @@ class TestImportStatement(unittest.TestCase): ' {},'.format('b' * 20), ' {},'.format('c' * 20), ')'], - '\r\n', - artifacts={'sep': '\r\n'}) + sep='\r\n', + file_artifacts={'sep': '\r\n'}) + _test('foo', [], + ['import foo # comment'], + comments=[Token('# comment')]) + _test('foo', [ImportLeaf('bar', comments=[Token('#comment')])], + ['from foo import bar # comment']) + _test('something', [ImportLeaf('foo'), + ImportLeaf('bar')], + ['from something import bar, foo # noqa'], + comments=[Token('# noqa')]) + _test('foo', + [ImportLeaf('bar', comments=[Token('#hello')]), + ImportLeaf('rainbows', comments=[Token('#world')]), + ImportLeaf('zzz', comments=[Token('#and lots of sleep', + is_comment_first=True)])], + ['from foo import ( # noqa', + ' bar, # hello', + ' rainbows, # world', + ' # and lots of sleep', + ' zzz,', + ')'], + comments=[Token('#noqa')]) def test_str(self): statement = ImportStatement([], 'a')
{ "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": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 9 }
0.2
{ "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", "pytest" ], "pre_install": null, "python": "3.9", "reqs_path": [ "requirements.txt", "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
cachetools==5.5.2 chardet==5.2.0 colorama==0.4.6 coverage==7.8.0 distlib==0.3.9 exceptiongroup==1.2.2 filelock==3.18.0 flake8==7.2.0 future==1.0.0 -e git+https://github.com/miki725/importanize.git@2046972231a37055b5698d80153b08ff35e6864b#egg=importanize iniconfig==2.1.0 mccabe==0.7.0 mock==5.2.0 nose==1.3.7 packaging==24.2 platformdirs==4.3.7 pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.1 pyproject-api==1.9.0 pytest==8.3.5 rednose==1.3.0 six==1.17.0 termstyle==0.1.11 tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 virtualenv==20.29.3
name: importanize 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: - cachetools==5.5.2 - chardet==5.2.0 - colorama==0.4.6 - coverage==7.8.0 - distlib==0.3.9 - exceptiongroup==1.2.2 - filelock==3.18.0 - flake8==7.2.0 - future==1.0.0 - iniconfig==2.1.0 - mccabe==0.7.0 - mock==5.2.0 - nose==1.3.7 - packaging==24.2 - platformdirs==4.3.7 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - pyproject-api==1.9.0 - pytest==8.3.5 - rednose==1.3.0 - six==1.17.0 - termstyle==0.1.11 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - virtualenv==20.29.3 prefix: /opt/conda/envs/importanize
[ "tests/test_groups.py::TestBaseImportGroup::test_add_statement_false", "tests/test_groups.py::TestBaseImportGroup::test_add_statement_true", "tests/test_groups.py::TestBaseImportGroup::test_all_line_numbers", "tests/test_groups.py::TestBaseImportGroup::test_as_string", "tests/test_groups.py::TestBaseImportGroup::test_as_string_with_artifacts", "tests/test_groups.py::TestBaseImportGroup::test_formatted", "tests/test_groups.py::TestBaseImportGroup::test_formatted_with_artifacts", "tests/test_groups.py::TestBaseImportGroup::test_init", "tests/test_groups.py::TestBaseImportGroup::test_merged_statements", "tests/test_groups.py::TestBaseImportGroup::test_merged_statements_leafless", "tests/test_groups.py::TestBaseImportGroup::test_should_add_statement", "tests/test_groups.py::TestBaseImportGroup::test_str", "tests/test_groups.py::TestBaseImportGroup::test_unique_statements", "tests/test_groups.py::TestStdLibGroup::test_should_add_statement", "tests/test_groups.py::TestPackagesGroup::test_init", "tests/test_groups.py::TestPackagesGroup::test_should_add_statement", "tests/test_groups.py::TestLocalGroup::test_should_add_statement", "tests/test_groups.py::TestRemainderGroup::test_should_add_statement", "tests/test_groups.py::TestImportGroups::test_add_group", "tests/test_groups.py::TestImportGroups::test_add_statement_to_group_one", "tests/test_groups.py::TestImportGroups::test_add_statement_to_group_priority", "tests/test_groups.py::TestImportGroups::test_all_line_numbers", "tests/test_groups.py::TestImportGroups::test_as_string", "tests/test_groups.py::TestImportGroups::test_formatted_empty", "tests/test_groups.py::TestImportGroups::test_formatted_with_artifacts", "tests/test_groups.py::TestImportGroups::test_init", "tests/test_groups.py::TestImportGroups::test_str_mock", "tests/test_main.py::TestMain::test_find_config", "tests/test_main.py::TestMain::test_main_version", "tests/test_main.py::TestMain::test_main_with_config", "tests/test_main.py::TestMain::test_main_without_config", "tests/test_main.py::TestMain::test_run_folder", "tests/test_main.py::TestMain::test_run_folder_exception", "tests/test_main.py::TestMain::test_run_importanize_print", "tests/test_main.py::TestMain::test_run_importanize_skip", "tests/test_main.py::TestMain::test_run_importanize_write", "tests/test_main.py::TestMain::test_run_single_file", "tests/test_main.py::TestMain::test_run_single_file_exception", "tests/test_parser.py::TestToken::test_is_comment", "tests/test_parser.py::TestToken::test_normalized", "tests/test_parser.py::TestParsing::test_from_statements", "tests/test_parser.py::TestParsing::test_get_file_artifacts", "tests/test_parser.py::TestParsing::test_import_statements", "tests/test_parser.py::TestParsing::test_parsing", "tests/test_parser.py::TestParsing::test_tokenize_import_lines", "tests/test_statements.py::TestImportLeaf::test_as_string", "tests/test_statements.py::TestImportLeaf::test_eq", "tests/test_statements.py::TestImportLeaf::test_gt", "tests/test_statements.py::TestImportLeaf::test_hash", "tests/test_statements.py::TestImportLeaf::test_hash_mock", "tests/test_statements.py::TestImportLeaf::test_init", "tests/test_statements.py::TestImportLeaf::test_repr", "tests/test_statements.py::TestImportLeaf::test_str", "tests/test_statements.py::TestImportLeaf::test_str_mock", "tests/test_statements.py::TestImportStatement::test_add", "tests/test_statements.py::TestImportStatement::test_as_string", "tests/test_statements.py::TestImportStatement::test_eq", "tests/test_statements.py::TestImportStatement::test_formatted", "tests/test_statements.py::TestImportStatement::test_gt", "tests/test_statements.py::TestImportStatement::test_hash", "tests/test_statements.py::TestImportStatement::test_hash_mock", "tests/test_statements.py::TestImportStatement::test_init", "tests/test_statements.py::TestImportStatement::test_repr", "tests/test_statements.py::TestImportStatement::test_root_module", "tests/test_statements.py::TestImportStatement::test_str", "tests/test_statements.py::TestImportStatement::test_str_mock" ]
[]
[]
[]
MIT License
28
[ "Makefile", "importanize/parser.py", "HISTORY.rst", "setup.py", "importanize/main.py", "importanize/__init__.py", "importanize/statements.py", "importanize/groups.py", "importanize/utils.py" ]
[ "Makefile", "importanize/parser.py", "HISTORY.rst", "setup.py", "importanize/main.py", "importanize/__init__.py", "importanize/statements.py", "importanize/groups.py", "importanize/utils.py" ]
nose-devs__nose2-234
5df9a70fe7089b49f42e5ac38a88847b0ba48473
2015-01-18 04:41:59
bbf5897eb1aa224100e86ba594042e4399fd2f5f
diff --git a/nose2/collector.py b/nose2/collector.py index 70fcd87..63a1854 100644 --- a/nose2/collector.py +++ b/nose2/collector.py @@ -13,11 +13,16 @@ def collector(): ok = self._collector(result_) sys.exit(not ok) - def _collector(self, result_): + def _get_objects(self): ssn = session.Session() ldr = loader.PluggableTestLoader(ssn) rnr = runner.PluggableTestRunner(ssn) + return ssn, ldr, rnr + + def _collector(self, result_): + ssn, ldr, rnr = self._get_objects() + ssn.testLoader = ldr ssn.loadConfigFiles('unittest.cfg', 'nose2.cfg', 'setup.cfg') ssn.setStartDir() ssn.prepareSysPath() diff --git a/requirements-2.7.txt b/requirements-2.7.txt index bc04b49..8a8f980 100644 --- a/requirements-2.7.txt +++ b/requirements-2.7.txt @@ -1,1 +1,2 @@ +mock -r requirements.txt diff --git a/requirements-py26.txt b/requirements-py26.txt index 2ed4175..e1cebc9 100644 --- a/requirements-py26.txt +++ b/requirements-py26.txt @@ -1,3 +1,4 @@ +mock unittest2==0.5.1 --allow-external argparse --allow-unverified argparse
Layers is incompatible with setuptools test Layers crashes when tests are run from setuptools via nose2.collector.collector ``` Traceback (most recent call last): File "setup.py", line 8, in <module> test_suite="nose2.collector.collector", File "C:\Python34\lib\distutils\core.py", line 149, in setup dist.run_commands() File "C:\Python34\lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "C:\Python34\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "c:\Projects\tdd_with_python\lib\site-packages\setuptools\command\test.py", line 146, in run self.with_project_on_sys_path(self.run_tests) File "c:\Projects\tdd_with_python\lib\site-packages\setuptools\command\test.py", line 127, in with_project_on_sys_path func() File "c:\Projects\tdd_with_python\lib\site-packages\setuptools\command\test.py", line 167, in run_tests testRunner=self._resolve_as_ep(self.test_runner), File "C:\Python34\lib\unittest\main.py", line 93, in __init__ self.runTests() File "C:\Python34\lib\unittest\main.py", line 244, in runTests self.result = testRunner.run(self.test) File "C:\Python34\lib\unittest\runner.py", line 168, in run test(result) File "C:\Python34\lib\unittest\suite.py", line 87, in __call__ return self.run(*args, **kwds) File "C:\Python34\lib\unittest\suite.py", line 125, in run test(result) File "C:\Python34\lib\unittest\suite.py", line 87, in __call__ return self.run(*args, **kwds) File "C:\Python34\lib\unittest\suite.py", line 125, in run test(result) File "C:\Python34\lib\unittest\case.py", line 622, in __call__ return self.run(*args, **kwds) File "c:\Projects\tdd_with_python\lib\site-packages\nose2\collector.py", line 13, in run ok = self._collector(result_) File "c:\Projects\tdd_with_python\lib\site-packages\nose2\collector.py", line 27, in _collector rslt = rnr.run(test) File "c:\Projects\tdd_with_python\lib\site-packages\nose2\runner.py", line 45, in run self.session.hooks.startTestRun(event) File "c:\Projects\tdd_with_python\lib\site-packages\nose2\events.py", line 224, in __call__ result = getattr(plugin, self.method)(event) File "c:\Projects\tdd_with_python\lib\site-packages\nose2\plugins\layers.py", line 22, in startTestRun event.suite = self._makeLayerSuite(event) File "c:\Projects\tdd_with_python\lib\site-packages\nose2\plugins\layers.py", line 26, in _makeLayerSuite event.suite, self.session.testLoader.suiteClass) AttributeError: 'NoneType' object has no attribute 'suiteClass' ``` Layers uses `session.testLoader` which is set in `PluggableTestProgram.parseArgs`. This field is not set when tests are executed via the `nose2.collector.collector` entry point.
nose-devs/nose2
diff --git a/nose2/tests/unit/test_collector.py b/nose2/tests/unit/test_collector.py index 358de17..7a24da1 100644 --- a/nose2/tests/unit/test_collector.py +++ b/nose2/tests/unit/test_collector.py @@ -1,3 +1,9 @@ +try: + from unittest import mock +except ImportError: + # Older python versions dont have mock by default + import mock + from nose2.tests._common import TestCase, RedirectStdStreams from nose2 import collector from textwrap import dedent @@ -20,3 +26,18 @@ class TestCollector(TestCase): self.assertEqual("", redir.stdout.getvalue()) self.assertTrue(re.match(r'\n-+\nRan 0 tests in \d.\d\d\ds\n\nOK\n', redir.stderr.getvalue())) + + def test_collector_sets_testLoader_in_session(self): + """ + session.testLoader needs to be set so that plugins that use this + field (like Layers) dont break. + """ + test = collector.collector() + mock_session = mock.MagicMock() + mock_loader = mock.MagicMock() + mock_runner = mock.MagicMock() + test._get_objects = mock.Mock(return_value=(mock_session, + mock_loader, + mock_runner)) + test._collector(None) + self.assertTrue(mock_session.testLoader is mock_loader)
{ "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": 3 }
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": 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 cov-core==1.15.0 coverage==6.2 importlib-metadata==4.8.3 iniconfig==1.1.1 -e git+https://github.com/nose-devs/nose2.git@5df9a70fe7089b49f42e5ac38a88847b0ba48473#egg=nose2 packaging==21.3 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: 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=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 - cov-core==1.15.0 - coverage==6.2 - 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 - six==1.17.0 - tomli==1.2.3 - typing-extensions==4.1.1 - zipp==3.6.0 prefix: /opt/conda/envs/nose2
[ "nose2/tests/unit/test_collector.py::TestCollector::test_collector_sets_testLoader_in_session" ]
[]
[ "nose2/tests/unit/test_collector.py::TestCollector::test_collector_completes_with_no_tests" ]
[]
BSD
29
[ "requirements-py26.txt", "nose2/collector.py", "requirements-2.7.txt" ]
[ "requirements-py26.txt", "nose2/collector.py", "requirements-2.7.txt" ]
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
[ "xmltodict.py" ]
[ "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
[ "dtb/gui.py", "dtb/song.py" ]
[ "dtb/gui.py", "dtb/song.py" ]
softlayer__softlayer-python-481
d14a960c929240af09d77717ab5772b22d00e6b1
2015-01-24 02:50:13
200787d4c3bf37bc4e701caf6a52e24dd07d18a3
diff --git a/SoftLayer/CLI/routes.py b/SoftLayer/CLI/routes.py index 67675738..507ce234 100644 --- a/SoftLayer/CLI/routes.py +++ b/SoftLayer/CLI/routes.py @@ -149,6 +149,7 @@ ('server:reboot', 'SoftLayer.CLI.server.power:reboot'), ('server:reload', 'SoftLayer.CLI.server.reload:cli'), ('server:credentials', 'SoftLayer.CLI.server.credentials:cli'), + ('server:update-firmware', 'SoftLayer.CLI.server.update_firmware:cli'), ('snapshot', 'SoftLayer.CLI.snapshot'), ('snapshot:cancel', 'SoftLayer.CLI.snapshot.cancel:cli'), diff --git a/SoftLayer/CLI/server/update_firmware.py b/SoftLayer/CLI/server/update_firmware.py new file mode 100644 index 00000000..f5782787 --- /dev/null +++ b/SoftLayer/CLI/server/update_firmware.py @@ -0,0 +1,27 @@ +"""Update firmware.""" +# :license: MIT, see LICENSE for more details. + +import SoftLayer +from SoftLayer.CLI import environment +from SoftLayer.CLI import exceptions +from SoftLayer.CLI import formatting +from SoftLayer.CLI import helpers + +import click + + [email protected]() [email protected]('identifier') [email protected]_env +def cli(env, identifier): + """Update server firmware.""" + + mgr = SoftLayer.HardwareManager(env.client) + hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') + if env.skip_confirmations or formatting.confirm('This will power off the ' + 'server with id %s and ' + 'update device firmware. ' + 'Continue?' % hw_id): + mgr.update_firmware(hw_id) + else: + raise exceptions.CLIAbort('Aborted.') diff --git a/SoftLayer/managers/hardware.py b/SoftLayer/managers/hardware.py index 29dde1b1..90e911f5 100644 --- a/SoftLayer/managers/hardware.py +++ b/SoftLayer/managers/hardware.py @@ -745,6 +745,28 @@ def edit(self, hardware_id, userdata=None, hostname=None, domain=None, return self.hardware.editObject(obj, id=hardware_id) + def update_firmware(self, + hardware_id, + ipmi=True, + raid_controller=True, + bios=True, + hard_drive=True): + """Update hardware firmware. + + This will cause the server to be unavailable for ~20 minutes. + + :param int hardware_id: The ID of the hardware to have its firmware + updated. + :param bool ipmi: Update the ipmi firmware. + :param bool raid_controller: Update the raid controller firmware. + :param bool bios: Update the bios firmware. + :param bool hard_drive: Update the hard drive firmware. + """ + + return self.hardware.createFirmwareUpdateTransaction( + bool(ipmi), bool(raid_controller), bool(bios), bool(hard_drive), + id=hardware_id) + def get_default_value(package_options, category, hourly=False): """Returns the default price ID for the specified category. diff --git a/SoftLayer/transports.py b/SoftLayer/transports.py index 15964e5c..86307354 100644 --- a/SoftLayer/transports.py +++ b/SoftLayer/transports.py @@ -226,8 +226,8 @@ def __call__(self, call): module_path = 'SoftLayer.testing.fixtures.%s' % call.service module = importlib.import_module(module_path) except ImportError: - raise NotImplementedError('%s::%s fixture is not implemented' - % (call.service, call.method)) + raise NotImplementedError('%s fixture is not implemented' + % call.service) try: return getattr(module, call.method) except AttributeError:
Firmware Update Please add the ability to the API and CLI to update the server's firmware. http://sldn.softlayer.com/reference/services/SoftLayer_Hardware_Server/createFirmwareUpdateTransaction
softlayer/softlayer-python
diff --git a/SoftLayer/testing/fixtures/SoftLayer_Hardware_Server.py b/SoftLayer/testing/fixtures/SoftLayer_Hardware_Server.py index 6da486e1..f8828daa 100644 --- a/SoftLayer/testing/fixtures/SoftLayer_Hardware_Server.py +++ b/SoftLayer/testing/fixtures/SoftLayer_Hardware_Server.py @@ -70,6 +70,7 @@ rebootSoft = True rebootDefault = True rebootHard = True +createFirmwareUpdateTransaction = True setUserMetadata = ['meta'] reloadOperatingSystem = 'OK' getReverseDomainRecords = [ diff --git a/SoftLayer/tests/CLI/modules/server_tests.py b/SoftLayer/tests/CLI/modules/server_tests.py index f11b58a6..2152df0c 100644 --- a/SoftLayer/tests/CLI/modules/server_tests.py +++ b/SoftLayer/tests/CLI/modules/server_tests.py @@ -636,3 +636,14 @@ def test_get_default_value_returns_none_for_unknown_category(self): option_mock = {'categories': {'cat1': []}} output = create._get_default_value(option_mock, 'nope') self.assertEqual(None, output) + + @mock.patch('SoftLayer.CLI.formatting.confirm') + def test_update_firmware(self, confirm_mock): + confirm_mock.return_value = True + result = self.run_command(['server', 'update-firmware', '1000']) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(result.output, "") + self.assert_called_with('SoftLayer_Hardware_Server', + 'createFirmwareUpdateTransaction', + args=((1, 1, 1, 1)), identifier=1000) diff --git a/SoftLayer/tests/managers/hardware_tests.py b/SoftLayer/tests/managers/hardware_tests.py index 86ea0719..5044e247 100644 --- a/SoftLayer/tests/managers/hardware_tests.py +++ b/SoftLayer/tests/managers/hardware_tests.py @@ -473,10 +473,27 @@ def test_edit(self): identifier=100) def test_rescue(self): - # Test rescue environment - restult = self.hardware.rescue(1234) + result = self.hardware.rescue(1234) - self.assertEqual(restult, True) + self.assertEqual(result, True) self.assert_called_with('SoftLayer_Hardware_Server', 'bootToRescueLayer', identifier=1234) + + def test_update_firmware(self): + result = self.hardware.update_firmware(100) + + self.assertEqual(result, True) + self.assert_called_with('SoftLayer_Hardware_Server', + 'createFirmwareUpdateTransaction', + identifier=100, args=(1, 1, 1, 1)) + + def test_update_firmware_selective(self): + result = self.hardware.update_firmware(100, + ipmi=False, + hard_drive=False) + + self.assertEqual(result, True) + self.assert_called_with('SoftLayer_Hardware_Server', + 'createFirmwareUpdateTransaction', + identifier=100, args=(0, 1, 1, 0))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 3 }
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@d14a960c929240af09d77717ab5772b22d00e6b1#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/server_tests.py::ServerCLITests::test_update_firmware", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_update_firmware", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_update_firmware_selective" ]
[]
[ "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_cancel_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_for_bmc", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_missing_required", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_test_flag", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_test_for_bmc", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_test_no_disk", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_test_no_disk_no_raid", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_with_export", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_failed", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata_and_file", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userfile", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_get_default_value_returns_none_for_unknown_category", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_list_chassis_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_list_servers", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_nic_edit_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_cancel_reasons", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_create_options", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_create_options_for_bmc", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_create_options_with_invalid_chassis", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_details", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle_negative", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_off", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_on", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_default", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_hard", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_negative", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_soft", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reload", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_hardware_on_bmc", "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_cancel_metal_immediately", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_cancel_metal_on_anniversary", "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_with_all_bare_metal_options", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_generate_create_dict_with_all_dedicated_server_options", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_available_dedicated_server_packages", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_bare_metal_create_options", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_bare_metal_create_options_returns_none_on_error", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_dedicated_server_options", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_default_value", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_default_value_hourly", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_default_value_monthly", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_default_value_none_free", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_default_value_returns_none_for_unknown_category", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_hardware", "SoftLayer/tests/managers/hardware_tests.py::HardwareTests::test_get_server_packages_with_ordering_manager_provided", "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_verify_order" ]
[]
MIT License
33
[ "SoftLayer/CLI/routes.py", "SoftLayer/CLI/server/update_firmware.py", "SoftLayer/managers/hardware.py", "SoftLayer/transports.py" ]
[ "SoftLayer/CLI/routes.py", "SoftLayer/CLI/server/update_firmware.py", "SoftLayer/managers/hardware.py", "SoftLayer/transports.py" ]
bokeh__bokeh-1760
f161e86976a3ebcc15844339c757ff2e7fb0d9b7
2015-01-24 13:03:44
06016265b60f9cd6dba0fcf9bb7a5bf64b096244
diff --git a/bokeh/properties.py b/bokeh/properties.py index a7304e85d..d234beeb3 100644 --- a/bokeh/properties.py +++ b/bokeh/properties.py @@ -1091,7 +1091,7 @@ class DashPattern(Either): } def __init__(self, default=[], help=None): - types = Enum(enums.DashPattern), Regex(r"^(\d+(\s+\d+)*)?$"), List(Int) + types = Enum(enums.DashPattern), Regex(r"^(\d+(\s+\d+)*)?$"), Seq(Int) super(DashPattern, self).__init__(*types, default=default, help=help) def transform(self, value):
bokeh.plotting.patches line_dash argument only takes a list The `bokeh.plotting.patches` renderer requires the argument to `line_dash` to be a list, it should probably take list and tuple
bokeh/bokeh
diff --git a/bokeh/tests/test_properties.py b/bokeh/tests/test_properties.py index a520745b3..08b27b501 100644 --- a/bokeh/tests/test_properties.py +++ b/bokeh/tests/test_properties.py @@ -330,6 +330,25 @@ class TestDashPattern(unittest.TestCase): with self.assertRaises(ValueError): f.pat = [2, "a"] + def test_list(self): + class Foo(HasProps): + pat = DashPattern + f = Foo() + + f.pat = () + self.assertEqual(f.pat, ()) + f.pat = (2,) + self.assertEqual(f.pat, (2,)) + f.pat = (2, 4) + self.assertEqual(f.pat, (2, 4)) + f.pat = (2, 4, 6) + self.assertEqual(f.pat, (2, 4, 6)) + + with self.assertRaises(ValueError): + f.pat = (2, 4.2) + with self.assertRaises(ValueError): + f.pat = (2, "a") + def test_invalid(self): class Foo(HasProps): pat = DashPattern @@ -764,7 +783,7 @@ class TestProperties(unittest.TestCase): self.assertFalse(prop.is_valid(1.0)) self.assertFalse(prop.is_valid(1.0+1.0j)) self.assertTrue(prop.is_valid("")) - self.assertFalse(prop.is_valid(())) + self.assertTrue(prop.is_valid(())) self.assertTrue(prop.is_valid([])) self.assertFalse(prop.is_valid({})) self.assertFalse(prop.is_valid(Foo()))
{ "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": 0, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 1 }
0.7
{ "env_vars": null, "env_yml_path": null, "install": "pip install bokeh", "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" }
bokeh==3.4.3 contourpy==1.3.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pillow==11.1.0 pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 six==1.17.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tornado==6.4.2 tzdata==2025.2 xyzservices==2025.1.0
name: bokeh 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 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - bokeh==3.4.3 - contourpy==1.3.0 - jinja2==3.1.6 - markupsafe==3.0.2 - numpy==2.0.2 - pandas==2.2.3 - pillow==11.1.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - six==1.17.0 - tornado==6.4.2 - tzdata==2025.2 - xyzservices==2025.1.0 prefix: /opt/conda/envs/bokeh
[ "bokeh/tests/test_properties.py::TestDashPattern::test_list", "bokeh/tests/test_properties.py::TestProperties::test_DashPattern" ]
[]
[ "bokeh/tests/test_properties.py::Basictest::test_enum", "bokeh/tests/test_properties.py::Basictest::test_inheritance", "bokeh/tests/test_properties.py::Basictest::test_no_parens", "bokeh/tests/test_properties.py::Basictest::test_set", "bokeh/tests/test_properties.py::Basictest::test_simple_class", "bokeh/tests/test_properties.py::TestDataSpec::test_default", "bokeh/tests/test_properties.py::TestDataSpec::test_field", "bokeh/tests/test_properties.py::TestDataSpec::test_multiple_instances", "bokeh/tests/test_properties.py::TestDataSpec::test_value", "bokeh/tests/test_properties.py::TestColorSpec::test_default_tuple", "bokeh/tests/test_properties.py::TestColorSpec::test_field", "bokeh/tests/test_properties.py::TestColorSpec::test_field_default", "bokeh/tests/test_properties.py::TestColorSpec::test_fixed_value", "bokeh/tests/test_properties.py::TestColorSpec::test_hex_value", "bokeh/tests/test_properties.py::TestColorSpec::test_named_color_overriding_default", "bokeh/tests/test_properties.py::TestColorSpec::test_named_value", "bokeh/tests/test_properties.py::TestColorSpec::test_named_value_set_none", "bokeh/tests/test_properties.py::TestColorSpec::test_named_value_unset", "bokeh/tests/test_properties.py::TestColorSpec::test_set_dict", "bokeh/tests/test_properties.py::TestColorSpec::test_tuple_value", "bokeh/tests/test_properties.py::TestDashPattern::test_invalid", "bokeh/tests/test_properties.py::TestDashPattern::test_named", "bokeh/tests/test_properties.py::TestDashPattern::test_string", "bokeh/tests/test_properties.py::TestProperties::test_Align", "bokeh/tests/test_properties.py::TestProperties::test_Angle", "bokeh/tests/test_properties.py::TestProperties::test_Any", "bokeh/tests/test_properties.py::TestProperties::test_Bool", "bokeh/tests/test_properties.py::TestProperties::test_Color", "bokeh/tests/test_properties.py::TestProperties::test_Complex", "bokeh/tests/test_properties.py::TestProperties::test_Dict", "bokeh/tests/test_properties.py::TestProperties::test_Either", "bokeh/tests/test_properties.py::TestProperties::test_Enum", "bokeh/tests/test_properties.py::TestProperties::test_Float", "bokeh/tests/test_properties.py::TestProperties::test_Instance", "bokeh/tests/test_properties.py::TestProperties::test_Int", "bokeh/tests/test_properties.py::TestProperties::test_List", "bokeh/tests/test_properties.py::TestProperties::test_Percent", "bokeh/tests/test_properties.py::TestProperties::test_Range", "bokeh/tests/test_properties.py::TestProperties::test_Regex", "bokeh/tests/test_properties.py::TestProperties::test_Size", "bokeh/tests/test_properties.py::TestProperties::test_String", "bokeh/tests/test_properties.py::TestProperties::test_Tuple", "bokeh/tests/test_properties.py::test_HasProps_clone" ]
[]
BSD 3-Clause "New" or "Revised" License
34
[ "bokeh/properties.py" ]
[ "bokeh/properties.py" ]
ipython__ipython-7819
92333e1084ea0d6ff91b55434555e741d2274dc7
2015-02-19 20:14:23
9e486f4cba27a9d43f75363e60d5371f6c18855c
diff --git a/IPython/html/static/notebook/js/actions.js b/IPython/html/static/notebook/js/actions.js index 828b724e7..40816144e 100644 --- a/IPython/html/static/notebook/js/actions.js +++ b/IPython/html/static/notebook/js/actions.js @@ -79,7 +79,6 @@ define(function(require){ } }, 'select-previous-cell' : { - help: 'select cell above', help_index : 'da', handler : function (env) { var index = env.notebook.get_selected_index(); @@ -90,7 +89,6 @@ define(function(require){ } }, 'select-next-cell' : { - help: 'select cell below', help_index : 'db', handler : function (env) { var index = env.notebook.get_selected_index(); @@ -119,14 +117,12 @@ define(function(require){ } }, 'paste-cell-before' : { - help: 'paste cell above', help_index : 'eg', handler : function (env) { env.notebook.paste_cell_above(); } }, 'paste-cell-after' : { - help: 'paste cell below', icon: 'fa-paste', help_index : 'eh', handler : function (env) { @@ -134,7 +130,6 @@ define(function(require){ } }, 'insert-cell-before' : { - help: 'insert cell above', help_index : 'ec', handler : function (env) { env.notebook.insert_cell_above(); @@ -143,7 +138,6 @@ define(function(require){ } }, 'insert-cell-after' : { - help: 'insert cell below', icon : 'fa-plus', help_index : 'ed', handler : function (env) { @@ -257,7 +251,6 @@ define(function(require){ } }, 'delete-cell': { - help: 'delete selected cell', help_index : 'ej', handler : function (env) { env.notebook.delete_cell(); diff --git a/IPython/html/static/notebook/js/quickhelp.js b/IPython/html/static/notebook/js/quickhelp.js index 36402139f..bceaa2db1 100644 --- a/IPython/html/static/notebook/js/quickhelp.js +++ b/IPython/html/static/notebook/js/quickhelp.js @@ -38,8 +38,8 @@ define([ { shortcut: "Cmd-Down", help:"go to cell end" }, { shortcut: "Alt-Left", help:"go one word left" }, { shortcut: "Alt-Right", help:"go one word right" }, - { shortcut: "Alt-Backspace", help:"delete word before" }, - { shortcut: "Alt-Delete", help:"delete word after" }, + { shortcut: "Alt-Backspace", help:"del word before" }, + { shortcut: "Alt-Delete", help:"del word after" }, ]; } else { // PC specific @@ -50,8 +50,8 @@ define([ { shortcut: "Ctrl-Down", help:"go to cell end" }, { shortcut: "Ctrl-Left", help:"go one word left" }, { shortcut: "Ctrl-Right", help:"go one word right" }, - { shortcut: "Ctrl-Backspace", help:"delete word before" }, - { shortcut: "Ctrl-Delete", help:"delete word after" }, + { shortcut: "Ctrl-Backspace", help:"del word before" }, + { shortcut: "Ctrl-Delete", help:"del word after" }, ]; } diff --git a/IPython/html/static/widgets/js/widget.js b/IPython/html/static/widgets/js/widget.js index e5f758dd3..073186716 100644 --- a/IPython/html/static/widgets/js/widget.js +++ b/IPython/html/static/widgets/js/widget.js @@ -155,9 +155,8 @@ define(["widgets/js/manager", this.trigger('msg:custom', msg.content.data.content); break; case 'display': - this.state_change = this.state_change.then(function() { - that.widget_manager.display_view(msg, that); - }).catch(utils.reject('Could not process display view msg', true)); + this.widget_manager.display_view(msg, this) + .catch(utils.reject('Could not process display view msg', true)); break; } }, diff --git a/IPython/utils/tokenutil.py b/IPython/utils/tokenutil.py index 48cc82c2e..f0040bfd8 100644 --- a/IPython/utils/tokenutil.py +++ b/IPython/utils/tokenutil.py @@ -58,6 +58,9 @@ def token_at_cursor(cell, cursor_pos=0): Used for introspection. + Function calls are prioritized, so the token for the callable will be returned + if the cursor is anywhere inside the call. + Parameters ---------- @@ -70,6 +73,7 @@ def token_at_cursor(cell, cursor_pos=0): names = [] tokens = [] offset = 0 + call_names = [] for tup in generate_tokens(StringIO(cell).readline): tok = Token(*tup) @@ -93,6 +97,11 @@ def token_at_cursor(cell, cursor_pos=0): if tok.text == '=' and names: # don't inspect the lhs of an assignment names.pop(-1) + if tok.text == '(' and names: + # if we are inside a function call, inspect the function + call_names.append(names[-1]) + elif tok.text == ')' and call_names: + call_names.pop(-1) if offset + end_col > cursor_pos: # we found the cursor, stop reading @@ -102,7 +111,9 @@ def token_at_cursor(cell, cursor_pos=0): if tok.token == tokenize2.NEWLINE: offset += len(tok.line) - if names: + if call_names: + return call_names[-1] + elif names: return names[-1] else: return '' diff --git a/examples/Notebook/Notebook Basics.ipynb b/examples/Notebook/Notebook Basics.ipynb index ae67fab91..ce5c43338 100644 --- a/examples/Notebook/Notebook Basics.ipynb +++ b/examples/Notebook/Notebook Basics.ipynb @@ -226,7 +226,7 @@ "1. Basic navigation: `enter`, `shift-enter`, `up/k`, `down/j`\n", "2. Saving the notebook: `s`\n", "2. Cell types: `y`, `m`, `1-6`, `t`\n", - "3. Cell creation: `a`, `b`\n", + "3. Cell creation and movement: `a`, `b`, `ctrl+k`, `ctrl+j`\n", "4. Cell editing: `x`, `c`, `v`, `d`, `z`, `shift+=`\n", "5. Kernel operations: `i`, `.`" ]
Inspect requests inside a function call should be smarter about what they inspect. Previously, `func(a, b, <shift-tab>` would give information on `func`, now it gives information on `b`, which is not especially helpful. This is because we removed logic from the frontend to make it more language agnostic, and we have not yet reimplemented that on the frontend. For 3.1, we should make it at least as smart as 2.x was. The quicky and dirty approach would be a regex; the proper way is tokenising the code. Ping @mwaskom who brought this up on the mailing list.
ipython/ipython
diff --git a/IPython/utils/tests/test_tokenutil.py b/IPython/utils/tests/test_tokenutil.py index be9cb578a..ff3efc75c 100644 --- a/IPython/utils/tests/test_tokenutil.py +++ b/IPython/utils/tests/test_tokenutil.py @@ -48,13 +48,28 @@ def test_multiline(): start = cell.index(expected) + 1 for i in range(start, start + len(expected)): expect_token(expected, cell, i) - expected = 'there' + expected = 'hello' start = cell.index(expected) + 1 for i in range(start, start + len(expected)): expect_token(expected, cell, i) +def test_nested_call(): + cell = "foo(bar(a=5), b=10)" + expected = 'foo' + start = cell.index('bar') + 1 + for i in range(start, start + 3): + expect_token(expected, cell, i) + expected = 'bar' + start = cell.index('a=') + for i in range(start, start + 3): + expect_token(expected, cell, i) + expected = 'foo' + start = cell.index(')') + 1 + for i in range(start, len(cell)-1): + expect_token(expected, cell, i) + def test_attrs(): - cell = "foo(a=obj.attr.subattr)" + cell = "a = obj.attr.subattr" expected = 'obj' idx = cell.find('obj') + 1 for i in range(idx, idx + 3):
{ "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": 1 }, "num_modified_files": 5 }
2.4
{ "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@92333e1084ea0d6ff91b55434555e741d2274dc7#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 ptyprocess==0.7.0 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 terminado==0.17.1 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 - ptyprocess==0.7.0 - 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 - terminado==0.17.1 - tornado==6.2 - urllib3==2.0.7 prefix: /opt/conda/envs/ipython
[ "IPython/utils/tests/test_tokenutil.py::test_nested_call" ]
[]
[ "IPython/utils/tests/test_tokenutil.py::test_simple", "IPython/utils/tests/test_tokenutil.py::test_function", "IPython/utils/tests/test_tokenutil.py::test_multiline", "IPython/utils/tests/test_tokenutil.py::test_attrs", "IPython/utils/tests/test_tokenutil.py::test_line_at_cursor" ]
[]
BSD 3-Clause "New" or "Revised" License
39
[ "IPython/html/static/notebook/js/quickhelp.js", "examples/Notebook/Notebook", "IPython/html/static/notebook/js/actions.js", "examples/Notebook/Notebook Basics.ipynb", "IPython/utils/tokenutil.py", "IPython/html/static/widgets/js/widget.js" ]
[ "IPython/html/static/notebook/js/quickhelp.js", "IPython/html/static/notebook/js/actions.js", "sics.ipynb", "examples/Notebook/Notebook Basics.ipynb", "IPython/utils/tokenutil.py", "IPython/html/static/widgets/js/widget.js" ]
grampajoe__happy-6
7121a2d81b511fd198624ddb37526ef541ffd2c6
2015-02-22 19:55:52
5452df62558066dc7b6f1ee408f55bc60da6bdf7
diff --git a/README.rst b/README.rst index 1acae81..738e6ed 100644 --- a/README.rst +++ b/README.rst @@ -75,6 +75,13 @@ happy can find it later. logged in through Heroku CLI, i.e. your token is stored in your ``netrc`` file. +- ``--env`` + + (optional) Environment variable overrides, e.g. ``--env KEY=value``. For + multiple variables, this option can be passed more than once. Variable names + MUST match one of the names in the ``env`` section of your ``app.json``, or + the build will fail with an ``invalid app.json`` message. + - ``--tarball-url`` (optional) URL of the tarball containing app.json. If this is not given, diff --git a/happy/__init__.py b/happy/__init__.py index a59c152..b5be08e 100644 --- a/happy/__init__.py +++ b/happy/__init__.py @@ -15,13 +15,14 @@ class Happy(object): """ self._api = Heroku(auth_token=auth_token) - def create(self, tarball_url): + def create(self, tarball_url, env=None): """Creates a Heroku app-setup build. :param tarball_url: URL of a tarball containing an ``app.json``. + :param env: Dict containing environment variable overrides. :returns: A tuple with ``(build_id, app_name)``. """ - data = self._api.create_build(tarball_url=tarball_url) + data = self._api.create_build(tarball_url=tarball_url, env=env) return (data['id'], data['app']['name']) diff --git a/happy/cli.py b/happy/cli.py index 4636560..76083e4 100644 --- a/happy/cli.py +++ b/happy/cli.py @@ -52,7 +52,8 @@ def cli(): @cli.command(name='up') @click.option('--tarball-url', help='URL of the tarball containing app.json.') @click.option('--auth-token', help='Heroku API auth token.') -def up(tarball_url, auth_token): [email protected]('--env', multiple=True, help='Env override, e.g. KEY=value.') +def up(tarball_url, auth_token, env): """Brings up a Heroku app.""" tarball_url = tarball_url or _infer_tarball_url() @@ -60,11 +61,18 @@ def up(tarball_url, auth_token): click.echo('No tarball URL found.') sys.exit(1) + if env: + # Split ["KEY=value", ...] into {"KEY": "value", ...} + env = { + arg.split('=')[0]: arg.split('=')[1] + for arg in env + } + happy = Happy(auth_token=auth_token) click.echo('Creating app... ', nl=False) - build_id, app_name = happy.create(tarball_url=tarball_url) + build_id, app_name = happy.create(tarball_url=tarball_url, env=env) click.echo(app_name) diff --git a/happy/heroku.py b/happy/heroku.py index a5f95c9..9684b34 100644 --- a/happy/heroku.py +++ b/happy/heroku.py @@ -66,10 +66,11 @@ class Heroku(object): return response.json() - def create_build(self, tarball_url): + def create_build(self, tarball_url, env=None): """Creates an app-setups build. Returns response data as a dict. :param tarball_url: URL of a tarball containing an ``app.json``. + :param env: Dict containing environment variable overrides. :returns: Response data as a ``dict``. """ data = { @@ -78,6 +79,9 @@ class Heroku(object): } } + if env: + data['overrides'] = {'env': env} + return self.api_request('POST', '/app-setups', data=data) def check_build_status(self, build_id):
Add an --env option to pass env overrides There should be an `--env` option for `happy up` that allows passing env overrides to the `app-setups` endpoint.
grampajoe/happy
diff --git a/tests/test_cli.py b/tests/test_cli.py index b613880..2bfaeb8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -96,6 +96,26 @@ def test_up_no_tarball_url(happy, runner): assert 'no tarball' in result.output.lower() +def test_up_env(happy, runner): + """Running up --env should pass environment overrides.""" + with runner.isolated_filesystem(): + runner.invoke(cli, [ + 'up', + '--env', + 'FART=test', + '--env', + 'BUTT=wow', + '--tarball-url=example.com', + ]) + + args_, kwargs = happy().create.call_args + + assert kwargs['env'] == { + 'FART': 'test', + 'BUTT': 'wow', + } + + def test_up_writes_app_name(happy, runner): """Running up should write the app name to .happy.""" with runner.isolated_filesystem(): diff --git a/tests/test_happy.py b/tests/test_happy.py index a5bdb25..f343079 100644 --- a/tests/test_happy.py +++ b/tests/test_happy.py @@ -39,7 +39,20 @@ def test_create(heroku, happy): """Should create an app build on Heroku.""" happy.create(tarball_url='tarball-url') - heroku().create_build.assert_called_with(tarball_url='tarball-url') + heroku().create_build.assert_called_with( + env=None, + tarball_url='tarball-url', + ) + + +def test_create_env(heroku, happy): + """Should pass env overrides to Heroku.create_build.""" + happy.create(tarball_url='tarball-url', env={'TEST': 'env'}) + + heroku().create_build.assert_called_with( + tarball_url='tarball-url', + env={'TEST': 'env'}, + ) def test_create_returns_app_name(heroku, happy): diff --git a/tests/test_heroku.py b/tests/test_heroku.py index 2ea21f2..5a7a5e5 100644 --- a/tests/test_heroku.py +++ b/tests/test_heroku.py @@ -124,6 +124,23 @@ def test_heroku_create_build(api_request): assert result == fake_json [email protected](Heroku, 'api_request') +def test_heroku_create_build_env(api_request): + """Heroku.create_build should send a POST to /app-setups.""" + heroku = Heroku() + + result = heroku.create_build('tarball-url', env={'HELLO': 'world'}) + + api_request.assert_called_with( + 'POST', + '/app-setups', + data={ + 'source_blob': {'url': 'tarball-url'}, + 'overrides': {'env': {'HELLO': 'world'}}, + }, + ) + + @mock.patch.object(Heroku, 'api_request') def test_heroku_check_build_status(api_request): """Heroku.check_build_status should send a GET to /app-setups/:id."""
{ "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": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 4 }
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-flake8", "mock" ], "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" }
certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 coverage==7.8.0 exceptiongroup==1.2.2 flake8==7.2.0 -e git+https://github.com/grampajoe/happy.git@7121a2d81b511fd198624ddb37526ef541ffd2c6#egg=happy idna==3.10 iniconfig==2.1.0 mccabe==0.7.0 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.2 pytest==8.3.5 pytest-cov==6.0.0 pytest-flake8==1.3.0 requests==2.32.3 tomli==2.2.1 urllib3==2.3.0
name: happy 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 - click==8.1.8 - coverage==7.8.0 - exceptiongroup==1.2.2 - flake8==7.2.0 - idna==3.10 - iniconfig==2.1.0 - mccabe==0.7.0 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.2 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-flake8==1.3.0 - requests==2.32.3 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/happy
[ "tests/test_cli.py::test_up_env", "tests/test_happy.py::test_create", "tests/test_happy.py::test_create_env", "tests/test_heroku.py::test_heroku_create_build_env" ]
[]
[ "tests/test_cli.py::test_help", "tests/test_cli.py::test_up", "tests/test_cli.py::test_up_auth_token", "tests/test_cli.py::test_up_tarball_url", "tests/test_cli.py::test_up_tarball_url_app_json", "tests/test_cli.py::test_up_no_tarball_url", "tests/test_cli.py::test_up_writes_app_name", "tests/test_cli.py::test_up_waits_for_build", "tests/test_cli.py::test_up_prints_info", "tests/test_cli.py::test_down", "tests/test_cli.py::test_down_auth_token", "tests/test_cli.py::test_down_deletes_app_name_file", "tests/test_cli.py::test_down_no_app", "tests/test_cli.py::test_down_prints_info", "tests/test_happy.py::test_auth_token", "tests/test_happy.py::test_create_returns_app_name", "tests/test_happy.py::test_wait", "tests/test_happy.py::test_delete", "tests/test_heroku.py::test_heroku", "tests/test_heroku.py::test_heroku_api_request", "tests/test_heroku.py::test_heroku_api_request_headers", "tests/test_heroku.py::test_heroku_api_request_auth_token", "tests/test_heroku.py::test_heroku_api_request_fail", "tests/test_heroku.py::test_heroku_api_request_big_fail", "tests/test_heroku.py::test_heroku_create_build", "tests/test_heroku.py::test_heroku_check_build_status", "tests/test_heroku.py::test_heroku_check_build_status_pending", "tests/test_heroku.py::test_heroku_check_build_status_succeeded", "tests/test_heroku.py::test_heroku_check_build_status_failed", "tests/test_heroku.py::test_heroku_delete_app" ]
[]
MIT License
41
[ "README.rst", "happy/__init__.py", "happy/cli.py", "happy/heroku.py" ]
[ "README.rst", "happy/__init__.py", "happy/cli.py", "happy/heroku.py" ]
Juniper__py-junos-eznc-351
c561ed6f7e16b63a2d71c410c1ce2acc4fa75ed8
2015-02-23 20:42:02
b6e548b7342bc5b867af03d08c65564768c340b0
diff --git a/lib/jnpr/junos/exception.py b/lib/jnpr/junos/exception.py index 6e3a89fa..390dc34e 100644 --- a/lib/jnpr/junos/exception.py +++ b/lib/jnpr/junos/exception.py @@ -1,4 +1,3 @@ -from lxml import etree from jnpr.junos import jxml @@ -129,6 +128,9 @@ class ConnectError(Exception): """ Parent class for all connection related exceptions """ + def __init__(self, dev, msg=None): + self.dev = dev + self._orig = msg @property def user(self): @@ -145,15 +147,18 @@ class ConnectError(Exception): """ login SSH port """ return self.dev._port - def __init__(self, dev): - self.dev = dev - # @@@ need to attach attributes for each access - # @@@ to user-name, host, jump-host, etc. + @property + def msg(self): + """ login SSH port """ + return self._orig def __repr__(self): - return "{0}({1})".format( - self.__class__.__name__, - self.dev.hostname) + if self._orig: + return "{0}(host: {1}, msg: {2})".format(self.__class__.__name__, + self.dev.hostname, self._orig) + else: + return "{0}({1})".format(self.__class__.__name__, + self.dev.hostname) __str__ = __repr__
Invalid host key error not caught If the `~.ssh/known_hosts` file contains an invalid entry (in my case, caused by a missing newline) then PyEZ will only return the nondescript `ConnectError` message. The failure comes from the **ncclient** `manager.connect()` function which, in turn, calls **paramiko**'s `load_known_hosts()`. The latter actually returns a clear error message: ``` InvalidHostKey: ('172.22.196.114 ssh-rsa AAAA... <snip /> ...+SQ==', Error('Incorrect padding',)) ``` I think there are 2 issues here: 1. **ncclient** `manager.connect()` takes several arguments, one of which is `hostkey_verify` which we set to `False` so I believe we should not even be loading the `known_hosts` file. I played with different parameters and we always seem to be performing this verification - this is a ncclient bug in my opinion. 2. PyEZ obfuscates the error by using the generic ConnectError message - this occurs in the following bit of code in the `device.py` file: ```python except Exception as err: # anything else, we will re-raise as a # generic ConnectError cnx_err = EzErrors.ConnectError(self) cnx_err._orig = err raise cnx_err ``` If we were to `raise cnx_err._orig` instead then we would have a clearer picture of what's going on.
Juniper/py-junos-eznc
diff --git a/tests/unit/test_exception.py b/tests/unit/test_exception.py index bf340cd9..99821e75 100644 --- a/tests/unit/test_exception.py +++ b/tests/unit/test_exception.py @@ -61,14 +61,19 @@ class Test_RpcError(unittest.TestCase): self.assertEqual(obj.rpc_error['bad_element'], 'unit 2') def test_ConnectError(self): - self.dev = Device(host='1.1.1.1', user='rick', password='password123', - gather_facts=False) + self.dev = Device(host='1.1.1.1', user='rick') obj = ConnectError(self.dev) self.assertEqual(obj.user, 'rick') self.assertEqual(obj.host, '1.1.1.1') self.assertEqual(obj.port, 830) self.assertEqual(repr(obj), 'ConnectError(1.1.1.1)') + def test_ConnectError_msg(self): + self.dev = Device(host='1.1.1.1', user='rick') + obj = ConnectError(self.dev, msg='underlying exception info') + self.assertEqual(obj.msg, 'underlying exception info') + self.assertEqual(repr(obj), 'ConnectError(host: 1.1.1.1, msg: underlying exception info)') + def test_CommitError_repr(self): rsp = etree.XML(commit_xml) obj = CommitError(rsp=rsp)
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 2, "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": [ "coverage", "mock", "nose", "pep8", "pyflakes", "coveralls", "ntc_templates", "cryptography==3.2", "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" }
bcrypt==4.2.1 certifi @ file:///croot/certifi_1671487769961/work/certifi cffi==1.15.1 charset-normalizer==3.4.1 coverage==6.5.0 coveralls==3.3.1 cryptography==44.0.2 docopt==0.6.2 exceptiongroup==1.2.2 future==1.0.0 idna==3.10 importlib-metadata==6.7.0 iniconfig==2.0.0 Jinja2==3.1.6 -e git+https://github.com/Juniper/py-junos-eznc.git@c561ed6f7e16b63a2d71c410c1ce2acc4fa75ed8#egg=junos_eznc lxml==5.3.1 MarkupSafe==2.1.5 mock==5.2.0 ncclient==0.6.19 netaddr==1.3.0 nose==1.3.7 ntc_templates==4.0.1 packaging==24.0 paramiko==3.5.1 pep8==1.7.1 pluggy==1.2.0 pycparser==2.21 pyflakes==3.0.1 PyNaCl==1.5.0 pytest==7.4.4 PyYAML==6.0.1 requests==2.31.0 scp==0.15.0 six==1.17.0 textfsm==1.1.3 tomli==2.0.1 typing_extensions==4.7.1 urllib3==2.0.7 zipp==3.15.0
name: py-junos-eznc 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: - bcrypt==4.2.1 - cffi==1.15.1 - charset-normalizer==3.4.1 - coverage==6.5.0 - coveralls==3.3.1 - cryptography==44.0.2 - docopt==0.6.2 - exceptiongroup==1.2.2 - future==1.0.0 - idna==3.10 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - jinja2==3.1.6 - lxml==5.3.1 - markupsafe==2.1.5 - mock==5.2.0 - ncclient==0.6.19 - netaddr==1.3.0 - nose==1.3.7 - ntc-templates==4.0.1 - packaging==24.0 - paramiko==3.5.1 - pep8==1.7.1 - pluggy==1.2.0 - pycparser==2.21 - pyflakes==3.0.1 - pynacl==1.5.0 - pytest==7.4.4 - pyyaml==6.0.1 - requests==2.31.0 - scp==0.15.0 - six==1.17.0 - textfsm==1.1.3 - tomli==2.0.1 - typing-extensions==4.7.1 - urllib3==2.0.7 - zipp==3.15.0 prefix: /opt/conda/envs/py-junos-eznc
[ "tests/unit/test_exception.py::Test_RpcError::test_ConnectError_msg" ]
[]
[ "tests/unit/test_exception.py::Test_RpcError::test_CommitError_repr", "tests/unit/test_exception.py::Test_RpcError::test_ConfigLoadError_repr", "tests/unit/test_exception.py::Test_RpcError::test_ConnectError", "tests/unit/test_exception.py::Test_RpcError::test_RpcTimeoutError_repr", "tests/unit/test_exception.py::Test_RpcError::test_rpcerror_jxml_check", "tests/unit/test_exception.py::Test_RpcError::test_rpcerror_repr" ]
[]
Apache License 2.0
42
[ "lib/jnpr/junos/exception.py" ]
[ "lib/jnpr/junos/exception.py" ]
richardkiss__pycoin-88
f1460bae2d7cda77f1380ec08e7bbe1f38a34163
2015-02-25 16:42:19
7833e86ac5260f784ded567dcec42d63cee036aa
diff --git a/CREDITS b/CREDITS index 55e4cc4..c21c03b 100644 --- a/CREDITS +++ b/CREDITS @@ -14,7 +14,7 @@ Mike Owens https://github.com/mike0wens Todd Boland https://github.com/boland https://github.com/ap-m Roman Zeyde https://github.com/romanz -Matthew Bogosian https://github.com/mbogosian +Matt Bogosian https://github.com/posita JahPowerBit https://github.com/JahPowerBit https://github.com/fluxism BtcDrak https://github.com/btcdrak diff --git a/pycoin/key/Key.py b/pycoin/key/Key.py index 95ad838..809551c 100644 --- a/pycoin/key/Key.py +++ b/pycoin/key/Key.py @@ -220,6 +220,6 @@ class Key(object): def __repr__(self): r = self.public_copy().as_text() - if self.is_private: + if self.is_private(): return "private_for <%s>" % r return "<%s>" % r diff --git a/pycoin/scripts/genwallet.py b/pycoin/scripts/genwallet.py index e9cacf7..ba1c0e2 100755 --- a/pycoin/scripts/genwallet.py +++ b/pycoin/scripts/genwallet.py @@ -72,7 +72,7 @@ def main(): child_index = "%d" % wallet.child_index() if args.json: d = dict( - wallet_key=wallet.wallet_key(as_private=wallet.is_private), + wallet_key=wallet.wallet_key(as_private=wallet.is_private()), public_pair_x=wallet.public_pair[0], public_pair_y=wallet.public_pair[1], tree_depth=wallet.depth, @@ -84,7 +84,7 @@ def main(): bitcoin_addr_uncompressed=wallet.bitcoin_address(compressed=False), network="test" if wallet.is_test else "main", ) - if wallet.is_private: + if wallet.is_private(): d.update(dict( key="private", secret_exponent=wallet.secret_exponent, @@ -95,9 +95,9 @@ def main(): d.update(dict(key="public")) print(json.dumps(d, indent=3)) elif args.info: - print(wallet.wallet_key(as_private=wallet.is_private)) + print(wallet.wallet_key(as_private=wallet.is_private())) print(full_network_name_for_netcode(wallet.netcode)) - if wallet.is_private: + if wallet.is_private(): print("private key") print("secret exponent: %d" % wallet.secret_exponent) else: @@ -108,7 +108,7 @@ def main(): print("parent f'print: %s" % b2h(wallet.parent_fingerprint)) print("child index: %s" % child_index) print("chain code: %s" % b2h(wallet.chain_code)) - if wallet.is_private: + if wallet.is_private(): print("WIF: %s" % wallet.wif()) print(" uncompressed: %s" % wallet.wif(compressed=False)) print("Bitcoin address: %s" % wallet.bitcoin_address()) @@ -118,7 +118,7 @@ def main(): elif args.wif: print(wallet.wif(compressed=not args.uncompressed)) else: - print(wallet.wallet_key(as_private=wallet.is_private)) + print(wallet.wallet_key(as_private=wallet.is_private())) except PublicPrivateMismatchError as ex: print(ex.args[0])
Fixed in PR #88 - Key.is_private (which is always True) is used in some places instead of Key.is_private() (which is sometimes False) See, e.g.: https://github.com/richardkiss/pycoin/blob/5a3f30986dec6b4e82c45c0955c139891ce8ba0f/pycoin/key/Key.py#L223 https://github.com/richardkiss/pycoin/blob/5a3f30986dec6b4e82c45c0955c139891ce8ba0f/pycoin/scripts/genwallet.py#L87
richardkiss/pycoin
diff --git a/tests/bip32_test.py b/tests/bip32_test.py index fa2c37b..75bb2a9 100755 --- a/tests/bip32_test.py +++ b/tests/bip32_test.py @@ -151,6 +151,20 @@ class Bip0032TestCase(unittest.TestCase): uag = my_prv.subkey(i=0, is_hardened=True, as_private=True) self.assertEqual(None, uag.subkey(i=0, as_private=False).secret_exponent()) + def test_repr(self): + from pycoin.key import Key + netcode = 'XTN' + key = Key(secret_exponent=273, netcode=netcode) + wallet = BIP32Node.from_master_secret(bytes(key.wif().encode('ascii')), netcode) + + address = wallet.address() + pub_k = wallet.from_text(address) + self.assertEqual(repr(pub_k), '<myb5gZNXePNf2E2ksrjnHRFCwyuvt7oEay>') + + wif = wallet.wif() + priv_k = wallet.from_text(wif) + self.assertEqual(repr(priv_k), 'private_for <03ad094b1dc9fdce5d3648ca359b4e210a89d049532fdd39d9ccdd8ca393ac82f4>') + if __name__ == '__main__': unittest.main() diff --git a/tests/key_validate_test.py b/tests/key_validate_test.py index cee20ce..7cabd8c 100755 --- a/tests/key_validate_test.py +++ b/tests/key_validate_test.py @@ -2,12 +2,10 @@ import unittest -from pycoin.block import Block from pycoin.encoding import hash160_sec_to_bitcoin_address from pycoin.key import Key -from pycoin.key.bip32 import Wallet -from pycoin.networks import pay_to_script_prefix_for_netcode, prv32_prefix_for_netcode, NETWORK_NAMES -from pycoin.serialize import b2h_rev, h2b +from pycoin.key.BIP32Node import BIP32Node +from pycoin.networks import pay_to_script_prefix_for_netcode, NETWORK_NAMES from pycoin.key.validate import is_address_valid, is_wif_valid, is_public_bip32_valid, is_private_bip32_valid @@ -69,7 +67,7 @@ class KeyUtilsTest(unittest.TestCase): # not all networks support BIP32 yet for netcode in "BTC XTN DOGE".split(): for wk in WALLET_KEYS: - wallet = Wallet.from_master_secret(wk.encode("utf8"), netcode=netcode) + wallet = BIP32Node.from_master_secret(wk.encode("utf8"), netcode=netcode) text = wallet.wallet_key(as_private=True) self.assertEqual(is_private_bip32_valid(text, allowable_netcodes=NETWORK_NAMES), netcode) self.assertEqual(is_public_bip32_valid(text, allowable_netcodes=NETWORK_NAMES), None) @@ -82,3 +80,17 @@ class KeyUtilsTest(unittest.TestCase): a = text[:-1] + chr(ord(text[-1])+1) self.assertEqual(is_private_bip32_valid(a, allowable_netcodes=NETWORK_NAMES), None) self.assertEqual(is_public_bip32_valid(a, allowable_netcodes=NETWORK_NAMES), None) + + def test_repr(self): + key = Key(secret_exponent=273, netcode='XTN') + + address = key.address() + pub_k = Key.from_text(address) + self.assertEqual(repr(pub_k), '<mhDVBkZBWLtJkpbszdjZRkH1o5RZxMwxca>') + + wif = key.wif() + priv_k = Key.from_text(wif) + self.assertEqual(repr(priv_k), 'private_for <0264e1b1969f9102977691a40431b0b672055dcf31163897d996434420e6c95dc9>') + +if __name__ == '__main__': + unittest.main()
{ "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": 3 }, "num_modified_files": 3 }
0.52
{ "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": [ "pip-req.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 -e git+https://github.com/richardkiss/pycoin.git@f1460bae2d7cda77f1380ec08e7bbe1f38a34163#egg=pycoin pytest==8.3.5 tomli==2.2.1
name: pycoin 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 - tomli==2.2.1 prefix: /opt/conda/envs/pycoin
[ "tests/bip32_test.py::Bip0032TestCase::test_repr", "tests/key_validate_test.py::KeyUtilsTest::test_repr" ]
[]
[ "tests/bip32_test.py::Bip0032TestCase::test_public_subkey", "tests/bip32_test.py::Bip0032TestCase::test_streams", "tests/bip32_test.py::Bip0032TestCase::test_testnet", "tests/bip32_test.py::Bip0032TestCase::test_vector_1", "tests/bip32_test.py::Bip0032TestCase::test_vector_2", "tests/key_validate_test.py::KeyUtilsTest::test_address_valid_btc", "tests/key_validate_test.py::KeyUtilsTest::test_is_public_private_bip32_valid", "tests/key_validate_test.py::KeyUtilsTest::test_is_wif_valid" ]
[]
MIT License
43
[ "pycoin/key/Key.py", "pycoin/scripts/genwallet.py", "CREDITS" ]
[ "pycoin/key/Key.py", "pycoin/scripts/genwallet.py", "CREDITS" ]
ipython__ipython-7872
cbcf741896140953195ea9cd3de0f10c3f28bef1
2015-02-25 22:51:22
9e486f4cba27a9d43f75363e60d5371f6c18855c
diff --git a/IPython/config/manager.py b/IPython/config/manager.py index 429bfaa97..0628a6afa 100644 --- a/IPython/config/manager.py +++ b/IPython/config/manager.py @@ -86,7 +86,7 @@ def set(self, section_name, data): else: f = open(filename, 'wb') with f: - json.dump(data, f, indent=2) + json.dump(data, f) def update(self, section_name, new_data): """Modify the config section by recursively updating it with new_data. diff --git a/IPython/html/services/config/manager.py b/IPython/html/services/config/manager.py index c26828428..78b4c45e8 100644 --- a/IPython/html/services/config/manager.py +++ b/IPython/html/services/config/manager.py @@ -8,7 +8,7 @@ from IPython.config.manager import BaseJSONConfigManager class ConfigManager(BaseJSONConfigManager): - """Config Manager used for storing notebook frontend config""" + """Config Manager use for storin Javascript side config""" def _config_dir(self): return os.path.join(self.profile_dir, 'nbconfig') diff --git a/IPython/html/services/contents/filemanager.py b/IPython/html/services/contents/filemanager.py index c502d4816..29ddfde5f 100644 --- a/IPython/html/services/contents/filemanager.py +++ b/IPython/html/services/contents/filemanager.py @@ -348,7 +348,7 @@ def get(self, path, content=True, type=None, format=None): else: if type == 'directory': raise web.HTTPError(400, - u'%s is not a directory' % path, reason='bad type') + u'%s is not a directory', reason='bad type') model = self._file_model(path, content=content, format=format) return model diff --git a/IPython/html/services/sessions/sessionmanager.py b/IPython/html/services/sessions/sessionmanager.py index 967c4b16e..4f05bf172 100644 --- a/IPython/html/services/sessions/sessionmanager.py +++ b/IPython/html/services/sessions/sessionmanager.py @@ -16,7 +16,7 @@ class SessionManager(LoggingConfigurable): kernel_manager = Instance('IPython.html.services.kernels.kernelmanager.MappingKernelManager') - contents_manager = Instance('IPython.html.services.contents.manager.ContentsManager') + contents_manager = Instance('IPython.html.services.contents.manager.ContentsManager', args=()) # Session database initialized below _cursor = None diff --git a/IPython/html/static/style/ipython.min.css b/IPython/html/static/style/ipython.min.css index 20a2c464f..3e160b551 100644 --- a/IPython/html/static/style/ipython.min.css +++ b/IPython/html/static/style/ipython.min.css @@ -1195,6 +1195,10 @@ h6:hover .anchor-link { font-size: 100%; font-style: italic; } +.widget-interact > div, +.widget-interact > input { + padding: 2.5px; +} .widget-area { /* LESS file that styles IPython notebook widgets and the area they sit in. diff --git a/IPython/html/static/style/style.min.css b/IPython/html/static/style/style.min.css index a36c23633..feface624 100644 --- a/IPython/html/static/style/style.min.css +++ b/IPython/html/static/style/style.min.css @@ -9978,6 +9978,10 @@ h6:hover .anchor-link { font-size: 100%; font-style: italic; } +.widget-interact > div, +.widget-interact > input { + padding: 2.5px; +} .widget-area { /* LESS file that styles IPython notebook widgets and the area they sit in. diff --git a/IPython/html/static/widgets/less/widgets.less b/IPython/html/static/widgets/less/widgets.less index 08a920e05..ffe3decf8 100644 --- a/IPython/html/static/widgets/less/widgets.less +++ b/IPython/html/static/widgets/less/widgets.less @@ -1,6 +1,13 @@ @widget-width: 350px; @widget-width-short: 150px; +// Pad interact widgets by default. +.widget-interact { + >div, >input { + padding: 2.5px; + } +} + .widget-area { /* LESS file that styles IPython notebook widgets and the area they sit in. diff --git a/IPython/html/widgets/interaction.py b/IPython/html/widgets/interaction.py index 76d63f524..b9e37defc 100644 --- a/IPython/html/widgets/interaction.py +++ b/IPython/html/widgets/interaction.py @@ -181,7 +181,7 @@ def interactive(__interact_f, **kwargs): co = kwargs.pop('clear_output', True) manual = kwargs.pop('__manual', False) kwargs_widgets = [] - container = Box() + container = Box(_dom_classes=['widget-interact']) container.result = None container.args = [] container.kwargs = dict() diff --git a/IPython/html/widgets/widget.py b/IPython/html/widgets/widget.py index fcb76c0a4..062b6716b 100644 --- a/IPython/html/widgets/widget.py +++ b/IPython/html/widgets/widget.py @@ -435,7 +435,7 @@ class DOMWidget(Widget): width = CUnicode(sync=True) height = CUnicode(sync=True) # A default padding of 2.5 px makes the widgets look nice when displayed inline. - padding = CUnicode("2.5px", sync=True) + padding = CUnicode(sync=True) margin = CUnicode(sync=True) color = Unicode(sync=True) diff --git a/IPython/nbconvert/postprocessors/serve.py b/IPython/nbconvert/postprocessors/serve.py index 09caedd3d..d2383bed4 100644 --- a/IPython/nbconvert/postprocessors/serve.py +++ b/IPython/nbconvert/postprocessors/serve.py @@ -1,9 +1,16 @@ """PostProcessor for serving reveal.js HTML slideshows.""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - from __future__ import print_function +#----------------------------------------------------------------------------- +#Copyright (c) 2013, the IPython Development Team. +# +#Distributed under the terms of the Modified BSD License. +# +#The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- import os import webbrowser @@ -15,6 +22,9 @@ from .base import PostProcessorBase +#----------------------------------------------------------------------------- +# Classes +#----------------------------------------------------------------------------- class ProxyHandler(web.RequestHandler): """handler the proxies requests from a local prefix to a CDN""" @@ -27,15 +37,12 @@ def get(self, prefix, url): def finish_get(self, response): """finish the request""" - # rethrow errors - response.rethrow() - + # copy potentially relevant headers for header in ["Content-Type", "Cache-Control", "Date", "Last-Modified", "Expires"]: if header in response.headers: self.set_header(header, response.headers[header]) self.finish(response.body) - class ServePostProcessor(PostProcessorBase): """Post processor designed to serve files diff --git a/docs/source/parallel/dag_dependencies.rst b/docs/source/parallel/dag_dependencies.rst index a94dd3140..06ba12f76 100644 --- a/docs/source/parallel/dag_dependencies.rst +++ b/docs/source/parallel/dag_dependencies.rst @@ -123,7 +123,7 @@ on which it depends: ...: deps = [ results[n] for n in G.predecessors(node) ] ...: # submit and store AsyncResult object ...: with view.temp_flags(after=deps, block=False): - ...: results[node] = view.apply(jobs[node]) + ...: results[node] = view.apply_with_flags(jobs[node]) Now that we have submitted all the jobs, we can wait for the results: diff --git a/examples/Interactive Widgets/Index.ipynb b/examples/Interactive Widgets/Index.ipynb index d4da12c04..5049b4fd7 100644 --- a/examples/Interactive Widgets/Index.ipynb +++ b/examples/Interactive Widgets/Index.ipynb @@ -42,7 +42,7 @@ "- [Using Interact](Using Interact.ipynb)\n", "- [Widget Basics](Widget Basics.ipynb) \n", "- [Widget Events](Widget Events.ipynb) \n", - "- [Widget List](Widget List.ipynb) \n", + "- [Widget Placement](Widget Placement.ipynb) \n", "- [Widget Styling](Widget Styling.ipynb) \n", "- [Custom Widget](Custom Widget - Hello World.ipynb)" ]
Default DOMWidget Padding should be 0px, and Button styling issue @jdfreder ![padding](https://cloud.githubusercontent.com/assets/2397974/6379572/53fb8cfc-bd01-11e4-9786-f350566688b0.png)
ipython/ipython
diff --git a/IPython/html/services/sessions/tests/test_sessionmanager.py b/IPython/html/services/sessions/tests/test_sessionmanager.py index 78036c961..36980bd6a 100644 --- a/IPython/html/services/sessions/tests/test_sessionmanager.py +++ b/IPython/html/services/sessions/tests/test_sessionmanager.py @@ -6,7 +6,6 @@ from ..sessionmanager import SessionManager from IPython.html.services.kernels.kernelmanager import MappingKernelManager -from IPython.html.services.contents.manager import ContentsManager class DummyKernel(object): def __init__(self, kernel_name='python'): @@ -29,17 +28,10 @@ def start_kernel(self, kernel_id=None, path=None, kernel_name='python', **kwargs def shutdown_kernel(self, kernel_id, now=False): del self._kernels[kernel_id] - class TestSessionManager(TestCase): - def setUp(self): - self.sm = SessionManager( - kernel_manager=DummyMKM(), - contents_manager=ContentsManager(), - ) - def test_get_session(self): - sm = self.sm + sm = SessionManager(kernel_manager=DummyMKM()) session_id = sm.create_session(path='/path/to/test.ipynb', kernel_name='bar')['id'] model = sm.get_session(session_id=session_id) @@ -50,13 +42,13 @@ def test_get_session(self): def test_bad_get_session(self): # Should raise error if a bad key is passed to the database. - sm = self.sm + sm = SessionManager(kernel_manager=DummyMKM()) session_id = sm.create_session(path='/path/to/test.ipynb', kernel_name='foo')['id'] self.assertRaises(TypeError, sm.get_session, bad_id=session_id) # Bad keyword def test_get_session_dead_kernel(self): - sm = self.sm + sm = SessionManager(kernel_manager=DummyMKM()) session = sm.create_session(path='/path/to/1/test1.ipynb', kernel_name='python') # kill the kernel sm.kernel_manager.shutdown_kernel(session['kernel']['id']) @@ -67,7 +59,7 @@ def test_get_session_dead_kernel(self): self.assertEqual(listed, []) def test_list_sessions(self): - sm = self.sm + sm = SessionManager(kernel_manager=DummyMKM()) sessions = [ sm.create_session(path='/path/to/1/test1.ipynb', kernel_name='python'), sm.create_session(path='/path/to/2/test2.ipynb', kernel_name='python'), @@ -92,7 +84,7 @@ def test_list_sessions(self): self.assertEqual(sessions, expected) def test_list_sessions_dead_kernel(self): - sm = self.sm + sm = SessionManager(kernel_manager=DummyMKM()) sessions = [ sm.create_session(path='/path/to/1/test1.ipynb', kernel_name='python'), sm.create_session(path='/path/to/2/test2.ipynb', kernel_name='python'), @@ -115,7 +107,7 @@ def test_list_sessions_dead_kernel(self): self.assertEqual(listed, expected) def test_update_session(self): - sm = self.sm + sm = SessionManager(kernel_manager=DummyMKM()) session_id = sm.create_session(path='/path/to/test.ipynb', kernel_name='julia')['id'] sm.update_session(session_id, path='/path/to/new_name.ipynb') @@ -127,13 +119,13 @@ def test_update_session(self): def test_bad_update_session(self): # try to update a session with a bad keyword ~ raise error - sm = self.sm + sm = SessionManager(kernel_manager=DummyMKM()) session_id = sm.create_session(path='/path/to/test.ipynb', kernel_name='ir')['id'] self.assertRaises(TypeError, sm.update_session, session_id=session_id, bad_kw='test.ipynb') # Bad keyword def test_delete_session(self): - sm = self.sm + sm = SessionManager(kernel_manager=DummyMKM()) sessions = [ sm.create_session(path='/path/to/1/test1.ipynb', kernel_name='python'), sm.create_session(path='/path/to/2/test2.ipynb', kernel_name='python'), @@ -155,7 +147,7 @@ def test_delete_session(self): def test_bad_delete_session(self): # try to delete a session that doesn't exist ~ raise error - sm = self.sm + sm = SessionManager(kernel_manager=DummyMKM()) sm.create_session(path='/path/to/test.ipynb', kernel_name='python') self.assertRaises(TypeError, sm.delete_session, bad_kwarg='23424') # Bad keyword self.assertRaises(web.HTTPError, sm.delete_session, session_id='23424') # nonexistant
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "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": 3, "test_score": 3 }, "num_modified_files": 12 }
2.4
{ "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@cbcf741896140953195ea9cd3de0f10c3f28bef1#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 ptyprocess==0.7.0 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 terminado==0.17.1 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 - ptyprocess==0.7.0 - 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 - terminado==0.17.1 - tornado==6.2 - urllib3==2.0.7 prefix: /opt/conda/envs/ipython
[ "IPython/html/services/sessions/tests/test_sessionmanager.py::TestSessionManager::test_bad_delete_session", "IPython/html/services/sessions/tests/test_sessionmanager.py::TestSessionManager::test_bad_get_session", "IPython/html/services/sessions/tests/test_sessionmanager.py::TestSessionManager::test_bad_update_session", "IPython/html/services/sessions/tests/test_sessionmanager.py::TestSessionManager::test_delete_session", "IPython/html/services/sessions/tests/test_sessionmanager.py::TestSessionManager::test_get_session", "IPython/html/services/sessions/tests/test_sessionmanager.py::TestSessionManager::test_get_session_dead_kernel", "IPython/html/services/sessions/tests/test_sessionmanager.py::TestSessionManager::test_list_sessions", "IPython/html/services/sessions/tests/test_sessionmanager.py::TestSessionManager::test_list_sessions_dead_kernel", "IPython/html/services/sessions/tests/test_sessionmanager.py::TestSessionManager::test_update_session" ]
[]
[]
[]
BSD 3-Clause "New" or "Revised" License
44
[ "IPython/nbconvert/postprocessors/serve.py", "IPython/html/widgets/interaction.py", "IPython/html/services/config/manager.py", "examples/Interactive", "docs/source/parallel/dag_dependencies.rst", "IPython/html/static/style/ipython.min.css", "IPython/html/widgets/widget.py", "examples/Interactive Widgets/Index.ipynb", "IPython/html/services/contents/filemanager.py", "IPython/html/services/sessions/sessionmanager.py", "IPython/html/static/widgets/less/widgets.less", "IPython/config/manager.py", "IPython/html/static/style/style.min.css" ]
[ "IPython/nbconvert/postprocessors/serve.py", "IPython/html/widgets/interaction.py", "IPython/html/services/config/manager.py", "docs/source/parallel/dag_dependencies.rst", "IPython/html/static/style/ipython.min.css", "IPython/html/widgets/widget.py", "examples/Interactive Widgets/Index.ipynb", "IPython/html/services/contents/filemanager.py", "IPython/html/services/sessions/sessionmanager.py", "IPython/html/static/widgets/less/widgets.less", "IPython/config/manager.py", "dgets/Index.ipynb", "IPython/html/static/style/style.min.css" ]
Shopify__shopify_python_api-89
63c4a8dd026a60bce7880eeba792e1aeeaccc471
2015-02-26 16:57:37
c29e0ecbed9de67dd923f980a3ac053922dab75e
gavinballard: The build failures here are the same as those mentioned in PR #86 (issue with `pyactiveresource` and Python v2.7.9).
diff --git a/CHANGELOG b/CHANGELOG index 4301098..00fe323 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,6 +2,7 @@ * Added Checkout resource * Updated to pyactiveresource v2.1.1 which includes a test-related bugfix +* Changed OAuth validation from MD5 to HMAC-SHA256 == Version 2.1.0 diff --git a/shopify/session.py b/shopify/session.py index 9058d55..8741ec4 100644 --- a/shopify/session.py +++ b/shopify/session.py @@ -1,8 +1,6 @@ import time -try: - from hashlib import md5 -except ImportError: - from md5 import md5 +import hmac +from hashlib import sha256 try: import simplejson as json except ImportError: @@ -53,7 +51,7 @@ class Session(object): return self.token if not self.validate_params(params): - raise ValidationException('Invalid Signature: Possibly malicious login') + raise ValidationException('Invalid HMAC: Possibly malicious login') code = params['code'] @@ -94,18 +92,30 @@ class Session(object): if int(params['timestamp']) < time.time() - one_day: return False - return cls.validate_signature(params) + return cls.validate_hmac(params) @classmethod - def validate_signature(cls, params): - if "signature" not in params: + def validate_hmac(cls, params): + if 'hmac' not in params: return False - sorted_params = "" - signature = params['signature'] + hmac_calculated = cls.calculate_hmac(params) + hmac_to_verify = params['hmac'] - for k in sorted(params.keys()): - if k != "signature": - sorted_params += k + "=" + str(params[k]) + # Try to use compare_digest() to reduce vulnerability to timing attacks. + # If it's not available, just fall back to regular string comparison. + try: + return hmac.compare_digest(hmac_calculated, hmac_to_verify) + except AttributeError: + return hmac_calculated == hmac_to_verify - return md5((cls.secret + sorted_params).encode('utf-8')).hexdigest() == signature + @classmethod + def calculate_hmac(cls, params): + """ + Calculate the HMAC of the given parameters in line with Shopify's rules for OAuth authentication. + See http://docs.shopify.com/api/authentication/oauth#verification. + """ + # Sort and combine query parameters into a single string, excluding those that should be removed and joining with '&'. + sorted_params = '&'.join(['{0}={1}'.format(k, params[k]) for k in sorted(params.keys()) if k not in ['signature', 'hmac']]) + # Generate the hex digest for the sorted parameters using the secret. + return hmac.new(cls.secret.encode(), sorted_params.encode(), sha256).hexdigest()
Update MD5 Signature validation to HMAC Docs say that MD5 signature validation 'To be removed after June 1st, 2015' It appears ```Session``` is still doing it this way vs HMAC
Shopify/shopify_python_api
diff --git a/test/session_test.py b/test/session_test.py index c8c1643..c85eb4b 100644 --- a/test/session_test.py +++ b/test/session_test.py @@ -113,24 +113,54 @@ class SessionTest(TestCase): session = shopify.Session("testshop.myshopify.com", "any-token") self.assertEqual("https://testshop.myshopify.com/admin", session.site) - def test_return_token_if_signature_is_valid(self): + def test_hmac_calculation(self): + # Test using the secret and parameter examples given in the Shopify API documentation. + shopify.Session.secret='hush' + params = { + 'shop': 'some-shop.myshopify.com', + 'code': 'a94a110d86d2452eb3e2af4cfb8a3828', + 'timestamp': '1337178173', + 'signature': '6e39a2ea9e497af6cb806720da1f1bf3', + 'hmac': '2cb1a277650a659f1b11e92a4a64275b128e037f2c3390e3c8fd2d8721dac9e2', + } + self.assertEqual(shopify.Session.calculate_hmac(params), params['hmac']) + + def test_return_token_if_hmac_is_valid(self): shopify.Session.secret='secret' params = {'code': 'any-code', 'timestamp': time.time()} - sorted_params = self.make_sorted_params(params) - signature = md5((shopify.Session.secret + sorted_params).encode('utf-8')).hexdigest() - params['signature'] = signature + hmac = shopify.Session.calculate_hmac(params) + params['hmac'] = hmac self.fake(None, url='https://localhost.myshopify.com/admin/oauth/access_token', method='POST', body='{"access_token" : "token"}', has_user_agent=False) session = shopify.Session('http://localhost.myshopify.com') token = session.request_token(params) self.assertEqual("token", token) - def test_raise_error_if_signature_does_not_match_expected(self): + def test_return_token_if_hmac_is_valid_but_signature_also_provided(self): + shopify.Session.secret='secret' + params = {'code': 'any-code', 'timestamp': time.time(), 'signature': '6e39a2'} + hmac = shopify.Session.calculate_hmac(params) + params['hmac'] = hmac + + self.fake(None, url='https://localhost.myshopify.com/admin/oauth/access_token', method='POST', body='{"access_token" : "token"}', has_user_agent=False) + session = shopify.Session('http://localhost.myshopify.com') + token = session.request_token(params) + self.assertEqual("token", token) + + def test_raise_error_if_hmac_is_invalid(self): + shopify.Session.secret='secret' + params = {'code': 'any-code', 'timestamp': time.time()} + params['hmac'] = 'a94a110d86d2452e92a4a64275b128e9273be3037f2c339eb3e2af4cfb8a3828' + + with self.assertRaises(shopify.ValidationException): + session = shopify.Session('http://localhost.myshopify.com') + session = session.request_token(params) + + def test_raise_error_if_hmac_does_not_match_expected(self): shopify.Session.secret='secret' params = {'foo': 'hello', 'timestamp': time.time()} - sorted_params = self.make_sorted_params(params) - signature = md5((shopify.Session.secret + sorted_params).encode('utf-8')).hexdigest() - params['signature'] = signature + hmac = shopify.Session.calculate_hmac(params) + params['hmac'] = hmac params['bar'] = 'world' params['code'] = 'code' @@ -142,22 +172,13 @@ class SessionTest(TestCase): shopify.Session.secret='secret' one_day = 24 * 60 * 60 params = {'code': 'any-code', 'timestamp': time.time()-(2*one_day)} - sorted_params = self.make_sorted_params(params) - signature = md5((shopify.Session.secret + sorted_params).encode('utf-8')).hexdigest() - params['signature'] = signature + hmac = shopify.Session.calculate_hmac(params) + params['hmac'] = hmac with self.assertRaises(shopify.ValidationException): session = shopify.Session('http://localhost.myshopify.com') session = session.request_token(params) - - def make_sorted_params(self, params): - sorted_params = "" - for k in sorted(params.keys()): - if k != "signature": - sorted_params += k + "=" + str(params[k]) - return sorted_params - def normalize_url(self, url): scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url) query = "&".join(sorted(query.split("&")))
{ "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": 2, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
2.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": [ "mock>=1.0.1", "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 mock==5.2.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@63c4a8dd026a60bce7880eeba792e1aeeaccc471#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 - mock==5.2.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/session_test.py::SessionTest::test_hmac_calculation", "test/session_test.py::SessionTest::test_raise_error_if_hmac_does_not_match_expected", "test/session_test.py::SessionTest::test_raise_error_if_timestamp_is_too_old", "test/session_test.py::SessionTest::test_return_token_if_hmac_is_valid", "test/session_test.py::SessionTest::test_return_token_if_hmac_is_valid_but_signature_also_provided" ]
[]
[ "test/session_test.py::SessionTest::test_be_valid_with_any_token_and_any_url", "test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_dual_scope_no_redirect_uri", "test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_no_scope_no_redirect_uri", "test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_single_scope_and_redirect_uri", "test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_single_scope_no_redirect_uri", "test/session_test.py::SessionTest::test_not_be_valid_without_a_url", "test/session_test.py::SessionTest::test_not_be_valid_without_token", "test/session_test.py::SessionTest::test_not_raise_error_without_params", "test/session_test.py::SessionTest::test_raise_error_if_hmac_is_invalid", "test/session_test.py::SessionTest::test_raise_error_if_params_passed_but_signature_omitted", "test/session_test.py::SessionTest::test_raise_exception_if_code_invalid_in_request_token", "test/session_test.py::SessionTest::test_return_site_for_session", "test/session_test.py::SessionTest::test_setup_api_key_and_secret_for_all_sessions", "test/session_test.py::SessionTest::test_temp_reset_shopify_ShopifyResource_site_to_original_value", "test/session_test.py::SessionTest::test_temp_reset_shopify_ShopifyResource_site_to_original_value_when_using_a_non_standard_port", "test/session_test.py::SessionTest::test_temp_works_without_currently_active_session", "test/session_test.py::SessionTest::test_use_https_protocol_by_default_for_all_sessions" ]
[]
MIT License
45
[ "CHANGELOG", "shopify/session.py" ]
[ "CHANGELOG", "shopify/session.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
[ "setup.py", "pre_commit_hooks/autopep8_wrapper.py" ]
[ "setup.py", "pre_commit_hooks/autopep8_wrapper.py" ]
jacebrowning__yorm-52
59a6372eb90fe702863c3e231dffc1ed367b7613
2015-03-01 01:11:13
59a6372eb90fe702863c3e231dffc1ed367b7613
diff --git a/CHANGES.md b/CHANGES.md index 6116a4c..9653aeb 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,11 @@ Changelog ========= +0.3 (dev) +--------- + +- Updated mapped objects to only read from the filesystem if there are changes. + 0.2.1 (2015-2-12) ----------------- diff --git a/yorm/__init__.py b/yorm/__init__.py index b2e342a..967c38f 100644 --- a/yorm/__init__.py +++ b/yorm/__init__.py @@ -3,7 +3,7 @@ import sys __project__ = 'YORM' -__version__ = '0.2.1' +__version__ = '0.3dev' VERSION = __project__ + '-' + __version__ diff --git a/yorm/base.py b/yorm/base.py index 79cc2c0..14929e5 100644 --- a/yorm/base.py +++ b/yorm/base.py @@ -18,11 +18,11 @@ class Mappable(metaclass=abc.ABCMeta): # pylint:disable=R0921 try: value = object.__getattribute__(self, name) except AttributeError: - self.yorm_mapper.retrieve(self) + self.yorm_mapper.retrieve(self, self.yorm_attrs) value = object.__getattribute__(self, name) else: if name in self.yorm_attrs: - self.yorm_mapper.retrieve(self) + self.yorm_mapper.retrieve(self, self.yorm_attrs) value = object.__getattribute__(self, name) return value @@ -36,7 +36,7 @@ class Mappable(metaclass=abc.ABCMeta): # pylint:disable=R0921 if hasattr(self, 'yorm_attrs') and name in self.yorm_attrs: if hasattr(self, 'yorm_mapper') and self.yorm_mapper.auto: - self.yorm_mapper.store(self) + self.yorm_mapper.store(self, self.yorm_attrs) else: log.trace("automatic storage is off") @@ -46,7 +46,7 @@ class Mappable(metaclass=abc.ABCMeta): # pylint:disable=R0921 def __exit__(self, *_): log.debug("turning on automatic storage...") - self.yorm_mapper.store(self) + self.yorm_mapper.store(self, self.yorm_attrs) class Converter(metaclass=abc.ABCMeta): # pylint:disable=R0921 diff --git a/yorm/common.py b/yorm/common.py index 0771870..b8f7024 100644 --- a/yorm/common.py +++ b/yorm/common.py @@ -144,6 +144,11 @@ def touch(path): write_text('', path) +def stamp(path): + """Get the modification timestamp from a file.""" + return os.path.getmtime(path) + + def delete(path): """Delete a file or directory with error handling.""" if os.path.isdir(path): diff --git a/yorm/mapper.py b/yorm/mapper.py index 9917c1a..53fcf1f 100644 --- a/yorm/mapper.py +++ b/yorm/mapper.py @@ -49,60 +49,68 @@ class Mapper: def __init__(self, path): self.path = path self.auto = False - self.exists = True - self.retrieving = False - self.storing = False - # TODO: replace this variable with a timeout or modification check - self.retrieved = False + self.exists = os.path.isfile(self.path) + self._retrieving = False + self._storing = False + self._timestamp = 0 def __str__(self): return str(self.path) + @property + def _fake(self): # pylint: disable=R0201 + """Get a string indicating the fake setting to use in logging.""" + return "(fake) " if settings.fake else '' + def create(self, obj): """Create a new file for the object.""" - log.critical((self.path, obj)) - if self._fake or not os.path.isfile(self.path): - log.info("mapping %r to %s'%s'...", obj, self._fake, self) - if not self._fake: - common.create_dirname(self.path) - common.touch(self.path) + log.info("creating %s'%s' for %r...", self._fake, self, obj) + if self.exists: + log.warning("already created: %s", self) + return + if not self._fake: + common.create_dirname(self.path) + common.touch(self.path) + self.modified = False self.exists = True @readwrite - def retrieve(self, obj): - """Load the object's properties from its file.""" - if self.storing: + def retrieve(self, obj, attrs): + """Load the object's mapped attributes from its file.""" + if self._storing: + return + if not self.modified: return - self.retrieving = True + self._retrieving = True log.debug("retrieving %r from %s'%s'...", obj, self._fake, self.path) # Parse data from file if self._fake: text = getattr(obj, 'yorm_fake', "") else: - text = self.read() - data = self.load(text, self.path) + text = self._read() + data = self._load(text, self.path) log.trace("loaded: {}".format(data)) # Update attributes for name, data in data.items(): try: - converter = obj.yorm_attrs[name] + converter = attrs[name] except KeyError: # TODO: determine if this runtime import is the best way to do this from . import standard converter = standard.match(name, data) - obj.yorm_attrs[name] = converter + attrs[name] = converter value = converter.to_value(data) log.trace("value retrieved: '{}' = {}".format(name, repr(value))) setattr(obj, name, value) # Set meta attributes - self.retrieving = False - self.retrieved = True + self.modified = False + self._retrieving = False @readwrite - def read(self): + def _read(self): """Read text from the object's file. :param path: path to a text file @@ -113,7 +121,7 @@ class Mapper: return common.read_text(self.path) @staticmethod - def load(text, path): + def _load(text, path): """Load YAML data from text. :param text: text read from a file @@ -125,16 +133,16 @@ class Mapper: return common.load_yaml(text, path) @readwrite - def store(self, obj): - """Format and save the object's properties to its file.""" - if self.retrieving: + def store(self, obj, attrs): + """Format and save the object's mapped attributes to its file.""" + if self._retrieving: return - self.storing = True + self._storing = True log.debug("storing %r to %s'%s'...", obj, self._fake, self.path) # Format the data items data = {} - for name, converter in obj.yorm_attrs.items(): + for name, converter in attrs.items(): try: value = getattr(obj, name) except AttributeError as exc: @@ -145,17 +153,18 @@ class Mapper: data[name] = data2 # Dump data to file - text = self.dump(data) + text = self._dump(data) if self._fake: obj.yorm_fake = text else: - self.write(text) + self._write(text) # Set meta attributes - self.storing = False + self.modified = False + self._storing = False @staticmethod - def dump(data): + def _dump(data): """Dump YAML data to text. :param data: dictionary of YAML data @@ -166,7 +175,7 @@ class Mapper: return yaml.dump(data, default_flow_style=False, allow_unicode=True) @readwrite - def write(self, text): + def _write(self, text): """Write text to the object's file. :param text: text to write to a file @@ -175,18 +184,42 @@ class Mapper: """ common.write_text(text, self.path) + @property + def modified(self): + """Determine if the file has been modified.""" + if self._fake: + log.trace("file is modified (it is fake)") + return True + elif not self.exists: + log.trace("file is modified (it is deleted)") + return True + else: + was = self._timestamp + now = common.stamp(self.path) + log.trace("file is %smodified (%s -> %s)", + "not " if was == now else "", + was, now) + return was != now + + @modified.setter + def modified(self, changes): + """Mark the file as modified if there are changes.""" + if changes: + log.trace("marked %sfile as modified", self._fake) + self._timestamp = 0 + else: + if self._fake: + self._timestamp = None + else: + self._timestamp = common.stamp(self.path) + log.trace("marked %sfile as not modified", self._fake) + def delete(self): """Delete the object's file from the file system.""" if self.exists: log.info("deleting %s'%s'...", self._fake, self.path) if not self._fake: common.delete(self.path) - self.retrieved = False self.exists = False else: log.warning("already deleted: %s", self) - - @property - def _fake(self): # pylint: disable=R0201 - """Return a string indicating the fake setting to use in logging.""" - return "(fake) " if settings.fake else '' diff --git a/yorm/utilities.py b/yorm/utilities.py index 1a51f75..403e15f 100644 --- a/yorm/utilities.py +++ b/yorm/utilities.py @@ -1,6 +1,5 @@ """Functions and decorators.""" -import os import uuid from . import common @@ -36,12 +35,12 @@ def store(instance, path, mapping=None, auto=True): instance.yorm_path = path instance.yorm_mapper = Mapper(instance.yorm_path) - if not os.path.exists(instance.yorm_path): + if not instance.yorm_mapper.exists: instance.yorm_mapper.create(instance) if auto: - instance.yorm_mapper.store(instance) + instance.yorm_mapper.store(instance, instance.yorm_attrs) else: - instance.yorm_mapper.retrieve(instance) + instance.yorm_mapper.retrieve(instance, instance.yorm_attrs) instance.yorm_mapper.auto = auto @@ -84,12 +83,12 @@ def store_instances(path_format, format_spec=None, mapping=None, auto=True): self.yorm_path = path_format.format(**format_spec2) self.yorm_mapper = Mapper(self.yorm_path) - if not os.path.exists(self.yorm_path): + if not self.yorm_mapper.exists: self.yorm_mapper.create(self) if auto: - self.yorm_mapper.store(self) + self.yorm_mapper.store(self, self.yorm_attrs) else: - self.yorm_mapper.retrieve(self) + self.yorm_mapper.retrieve(self, self.yorm_attrs) self.yorm_mapper.auto = auto
Reload the file only after a configurable timeout has occurred Or, only read from the file if it **has** actually changed. <bountysource-plugin> --- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/4360121-reload-the-file-only-after-a-configurable-timeout-has-occurred?utm_campaign=plugin&utm_content=tracker%2F1536163&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F1536163&utm_medium=issues&utm_source=github). </bountysource-plugin>
jacebrowning/yorm
diff --git a/yorm/test/test_all.py b/yorm/test/test_all.py index ea57b45..0d60905 100644 --- a/yorm/test/test_all.py +++ b/yorm/test/test_all.py @@ -3,6 +3,9 @@ """Integration tests for the `yorm` package.""" +import time +import logging + import pytest from yorm import store, store_instances, map_attr, Converter @@ -134,7 +137,7 @@ class SampleStandardDecorated: @store_instances("sample.yml", auto=False) class SampleDecoratedNoAuto: - """Sample class with automatic storate turned off.""" + """Sample class with automatic storage turned off.""" def __init__(self): self.string = "" @@ -193,6 +196,13 @@ class SampleCustomDecorated: # tests ####################################################################### +def refresh_file_modification_times(seconds=1.1): + """Sleep to allow file modification times to refresh.""" + logging.info("delaying for %s second%s...", seconds, + "" if seconds == 1 else "s") + time.sleep(seconds) + + def test_imports(): """Verify the package namespace is mapped correctly.""" # pylint: disable=W0404,W0612,W0621 @@ -260,6 +270,7 @@ class TestStandard: """.strip().replace(" ", "") + '\n' == text # change file values + refresh_file_modification_times() text = """ array: [4, 5, 6] 'false': null @@ -297,7 +308,7 @@ class TestStandard: assert "path/to/directory/sample.yml" == sample.yorm_path # check defaults - assert {'key': ''} == sample.object + assert {} == sample.object assert [] == sample.array assert "" == sample.string assert 0 == sample.number_int @@ -374,7 +385,7 @@ class TestStandard: assert "" == text # store value - sample.yorm_mapper.store(sample) + sample.yorm_mapper.store(sample, sample.yorm_attrs) sample.yorm_mapper.auto = True # check for changed file values @@ -447,6 +458,7 @@ class TestContainers: """.strip().replace(" ", "") + '\n' == text # change file values + refresh_file_modification_times() text = """ count: 3 other: 4.2 @@ -472,6 +484,7 @@ class TestContainers: sample = SampleEmptyDecorated() # change file values + refresh_file_modification_times() text = """ object: {'key': 'value'} array: [1, '2', '3.0'] @@ -479,8 +492,8 @@ class TestContainers: with open(sample.yorm_path, 'w') as stream: stream.write(text) - # (a mapped attribute must be read first to trigger retrieving) - sample.yorm_mapper.retrieve(sample) + # (a mapped attribute must be read first to trigger retrieving) + sample.yorm_mapper.retrieve(sample, sample.yorm_attrs) # check object values assert {'key': 'value'} == sample.object @@ -519,6 +532,7 @@ class TestExtended: assert "" == sample.text # change object values + refresh_file_modification_times() sample.text = """ This is the first sentence. This is the second sentence. This is the third sentence. @@ -535,6 +549,7 @@ class TestExtended: """.strip().replace(" ", "") + '\n' == text # change file values + refresh_file_modification_times() text = """ text: | This is a @@ -571,6 +586,7 @@ class TestCustom: """.strip().replace(" ", "") + '\n' == text # change file values + refresh_file_modification_times() text = """ level: 1 """.strip().replace(" ", "") + '\n' @@ -593,7 +609,9 @@ class TestInit: sample2 = SampleStandardDecorated('sample') assert sample2.yorm_path == sample.yorm_path - # change object values + refresh_file_modification_times() + + logging.info("changing values in object 1...") sample.object = {'key2': 'value'} sample.array = [0, 1, 2] sample.string = "Hello, world!" @@ -602,8 +620,8 @@ class TestInit: sample.true = True sample.false = False - # check object values - assert {'key2': 'value', 'status': False} == sample2.object + logging.info("reading changed values in object 2...") + assert 'value' == sample2.object.get('key2') assert [0, 1, 2] == sample2.array assert "Hello, world!" == sample2.string assert 42 == sample2.number_int diff --git a/yorm/test/test_base.py b/yorm/test/test_base.py index 1b2d03f..2692b81 100644 --- a/yorm/test/test_base.py +++ b/yorm/test/test_base.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# pylint:disable=W0201,W0613,R0201 +# pylint:disable=W0201,W0613,R0201,W0212 """Unit tests for the `base` module.""" @@ -18,15 +18,26 @@ class MockMapper(Mapper): def __init__(self, path): super().__init__(path) self._mock_file = None + self._mock_modified = True + self.exists = True - def read(self): + def _read(self): text = self._mock_file logging.debug("mock read:\n%s", text.strip()) return text - def write(self, text): + def _write(self, text): logging.debug("mock write:\n%s", text.strip()) self._mock_file = text + self.modified = True + + @property + def modified(self): + return self._mock_modified + + @modified.setter + def modified(self, changes): # pylint: disable=W0221 + self._mock_modified = changes # sample classes ############################################################## @@ -48,7 +59,7 @@ class SampleMappable(Mappable): 'var2': Integer, 'var3': Boolean} self.yorm_mapper = MockMapper(self.yorm_path) - self.yorm_mapper.store(self) + self.yorm_mapper.store(self, self.yorm_attrs) self.yorm_mapper.auto = True def __repr__(self): @@ -68,7 +79,7 @@ class TestMappable: def test_init(self): """Verify files are created after initialized.""" - text = self.sample.yorm_mapper.read() + text = self.sample.yorm_mapper._read() assert """ var1: '' var2: 0 @@ -80,7 +91,7 @@ class TestMappable: self.sample.var1 = "abc123" self.sample.var2 = 1 self.sample.var3 = True - text = self.sample.yorm_mapper.read() + text = self.sample.yorm_mapper._read() assert """ var1: abc123 var2: 1 @@ -92,7 +103,7 @@ class TestMappable: self.sample.var1 = 42 self.sample.var2 = "1" self.sample.var3 = 'off' - text = self.sample.yorm_mapper.read() + text = self.sample.yorm_mapper._read() assert """ var1: '42' var2: 1 @@ -111,7 +122,7 @@ class TestMappable: var2: 42 var3: off """.strip().replace(" ", "") + '\n' - self.sample.yorm_mapper.write(text) + self.sample.yorm_mapper._write(text) assert"def456" == self.sample.var1 assert 42 == self.sample.var2 assert False is self.sample.var3 @@ -121,7 +132,7 @@ class TestMappable: text = """ invalid: - """.strip().replace(" ", "") + '\n' - self.sample.yorm_mapper.write(text) + self.sample.yorm_mapper._write(text) with pytest.raises(ValueError): print(self.sample.var1) @@ -130,7 +141,7 @@ class TestMappable: text = """ not a dictionary """.strip().replace(" ", "") + '\n' - self.sample.yorm_mapper.write(text) + self.sample.yorm_mapper._write(text) with pytest.raises(ValueError): print(self.sample.var1) @@ -139,14 +150,14 @@ class TestMappable: with self.sample: self.sample.var1 = "abc123" - text = self.sample.yorm_mapper.read() + text = self.sample.yorm_mapper._read() assert """ var1: '' var2: 0 var3: false """.strip().replace(" ", "") + '\n' == text - text = self.sample.yorm_mapper.read() + text = self.sample.yorm_mapper._read() assert """ var1: abc123 var2: 0 @@ -158,7 +169,7 @@ class TestMappable: text = """ new: 42 """.strip().replace(" ", "") + '\n' - self.sample.yorm_mapper.write(text) + self.sample.yorm_mapper._write(text) assert 42 == self.sample.new def test_new_unknown(self): @@ -166,7 +177,7 @@ class TestMappable: text = """ new: !!timestamp 2001-12-15T02:59:43.1Z """.strip().replace(" ", "") + '\n' - self.sample.yorm_mapper.write(text) + self.sample.yorm_mapper._write(text) with pytest.raises(ValueError): print(self.sample.var1) diff --git a/yorm/test/test_mapper.py b/yorm/test/test_mapper.py index d86b193..6592461 100644 --- a/yorm/test/test_mapper.py +++ b/yorm/test/test_mapper.py @@ -30,6 +30,17 @@ class TestFake: assert not os.path.exists(mapped.path) + def test_modified(self): + """Verify a fake file is always modified.""" + mapped = mapper.Mapper("fake/path/to/file") + mapped.create(None) + + assert mapped.modified + + mapped.modified = False + + assert mapped.modified + class TestReal: @@ -43,14 +54,14 @@ class TestReal: assert os.path.isfile(mapped.path) - def test_create_exists(self, tmpdir): - """Verify files are only created if they don't exist.""" + def test_create_twice(self, tmpdir): + """Verify the second creation is ignored.""" tmpdir.chdir() mapped = mapper.Mapper("real/path/to/file") - with patch('os.path.isfile', Mock(return_value=True)): - mapped.create(None) + mapped.create(None) + mapped.create(None) - assert not os.path.isfile(mapped.path) + assert os.path.isfile(mapped.path) def test_delete(self, tmpdir): """Verify files can be deleted.""" @@ -61,6 +72,32 @@ class TestReal: assert not os.path.exists(mapped.path) + def test_delete_twice(self, tmpdir): + """Verify the second deletion is ignored.""" + tmpdir.chdir() + mapped = mapper.Mapper("real/path/to/file") + mapped.delete() + + assert not os.path.exists(mapped.path) + + def test_modified(self, tmpdir): + """Verify files track modifications.""" + tmpdir.chdir() + mapped = mapper.Mapper("real/path/to/file") + mapped.create(None) + + assert not mapped.modified + + mapped.modified = True + + assert mapped.modified + + def test_modified_deleted(self): + """Verify a deleted file is always modified.""" + mapped = mapper.Mapper("fake/path/to/file") + + assert mapped.modified + if __name__ == '__main__': pytest.main() diff --git a/yorm/test/test_utilities.py b/yorm/test/test_utilities.py index 6b6d91d..90fe6d2 100644 --- a/yorm/test/test_utilities.py +++ b/yorm/test/test_utilities.py @@ -56,6 +56,7 @@ class MockConverter4(MockConverter): @patch('yorm.common.write_text', Mock()) +@patch('yorm.common.stamp', Mock()) class TestStore: """Unit tests for the `store` function.""" @@ -83,7 +84,7 @@ class TestStore: with pytest.raises(common.UseageError): utilities.store(sample, "sample.yml") - @patch('os.path.exists', Mock(return_value=True)) + @patch('os.path.isfile', Mock(return_value=True)) @patch('yorm.common.read_text', Mock(return_value="abc: 123")) def test_init_existing(self): """Verify an existing file is read.""" @@ -97,7 +98,7 @@ class TestStore: with patch.object(sample, 'yorm_mapper') as mock_yorm_mapper: setattr(sample, 'var1', None) mock_yorm_mapper.retrieve.assert_never_called() - mock_yorm_mapper.store.assert_called_once_with(sample) + mock_yorm_mapper.store.assert_called_once_with(sample, mapping) def test_retrieve(self): """Verify retrieve is called when getting an attribute.""" @@ -105,12 +106,13 @@ class TestStore: sample = utilities.store(self.Sample(), "sample.yml", mapping) with patch.object(sample, 'yorm_mapper') as mock_yorm_mapper: getattr(sample, 'var1', None) - mock_yorm_mapper.retrieve.assert_called_once_with(sample) + mock_yorm_mapper.retrieve.assert_called_once_with(sample, mapping) mock_yorm_mapper.store.assert_never_called() @patch('yorm.common.create_dirname', Mock()) @patch('yorm.common.write_text', Mock()) +@patch('yorm.common.stamp', Mock()) class TestStoreInstances: """Unit tests for the `store_instances` decorator.""" @@ -120,11 +122,17 @@ class TestStoreInstances: """Sample decorated class using a single path.""" + def __repr__(self): + return "<decorated {}>".format(id(self)) + @utilities.store_instances("{UUID}.yml") class SampleDecoratedIdentifiers: """Sample decorated class using UUIDs for paths.""" + def __repr__(self): + return "<decorated w/ UUID {}>".format(id(self)) + @utilities.store_instances("path/to/{n}.yml", {'n': 'name'}) class SampleDecoratedAttributes: @@ -133,6 +141,9 @@ class TestStoreInstances: def __init__(self, name): self.name = name + def __repr__(self): + return "<decorated w/ specified attributes {}>".format(id(self)) + @utilities.store_instances("path/to/{self.name}.yml") class SampleDecoratedAttributesAutomatic: @@ -141,6 +152,9 @@ class TestStoreInstances: def __init__(self, name): self.name = name + def __repr__(self): + return "<decorated w/ automatic attributes {}>".format(id(self)) + @utilities.store_instances("{self.a}/{self.b}/{c}.yml", {'self.b': 'b', 'c': 'c'}) class SampleDecoratedAttributesCombination: @@ -152,6 +166,9 @@ class TestStoreInstances: self.b = b self.c = c + def __repr__(self): + return "<decorated w/ attributes {}>".format(id(self)) + @utilities.store_instances("sample.yml", mapping={'var1': MockConverter}) class SampleDecoratedWithAttributes: @@ -169,7 +186,7 @@ class TestStoreInstances: assert "sample.yml" == sample.yorm_path assert ['var1'] == list(sample.yorm_attrs.keys()) - @patch('os.path.exists', Mock(return_value=True)) + @patch('os.path.isfile', Mock(return_value=True)) @patch('yorm.common.read_text', Mock(return_value="abc: 123")) def test_init_existing(self): """Verify an existing file is read.""" @@ -210,18 +227,21 @@ class TestStoreInstances: with patch.object(sample, 'yorm_mapper') as mock_yorm_mapper: setattr(sample, 'var1', None) mock_yorm_mapper.retrieve.assert_never_called() - mock_yorm_mapper.store.assert_called_once_with(sample) + mock_yorm_mapper.store.assert_called_once_with(sample, + sample.yorm_attrs) def test_retrieve(self): """Verify retrieve is called when getting an attribute.""" sample = self.SampleDecoratedWithAttributes() with patch.object(sample, 'yorm_mapper') as mock_yorm_mapper: getattr(sample, 'var1', None) - mock_yorm_mapper.retrieve.assert_called_once_with(sample) + mock_yorm_mapper.retrieve.assert_called_once_with(sample, + sample.yorm_attrs) mock_yorm_mapper.store.assert_never_called() @patch('yorm.common.write_text', Mock()) +@patch('yorm.common.stamp', Mock()) class TestMapAttr: """Unit tests for the `map_attr` decorator."""
{ "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": 2, "test_score": 3 }, "num_modified_files": 6 }
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": [ "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" }
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 PyYAML==3.13 tomli==2.2.1 -e git+https://github.com/jacebrowning/yorm.git@59a6372eb90fe702863c3e231dffc1ed367b7613#egg=YORM
name: yorm 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 - pyyaml==3.13 - tomli==2.2.1 prefix: /opt/conda/envs/yorm
[ "yorm/test/test_base.py::TestMappable::test_init", "yorm/test/test_base.py::TestMappable::test_set", "yorm/test/test_base.py::TestMappable::test_set_converted", "yorm/test/test_base.py::TestMappable::test_set_error", "yorm/test/test_base.py::TestMappable::test_get", "yorm/test/test_base.py::TestMappable::test_error_invalid_yaml", "yorm/test/test_base.py::TestMappable::test_error_unexpected_yaml", "yorm/test/test_base.py::TestMappable::test_context_manager", "yorm/test/test_base.py::TestMappable::test_new", "yorm/test/test_base.py::TestMappable::test_new_unknown", "yorm/test/test_mapper.py::TestFake::test_modified", "yorm/test/test_mapper.py::TestReal::test_modified", "yorm/test/test_mapper.py::TestReal::test_modified_deleted", "yorm/test/test_utilities.py::TestStore::test_no_attrs", "yorm/test/test_utilities.py::TestStore::test_with_attrs", "yorm/test/test_utilities.py::TestStore::test_multiple", "yorm/test/test_utilities.py::TestStore::test_init_existing", "yorm/test/test_utilities.py::TestStoreInstances::test_no_attrs", "yorm/test/test_utilities.py::TestStoreInstances::test_with_attrs", "yorm/test/test_utilities.py::TestStoreInstances::test_init_existing", "yorm/test/test_utilities.py::TestStoreInstances::test_filename_uuid", "yorm/test/test_utilities.py::TestStoreInstances::test_filename_attributes", "yorm/test/test_utilities.py::TestStoreInstances::test_filename_attributes_automatic", "yorm/test/test_utilities.py::TestStoreInstances::test_filename_attributes_combination", "yorm/test/test_utilities.py::TestMapAttr::test_single", "yorm/test/test_utilities.py::TestMapAttr::test_multiple", "yorm/test/test_utilities.py::TestMapAttr::test_combo", "yorm/test/test_utilities.py::TestMapAttr::test_backwards" ]
[ "yorm/test/test_utilities.py::TestStore::test_store", "yorm/test/test_utilities.py::TestStore::test_retrieve", "yorm/test/test_utilities.py::TestStoreInstances::test_store", "yorm/test/test_utilities.py::TestStoreInstances::test_retrieve" ]
[ "yorm/test/test_all.py::test_imports", "yorm/test/test_base.py::TestConverter::test_not_implemented", "yorm/test/test_mapper.py::TestFake::test_create", "yorm/test/test_mapper.py::TestFake::test_delete", "yorm/test/test_mapper.py::TestReal::test_create", "yorm/test/test_mapper.py::TestReal::test_create_twice", "yorm/test/test_mapper.py::TestReal::test_delete", "yorm/test/test_mapper.py::TestReal::test_delete_twice" ]
[]
MIT License
49
[ "yorm/utilities.py", "CHANGES.md", "yorm/common.py", "yorm/base.py", "yorm/__init__.py", "yorm/mapper.py" ]
[ "yorm/utilities.py", "CHANGES.md", "yorm/common.py", "yorm/base.py", "yorm/__init__.py", "yorm/mapper.py" ]
crccheck__postdoc-17
4080450041ae86b295a2e1f8aea2018bf5e4b32a
2015-03-02 04:21:22
4080450041ae86b295a2e1f8aea2018bf5e4b32a
diff --git a/README.rst b/README.rst index 599ed6e..c4e5cb4 100644 --- a/README.rst +++ b/README.rst @@ -49,7 +49,9 @@ You can do MySQL stuff too:: If your database url isn't `DATABASE_URL`, you can connect to it by making it the first argument:: + $ export FATTYBASE_URL=postgres://fatty@fat/phat $ phd FATTYBASE_URL psql + psql -U fatty -h fat phat Installation @@ -60,7 +62,18 @@ Install with pip:: pip install postdoc +Extras +------ +Add the flag `--postdoc-dry-run` to just print the command. + +Add the flag `--postdoc-quiet` to execute the command without printing the +debugging line. + +Aliases:: + + alias dphd="phd --postdoc-dry-run" + alias qphd="phd --postdoc-quiet" diff --git a/postdoc.py b/postdoc.py index f1f20fb..4a40e16 100755 --- a/postdoc.py +++ b/postdoc.py @@ -1,5 +1,15 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Usage: phd COMMAND [options] [command options] + + COMMAND A command like psql, createdb, dropdb + +Options: + + --postdoc-dry-run Print output and then exit. + --postdoc-quiet Don't print debugging output. +""" import os import subprocess @@ -103,22 +113,18 @@ def get_command(command, meta): return bits -def main(): - if '--version' in sys.argv: - exit('PostDoc {0}'.format(__version__)) - if '--help' in sys.argv or len(sys.argv) < 2: - exit('Usage: phd COMMAND [additional-options]\n\n' - ' ERROR: Must give a COMMAND like psql, createdb, dropdb') - # if sys.argv[1] not in VALID_COMMANDS: +def make_tokens_and_env(sys_argv): + """Get the tokens or quit with help.""" + # if sys_argv[1] not in VALID_COMMANDS: # exit('Usage: phd COMMAND [additional-options]\n\n' - # ' ERROR: "%s" is not a known postgres command' % sys.argv[1]) + # ' ERROR: "%s" is not a known postgres command' % sys_argv[1]) - if sys.argv[1].isupper(): - environ_key = sys.argv[1] - args = sys.argv[2:] + if sys_argv[1].isupper(): + environ_key = sys_argv[1] + args = sys_argv[2:] else: environ_key = 'DATABASE_URL' - args = sys.argv[1:] + args = sys_argv[1:] try: meta = get_uri(environ_key) @@ -134,16 +140,36 @@ def main(): env['PGPASSWORD'] = meta.password # pass any other flags the user set along tokens.extend(args[1:]) - sys.stderr.write(' '.join(tokens) + '\n') + return tokens, env + + +def main(): + if '--version' in sys.argv: + exit('PostDoc {0}'.format(__version__)) + if '--help' in sys.argv or len(sys.argv) < 2: + exit(__doc__) + is_dry_run = '--postdoc-dry-run' in sys.argv + if is_dry_run: + sys.argv.remove('--postdoc-dry-run') + is_quiet = '--postdoc-quiet' in sys.argv + if is_quiet: + sys.argv.remove('--postdoc-quiet') + + tokens, env = make_tokens_and_env(sys.argv) + if is_dry_run: + sys.stdout.write(' '.join(tokens) + '\n') + exit(0) + if not is_quiet: + sys.stderr.write(' '.join(tokens) + '\n') try: subprocess.call(tokens, env=env) except OSError as e: import errno if e.errno == errno.ENOENT: # No such file or directory - exit('{0}: command not found'.format(args[0])) - + exit('{0}: command not found'.format(tokens[0])) except KeyboardInterrupt: pass + if __name__ == '__main__': main()
Add a way to let the user decide if postdoc outputs anything at all As a human using postdoc, I want to be able to see what it's doing under the hood. But if I were a script, I may not want any output at all.
crccheck/postdoc
diff --git a/test_postdoc.py b/test_postdoc.py index 0715a83..a61568a 100644 --- a/test_postdoc.py +++ b/test_postdoc.py @@ -12,6 +12,12 @@ import mock import postdoc +# Just a reminder to myself that if I set DATABASE_URL, it will mess up the +# test suite +if 'DATABASE_URL' in os.environ: + exit('Re-run tests in an environment without DATABASE_URL') + + class ConnectBitsTest(unittest.TestCase): def test_pg_connect_bits_trivial_case(self): meta = type('mock', (object, ), @@ -117,63 +123,106 @@ class PHDTest(unittest.TestCase): self.assertEqual(postdoc.get_command('mysql', meta), ['mysql', 'rofl', '--database', 'database']) - def test_main_exits_with_no_command(self): - with mock.patch('postdoc.sys') as mock_sys: - mock_sys.argv = ['phd'] + def test_make_tokens_and_env_exits_with_bad_command(self): + with self.assertRaises(SystemExit): + postdoc.make_tokens_and_env(['phd', 'fun']) + + def test_make_tokens_and_env_exits_with_missing_env(self): + mock_get_command = mock.MagicMock(return_value=['get_command']) + + with mock.patch.multiple( + postdoc, + get_command=mock_get_command, + ): with self.assertRaises(SystemExit): - postdoc.main() + postdoc.make_tokens_and_env(['argv1', 'psql', 'argv3', 'argv4']) - def test_main_exits_with_bad_command(self): - with mock.patch('postdoc.sys') as mock_sys: - mock_sys.argv = ['phd', 'fun'] + def test_make_tokens_and_env_can_use_alternate_url(self): + mock_os = mock.MagicMock(environ={ + 'FATTYBASE_URL': 'postgis://u@h/test', + }) + + with mock.patch.multiple( + postdoc, + os=mock_os, + ): + tokens, env = postdoc.make_tokens_and_env( + ['argv1', 'FATTYBASE_URL', 'psql', 'extra_arg']) + self.assertEqual(tokens, + ['psql', '-U', 'u', '-h', 'h', 'test', 'extra_arg']) + + # INTEGRATION TESTING AROUND main() # + + def test_main_exits_with_no_command(self): + # TODO verify we exited for the right reason + mock_sys = mock.MagicMock(argv=['phd']) + with mock.patch.multiple( + postdoc, + sys=mock_sys, + ): with self.assertRaises(SystemExit): postdoc.main() - def test_main_exits_with_missing_env(self): + def test_main_works(self): mock_subprocess = mock.MagicMock() + # to avoid having to patch os.environ mock_get_command = mock.MagicMock(return_value=['get_command']) - mock_sys = mock.MagicMock() - mock_sys.argv = ['argv1', 'psql', 'argv3', 'argv4'] + mock_get_uri = mock.MagicMock() + mock_sys = mock.MagicMock(argv=['phd', 'psql']) with mock.patch.multiple( postdoc, subprocess=mock_subprocess, get_command=mock_get_command, + get_uri=mock_get_uri, + sys=mock_sys, + ): + postdoc.main() + self.assertEqual(mock_subprocess.call.call_args[0][0], ['get_command']) + self.assertEqual(mock_sys.stderr.write.call_args[0][0], 'get_command\n') + + def test_main_can_do_a_dry_run_to_stdout(self): + mock_subprocess = mock.MagicMock() + mock_get_command = mock.MagicMock(return_value=['get_command']) + mock_get_uri = mock.MagicMock() + mock_sys = mock.MagicMock(argv=['phd', 'psql', '--postdoc-dry-run']) + + with mock.patch.multiple( + postdoc, + subprocess=mock_subprocess, + get_command=mock_get_command, + get_uri=mock_get_uri, sys=mock_sys, ): with self.assertRaises(SystemExit): postdoc.main() + self.assertEqual(mock_sys.stdout.write.call_args[0][0], 'get_command\n') - def test_main_can_use_alternate_url(self): + def test_main_command_debug_can_be_quiet(self): mock_subprocess = mock.MagicMock() - mock_sys = mock.MagicMock( - argv=['argv1', 'FATTYBASE_URL', 'psql', 'extra_arg'], - ) - mock_os = mock.MagicMock(environ={ - 'FATTYBASE_URL': 'postgis://u@h/test', - }) + mock_get_command = mock.MagicMock(return_value=['get_command']) + mock_get_uri = mock.MagicMock() + mock_sys = mock.MagicMock(argv=['phd', 'psql', '--postdoc-quiet']) with mock.patch.multiple( postdoc, subprocess=mock_subprocess, + get_command=mock_get_command, + get_uri=mock_get_uri, sys=mock_sys, - os=mock_os, ): postdoc.main() - self.assertEqual(mock_subprocess.call.call_args[0][0], - ['psql', '-U', 'u', '-h', 'h', 'test', 'extra_arg']) + self.assertEqual(mock_subprocess.call.call_args[0][0], ['get_command']) + self.assertFalse(mock_sys.stderr.write.called) def test_main_passes_password_in_env(self): my_password = 'hunter2' meta = type('mock', (object, ), {'password': my_password}) - self.assertNotIn('DATABASE_URL', os.environ, - msg="Re-run tests in an environment without DATABASE_URL") mock_subprocess = mock.MagicMock() mock_get_command = mock.MagicMock(return_value=['get_command']) mock_get_uri = mock.MagicMock(return_value=meta) - mock_sys = mock.MagicMock() - mock_sys.argv = ['foo', 'psql'] + mock_sys = mock.MagicMock(argv=['foo', 'psql']) with mock.patch.multiple( postdoc, @@ -188,13 +237,10 @@ class PHDTest(unittest.TestCase): my_password) def test_main_appends_additional_flags(self): - self.assertNotIn('DATABASE_URL', os.environ, - msg="Re-run tests in an environment without DATABASE_URL") mock_subprocess = mock.MagicMock() mock_get_command = mock.MagicMock(return_value=['get_command']) mock_get_uri = mock.MagicMock() - mock_sys = mock.MagicMock() - mock_sys.argv = ['argv1', 'psql', 'argv3', 'argv4'] + mock_sys = mock.MagicMock(argv=['argv1', 'psql', 'argv3', 'argv4']) with mock.patch.multiple( postdoc, @@ -204,17 +250,16 @@ class PHDTest(unittest.TestCase): sys=mock_sys, ): postdoc.main() - self.assertEqual( - mock_subprocess.call.call_args[0][0], - ['get_command', 'argv3', 'argv4'] - ) + self.assertEqual( + mock_subprocess.call.call_args[0][0], + ['get_command', 'argv3', 'argv4'] + ) def test_nonsense_command_has_meaningful_error(self): mock_os = mock.MagicMock(environ={ 'DATABASE_URL': 'postgis://u@h/test', }) - mock_sys = mock.MagicMock( - argv=['phd', 'xyzzy']) + mock_sys = mock.MagicMock(argv=['phd', 'xyzzy']) with mock.patch.multiple( postdoc, os=mock_os,
{ "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": 2 }
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": [ "pytest", "mock" ], "pre_install": [ "find . -name '*.pyc' -delete", "find . -name '.DS_Store' -delete", "rm -rf *.egg", "rm -rf *.egg-info", "rm -rf __pycache__", "rm -rf build", "rm -rf dist" ], "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 -e git+https://github.com/crccheck/postdoc.git@4080450041ae86b295a2e1f8aea2018bf5e4b32a#egg=postdoc pytest @ file:///croot/pytest_1738938843180/work tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
name: postdoc 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 prefix: /opt/conda/envs/postdoc
[ "test_postdoc.py::PHDTest::test_main_can_do_a_dry_run_to_stdout", "test_postdoc.py::PHDTest::test_main_command_debug_can_be_quiet", "test_postdoc.py::PHDTest::test_make_tokens_and_env_can_use_alternate_url", "test_postdoc.py::PHDTest::test_make_tokens_and_env_exits_with_bad_command", "test_postdoc.py::PHDTest::test_make_tokens_and_env_exits_with_missing_env" ]
[]
[ "test_postdoc.py::ConnectBitsTest::test_connect_bits_supported_schemas", "test_postdoc.py::ConnectBitsTest::test_mysql_connect_bits_trivial_case", "test_postdoc.py::ConnectBitsTest::test_mysql_connect_bits_works", "test_postdoc.py::ConnectBitsTest::test_pg_connect_bits_trivial_case", "test_postdoc.py::ConnectBitsTest::test_pg_connect_bits_works", "test_postdoc.py::PHDTest::test_get_command_assembles_bits_in_right_order", "test_postdoc.py::PHDTest::test_get_command_ignores_password", "test_postdoc.py::PHDTest::test_get_command_special_syntax_for_mysql", "test_postdoc.py::PHDTest::test_get_command_special_syntax_for_pg_restore", "test_postdoc.py::PHDTest::test_get_commands_can_ignore_database_name", "test_postdoc.py::PHDTest::test_get_uri", "test_postdoc.py::PHDTest::test_main_appends_additional_flags", "test_postdoc.py::PHDTest::test_main_exits_with_no_command", "test_postdoc.py::PHDTest::test_main_passes_password_in_env", "test_postdoc.py::PHDTest::test_main_works", "test_postdoc.py::PHDTest::test_nonsense_command_has_meaningful_error" ]
[]
Apache License 2.0
51
[ "README.rst", "postdoc.py" ]
[ "README.rst", "postdoc.py" ]
thisfred__val-9
a60e8de415d9ed855570fc09ee14a5974532cf07
2015-03-03 07:49:35
a60e8de415d9ed855570fc09ee14a5974532cf07
coveralls: [![Coverage Status](https://coveralls.io/builds/2031381/badge)](https://coveralls.io/builds/2031381) Coverage remained the same at 100.0% when pulling **8f5f8492be58f84c36c8751ec81a90b9d4f64353 on collect-all-errors** into **a60e8de415d9ed855570fc09ee14a5974532cf07 on master**.
diff --git a/README.rst b/README.rst index bc413c0..33d435d 100644 --- a/README.rst +++ b/README.rst @@ -184,11 +184,10 @@ not missing any of the keys specified (unless they are specified as >>> schema.validates({'foo': 12, 'bar': 888, 'baz': 299}) True - >>> schema.validate({'foo': 'bar'}) + >>> schema.validate({'foo': 'bar', 'baz': 'qux'}) Traceback (most recent call last): ... - val.NotValid: 'foo': 'bar' is not of type <class 'int'> - + val.NotValid: ("'foo': 'bar' is not of type <class 'int'>", "'baz': 'qux' not matched") >>> schema.validate({'qux': 19}) Traceback (most recent call last): ... @@ -286,7 +285,7 @@ elements passed into the Or: >>> schema.validate('bar') Traceback (most recent call last): ... - val.NotValid: 'bar' is not equal to 'foo', 'bar' is not of type <class 'int'> + val.NotValid: 'bar' is not equal to 'foo' and 'bar' is not of type <class 'int'> And() diff --git a/pp.yaml b/pp.yaml index f3a43d0..bdcd9e8 100644 --- a/pp.yaml +++ b/pp.yaml @@ -10,8 +10,6 @@ ignore-patterns: pep8: run: true - options: - max-line-length: 80 mccabe: run: true @@ -44,3 +42,5 @@ pylint: disable: - too-few-public-methods - invalid-name + - star-args + - line-too-long diff --git a/requirements.txt b/requirements.txt index b8313ef..20b74fc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,1 @@ -teleport pyRFC3339>=0.2 diff --git a/val/__init__.py b/val/__init__.py index b22cb10..42fd75a 100644 --- a/val/__init__.py +++ b/val/__init__.py @@ -60,7 +60,7 @@ def build_callable_validator(function): return data except (TypeError, ValueError, NotValid) as ex: - raise NotValid(', '.join(ex.args)) + raise NotValid(ex.args) raise NotValid("%r invalidated by '%s'" % (data, get_repr(function))) @@ -116,14 +116,17 @@ def _determine_keys(dictionary): def _validate_mandatory_keys(mandatory, validated, data, to_validate): """Validate the manditory keys.""" + errors = [] for key, sub_schema in mandatory.items(): if key not in data: - raise NotValid('missing key: %r' % (key,)) + errors.append('missing key: %r' % (key,)) + continue try: validated[key] = sub_schema(data[key]) except NotValid as ex: - raise NotValid('%r: %s' % (key, ', '.join(ex.args))) + errors.extend(['%r: %s' % (key, arg) for arg in ex.args]) to_validate.remove(key) + return errors def _validate_optional_key(key, missing, value, validated, optional): @@ -131,9 +134,10 @@ def _validate_optional_key(key, missing, value, validated, optional): try: validated[key] = optional[key](value) except NotValid as ex: - raise NotValid('%r: %s' % (key, ', '.join(ex.args))) + return ['%r: %s' % (key, arg) for arg in ex.args] if key in missing: missing.remove(key) + return [] def _validate_type_key(key, value, types, validated): @@ -146,20 +150,24 @@ def _validate_type_key(key, value, types, validated): except NotValid: continue else: - break - else: - raise NotValid('%r: %r not matched' % (key, value)) + return [] + + return ['%r: %r not matched' % (key, value)] def _validate_other_keys(optional, types, missing, validated, data, to_validate): """Validate the rest of the keys present in the data.""" + errors = [] for key in to_validate: value = data[key] if key in optional: - _validate_optional_key(key, missing, value, validated, optional) + errors.extend( + _validate_optional_key( + key, missing, value, validated, optional)) continue - _validate_type_key(key, value, types, validated) + errors.extend(_validate_type_key(key, value, types, validated)) + return errors def build_dict_validator(dictionary): @@ -174,9 +182,13 @@ def build_dict_validator(dictionary): validated = {} to_validate = list(data.keys()) - _validate_mandatory_keys(mandatory, validated, data, to_validate) - _validate_other_keys( - optional, types, missing, validated, data, to_validate) + errors = _validate_mandatory_keys( + mandatory, validated, data, to_validate) + errors.extend( + _validate_other_keys( + optional, types, missing, validated, data, to_validate)) + if errors: + raise NotValid(*errors) for key in missing: validated[key] = defaults[key][0] @@ -233,11 +245,14 @@ class BaseSchema(object): def validate(self, data): """Validate data. Raise NotValid error for invalid data.""" validated = self._validated(data) + errors = [] for validator in self.additional_validators: if not validator(validated): - raise NotValid( + errors.append( "%s invalidated by '%s'" % ( validated, get_repr(validator))) + if errors: + raise NotValid(*errors) if self.default is UNSPECIFIED: return validated @@ -303,7 +318,7 @@ class Or(BaseSchema): except NotValid as ex: errors.extend(ex.args) - raise NotValid(', '.join(errors)) + raise NotValid(' and '.join(errors)) def __repr__(self): return "<%s>" % (" or ".join(["%r" % (v,) for v in self.values]),) @@ -347,7 +362,7 @@ class Convert(BaseSchema): try: return self.convert(data) except (TypeError, ValueError) as ex: - raise NotValid(', '.join(ex.args)) + raise NotValid(*ex.args) def __repr__(self): """Display schema."""
Return all validation errors, rather than just the first one. Currently val's ValidationErrors only contain a single validation error message, even if the data was invalid in more than one way. This makes validation a tiny bit faster, but at the expense of not being as informative as it could be. I think I am going to reverse this decision.
thisfred/val
diff --git a/tests/test_val.py b/tests/test_val.py index c60bf63..fa4825b 100644 --- a/tests/test_val.py +++ b/tests/test_val.py @@ -487,3 +487,10 @@ def test_cannot_change_definition(): schema = Schema({"foo": "bar"}) with pytest.raises(AttributeError): schema.definition = {"qux": "baz"} + + +def test_captures_multiple_errors(): + schema = Schema({"foo": str}) + with pytest.raises(NotValid) as exception: + schema.validate({'foo': 12, 'bar': 'qux'}) + assert len(exception.value.args) == 2
{ "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": 2, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 4 }
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", "pytest-cov", "flake8", "coveralls", "schema" ], "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 charset-normalizer==2.0.12 coverage==6.2 coveralls==3.3.1 docopt==0.6.2 flake8==5.0.4 idna==3.10 importlib-metadata==4.2.0 iniconfig==1.1.1 mccabe==0.7.0 packaging==21.3 pluggy==1.0.0 py==1.11.0 pycodestyle==2.9.1 pyflakes==2.5.0 pyparsing==3.1.4 pyRFC3339==2.0.1 pytest==7.0.1 pytest-cov==4.0.0 requests==2.27.1 schema==0.7.7 teleport==0.4.0 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 -e git+https://github.com/thisfred/val.git@a60e8de415d9ed855570fc09ee14a5974532cf07#egg=val zipp==3.6.0
name: val 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 - docopt==0.6.2 - flake8==5.0.4 - idna==3.10 - importlib-metadata==4.2.0 - iniconfig==1.1.1 - mccabe==0.7.0 - packaging==21.3 - pluggy==1.0.0 - py==1.11.0 - pycodestyle==2.9.1 - pyflakes==2.5.0 - pyparsing==3.1.4 - pyrfc3339==2.0.1 - pytest==7.0.1 - pytest-cov==4.0.0 - requests==2.27.1 - schema==0.7.7 - teleport==0.4.0 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/val
[ "tests/test_val.py::test_captures_multiple_errors" ]
[]
[ "tests/test_val.py::test_must_implement_validated", "tests/test_val.py::test_identity", "tests/test_val.py::test_non_identity", "tests/test_val.py::test_type_check", "tests/test_val.py::test_failing_type_check", "tests/test_val.py::test_dictionary", "tests/test_val.py::test_dictionary_not_a_dict", "tests/test_val.py::test_dictionary_optional", "tests/test_val.py::test_dictionary_optional_repr", "tests/test_val.py::test_dictionary_optional_with_default_on_value", "tests/test_val.py::test_dictionary_optional_with_null_values", "tests/test_val.py::test_dictionary_missing_with_null_values", "tests/test_val.py::test_regression_validating_twice_works", "tests/test_val.py::test_dictionary_optional_with_null_value_on_value_schema", "tests/test_val.py::test_dictionary_optional_not_missing", "tests/test_val.py::test_dictionary_optional_with_default_on_value_not_missing", "tests/test_val.py::test_dictionary_wrong_key", "tests/test_val.py::test_dictionary_missing_key", "tests/test_val.py::test_dictionary_leftover_key", "tests/test_val.py::test_list_data", "tests/test_val.py::test_list_data_wrong_type", "tests/test_val.py::test_list_data_multiple_types", "tests/test_val.py::test_not_list", "tests/test_val.py::test_list_not_found", "tests/test_val.py::test_or", "tests/test_val.py::test_or_repr", "tests/test_val.py::test_nullable", "tests/test_val.py::test_nullable_with_default", "tests/test_val.py::test_and", "tests/test_val.py::test_and_repr", "tests/test_val.py::test_dont_care_values_in_dict", "tests/test_val.py::test_callable", "tests/test_val.py::test_callable_gives_readable_error", "tests/test_val.py::test_callable_gives_sensible_error", "tests/test_val.py::test_convert", "tests/test_val.py::test_ordered", "tests/test_val.py::test_ordered_repr", "tests/test_val.py::test_callable_exception", "tests/test_val.py::test_subschemas", "tests/test_val.py::test_and_schema", "tests/test_val.py::test_or_schema", "tests/test_val.py::test_validate_list", "tests/test_val.py::test_list_tuple_set_frozenset", "tests/test_val.py::test_strictly", "tests/test_val.py::test_dict", "tests/test_val.py::test_dict_keys", "tests/test_val.py::test_dict_optional_keys", "tests/test_val.py::test_validate_object", "tests/test_val.py::test_issue_9_prioritized_key_comparison", "tests/test_val.py::test_issue_9_prioritized_key_comparison_in_dicts", "tests/test_val.py::test_schema_with_additional_validators", "tests/test_val.py::test_does_not_use_default_value_to_replace_falsy_values", "tests/test_val.py::test_uses_default_value_when_explicitly_told_to", "tests/test_val.py::test_uses_default_value_to_replace_missing_values", "tests/test_val.py::test_can_see_definition", "tests/test_val.py::test_cannot_change_definition" ]
[]
BSD 2-Clause "Simplified" License
53
[ "README.rst", "val/__init__.py", "requirements.txt", "pp.yaml" ]
[ "README.rst", "val/__init__.py", "requirements.txt", "pp.yaml" ]
Turbo87__utm-12
a8b2496e534671e5f07a19371f2c80813d7f2f50
2015-03-06 12:48:24
4c7c13f2b2b9c01a8581392641aeb8bbda6aba6f
diff --git a/utm/__init__.py b/utm/__init__.py index 4c844d2..3dece60 100644 --- a/utm/__init__.py +++ b/utm/__init__.py @@ -1,2 +1,2 @@ -from utm.conversion import to_latlon, from_latlon +from utm.conversion import to_latlon, from_latlon, latlon_to_zone_number, latitude_to_zone_letter from utm.error import OutOfRangeError diff --git a/utm/conversion.py b/utm/conversion.py old mode 100644 new mode 100755 index 5d5723a..eb3b35d --- a/utm/conversion.py +++ b/utm/conversion.py @@ -29,16 +29,10 @@ P5 = (1097. / 512 * _E4) R = 6378137 -ZONE_LETTERS = [ - (84, None), (72, 'X'), (64, 'W'), (56, 'V'), (48, 'U'), (40, 'T'), - (32, 'S'), (24, 'R'), (16, 'Q'), (8, 'P'), (0, 'N'), (-8, 'M'), (-16, 'L'), - (-24, 'K'), (-32, 'J'), (-40, 'H'), (-48, 'G'), (-56, 'F'), (-64, 'E'), - (-72, 'D'), (-80, 'C') -] +ZONE_LETTERS = "CDEFGHJKLMNPQRSTUVWXX" def to_latlon(easting, northing, zone_number, zone_letter=None, northern=None): - if not zone_letter and northern is None: raise ValueError('either zone_letter or northern needs to be set') @@ -90,7 +84,7 @@ def to_latlon(easting, northing, zone_number, zone_letter=None, northern=None): n = R / ep_sin_sqrt r = (1 - E) / ep_sin - c = _E * p_cos**2 + c = _E * p_cos ** 2 c2 = c * c d = x / (n * K0) @@ -103,7 +97,7 @@ def to_latlon(easting, northing, zone_number, zone_letter=None, northern=None): latitude = (p_rad - (p_tan / r) * (d2 / 2 - d4 / 24 * (5 + 3 * p_tan2 + 10 * c - 4 * c2 - 9 * E_P2)) + - d6 / 720 * (61 + 90 * p_tan2 + 298 * c + 45 * p_tan4 - 252 * E_P2 - 3 * c2)) + d6 / 720 * (61 + 90 * p_tan2 + 298 * c + 45 * p_tan4 - 252 * E_P2 - 3 * c2)) longitude = (d - d3 / 6 * (1 + 2 * p_tan2 + c) + @@ -138,8 +132,8 @@ def from_latlon(latitude, longitude, force_zone_number=None): central_lon = zone_number_to_central_longitude(zone_number) central_lon_rad = math.radians(central_lon) - n = R / math.sqrt(1 - E * lat_sin**2) - c = E_P2 * lat_cos**2 + n = R / math.sqrt(1 - E * lat_sin ** 2) + c = E_P2 * lat_cos ** 2 a = lat_cos * (lon_rad - central_lon_rad) a2 = a * a @@ -158,7 +152,7 @@ def from_latlon(latitude, longitude, force_zone_number=None): a5 / 120 * (5 - 18 * lat_tan2 + lat_tan4 + 72 * c - 58 * E_P2)) + 500000 northing = K0 * (m + n * lat_tan * (a2 / 2 + - a4 / 24 * (5 - lat_tan2 + 9 * c + 4 * c**2) + + a4 / 24 * (5 - lat_tan2 + 9 * c + 4 * c ** 2) + a6 / 720 * (61 - 58 * lat_tan2 + lat_tan4 + 600 * c - 330 * E_P2))) if latitude < 0: @@ -168,11 +162,10 @@ def from_latlon(latitude, longitude, force_zone_number=None): def latitude_to_zone_letter(latitude): - for lat_min, zone_letter in ZONE_LETTERS: - if latitude >= lat_min: - return zone_letter - - return None + if -80 <= latitude <= 84: + return ZONE_LETTERS[int(latitude + 80) >> 3] + else: + return None def latlon_to_zone_number(latitude, longitude):
Zone letter problem Zone letter return 'None' for latitude 84
Turbo87/utm
diff --git a/test/test_utm.py b/test/test_utm.py old mode 100644 new mode 100755 index 1ffcab2..4e8f7e8 --- a/test/test_utm.py +++ b/test/test_utm.py @@ -58,6 +58,12 @@ class KnownValues(UTMTestCase): (377486, 6296562, 30, 'V'), {'northern': True}, ), + # Latitude 84 + ( + (84, -5.00601), + (476594, 9328501, 30, 'X'), + {'northern': True}, + ), ] def test_from_latlon(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": 0, "issue_text_score": 1, "test_score": 1 }, "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": "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/Turbo87/utm.git@a8b2496e534671e5f07a19371f2c80813d7f2f50#egg=utm
name: utm 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/utm
[ "test/test_utm.py::KnownValues::test_from_latlon" ]
[]
[ "test/test_utm.py::KnownValues::test_to_latlon", "test/test_utm.py::BadInput::test_from_latlon_range_checks", "test/test_utm.py::BadInput::test_to_latlon_range_checks" ]
[]
MIT License
54
[ "utm/conversion.py", "utm/__init__.py" ]
[ "utm/conversion.py", "utm/__init__.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
[ "tornado/util.py", "tornado/web.py", "tornado/simple_httpclient.py", "tornado/httpserver.py" ]
[ "tornado/util.py", "tornado/web.py", "tornado/simple_httpclient.py", "tornado/httpserver.py" ]
bokeh__bokeh-2052
65d083b2504d6dc602fd892c4986eed56c5ddf49
2015-03-09 16:50:16
3134cdd802c6969274c8227b3231f27b4d383e1e
diff --git a/bokeh/__init__.py b/bokeh/__init__.py index d561ab1c0..51c521ab5 100644 --- a/bokeh/__init__.py +++ b/bokeh/__init__.py @@ -10,7 +10,7 @@ and data applications. For full documentation, please visit: http://bokeh.pydata.org """ -from __future__ import absolute_import, print_function +from __future__ import absolute_import # configure Bokeh version from .util.version import __version__; __version__ @@ -23,7 +23,4 @@ del logconfig # module as transitive imports from . import sampledata; sampledata -from .settings import settings; settings -from .util.testing import print_versions; print_versions -from .util.testing import report_issue; report_issue from .util.testing import runtests as test; test diff --git a/bokeh/browserlib.py b/bokeh/browserlib.py index a97bbdf17..64ffa4f56 100644 --- a/bokeh/browserlib.py +++ b/bokeh/browserlib.py @@ -3,7 +3,7 @@ from __future__ import absolute_import from os.path import abspath import webbrowser -from . import settings +from .settings import settings def get_browser_controller(browser=None): browser = settings.browser(browser) diff --git a/bokeh/resources.py b/bokeh/resources.py index e78522e5d..53e2e58ae 100644 --- a/bokeh/resources.py +++ b/bokeh/resources.py @@ -19,7 +19,8 @@ logger = logging.getLogger(__name__) import six -from . import __version__, settings +from . import __version__ +from .settings import settings def _server_static_dir(): return join(abspath(split(__file__)[0]), "server", "static") diff --git a/sphinx/source/conf.py b/sphinx/source/conf.py index d0ebd93f9..928bf0780 100644 --- a/sphinx/source/conf.py +++ b/sphinx/source/conf.py @@ -59,23 +59,14 @@ master_doc = 'index' project = u'Bokeh' copyright = u'2013, Continuum Analytics' -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# Let's try to automatically get the version -from bokeh._version import get_versions -from bokeh import settings - -try: - from bokeh.__conda_version__ import conda_version - __version__ = conda_version.replace("'","") - del conda_version -except ImportError: - __version__ = get_versions()['version'] - del get_versions - -# if you need to redeploy the released docs, you only need the x.x.x version +# Get the standard computed Bokeh version string to use for |version| +# and |release| +from bokeh import __version__ + +# Check for version override (e.g. when re-deploying a previously released +# docs, or when pushing test docs that do not have a corresponding BokehJS +# available on CDN) +from bokeh.settings import settings if settings.released_docs(): __version__ = __version__.split('-')[0] diff --git a/sphinx/source/docs/reference/plot_objects.rst b/sphinx/source/docs/reference/plot_objects.rst index 9cfcd71f6..84f3dddf6 100644 --- a/sphinx/source/docs/reference/plot_objects.rst +++ b/sphinx/source/docs/reference/plot_objects.rst @@ -14,8 +14,6 @@ Plot Objects The ``bokeh`` module itself contains a few useful functions for testing and reporting issues: -.. autofunction:: bokeh.print_versions -.. autofunction:: bokeh.report_issue .. autofunction:: bokeh.test .. _bokeh.document: diff --git a/sphinx/source/docs/user_guide.rst b/sphinx/source/docs/user_guide.rst index f951011e7..173c6630a 100644 --- a/sphinx/source/docs/user_guide.rst +++ b/sphinx/source/docs/user_guide.rst @@ -20,5 +20,4 @@ the kinds of low-level object attributes that can be set to really customize a p user_guide/widgets.rst user_guide/ar.rst user_guide/examples.rst - user_guide/issues.rst diff --git a/sphinx/source/docs/user_guide/issues.rst b/sphinx/source/docs/user_guide/issues.rst deleted file mode 100644 index 40c49ab9b..000000000 --- a/sphinx/source/docs/user_guide/issues.rst +++ /dev/null @@ -1,55 +0,0 @@ -.. _userguide_issues: - -Reporting Issues -================ - -You can report possible bugs, start discussions, or ask for features on our -`issue tracker <https://github.com/bokeh/bokeh/issues>`_. -To start a new issue, you will find a ``New issue`` green button at the top -right area of the page. - -Bokeh also provides the :func:`bokeh.report_issue()` function to easily open -issues from an interactive console prompt:: - - - In [1]: bokeh.report_issue() - This is the Bokeh reporting engine. - - You will be guided to build a GitHub issue. - - Issue title: A Short Issue Title - Description: Some additional details and description - GitHub username: SomeUser - GitHub password: xxxxxxxx - - Preview: - - Title: A Short Issue Title - Description: - - Some additional details and description - - System information: - Bokeh version: 0.5.2-436-g831adf5-dirty - Python version: 2.7.8-CPython - Platform: Darwin-13.3.0-x86_64-i386-64bit - - Submit (y/n)? - -This will open a new issue on our issue tracker as well as open a new browser tab -showing the issue, in case you want to add more comments. As you can see, this -automatically appends useful information about versions and architecture that can -help us to reproduce the problem. - -Finally, you can also make a comment on any issue using this tool just by passing -the issue number as an argument:: - - In [3]: bokeh.report_issue(555) - This is the Bokeh reporting engine. - - You will be guided to build a GitHub issue. - - Write your comment here: Some new information! - - -
simplify bokeh/__init__.py even more
bokeh/bokeh
diff --git a/bokeh/tests/test_bokeh_init.py b/bokeh/tests/test_bokeh_init.py index e47ad7f0b..628987bf4 100644 --- a/bokeh/tests/test_bokeh_init.py +++ b/bokeh/tests/test_bokeh_init.py @@ -1,49 +1,19 @@ from __future__ import absolute_import import unittest -import sys -import platform -import os -import mock +class TestContents(unittest.TestCase): -class CaptureString(): - value = "" - - def write(self, string): - self.value += string - - def flush(self): - pass - - -def CaptureStdOut(): - # replace stdout with something we can capture - out = CaptureString() - sys.stdout = out - return out - - -class TestPrintVersions(unittest.TestCase): - - def setUp(self): - self.out = CaptureStdOut() - - def test_print(self): + def test_dir(self): import bokeh - bokeh.print_versions() - # check the correct info is present - sysinfo = [platform.python_version(), - platform.python_implementation(), - platform.platform(), - bokeh.__version__] - for info in sysinfo: - self.assertIn(info, self.out.value) + names = dir(bokeh) + self.assertTrue("__version__" in names) + self.assertTrue("test" in names) + self.assertTrue("sampledata" in names) def test_version_defined(self): import bokeh self.assertTrue(bokeh.__version__ != 'unknown') - if __name__ == "__main__": unittest.main() diff --git a/bokeh/util/testing.py b/bokeh/util/testing.py index 9c7ab39f5..a0f7adfd6 100644 --- a/bokeh/util/testing.py +++ b/bokeh/util/testing.py @@ -20,7 +20,13 @@ def skipIfPyPy(message): from .platform import is_pypy return skipIf(is_pypy(), message) -def _print_versions(): +def print_versions(): + """ Print the versions for Bokeh and the current Python and OS. + + Returns: + None + + """ import platform as pt from .. import __version__ message = """ @@ -29,16 +35,7 @@ def _print_versions(): Platform: %s """ % (__version__, pt.python_version(), pt.python_implementation(), pt.platform()) - return(message) - -def print_versions(): - """ Print the versions for Bokeh and the current Python and OS. - - Returns: - None - - """ - print(_print_versions()) + print(message) def runtests(verbosity=1, xunitfile=None, exit=False): """ Run the full Bokeh test suite, and output the results of the tests @@ -89,115 +86,3 @@ def runtests(verbosity=1, xunitfile=None, exit=False): # Run the tests return nose.main(argv=argv, exit=exit) - - -def report_issue(number=None, owner="bokeh", repo="bokeh", - versions=True, browser=True): - """ Open or add to a Github issue programmatically. - - This interactive function will ask you for some minimal content - and submit a new Github issue, adding information about your - current environment. - - You can also call this function with a specific issue number to - add a comment to an already open issue. - - Args: - number (int, optional) : - Omit to create a new issue, otherwise supply to comment on an - already created issue. (default: None) - - owner (str, optional) : owner username (default: "bokeh") - - repo (str, optional) : repository name (default: "bokeh") - - versions (bool, optional) : - Whether to print system information. If True, add the current - system info to the end of the issue description. (default: True) - - browser (bool, optional) : - Whether to open a browser automatically. If True, open a browser - to the GitHub issue page (default: True) - - .. note:: - Setting the environment variables GHUSER (Github username) and - GHPASS (Github password) will supply those values automatically - and streamline the dialog. Additionally, this function can report - on any GitHub project by changing the default parameters. - - Returns: - None - - """ - - import requests - import json - import os - import webbrowser - - from six.moves import input - from six.moves.urllib.parse import urljoin - - print("This is the Bokeh reporting engine.\n\n" - "You will be guided to build a GitHub issue.\n") - - if number is None: - title = input('Issue title: ') - body = input('Description: ') - else: - body = input('Write your comment here: ') - - ghuser, ghpass = (os.environ.get(x) for x in ["GHUSER", "GHPASS"]) - - if ghuser is None: - ghuser = input('GitHub username: ') - else: - print("Found GHUSER, using for GitHub username") - - if ghpass is None: - ghpass = input('GitHub password: ') - else: - print("Found GHPASS, using for GitHub password") - - base = "https://api.github.com" - if number is None: - url = "/".join(["repos", owner, repo, "issues"]) - if versions: - data = {"title": title, "body": body + "\nSystem information:" + _print_versions()} - else: - data = {"title": title, "body": body} - else: - url = "/".join(["repos", owner, repo, "issues", str(number), "comments"]) - if versions: - data = {"body": body + "\nSystem information:" + _print_versions()} - else: - data = {"body": body} - issues_url = urljoin(base, url) - - print("\nPreview:\n") - print("Title: ", data["title"]) - print("Description:\n\n") - print(data["body"]) - value = input('Submit (y/n)? ') - if value.lower() in ["true", "yes", "y", "1"]: - r = requests.post(issues_url, - auth=(ghuser, ghpass), - headers={'Content-Type': 'application/json'}, - data=json.dumps(data)) - if r.status_code == 201: - g = requests.get(issues_url) - if number is None: - print("Issue successfully submitted.") - if browser: - webbrowser.open_new(g.json()[0].get("html_url")) - else: - print("Comment successfully submitted.") - g = requests.get(issues_url) - if browser: - webbrowser.open_new(g.json()[-1].get("html_url")) - else: - print("Something failed, please check your username and password.") - else: - print("Issue not submitted.") - - diff --git a/bokeh/util/tests/test_testing.py b/bokeh/util/tests/test_testing.py new file mode 100644 index 000000000..817b4e30c --- /dev/null +++ b/bokeh/util/tests/test_testing.py @@ -0,0 +1,41 @@ +from __future__ import absolute_import + +import unittest +import sys +import platform + +import bokeh.util.testing as testing + +class _CaptureString(): + value = "" + + def write(self, string): + self.value += string + + def flush(self): + pass + +def _CaptureStdOut(): + # replace stdout with something we can capture + out = _CaptureString() + sys.stdout = out + return out + +class TestPrintVersions(unittest.TestCase): + + def setUp(self): + self.out = _CaptureStdOut() + + def test_print(self): + import bokeh + testing.print_versions() + # check the correct info is present + sysinfo = [platform.python_version(), + platform.python_implementation(), + platform.platform(), + bokeh.__version__] + for info in sysinfo: + self.assertIn(info, self.out.value) + +if __name__ == "__main__": + unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_removed_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 6 }
0.8
{ "env_vars": null, "env_yml_path": null, "install": "pip install bokeh", "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" }
bokeh==3.4.3 contourpy==1.3.0 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work Jinja2==3.1.6 MarkupSafe==3.0.2 numpy==2.0.2 packaging @ file:///croot/packaging_1734472117206/work pandas==2.2.3 pillow==11.1.0 pluggy @ file:///croot/pluggy_1733169602837/work pytest @ file:///croot/pytest_1738938843180/work python-dateutil==2.9.0.post0 pytz==2025.2 PyYAML==6.0.2 six==1.17.0 tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work tornado==6.4.2 tzdata==2025.2 xyzservices==2025.1.0
name: bokeh 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 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - bokeh==3.4.3 - contourpy==1.3.0 - jinja2==3.1.6 - markupsafe==3.0.2 - numpy==2.0.2 - pandas==2.2.3 - pillow==11.1.0 - python-dateutil==2.9.0.post0 - pytz==2025.2 - pyyaml==6.0.2 - six==1.17.0 - tornado==6.4.2 - tzdata==2025.2 - xyzservices==2025.1.0 prefix: /opt/conda/envs/bokeh
[ "bokeh/tests/test_bokeh_init.py::TestContents::test_dir", "bokeh/tests/test_bokeh_init.py::TestContents::test_version_defined", "bokeh/util/tests/test_testing.py::TestPrintVersions::test_print" ]
[]
[]
[]
BSD 3-Clause "New" or "Revised" License
57
[ "sphinx/source/docs/user_guide/issues.rst", "sphinx/source/docs/user_guide.rst", "sphinx/source/conf.py", "bokeh/__init__.py", "sphinx/source/docs/reference/plot_objects.rst", "bokeh/resources.py", "bokeh/browserlib.py" ]
[ "sphinx/source/docs/user_guide/issues.rst", "sphinx/source/docs/user_guide.rst", "sphinx/source/conf.py", "bokeh/__init__.py", "sphinx/source/docs/reference/plot_objects.rst", "bokeh/resources.py", "bokeh/browserlib.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
[ "treelib/tree.py" ]
[ "treelib/tree.py" ]
ekalinin__nodeenv-118
677df66038d8ef2a5180a41e8335a857af5494f0
2015-03-11 21:55:41
677df66038d8ef2a5180a41e8335a857af5494f0
diff --git a/nodeenv.py b/nodeenv.py index c00a75c..ec9e358 100644 --- a/nodeenv.py +++ b/nodeenv.py @@ -36,13 +36,15 @@ except ImportError: # pragma: no cover (py3 only) from pkg_resources import parse_version - nodeenv_version = '0.13.0' join = os.path.join abspath = os.path.abspath src_domain = "nodejs.org" +is_PY3 = sys.version_info[0] == 3 +if is_PY3: + from functools import cmp_to_key # --------------------------------------------------------- # Utils @@ -711,20 +713,58 @@ def create_environment(env_dir, opt): callit(['rm -rf', pipes.quote(src_dir)], opt.verbose, True, env_dir) +class GetsAHrefs(HTMLParser): + def __init__(self): + # Old style class in py2 :( + HTMLParser.__init__(self) + self.hrefs = [] + + def handle_starttag(self, tag, attrs): + if tag == 'a': + self.hrefs.append(dict(attrs).get('href', '')) + VERSION_RE = re.compile('\d+\.\d+\.\d+') +def _py2_cmp(a, b): + # -1 = a < b, 0 = eq, 1 = a > b + return (a > b) - (a < b) + + +def compare_versions(version, other_version): + version_tuple = version.split('.') + other_tuple = other_version.split('.') + + version_length = len(version_tuple) + other_length = len(other_tuple) + version_dots = min(version_length, other_length) + + for i in range(version_dots): + a = int(version_tuple[i]) + b = int(other_tuple[i]) + cmp_value = _py2_cmp(a, b) + if cmp_value != 0: + return cmp_value + + return _py2_cmp(version_length, other_length) + + def get_node_versions(): response = urlopen('https://{0}/dist'.format(src_domain)) href_parser = GetsAHrefs() href_parser.feed(response.read().decode('UTF-8')) + versions = set( VERSION_RE.search(href).group() for href in href_parser.hrefs if VERSION_RE.search(href) ) - sorted_versions = sorted([parse_version(version) for version in versions]) - return [v.public for v in sorted_versions] + if is_PY3: + key_compare = cmp_to_key(compare_versions) + versions = sorted(versions, key=key_compare) + else: + versions = sorted(versions, cmp=compare_versions) + return versions def print_node_versions(): @@ -739,17 +779,6 @@ def print_node_versions(): logger.info('\t'.join(chunk)) -class GetsAHrefs(HTMLParser): - def __init__(self): - # Old style class in py2 :( - HTMLParser.__init__(self) - self.hrefs = [] - - def handle_starttag(self, tag, attrs): - if tag == 'a': - self.hrefs.append(dict(attrs).get('href', '')) - - def get_last_stable_node_version(): """ Return last stable node.js version
nodeenv --list is raising TypeError When installed globally with `sudo pip install nodeenv`, `nodeenv --list` raises an exception. This is due to `pkg_resources.parse_version` method having different return types in older versions. ![nodeenv_bug](https://cloud.githubusercontent.com/assets/6031925/6599860/d253a2b0-c814-11e4-94d6-9a9d79cdf27c.png) Possible hotfix solutions are: * write a helper function to parse strings, * write our own Version type :-1: But atm I'm working on finding out which version of `setuptools` introduced the newer (currently used in master) Version type that parses version strings and rely on it if `setuptools` is >= that version. I'll combine that with one of two approaches: * the raw string representation we get with regex pattern. However ascending sorting will be `0.1.0, 0.10.0, 0.9.0`, * the before mentioned helper function I think broken ascending sort is acceptable as a hotfix. PR will be submitted soon-ish. :8ball:
ekalinin/nodeenv
diff --git a/tests/nodeenv_test.py b/tests/nodeenv_test.py index 8c8b163..f13b219 100644 --- a/tests/nodeenv_test.py +++ b/tests/nodeenv_test.py @@ -14,6 +14,17 @@ import nodeenv HERE = os.path.abspath(os.path.dirname(__file__)) +def test_compare_versions(): + assert nodeenv.compare_versions('1', '2') == -1 + assert nodeenv.compare_versions('1', '2') == -1 + assert nodeenv.compare_versions('0.1', '0.2') == -1 + assert nodeenv.compare_versions('0.9', '0.10') == -1 + assert nodeenv.compare_versions('0.2', '0.2.1') == -1 + assert nodeenv.compare_versions('0.2.1', '0.2.10') == -1 + assert nodeenv.compare_versions('0.2.9', '0.2.10') == -1 + assert nodeenv.compare_versions('0.2.1', '0.3') == -1 + + def test_gets_a_hrefs_trivial(): parser = nodeenv.GetsAHrefs() parser.feed('')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_media" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.13
{ "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-django", "pytest-cov", "pytest-localserver", "pytest-mock", "pytest-benchmark", "pytest-bdd", "pytest-rerunfailures", "jsonschema", "more-itertools", "pluggy", "atomicwrites", "pyrsistent", "configparser", "contextlib2", "importlib-metadata", "packaging", "Mako", "glob2", "parse", "parse-type", "toml", "iniconfig", "docutils", "py-cpuinfo", "urllib3", "certifi", "Logbook", "WebOb", "argparse", "greenlet", "mock", "msgpack-python", "pep8", "pytz", "ecs_logging", "structlog", "pytest-asyncio", "asynctest", "typing_extensions" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "tests/requirements/reqs-base.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
asynctest==0.13.0 atomicwrites==1.4.1 attrs==25.3.0 certifi==2025.1.31 configparser==7.2.0 contextlib2==21.6.0 coverage==7.8.0 docutils==0.21.2 ecs-logging==2.2.0 exceptiongroup==1.2.2 gherkin-official==29.0.0 glob2==0.7 greenlet==3.1.1 importlib_metadata==8.6.1 iniconfig==2.1.0 jsonschema==4.23.0 jsonschema-specifications==2024.10.1 Logbook==1.8.1 Mako==1.3.9 MarkupSafe==3.0.2 mock==5.2.0 more-itertools==10.6.0 msgpack-python==0.5.6 -e git+https://github.com/ekalinin/nodeenv.git@677df66038d8ef2a5180a41e8335a857af5494f0#egg=nodeenv packaging==24.2 parse==1.20.2 parse_type==0.6.4 pep8==1.7.1 pluggy==1.5.0 py-cpuinfo==9.0.0 pyrsistent==0.20.0 pytest==8.3.5 pytest-asyncio==0.26.0 pytest-bdd==8.1.0 pytest-benchmark==5.1.0 pytest-cov==6.0.0 pytest-django==4.10.0 pytest-localserver==0.9.0.post0 pytest-mock==3.14.0 pytest-rerunfailures==15.0 pytz==2025.2 referencing==0.36.2 rpds-py==0.24.0 six==1.17.0 structlog==25.2.0 toml==0.10.2 tomli==2.2.1 typing_extensions==4.13.0 urllib3==2.3.0 WebOb==1.8.9 Werkzeug==3.1.3 zipp==3.21.0
name: nodeenv 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 - asynctest==0.13.0 - atomicwrites==1.4.1 - attrs==25.3.0 - certifi==2025.1.31 - configparser==7.2.0 - contextlib2==21.6.0 - coverage==7.8.0 - docutils==0.21.2 - ecs-logging==2.2.0 - exceptiongroup==1.2.2 - gherkin-official==29.0.0 - glob2==0.7 - greenlet==3.1.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - jsonschema==4.23.0 - jsonschema-specifications==2024.10.1 - logbook==1.8.1 - mako==1.3.9 - markupsafe==3.0.2 - mock==5.2.0 - more-itertools==10.6.0 - msgpack-python==0.5.6 - packaging==24.2 - parse==1.20.2 - parse-type==0.6.4 - pep8==1.7.1 - pluggy==1.5.0 - py-cpuinfo==9.0.0 - pyrsistent==0.20.0 - pytest==8.3.5 - pytest-asyncio==0.26.0 - pytest-bdd==8.1.0 - pytest-benchmark==5.1.0 - pytest-cov==6.0.0 - pytest-django==4.10.0 - pytest-localserver==0.9.0.post0 - pytest-mock==3.14.0 - pytest-rerunfailures==15.0 - pytz==2025.2 - referencing==0.36.2 - rpds-py==0.24.0 - six==1.17.0 - structlog==25.2.0 - toml==0.10.2 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 - webob==1.8.9 - werkzeug==3.1.3 - zipp==3.21.0 prefix: /opt/conda/envs/nodeenv
[ "tests/nodeenv_test.py::test_compare_versions" ]
[ "tests/nodeenv_test.py::test_smoke" ]
[ "tests/nodeenv_test.py::test_gets_a_hrefs_trivial", "tests/nodeenv_test.py::test_gets_a_hrefs_nodejs_org", "tests/nodeenv_test.py::test_gets_a_hrefs_iojs_org", "tests/nodeenv_test.py::test_get_node_versions_iojs", "tests/nodeenv_test.py::test_get_node_versions_nodejs", "tests/nodeenv_test.py::test_print_node_versions_iojs", "tests/nodeenv_test.py::test_print_node_versions_node" ]
[]
BSD License
59
[ "nodeenv.py" ]
[ "nodeenv.py" ]
ipython__ipython-8030
d4e786e20631074a8713f78c7103dcab0c72b840
2015-03-12 18:02:36
ff02638008de8c90ca5f177e559efa048a2557a0
diff --git a/IPython/config/loader.py b/IPython/config/loader.py index 12752d000..196ed4932 100644 --- a/IPython/config/loader.py +++ b/IPython/config/loader.py @@ -11,6 +11,7 @@ import re import sys import json +from ast import literal_eval from IPython.utils.path import filefind, get_ipython_dir from IPython.utils import py3compat @@ -487,7 +488,7 @@ def _exec_config_str(self, lhs, rhs): """execute self.config.<lhs> = <rhs> * expands ~ with expanduser - * tries to assign with raw eval, otherwise assigns with just the string, + * tries to assign with literal_eval, otherwise assigns with just the string, allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not* equivalent are `--C.a=4` and `--C.a='4'`. """ @@ -496,8 +497,8 @@ def _exec_config_str(self, lhs, rhs): # Try to see if regular Python syntax will work. This # won't handle strings as the quote marks are removed # by the system shell. - value = eval(rhs) - except (NameError, SyntaxError): + value = literal_eval(rhs) + except (NameError, SyntaxError, ValueError): # This case happens if the rhs is a string. value = rhs
commandline parser can't handle --something="all" It seems that parsing `all` will convert it to the `all()` function and an error is shown: ```python knitpy_aliases.update({ 'to' : 'KnitpyApp.export_format', [...] }) class KnitpyApp(BaseIPythonApplication): # '--to' ends up here export_format = CaselessStrEnum(VALID_OUTPUT_FORMATS+["all"], default_value=DEFAULT_OUTPUT_FORMAT, config=True, help="""The export format to be used.""" ) ``` and then when I call it: ``` $ knitpy --to="all" example\hello.pymd # or `--to=all` [...] [KnitpyApp] CRITICAL | The 'export_format' trait of a KnitpyApp instance must be any of [u'pdf', u'docx', u'html', u'all'] or None, but a value of <built-in fun ction all> <type 'builtin_function_or_method'> was specified. ```
ipython/ipython
diff --git a/IPython/config/tests/test_loader.py b/IPython/config/tests/test_loader.py index a5fc91dd8..dc8f2573d 100644 --- a/IPython/config/tests/test_loader.py +++ b/IPython/config/tests/test_loader.py @@ -33,7 +33,7 @@ c.a=10 c.b=20 c.Foo.Bar.value=10 -c.Foo.Bam.value=list(range(10)) # list() is just so it's the same on Python 3 +c.Foo.Bam.value=list(range(10)) c.D.C.value='hi there' """ @@ -188,14 +188,23 @@ def test_argv(self): class TestKeyValueCL(TestCase): klass = KeyValueConfigLoader + def test_eval(self): + cl = self.klass(log=log) + config = cl.load_config('--Class.str_trait=all --Class.int_trait=5 --Class.list_trait=["hello",5]'.split()) + self.assertEqual(config.Class.str_trait, 'all') + self.assertEqual(config.Class.int_trait, 5) + self.assertEqual(config.Class.list_trait, ["hello", 5]) + def test_basic(self): cl = self.klass(log=log) - argv = ['--'+s.strip('c.') for s in pyfile.split('\n')[2:-1]] + argv = [ '--' + s[2:] for s in pyfile.split('\n') if s.startswith('c.') ] + print(argv) config = cl.load_config(argv) self.assertEqual(config.a, 10) self.assertEqual(config.b, 20) self.assertEqual(config.Foo.Bar.value, 10) - self.assertEqual(config.Foo.Bam.value, list(range(10))) + # non-literal expressions are not evaluated + self.assertEqual(config.Foo.Bam.value, 'list(range(10))') self.assertEqual(config.D.C.value, 'hi there') def test_expanduser(self):
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 1 }, "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@d4e786e20631074a8713f78c7103dcab0c72b840#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_loader.py::TestKeyValueCL::test_basic", "IPython/config/tests/test_loader.py::TestKeyValueCL::test_eval", "IPython/config/tests/test_loader.py::TestArgParseKVCL::test_basic" ]
[]
[ "IPython/config/tests/test_loader.py::TestFileCL::test_collision", "IPython/config/tests/test_loader.py::TestFileCL::test_json", "IPython/config/tests/test_loader.py::TestFileCL::test_python", "IPython/config/tests/test_loader.py::TestFileCL::test_v2raise", "IPython/config/tests/test_loader.py::TestArgParseCL::test_add_arguments", "IPython/config/tests/test_loader.py::TestArgParseCL::test_argv", "IPython/config/tests/test_loader.py::TestArgParseCL::test_basic", "IPython/config/tests/test_loader.py::TestKeyValueCL::test_expanduser", "IPython/config/tests/test_loader.py::TestKeyValueCL::test_extra_args", "IPython/config/tests/test_loader.py::TestKeyValueCL::test_unicode_alias", "IPython/config/tests/test_loader.py::TestKeyValueCL::test_unicode_args", "IPython/config/tests/test_loader.py::TestArgParseKVCL::test_eval", "IPython/config/tests/test_loader.py::TestArgParseKVCL::test_expanduser", "IPython/config/tests/test_loader.py::TestArgParseKVCL::test_expanduser2", "IPython/config/tests/test_loader.py::TestArgParseKVCL::test_extra_args", "IPython/config/tests/test_loader.py::TestArgParseKVCL::test_unicode_alias", "IPython/config/tests/test_loader.py::TestArgParseKVCL::test_unicode_args", "IPython/config/tests/test_loader.py::TestConfig::test_auto_section", "IPython/config/tests/test_loader.py::TestConfig::test_builtin", "IPython/config/tests/test_loader.py::TestConfig::test_contains", "IPython/config/tests/test_loader.py::TestConfig::test_deepcopy", "IPython/config/tests/test_loader.py::TestConfig::test_fromdict", "IPython/config/tests/test_loader.py::TestConfig::test_fromdictmerge", "IPython/config/tests/test_loader.py::TestConfig::test_fromdictmerge2", "IPython/config/tests/test_loader.py::TestConfig::test_getattr_not_section", "IPython/config/tests/test_loader.py::TestConfig::test_getattr_private_missing", "IPython/config/tests/test_loader.py::TestConfig::test_getattr_section", "IPython/config/tests/test_loader.py::TestConfig::test_getitem_not_section", "IPython/config/tests/test_loader.py::TestConfig::test_getitem_section", "IPython/config/tests/test_loader.py::TestConfig::test_merge_copies", "IPython/config/tests/test_loader.py::TestConfig::test_merge_doesnt_exist", "IPython/config/tests/test_loader.py::TestConfig::test_merge_exists", "IPython/config/tests/test_loader.py::TestConfig::test_pickle_config", "IPython/config/tests/test_loader.py::TestConfig::test_setget" ]
[]
BSD 3-Clause "New" or "Revised" License
60
[ "IPython/config/loader.py" ]
[ "IPython/config/loader.py" ]
marshmallow-code__marshmallow-168
4748220fc19c2b7389a1f3474e123fe285154538
2015-03-14 19:14:05
4748220fc19c2b7389a1f3474e123fe285154538
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 81840c5e..589c12fe 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -6,8 +6,9 @@ Changelog Features: -- *Backwards-incompatible*: When ``many=True``, the errors dictionary returned by ``dump`` and ``load`` will be keyed on the indices of invalid items in the (de)serialized collection (:issue:`75`). Add the ``index_errors`` class Meta option. +- *Backwards-incompatible*: When ``many=True``, the errors dictionary returned by ``dump`` and ``load`` will be keyed on the indices of invalid items in the (de)serialized collection (:issue:`75`). Add the ``index_errors`` class Meta option to disable this behavior. - *Backwards-incompatible*: By default, required fields will raise a ValidationError if the input is ``None`` or the empty string. The ``allow_none`` and ``allow_blank`` parameters can override this behavior. +- In ``strict`` mode, a ``ValidationError`` is raised. Error messages are accessed via the ``ValidationError's`` ``messages`` attribute (:issue:`128`). - Add ``allow_none`` parameter to ``fields.Field``. If ``False`` (the default), validation fails when the field's value is ``None`` (:issue:`76`, :issue:`111`). If ``allow_none`` is ``True``, ``None`` is considered valid and will deserialize to ``None``. - Add ``allow_blank`` parameter to ``fields.String`` fields (incl. ``fields.URL``, ``fields.Email``). If ``False`` (the default), validation fails when the field's value is the empty string (:issue:`76`). - Schema-level validators can store error messages for multiple fields (:issue:`118`). Thanks :user:`ksesong` for the suggestion. @@ -23,6 +24,8 @@ Features: Deprecation/Removals: +- ``MarshallingError`` and ``UnmarshallingError`` error are deprecated in favor of a single ``ValidationError`` (:issue:`160`). +- Remove ``ForcedError``. - Remove support for generator functions that yield validators (:issue:`74`). Plain generators of validators are still supported. - The ``Select/Enum`` field is deprecated in favor of using `validate.OneOf` validator (:issue:`135`). - Remove legacy, pre-1.0 API (``Schema.data`` and ``Schema.errors`` properties) (:issue:`73`). diff --git a/docs/custom_fields.rst b/docs/custom_fields.rst index c0ca8673..78036cc6 100644 --- a/docs/custom_fields.rst +++ b/docs/custom_fields.rst @@ -66,8 +66,8 @@ A :class:`Function <marshmallow.fields.Function>` field will take the value of a .. _adding-context: -Adding Context to Method and Function Fields --------------------------------------------- +Adding Context to `Method` and `Function` Fields +------------------------------------------------ A :class:`Function <marshmallow.fields.Function>` or :class:`Method <marshmallow.fields.Method>` field may need information about its environment to know how to serialize a value. diff --git a/docs/extending.rst b/docs/extending.rst index 1f0fc6f3..78e4b982 100644 --- a/docs/extending.rst +++ b/docs/extending.rst @@ -82,7 +82,7 @@ Normally, unspecified field names are ignored by the validator. If you would lik Storing Errors on Specific Fields +++++++++++++++++++++++++++++++++ -If you want to store schema-level validation errors on a specific field, you can pass a field name to the :exc:`ValidationError`. +If you want to store schema-level validation errors on a specific field, you can pass a field name (or multiple field names) to the :exc:`ValidationError <marshmallow.exceptions.ValidationError>`. .. code-block:: python @@ -194,7 +194,7 @@ You can register error handlers, validators, and data handlers as optional class Extending "class Meta" Options -------------------------------- -``class Meta`` options are a way to configure and modify a :class:`Schema's <Schema>` behavior. See the :class:`API docs <Schema>` for a listing of available options. +``class Meta`` options are a way to configure and modify a :class:`Schema's <Schema>` behavior. See the :class:`API docs <Schema.Meta>` for a listing of available options. You can add custom ``class Meta`` options by subclassing :class:`SchemaOpts`. diff --git a/docs/nesting.rst b/docs/nesting.rst index 98b81e42..af31e005 100644 --- a/docs/nesting.rst +++ b/docs/nesting.rst @@ -24,7 +24,7 @@ Schemas can be nested to represent relationships between objects (e.g. foreign k self.title = title self.author = author # A User object -Use a :class:`Nested <marshmallow.fields.Nested>` field to represent the relationship, passing in nested schema class. +Use a :class:`Nested <marshmallow.fields.Nested>` field to represent the relationship, passing in a nested schema class. .. code-block:: python :emphasize-lines: 10 diff --git a/docs/quickstart.rst b/docs/quickstart.rst index 283c5b70..d657ff82 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -16,13 +16,10 @@ Let's start with a basic user "model". import datetime as dt class User(object): - def __init__(self, name, email, age=None): + def __init__(self, name, email): self.name = name self.email = email self.created_at = dt.datetime.now() - self.friends = [] - self.employer = None - self.age = age def __repr__(self): return '<User(name={self.name!r})>'.format(self=self) @@ -168,10 +165,10 @@ Validation .. code-block:: python data, errors = UserSchema().load({'email': 'foo'}) - errors # => {'email': ['foo is not a valid email address.']} + errors # => {'email': ['"foo" is not a valid email address.']} # OR, equivalently result = UserSchema().load({'email': 'foo'}) - result.errors # => {'email': ['foo is not a valid email address.']} + result.errors # => {'email': ['"foo" is not a valid email address.']} When validating a collection, the errors dictionary will be keyed on the indicies of invalid items. @@ -207,9 +204,10 @@ You can perform additional validation for a field by passing it a ``validate`` c result.errors # => {'age': ['Validator <lambda>(71.0) is False']} -Validation functions either return a boolean or raise a :exc:`ValidationError`. If a :exc:`ValidationError` is raised, its message is stored when validation fails. +Validation functions either return a boolean or raise a :exc:`ValidationError`. If a :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised, its message is stored when validation fails. .. code-block:: python + :emphasize-lines: 7,10,14 from marshmallow import Schema, fields, ValidationError @@ -228,24 +226,30 @@ Validation functions either return a boolean or raise a :exc:`ValidationError`. .. note:: - If you have multiple validations to perform, you may also pass a collection (list, tuple) or generator of callables to the ``validate`` parameter. + If you have multiple validations to perform, you may also pass a collection (list, tuple, generator) of callables. .. note:: :meth:`Schema.dump` also validates the format of its fields and returns a dictionary of errors. However, the callables passed to ``validate`` are only applied during deserialization. -.. note:: - If you set ``strict=True`` in either the Schema constructor or as a ``class Meta`` option, an error will be raised when invalid data are passed in. +``strict`` Mode ++++++++++++++++ + + If you set ``strict=True`` in either the Schema constructor or as a ``class Meta`` option, an error will be raised when invalid data are passed in. You can access the dictionary of validation errors from the `ValidationError.messages <marshmallow.exceptions.ValidationError.messages>` attribute. .. code-block:: python - UserSchema(strict=True).load({'email': 'foo'}) - # => UnmarshallingError: "foo" is not a valid email address. + from marshmallow import ValidationError + try: + UserSchema(strict=True).load({'email': 'foo'}) + except ValidationError as err: + print(err.messages)# => {'email': ['"foo" is not a valid email address.']} - Alternatively, you can also register a custom error handler function for a schema using the :func:`error_handler <Schema.error_handler>` decorator. See the :ref:`Extending Schemas <extending>` page for more info. +.. seealso:: + You can register a custom error handler function for a schema using the :func:`error_handler <Schema.error_handler>` decorator. See the :ref:`Extending Schemas <extending>` page for more info. .. seealso:: @@ -310,21 +314,21 @@ By default, `Schemas` will marshal the object attributes that are identical to t Specifying Deserialization Keys ------------------------------- -By default `Schemas` will unmarshal an input dictionary to an output dictionary whose keys are identical to the field names. However, if you are consuming data that does not exactly match your schema, you can specify additional keys to load values from. +By default `Schemas` will unmarshal an input dictionary to an output dictionary whose keys are identical to the field names. However, if you are consuming data that does not exactly match your schema, you can specify additional keys to load values by passing the `load_from` argument. .. code-block:: python :emphasize-lines: 2,3,11,12 class UserSchema(Schema): name = fields.String() - email = fields.Email(load_from='email_address') + email = fields.Email(load_from='emailAddress') data = { 'name': 'Mike', - 'email_address': '[email protected]' + 'emailAddress': '[email protected]' } - ser = UserSchema() - result, errors = ser.load(data) + s = UserSchema() + result, errors = s.load(data) #{'name': u'Mike', # 'email': '[email protected]'} @@ -361,7 +365,8 @@ Note that ``name`` will be automatically formatted as a :class:`String <marshmal class UserSchema(Schema): uppername = fields.Function(lambda obj: obj.name.upper()) class Meta: - additional = ("name", "email", "created_at") # No need to include 'uppername' + # No need to include 'uppername' + additional = ("name", "email", "created_at") Ordering Output --------------- diff --git a/docs/upgrading.rst b/docs/upgrading.rst index c18cce82..26d448ff 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -78,11 +78,88 @@ When validating a collection (i.e. when calling ``load`` or ``dump`` with ``many You can still get the pre-2.0 behavior by setting the ``index_errors`` *class Meta* option to `False`. +Use ``ValidationError`` instead of ``MarshallingError`` and ``UnmarshallingError`` +********************************************************************************** + +The :exc:`MarshallingError` and :exc:`UnmarshallingError` exceptions are deprecated in favor of a single :exc:`ValidationError <marshmallow.exceptions.ValidationError>`. Users who have written custom fields or are using ``strict`` mode will need to change their code accordingly. + +Custom Fields +------------- + +Custom fields should raise :exc:`ValidationError <marshmallow.exceptions.ValidationError>` in their `_deserialize` and `_serialize` methods when a validation error occurs. + +.. code-block:: python + :emphasize-lines: 17 + + from marshmallow import fields, ValidationError + from marshmallow.exceptions import UnmarshallingError + + # In 1.0, an UnmarshallingError was raised + class PasswordField(fields.Field): + + def _deserialize(self, val): + if not len(val) >= 6: + raise UnmarshallingError('Password to short.') + return val + + # In 2.0, an UnmarshallingError is raised + class PasswordField(fields.Field): + + def _deserialize(self, val): + if not len(val) >= 6: + raise ValidationError('Password to short.') + return val + +Handle ``ValidationError`` in strict mode +----------------------------------------- + +When using `strict` mode, you should handle `ValidationErrors` when calling `Schema.dump` and `Schema.load`. + +.. code-block:: python + :emphasize-lines: 14 + + from marshmallow import exceptions as exc + + schema = BandMemberSchema(strict=True) + + # 1.0 + try: + schema.load({'email': 'invalid-email'}) + except exc.UnmarshallingError as err: + # ... + + # 2.0 + try: + schema.load({'email': 'invalid-email'}) + except exc.ValidationError as err: + # ... + + +Accessing error messages in strict mode +*************************************** + +In 2.0, `strict` mode was improved so that you can access all error messages for a schema (rather than failing early) by accessing a `ValidationError's` ``messages`` attribute. + +.. code-block:: python + :emphasize-lines: 6 + + schema = BandMemberSchema(strict=True) + + try: + result = schema.load({'email': 'invalid'}) + except ValidationMessage as err: + print(err.messages) + # { + # 'email': ['"invalid" is not a valid email address.'], + # 'name': ['Missing data for required field.'] + # } + + Use ``OneOf`` instead of ``fields.Select`` ****************************************** -The `fields.Select` field was deprecated in favor of the newly-added `OneOf` validator. +The `fields.Select` field is deprecated in favor of the newly-added `OneOf` validator. .. code-block:: python @@ -95,6 +172,7 @@ The `fields.Select` field was deprecated in favor of the newly-added `OneOf` val # 2.0 fields.Str(validate=OneOf(['red', 'blue'])) + Upgrading to 1.2 ++++++++++++++++ diff --git a/marshmallow/exceptions.py b/marshmallow/exceptions.py index 5d38f7d5..706b28f5 100644 --- a/marshmallow/exceptions.py +++ b/marshmallow/exceptions.py @@ -1,87 +1,74 @@ # -*- coding: utf-8 -*- """Exception classes for marshmallow-related errors.""" -from marshmallow.compat import text_type, basestring +import warnings + +from marshmallow.compat import basestring class MarshmallowError(Exception): """Base class for all marshmallow-related errors.""" pass -class _WrappingException(MarshmallowError): - """Exception that wraps a different, underlying exception. Used so that - an error in serialization or deserialization can be reraised as a - :exc:`MarshmallowError <MarshmallowError>`. - """ - - def __init__(self, underlying_exception, fields=None, field_names=None): - if isinstance(underlying_exception, Exception): - self.underlying_exception = underlying_exception - else: - self.underlying_exception = None - self.fields = fields - self.field_names = field_names - super(_WrappingException, self).__init__( - text_type(underlying_exception) - ) - - -class ForcedError(_WrappingException): - """Error that always gets raised, even during serialization. - Field classes should raise this error if the error should not be stored in - the Marshaller's error dictionary and should instead be raised. - - Must be instantiated with an underlying exception. - - Example: :: - - def _serialize(self, value, key, obj): - if not isinstace(value, dict): - raise ForcedError(ValueError('Value must be a dict.')) - """ - pass - - class ValidationError(MarshmallowError): - """Raised when validation fails on a field. + """Raised when validation fails on a field. Validators and custom fields should + raise this exception. :param message: An error message, list of error messages, or dict of error messages. - :param str field: Field name (or list of field names) to store the error on. + :param list field_names: Field names to store the error on. If `None`, the error is stored in its default location. + :param list fields: `Field` objects to which the error applies. """ - def __init__(self, message, field=None): + def __init__(self, message, field_names=None, fields=None): if not isinstance(message, dict) and not isinstance(message, list): messages = [message] else: messages = message + #: String, list, or dictionary of error messages. + #: If a `dict`, the keys will be field names and the values will be lists of + #: messages. self.messages = messages - self.field = field - if isinstance(field, basestring): - self.fields = [field] - else: # field is a list or None - self.fields = field + #: List of field objects which failed validation. + self.fields = fields + if isinstance(field_names, basestring): + #: List of field_names which failed validation. + self.field_names = [field_names] + else: # fields is a list or None + self.field_names = field_names or [] MarshmallowError.__init__(self, message) -class RegistryError(ForcedError, NameError): +class RegistryError(NameError): """Raised when an invalid operation is performed on the serializer class registry. """ pass -class MarshallingError(_WrappingException): +class MarshallingError(ValidationError): """Raised in case of a marshalling error. If raised during serialization, the error is caught and the error message is stored in an ``errors`` dictionary (unless ``strict`` mode is turned on). + + .. deprecated:: 2.0.0 + Use :exc:`ValidationError` instead. """ - pass + def __init__(self, *args, **kwargs): + warnings.warn('MarshallingError is deprecated. Raise a ValidationError instead', + category=DeprecationWarning) + super(MarshallingError, self).__init__(*args, **kwargs) -class UnmarshallingError(_WrappingException): +class UnmarshallingError(ValidationError): """Raised when invalid data are passed to a deserialization function. If raised during deserialization, the error is caught and the error message is stored in an ``errors`` dictionary. + + .. deprecated:: 2.0.0 + Use :exc:`ValidationError` instead. """ - pass + def __init__(self, *args, **kwargs): + warnings.warn('UnmarshallingError is deprecated. Raise a ValidationError instead', + category=DeprecationWarning) + super(UnmarshallingError, self).__init__(*args, **kwargs) diff --git a/marshmallow/fields.py b/marshmallow/fields.py index 182b832b..e1f64618 100755 --- a/marshmallow/fields.py +++ b/marshmallow/fields.py @@ -13,13 +13,7 @@ from marshmallow import validate, utils, class_registry from marshmallow.base import FieldABC, SchemaABC from marshmallow.marshalling import null, missing from marshmallow.compat import text_type, basestring -from marshmallow.exceptions import ( - MarshallingError, - UnmarshallingError, - ForcedError, - ValidationError, -) - +from marshmallow.exceptions import ValidationError __all__ = [ 'Field', @@ -72,8 +66,8 @@ class Field(FieldABC): :param callable validate: Validator or collection of validators that are called during deserialization. Validator takes a field's input value as its only parameter and returns a boolean. - If it returns `False`, an :exc:`UnmarshallingError` is raised. - :param required: Raise an :exc:`UnmarshallingError` if the field value + If it returns `False`, an :exc:`ValidationError` is raised. + :param required: Raise an :exc:`ValidationError` if the field value is not supplied during deserialization. If not a `bool`(e.g. a `str`), the provided value will be used as the message of the :exc:`ValidationError` instead of the default message. @@ -186,27 +180,6 @@ class Field(FieldABC): if errors: raise ValidationError(errors) - def _call_and_reraise(self, func, exception_class): - """Utility method to invoke a function and raise ``exception_class`` if an error - occurs. - - :param callable func: Function to call. Must take no arguments. - :param Exception exception_class: Type of exception to raise when an error occurs. - """ - try: - return func() - # TypeErrors should be raised if fields are not declared as instances - except TypeError: - raise - # Raise ForcedErrors - except ForcedError as err: - if err.underlying_exception: - raise err.underlying_exception - else: - raise err - except ValidationError as err: - raise exception_class(err) - def _validate_missing(self, value): """Validate missing values. Raise a :exc:`ValidationError` if `value` should be considered missing. @@ -231,7 +204,7 @@ class Field(FieldABC): :param str attr: The attibute or key to get from the object. :param str obj: The object to pull the key from. :param callable accessor: Function used to pull values from ``obj``. - :raise MarshallingError: In case of formatting problem + :raise ValidationError: In case of formatting problem """ value = self.get_value(attr, obj, accessor=accessor) if value is None and self._CHECK_ATTRIBUTE: @@ -240,25 +213,22 @@ class Field(FieldABC): return self.default() else: return self.default - func = lambda: self._serialize(value, attr, obj) - return self._call_and_reraise(func, MarshallingError) + return self._serialize(value, attr, obj) def deserialize(self, value): """Deserialize ``value``. - :raise UnmarshallingError: If an invalid value is passed or if a required value + :raise ValidationError: If an invalid value is passed or if a required value is missing. """ # Validate required fields, deserialize, then validate # deserialized value - def do_deserialization(): - self._validate_missing(value) - if getattr(self, 'allow_none', False) is True and value is None: - return None - output = self._deserialize(value) - self._validate(output) - return output - return self._call_and_reraise(do_deserialization, UnmarshallingError) + self._validate_missing(value) + if getattr(self, 'allow_none', False) is True and value is None: + return None + output = self._deserialize(value) + self._validate(output) + return output # Methods for concrete classes to override. @@ -277,14 +247,14 @@ class Field(FieldABC): :param value: The value to be serialized. :param str attr: The attribute or key on the object to be serialized. :param object obj: The object the value was pulled from. - :raise MarshallingError: In case of formatting or validation failure. + :raise ValidationError: In case of formatting or validation failure. """ return value def _deserialize(self, value): """Deserialize value. Concrete :class:`Field` classes should implement this method. - :raise UnmarshallingError: In case of formatting or validation failure. + :raise ValidationError: In case of formatting or validation failure. """ return value @@ -362,9 +332,8 @@ class Nested(Field): self.__schema = schema_class(many=self.many, only=only, exclude=self.exclude) else: - raise ForcedError(ValueError('Nested fields must be passed a ' - 'Schema, not {0}.' - .format(self.nested.__class__))) + raise ValueError('Nested fields must be passed a ' + 'Schema, not {0}.'.format(self.nested.__class__)) self.__schema.ordered = getattr(self.parent, 'ordered', False) # Inherit context from parent self.__schema.context.update(getattr(self.parent, 'context', {})) @@ -496,7 +465,7 @@ class UUID(String): def _deserialize(self, value): msg = 'Could not deserialize {0!r} to a UUID object.'.format(value) - err = UnmarshallingError(getattr(self, 'error', None) or msg) + err = ValidationError(getattr(self, 'error', None) or msg) try: return uuid.UUID(value) except (ValueError, AttributeError): @@ -521,14 +490,14 @@ class Number(Field): """Return the number value for value, given this field's `num_type`.""" return self.num_type(value) - def _validated(self, value, exception_class): + def _validated(self, value): """Format the value or raise ``exception_class`` if an error occurs.""" if value is None: return self.default try: return self._format_num(value) except (TypeError, ValueError, decimal.InvalidOperation) as err: - raise exception_class(getattr(self, 'error', None) or err) + raise ValidationError(getattr(self, 'error', None) or text_type(err)) def serialize(self, attr, obj, accessor=None): """Pulls the value for the given key from the object and returns the @@ -540,10 +509,10 @@ class Number(Field): return str(ret) if self.as_string else ret def _serialize(self, value, attr, obj): - return self._validated(value, MarshallingError) + return self._validated(value) def _deserialize(self, value): - return self._validated(value, UnmarshallingError) + return self._validated(value) class Integer(Number): @@ -624,14 +593,14 @@ class Boolean(Field): try: value_str = text_type(value) except TypeError as error: - raise UnmarshallingError(error) + raise ValidationError(text_type(error)) if value_str in self.falsy: return False elif self.truthy: if value_str in self.truthy: return True else: - raise UnmarshallingError( + raise ValidationError( '{0!r} is not in {1} nor {2}'.format( value_str, self.truthy, self.falsy )) @@ -663,7 +632,7 @@ class FormattedString(Field): data = utils.to_marshallable_type(obj) return self.src_str.format(**data) except (TypeError, IndexError) as error: - raise MarshallingError(getattr(self, 'error', None) or error) + raise ValidationError(getattr(self, 'error', None) or error) class Float(Number): @@ -695,20 +664,20 @@ class Arbitrary(Number): ) super(Arbitrary, self).__init__(default=default, attribute=attribute, **kwargs) - def _validated(self, value, exception_class): + def _validated(self, value): """Format ``value`` or raise ``exception_class`` if an error occurs.""" try: if value is None: return self.default return text_type(utils.float_to_decimal(float(value))) except ValueError as ve: - raise exception_class(ve) + raise ValidationError(text_type(ve)) def _serialize(self, value, attr, obj): - return self._validated(value, MarshallingError) + return self._validated(value) def _deserialize(self, value): - return self._validated(value, UnmarshallingError) + return self._validated(value) class DateTime(Field): @@ -758,13 +727,13 @@ class DateTime(Field): try: return format_func(value, localtime=self.localtime) except (AttributeError, ValueError) as err: - raise MarshallingError(getattr(self, 'error', None) or err) + raise ValidationError(getattr(self, 'error', None) or text_type(err)) else: return value.strftime(self.dateformat) def _deserialize(self, value): msg = 'Could not deserialize {0!r} to a datetime object.'.format(value) - err = UnmarshallingError(getattr(self, 'error', None) or msg) + err = ValidationError(getattr(self, 'error', None) or msg) if not value: # Falsy values, e.g. '', None, [] are not valid raise err self.dateformat = self.dateformat or self.DEFAULT_FORMAT @@ -806,7 +775,7 @@ class Time(Field): ret = value.isoformat() except AttributeError: msg = '{0!r} cannot be formatted as a time.'.format(value) - raise MarshallingError(getattr(self, 'error', None) or msg) + raise ValidationError(getattr(self, 'error', None) or msg) if value.microsecond: return ret[:12] return ret @@ -814,7 +783,7 @@ class Time(Field): def _deserialize(self, value): """Deserialize an ISO8601-formatted time to a :class:`datetime.time` object.""" msg = 'Could not deserialize {0!r} to a time object.'.format(value) - err = UnmarshallingError(getattr(self, 'error', None) or msg) + err = ValidationError(getattr(self, 'error', None) or msg) if not value: # falsy values are invalid raise err try: @@ -833,7 +802,7 @@ class Date(Field): return value.isoformat() except AttributeError: msg = '{0} cannot be formatted as a date.'.format(repr(value)) - raise MarshallingError(getattr(self, 'error', None) or msg) + raise ValidationError(getattr(self, 'error', None) or msg) return value def _deserialize(self, value): @@ -841,7 +810,7 @@ class Date(Field): :class:`datetime.date` object. """ msg = 'Could not deserialize {0!r} to a date object.'.format(value) - err = UnmarshallingError(getattr(self, 'error', None) or msg) + err = ValidationError(getattr(self, 'error', None) or msg) if not value: # falsy values are invalid raise err try: @@ -893,14 +862,14 @@ class TimeDelta(Field): return seconds * 10**6 + value.microseconds # flake8: noqa except AttributeError: msg = '{0!r} cannot be formatted as a timedelta.'.format(value) - raise MarshallingError(getattr(self, 'error', None) or msg) + raise ValidationError(getattr(self, 'error', None) or msg) def _deserialize(self, value): try: value = int(value) except (TypeError, ValueError): msg = '{0!r} cannot be interpreted as a valid period of time.'.format(value) - raise UnmarshallingError(getattr(self, 'error', None) or msg) + raise ValidationError(getattr(self, 'error', None) or msg) kwargs = {self.precision: value} @@ -908,7 +877,7 @@ class TimeDelta(Field): return dt.timedelta(**kwargs) except OverflowError: msg = '{0!r} cannot be interpreted as a valid period of time.'.format(value) - raise UnmarshallingError(getattr(self, 'error', None) or msg) + raise ValidationError(getattr(self, 'error', None) or msg) class Fixed(Number): @@ -930,21 +899,15 @@ class Fixed(Number): *args, **kwargs) self.precision = decimal.Decimal('0.' + '0' * (decimals - 1) + '1') - def _serialize(self, value, attr, obj): - return self._validated(value, MarshallingError) - - def _deserialize(self, value): - return self._validated(value, UnmarshallingError) - - def _validated(self, value, exception_class): + def _validated(self, value): if value is None: value = self.default try: dvalue = utils.float_to_decimal(float(value)) except (TypeError, ValueError) as err: - raise exception_class(getattr(self, 'error', None) or err) + raise ValidationError(getattr(self, 'error', None) or text_type(err)) if not dvalue.is_normal() and dvalue != utils.ZERO_DECIMAL: - raise exception_class( + raise ValidationError( getattr(self, 'error', None) or 'Invalid Fixed precision number.' ) return utils.decimal_to_fixed(dvalue, self.precision) @@ -1067,7 +1030,7 @@ class Method(Field): if len(utils.get_func_args(method)) > 2: if self.parent.context is None: msg = 'No context available for Method field {0!r}'.format(attr) - raise MarshallingError(msg) + raise ValidationError(msg) return method(obj, self.parent.context) else: return method(obj) @@ -1111,7 +1074,7 @@ class Function(Field): if len(utils.get_func_args(self.func)) > 1: if self.parent.context is None: msg = 'No context available for Function field {0!r}'.format(attr) - raise MarshallingError(msg) + raise ValidationError(msg) return self.func(obj, self.parent.context) else: return self.func(obj) @@ -1135,7 +1098,7 @@ class Select(Field): :param str error: Error message stored upon validation failure. :param kwargs: The same keyword arguments that :class:`Fixed` receives. - :raise: MarshallingError if attribute's value is not one of the given choices. + :raise: ValidationError if attribute's value is not one of the given choices. """ def __init__(self, choices, default=None, attribute=None, error=None, **kwargs): warnings.warn( @@ -1146,19 +1109,19 @@ class Select(Field): self.choices = choices return super(Select, self).__init__(default, attribute, error, **kwargs) - def _validated(self, value, exception_class): + def _validated(self, value): if value not in self.choices: - raise exception_class( + raise ValidationError( getattr(self, 'error', None) or "{0!r} is not a valid choice for this field.".format(value) ) return value def _serialize(self, value, attr, obj): - return self._validated(value, MarshallingError) + return self._validated(value) def _deserialize(self, value): - return self._validated(value, UnmarshallingError) + return self._validated(value) class QuerySelect(Field): @@ -1223,7 +1186,7 @@ class QuerySelect(Field): return value error = getattr(self, 'error', None) or 'Invalid object.' - raise MarshallingError(error) + raise ValidationError(error) def _deserialize(self, value): for key, result in self.pairs(): @@ -1231,7 +1194,7 @@ class QuerySelect(Field): return result error = getattr(self, 'error', None) or 'Invalid key.' - raise UnmarshallingError(error) + raise ValidationError(error) class QuerySelectList(QuerySelect): @@ -1261,7 +1224,7 @@ class QuerySelectList(QuerySelect): keys.remove(item) except ValueError: error = getattr(self, 'error', None) or 'Invalid objects.' - raise MarshallingError(error) + raise ValidationError(error) return items @@ -1277,7 +1240,7 @@ class QuerySelectList(QuerySelect): index = keys.index(val) except ValueError: error = getattr(self, 'error', None) or 'Invalid keys.' - raise UnmarshallingError(error) + raise ValidationError(error) else: del keys[index] items.append(results.pop(index)) diff --git a/marshmallow/marshalling.py b/marshmallow/marshalling.py index a1f47cb4..ffcb3a67 100644 --- a/marshmallow/marshalling.py +++ b/marshmallow/marshalling.py @@ -14,8 +14,6 @@ from marshmallow import base, utils from marshmallow.compat import text_type, iteritems from marshmallow.exceptions import ( ValidationError, - MarshallingError, - UnmarshallingError, ) __all__ = [ @@ -42,10 +40,7 @@ class _Missing(_Null): return '<marshmallow.marshalling.missing>' -# Singleton that represents an empty value. Used as the default for Nested -# fields so that `Field._call_with_validation` is invoked, even when the -# object to serialize has the nested attribute set to None. Therefore, -# `RegistryErrors` are properly raised. +# Singleton that represents an empty value. null = _Null() # Singleton value that indicates that a field's value is missing from input @@ -54,63 +49,64 @@ null = _Null() missing = _Missing() -def _call_and_store(getter_func, data, field_name, field_obj, errors_dict, - exception_class, strict=False, index=None): - """Helper method for DRYing up logic in the :meth:`Marshaller.serialize` and - :meth:`Unmarshaller.deserialize` methods. Call ``getter_func`` with ``data`` as its - argument, and store any errors of type ``exception_class`` in ``error_dict``. - - :param callable getter_func: Function for getting the serialized/deserialized - value from ``data``. - :param data: The data passed to ``getter_func``. - :param str field_name: Field name. - :param FieldABC field_obj: Field object that performs the - serialization/deserialization behavior. - :param dict errors_dict: Dictionary to store errors on. - :param type exception_class: Exception class that will be caught during - serialization/deserialization. Errors of this type will be stored - in ``errors_dict``. - :param int index: Index of the item being validated, if validating a collection, - otherwise `None`. - """ - try: - value = getter_func(data) - except exception_class as err: # Store errors - if strict: - err.field = field_obj - err.field_name = field_name - raise err - # Warning: Mutation! - if index is not None: - errors = {} - errors_dict[index] = errors - else: - errors = errors_dict - # Warning: Mutation! - if (hasattr(err, 'underlying_exception') and - isinstance(err.underlying_exception, ValidationError)): - validation_error = err.underlying_exception - if isinstance(validation_error.messages, dict): - errors[field_name] = validation_error.messages +class ErrorStore(object): + + def __init__(self): + #: Dictionary of errors stored during serialization + self.errors = {} + #: List of `Field` objects which have validation errors + self.error_fields = [] + #: List of field_names which have validation errors + self.error_field_names = [] + #: True while (de)serializing a collection + self._pending = False + + def reset_errors(self): + self.errors = {} + self.error_field_names = [] + self.error_fields = [] + + def call_and_store(self, getter_func, data, field_name, field_obj, index=None): + """Call ``getter_func`` with ``data`` as its argument, and store any `ValidationErrors`. + + :param callable getter_func: Function for getting the serialized/deserialized + value from ``data``. + :param data: The data passed to ``getter_func``. + :param str field_name: Field name. + :param FieldABC field_obj: Field object that performs the + serialization/deserialization behavior. + :param int index: Index of the item being validated, if validating a collection, + otherwise `None`. + """ + try: + value = getter_func(data) + except ValidationError as err: # Store validation errors + self.error_fields.append(field_obj) + self.error_field_names.append(field_name) + if index is not None: + errors = {} + self.errors[index] = errors else: - errors.setdefault(field_name, []).extend(validation_error.messages) - else: - errors.setdefault(field_name, []).append(text_type(err)) - value = None - except TypeError: - # field declared as a class, not an instance - if (isinstance(field_obj, type) and - issubclass(field_obj, base.FieldABC)): - msg = ('Field for "{0}" must be declared as a ' - 'Field instance, not a class. ' - 'Did you mean "fields.{1}()"?' - .format(field_name, field_obj.__name__)) - raise TypeError(msg) - raise - return value - - -class Marshaller(object): + errors = self.errors + # Warning: Mutation! + if isinstance(err.messages, dict): + errors[field_name] = err.messages + else: + errors.setdefault(field_name, []).extend(err.messages) + value = None + except TypeError: + # field declared as a class, not an instance + if (isinstance(field_obj, type) and + issubclass(field_obj, base.FieldABC)): + msg = ('Field for "{0}" must be declared as a ' + 'Field instance, not a class. ' + 'Did you mean "fields.{1}()"?' + .format(field_name, field_obj.__name__)) + raise TypeError(msg) + raise + return value + +class Marshaller(ErrorStore): """Callable class responsible for serializing data and storing errors. :param str prefix: Optional prefix that will be prepended to all the @@ -118,10 +114,7 @@ class Marshaller(object): """ def __init__(self, prefix=''): self.prefix = prefix - #: Dictionary of errors stored during serialization - self.errors = {} - #: True while serializing a collection - self.__pending = False + ErrorStore.__init__(self) def serialize(self, obj, fields_dict, many=False, strict=False, skip_missing=False, accessor=None, dict_class=dict, index_errors=True, index=None): @@ -147,29 +140,26 @@ class Marshaller(object): Renamed from ``marshal``. """ # Reset errors dict if not serializing a collection - if not self.__pending: - self.errors = {} + if not self._pending: + self.reset_errors() if many and obj is not None: - self.__pending = True + self._pending = True ret = [self.serialize(d, fields_dict, many=False, strict=strict, dict_class=dict_class, accessor=accessor, skip_missing=skip_missing, index=idx, index_errors=index_errors) for idx, d in enumerate(obj)] - self.__pending = False + self._pending = False return ret items = [] for attr_name, field_obj in iteritems(fields_dict): key = ''.join([self.prefix, attr_name]) getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor) - value = _call_and_store( + value = self.call_and_store( getter_func=getter, data=obj, field_name=key, field_obj=field_obj, - errors_dict=self.errors, - exception_class=MarshallingError, - strict=strict, index=(index if index_errors else None) ) skip_conds = ( @@ -180,22 +170,23 @@ class Marshaller(object): if any(skip_conds): continue items.append((key, value)) + if self.errors and strict: + raise ValidationError( + self.errors, + field_names=self.error_field_names, + fields=self.error_fields + ) return dict_class(items) # Make an instance callable __call__ = serialize -class Unmarshaller(object): +class Unmarshaller(ErrorStore): """Callable class responsible for deserializing data and storing errors. .. versionadded:: 1.0.0 """ - def __init__(self): - #: Dictionary of errors stored during deserialization - self.errors = {} - #: True while deserializing a collection - self.__pending = False def _validate(self, validators, output, raw_data, fields_dict, strict=False): """Perform schema-level validation. Stores errors if ``strict`` is `False`. @@ -214,15 +205,12 @@ class Unmarshaller(object): )) except ValidationError as err: # Store or reraise errors - if err.fields: - field_names = err.fields + if err.field_names: + field_names = err.field_names field_objs = [fields_dict[each] for each in field_names] else: field_names = ['_schema'] field_objs = [] - if strict: - raise UnmarshallingError(err, fields=field_objs, - field_names=field_names) for field_name in field_names: if isinstance(err.messages, (list, tuple)): # self.errors[field_name] may be a dict if schemas are nested @@ -236,6 +224,12 @@ class Unmarshaller(object): self.errors.setdefault(field_name, []).append(err.messages) else: self.errors.setdefault(field_name, []).append(text_type(err)) + if strict: + raise ValidationError( + self.errors, + fields=field_objs, + field_names=field_names + ) return output def deserialize(self, data, fields_dict, many=False, validators=None, @@ -261,16 +255,16 @@ class Unmarshaller(object): :return: A dictionary of the deserialized data. """ # Reset errors if not deserializing a collection - if not self.__pending: - self.errors = {} + if not self._pending: + self.reset_errors() if many and data is not None: - self.__pending = True + self._pending = True ret = [self.deserialize(d, fields_dict, many=False, validators=validators, preprocess=preprocess, postprocess=postprocess, strict=strict, dict_class=dict_class, index=idx, index_errors=index_errors) for idx, d in enumerate(data)] - self.__pending = False + self._pending = False return ret raw_data = data if data is not None: @@ -287,14 +281,11 @@ class Unmarshaller(object): raw_value = _miss() if callable(_miss) else _miss if raw_value is missing and not field_obj.required: continue - value = _call_and_store( + value = self.call_and_store( getter_func=field_obj.deserialize, data=raw_value, field_name=key, field_obj=field_obj, - errors_dict=self.errors, - exception_class=UnmarshallingError, - strict=strict, index=(index if index_errors else None) ) if raw_value is not missing: @@ -311,6 +302,12 @@ class Unmarshaller(object): validators = validators or [] ret = self._validate(validators, ret, raw_data, fields_dict=fields_dict, strict=strict) + if self.errors and strict: + raise ValidationError( + self.errors, + field_names=self.error_field_names, + fields=self.error_fields + ) if postprocess: postprocess = postprocess or [] for func in postprocess:
Remove MarshallingError and UnmarshallingError in favor of a single ValidationError Currently, `MarshallingError` and `UnmarshallingError` signal that an error should be stored in the `errors` dictionary during marshalling and unmarshalling. These exceptions only served a purpose prior to commit https://github.com/marshmallow-code/marshmallow/commit/00a18667b5a7a6a630d07062693e50007eefa5c8, when all exceptions were caught and reraised as (Un)MarshallingErrors. Now, they are only raised when a validation error occurs. I propose to remove these exception classes in favor of a single `ValidationError`. Doing so would reduce the API and make accessing error messages when using `strict` mode much cleaner. **Current**: ```python from marshmallow.exceptions import MarshallingError, UnmarshallingError, ValidationError schema = MySchema(strict=True) try: schema.dump(some_obj) except MarshallingError as err: if isinstance(err.underlying_error, ValidationError): messages = err.underlying_error.messages # ... try: schema.load(some_obj) except UnmarshallingError as err: if isinstance(err.underlying_error, ValidationError): messages = err.underlying_error.messages # ... ``` **Proposed**: ```python from marshmallow.exceptions import ValidationError schema = MySchema(strict=True) try: schema.dump(some_obj) except ValidationError as err: messages = err.messages # ... try: schema.load(some_obj) except ValidationError as err: messages = err.messages # ... ``` This could be implemented in conjunction with https://github.com/marshmallow-code/marshmallow/issues/128 . **WARNING**: This would be a major breaking change for people using `strict` mode.
marshmallow-code/marshmallow
diff --git a/tests/base.py b/tests/base.py index 55980f5b..f4beca08 100644 --- a/tests/base.py +++ b/tests/base.py @@ -6,7 +6,8 @@ import uuid import pytz from marshmallow import Schema, fields -from marshmallow.exceptions import MarshallingError +from marshmallow.compat import text_type +from marshmallow.exceptions import ValidationError central = pytz.timezone("US/Central") @@ -160,7 +161,7 @@ class UserSchema(Schema): try: return obj.age > 80 except TypeError as te: - raise MarshallingError(te) + raise ValidationError(text_type(te)) def make_object(self, data): return User(**data) @@ -181,7 +182,7 @@ class UserMetaSchema(Schema): try: return obj.age > 80 except TypeError as te: - raise MarshallingError(te) + raise ValidationError(te) class Meta: fields = ('name', 'age', 'created', 'updated', 'id', 'homepage', diff --git a/tests/test_deserialization.py b/tests/test_deserialization.py index 731fb438..99744563 100644 --- a/tests/test_deserialization.py +++ b/tests/test_deserialization.py @@ -6,7 +6,7 @@ import decimal import pytest from marshmallow import fields, utils, Schema -from marshmallow.exceptions import UnmarshallingError, ValidationError +from marshmallow.exceptions import ValidationError from marshmallow.compat import text_type, basestring from tests.base import ( @@ -42,7 +42,7 @@ class TestDeserializingNone: field = FieldClass(choices=['foo', 'bar']) else: field = FieldClass() - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize(None) assert 'Field may not be null.' in str(excinfo) @@ -65,15 +65,15 @@ class TestFieldDeserialization: ]) def test_invalid_float_field_deserialization(self, in_val): field = fields.Float() - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(in_val) def test_integer_field_deserialization(self): field = fields.Integer() assert field.deserialize('42') == 42 - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('42.0') - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('bad') def test_decimal_field_deserialization(self): @@ -90,9 +90,9 @@ class TestFieldDeserialization: assert field.deserialize(m2) == decimal.Decimal('12.355') assert isinstance(field.deserialize(m3), decimal.Decimal) assert field.deserialize(m3) == decimal.Decimal(1) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(m4) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(m5) def test_decimal_field_with_places(self): @@ -109,9 +109,9 @@ class TestFieldDeserialization: assert field.deserialize(m2) == decimal.Decimal('12.4') assert isinstance(field.deserialize(m3), decimal.Decimal) assert field.deserialize(m3) == decimal.Decimal(1) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(m4) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(m5) def test_decimal_field_with_places_and_rounding(self): @@ -128,9 +128,9 @@ class TestFieldDeserialization: assert field.deserialize(m2) == decimal.Decimal('12.3') assert isinstance(field.deserialize(m3), decimal.Decimal) assert field.deserialize(m3) == decimal.Decimal(1) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(m4) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(m5) def test_decimal_field_deserialization_string(self): @@ -147,9 +147,9 @@ class TestFieldDeserialization: assert field.deserialize(m2) == decimal.Decimal('12.355') assert isinstance(field.deserialize(m3), decimal.Decimal) assert field.deserialize(m3) == decimal.Decimal(1) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(m4) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(m5) def test_string_field_deserialization(self): @@ -187,7 +187,7 @@ class TestFieldDeserialization: class MyBoolean(fields.Boolean): truthy = set(['yep']) field = MyBoolean() - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(in_val) def test_arbitrary_field_deserialization(self): @@ -204,7 +204,7 @@ class TestFieldDeserialization: ]) def test_invalid_datetime_deserialization(self, in_value): field = fields.DateTime() - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize(in_value) msg = 'Could not deserialize {0!r} to a datetime object.'.format(in_value) assert msg in str(excinfo) @@ -255,7 +255,7 @@ class TestFieldDeserialization: ]) def test_invalid_time_field_deserialization(self, in_data): field = fields.Time() - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize(in_data) msg = 'Could not deserialize {0!r} to a time object.'.format(in_data) assert msg in str(excinfo) @@ -268,7 +268,7 @@ class TestFieldDeserialization: def test_fixed_field_deserialize_invalid_value(self): field = fields.Fixed(decimals=3) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('badvalue') def test_timedelta_field_deserialization(self): @@ -322,7 +322,7 @@ class TestFieldDeserialization: ]) def test_invalid_timedelta_field_deserialization(self, in_value): field = fields.TimeDelta(fields.TimeDelta.DAYS) - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize(in_value) msg = '{0!r} cannot be interpreted as a valid period of time.'.format(in_value) assert msg in str(excinfo) @@ -343,7 +343,7 @@ class TestFieldDeserialization: ]) def test_invalid_date_field_deserialization(self, in_value): field = fields.Date() - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize(in_value) msg = 'Could not deserialize {0!r} to a date object.'.format(in_value) assert msg in str(excinfo) @@ -355,10 +355,10 @@ class TestFieldDeserialization: def test_url_field_deserialization(self): field = fields.Url() assert field.deserialize('https://duckduckgo.com') == 'https://duckduckgo.com' - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('badurl') # Relative URLS not allowed by default - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('/foo/bar') def test_relative_url_field_deserialization(self): @@ -368,7 +368,7 @@ class TestFieldDeserialization: def test_email_field_deserialization(self): field = fields.Email() assert field.deserialize('[email protected]') == '[email protected]' - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('invalidemail') def test_function_field_deserialization_is_noop_by_default(self): @@ -397,7 +397,7 @@ class TestFieldDeserialization: ]) def test_invalid_uuid_deserialization(self, in_value): field = fields.UUID() - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize(in_value) msg = 'Could not deserialize {0!r} to a UUID object.'.format(in_value) assert msg in str(excinfo) @@ -441,7 +441,7 @@ class TestFieldDeserialization: def test_enum_field_deserialization(self): field = fields.Enum(['red', 'blue']) assert field.deserialize('red') == 'red' - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('notvalid') def test_query_select_field_func_key_deserialization(self): @@ -451,9 +451,9 @@ class TestFieldDeserialization: assert field.deserialize('bar a') == DummyModel('a') assert field.deserialize('bar b') == DummyModel('b') assert field.deserialize('bar c') == DummyModel('c') - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('bar d') - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('c') assert list(field.keys()) == ['bar ' + ch for ch in 'abc'] assert list(field.results()) == [DummyModel(ch) for ch in 'abc'] @@ -469,9 +469,9 @@ class TestFieldDeserialization: assert field.deserialize('a') == DummyModel('a') assert field.deserialize('b') == DummyModel('b') assert field.deserialize('c') == DummyModel('c') - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('d') - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('bar d') assert list(field.keys()) == [ch for ch in 'abc'] assert list(field.results()) == [DummyModel(ch) for ch in 'abc'] @@ -489,9 +489,9 @@ class TestFieldDeserialization: assert field.deserialize(['bar d', 'bar e', 'bar e']) == \ [DummyModel('d'), DummyModel('e'), DummyModel('e')] assert field.deserialize([]) == [] - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(['a', 'b', 'f']) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(['a', 'b', 'b']) def test_query_select_list_field_string_key_deserialization(self): @@ -503,16 +503,16 @@ class TestFieldDeserialization: assert field.deserialize(['d', 'e', 'e']) == \ [DummyModel('d'), DummyModel('e'), DummyModel('e')] assert field.deserialize([]) == [] - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(['a', 'b', 'f']) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(['a', 'b', 'b']) def test_fixed_list_field_deserialization(self): field = fields.List(fields.Fixed(3)) nums = (1, 2, 3) assert field.deserialize(nums) == ['1.000', '2.000', '3.000'] - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize((1, 2, 'invalid')) def test_datetime_list_field_deserialization(self): @@ -533,16 +533,16 @@ class TestFieldDeserialization: def test_list_field_deserialize_invalid_value(self): field = fields.List(fields.DateTime) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('badvalue') def test_field_deserialization_with_user_validator_function(self): field = fields.String(validate=lambda s: s.lower() == 'valid') assert field.deserialize('Valid') == 'Valid' - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize('invalid') assert 'Validator <lambda>(invalid) is False' in str(excinfo) - assert type(excinfo.value.underlying_exception) == ValidationError + assert type(excinfo.value) == ValidationError def test_field_deserialization_with_user_validator_class_that_returns_bool(self): class MyValidator(object): @@ -553,7 +553,7 @@ class TestFieldDeserialization: field = fields.Field(validate=MyValidator()) assert field.deserialize('valid') == 'valid' - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize('invalid') assert 'Validator MyValidator(invalid) is False' in str(excinfo) @@ -573,14 +573,14 @@ class TestFieldDeserialization: assert field.deserialize('Valid') == 'Valid' # validator returns False, so nothing validates field2 = fields.String(validate=lambda s: False) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field2.deserialize('invalid') def test_field_deserialization_with_validator_with_nonascii_input(self): field = fields.String(validate=lambda s: False) - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize(u'привет') - assert type(excinfo.value.underlying_exception) == ValidationError + assert type(excinfo.value) == ValidationError def test_field_deserialization_with_user_validators(self): validators_gen = (func for func in (lambda s: s.lower() == 'valid', @@ -596,13 +596,13 @@ class TestFieldDeserialization: for field in m_colletion_type: assert field.deserialize('Valid') == 'Valid' - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize('invalid') assert 'Validator <lambda>(invalid) is False' in str(excinfo) def test_field_deserialization_with_custom_error_message(self): field = fields.String(validate=lambda s: s.lower() == 'valid', error='Bad value.') - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: field.deserialize('invalid') assert 'Bad value.' in str(excinfo) @@ -833,7 +833,7 @@ class TestSchemaDeserialization: 'age': -1, } v = Validator(strict=True) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): v.load(bad_data) def test_strict_mode_many(self): @@ -842,7 +842,7 @@ class TestSchemaDeserialization: {'email': 'bad', 'colors': 'pizza', 'age': -1} ] v = Validator(strict=True, many=True) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): v.load(bad_data) def test_strict_mode_deserialization_with_multiple_validators(self): @@ -852,7 +852,7 @@ class TestSchemaDeserialization: 'age': -1, } v = Validators(strict=True) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): v.load(bad_data) def test_uncaught_validation_errors_are_stored(self): @@ -931,7 +931,7 @@ class TestValidation: field = fields.Integer(validate=lambda x: 18 <= x <= 24) out = field.deserialize('20') assert out == 20 - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(25) @pytest.mark.parametrize('field', [ @@ -942,7 +942,7 @@ class TestValidation: def test_integer_with_validators(self, field): out = field.deserialize('20') assert out == 20 - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(25) @pytest.mark.parametrize('field', [ @@ -952,20 +952,20 @@ class TestValidation: ]) def test_float_with_validators(self, field): assert field.deserialize(3.14) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize(4.2) def test_string_validator(self): field = fields.String(validate=lambda n: len(n) == 3) assert field.deserialize('Joe') == 'Joe' - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('joseph') def test_function_validator(self): field = fields.Function(lambda d: d.name.upper(), validate=lambda n: len(n) == 3) assert field.deserialize('joe') - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('joseph') @pytest.mark.parametrize('field', [ @@ -978,7 +978,7 @@ class TestValidation: ]) def test_function_validators(self, field): assert field.deserialize('joe') - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): field.deserialize('joseph') def test_method_validator(self): @@ -989,7 +989,7 @@ class TestValidation: def get_name(self, val): return val.upper() assert MethodSerializer(strict=True).load({'name': 'joe'}) - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: MethodSerializer(strict=True).load({'name': 'joseph'}) assert 'is False' in str(excinfo) diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 5ee74a23..dbbb1778 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- +import pytest from marshmallow.exceptions import ValidationError, MarshallingError, UnmarshallingError -from marshmallow import fields +from marshmallow import fields, Schema class TestValidationError: @@ -19,9 +20,11 @@ class TestValidationError: err = ValidationError(messages) assert err.messages == messages - def test_can_store_field_name(self): - err = ValidationError('invalid email', field='email') - assert err.field == 'email' + def test_can_store_field_names(self): + err = ValidationError('invalid email', field_names='email') + assert err.field_names == ['email'] + err = ValidationError('invalid email', field_names=['email']) + assert err.field_names == ['email'] def test_str(self): err = ValidationError('invalid email') @@ -33,6 +36,9 @@ class TestValidationError: class TestMarshallingError: + def test_deprecated(self): + pytest.deprecated_call(MarshallingError, 'foo') + def test_can_store_field_and_field_name(self): field_name = 'foo' field = fields.Str() @@ -41,8 +47,24 @@ class TestMarshallingError: assert err.fields == [field] assert err.field_names == [field_name] + def test_can_be_raised_by_custom_field(self): + class MyField(fields.Field): + def _serialize(self, val, attr, obj): + raise MarshallingError('oops') + + class MySchema(Schema): + foo = MyField() + + s = MySchema() + result = s.dump({'foo': 42}) + assert 'foo' in result.errors + assert result.errors['foo'] == ['oops'] + class TestUnmarshallingError: + def test_deprecated(self): + pytest.deprecated_call(UnmarshallingError, 'foo') + def test_can_store_field_and_field_name(self): field_name = 'foo' field = fields.Str() @@ -50,3 +72,15 @@ class TestUnmarshallingError: field_names=[field_name]) assert err.fields == [field] assert err.field_names == [field_name] + + def test_can_be_raised_by_validator(self): + def validator(val): + raise UnmarshallingError('oops') + + class MySchema(Schema): + foo = fields.Field(validate=[validator]) + + s = MySchema() + result = s.load({'foo': 42}) + assert 'foo' in result.errors + assert result.errors['foo'] == ['oops'] diff --git a/tests/test_marshalling.py b/tests/test_marshalling.py index 128e8a82..b75bb814 100644 --- a/tests/test_marshalling.py +++ b/tests/test_marshalling.py @@ -4,7 +4,7 @@ import pytest from marshmallow import fields from marshmallow.marshalling import Marshaller, Unmarshaller, null, missing -from marshmallow.exceptions import UnmarshallingError +from marshmallow.exceptions import ValidationError from tests.base import User @@ -88,7 +88,7 @@ class TestUnmarshaller: {'email': 'foobar'}, {'email': '[email protected]'} ] - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: unmarshal(users, {'email': fields.Email()}, strict=True, many=True) assert 'foobar' in str(excinfo) @@ -150,7 +150,7 @@ class TestUnmarshaller: assert user['age'] == 71 def test_deserialize_strict_raises_error(self, unmarshal): - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): unmarshal( {'email': 'invalid', 'name': 'Mick'}, {'email': fields.Email(), 'name': fields.String()}, diff --git a/tests/test_options.py b/tests/test_options.py index e0d98b1b..c42673b3 100644 --- a/tests/test_options.py +++ b/tests/test_options.py @@ -2,7 +2,7 @@ import pytest from marshmallow import fields, Schema -from marshmallow.exceptions import UnmarshallingError +from marshmallow.exceptions import ValidationError from marshmallow.compat import OrderedDict from tests.base import * # noqa @@ -14,7 +14,7 @@ class TestStrict: strict = True def test_strict_meta_option(self): - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): self.StrictUserSchema().load({'email': 'foo.com'}) def test_strict_meta_option_is_inherited(self): @@ -24,7 +24,7 @@ class TestStrict: class ChildStrictSchema(self.StrictUserSchema): pass - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError): ChildStrictSchema().load({'email': 'foo.com'}) diff --git a/tests/test_schema.py b/tests/test_schema.py index bad349a6..1e81ebe1 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -32,7 +32,7 @@ def test_serializer_dump(user): # Change strict mode s.strict = True bad_user = User(name='Monty', age='badage') - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): s.dump(bad_user) def test_dump_returns_dict_of_errors(): @@ -42,15 +42,21 @@ def test_dump_returns_dict_of_errors(): assert 'age' in errors -def test_dump_with_strict_mode_raises_error(): - s = UserSchema(strict=True) [email protected]('SchemaClass', +[ + UserSchema, UserMetaSchema +]) +def test_dump_with_strict_mode_raises_error(SchemaClass): + s = SchemaClass(strict=True) bad_user = User(name='Monty', email='invalid-email') - with pytest.raises(MarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: s.dump(bad_user) exc = excinfo.value - assert type(exc.field) == fields.Email - assert exc.field_name == 'email' + assert type(exc.fields[0]) == fields.Email + assert exc.field_names[0] == 'email' + assert type(exc.messages) == dict + assert exc.messages == {'email': ['"invalid-email" is not a valid email address.']} def test_dump_resets_errors(): class MySchema(Schema): @@ -64,6 +70,52 @@ def test_dump_resets_errors(): assert len(result.errors['email']) == 1 assert '__invalid' in result.errors['email'][0] +def test_load_resets_errors(): + class MySchema(Schema): + email = fields.Email() + + schema = MySchema() + result = schema.load({'name': 'Joe', 'email': 'notvalid'}) + assert len(result.errors['email']) == 1 + assert 'notvalid' in result.errors['email'][0] + result = schema.load({'name': 'Joe', 'email': '__invalid'}) + assert len(result.errors['email']) == 1 + assert '__invalid' in result.errors['email'][0] + +def test_dump_resets_error_fields(): + class MySchema(Schema): + email = fields.Email() + + schema = MySchema(strict=True) + with pytest.raises(ValidationError) as excinfo: + schema.dump(User('Joe', email='notvalid')) + exc = excinfo.value + assert len(exc.fields) == 1 + assert len(exc.field_names) == 1 + + with pytest.raises(ValidationError) as excinfo: + schema.dump(User('Joe', email='__invalid')) + + assert len(exc.fields) == 1 + assert len(exc.field_names) == 1 + +def test_load_resets_error_fields(): + class MySchema(Schema): + email = fields.Email() + + schema = MySchema(strict=True) + with pytest.raises(ValidationError) as excinfo: + schema.load({'name': 'Joe', 'email': 'not-valid'}) + exc = excinfo.value + assert len(exc.fields) == 1 + assert len(exc.field_names) == 1 + + with pytest.raises(ValidationError) as excinfo: + schema.load({'name': 'Joe', 'email': '__invalid'}) + + assert len(exc.fields) == 1 + assert len(exc.field_names) == 1 + def test_dump_many(): s = UserSchema() u1, u2 = User('Mick'), User('Keith') @@ -227,8 +279,11 @@ class TestValidate: def test_validate_strict(self): s = UserSchema(strict=True) - with pytest.raises(UnmarshallingError): + with pytest.raises(ValidationError) as excinfo: s.validate({'email': 'bad-email'}) + exc = excinfo.value + assert exc.messages == {'email': ['"bad-email" is not a valid email address.']} + assert type(exc.fields[0]) == fields.Email def test_validate_required(self): class MySchema(Schema): @@ -901,18 +956,19 @@ class TestSchemaValidator: def test_schema_validation_error_with_stict_stores_correct_field_name(self): def validate_with_bool(schema, in_vals): - return False + raise ValidationError('oops') class ValidatingSchema(Schema): __validators__ = [validate_with_bool] field_a = fields.Field() schema = ValidatingSchema(strict=True) - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: schema.load({'field_a': 1}) exc = excinfo.value assert exc.fields == [] assert exc.field_names == ['_schema'] + assert exc.messages == {'_schema': ['oops']} def test_schema_validation_error_with_strict_when_field_is_specified(self): def validate_with_err(schema, inv_vals): @@ -924,7 +980,7 @@ class TestSchemaValidator: field_b = fields.Field() schema = ValidatingSchema(strict=True) - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: schema.load({'field_a': 1}) exc = excinfo.value assert type(exc.fields[0]) == fields.Str @@ -946,6 +1002,18 @@ class TestSchemaValidator: assert result.errors['field_a'] == ['Something went wrong.'] assert result.errors['field_b'] == ['Something went wrong.'] + schema = ValidatingSchema(strict=True) + with pytest.raises(ValidationError) as excinfo: + schema.load({'field_a': 1}) + err = excinfo.value + assert type(err.fields[0]) == fields.Str + assert type(err.fields[1]) == fields.Field + assert err.field_names == ['field_a', 'field_b'] + assert err.messages == { + 'field_a': ['Something went wrong.'], + 'field_b': ['Something went wrong.'] + } + def test_validator_with_strict(self): def validate_schema(instance, input_vals): assert isinstance(instance, Schema) @@ -958,14 +1026,14 @@ class TestSchemaValidator: schema = ValidatingSchema(strict=True) in_data = {'field_a': 2, 'field_b': 1} - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: schema.load(in_data) assert 'Schema validator' in str(excinfo) assert 'is False' in str(excinfo) # underlying exception is a ValidationError exc = excinfo.value - assert isinstance(exc.underlying_exception, ValidationError) + assert isinstance(exc, ValidationError) def test_validator_defined_by_decorator(self): class ValidatingSchema(Schema): @@ -1458,7 +1526,7 @@ class TestNestedSchema: assert "collaborators" not in errors def test_nested_strict(self): - with pytest.raises(UnmarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: _, errors = BlogSchema(strict=True).load( {'title': "Monty's blog", 'user': {'name': 'Monty', 'email': 'foo'}} ) @@ -1679,7 +1747,7 @@ class TestContext: owner = User('Joe') serializer = UserMethodContextSchema(strict=True) serializer.context = None - with pytest.raises(MarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: serializer.dump(owner) msg = 'No context available for Method field {0!r}'.format('is_owner') @@ -1694,7 +1762,7 @@ class TestContext: serializer = UserFunctionContextSchema(strict=True) # no context serializer.context = None - with pytest.raises(MarshallingError) as excinfo: + with pytest.raises(ValidationError) as excinfo: serializer.dump(owner) msg = 'No context available for Function field {0!r}'.format('is_collab') assert msg in str(excinfo) @@ -1723,23 +1791,6 @@ class TestContext: result = ser.dump(obj) assert result.data['inner']['likes_bikes'] is True - -def raise_marshalling_value_error(): - try: - raise ValueError('Foo bar') - except ValueError as error: - raise MarshallingError(error) - -class TestMarshallingError: - - def test_saves_underlying_exception(self): - with pytest.raises(MarshallingError) as excinfo: - raise_marshalling_value_error() - assert 'Foo bar' in str(excinfo) - error = excinfo.value - assert isinstance(error.underlying_exception, ValueError) - - def test_error_gets_raised_if_many_is_omitted(user): class BadSchema(Schema): # forgot to set many=True diff --git a/tests/test_serialization.py b/tests/test_serialization.py index 10564d20..41ae0ae4 100644 --- a/tests/test_serialization.py +++ b/tests/test_serialization.py @@ -7,7 +7,7 @@ import decimal import pytest from marshmallow import Schema, fields, utils -from marshmallow.exceptions import MarshallingError +from marshmallow.exceptions import ValidationError from marshmallow.compat import text_type, basestring from tests.base import User, DummyModel @@ -92,9 +92,9 @@ class TestFieldSerialization: assert field.serialize('m3', user) == decimal.Decimal(1) assert isinstance(field.serialize('m4', user), decimal.Decimal) assert field.serialize('m4', user) == decimal.Decimal() - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m5', user) - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m6', user) field = fields.Decimal(1) @@ -106,9 +106,9 @@ class TestFieldSerialization: assert field.serialize('m3', user) == decimal.Decimal(1) assert isinstance(field.serialize('m4', user), decimal.Decimal) assert field.serialize('m4', user) == decimal.Decimal() - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m5', user) - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m6', user) field = fields.Decimal(1, decimal.ROUND_DOWN) @@ -120,9 +120,9 @@ class TestFieldSerialization: assert field.serialize('m3', user) == decimal.Decimal(1) assert isinstance(field.serialize('m4', user), decimal.Decimal) assert field.serialize('m4', user) == decimal.Decimal() - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m5', user) - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m6', user) def test_decimal_field_string(self, user): @@ -142,9 +142,9 @@ class TestFieldSerialization: assert field.serialize('m3', user) == '1' assert isinstance(field.serialize('m4', user), basestring) assert field.serialize('m4', user) == '0' - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m5', user) - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m6', user) field = fields.Decimal(1, as_string=True) @@ -156,9 +156,9 @@ class TestFieldSerialization: assert field.serialize('m3', user) == '1.0' assert isinstance(field.serialize('m4', user), basestring) assert field.serialize('m4', user) == '0' - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m5', user) - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m6', user) field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) @@ -170,9 +170,9 @@ class TestFieldSerialization: assert field.serialize('m3', user) == '1.0' assert isinstance(field.serialize('m4', user), basestring) assert field.serialize('m4', user) == '0' - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m5', user) - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('m6', user) def test_function_with_uncallable_param(self): @@ -182,13 +182,13 @@ class TestFieldSerialization: def test_email_field_validates(self, user): user.email = 'bademail' field = fields.Email() - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('email', user) def test_url_field_validates(self, user): user.homepage = 'badhomepage' field = fields.URL() - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('homepage', user) def test_method_field_with_method_missing(self): @@ -309,7 +309,7 @@ class TestFieldSerialization: field = fields.Select(['male', 'female', 'transexual', 'asexual']) assert field.serialize("sex", user) == "male" invalid = User('foo', sex='alien') - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('sex', invalid) def test_datetime_list_field(self): @@ -321,7 +321,7 @@ class TestFieldSerialization: def test_list_field_with_error(self): obj = DateTimeList(['invaliddate']) field = fields.List(fields.DateTime) - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('dtimes', obj) def test_datetime_list_serialize_single_value(self): @@ -366,7 +366,7 @@ class TestFieldSerialization: def test_arbitrary_field_invalid_value(self, user): field = fields.Arbitrary() - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): user.age = 'invalidvalue' field.serialize('age', user) @@ -383,7 +383,7 @@ class TestFieldSerialization: def test_fixed_field_invalid_value(self, user): field = fields.Fixed() - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): user.age = 'invalidvalue' field.serialize('age', user) @@ -413,7 +413,7 @@ class TestFieldSerialization: assert field.serialize('du1', user) == 'bar a' assert field.serialize('du2', user) == 'bar b' assert field.serialize('du3', user) == 'bar c' - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('du4', user) def test_query_select_field_string_key(self, user): @@ -427,7 +427,7 @@ class TestFieldSerialization: assert field.serialize('du1', user) == 'a' assert field.serialize('du2', user) == 'b' assert field.serialize('du3', user) == 'c' - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('du4', user) def test_query_select_list_field_func_key(self, user): @@ -442,9 +442,9 @@ class TestFieldSerialization: assert field.serialize('du1', user) == ['bar a', 'bar c', 'bar b'] assert field.serialize('du2', user) == ['bar d', 'bar e', 'bar e'] assert field.serialize('du5', user) == [] - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('du3', user) - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('du4', user) def test_query_select_list_field_string_key(self, user): @@ -459,9 +459,9 @@ class TestFieldSerialization: assert field.serialize('du1', user) == ['a', 'c', 'b'] assert field.serialize('du2', user) == ['d', 'e', 'e'] assert field.serialize('du5', user) == [] - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('du3', user) - with pytest.raises(MarshallingError): + with pytest.raises(ValidationError): field.serialize('du4', user)
{ "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": 1 }, "num_modified_files": 9 }
1.2
{ "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@4748220fc19c2b7389a1f3474e123fe285154538#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_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[LocalDateTime]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Fixed]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FormattedString]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Select]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value3]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", "tests/test_deserialization.py::TestFieldDeserialization::test_fixed_field_deserialize_invalid_value", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_query_select_field_func_key_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_query_select_field_string_key_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_query_select_list_field_func_key_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_query_select_list_field_string_key_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_fixed_list_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_value", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", "tests/test_deserialization.py::TestSchemaDeserialization::test_strict_mode_deserialization", "tests/test_deserialization.py::TestSchemaDeserialization::test_strict_mode_many", "tests/test_deserialization.py::TestSchemaDeserialization::test_strict_mode_deserialization_with_multiple_validators", "tests/test_deserialization.py::TestValidation::test_integer_with_validator", "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", "tests/test_deserialization.py::TestValidation::test_string_validator", "tests/test_deserialization.py::TestValidation::test_function_validator", "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", "tests/test_deserialization.py::TestValidation::test_method_validator", "tests/test_exceptions.py::TestValidationError::test_can_store_field_names", "tests/test_exceptions.py::TestMarshallingError::test_deprecated", "tests/test_exceptions.py::TestUnmarshallingError::test_deprecated", "tests/test_marshalling.py::TestUnmarshaller::test_strict_mode_many", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_strict_raises_error", "tests/test_options.py::TestStrict::test_strict_meta_option", "tests/test_options.py::TestStrict::test_strict_meta_option_is_inherited", "tests/test_schema.py::test_serializer_dump", "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_error_fields", "tests/test_schema.py::test_load_resets_error_fields", "tests/test_schema.py::TestValidate::test_validate_strict", "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::TestNestedSchema::test_nested_strict", "tests/test_schema.py::TestContext::test_method_field_raises_error_when_context_not_available", "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", "tests/test_serialization.py::TestFieldSerialization::test_email_field_validates", "tests/test_serialization.py::TestFieldSerialization::test_url_field_validates", "tests/test_serialization.py::TestFieldSerialization::test_select_field", "tests/test_serialization.py::TestFieldSerialization::test_list_field_with_error", "tests/test_serialization.py::TestFieldSerialization::test_arbitrary_field_invalid_value", "tests/test_serialization.py::TestFieldSerialization::test_fixed_field_invalid_value", "tests/test_serialization.py::TestFieldSerialization::test_query_select_field_func_key", "tests/test_serialization.py::TestFieldSerialization::test_query_select_field_string_key", "tests/test_serialization.py::TestFieldSerialization::test_query_select_list_field_func_key", "tests/test_serialization.py::TestFieldSerialization::test_query_select_list_field_string_key" ]
[]
[ "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[LocalDateTime]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Fixed]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FormattedString]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Select]", "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_empty_list", "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", "tests/test_deserialization.py::TestFieldDeserialization::test_arbitrary_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_rfc_datetime_field_deserialization[rfc]", "tests/test_deserialization.py::TestFieldDeserialization::test_rfc_datetime_field_deserialization[rfc822]", "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[iso]", "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[iso8601]", "tests/test_deserialization.py::TestFieldDeserialization::test_localdatetime_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_fixed_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_price_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_single_value", "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", "tests/test_deserialization.py::TestSchemaDeserialization::test_make_object", "tests/test_deserialization.py::TestSchemaDeserialization::test_make_object_many", "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", "tests/test_deserialization.py::TestSchemaDeserialization::test_none_deserialization", "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_load_from_param", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_returns_errors", "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_returns_errors_with_multiple_validators", "tests/test_deserialization.py::TestSchemaDeserialization::test_uncaught_validation_errors_are_stored", "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", "tests/test_deserialization.py::test_required_field_failure[String]", "tests/test_deserialization.py::test_required_field_failure[Integer]", "tests/test_deserialization.py::test_required_field_failure[Boolean]", "tests/test_deserialization.py::test_required_field_failure[Float]", "tests/test_deserialization.py::test_required_field_failure[Number]", "tests/test_deserialization.py::test_required_field_failure[DateTime]", "tests/test_deserialization.py::test_required_field_failure[LocalDateTime]", "tests/test_deserialization.py::test_required_field_failure[Time]", "tests/test_deserialization.py::test_required_field_failure[Date]", "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", "tests/test_deserialization.py::test_required_field_failure[Fixed]", "tests/test_deserialization.py::test_required_field_failure[Url]", "tests/test_deserialization.py::test_required_field_failure[Email]", "tests/test_deserialization.py::test_required_field_failure[UUID]", "tests/test_deserialization.py::test_required_field_failure[Decimal]", "tests/test_deserialization.py::test_required_enum", "tests/test_deserialization.py::test_required_message_can_be_changed[My", "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", "tests/test_exceptions.py::TestValidationError::test_str", "tests/test_exceptions.py::TestMarshallingError::test_can_store_field_and_field_name", "tests/test_exceptions.py::TestMarshallingError::test_can_be_raised_by_custom_field", "tests/test_exceptions.py::TestUnmarshallingError::test_can_store_field_and_field_name", "tests/test_exceptions.py::TestUnmarshallingError::test_can_be_raised_by_validator", "tests/test_marshalling.py::test_null_is_falsy", "tests/test_marshalling.py::test_missing_is_falsy", "tests/test_marshalling.py::TestMarshaller::test_prefix", "tests/test_marshalling.py::TestMarshaller::test_marshalling_generator", "tests/test_marshalling.py::TestMarshaller::test_default_to_missing", "tests/test_marshalling.py::TestMarshaller::test_serialize_fields_with_load_only_param", "tests/test_marshalling.py::TestMarshaller::test_stores_indices_of_errors_when_many_equals_true", "tests/test_marshalling.py::TestMarshaller::test_doesnt_store_errors_when_index_errors_equals_false", "tests/test_marshalling.py::TestUnmarshaller::test_extra_data_is_ignored", "tests/test_marshalling.py::TestUnmarshaller::test_stores_errors", "tests/test_marshalling.py::TestUnmarshaller::test_stores_indices_of_errors_when_many_equals_true", "tests/test_marshalling.py::TestUnmarshaller::test_doesnt_store_errors_when_index_errors_equals_false", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize", "tests/test_marshalling.py::TestUnmarshaller::test_extra_fields", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_many", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_stores_errors", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_attribute_param", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_load_from_param", "tests/test_marshalling.py::TestUnmarshaller::test_deserialize_fields_with_dump_only_param", "tests/test_marshalling.py::TestUnmarshaller::test_preprocessing_function", "tests/test_marshalling.py::TestUnmarshaller::test_preprocessing_many", "tests/test_options.py::TestSkipMissingOption::test_skip_missing_opt", "tests/test_options.py::TestSkipMissingOption::test_missing_values_are_skipped", "tests/test_options.py::TestSkipMissingOption::test_missing_values_are_skipped_with_many", "tests/test_options.py::TestSkipMissingOption::test_missing_string_values_can_be_skipped", "tests/test_options.py::TestSkipMissingOption::test_empty_list_can_be_skipped", "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited", "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exlude_arg_is_maintained", "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", "tests/test_options.py::TestIncludeOption::test_fields_are_added", "tests/test_options.py::TestIncludeOption::test_ordered_included", "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", "tests/test_schema.py::test_serializing_basic_object[UserSchema]", "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", "tests/test_schema.py::test_dump_returns_dict_of_errors", "tests/test_schema.py::test_dump_resets_errors", "tests/test_schema.py::test_load_resets_errors", "tests/test_schema.py::test_dump_many", "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_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_no_implicit_list_handling", "tests/test_schema.py::test_inheriting_serializer", "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_default", "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_integer_default", "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_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_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_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_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_raw_data_validation", "tests/test_schema.py::TestSchemaValidator::test_nested_schema_validators", "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_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_default", "tests/test_schema.py::TestNestedSchema::test_nested_none_default", "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_only_takes_precedence_over_exclude", "tests/test_schema.py::TestNestedSchema::test_list_field", "tests/test_schema.py::TestNestedSchema::test_nested_load_many", "tests/test_schema.py::TestNestedSchema::test_nested_errors", "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::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_fields_context", "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", "tests/test_schema.py::test_error_gets_raised_if_many_is_omitted", "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::TestEmpty::test_required_string_field_missing", "tests/test_schema.py::TestEmpty::test_required_string_field_failure[None-Field", "tests/test_schema.py::TestEmpty::test_required_string_field_failure[-Field", "tests/test_schema.py::TestEmpty::test_allow_none_param", "tests/test_schema.py::TestEmpty::test_allow_blank_param", "tests/test_schema.py::TestEmpty::test_allow_none_custom_message", "tests/test_schema.py::TestEmpty::test_allow_blank_custom_message", "tests/test_schema.py::TestEmpty::test_allow_blank_string_fields[String]", "tests/test_schema.py::TestEmpty::test_allow_blank_string_fields[Url]", "tests/test_schema.py::TestEmpty::test_allow_blank_string_fields[Email]", "tests/test_schema.py::TestEmpty::test_allow_blank_on_serialization[Url]", "tests/test_schema.py::TestEmpty::test_allow_blank_on_serialization[Email]", "tests/test_serialization.py::TestFieldSerialization::test_default", "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", "tests/test_serialization.py::TestFieldSerialization::test_number[None-0.0]", "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_default", "tests/test_serialization.py::TestFieldSerialization::test_callable_default", "tests/test_serialization.py::TestFieldSerialization::test_function_field", "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", "tests/test_serialization.py::TestFieldSerialization::test_integer_field", "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", "tests/test_serialization.py::TestFieldSerialization::test_function_with_uncallable_param", "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", "tests/test_serialization.py::TestFieldSerialization::test_datetime_deserializes_to_iso_by_default", "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_rfc822[rfc]", "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_rfc822[rfc822]", "tests/test_serialization.py::TestFieldSerialization::test_localdatetime_rfc_field", "tests/test_serialization.py::TestFieldSerialization::test_datetime_iso8601[iso]", "tests/test_serialization.py::TestFieldSerialization::test_datetime_iso8601[iso8601]", "tests/test_serialization.py::TestFieldSerialization::test_localdatetime_iso", "tests/test_serialization.py::TestFieldSerialization::test_datetime_format", "tests/test_serialization.py::TestFieldSerialization::test_string_field", "tests/test_serialization.py::TestFieldSerialization::test_formattedstring_field", "tests/test_serialization.py::TestFieldSerialization::test_string_field_defaults_to_empty_string", "tests/test_serialization.py::TestFieldSerialization::test_time_field", "tests/test_serialization.py::TestFieldSerialization::test_date_field", "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_serialize_single_value", "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_empty_list_by_default", "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_default_none", "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", "tests/test_serialization.py::TestFieldSerialization::test_arbitrary_field", "tests/test_serialization.py::TestFieldSerialization::test_arbitrary_field_default", "tests/test_serialization.py::TestFieldSerialization::test_fixed_field", "tests/test_serialization.py::TestFieldSerialization::test_fixed_field_default", "tests/test_serialization.py::TestFieldSerialization::test_price_field", "tests/test_serialization.py::TestFieldSerialization::test_price_field_default", "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", "tests/test_serialization.py::test_serializing_named_tuple", "tests/test_serialization.py::test_serializing_named_tuple_with_meta" ]
[]
MIT License
63
[ "docs/quickstart.rst", "docs/nesting.rst", "marshmallow/marshalling.py", "CHANGELOG.rst", "docs/extending.rst", "docs/upgrading.rst", "marshmallow/exceptions.py", "marshmallow/fields.py", "docs/custom_fields.rst" ]
[ "docs/quickstart.rst", "docs/nesting.rst", "marshmallow/marshalling.py", "CHANGELOG.rst", "docs/extending.rst", "docs/upgrading.rst", "marshmallow/exceptions.py", "marshmallow/fields.py", "docs/custom_fields.rst" ]
networkx__networkx-1407
33c39a05c03d699d76c4e4194ffeb9d818ee3934
2015-03-15 02:57:54
965640e7399c669980243d8b162c4521339f294f
diff --git a/networkx/algorithms/connectivity/connectivity.py b/networkx/algorithms/connectivity/connectivity.py index ef31f33a9..bf7916160 100644 --- a/networkx/algorithms/connectivity/connectivity.py +++ b/networkx/algorithms/connectivity/connectivity.py @@ -454,12 +454,13 @@ def all_pairs_node_connectivity(G, nbunch=None, flow_func=None): else: nbunch = set(nbunch) - if G.is_directed(): + directed = G.is_directed() + if directed: iter_func = itertools.permutations else: iter_func = itertools.combinations - all_pairs = dict.fromkeys(nbunch, dict()) + all_pairs = {n: {} for n in nbunch} # Reuse auxiliary digraph and residual network H = build_auxiliary_node_connectivity(G) @@ -470,6 +471,8 @@ def all_pairs_node_connectivity(G, nbunch=None, flow_func=None): for u, v in iter_func(nbunch, 2): K = local_node_connectivity(G, u, v, **kwargs) all_pairs[u][v] = K + if not directed: + all_pairs[v][u] = K return all_pairs
bug in all_pairs_node_connectivity For building the dictionary to store the results I was using: ```python all_pairs = dict.fromkeys(nbunch, dict()) ``` Which is using refrences to the same dict for each node. The tests did not catch this (ouch!), I found out while working on #1405. I'll send a PR fixing it, by using: ```python all_pairs = {n: {} for n in nbunch} ``` I'll also add tests.
networkx/networkx
diff --git a/networkx/algorithms/connectivity/tests/test_connectivity.py b/networkx/algorithms/connectivity/tests/test_connectivity.py index 93420ae76..6b0b8af4a 100644 --- a/networkx/algorithms/connectivity/tests/test_connectivity.py +++ b/networkx/algorithms/connectivity/tests/test_connectivity.py @@ -279,7 +279,58 @@ def test_edge_connectivity_flow_vs_stoer_wagner(): G = graph_func() assert_equal(nx.stoer_wagner(G)[0], nx.edge_connectivity(G)) -class TestConnectivityPairs(object): + +class TestAllPairsNodeConnectivity: + + def setUp(self): + self.path = nx.path_graph(7) + self.directed_path = nx.path_graph(7, create_using=nx.DiGraph()) + self.cycle = nx.cycle_graph(7) + self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph()) + self.gnp = nx.gnp_random_graph(30, 0.1) + self.directed_gnp = nx.gnp_random_graph(30, 0.1, directed=True) + self.K20 = nx.complete_graph(20) + self.K10 = nx.complete_graph(10) + self.K5 = nx.complete_graph(5) + self.G_list = [self.path, self.directed_path, self.cycle, + self.directed_cycle, self.gnp, self.directed_gnp, self.K10, + self.K5, self.K20] + + def test_cycles(self): + K_undir = nx.all_pairs_node_connectivity(self.cycle) + for source in K_undir: + for target, k in K_undir[source].items(): + assert_true(k == 2) + K_dir = nx.all_pairs_node_connectivity(self.directed_cycle) + for source in K_dir: + for target, k in K_dir[source].items(): + assert_true(k == 1) + + def test_complete(self): + for G in [self.K10, self.K5, self.K20]: + K = nx.all_pairs_node_connectivity(G) + for source in K: + for target, k in K[source].items(): + assert_true(k == len(G)-1) + + def test_paths(self): + K_undir = nx.all_pairs_node_connectivity(self.path) + for source in K_undir: + for target, k in K_undir[source].items(): + assert_true(k == 1) + K_dir = nx.all_pairs_node_connectivity(self.directed_path) + for source in K_dir: + for target, k in K_dir[source].items(): + if source < target: + assert_true(k == 1) + else: + assert_true(k == 0) + + def test_all_pairs_connectivity_nbunch(self): + G = nx.complete_graph(5) + nbunch = [0, 2, 3] + C = nx.all_pairs_node_connectivity(G, nbunch=nbunch) + assert_equal(len(C), len(nbunch)) def test_all_pairs_connectivity_icosahedral(self): G = nx.icosahedral_graph() @@ -290,9 +341,9 @@ class TestConnectivityPairs(object): G = nx.Graph() nodes = [0, 1, 2, 3] G.add_path(nodes) - A = dict.fromkeys(G, dict()) + A = {n: {} for n in G} for u, v in itertools.combinations(nodes,2): - A[u][v] = nx.node_connectivity(G, u, v) + A[u][v] = A[v][u] = nx.node_connectivity(G, u, v) C = nx.all_pairs_node_connectivity(G) assert_equal(sorted((k, sorted(v)) for k, v in A.items()), sorted((k, sorted(v)) for k, v in C.items())) @@ -301,7 +352,7 @@ class TestConnectivityPairs(object): G = nx.DiGraph() nodes = [0, 1, 2, 3] G.add_path(nodes) - A = dict.fromkeys(G, dict()) + A = {n: {} for n in G} for u, v in itertools.permutations(nodes, 2): A[u][v] = nx.node_connectivity(G, u, v) C = nx.all_pairs_node_connectivity(G) @@ -311,9 +362,9 @@ class TestConnectivityPairs(object): def test_all_pairs_connectivity_nbunch(self): G = nx.complete_graph(5) nbunch = [0, 2, 3] - A = dict.fromkeys(nbunch, dict()) + A = {n: {} for n in nbunch} for u, v in itertools.combinations(nbunch, 2): - A[u][v] = nx.node_connectivity(G, u, v) + A[u][v] = A[v][u] = nx.node_connectivity(G, u, v) C = nx.all_pairs_node_connectivity(G, nbunch=nbunch) assert_equal(sorted((k, sorted(v)) for k, v in A.items()), sorted((k, sorted(v)) for k, v in C.items())) @@ -321,9 +372,9 @@ class TestConnectivityPairs(object): def test_all_pairs_connectivity_nbunch_iter(self): G = nx.complete_graph(5) nbunch = [0, 2, 3] - A = dict.fromkeys(nbunch, dict()) + A = {n: {} for n in nbunch} for u, v in itertools.combinations(nbunch, 2): - A[u][v] = nx.node_connectivity(G, u, v) + A[u][v] = A[v][u] = nx.node_connectivity(G, u, v) C = nx.all_pairs_node_connectivity(G, nbunch=iter(nbunch)) assert_equal(sorted((k, sorted(v)) for k, v in A.items()), sorted((k, sorted(v)) for k, v in C.items()))
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
1.9
{ "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@33c39a05c03d699d76c4e4194ffeb9d818ee3934#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/connectivity/tests/test_connectivity.py::TestAllPairsNodeConnectivity::test_all_pairs_connectivity_nbunch", "networkx/algorithms/connectivity/tests/test_connectivity.py::TestAllPairsNodeConnectivity::test_all_pairs_connectivity", "networkx/algorithms/connectivity/tests/test_connectivity.py::TestAllPairsNodeConnectivity::test_all_pairs_connectivity_directed", "networkx/algorithms/connectivity/tests/test_connectivity.py::TestAllPairsNodeConnectivity::test_all_pairs_connectivity_nbunch_iter" ]
[ "networkx/algorithms/connectivity/tests/test_connectivity.py::TestAllPairsNodeConnectivity::test_cycles", "networkx/algorithms/connectivity/tests/test_connectivity.py::TestAllPairsNodeConnectivity::test_complete", "networkx/algorithms/connectivity/tests/test_connectivity.py::TestAllPairsNodeConnectivity::test_paths" ]
[ "networkx/algorithms/connectivity/tests/test_connectivity.py::test_average_connectivity", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_average_connectivity_directed", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_articulation_points", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_brandes_erlebach", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_white_harary_1", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_white_harary_2", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_complete_graphs", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_empty_graphs", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_petersen", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_tutte", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_dodecahedral", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_octahedral", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_icosahedral", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_missing_source", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_missing_target", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_edge_missing_source", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_edge_missing_target", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_not_weakly_connected", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_not_connected", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_directed_edge_connectivity", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_cutoff", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_invalid_auxiliary", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_interface_only_source", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_interface_only_target", "networkx/algorithms/connectivity/tests/test_connectivity.py::test_edge_connectivity_flow_vs_stoer_wagner", "networkx/algorithms/connectivity/tests/test_connectivity.py::TestAllPairsNodeConnectivity::test_all_pairs_connectivity_icosahedral" ]
[]
BSD 3-Clause
64
[ "networkx/algorithms/connectivity/connectivity.py" ]
[ "networkx/algorithms/connectivity/connectivity.py" ]
klen__graphite-beacon-32
66ec0720ca5a3a9d43a63fa0a60b3eb6e26e4157
2015-03-17 20:27:02
66ec0720ca5a3a9d43a63fa0a60b3eb6e26e4157
diff --git a/graphite_beacon/core.py b/graphite_beacon/core.py index 88fadfa..adef419 100644 --- a/graphite_beacon/core.py +++ b/graphite_beacon/core.py @@ -2,6 +2,7 @@ import os from re import compile as re, M import json +import logging from tornado import ioloop, log from .alerts import BaseAlert @@ -56,7 +57,7 @@ class Reactor(object): for config in self.options.pop('include', []): self.include_config(config) - LOGGER.setLevel(self.options.get('logging', 'info').upper()) + LOGGER.setLevel(_get_numeric_log_level(self.options.get('logging', 'info'))) registry.clean() self.handlers = {'warning': set(), 'critical': set(), 'normal': set()} @@ -123,3 +124,33 @@ class Reactor(object): for handler in self.handlers.get(level, []): handler.notify(level, alert, value, target=target, ntype=ntype, rule=rule) + + +_LOG_LEVELS = { + 'DEBUG': logging.DEBUG, + 'INFO': logging.INFO, + 'WARN': logging.WARN, + 'WARNING': logging.WARNING, + 'ERROR': logging.ERROR, + 'CRITICAL': logging.CRITICAL +} + + +def _get_numeric_log_level(name): + """Convert a textual log level to the numeric constants expected by the + :meth:`logging.Logger.setLevel` method. + + This is required for compatibility with Python 2.6 where there is no conversion + performed by the ``setLevel`` method. In Python 2.7 textual names are converted + to numeric constants automatically. + + :param basestring name: Textual log level name + :return: Numeric log level constant + :rtype: int + """ + name = str(name).upper() + + try: + return _LOG_LEVELS[name] + except KeyError: + raise ValueError("Unknown level: %s" % name)
Logging configuration only works in Python 2.7+ Hi, The way log level is set in [`Reactor`](https://github.com/klen/graphite-beacon/blob/develop/graphite_beacon/core.py#L59) requires that textual log levels ("INFO", "WARN") are converted to the numeric log levels by the `logging.Logger.setLevel` method. This is only the case in Python 2.7. You can see the change between 2.6 and 2.7 here: 2.6 - https://github.com/python/cpython/blob/2.6/Lib/logging/__init__.py#L1032 2.7 - https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L1136 I'll submit a pull request shortly. Thanks!
klen/graphite-beacon
diff --git a/tests.py b/tests.py index 7bcd15a..9d5458a 100644 --- a/tests.py +++ b/tests.py @@ -1,5 +1,6 @@ """ TODO: Implement the tests. """ +import logging import pytest import mock @@ -24,6 +25,28 @@ def test_reactor(): assert len(rr.alerts) == 2 +def test_convert_config_log_level(): + from graphite_beacon.core import _get_numeric_log_level + + assert logging.DEBUG == _get_numeric_log_level('debug') + assert logging.DEBUG == _get_numeric_log_level('DEBUG') + + assert logging.INFO == _get_numeric_log_level('info') + assert logging.INFO == _get_numeric_log_level('INFO') + + assert logging.WARN == _get_numeric_log_level('warn') + assert logging.WARN == _get_numeric_log_level('WARN') + + assert logging.WARNING == _get_numeric_log_level('warning') + assert logging.WARNING == _get_numeric_log_level('WARNING') + + assert logging.ERROR == _get_numeric_log_level('error') + assert logging.ERROR == _get_numeric_log_level('ERROR') + + assert logging.CRITICAL == _get_numeric_log_level('critical') + assert logging.CRITICAL == _get_numeric_log_level('CRITICAL') + + def test_alert(reactor): from graphite_beacon.alerts import BaseAlert, GraphiteAlert, URLAlert
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 1 }
0.22
{ "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.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi==2025.1.31 exceptiongroup==1.2.2 -e git+https://github.com/klen/graphite-beacon.git@66ec0720ca5a3a9d43a63fa0a60b3eb6e26e4157#egg=graphite_beacon iniconfig==2.1.0 mock==5.2.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1 tornado==4.0.2
name: graphite-beacon 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 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 - tornado==4.0.2 prefix: /opt/conda/envs/graphite-beacon
[ "tests.py::test_convert_config_log_level" ]
[ "tests.py::test_reactor", "tests.py::test_convert", "tests.py::test_parse_interval", "tests.py::test_interval_to_graphite", "tests.py::test_parse_rule" ]
[]
[]
MIT License
67
[ "graphite_beacon/core.py" ]
[ "graphite_beacon/core.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
[ "okonomiyaki/platforms/platform.py", "okonomiyaki/platforms/epd_platform.py" ]
[ "okonomiyaki/platforms/platform.py", "okonomiyaki/platforms/epd_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
[ "shaker/helpers.py", "shaker/resolve_deps.py" ]
[ "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
[ "IPython/config/application.py" ]
[ "IPython/config/application.py" ]
richardkiss__pycoin-108
130f1cec7ed41b05c4f887dc386c6447d74cb97e
2015-03-24 16:58:56
7833e86ac5260f784ded567dcec42d63cee036aa
diff --git a/pycoin/ecdsa/ellipticcurve.py b/pycoin/ecdsa/ellipticcurve.py index 0644c52..02b1ecd 100644 --- a/pycoin/ecdsa/ellipticcurve.py +++ b/pycoin/ecdsa/ellipticcurve.py @@ -55,10 +55,15 @@ class CurveFp( object ): """Is the point (x,y) on this curve?""" return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0 + def __repr__(self): + return '{}({!r},{!r},{!r})'.format(self.__class__.__name__, self.__p, self.__a, self.__b) + + def __str__(self): + return 'y^2 = x^3 + {}*x + {} (mod {})'.format(self.__a, self.__b, self.__p) class Point( object ): - """A point on an elliptic curve. Altering x and y is forbidding, + """A point on an elliptic curve. Altering x and y is forbidden, but they can be read by the x() and y() methods.""" def __init__( self, curve, x, y, order = None ): """curve, x, y, order; order (optional) is the order of this point.""" @@ -67,7 +72,8 @@ class Point( object ): self.__y = y self.__order = order # self.curve is allowed to be None only for INFINITY: - if self.__curve: assert self.__curve.contains_point( x, y ) + if self.__curve and not self.__curve.contains_point( x, y ): + raise ValueError('({},{}) is not on the curve {}'.format(x, y, curve)) if order: assert self * order == INFINITY def __eq__( self, other ): @@ -139,6 +145,9 @@ class Point( object ): return self * other + def __repr__( self ): + return "{}({!r},{!r},{!r},{!r})".format(self.__class__.__name__, self.__curve, self.__x, self.__y, self.__order) + def __str__( self ): if self == INFINITY: return "infinity" return "(%d,%d)" % ( self.__x, self.__y ) diff --git a/pycoin/key/BIP32Node.py b/pycoin/key/BIP32Node.py index 2a67e51..c562714 100644 --- a/pycoin/key/BIP32Node.py +++ b/pycoin/key/BIP32Node.py @@ -102,14 +102,13 @@ class BIP32Node(Key): if [secret_exponent, public_pair].count(None) != 1: raise ValueError("must include exactly one of public_pair and secret_exponent") - if secret_exponent: - self._secret_exponent_bytes = to_bytes_32(secret_exponent) - super(BIP32Node, self).__init__( secret_exponent=secret_exponent, public_pair=public_pair, prefer_uncompressed=False, is_compressed=True, is_pay_to_script=False, netcode=netcode) - # validate public_pair is on the curve + if secret_exponent: + self._secret_exponent_bytes = to_bytes_32(secret_exponent) + if not isinstance(chain_code, bytes): raise ValueError("chain code must be bytes") if len(chain_code) != 32: diff --git a/pycoin/key/Key.py b/pycoin/key/Key.py index 809551c..04b6d2c 100644 --- a/pycoin/key/Key.py +++ b/pycoin/key/Key.py @@ -1,18 +1,13 @@ from pycoin import ecdsa +from pycoin.encoding import EncodingError, a2b_hashed_base58, \ + from_bytes_32, hash160, hash160_sec_to_bitcoin_address, \ + is_sec_compressed, public_pair_to_sec, sec_to_public_pair, \ + secret_exponent_to_wif from pycoin.key.validate import netcode_and_type_for_data from pycoin.networks import address_prefix_for_netcode, wif_prefix_for_netcode - -from pycoin.encoding import a2b_hashed_base58, secret_exponent_to_wif,\ - public_pair_to_sec, hash160,\ - hash160_sec_to_bitcoin_address, sec_to_public_pair,\ - is_sec_compressed, from_bytes_32, EncodingError from pycoin.serialize import b2h -class InvalidKeyGeneratedError(Exception): - pass - - class Key(object): def __init__(self, secret_exponent=None, public_pair=None, hash160=None, prefer_uncompressed=None, is_compressed=True, is_pay_to_script=False, netcode='BTC'): @@ -55,6 +50,19 @@ class Key(object): self._hash160_uncompressed = hash160 self._netcode = netcode + if self._public_pair is None and self._secret_exponent is not None: + if self._secret_exponent < 1 \ + or self._secret_exponent >= ecdsa.generator_secp256k1.order(): + raise ValueError("invalid secret exponent") + public_pair = ecdsa.public_pair_for_secret_exponent( + ecdsa.generator_secp256k1, self._secret_exponent) + self._public_pair = public_pair + + if self._public_pair is not None \ + and (None in self._public_pair \ + or not ecdsa.is_public_pair_valid(ecdsa.generator_secp256k1, self._public_pair)): + raise ValueError("invalid public pair") + @classmethod def from_text(class_, text, is_compressed=True): """ @@ -117,14 +125,6 @@ class Key(object): """ Return a pair of integers representing the public key (or None). """ - if self._public_pair is None and self.secret_exponent(): - public_pair = ecdsa.public_pair_for_secret_exponent( - ecdsa.generator_secp256k1, self._secret_exponent) - if not ecdsa.is_public_pair_valid(ecdsa.generator_secp256k1, public_pair): - raise InvalidKeyGeneratedError( - "this key would produce an invalid public pair; please skip it") - self._public_pair = public_pair - return self._public_pair def sec(self, use_uncompressed=None): diff --git a/pycoin/key/bip32.py b/pycoin/key/bip32.py index cce2fdf..a13b733 100644 --- a/pycoin/key/bip32.py +++ b/pycoin/key/bip32.py @@ -41,14 +41,35 @@ THE SOFTWARE. import hashlib import hmac +import logging import struct from .. import ecdsa from ..encoding import public_pair_to_sec, from_bytes_32, to_bytes_32 +from ..ecdsa.ellipticcurve import INFINITY + +logger = logging.getLogger(__name__) ORDER = ecdsa.generator_secp256k1.order() +_SUBKEY_VALIDATION_LOG_ERR_FMT = """ +BUY A LOTTO TICKET RIGHT NOW! (And consider giving up your wallet to +science!) + +You have stumbled across and astronomically unlikely scenario. Your HD +wallet contains an invalid subkey. Having access to this information would +be incredibly valuable to the Bitcoin development community. + +If you are inclined to help, please make sure to back up this wallet (or +any outputted information) onto a USB drive and e-mail "Richard Kiss" +<[email protected]> or "Matt Bogosian" <[email protected]> for +instructions on how best to donate it without losing your bitcoins. + +WARNING: DO NOT SEND ANY WALLET INFORMATION UNLESS YOU WANT TO LOSE ALL +THE BITCOINS IT CONTAINS. +""".strip() + def subkey_secret_exponent_chain_code_pair( secret_exponent, chain_code_bytes, i, is_hardened, public_pair=None): @@ -81,7 +102,13 @@ def subkey_secret_exponent_chain_code_pair( I64 = hmac.HMAC(key=chain_code_bytes, msg=data, digestmod=hashlib.sha512).digest() I_left_as_exponent = from_bytes_32(I64[:32]) + if I_left_as_exponent >= ORDER: + logger.critical(_SUBKEY_VALIDATION_LOG_ERR_FMT) + raise ValueError('bad derviation: I_L >= {}'.format(ORDER)) new_secret_exponent = (I_left_as_exponent + secret_exponent) % ORDER + if new_secret_exponent == 0: + logger.critical(_SUBKEY_VALIDATION_LOG_ERR_FMT) + raise ValueError('bad derviation: k_{} == 0'.format(i)) new_chain_code = I64[32:] return new_secret_exponent, new_chain_code @@ -107,10 +134,17 @@ def subkey_public_pair_chain_code_pair(public_pair, chain_code_bytes, i): I_left_as_exponent = from_bytes_32(I64[:32]) x, y = public_pair + the_point = I_left_as_exponent * ecdsa.generator_secp256k1 + \ ecdsa.Point(ecdsa.generator_secp256k1.curve(), x, y, ORDER) + if the_point == INFINITY: + logger.critical(_SUBKEY_VALIDATION_LOG_ERR_FMT) + raise ValueError('bad derviation: K_{} == {}'.format(i, the_point)) I_left_as_exponent = from_bytes_32(I64[:32]) + if I_left_as_exponent >= ORDER: + logger.critical(_SUBKEY_VALIDATION_LOG_ERR_FMT) + raise ValueError('bad derviation: I_L >= {}'.format(ORDER)) new_public_pair = the_point.pair() new_chain_code = I64[32:] return new_public_pair, new_chain_code diff --git a/pycoin/scripts/ku.py b/pycoin/scripts/ku.py index 0ac6e25..5c80013 100755 --- a/pycoin/scripts/ku.py +++ b/pycoin/scripts/ku.py @@ -215,13 +215,22 @@ def main(): # force network arg to match override, but also will override decoded data below. args.network = args.override_network + def _create(_): + max_retries = 64 + for _ in range(max_retries): + try: + return BIP32Node.from_master_secret(get_entropy(), netcode=args.network) + except ValueError as e: + continue + # Probably a bug if we get here + raise e + PREFIX_TRANSFORMS = ( ("P:", lambda s: BIP32Node.from_master_secret(s.encode("utf8"), netcode=args.network)), ("H:", lambda s: BIP32Node.from_master_secret(h2b(s), netcode=args.network)), - ("create", lambda s: - BIP32Node.from_master_secret(get_entropy(), netcode=args.network)), + ("create", _create), ) for item in args.item:
BIP32 private key derivation edge case Regarding this section of BIP32: https://github.com/bitcoin/bips/blob/2ea19daaa0380fed7a2b053fd1f488fadba28bda/bip-0032.mediawiki#private-parent-key--private-child-key > In case parse256(IL) ≥ n or ki = 0, the resulting key is invalid, and one should proceed with the next value for i. (Note: this has probability lower than 1 in 2^(127).) In particular I suspect this should be implemented near: https://github.com/richardkiss/pycoin/blob/5ebd6c038eb5de5ee5330eea70887ddd4ba390ce/pycoin/key/BIP32Node.py#L232 Alternatively, what about raising an error instead? I know this is not standards-compliant, but if someone really needs that functionality they can just increment the value themselves and try again, I believe.
richardkiss/pycoin
diff --git a/tests/bip32_test.py b/tests/bip32_test.py index 75bb2a9..c6473e8 100755 --- a/tests/bip32_test.py +++ b/tests/bip32_test.py @@ -1,22 +1,13 @@ #!/usr/bin/env python import unittest - -from pycoin.key import bip32 -from pycoin.serialize import h2b - from pycoin.key.BIP32Node import BIP32Node - -def Wallet(*args, **kwargs): - return BIP32Node(*args, **kwargs) -Wallet.from_master_secret = lambda *args, **kwargs: BIP32Node.from_master_secret(*args, **kwargs) -Wallet.from_wallet_key = lambda *args, **kwargs: BIP32Node.from_wallet_key(*args, **kwargs) -bip32.Wallet = Wallet +from pycoin.serialize import h2b class Bip0032TestCase(unittest.TestCase): def test_vector_1(self): - master = bip32.Wallet.from_master_secret(h2b("000102030405060708090a0b0c0d0e0f")) + master = BIP32Node.from_master_secret(h2b("000102030405060708090a0b0c0d0e0f")) self.assertEqual(master.wallet_key(as_private=True), "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi") self.assertEqual(master.bitcoin_address(), "15mKKb2eos1hWa6tisdPwwDC1a5J1y9nma") self.assertEqual(master.wif(), "L52XzL2cMkHxqxBXRyEpnPQZGUs3uKiL3R11XbAdHigRzDozKZeW") @@ -70,7 +61,7 @@ class Bip0032TestCase(unittest.TestCase): def test_vector_2(self): - master = bip32.Wallet.from_master_secret(h2b("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542")) + master = BIP32Node.from_master_secret(h2b("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542")) self.assertEqual(master.wallet_key(as_private=True), "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U") self.assertEqual(master.wallet_key(), "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB") @@ -114,13 +105,13 @@ class Bip0032TestCase(unittest.TestCase): def test_testnet(self): # WARNING: these values have not been verified independently. TODO: do so - master = bip32.Wallet.from_master_secret(h2b("000102030405060708090a0b0c0d0e0f"), netcode='XTN') + master = BIP32Node.from_master_secret(h2b("000102030405060708090a0b0c0d0e0f"), netcode='XTN') self.assertEqual(master.wallet_key(as_private=True), "tprv8ZgxMBicQKsPeDgjzdC36fs6bMjGApWDNLR9erAXMs5skhMv36j9MV5ecvfavji5khqjWaWSFhN3YcCUUdiKH6isR4Pwy3U5y5egddBr16m") self.assertEqual(master.bitcoin_address(), "mkHGce7dctSxHgaWSSbmmrRWsZfzz7MxMk") self.assertEqual(master.wif(), "cVPXTF2TnozE1PenpP3x9huctiATZmp27T9Ue1d8nqLSExoPwfN5") def test_streams(self): - m0 = bip32.Wallet.from_master_secret("foo bar baz".encode("utf8")) + m0 = BIP32Node.from_master_secret("foo bar baz".encode("utf8")) pm0 = m0.public_copy() self.assertEqual(m0.wallet_key(), pm0.wallet_key()) m1 = m0.subkey() @@ -130,15 +121,15 @@ class Bip0032TestCase(unittest.TestCase): pm = pm1.subkey(i=i) self.assertEqual(m.wallet_key(), pm.wallet_key()) self.assertEqual(m.bitcoin_address(), pm.bitcoin_address()) - m2 = bip32.Wallet.from_wallet_key(m.wallet_key(as_private=True)) + m2 = BIP32Node.from_wallet_key(m.wallet_key(as_private=True)) m3 = m2.public_copy() self.assertEqual(m.wallet_key(as_private=True), m2.wallet_key(as_private=True)) self.assertEqual(m.wallet_key(), m3.wallet_key()) print(m.wallet_key(as_private=True)) for j in range(2): k = m.subkey(i=j) - k2 = bip32.Wallet.from_wallet_key(k.wallet_key(as_private=True)) - k3 = bip32.Wallet.from_wallet_key(k.wallet_key()) + k2 = BIP32Node.from_wallet_key(k.wallet_key(as_private=True)) + k3 = BIP32Node.from_wallet_key(k.wallet_key()) k4 = k.public_copy() self.assertEqual(k.wallet_key(as_private=True), k2.wallet_key(as_private=True)) self.assertEqual(k.wallet_key(), k2.wallet_key()) @@ -167,4 +158,3 @@ class Bip0032TestCase(unittest.TestCase): if __name__ == '__main__': unittest.main() - diff --git a/tests/key_test.py b/tests/key_test.py index 21123d3..22efe10 100755 --- a/tests/key_test.py +++ b/tests/key_test.py @@ -101,4 +101,3 @@ class KeyTest(unittest.TestCase): if __name__ == '__main__': unittest.main() - diff --git a/tests/key_validate_test.py b/tests/key_validate_test.py index 7cabd8c..4ef462e 100755 --- a/tests/key_validate_test.py +++ b/tests/key_validate_test.py @@ -2,12 +2,14 @@ import unittest +from pycoin.ecdsa.ellipticcurve import Point +from pycoin.ecdsa.secp256k1 import generator_secp256k1 from pycoin.encoding import hash160_sec_to_bitcoin_address from pycoin.key import Key from pycoin.key.BIP32Node import BIP32Node +from pycoin.key.validate import is_address_valid, is_wif_valid, is_public_bip32_valid, is_private_bip32_valid from pycoin.networks import pay_to_script_prefix_for_netcode, NETWORK_NAMES -from pycoin.key.validate import is_address_valid, is_wif_valid, is_public_bip32_valid, is_private_bip32_valid def change_prefix(address, new_prefix): return hash160_sec_to_bitcoin_address(Key.from_text(address).hash160(), address_prefix=new_prefix) @@ -81,6 +83,252 @@ class KeyUtilsTest(unittest.TestCase): self.assertEqual(is_private_bip32_valid(a, allowable_netcodes=NETWORK_NAMES), None) self.assertEqual(is_public_bip32_valid(a, allowable_netcodes=NETWORK_NAMES), None) + + def test_key_limits(self): + nc = 'BTC' + cc = b'000102030405060708090a0b0c0d0e0f' + order = generator_secp256k1.order() + + for k in -1, 0, order, order + 1: + with self.assertRaises(ValueError) as cm: + Key(secret_exponent=k) + err = cm.exception + self.assertEqual(err.args[0], 'invalid secret exponent') + + with self.assertRaises(ValueError) as cm: + BIP32Node(nc, cc, secret_exponent=k) + err = cm.exception + self.assertEqual(err.args[0], 'invalid secret exponent') + + for i in range(1, 512): + Key(secret_exponent=i) + BIP32Node(nc, cc, secret_exponent=i) + + + def test_points(self): + secp256k1_curve = generator_secp256k1.curve() + # From <https://crypto.stackexchange.com/questions/784/are-there-any-secp256k1-ecdsa-test-examples-available> + test_points = [] + k = 1 + x = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 + y = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 + test_points.append((k, x, y)) + k = 2 + x = 0xC6047F9441ED7D6D3045406E95C07CD85C778E4B8CEF3CA7ABAC09B95C709EE5 + y = 0x1AE168FEA63DC339A3C58419466CEAEEF7F632653266D0E1236431A950CFE52A + test_points.append((k, x, y)) + k = 3 + x = 0xF9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9 + y = 0x388F7B0F632DE8140FE337E62A37F3566500A99934C2231B6CB9FD7584B8E672 + test_points.append((k, x, y)) + k = 4 + x = 0xE493DBF1C10D80F3581E4904930B1404CC6C13900EE0758474FA94ABE8C4CD13 + y = 0x51ED993EA0D455B75642E2098EA51448D967AE33BFBDFE40CFE97BDC47739922 + test_points.append((k, x, y)) + k = 5 + x = 0x2F8BDE4D1A07209355B4A7250A5C5128E88B84BDDC619AB7CBA8D569B240EFE4 + y = 0xD8AC222636E5E3D6D4DBA9DDA6C9C426F788271BAB0D6840DCA87D3AA6AC62D6 + test_points.append((k, x, y)) + k = 6 + x = 0xFFF97BD5755EEEA420453A14355235D382F6472F8568A18B2F057A1460297556 + y = 0xAE12777AACFBB620F3BE96017F45C560DE80F0F6518FE4A03C870C36B075F297 + test_points.append((k, x, y)) + k = 7 + x = 0x5CBDF0646E5DB4EAA398F365F2EA7A0E3D419B7E0330E39CE92BDDEDCAC4F9BC + y = 0x6AEBCA40BA255960A3178D6D861A54DBA813D0B813FDE7B5A5082628087264DA + test_points.append((k, x, y)) + k = 8 + x = 0x2F01E5E15CCA351DAFF3843FB70F3C2F0A1BDD05E5AF888A67784EF3E10A2A01 + y = 0x5C4DA8A741539949293D082A132D13B4C2E213D6BA5B7617B5DA2CB76CBDE904 + test_points.append((k, x, y)) + k = 9 + x = 0xACD484E2F0C7F65309AD178A9F559ABDE09796974C57E714C35F110DFC27CCBE + y = 0xCC338921B0A7D9FD64380971763B61E9ADD888A4375F8E0F05CC262AC64F9C37 + test_points.append((k, x, y)) + k = 10 + x = 0xA0434D9E47F3C86235477C7B1AE6AE5D3442D49B1943C2B752A68E2A47E247C7 + y = 0x893ABA425419BC27A3B6C7E693A24C696F794C2ED877A1593CBEE53B037368D7 + test_points.append((k, x, y)) + k = 11 + x = 0x774AE7F858A9411E5EF4246B70C65AAC5649980BE5C17891BBEC17895DA008CB + y = 0xD984A032EB6B5E190243DD56D7B7B365372DB1E2DFF9D6A8301D74C9C953C61B + test_points.append((k, x, y)) + k = 12 + x = 0xD01115D548E7561B15C38F004D734633687CF4419620095BC5B0F47070AFE85A + y = 0xA9F34FFDC815E0D7A8B64537E17BD81579238C5DD9A86D526B051B13F4062327 + test_points.append((k, x, y)) + k = 13 + x = 0xF28773C2D975288BC7D1D205C3748651B075FBC6610E58CDDEEDDF8F19405AA8 + y = 0x0AB0902E8D880A89758212EB65CDAF473A1A06DA521FA91F29B5CB52DB03ED81 + test_points.append((k, x, y)) + k = 14 + x = 0x499FDF9E895E719CFD64E67F07D38E3226AA7B63678949E6E49B241A60E823E4 + y = 0xCAC2F6C4B54E855190F044E4A7B3D464464279C27A3F95BCC65F40D403A13F5B + test_points.append((k, x, y)) + k = 15 + x = 0xD7924D4F7D43EA965A465AE3095FF41131E5946F3C85F79E44ADBCF8E27E080E + y = 0x581E2872A86C72A683842EC228CC6DEFEA40AF2BD896D3A5C504DC9FF6A26B58 + test_points.append((k, x, y)) + k = 16 + x = 0xE60FCE93B59E9EC53011AABC21C23E97B2A31369B87A5AE9C44EE89E2A6DEC0A + y = 0xF7E3507399E595929DB99F34F57937101296891E44D23F0BE1F32CCE69616821 + test_points.append((k, x, y)) + k = 17 + x = 0xDEFDEA4CDB677750A420FEE807EACF21EB9898AE79B9768766E4FAA04A2D4A34 + y = 0x4211AB0694635168E997B0EAD2A93DAECED1F4A04A95C0F6CFB199F69E56EB77 + test_points.append((k, x, y)) + k = 18 + x = 0x5601570CB47F238D2B0286DB4A990FA0F3BA28D1A319F5E7CF55C2A2444DA7CC + y = 0xC136C1DC0CBEB930E9E298043589351D81D8E0BC736AE2A1F5192E5E8B061D58 + test_points.append((k, x, y)) + k = 19 + x = 0x2B4EA0A797A443D293EF5CFF444F4979F06ACFEBD7E86D277475656138385B6C + y = 0x85E89BC037945D93B343083B5A1C86131A01F60C50269763B570C854E5C09B7A + test_points.append((k, x, y)) + k = 20 + x = 0x4CE119C96E2FA357200B559B2F7DD5A5F02D5290AFF74B03F3E471B273211C97 + y = 0x12BA26DCB10EC1625DA61FA10A844C676162948271D96967450288EE9233DC3A + test_points.append((k, x, y)) + k = 112233445566778899 + x = 0xA90CC3D3F3E146DAADFC74CA1372207CB4B725AE708CEF713A98EDD73D99EF29 + y = 0x5A79D6B289610C68BC3B47F3D72F9788A26A06868B4D8E433E1E2AD76FB7DC76 + test_points.append((k, x, y)) + k = 112233445566778899112233445566778899 + x = 0xE5A2636BCFD412EBF36EC45B19BFB68A1BC5F8632E678132B885F7DF99C5E9B3 + y = 0x736C1CE161AE27B405CAFD2A7520370153C2C861AC51D6C1D5985D9606B45F39 + test_points.append((k, x, y)) + k = 28948022309329048855892746252171976963209391069768726095651290785379540373584 + x = 0xA6B594B38FB3E77C6EDF78161FADE2041F4E09FD8497DB776E546C41567FEB3C + y = 0x71444009192228730CD8237A490FEBA2AFE3D27D7CC1136BC97E439D13330D55 + test_points.append((k, x, y)) + k = 57896044618658097711785492504343953926418782139537452191302581570759080747168 + x = 0x00000000000000000000003B78CE563F89A0ED9414F5AA28AD0D96D6795F9C63 + y = 0x3F3979BF72AE8202983DC989AEC7F2FF2ED91BDD69CE02FC0700CA100E59DDF3 + test_points.append((k, x, y)) + k = 86844066927987146567678238756515930889628173209306178286953872356138621120752 + x = 0xE24CE4BEEE294AA6350FAA67512B99D388693AE4E7F53D19882A6EA169FC1CE1 + y = 0x8B71E83545FC2B5872589F99D948C03108D36797C4DE363EBD3FF6A9E1A95B10 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494317 + x = 0x4CE119C96E2FA357200B559B2F7DD5A5F02D5290AFF74B03F3E471B273211C97 + y = 0xED45D9234EF13E9DA259E05EF57BB3989E9D6B7D8E269698BAFD77106DCC1FF5 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494318 + x = 0x2B4EA0A797A443D293EF5CFF444F4979F06ACFEBD7E86D277475656138385B6C + y = 0x7A17643FC86BA26C4CBCF7C4A5E379ECE5FE09F3AFD9689C4A8F37AA1A3F60B5 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494319 + x = 0x5601570CB47F238D2B0286DB4A990FA0F3BA28D1A319F5E7CF55C2A2444DA7CC + y = 0x3EC93E23F34146CF161D67FBCA76CAE27E271F438C951D5E0AE6D1A074F9DED7 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494320 + x = 0xDEFDEA4CDB677750A420FEE807EACF21EB9898AE79B9768766E4FAA04A2D4A34 + y = 0xBDEE54F96B9CAE9716684F152D56C251312E0B5FB56A3F09304E660861A910B8 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494321 + x = 0xE60FCE93B59E9EC53011AABC21C23E97B2A31369B87A5AE9C44EE89E2A6DEC0A + y = 0x081CAF8C661A6A6D624660CB0A86C8EFED6976E1BB2DC0F41E0CD330969E940E + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494322 + x = 0xD7924D4F7D43EA965A465AE3095FF41131E5946F3C85F79E44ADBCF8E27E080E + y = 0xA7E1D78D57938D597C7BD13DD733921015BF50D427692C5A3AFB235F095D90D7 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494323 + x = 0x499FDF9E895E719CFD64E67F07D38E3226AA7B63678949E6E49B241A60E823E4 + y = 0x353D093B4AB17AAE6F0FBB1B584C2B9BB9BD863D85C06A4339A0BF2AFC5EBCD4 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494324 + x = 0xF28773C2D975288BC7D1D205C3748651B075FBC6610E58CDDEEDDF8F19405AA8 + y = 0xF54F6FD17277F5768A7DED149A3250B8C5E5F925ADE056E0D64A34AC24FC0EAE + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494325 + x = 0xD01115D548E7561B15C38F004D734633687CF4419620095BC5B0F47070AFE85A + y = 0x560CB00237EA1F285749BAC81E8427EA86DC73A2265792AD94FAE4EB0BF9D908 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494326 + x = 0x774AE7F858A9411E5EF4246B70C65AAC5649980BE5C17891BBEC17895DA008CB + y = 0x267B5FCD1494A1E6FDBC22A928484C9AC8D24E1D20062957CFE28B3536AC3614 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494327 + x = 0xA0434D9E47F3C86235477C7B1AE6AE5D3442D49B1943C2B752A68E2A47E247C7 + y = 0x76C545BDABE643D85C4938196C5DB3969086B3D127885EA6C3411AC3FC8C9358 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494328 + x = 0xACD484E2F0C7F65309AD178A9F559ABDE09796974C57E714C35F110DFC27CCBE + y = 0x33CC76DE4F5826029BC7F68E89C49E165227775BC8A071F0FA33D9D439B05FF8 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494329 + x = 0x2F01E5E15CCA351DAFF3843FB70F3C2F0A1BDD05E5AF888A67784EF3E10A2A01 + y = 0xA3B25758BEAC66B6D6C2F7D5ECD2EC4B3D1DEC2945A489E84A25D3479342132B + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494330 + x = 0x5CBDF0646E5DB4EAA398F365F2EA7A0E3D419B7E0330E39CE92BDDEDCAC4F9BC + y = 0x951435BF45DAA69F5CE8729279E5AB2457EC2F47EC02184A5AF7D9D6F78D9755 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494331 + x = 0xFFF97BD5755EEEA420453A14355235D382F6472F8568A18B2F057A1460297556 + y = 0x51ED8885530449DF0C4169FE80BA3A9F217F0F09AE701B5FC378F3C84F8A0998 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494332 + x = 0x2F8BDE4D1A07209355B4A7250A5C5128E88B84BDDC619AB7CBA8D569B240EFE4 + y = 0x2753DDD9C91A1C292B24562259363BD90877D8E454F297BF235782C459539959 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494333 + x = 0xE493DBF1C10D80F3581E4904930B1404CC6C13900EE0758474FA94ABE8C4CD13 + y = 0xAE1266C15F2BAA48A9BD1DF6715AEBB7269851CC404201BF30168422B88C630D + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494334 + x = 0xF9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9 + y = 0xC77084F09CD217EBF01CC819D5C80CA99AFF5666CB3DDCE4934602897B4715BD + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494335 + x = 0xC6047F9441ED7D6D3045406E95C07CD85C778E4B8CEF3CA7ABAC09B95C709EE5 + y = 0xE51E970159C23CC65C3A7BE6B99315110809CD9ACD992F1EDC9BCE55AF301705 + test_points.append((k, x, y)) + k = 115792089237316195423570985008687907852837564279074904382605163141518161494336 + x = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 + y = 0xB7C52588D95C3B9AA25B0403F1EEF75702E84BB7597AABE663B82F6F04EF2777 + test_points.append((k, x, y)) + k = 0xaa5e28d6a97a2479a65527f7290311a3624d4cc0fa1578598ee3c2613bf99522 + x = 0x34f9460f0e4f08393d192b3c5133a6ba099aa0ad9fd54ebccfacdfa239ff49c6 + y = 0x0b71ea9bd730fd8923f6d25a7a91e7dd7728a960686cb5a901bb419e0f2ca232 + test_points.append((k, x, y)) + k = 0x7e2b897b8cebc6361663ad410835639826d590f393d90a9538881735256dfae3 + x = 0xd74bf844b0862475103d96a611cf2d898447e288d34b360bc885cb8ce7c00575 + y = 0x131c670d414c4546b88ac3ff664611b1c38ceb1c21d76369d7a7a0969d61d97d + test_points.append((k, x, y)) + k = 0x6461e6df0fe7dfd05329f41bf771b86578143d4dd1f7866fb4ca7e97c5fa945d + x = 0xe8aecc370aedd953483719a116711963ce201ac3eb21d3f3257bb48668c6a72f + y = 0xc25caf2f0eba1ddb2f0f3f47866299ef907867b7d27e95b3873bf98397b24ee1 + test_points.append((k, x, y)) + k = 0x376a3a2cdcd12581efff13ee4ad44c4044b8a0524c42422a7e1e181e4deeccec + x = 0x14890e61fcd4b0bd92e5b36c81372ca6fed471ef3aa60a3e415ee4fe987daba1 + y = 0x297b858d9f752ab42d3bca67ee0eb6dcd1c2b7b0dbe23397e66adc272263f982 + test_points.append((k, x, y)) + k = 0x1b22644a7be026548810c378d0b2994eefa6d2b9881803cb02ceff865287d1b9 + x = 0xf73c65ead01c5126f28f442d087689bfa08e12763e0cec1d35b01751fd735ed3 + y = 0xf449a8376906482a84ed01479bd18882b919c140d638307f0c0934ba12590bde + test_points.append((k, x, y)) + + for k, x, y in test_points: + p = Point(secp256k1_curve, x, y) + self.assertTrue(secp256k1_curve.contains_point(p.x(), p.y())) + K = Key(public_pair=(x, y)) + k = Key(secret_exponent=k) + self.assertEqual(K.public_pair(), k.public_pair()) + + x = y = 0 + with self.assertRaises(ValueError) as cm: + Point(secp256k1_curve, x, y) + err = cm.exception + self.assertTrue(err.args[0].startswith('({},{}) is not on the curve '.format(x, y))) + + with self.assertRaises(ValueError) as cm: + Key(public_pair=(0, 0)) + err = cm.exception + self.assertEqual(err.args[0], 'invalid public pair') + + def test_repr(self): key = Key(secret_exponent=273, netcode='XTN') @@ -92,5 +340,6 @@ class KeyUtilsTest(unittest.TestCase): priv_k = Key.from_text(wif) self.assertEqual(repr(priv_k), 'private_for <0264e1b1969f9102977691a40431b0b672055dcf31163897d996434420e6c95dc9>') + if __name__ == '__main__': unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 5 }
0.52
{ "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", "tox" ], "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" }
cachetools==5.5.2 chardet==5.2.0 colorama==0.4.6 distlib==0.3.9 exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work filelock==3.18.0 iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work packaging @ file:///croot/packaging_1734472117206/work platformdirs==4.3.7 pluggy @ file:///croot/pluggy_1733169602837/work -e git+https://github.com/richardkiss/pycoin.git@130f1cec7ed41b05c4f887dc386c6447d74cb97e#egg=pycoin pyproject-api==1.9.0 pytest @ file:///croot/pytest_1738938843180/work tomli==2.2.1 tox==4.25.0 typing_extensions==4.13.0 virtualenv==20.29.3
name: pycoin 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 - tzdata=2025a=h04d1e81_0 - wheel=0.45.1=py39h06a4308_0 - xz=5.6.4=h5eee18b_1 - zlib=1.2.13=h5eee18b_1 - pip: - cachetools==5.5.2 - chardet==5.2.0 - colorama==0.4.6 - distlib==0.3.9 - filelock==3.18.0 - platformdirs==4.3.7 - pyproject-api==1.9.0 - tomli==2.2.1 - tox==4.25.0 - typing-extensions==4.13.0 - virtualenv==20.29.3 prefix: /opt/conda/envs/pycoin
[ "tests/key_validate_test.py::KeyUtilsTest::test_key_limits", "tests/key_validate_test.py::KeyUtilsTest::test_points" ]
[]
[ "tests/bip32_test.py::Bip0032TestCase::test_public_subkey", "tests/bip32_test.py::Bip0032TestCase::test_repr", "tests/bip32_test.py::Bip0032TestCase::test_streams", "tests/bip32_test.py::Bip0032TestCase::test_testnet", "tests/bip32_test.py::Bip0032TestCase::test_vector_1", "tests/bip32_test.py::Bip0032TestCase::test_vector_2", "tests/key_test.py::KeyTest::test_translation", "tests/key_validate_test.py::KeyUtilsTest::test_address_valid_btc", "tests/key_validate_test.py::KeyUtilsTest::test_is_public_private_bip32_valid", "tests/key_validate_test.py::KeyUtilsTest::test_is_wif_valid", "tests/key_validate_test.py::KeyUtilsTest::test_repr" ]
[]
MIT License
72
[ "pycoin/scripts/ku.py", "pycoin/key/Key.py", "pycoin/ecdsa/ellipticcurve.py", "pycoin/key/bip32.py", "pycoin/key/BIP32Node.py" ]
[ "pycoin/scripts/ku.py", "pycoin/key/Key.py", "pycoin/ecdsa/ellipticcurve.py", "pycoin/key/bip32.py", "pycoin/key/BIP32Node.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
[ "green/loader.py" ]
[ "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
[ "eadator/eadator.py" ]
[ "eadator/eadator.py" ]
kissmetrics__py-KISSmetrics-27
3e1819f735771472c112ee471ec732e5a8277bfe
2015-03-27 15:29:10
3e1819f735771472c112ee471ec732e5a8277bfe
diff --git a/KISSmetrics/query_string.py b/KISSmetrics/query_string.py index 4765b2c..4013d3a 100644 --- a/KISSmetrics/query_string.py +++ b/KISSmetrics/query_string.py @@ -43,7 +43,7 @@ def create_query(key, person, event=None, timestamp=None, query_dict = {KEY_KEY: key, PERSON_KEY: person} if timestamp: query_dict[TIME_FLAG_KEY] = 1 - query_dict[TIME_KEY] = timestamp + query_dict[TIME_KEY] = int(timestamp) if event: query_dict[EVENT_NAME_KEY] = event if identity:
Support for timestamps submitted as floats From Dylan: " Currently, if someone using the Python library (and potentially other libraries) tries to send in a float as a timestamp, it gets converted to something like 1426982400.0. This doesn't generate any errors, and it shows up in the live tab just fine, but any events recorded with this timestamp won't be properly processed and won't show up in a user's account. "
kissmetrics/py-KISSmetrics
diff --git a/KISSmetrics/tests/test_kissmetrics.py b/KISSmetrics/tests/test_kissmetrics.py index bfc5734..a15ba99 100644 --- a/KISSmetrics/tests/test_kissmetrics.py +++ b/KISSmetrics/tests/test_kissmetrics.py @@ -113,7 +113,7 @@ class TestKISSmetricsRequestFunctionsTestCase(unittest.TestCase): assert parse_qs(query_string)['_p'] == ['bar'] assert parse_qs(query_string)['_n'] == ['fizzed'] - def test_record_with_timestamp(self): + def test_record_with_integer_timestamp(self): query_string = KISSmetrics.request.record(key='foo', person='bar', event='fizzed', timestamp=1381849312) assert urlparse(query_string).path == '/e' query_string = urlparse(query_string).query @@ -122,6 +122,24 @@ class TestKISSmetricsRequestFunctionsTestCase(unittest.TestCase): assert parse_qs(query_string)['_d'] == ['1'] assert parse_qs(query_string)['_t'] == ['1381849312'] + def test_record_with_whole_float_timestamp(self): + query_string = KISSmetrics.request.record(key='foo', person='bar', event='fizzed', timestamp=1381849312.0) + assert urlparse(query_string).path == '/e' + query_string = urlparse(query_string).query + assert parse_qs(query_string)['_k'] == ['foo'] + assert parse_qs(query_string)['_p'] == ['bar'] + assert parse_qs(query_string)['_d'] == ['1'] + assert parse_qs(query_string)['_t'] == ['1381849312'] + + def test_record_with_non_whole_float_timestamp(self): + query_string = KISSmetrics.request.record(key='foo', person='bar', event='fizzed', timestamp=1381849312.5) + assert urlparse(query_string).path == '/e' + query_string = urlparse(query_string).query + assert parse_qs(query_string)['_k'] == ['foo'] + assert parse_qs(query_string)['_p'] == ['bar'] + assert parse_qs(query_string)['_d'] == ['1'] + assert parse_qs(query_string)['_t'] == ['1381849312'] + def test_record_custom_path(self): query_string = KISSmetrics.request.record(key='foo', person='bar', event='fizzed', path='get') assert urlparse(query_string).path == '/get' @@ -150,6 +168,28 @@ class TestKISSmetricsRequestFunctionsTestCase(unittest.TestCase): assert parse_qs(query_string)['_t'] == ['1381849312'] assert parse_qs(query_string)['cool'] == ['1'] + def test_set_with_whole_float_timestamp(self): + properties = {'cool': '1'} + query_string = KISSmetrics.request.set(key='foo', person='bar', properties=properties, timestamp=1381849312.0) + assert urlparse(query_string).path == '/s' + query_string = urlparse(query_string).query + assert parse_qs(query_string)['_k'] == ['foo'] + assert parse_qs(query_string)['_p'] == ['bar'] + assert parse_qs(query_string)['_d'] == ['1'] + assert parse_qs(query_string)['_t'] == ['1381849312'] + assert parse_qs(query_string)['cool'] == ['1'] + + def test_set_with_non_whole_float_timestamp(self): + properties = {'cool': '1'} + query_string = KISSmetrics.request.set(key='foo', person='bar', properties=properties, timestamp=1381849312.5) + assert urlparse(query_string).path == '/s' + query_string = urlparse(query_string).query + assert parse_qs(query_string)['_k'] == ['foo'] + assert parse_qs(query_string)['_p'] == ['bar'] + assert parse_qs(query_string)['_d'] == ['1'] + assert parse_qs(query_string)['_t'] == ['1381849312'] + assert parse_qs(query_string)['cool'] == ['1'] + def test_set_custom_path(self): properties = {'cool': '1'} query_string = KISSmetrics.request.set(key='foo', person='bar', properties=properties, path='get')
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "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" ], "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" }
coverage==7.8.0 exceptiongroup==1.2.2 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 -e git+https://github.com/kissmetrics/py-KISSmetrics.git@3e1819f735771472c112ee471ec732e5a8277bfe#egg=py_KISSmetrics pytest==8.3.5 pytest-cov==6.0.0 tomli==2.2.1 urllib3==1.26.20
name: py-KISSmetrics 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 - urllib3==1.26.20 prefix: /opt/conda/envs/py-KISSmetrics
[ "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_record_with_non_whole_float_timestamp", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_record_with_whole_float_timestamp", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_set_with_non_whole_float_timestamp", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_set_with_whole_float_timestamp" ]
[]
[ "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientTestCase::test_client_http_object", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientTestCase::test_client_key", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientTestCase::test_client_scheme", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientCompatTestCase::test_client_compat_check_identify", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientCompatTestCase::test_client_compat_check_init", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientCompatTestCase::test_client_compat_http_object", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientCompatTestCase::test_client_compat_key", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientCompatTestCase::test_client_compat_log_file", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientCompatTestCase::test_client_compat_now", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientCompatTestCase::test_client_compat_scheme", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsClientCompatTestCase::test_compatibility_alias", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsRequestTestCase::test_alias", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsRequestTestCase::test_event", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsRequestTestCase::test_minimum", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsRequestTestCase::test_set", "KISSmetrics/tests/test_kissmetrics.py::KISSmetricsRequestTestCase::test_timestamp", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_alias", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_alias_custom_path", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_record", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_record_custom_path", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_record_with_integer_timestamp", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_set", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_set_custom_path", "KISSmetrics/tests/test_kissmetrics.py::TestKISSmetricsRequestFunctionsTestCase::test_set_with_timestamp" ]
[]
MIT License
76
[ "KISSmetrics/query_string.py" ]
[ "KISSmetrics/query_string.py" ]
wndhydrnt__python-oauth2-38
afa9d84b54392391b888dc3bff36aaf08bbd5834
2015-03-29 12:17:16
9d56b2202515aaaf3bed7a5b3bc3b61f7fe17199
diff --git a/CHANGELOG.md b/CHANGELOG.md index 186083e..e1fe12f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ Improvements: Bugfixes: - Fix Resource Owner Grant responding with HTTP status code '500' in case an owner could not be authorized ([@wndhydrnt][]) + - Fix "scope" parameter not being urlencoded ([@wndhydrnt][]) ## 0.7.0 diff --git a/oauth2/grant.py b/oauth2/grant.py index ff9d65b..5dd586f 100644 --- a/oauth2/grant.py +++ b/oauth2/grant.py @@ -466,7 +466,7 @@ class AuthorizationCodeAuthHandler(AuthorizeMixin, AuthRequestMixin, query = "code=" + code if self.state is not None: - query += "&state=" + self.state + query += "&state=" + quote(self.state) return "%s?%s" % (self.client.redirect_uri, query) @@ -705,7 +705,7 @@ class ImplicitGrantHandler(AuthorizeMixin, AuthRequestMixin, GrantHandler): format(self.client.redirect_uri, token) if self.state is not None: - uri_with_fragment += "&state=" + self.state + uri_with_fragment += "&state=" + quote(self.state) if self.scope_handler.send_back is True: scopes_as_string = encode_scopes(self.scope_handler.scopes,
Returned state token not url-encoded Current implementation reads state from request query parameter with request.get_param(), which handles url-decoding automatically. When state is written back to a redirect url it is not url-encoded. This causes state mismatch in client. Only applies to clients that use state strings that yield are url-decodable. Reproducable with /examples/authorization_code_grant.py, modifying ClientApplication. Generate a state token in client: ``` def _request_auth_token(self): print("Requesting authorization token...") auth_endpoint = self.api_server_url + "/authorize" self.state = "123123%25" query = urllib.urlencode({"client_id": "abc", "redirect_uri": self.callback_url, "response_type": "code", "state":self.state, }) location = "%s?%s" % (auth_endpoint, query) ``` And check state when receiving token: ``` def _read_auth_token(self, env): print("Receiving authorization token...") query_params = urlparse.parse_qs(env["QUERY_STRING"]) self.auth_token = query_params["code"][0] if self.state and self.state != query_params["state"][0]: raise Exception("Received auth token with invalid state. If this was a browser, CSRF") ``` Fix by url-encoding the state when applying it to redirect urls. /oauth2/grant.py ``` 469 query += "&state=" + quote(self.state) 708 uri_with_fragment += "&state=" + quote(self.state)
wndhydrnt/python-oauth2
diff --git a/oauth2/test/test_grant.py b/oauth2/test/test_grant.py index 1cb7cb2..231c3ca 100644 --- a/oauth2/test/test_grant.py +++ b/oauth2/test/test_grant.py @@ -1,6 +1,7 @@ from mock import Mock, call, patch import json from oauth2.client_authenticator import ClientAuthenticator +from oauth2.compatibility import quote from oauth2.test import unittest from oauth2.web import Request, Response, ResourceOwnerGrantSiteAdapter, \ ImplicitGrantSiteAdapter, AuthorizationCodeGrantSiteAdapter @@ -196,11 +197,11 @@ class AuthorizationCodeAuthHandlerTestCase(unittest.TestCase): code = "abcd" environ = {"session": "data"} scopes = ["scope"] - state = "mystate" + state = "my%state" redirect_uri = "https://callback" user_data = {"user_id": 789} - location_uri = "%s?code=%s&state=%s" % (redirect_uri, code, state) + location_uri = "%s?code=%s&state=%s" % (redirect_uri, code, quote(state)) auth_code_store_mock = Mock(spec=AuthCodeStore) @@ -793,6 +794,7 @@ class ImplicitGrantTestCase(unittest.TestCase): request_mock.get_param.assert_called_with("response_type") self.assertEqual(result_class, None) + class ImplicitGrantHandlerTestCase(unittest.TestCase): def test_process_redirect_with_token(self): client_id = "abc" @@ -848,11 +850,11 @@ class ImplicitGrantHandlerTestCase(unittest.TestCase): ImplicitGrantHandler should include the value of the "state" query parameter from request in redirect """ redirect_uri = "http://callback" - state = "XHGFI" + state = "XH%GFI" token = "tokencode" user_data = ({}, 1) - expected_redirect_uri = "%s#access_token=%s&token_type=bearer&state=%s" % (redirect_uri, token, state) + expected_redirect_uri = "%s#access_token=%s&token_type=bearer&state=%s" % (redirect_uri, token, quote(state)) response_mock = Mock(spec=Response)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 1 }, "num_modified_files": 2 }
0.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.9", "reqs_path": [ "requirements.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
async-timeout==5.0.1 dnspython==2.7.0 exceptiongroup==1.2.2 iniconfig==2.1.0 mock==5.2.0 mysql-connector-python @ http://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-1.1.7.tar.gz#sha256=66f9aeadf2b908be0e31bf683cfa199c1c13401eb7c0acce7cec56d75d76e24a nose==1.3.7 packaging==24.2 pluggy==1.5.0 pymongo==4.11.3 pytest==8.3.5 -e git+https://github.com/wndhydrnt/python-oauth2.git@afa9d84b54392391b888dc3bff36aaf08bbd5834#egg=python_oauth2 redis==5.2.1 tomli==2.2.1
name: python-oauth2 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: - async-timeout==5.0.1 - dnspython==2.7.0 - exceptiongroup==1.2.2 - iniconfig==2.1.0 - mock==5.2.0 - mysql-connector-python==1.1.7 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pymongo==4.11.3 - pytest==8.3.5 - redis==5.2.1 - tomli==2.2.1 prefix: /opt/conda/envs/python-oauth2
[ "oauth2/test/test_grant.py::AuthorizationCodeAuthHandlerTestCase::test_process", "oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_process_redirect_with_state" ]
[]
[ "oauth2/test/test_grant.py::AuthorizationCodeGrantTestCase::test_create_auth_handler", "oauth2/test/test_grant.py::AuthorizationCodeGrantTestCase::test_create_no_match", "oauth2/test/test_grant.py::AuthorizationCodeGrantTestCase::test_create_token_handler", "oauth2/test/test_grant.py::AuthRequestMixinTestCase::test_read_validate_params_all_valid", "oauth2/test/test_grant.py::AuthorizeMixinTestCase::test_authorize_dict_return", "oauth2/test/test_grant.py::AuthorizeMixinTestCase::test_authorize_tuple_return", "oauth2/test/test_grant.py::AuthorizeMixinTestCase::test_authorize_user_denied_access", "oauth2/test/test_grant.py::AuthorizeMixinTestCase::test_authorize_user_not_authenticated", "oauth2/test/test_grant.py::AuthorizationCodeAuthHandlerTestCase::test_process_not_confirmed", "oauth2/test/test_grant.py::AuthorizationCodeAuthHandlerTestCase::test_redirect_oauth_error", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_no_refresh_token", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_refresh_token", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_unique_access_token", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_unique_access_token_different_scope", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_unique_access_token_expired_token", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_unique_access_token_no_user_id", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_process_with_unique_access_token_not_found", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params_missing_code", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params_no_auth_code_found", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params_token_expired", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params_unknown_code", "oauth2/test/test_grant.py::AuthorizationCodeTokenHandlerTestCase::test_read_validate_params_wrong_redirect_uri_in_code_data", "oauth2/test/test_grant.py::ImplicitGrantTestCase::test_create_matching_response_type", "oauth2/test/test_grant.py::ImplicitGrantTestCase::test_create_not_matching_response_type", "oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_process_redirect_with_token", "oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_process_unconfirmed", "oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_process_user_denied_access", "oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_process_with_scope", "oauth2/test/test_grant.py::ImplicitGrantHandlerTestCase::test_redirect_oauth_error", "oauth2/test/test_grant.py::ResourceOwnerGrantTestCase::test_call", "oauth2/test/test_grant.py::ResourceOwnerGrantTestCase::test_call_no_resource_request", "oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_handle_error_owner_not_authenticated", "oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_process", "oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_process_invalid_user", "oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_process_redirect_with_scope", "oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_process_with_refresh_token", "oauth2/test/test_grant.py::ResourceOwnerGrantHandlerTestCase::test_read_validate_params", "oauth2/test/test_grant.py::ScopeTestCase::test_compare_invalid_scope_requested", "oauth2/test/test_grant.py::ScopeTestCase::test_compare_scopes_equal", "oauth2/test/test_grant.py::ScopeTestCase::test_compare_valid_scope_subset", "oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_default_on_no_matching_scopes", "oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_default_on_no_scope", "oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_exception_on_available_scopes_no_scope_given", "oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_no_value_on_no_scope_no_default", "oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_scope_present_in_body", "oauth2/test/test_grant.py::ScopeTestCase::test_parse_scope_scope_present_in_query", "oauth2/test/test_grant.py::RefreshTokenTestCase::test_call", "oauth2/test/test_grant.py::RefreshTokenTestCase::test_call_other_grant_type", "oauth2/test/test_grant.py::RefreshTokenTestCase::test_call_wrong_path", "oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_process_no_reissue", "oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_process_with_reissue", "oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_read_validate_params", "oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_read_validate_params_expired_refresh_token", "oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_read_validate_params_invalid_refresh_token", "oauth2/test/test_grant.py::RefreshTokenHandlerTestCase::test_read_validate_params_no_refresh_token", "oauth2/test/test_grant.py::ClientCredentialsGrantTestCase::test_call", "oauth2/test/test_grant.py::ClientCredentialsGrantTestCase::test_call_other_grant_type", "oauth2/test/test_grant.py::ClientCredentialsGrantTestCase::test_call_wrong_request_path", "oauth2/test/test_grant.py::ClientCredentialsHandlerTestCase::test_process", "oauth2/test/test_grant.py::ClientCredentialsHandlerTestCase::test_process_with_refresh_token", "oauth2/test/test_grant.py::ClientCredentialsHandlerTestCase::test_read_validate_params" ]
[]
MIT License
77
[ "oauth2/grant.py", "CHANGELOG.md" ]
[ "oauth2/grant.py", "CHANGELOG.md" ]
jpadilla__pyjwt-122
8f28b4a6124830fcea400668840e645bb91e38a2
2015-03-29 14:57:58
b39b9a7887c2feab1058fa371f761e1e27f6da1d
diff --git a/jwt/api.py b/jwt/api.py index 5f2ce6f..201bffd 100644 --- a/jwt/api.py +++ b/jwt/api.py @@ -181,16 +181,32 @@ class PyJWT(object): except KeyError: raise InvalidAlgorithmError('Algorithm not supported') + if 'iat' in payload: + try: + int(payload['iat']) + except ValueError: + raise DecodeError('Issued At claim (iat) must be an integer.') + if 'nbf' in payload and verify_expiration: + try: + nbf = int(payload['nbf']) + except ValueError: + raise DecodeError('Not Before claim (nbf) must be an integer.') + utc_timestamp = timegm(datetime.utcnow().utctimetuple()) - if payload['nbf'] > (utc_timestamp + leeway): + if nbf > (utc_timestamp + leeway): raise ExpiredSignatureError('Signature not yet valid') if 'exp' in payload and verify_expiration: + try: + exp = int(payload['exp']) + except ValueError: + raise DecodeError('Expiration Time claim (exp) must be an integer.') + utc_timestamp = timegm(datetime.utcnow().utctimetuple()) - if payload['exp'] < (utc_timestamp - leeway): + if exp < (utc_timestamp - leeway): raise ExpiredSignatureError('Signature has expired') if 'aud' in payload:
non-numeric expiration claim does not raise an error I would expect a non-numeric expiration claim to raise an error but it does not. To reproduce, here's a JWT with ``{exp: '<not a number>'}``': ```` >>> import jwt >>> import calendar, time >>> iat = calendar.timegm(time.gmtime()) >>> token = jwt.encode({'aud': 'some-aud', 'iss': 'some-iss', 'typ': 'some-typ', 'iat': iat, 'exp': '<not a number>', 'request': {}}, 'secret') >>> jwt.decode(token, 'secret', verify=True, audience='some-aud') {u'aud': u'some-aud', u'iss': u'some-iss', u'request': {}, u'exp': u'<not a number>', u'iat': 1427495823, u'typ': u'some-typ'} ```` If a signature checking was somehow bypassed, an expiration like this could maybe allow for replay attacks.
jpadilla/pyjwt
diff --git a/tests/test_api.py b/tests/test_api.py index 3b79490..371390d 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -195,6 +195,33 @@ class TestAPI(unittest.TestCase): exception = context.exception self.assertEquals(str(exception), 'Algorithm not supported') + def test_decode_raises_exception_if_exp_is_not_int(self): + # >>> jwt.encode({'exp': 'not-an-int'}, 'secret') + example_jwt = ('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.' + 'eyJleHAiOiJub3QtYW4taW50In0.' + 'P65iYgoHtBqB07PMtBSuKNUEIPPPfmjfJG217cEE66s') + + with self.assertRaisesRegexp(DecodeError, 'exp'): + self.jwt.decode(example_jwt, 'secret') + + def test_decode_raises_exception_if_iat_is_not_int(self): + # >>> jwt.encode({'iat': 'not-an-int'}, 'secret') + example_jwt = ('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.' + 'eyJpYXQiOiJub3QtYW4taW50In0.' + 'H1GmcQgSySa5LOKYbzGm--b1OmRbHFkyk8pq811FzZM') + + with self.assertRaisesRegexp(DecodeError, 'iat'): + self.jwt.decode(example_jwt, 'secret') + + def test_decode_raises_exception_if_nbf_is_not_int(self): + # >>> jwt.encode({'nbf': 'not-an-int'}, 'secret') + example_jwt = ('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.' + 'eyJuYmYiOiJub3QtYW4taW50In0.' + 'c25hldC8G2ZamC8uKpax9sYMTgdZo3cxrmzFHaAAluw') + + with self.assertRaisesRegexp(DecodeError, 'nbf'): + self.jwt.decode(example_jwt, 'secret') + def test_encode_datetime(self): secret = 'secret' current_datetime = datetime.utcnow()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 2, "test_score": 3 }, "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": "pytest", "pip_packages": [ "cryptography", "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" }
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@8f28b4a6124830fcea400668840e645bb91e38a2#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_api.py::TestAPI::test_decode_raises_exception_if_exp_is_not_int", "tests/test_api.py::TestAPI::test_decode_raises_exception_if_iat_is_not_int", "tests/test_api.py::TestAPI::test_decode_raises_exception_if_nbf_is_not_int" ]
[ "tests/test_api.py::TestAPI::test_decodes_valid_es384_jwt", "tests/test_api.py::TestAPI::test_decodes_valid_rs384_jwt", "tests/test_api.py::TestAPI::test_encode_decode_with_ecdsa_sha256", "tests/test_api.py::TestAPI::test_encode_decode_with_ecdsa_sha384", "tests/test_api.py::TestAPI::test_encode_decode_with_ecdsa_sha512", "tests/test_api.py::TestAPI::test_encode_decode_with_rsa_sha256", "tests/test_api.py::TestAPI::test_encode_decode_with_rsa_sha384", "tests/test_api.py::TestAPI::test_encode_decode_with_rsa_sha512" ]
[ "tests/test_api.py::TestAPI::test_algorithms_parameter_removes_alg_from_algorithms_list", "tests/test_api.py::TestAPI::test_allow_skip_verification", "tests/test_api.py::TestAPI::test_bad_secret", "tests/test_api.py::TestAPI::test_bytes_secret", "tests/test_api.py::TestAPI::test_check_audience", "tests/test_api.py::TestAPI::test_check_audience_in_array", "tests/test_api.py::TestAPI::test_check_issuer", "tests/test_api.py::TestAPI::test_custom_headers", "tests/test_api.py::TestAPI::test_custom_json_encoder", "tests/test_api.py::TestAPI::test_decode_algorithm_param_should_be_case_sensitive", "tests/test_api.py::TestAPI::test_decode_fails_when_alg_is_not_on_method_algorithms_param", "tests/test_api.py::TestAPI::test_decode_invalid_crypto_padding", "tests/test_api.py::TestAPI::test_decode_invalid_header_padding", "tests/test_api.py::TestAPI::test_decode_invalid_header_string", "tests/test_api.py::TestAPI::test_decode_invalid_payload_padding", "tests/test_api.py::TestAPI::test_decode_invalid_payload_string", "tests/test_api.py::TestAPI::test_decode_missing_segments_throws_exception", "tests/test_api.py::TestAPI::test_decode_skip_expiration_verification", "tests/test_api.py::TestAPI::test_decode_skip_notbefore_verification", "tests/test_api.py::TestAPI::test_decode_unicode_value", "tests/test_api.py::TestAPI::test_decode_with_expiration", "tests/test_api.py::TestAPI::test_decode_with_expiration_with_leeway", "tests/test_api.py::TestAPI::test_decode_with_invalid_aud_list_member_throws_exception", "tests/test_api.py::TestAPI::test_decode_with_invalid_audience_param_throws_exception", "tests/test_api.py::TestAPI::test_decode_with_non_mapping_header_throws_exception", "tests/test_api.py::TestAPI::test_decode_with_non_mapping_payload_throws_exception", "tests/test_api.py::TestAPI::test_decode_with_nonlist_aud_claim_throws_exception", "tests/test_api.py::TestAPI::test_decode_with_notbefore", "tests/test_api.py::TestAPI::test_decode_with_notbefore_with_leeway", "tests/test_api.py::TestAPI::test_decode_works_with_unicode_token", "tests/test_api.py::TestAPI::test_decodes_valid_jwt", "tests/test_api.py::TestAPI::test_ecdsa_related_algorithms", "tests/test_api.py::TestAPI::test_encode_algorithm_param_should_be_case_sensitive", "tests/test_api.py::TestAPI::test_encode_bad_type", "tests/test_api.py::TestAPI::test_encode_datetime", "tests/test_api.py::TestAPI::test_encode_decode", "tests/test_api.py::TestAPI::test_encode_decode_with_algo_none", "tests/test_api.py::TestAPI::test_invalid_crypto_alg", "tests/test_api.py::TestAPI::test_load_no_verification", "tests/test_api.py::TestAPI::test_load_verify_valid_jwt", "tests/test_api.py::TestAPI::test_no_secret", "tests/test_api.py::TestAPI::test_nonascii_secret", "tests/test_api.py::TestAPI::test_raise_exception_invalid_audience", "tests/test_api.py::TestAPI::test_raise_exception_invalid_audience_in_array", "tests/test_api.py::TestAPI::test_raise_exception_invalid_issuer", "tests/test_api.py::TestAPI::test_raise_exception_token_without_audience", "tests/test_api.py::TestAPI::test_raise_exception_token_without_issuer", "tests/test_api.py::TestAPI::test_register_algorithm_does_not_allow_duplicate_registration", "tests/test_api.py::TestAPI::test_register_algorithm_rejects_non_algorithm_obj", "tests/test_api.py::TestAPI::test_rsa_related_algorithms", "tests/test_api.py::TestAPI::test_unicode_secret", "tests/test_api.py::TestAPI::test_unregister_algorithm_removes_algorithm", "tests/test_api.py::TestAPI::test_unregister_algorithm_throws_error_if_not_registered", "tests/test_api.py::TestAPI::test_verify_signature_no_secret" ]
[]
MIT License
78
[ "jwt/api.py" ]
[ "jwt/api.py" ]
mkdocs__mkdocs-390
9b0aa1f87266f35c366ee2383987c6ba2f7b31d4
2015-04-02 07:34:11
bfc393ce2dd31d0fea2be3a5b0fec20ed361bfe0
diff --git a/.travis.sh b/.travis.sh index ab95ebbc..de43ce8e 100755 --- a/.travis.sh +++ b/.travis.sh @@ -3,7 +3,7 @@ set -xe if [ $TOX_ENV == "coverage" ] then pip install coveralls - tox -e py27 + tox -e py27-unittests coveralls else tox -e $TOX_ENV diff --git a/mkdocs/config.py b/mkdocs/config.py index aeaad94e..2b6dcebe 100644 --- a/mkdocs/config.py +++ b/mkdocs/config.py @@ -97,6 +97,18 @@ def validate_config(user_config): if not config['site_name']: raise ConfigurationError("Config must contain 'site_name' setting.") + # Validate that the docs_dir and site_dir don't contain the + # other as this will lead to copying back and forth on each + # and eventually make a deep nested mess. + abs_site_dir = os.path.abspath(config['site_dir']) + abs_docs_dir = os.path.abspath(config['docs_dir']) + if abs_docs_dir.startswith(abs_site_dir): + raise ConfigurationError( + "The 'docs_dir' can't be within the 'site_dir'.") + elif abs_site_dir.startswith(abs_docs_dir): + raise ConfigurationError( + "The 'site_dir' can't be within the 'docs_dir'.") + # If not specified, then the 'pages' config simply includes all # markdown files in the docs dir, without generating any header items # for them.
Don't allow the `site_dir` to be within the `docs_dir` This leads to the output being copied into the output during a build.
mkdocs/mkdocs
diff --git a/mkdocs/tests/config_tests.py b/mkdocs/tests/config_tests.py index b28d9465..4c27ec9a 100644 --- a/mkdocs/tests/config_tests.py +++ b/mkdocs/tests/config_tests.py @@ -111,3 +111,27 @@ class ConfigTests(unittest.TestCase): self.assertEqual(conf['pages'], ['index.md', 'about.md']) finally: shutil.rmtree(tmp_dir) + + def test_doc_dir_in_site_dir(self): + + test_configs = ( + {'docs_dir': 'docs', 'site_dir': 'docs/site'}, + {'docs_dir': 'site/docs', 'site_dir': 'site'}, + {'docs_dir': 'docs', 'site_dir': '.'}, + {'docs_dir': '.', 'site_dir': 'site'}, + {'docs_dir': '.', 'site_dir': '.'}, + {'docs_dir': 'docs', 'site_dir': ''}, + {'docs_dir': '', 'site_dir': 'site'}, + {'docs_dir': '', 'site_dir': ''}, + {'docs_dir': '../mkdocs/docs', 'site_dir': 'docs'}, + ) + + conf = { + 'site_name': 'Example', + } + + for test_config in test_configs: + + c = conf.copy() + c.update(test_config) + self.assertRaises(ConfigurationError, config.validate_config, c)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
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", "coverage", "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 coverage==6.2 ghp-import==2.1.0 importlib-metadata==4.8.3 iniconfig==1.1.1 Jinja2==3.0.3 Markdown==2.4.1 MarkupSafe==2.0.1 -e git+https://github.com/mkdocs/mkdocs.git@9b0aa1f87266f35c366ee2383987c6ba2f7b31d4#egg=mkdocs nose==1.3.7 packaging==21.3 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 tomli==1.2.3 typing_extensions==4.1.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 - coverage==6.2 - ghp-import==2.1.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jinja2==3.0.3 - markdown==2.4.1 - markupsafe==2.0.1 - nose==1.3.7 - packaging==21.3 - 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 - tomli==1.2.3 - typing-extensions==4.1.1 - watchdog==2.3.1 - zipp==3.6.0 prefix: /opt/conda/envs/mkdocs
[ "mkdocs/tests/config_tests.py::ConfigTests::test_doc_dir_in_site_dir" ]
[ "mkdocs/tests/config_tests.py::ConfigTests::test_config_option", "mkdocs/tests/config_tests.py::ConfigTests::test_empty_config", "mkdocs/tests/config_tests.py::ConfigTests::test_theme" ]
[ "mkdocs/tests/config_tests.py::ConfigTests::test_default_pages", "mkdocs/tests/config_tests.py::ConfigTests::test_missing_config_file", "mkdocs/tests/config_tests.py::ConfigTests::test_missing_site_name" ]
[]
BSD 2-Clause "Simplified" License
79
[ ".travis.sh", "mkdocs/config.py" ]
[ ".travis.sh", "mkdocs/config.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
[ "mkdocs/nav.py" ]
[ "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
[ "mkdocs/compat.py", "mkdocs/toc.py" ]
[ "mkdocs/compat.py", "mkdocs/toc.py" ]
google__vimdoc-89
301b139ce8108bf6b8e814de5a36414034aa915b
2015-04-05 04:36:47
301b139ce8108bf6b8e814de5a36414034aa915b
diff --git a/vimdoc/block.py b/vimdoc/block.py index e56c357..03bed17 100644 --- a/vimdoc/block.py +++ b/vimdoc/block.py @@ -16,6 +16,7 @@ class Block(object): contain metadata statements specifying things like the plugin author, etc. Args: + type: Block type, e.g. vim.SECTION or vim.FUNCTION. is_secondary: Whether there are other blocks above this one that describe the same item. Only primary blocks should have tags, not secondary blocks. @@ -23,7 +24,7 @@ class Block(object): this one and prevent this block from showing up in the docs. """ - def __init__(self, is_secondary=False, is_default=False): + def __init__(self, type=None, is_secondary=False, is_default=False): # May include: # deprecated (boolean) # dict (name) @@ -34,6 +35,8 @@ class Block(object): # namespace (of function) # attribute (of function in dict) self.locals = {} + if type is not None: + self.SetType(type) # Merged into module. May include: # author (string) # library (boolean) diff --git a/vimdoc/error.py b/vimdoc/error.py index ead432b..127ad53 100644 --- a/vimdoc/error.py +++ b/vimdoc/error.py @@ -116,6 +116,18 @@ class NoSuchSection(BadStructure): 'Section {} never defined.'.format(section)) +class DuplicateSection(BadStructure): + def __init__(self, section): + super(DuplicateSection, self).__init__( + 'Duplicate section {} defined.'.format(section)) + + +class DuplicateBackmatter(BadStructure): + def __init__(self, section): + super(DuplicateBackmatter, self).__init__( + 'Duplicate backmatter defined for section {}.'.format(section)) + + class NeglectedSections(BadStructure): def __init__(self, sections, order): super(NeglectedSections, self).__init__( diff --git a/vimdoc/module.py b/vimdoc/module.py index 6e76c4e..05b09d1 100644 --- a/vimdoc/module.py +++ b/vimdoc/module.py @@ -60,11 +60,17 @@ class Module(object): # Overwrite existing section if it's a default. if block_id not in self.sections or self.sections[block_id].IsDefault(): self.sections[block_id] = block + elif not block.IsDefault(): + # Tried to overwrite explicit section with explicit section. + raise error.DuplicateSection(block_id) elif typ == vimdoc.BACKMATTER: # Overwrite existing section backmatter if it's a default. if (block_id not in self.backmatters or self.backmatters[block_id].IsDefault()): self.backmatters[block_id] = block + elif not block.IsDefault(): + # Tried to overwrite explicit backmatter with explicit backmatter. + raise error.DuplicateBackmatter(block_id) else: collection_type = self.plugin.GetCollectionType(block) if collection_type is not None: @@ -107,31 +113,26 @@ class Module(object): All default sections that have not been overridden will be created. """ if self.GetCollection(vimdoc.FUNCTION) and 'functions' not in self.sections: - functions = Block() - functions.SetType(vimdoc.SECTION) + functions = Block(vimdoc.SECTION) functions.Local(id='functions', name='Functions') self.Merge(functions) if (self.GetCollection(vimdoc.EXCEPTION) and 'exceptions' not in self.sections): - exceptions = Block() - exceptions.SetType(vimdoc.SECTION) + exceptions = Block(vimdoc.SECTION) exceptions.Local(id='exceptions', name='Exceptions') self.Merge(exceptions) if self.GetCollection(vimdoc.COMMAND) and 'commands' not in self.sections: - commands = Block() - commands.SetType(vimdoc.SECTION) + commands = Block(vimdoc.SECTION) commands.Local(id='commands', name='Commands') self.Merge(commands) if self.GetCollection(vimdoc.DICTIONARY) and 'dicts' not in self.sections: - dicts = Block() - dicts.SetType(vimdoc.SECTION) + dicts = Block(vimdoc.SECTION) dicts.Local(id='dicts', name='Dictionaries') self.Merge(dicts) if self.GetCollection(vimdoc.FLAG): # If any maktaba flags were documented, add a default configuration # section to explain how to use them. - config = Block(is_default=True) - config.SetType(vimdoc.SECTION) + config = Block(vimdoc.SECTION, is_default=True) config.Local(id='config', name='Configuration') config.AddLine( 'This plugin uses maktaba flags for configuration. Install Glaive' @@ -141,29 +142,18 @@ class Module(object): if ((self.GetCollection(vimdoc.FLAG) or self.GetCollection(vimdoc.SETTING)) and 'config' not in self.sections): - config = Block() - config.SetType(vimdoc.SECTION) + config = Block(vimdoc.SECTION) config.Local(id='config', name='Configuration') self.Merge(config) - if not self.order: - self.order = [] - for builtin in [ - 'intro', - 'config', - 'commands', - 'autocmds', - 'settings', - 'dicts', - 'functions', - 'exceptions', - 'mappings', - 'about']: - if builtin in self.sections or builtin in self.backmatters: - self.order.append(builtin) + for backmatter in self.backmatters: if backmatter not in self.sections: raise error.NoSuchSection(backmatter) - known = set(self.sections) | set(self.backmatters) + # Use explicit order as partial ordering and merge with default section + # ordering. All custom sections must be ordered explicitly. + self.order = self._GetSectionOrder(self.order, self.sections) + + known = set(self.sections) neglected = sorted(known.difference(self.order)) if neglected: raise error.NeglectedSections(neglected, self.order) @@ -200,6 +190,46 @@ class Module(object): if ident in self.backmatters: yield self.backmatters[ident] + @staticmethod + def _GetSectionOrder(explicit_order, sections): + """Gets final section order from explicit_order and actual sections present. + + Built-in sections with no explicit order come before custom sections, with + two exceptions: + * The "about" section comes last by default. + * If a built-in section is explicitly ordered, it "resets" the ordering so + so that subsequent built-in sections come directly after it. + This yields the order you would intuitively expect in cases like ordering + "intro" after other sections. + """ + order = explicit_order or [] + default_order = [ + 'intro', + 'config', + 'commands', + 'autocmds', + 'settings', + 'dicts', + 'functions', + 'exceptions', + 'mappings'] + # Add any undeclared sections before custom sections, except 'about' which + # comes at the end by default. + section_insertion_idx = 0 + order = order[:] + for builtin in default_order: + if builtin in order: + # Section already present. Skip and continue later sections after it. + section_insertion_idx = order.index(builtin) + 1 + continue + else: + # If section present, insert into order at logical index. + if builtin in sections: + order.insert(section_insertion_idx, builtin) + section_insertion_idx += 1 + if 'about' in sections and 'about' not in order: + order.append('about') + return order class VimPlugin(object): """State for entire plugin (potentially multiple modules).""" @@ -249,8 +279,7 @@ class VimPlugin(object): block = candidates[0] if block is None: # Create a dummy block to get default tag. - block = Block() - block.SetType(typ) + block = Block(typ) block.Local(name=fullname) return block.TagName() @@ -353,8 +382,7 @@ def Modules(directory): flagpath = relative_path if flagpath.startswith('after' + os.path.sep): flagpath = os.path.relpath(flagpath, 'after') - flagblock = Block(is_default=True) - flagblock.SetType(vimdoc.FLAG) + flagblock = Block(vimdoc.FLAG, is_default=True) name_parts = os.path.splitext(flagpath)[0].split(os.path.sep) flagname = name_parts.pop(0) flagname += ''.join('[' + p + ']' for p in name_parts)
More intuitive section/order handling It's annoying how you don't have to specify section order with the `@order` directive until you add the first custom section, at which point you have to explicitly list every section ID in the order. You have to cross-reference the list of default sections if you want to preserve the default sections and order. Also, if you have redundant definitions for the same section, vimdoc should complain instead of just picking one at random.
google/vimdoc
diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/module_tests.py b/tests/module_tests.py new file mode 100644 index 0000000..1226997 --- /dev/null +++ b/tests/module_tests.py @@ -0,0 +1,92 @@ +import unittest + +import vimdoc +from vimdoc.block import Block +from vimdoc import error +from vimdoc import module + +class TestVimModule(unittest.TestCase): + + def test_section(self): + plugin = module.VimPlugin('myplugin') + main_module = module.Module('myplugin', plugin) + intro = Block(vimdoc.SECTION) + intro.Local(name='Introduction', id='intro') + main_module.Merge(intro) + main_module.Close() + self.assertEqual([intro], list(main_module.Chunks())) + + def test_duplicate_section(self): + plugin = module.VimPlugin('myplugin') + main_module = module.Module('myplugin', plugin) + intro = Block(vimdoc.SECTION) + intro.Local(name='Introduction', id='intro') + main_module.Merge(intro) + intro2 = Block(vimdoc.SECTION) + intro2.Local(name='Intro', id='intro') + with self.assertRaises(error.DuplicateSection) as cm: + main_module.Merge(intro2) + self.assertEqual(('Duplicate section intro defined.',), cm.exception.args) + + def test_default_section_ordering(self): + """Sections should be ordered according to documented built-in ordering.""" + plugin = module.VimPlugin('myplugin') + main_module = module.Module('myplugin', plugin) + intro = Block(vimdoc.SECTION) + intro.Local(name='Introduction', id='intro') + commands = Block(vimdoc.SECTION) + commands.Local(name='Commands', id='commands') + about = Block(vimdoc.SECTION) + about.Local(name='About', id='about') + # Merge in arbitrary order. + main_module.Merge(commands) + main_module.Merge(about) + main_module.Merge(intro) + main_module.Close() + self.assertEqual([intro, commands, about], list(main_module.Chunks())) + + def test_manual_section_ordering(self): + """Sections should be ordered according to explicitly configured order.""" + plugin = module.VimPlugin('myplugin') + main_module = module.Module('myplugin', plugin) + intro = Block(vimdoc.SECTION) + intro.Local(name='Introduction', id='intro') + # Configure explicit order. + intro.Global(order=['commands', 'about', 'intro']) + commands = Block(vimdoc.SECTION) + commands.Local(name='Commands', id='commands') + about = Block(vimdoc.SECTION) + about.Local(name='About', id='about') + # Merge in arbitrary order. + main_module.Merge(commands) + main_module.Merge(about) + main_module.Merge(intro) + main_module.Close() + self.assertEqual([commands, about, intro], list(main_module.Chunks())) + + def test_partial_ordering(self): + """Always respect explicit order and prefer built-in ordering. + + Undeclared built-in sections will be inserted into explicit order according + to default built-in ordering. The about section should come after custom + sections unless explicitly ordered.""" + plugin = module.VimPlugin('myplugin') + main_module = module.Module('myplugin', plugin) + intro = Block(vimdoc.SECTION) + intro.Local(name='Introduction', id='intro') + # Configure explicit order. + intro.Global(order=['custom1', 'intro', 'custom2']) + commands = Block(vimdoc.SECTION) + commands.Local(name='Commands', id='commands') + about = Block(vimdoc.SECTION) + about.Local(name='About', id='about') + custom1 = Block(vimdoc.SECTION) + custom1.Local(name='Custom1', id='custom1') + custom2 = Block(vimdoc.SECTION) + custom2.Local(name='Custom2', id='custom2') + # Merge in arbitrary order. + for section in [commands, custom2, about, intro, custom1]: + main_module.Merge(section) + main_module.Close() + self.assertEqual([custom1, intro, commands, custom2, about], + list(main_module.Chunks()))
{ "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": 2, "issue_text_score": 2, "test_score": 3 }, "num_modified_files": 3 }
0.5
{ "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" }
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/vimdoc.git@301b139ce8108bf6b8e814de5a36414034aa915b#egg=vimdoc
name: vimdoc 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/vimdoc
[ "tests/module_tests.py::TestVimModule::test_default_section_ordering", "tests/module_tests.py::TestVimModule::test_duplicate_section", "tests/module_tests.py::TestVimModule::test_manual_section_ordering", "tests/module_tests.py::TestVimModule::test_partial_ordering", "tests/module_tests.py::TestVimModule::test_section" ]
[]
[]
[]
Apache License 2.0
82
[ "vimdoc/block.py", "vimdoc/module.py", "vimdoc/error.py" ]
[ "vimdoc/block.py", "vimdoc/module.py", "vimdoc/error.py" ]
jpadilla__pyjwt-131
a2601ad46433a99c8777a74abeaf4dfd70630d17
2015-04-07 04:00:01
b39b9a7887c2feab1058fa371f761e1e27f6da1d
diff --git a/AUTHORS b/AUTHORS index be65bf8..02fbc3b 100644 --- a/AUTHORS +++ b/AUTHORS @@ -21,3 +21,5 @@ Patches and Suggestions - Mark Adams <[email protected]> - Wouter Bolsterlee <[email protected]> + + - Michael Davis <[email protected]> <[email protected]> diff --git a/CHANGELOG.md b/CHANGELOG.md index ced0519..1564f5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ This project adheres to [Semantic Versioning](http://semver.org/). ------------------------------------------------------------------------- ### Changed - Added this CHANGELOG.md file +- Added flexible and complete verification options. #131 ### Fixed - Placeholder diff --git a/README.md b/README.md index 167f78e..5ae0b40 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,34 @@ except jwt.InvalidTokenError: pass # do something sensible here, e.g. return HTTP 403 status code ``` +You may also override exception checking via an `options` dictionary. The default +options are as follows: + +```python +options = { + 'verify_signature': True, + 'verify_exp': True, + 'verify_nbf': True, + 'verify_iat': True, + 'verify_aud`: True +} +``` + +You can skip individual checks by passing an `options` dictionary with certain keys set to `False`. +For example, if you want to verify the signature of a JWT that has already expired. + +```python +options = { + 'verify_exp': True, +} + +jwt.decode('someJWTstring', 'secret', options=options) +``` + +**NOTE**: *Changing the default behavior is done at your own risk, and almost certainly will make your +application less secure. Doing so should only be done with a very clear understanding of what you +are doing.* + ## Tests You can run tests from the project root after cloning with: diff --git a/jwt/api.py b/jwt/api.py index 6d39d8d..68d30f6 100644 --- a/jwt/api.py +++ b/jwt/api.py @@ -16,7 +16,7 @@ from .utils import base64url_decode, base64url_encode class PyJWT(object): - def __init__(self, algorithms=None): + def __init__(self, algorithms=None, options=None): self._algorithms = get_default_algorithms() self._valid_algs = set(algorithms) if algorithms is not None else set(self._algorithms) @@ -25,6 +25,19 @@ class PyJWT(object): if key not in self._valid_algs: del self._algorithms[key] + if not options: + options = {} + + self.default_options = { + 'verify_signature': True, + 'verify_exp': True, + 'verify_nbf': True, + 'verify_iat': True, + 'verify_aud': True, + } + + self.options = self._merge_options(self.default_options, options) + def register_algorithm(self, alg_id, alg_obj): """ Registers a new Algorithm for use when creating and verifying tokens. @@ -110,14 +123,16 @@ class PyJWT(object): return b'.'.join(segments) - def decode(self, jwt, key='', verify=True, algorithms=None, **kwargs): + def decode(self, jwt, key='', verify=True, algorithms=None, options=None, **kwargs): payload, signing_input, header, signature = self._load(jwt) if verify: - self._verify_signature(payload, signing_input, header, signature, - key, algorithms) + merged_options = self._merge_options(override_options=options) + if merged_options.get('verify_signature'): + self._verify_signature(payload, signing_input, header, signature, + key, algorithms) - self._validate_claims(payload, **kwargs) + self._validate_claims(payload, options=merged_options, **kwargs) return payload @@ -177,8 +192,8 @@ class PyJWT(object): except KeyError: raise InvalidAlgorithmError('Algorithm not supported') - def _validate_claims(self, payload, verify_expiration=True, leeway=0, - audience=None, issuer=None): + def _validate_claims(self, payload, audience=None, issuer=None, leeway=0, + options=None, **kwargs): if isinstance(leeway, timedelta): leeway = timedelta_total_seconds(leeway) @@ -187,7 +202,7 @@ class PyJWT(object): now = timegm(datetime.utcnow().utctimetuple()) - if 'iat' in payload: + if 'iat' in payload and options.get('verify_iat'): try: iat = int(payload['iat']) except ValueError: @@ -196,7 +211,7 @@ class PyJWT(object): if iat > (now + leeway): raise InvalidIssuedAtError('Issued At claim (iat) cannot be in the future.') - if 'nbf' in payload and verify_expiration: + if 'nbf' in payload and options.get('verify_nbf'): try: nbf = int(payload['nbf']) except ValueError: @@ -205,7 +220,7 @@ class PyJWT(object): if nbf > (now + leeway): raise ImmatureSignatureError('The token is not yet valid (nbf)') - if 'exp' in payload and verify_expiration: + if 'exp' in payload and options.get('verify_exp'): try: exp = int(payload['exp']) except ValueError: @@ -214,7 +229,7 @@ class PyJWT(object): if exp < (now - leeway): raise ExpiredSignatureError('Signature has expired') - if 'aud' in payload: + if 'aud' in payload and options.get('verify_aud'): audience_claims = payload['aud'] if isinstance(audience_claims, string_types): audience_claims = [audience_claims] @@ -233,6 +248,21 @@ class PyJWT(object): if payload.get('iss') != issuer: raise InvalidIssuerError('Invalid issuer') + def _merge_options(self, default_options=None, override_options=None): + if not default_options: + default_options = {} + + if not override_options: + override_options = {} + + try: + merged_options = self.default_options.copy() + merged_options.update(override_options) + except (AttributeError, ValueError) as e: + raise TypeError('options must be a dictionary: %s' % e) + + return merged_options + _jwt_global_obj = PyJWT() encode = _jwt_global_obj.encode
Add more flexible and complete verification options I was thinking that it might be useful for us to implement more flexible verification options. I propose something like this: ``` def decode(token, secret, options=None) ``` where options is a dict that looks something like this: ``` options = { 'verify_signature': True, 'verify_exp': True, 'verify_nbf': True, 'verify_iat': True, 'verify_aud`: True } ``` This is similar to what [ruby-jwt does](https://github.com/progrium/ruby-jwt/blob/master/lib/jwt.rb#L110) We could make it where options could be specified globally (at the PyJWT object level) or as an override argument to `decode()`
jpadilla/pyjwt
diff --git a/tests/test_api.py b/tests/test_api.py index f1734b4..33ccd51 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -71,6 +71,27 @@ class TestAPI(unittest.TestCase): self.assertNotIn('none', self.jwt.get_algorithms()) self.assertIn('HS256', self.jwt.get_algorithms()) + def test_default_options(self): + self.assertEqual(self.jwt.default_options, self.jwt.options) + + def test_override_options(self): + self.jwt = PyJWT(options={'verify_exp': False, 'verify_nbf': False}) + expected_options = self.jwt.default_options + expected_options['verify_exp'] = False + expected_options['verify_nbf'] = False + self.assertEqual(expected_options, self.jwt.options) + + def test_non_default_options_persist(self): + self.jwt = PyJWT(options={'verify_iat': False, 'foobar': False}) + expected_options = self.jwt.default_options + expected_options['verify_iat'] = False + expected_options['foobar'] = False + self.assertEqual(expected_options, self.jwt.options) + + def test_options_must_be_dict(self): + self.assertRaises(TypeError, PyJWT, options=object()) + self.assertRaises(TypeError, PyJWT, options=('something')) + def test_encode_decode(self): secret = 'secret' jwt_message = self.jwt.encode(self.payload, secret) @@ -467,14 +488,14 @@ class TestAPI(unittest.TestCase): secret = 'secret' jwt_message = self.jwt.encode(self.payload, secret) - self.jwt.decode(jwt_message, secret, verify_expiration=False) + self.jwt.decode(jwt_message, secret, options={'verify_exp': False}) def test_decode_skip_notbefore_verification(self): self.payload['nbf'] = time.time() + 10 secret = 'secret' jwt_message = self.jwt.encode(self.payload, secret) - self.jwt.decode(jwt_message, secret, verify_expiration=False) + self.jwt.decode(jwt_message, secret, options={'verify_nbf': False}) def test_decode_with_expiration_with_leeway(self): self.payload['exp'] = utc_timestamp() - 2 @@ -765,6 +786,52 @@ class TestAPI(unittest.TestCase): with self.assertRaises(InvalidIssuerError): self.jwt.decode(token, 'secret', issuer=issuer) + def test_skip_check_audience(self): + payload = { + 'some': 'payload', + 'aud': 'urn:me', + } + token = self.jwt.encode(payload, 'secret') + self.jwt.decode(token, 'secret', options={'verify_aud': False}) + + def test_skip_check_exp(self): + payload = { + 'some': 'payload', + 'exp': datetime.utcnow() - timedelta(days=1) + } + token = self.jwt.encode(payload, 'secret') + self.jwt.decode(token, 'secret', options={'verify_exp': False}) + + def test_skip_check_signature(self): + token = ("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" + ".eyJzb21lIjoicGF5bG9hZCJ9" + ".4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZA") + self.jwt.decode(token, 'secret', options={'verify_signature': False}) + + def test_skip_check_iat(self): + payload = { + 'some': 'payload', + 'iat': datetime.utcnow() + timedelta(days=1) + } + token = self.jwt.encode(payload, 'secret') + self.jwt.decode(token, 'secret', options={'verify_iat': False}) + + def test_skip_check_nbf(self): + payload = { + 'some': 'payload', + 'nbf': datetime.utcnow() + timedelta(days=1) + } + token = self.jwt.encode(payload, 'secret') + self.jwt.decode(token, 'secret', options={'verify_nbf': False}) + + def test_decode_options_must_be_dict(self): + payload = { + 'some': 'payload', + } + token = self.jwt.encode(payload, 'secret') + self.assertRaises(TypeError, self.jwt.decode, token, 'secret', options=object()) + self.assertRaises(TypeError, self.jwt.decode, token, 'secret', options='something') + def test_custom_json_encoder(self): class CustomJSONEncoder(json.JSONEncoder):
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "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": 0, "test_score": 0 }, "num_modified_files": 4 }
1.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": [ "coverage", "unittest2", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "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 coverage==6.2 importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work linecache2==1.0.0 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 -e git+https://github.com/jpadilla/pyjwt.git@a2601ad46433a99c8777a74abeaf4dfd70630d17#egg=PyJWT pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work pytest==6.2.4 six==1.17.0 toml @ file:///tmp/build/80754af9/toml_1616166611790/work traceback2==1.4.0 typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work unittest2==1.1.0 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/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 - 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: - argparse==1.4.0 - coverage==6.2 - linecache2==1.0.0 - six==1.17.0 - traceback2==1.4.0 - unittest2==1.1.0 prefix: /opt/conda/envs/pyjwt
[ "tests/test_api.py::TestAPI::test_decode_skip_expiration_verification", "tests/test_api.py::TestAPI::test_decode_skip_notbefore_verification", "tests/test_api.py::TestAPI::test_default_options", "tests/test_api.py::TestAPI::test_non_default_options_persist", "tests/test_api.py::TestAPI::test_override_options", "tests/test_api.py::TestAPI::test_skip_check_audience", "tests/test_api.py::TestAPI::test_skip_check_exp", "tests/test_api.py::TestAPI::test_skip_check_iat", "tests/test_api.py::TestAPI::test_skip_check_nbf", "tests/test_api.py::TestAPI::test_skip_check_signature" ]
[]
[ "tests/test_api.py::TestAPI::test_algorithms_parameter_removes_alg_from_algorithms_list", "tests/test_api.py::TestAPI::test_allow_skip_verification", "tests/test_api.py::TestAPI::test_bad_secret", "tests/test_api.py::TestAPI::test_bytes_secret", "tests/test_api.py::TestAPI::test_check_audience_in_array_when_valid", "tests/test_api.py::TestAPI::test_check_audience_when_valid", "tests/test_api.py::TestAPI::test_check_issuer_when_valid", "tests/test_api.py::TestAPI::test_custom_json_encoder", "tests/test_api.py::TestAPI::test_decode_algorithm_param_should_be_case_sensitive", "tests/test_api.py::TestAPI::test_decode_fails_when_alg_is_not_on_method_algorithms_param", "tests/test_api.py::TestAPI::test_decode_invalid_crypto_padding", "tests/test_api.py::TestAPI::test_decode_invalid_header_padding", "tests/test_api.py::TestAPI::test_decode_invalid_header_string", "tests/test_api.py::TestAPI::test_decode_invalid_payload_padding", "tests/test_api.py::TestAPI::test_decode_invalid_payload_string", "tests/test_api.py::TestAPI::test_decode_missing_segments_throws_exception", "tests/test_api.py::TestAPI::test_decode_options_must_be_dict", "tests/test_api.py::TestAPI::test_decode_raises_exception_if_exp_is_not_int", "tests/test_api.py::TestAPI::test_decode_raises_exception_if_iat_in_the_future", "tests/test_api.py::TestAPI::test_decode_raises_exception_if_iat_is_not_int", "tests/test_api.py::TestAPI::test_decode_raises_exception_if_nbf_is_not_int", "tests/test_api.py::TestAPI::test_decode_unicode_value", "tests/test_api.py::TestAPI::test_decode_with_algo_none_and_verify_false_should_pass", "tests/test_api.py::TestAPI::test_decode_with_algo_none_should_fail", "tests/test_api.py::TestAPI::test_decode_with_expiration", "tests/test_api.py::TestAPI::test_decode_with_expiration_with_leeway", "tests/test_api.py::TestAPI::test_decode_with_invalid_aud_list_member_throws_exception", "tests/test_api.py::TestAPI::test_decode_with_invalid_audience_param_throws_exception", "tests/test_api.py::TestAPI::test_decode_with_non_mapping_header_throws_exception", "tests/test_api.py::TestAPI::test_decode_with_non_mapping_payload_throws_exception", "tests/test_api.py::TestAPI::test_decode_with_nonlist_aud_claim_throws_exception", "tests/test_api.py::TestAPI::test_decode_with_notbefore", "tests/test_api.py::TestAPI::test_decode_with_notbefore_with_leeway", "tests/test_api.py::TestAPI::test_decode_works_with_unicode_token", "tests/test_api.py::TestAPI::test_decodes_valid_jwt", "tests/test_api.py::TestAPI::test_ecdsa_related_algorithms", "tests/test_api.py::TestAPI::test_encode_algorithm_param_should_be_case_sensitive", "tests/test_api.py::TestAPI::test_encode_bad_type", "tests/test_api.py::TestAPI::test_encode_datetime", "tests/test_api.py::TestAPI::test_encode_decode", "tests/test_api.py::TestAPI::test_invalid_crypto_alg", "tests/test_api.py::TestAPI::test_load_no_verification", "tests/test_api.py::TestAPI::test_load_verify_valid_jwt", "tests/test_api.py::TestAPI::test_no_secret", "tests/test_api.py::TestAPI::test_nonascii_secret", "tests/test_api.py::TestAPI::test_options_must_be_dict", "tests/test_api.py::TestAPI::test_raise_exception_invalid_audience", "tests/test_api.py::TestAPI::test_raise_exception_invalid_audience_in_array", "tests/test_api.py::TestAPI::test_raise_exception_invalid_issuer", "tests/test_api.py::TestAPI::test_raise_exception_token_without_audience", "tests/test_api.py::TestAPI::test_raise_exception_token_without_issuer", "tests/test_api.py::TestAPI::test_register_algorithm_does_not_allow_duplicate_registration", "tests/test_api.py::TestAPI::test_register_algorithm_rejects_non_algorithm_obj", "tests/test_api.py::TestAPI::test_rsa_related_algorithms", "tests/test_api.py::TestAPI::test_unicode_secret", "tests/test_api.py::TestAPI::test_unregister_algorithm_removes_algorithm", "tests/test_api.py::TestAPI::test_unregister_algorithm_throws_error_if_not_registered", "tests/test_api.py::TestAPI::test_verify_signature_with_no_secret" ]
[]
MIT License
83
[ "jwt/api.py", "README.md", "CHANGELOG.md", "AUTHORS" ]
[ "jwt/api.py", "README.md", "CHANGELOG.md", "AUTHORS" ]
google__yapf-75
cfb99aba49789019542ec6cb2b3f7215d1f9a04f
2015-04-07 05:21:11
5e7c8aadfe6ed7d892e858b305ef2ca60c65bfcc
coveralls: [![Coverage Status](https://coveralls.io/builds/2278632/badge)](https://coveralls.io/builds/2278632) Coverage decreased (-0.05%) to 90.88% when pulling **da1a700cebe8bc3698a501766295befafccaa404 on hayd:fix_74** into **cfb99aba49789019542ec6cb2b3f7215d1f9a04f on google:master**. coveralls: [![Coverage Status](https://coveralls.io/builds/2278632/badge)](https://coveralls.io/builds/2278632) Coverage decreased (-0.81%) to 90.12% when pulling **da1a700cebe8bc3698a501766295befafccaa404 on hayd:fix_74** into **cfb99aba49789019542ec6cb2b3f7215d1f9a04f on google:master**.
diff --git a/plugins/yapf.vim b/plugins/yapf.vim index cdbb048..3b43104 100644 --- a/plugins/yapf.vim +++ b/plugins/yapf.vim @@ -23,7 +23,7 @@ function! yapf#YAPF() range " Determine range to format. let l:line_ranges = a:firstline . '-' . a:lastline - let l:cmd = 'yapf --lines=' . l:line_ranges + let l:cmd = 'env PYTHONPATH=<path_to_srcdir>/yapf <path_to_python>/python -m yapf --lines=' . l:line_ranges " Call YAPF with the current buffer let l:formatted_text = system(l:cmd, join(getline(1, '$'), "\n") . "\n") diff --git a/yapf/yapflib/reformatter.py b/yapf/yapflib/reformatter.py index d8fcd79..6d0f5f2 100644 --- a/yapf/yapflib/reformatter.py +++ b/yapf/yapflib/reformatter.py @@ -102,7 +102,10 @@ def _RetainVerticalSpacing(prev_uwline, cur_uwline): """Retain all vertical spacing between lines.""" if not prev_uwline: return - prev_lineno = prev_uwline.last.lineno + if prev_uwline.last.is_string: + prev_lineno = prev_uwline.last.lineno + prev_uwline.last.value.count('\n') + else: + prev_lineno = prev_uwline.last.lineno if cur_uwline.first.is_comment: cur_lineno = cur_uwline.first.lineno - cur_uwline.first.value.count('\n') else:
Fixing lines with a multi-line string inserts too many lines Note: I have a fix for this #74. ``` code = '"""\ndocstring\n\n"""\n\nimport blah' from yapf.yapflib.yapf_api import FormatCode In [4]: FormatCode(code) Out[4]: '"""\ndocstring\n\n"""\n\nimport blah\n' In [5]: FormatCode(code, lines=[(2, 2)]) Out[5]: '"""\ndocstring\n\n"""\n\n\n\n\nimport blah\n' ``` The latter now has (the number of lines in the multi-line string) too many newlines. *This is an off-by-number-of-lines due to [this value](https://github.com/google/yapf/blob/cfb99aba49789019542ec6cb2b3f7215d1f9a04f/yapf/yapflib/reformatter.py#L105).*
google/yapf
diff --git a/yapftests/yapf_test.py b/yapftests/yapf_test.py index 5ae4e46..fb9f201 100644 --- a/yapftests/yapf_test.py +++ b/yapftests/yapf_test.py @@ -503,6 +503,24 @@ class CommandLineTest(unittest.TestCase): self.assertIsNone(stderrdata) self.assertEqual(reformatted_code.decode('utf-8'), expected_formatted_code) + unformatted_code = textwrap.dedent(u"""\ + ''' + docstring + + ''' + + import blah + """) + + p = subprocess.Popen(YAPF_BINARY + ['--lines', '2-2'], + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + stderr=subprocess.STDOUT) + reformatted_code, stderrdata = p.communicate( + unformatted_code.encode('utf-8')) + self.assertIsNone(stderrdata) + self.assertEqual(reformatted_code.decode('utf-8'), unformatted_code) + if __name__ == '__main__': unittest.main()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "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" ], "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==1.2.2 iniconfig==2.1.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1 -e git+https://github.com/google/yapf.git@cfb99aba49789019542ec6cb2b3f7215d1f9a04f#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 - 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 - tomli==2.2.1 prefix: /opt/conda/envs/yapf
[ "yapftests/yapf_test.py::CommandLineTest::testREtainingVerticalWhitespace" ]
[]
[ "yapftests/yapf_test.py::YapfTest::testNoEndingNewline", "yapftests/yapf_test.py::YapfTest::testSimple", "yapftests/yapf_test.py::CommandLineTest::testDisableButAdjustIndentations", "yapftests/yapf_test.py::CommandLineTest::testDisableWholeDataStructure", "yapftests/yapf_test.py::CommandLineTest::testEncodingVerification", "yapftests/yapf_test.py::CommandLineTest::testInPlaceReformatting", "yapftests/yapf_test.py::CommandLineTest::testReadFromStdin", "yapftests/yapf_test.py::CommandLineTest::testReadSingleLineCodeFromStdin", "yapftests/yapf_test.py::CommandLineTest::testReformattingSkippingLines", "yapftests/yapf_test.py::CommandLineTest::testReformattingSkippingSingleLine", "yapftests/yapf_test.py::CommandLineTest::testReformattingSkippingToEndOfFile", "yapftests/yapf_test.py::CommandLineTest::testReformattingSpecificLines", "yapftests/yapf_test.py::CommandLineTest::testRetainingHorizontalWhitespace", "yapftests/yapf_test.py::CommandLineTest::testSetCustomStyleBasedOnGoogle", "yapftests/yapf_test.py::CommandLineTest::testSetGoogleStyle", "yapftests/yapf_test.py::CommandLineTest::testUnicodeEncodingPipedToFile" ]
[]
Apache License 2.0
84
[ "plugins/yapf.vim", "yapf/yapflib/reformatter.py" ]
[ "plugins/yapf.vim", "yapf/yapflib/reformatter.py" ]
mkdocs__mkdocs-435
a633d92852794d8d86c289bcafa9121d680b1ae9
2015-04-08 16:12:44
bfc393ce2dd31d0fea2be3a5b0fec20ed361bfe0
diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md index fbd5a287..bb0ba228 100644 --- a/docs/user-guide/configuration.md +++ b/docs/user-guide/configuration.md @@ -200,6 +200,22 @@ For example, to enable the [SmartyPants typography extension][smarty], use: markdown_extensions: [smartypants] +Some extensions provide configuration options of their own. If you would like to set any configuration options, then you can define `markdown_extensions` as a key/value mapping rather than a list. The key must be the name of the extension and the value must be a key/value pair (option name/option value) for the configuration option. + +For example, to enable permalinks in the (included) `toc` extension, use: + + markdown_extensions: + toc: + permalink: True + +Add additonal items for each extension. If you have no configuration options to set for a specific extension, then you may leave that extensions options blank: + + markdown_extensions: + smartypants: + toc: + permalink: True + + **default**: `[]` [pymdk-extensions]: http://pythonhosted.org/Markdown/extensions/index.html diff --git a/mkdocs/build.py b/mkdocs/build.py index bda72820..cd29d3c3 100644 --- a/mkdocs/build.py +++ b/mkdocs/build.py @@ -28,11 +28,18 @@ def convert_markdown(markdown_source, site_navigation=None, extensions=(), stric """ # Generate the HTML from the markdown source + if isinstance(extensions, dict): + user_extensions = list(extensions.keys()) + extension_configs = dict([(k, v) for k, v in extensions.items() if isinstance(v, dict)]) + else: + user_extensions = list(extensions) + extension_configs = {} builtin_extensions = ['meta', 'toc', 'tables', 'fenced_code'] mkdocs_extensions = [RelativePathExtension(site_navigation, strict), ] - extensions = builtin_extensions + mkdocs_extensions + list(extensions) + extensions = set(builtin_extensions + mkdocs_extensions + user_extensions) md = markdown.Markdown( - extensions=extensions + extensions=extensions, + extension_configs=extension_configs ) html_content = md.convert(markdown_source)
Support Markdown Extension Configs Mkdocs uses Python-Markdown and offers support for users to specify extensions supported by Python-Markdown. However, currently mkdocs provides no way (sort-of; see below) to pass config settings into the extensions specified. For example, I would often like to use the [TOC][1] Extension's `permalink` feature to add the paragraph symbol (¶ or `&para;`) to the end of each header (`h1-6`) as a self-link. A very handy feature in documentation (in fact, it's used by Python-Markdown's docs, which I've linked to). Another use may be to customize how [syntax highlighting][2] works. Or non-english users may want to override the default substitutions used by [SmartyPants][3]. etc, etc... Sure, mkdocs could hard-code some specific settings for things that make sense. Granted, not all extensions configs make sense in the context of mkdocs. But do you really want to be fielding bug reports for years to come asking for some additional config setting? And don't forget about [third party extensions][9]. Some of them (like a few of the math extensions) make a lot of sense for some users of mkdocs. But you couldn't possibly expect to provide good support for them without offering a holistic approach. Interestingly, as mkdocs' config file is YAML and Python-Markdown's [`extension_configs`][4] keyword accepts a dictionary of dictionaries, it is pretty easy to replicate in the config file. Of note is the recent addition to Python-Markdown's CLI of support for a [YAML config file][5] for this very thing. One difference I would suggest is that, unlike the CLI feature, there should be no need to also provide a list of extensions separate from the extension configs. I would expect the implementation to be something like this: ```python if isinstance(config['markdown_extensions'], dict): extensions = config['markdown_extensions'].keys() extensions_configs = config['markdown_extensions'] else: # backward compat with old list type extensions = config['markdown_extensions'] extensions_configs = {} # then later in the code... md = markdown.Markdown( extensions=extensions, extensions_configs = extensions_configs ) html_content = md.convert(markdown_source) ``` Note that support for the existing list of extensions is still supported. The new behavior only happens when the config setting is of the dict type. And the new format in the config file would look something like this: ```yaml markdown_extensions: markdown.extensions.toc: permalink: True markdown.extensions.codehilite: linenums: True markdown.extensions.smarty: smart_angled_quotes: True, substitutions: left-single-quote: '&sbquo;', right-single-quote: '&lsquo;', left-double-quote: '&bdquo;', right-double-quote: '&ldquo;' ``` A few notes about this proposal: 1. Actually mkdocs does provide a method of sorts for passing in config settings which involves including the settings right in the name of the extension (see the [old docs][7]). However, that behavior is [deprecated][6] in Python-Markdown 2.6 (released yesterday) and was "pending deprecation" in 2.5. Even in older versions, it is very limited as no spaces are allowed and only string types could be used (booleans were tricky -- usually a 0 or 1 and then special code in the extension to call `int()` on the string). 2. In previous versions of Python-Markdown (prior to version 2.5), the `extensions_configs` keyword expected a list of tuples for each extension rather than a dictionary (again see the [old docs][8]). That being the case, the earliest version of Python-Markdown this would work with is 2.5. 3. As of today, mkdocs only supports Python-Markdown version 2.4 as that was the last version to support Python 2.6 (see #165). However, dropping support for Python 2.6 appears to be earmarked for mkdoc 1.0.0 (0.12.0 is currently in development with 1.0.0 being the next milestone). Given the above, I expect that this feature would be added to 1.0 at the earliest (although I understand if the desire is to not add any new features until after 1.0). Given that fact, I don't see much point in actually creating a pull request just yet (with tests and docs -- the code changes are pretty simple -- see above) as I'm not really interested in continually rebasing it until you guys are ready to accept it. That said, if the idea is accepted, I'll happily do the work when the time comes. If, on the other hand, you guys are not interested in adding support for this, I'll probably look for another project which fits my needs better (not having this is a non-starter for me). [1]: https://pythonhosted.org/Markdown/extensions/toc.html#usage [2]: https://pythonhosted.org/Markdown/extensions/code_hilite.html#usage [3]: https://pythonhosted.org/Markdown/extensions/smarty.html [4]: https://pythonhosted.org/Markdown/reference.html#extension_configs [5]: https://pythonhosted.org/Markdown/cli.html#using-extensions [6]: https://pythonhosted.org/Markdown/release-2.6.html#extension-configuration-as-part-of-extension-name-deprecated [7]: https://github.com/waylan/Python-Markdown/blob/e4c13788f1c6f6f204ca7c471b25246f6c156832/docs/reference.txt#L91 [8]: https://github.com/waylan/Python-Markdown/blob/e4c13788f1c6f6f204ca7c471b25246f6c156832/docs/reference.txt#L107 [9]: https://github.com/waylan/Python-Markdown/wiki/Third-Party-Extensions
mkdocs/mkdocs
diff --git a/mkdocs/tests/build_tests.py b/mkdocs/tests/build_tests.py index eaadf753..8c0808d5 100644 --- a/mkdocs/tests/build_tests.py +++ b/mkdocs/tests/build_tests.py @@ -320,3 +320,22 @@ class BuildTests(unittest.TestCase): self.assertRaises( MarkdownNotFound, build.convert_markdown, invalid, site_nav, strict=True) + + def test_extension_config(self): + """ + Test that a dictionary of 'markdown_extensions' is recognized as + both a list of extensions and a dictionary of extnesion configs. + """ + markdown_extensions = { + 'toc': {'permalink': True}, + 'meta': None # This gets ignored as it is an invalid config + } + html, toc, meta = build.convert_markdown(dedent(""" + # A Header + """), extensions=markdown_extensions) + + expected_html = dedent(""" + <h1 id="a-header">A Header<a class="headerlink" href="#a-header" title="Permanent link">&para;</a></h1> + """) + + self.assertEqual(html.strip(), expected_html)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "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 }
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", "coverage", "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 coverage==6.2 ghp-import==2.1.0 importlib-metadata==4.8.3 iniconfig==1.1.1 Jinja2==3.0.3 Markdown==3.3.7 MarkupSafe==2.0.1 -e git+https://github.com/mkdocs/mkdocs.git@a633d92852794d8d86c289bcafa9121d680b1ae9#egg=mkdocs nose==1.3.7 packaging==21.3 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 tomli==1.2.3 typing_extensions==4.1.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 - coverage==6.2 - ghp-import==2.1.0 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jinja2==3.0.3 - markdown==3.3.7 - markupsafe==2.0.1 - nose==1.3.7 - packaging==21.3 - 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 - tomli==1.2.3 - typing-extensions==4.1.1 - watchdog==2.3.1 - zipp==3.6.0 prefix: /opt/conda/envs/mkdocs
[ "mkdocs/tests/build_tests.py::BuildTests::test_extension_config" ]
[ "mkdocs/tests/build_tests.py::BuildTests::test_markdown_custom_extension" ]
[ "mkdocs/tests/build_tests.py::BuildTests::test_anchor_only_link", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_asbolute_media", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_differing_directory", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_with_anchor", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_media", "mkdocs/tests/build_tests.py::BuildTests::test_convert_markdown", "mkdocs/tests/build_tests.py::BuildTests::test_convert_multiple_internal_links", "mkdocs/tests/build_tests.py::BuildTests::test_copying_media", "mkdocs/tests/build_tests.py::BuildTests::test_dont_convert_code_block_urls", "mkdocs/tests/build_tests.py::BuildTests::test_empty_document", "mkdocs/tests/build_tests.py::BuildTests::test_ignore_external_link", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_duplicate_custom_extension", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_fenced_code_extension", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_table_extension", "mkdocs/tests/build_tests.py::BuildTests::test_not_use_directory_urls", "mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_invalid", "mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_valid" ]
[]
BSD 2-Clause "Simplified" License
85
[ "docs/user-guide/configuration.md", "mkdocs/build.py" ]
[ "docs/user-guide/configuration.md", "mkdocs/build.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
[ "mkdocs/new.py", "mkdocs/main.py" ]
[ "mkdocs/new.py", "mkdocs/main.py" ]
ReactiveX__RxPY-37
72eecb5292f7ce105fdadf3f66d9c49091e72fd5
2015-04-10 02:08:16
72eecb5292f7ce105fdadf3f66d9c49091e72fd5
diff --git a/examples/asyncio/toasyncgenerator.py b/examples/asyncio/toasyncgenerator.py index 076b82c4..9b3c2319 100644 --- a/examples/asyncio/toasyncgenerator.py +++ b/examples/asyncio/toasyncgenerator.py @@ -1,6 +1,6 @@ -import asyncio - import rx +asyncio = rx.config['asyncio'] + from rx.concurrency import AsyncIOScheduler from rx.observable import Observable from rx.internal import extensionmethod diff --git a/examples/autocomplete/autocomplete_asyncio.py b/examples/autocomplete/autocomplete_asyncio.py index 6ea4bd91..88cbd0cf 100644 --- a/examples/autocomplete/autocomplete_asyncio.py +++ b/examples/autocomplete/autocomplete_asyncio.py @@ -7,7 +7,8 @@ Uses the RxPY AsyncIOScheduler (Python 3.4 is required) """ import os -import asyncio +import rx +asyncio = rx.config['asyncio'] from tornado.websocket import WebSocketHandler from tornado.web import RequestHandler, StaticFileHandler, Application, url diff --git a/rx/__init__.py b/rx/__init__.py index f227089e..84d1f56e 100644 --- a/rx/__init__.py +++ b/rx/__init__.py @@ -1,3 +1,11 @@ +try: + import asyncio +except ImportError: + try: + import trollius as asyncio + except ImportError: + asyncio = None + try: from threading import Lock except ImportError: @@ -6,12 +14,17 @@ except ImportError: try: from asyncio import Future except ImportError: - Future = None + try: + from trollius import Future + except ImportError: + Future = None + # Rx configuration dictionary config = { "Future": Future, - "Lock": Lock + "Lock": Lock, + "asyncio": asyncio } from .observable import Observable diff --git a/rx/concurrency/mainloopscheduler/asyncioscheduler.py b/rx/concurrency/mainloopscheduler/asyncioscheduler.py index 0dd0a2de..6e1ee5d8 100644 --- a/rx/concurrency/mainloopscheduler/asyncioscheduler.py +++ b/rx/concurrency/mainloopscheduler/asyncioscheduler.py @@ -16,7 +16,9 @@ class AsyncIOScheduler(Scheduler): def __init__(self, loop=None): global asyncio - import asyncio + import rx + asyncio = rx.config['asyncio'] + self.loop = loop or asyncio.get_event_loop() def schedule(self, action, state=None):
AsyncIOScheduler for Python 2.7 via Trollius? It seems possible to make the `AsyncIOScheduler` available for Python 2.7 through the use of [trollius](http://trollius.readthedocs.org/). Perhaps it can be configured through `rx.config`, like the class for `Future` can be?
ReactiveX/RxPY
diff --git a/tests/test_concurrency/test_mainloopscheduler/py2_asyncioscheduler.py b/tests/test_concurrency/test_mainloopscheduler/py2_asyncioscheduler.py new file mode 100644 index 00000000..60d32c45 --- /dev/null +++ b/tests/test_concurrency/test_mainloopscheduler/py2_asyncioscheduler.py @@ -0,0 +1,86 @@ +from nose import SkipTest + +import rx +asyncio = rx.config['asyncio'] +if asyncio is None: + raise SkipTest("asyncio not available") + +try: + from trollius import From +except ImportError: + raise SkipTest("trollius.From not available") + +import unittest + +from datetime import datetime, timedelta +from time import sleep +from rx.concurrency import AsyncIOScheduler + +class TestAsyncIOScheduler(unittest.TestCase): + + def test_asyncio_schedule_now(self): + loop = asyncio.get_event_loop() + scheduler = AsyncIOScheduler(loop) + res = scheduler.now() - datetime.now() + assert(res < timedelta(seconds=1)) + + def test_asyncio_schedule_action(self): + loop = asyncio.get_event_loop() + + @asyncio.coroutine + def go(): + scheduler = AsyncIOScheduler(loop) + + class Nonlocal: + ran = False + + def action(scheduler, state): + Nonlocal.ran = True + + scheduler.schedule(action) + + yield From(asyncio.sleep(0.1, loop=loop)) + assert(Nonlocal.ran == True) + + loop.run_until_complete(go()) + + def test_asyncio_schedule_action_due(self): + loop = asyncio.get_event_loop() + + @asyncio.coroutine + def go(): + scheduler = AsyncIOScheduler(loop) + starttime = loop.time() + + class Nonlocal: + endtime = None + + def action(scheduler, state): + Nonlocal.endtime = loop.time() + + scheduler.schedule_relative(0.2, action) + + yield From(asyncio.sleep(0.3, loop=loop)) + diff = Nonlocal.endtime-starttime + assert(diff > 0.18) + + loop.run_until_complete(go()) + + def test_asyncio_schedule_action_cancel(self): + loop = asyncio.get_event_loop() + + @asyncio.coroutine + def go(): + class Nonlocal: + ran = False + scheduler = AsyncIOScheduler(loop) + + def action(scheduler, state): + Nonlocal.ran = True + d = scheduler.schedule_relative(0.01, action) + d.dispose() + + yield From(asyncio.sleep(0.1, loop=loop)) + assert(not Nonlocal.ran) + + loop.run_until_complete(go()) diff --git a/tests/test_concurrency/test_mainloopscheduler/py3_asyncioscheduler.py b/tests/test_concurrency/test_mainloopscheduler/py3_asyncioscheduler.py index 096256bf..b0ac51e8 100644 --- a/tests/test_concurrency/test_mainloopscheduler/py3_asyncioscheduler.py +++ b/tests/test_concurrency/test_mainloopscheduler/py3_asyncioscheduler.py @@ -1,6 +1,8 @@ -try: - import asyncio -except ImportError: +from nose import SkipTest + +import rx +asyncio = rx.config['asyncio'] +if asyncio is None: raise SkipTest("asyncio not available") import unittest diff --git a/tests/test_concurrency/test_mainloopscheduler/test_asyncioscheduler.py b/tests/test_concurrency/test_mainloopscheduler/test_asyncioscheduler.py index b7e4d0f5..ea47efe9 100644 --- a/tests/test_concurrency/test_mainloopscheduler/test_asyncioscheduler.py +++ b/tests/test_concurrency/test_mainloopscheduler/test_asyncioscheduler.py @@ -1,7 +1,8 @@ from nose import SkipTest -try: - import asyncio -except ImportError: - raise SkipTest("asyncio not available") -from .py3_asyncioscheduler import * \ No newline at end of file +import sys + +if sys.version_info.major < 3: + from .py2_asyncioscheduler import * +else: + from .py3_asyncioscheduler import * \ No newline at end of file diff --git a/tests/test_observable/py3_fromfuture.py b/tests/test_observable/py3_fromfuture.py index 122f544e..dbdf72a0 100644 --- a/tests/test_observable/py3_fromfuture.py +++ b/tests/test_observable/py3_fromfuture.py @@ -1,6 +1,11 @@ import unittest -import asyncio -from asyncio import Future + +from nose import SkipTest +import rx +asyncio = rx.config['asyncio'] +if asyncio is None: + raise SkipTest("asyncio not available") +Future = rx.config['Future'] from rx import Observable diff --git a/tests/test_observable/py3_start.py b/tests/test_observable/py3_start.py index 7900d76b..2f884355 100644 --- a/tests/test_observable/py3_start.py +++ b/tests/test_observable/py3_start.py @@ -1,6 +1,7 @@ import unittest -import asyncio -from asyncio import Future +import rx +asyncio = rx.config['asyncio'] +Future = rx.config['Future'] from rx import Observable from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable diff --git a/tests/test_observable/py3_tofuture.py b/tests/test_observable/py3_tofuture.py index 468f58fa..9795c6c9 100644 --- a/tests/test_observable/py3_tofuture.py +++ b/tests/test_observable/py3_tofuture.py @@ -1,5 +1,10 @@ import unittest -import asyncio + +from nose import SkipTest +import rx +asyncio = rx.config['asyncio'] +if asyncio is None: + raise SkipTest("asyncio not available") from rx.observable import Observable from rx.testing import TestScheduler, ReactiveTest diff --git a/tests/test_observable/test_fromfuture.py b/tests/test_observable/test_fromfuture.py index 609987e3..c2731de4 100644 --- a/tests/test_observable/test_fromfuture.py +++ b/tests/test_observable/test_fromfuture.py @@ -1,7 +1,7 @@ from nose import SkipTest -try: - import asyncio -except ImportError: - raise SkipTest("asyncio not available") + +import rx +asyncio = rx.config['asyncio'] +Future = rx.config['Future'] from .py3_fromfuture import * \ No newline at end of file diff --git a/tests/test_observable/test_start.py b/tests/test_observable/test_start.py index ea6a0136..2bca7027 100644 --- a/tests/test_observable/test_start.py +++ b/tests/test_observable/test_start.py @@ -1,7 +1,8 @@ from nose import SkipTest -try: - import asyncio -except ImportError: + +import rx +asyncio = rx.config['asyncio'] +if asyncio is None: raise SkipTest("asyncio not available") from .py3_start import * \ No newline at end of file diff --git a/tests/test_observable/test_tofuture.py b/tests/test_observable/test_tofuture.py index 2b790299..ed076ef8 100644 --- a/tests/test_observable/test_tofuture.py +++ b/tests/test_observable/test_tofuture.py @@ -1,7 +1,8 @@ from nose import SkipTest -try: - import asyncio -except ImportError: + +import rx +asyncio = rx.config['asyncio'] +if asyncio is None: raise SkipTest("asyncio not available") from .py3_tofuture import * \ No newline at end of file
{ "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": 2, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 4 }
1.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": [ "nose", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "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 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 -e git+https://github.com/ReactiveX/RxPY.git@72eecb5292f7ce105fdadf3f66d9c49091e72fd5#egg=Rx 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: RxPY 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/RxPY
[ "tests/test_concurrency/test_mainloopscheduler/py3_asyncioscheduler.py::TestAsyncIOScheduler::test_asyncio_schedule_action", "tests/test_concurrency/test_mainloopscheduler/py3_asyncioscheduler.py::TestAsyncIOScheduler::test_asyncio_schedule_action_cancel", "tests/test_concurrency/test_mainloopscheduler/py3_asyncioscheduler.py::TestAsyncIOScheduler::test_asyncio_schedule_action_due", "tests/test_concurrency/test_mainloopscheduler/py3_asyncioscheduler.py::TestAsyncIOScheduler::test_asyncio_schedule_now", "tests/test_concurrency/test_mainloopscheduler/test_asyncioscheduler.py::TestAsyncIOScheduler::test_asyncio_schedule_action", "tests/test_concurrency/test_mainloopscheduler/test_asyncioscheduler.py::TestAsyncIOScheduler::test_asyncio_schedule_action_cancel", "tests/test_concurrency/test_mainloopscheduler/test_asyncioscheduler.py::TestAsyncIOScheduler::test_asyncio_schedule_action_due", "tests/test_concurrency/test_mainloopscheduler/test_asyncioscheduler.py::TestAsyncIOScheduler::test_asyncio_schedule_now", "tests/test_observable/py3_fromfuture.py::TestFromFuture::test_future_dispose", "tests/test_observable/py3_fromfuture.py::TestFromFuture::test_future_failure", "tests/test_observable/py3_fromfuture.py::TestFromFuture::test_future_success", "tests/test_observable/py3_start.py::TestStart::test_start_action2", "tests/test_observable/py3_start.py::TestStart::test_start_async", "tests/test_observable/py3_start.py::TestStart::test_start_async_error", "tests/test_observable/py3_start.py::TestStart::test_start_func2", "tests/test_observable/py3_start.py::TestStart::test_start_funcerror", "tests/test_observable/py3_tofuture.py::TestToFuture::test_future_failure", "tests/test_observable/py3_tofuture.py::TestToFuture::test_future_success", "tests/test_observable/test_fromfuture.py::TestFromFuture::test_future_dispose", "tests/test_observable/test_fromfuture.py::TestFromFuture::test_future_failure", "tests/test_observable/test_fromfuture.py::TestFromFuture::test_future_success", "tests/test_observable/test_start.py::TestStart::test_start_action2", "tests/test_observable/test_start.py::TestStart::test_start_async", "tests/test_observable/test_start.py::TestStart::test_start_async_error", "tests/test_observable/test_start.py::TestStart::test_start_func2", "tests/test_observable/test_start.py::TestStart::test_start_funcerror", "tests/test_observable/test_tofuture.py::TestToFuture::test_future_failure", "tests/test_observable/test_tofuture.py::TestToFuture::test_future_success" ]
[]
[]
[]
MIT License
87
[ "rx/concurrency/mainloopscheduler/asyncioscheduler.py", "examples/autocomplete/autocomplete_asyncio.py", "rx/__init__.py", "examples/asyncio/toasyncgenerator.py" ]
[ "rx/concurrency/mainloopscheduler/asyncioscheduler.py", "examples/autocomplete/autocomplete_asyncio.py", "rx/__init__.py", "examples/asyncio/toasyncgenerator.py" ]
Polyconseil__getconf-11
28028bd9d85df0486e6c5c8f5bb25a9415c06816
2015-04-10 08:57:17
28028bd9d85df0486e6c5c8f5bb25a9415c06816
diff --git a/ChangeLog b/ChangeLog index 4ef00ca..55b40c1 100644 --- a/ChangeLog +++ b/ChangeLog @@ -7,6 +7,8 @@ ChangeLog *New:* * Add getfloat() method + * Allow globs in `config_files` + * <PROJECT>_CONFIG env var will now have the same behaviour than `config_files` items 1.2.1 (2014-10-24) diff --git a/README.rst b/README.rst index 61d8638..5601b1f 100644 --- a/README.rst +++ b/README.rst @@ -94,7 +94,7 @@ Features -------- **Env-based configuration files** - An extra configuration file can be provided through ``MYPROJ_CONFIG``; + An extra configuration file/directory/glob can be provided through ``MYPROJ_CONFIG``; it takes precedence over other files **Default options** diff --git a/docs/reference.rst b/docs/reference.rst index 6bf9e47..dd5d19b 100644 --- a/docs/reference.rst +++ b/docs/reference.rst @@ -16,7 +16,9 @@ The ``ConfigGetter`` class will be loaded. :param list config_files: List of ini-style configuration files to use. Each item may either be the path to a simple file, or to a directory - (if the path ends with a '/'). Each directory path will be replaced by the list of + (if the path ends with a '/') or a glob pattern (which will select all the files + matching the pattern according to the rules used by the shell). + Each directory path will be replaced by the list of its directly contained files, in alphabetical order, excluding those whose name starts with a '.'. Provided configuration files are read in the order their name was provided, diff --git a/getconf/base.py b/getconf/base.py index 1d61b67..8c7908e 100644 --- a/getconf/base.py +++ b/getconf/base.py @@ -67,27 +67,31 @@ class ConfigGetter(object): self.namespace = namespace self.defaults = defaults or {} - final_config_files = [] - for path in config_files: + self.search_files = [] + extra_config_file = os.environ.get(self._env_key('config'), None) + + for path in list(config_files) + [extra_config_file]: + if path is None: + continue # Handle '~/.foobar.conf' path = os.path.abspath(os.path.expanduser(path)) if os.path.isdir(path): - directory_files = glob.glob(os.path.join(path, '*')) + path = os.path.join(path, '*') + + self.search_files.append(path) + + final_config_files = [] + for path in self.search_files: + directory_files = glob.glob(path) + if directory_files: # Reverse order: final_config_files is parsed from left to right, # so 99_foo naturally takes precedence over 10_base final_config_files.extend(sorted(directory_files)) - else: - final_config_files.append(path) - - extra_config_file = os.environ.get(self._env_key('config'), '') - if extra_config_file: - final_config_files.append(extra_config_file) - self.search_files = final_config_files # ConfigParser's precedence rules say "later files take precedence over previous ones". # Since our final_config_files are sorted from least important to most important, # that's exactly what we need. - self.found_files = self.parser.read(self.search_files) + self.found_files = self.parser.read(final_config_files) logger.info( "Successfully loaded configuration from files %r (searching in %r)",
Load particular files from a directory When using ``ansible`` to deploy a new configuration, ``ansible`` will create backups of the files it plans to update. Here, this would be ``/path/to/file.ini.20150218``, which *will* be loaded by ``getconf``. I'd like ``getconf`` to only load ``*.ini`` files. (original french message below) > Lorsqu'ansible déploie une configuration il cré systématiquement un backup des fichiers à modifier. Dans le cas de la configuration, il cré un fichier `SINAME.ini.DATE` ce qui peut poser problème si on charge tous les fichiers d'un répertoire. > > Il ne faudrait donc charger que les fichiers `*.ini`
Polyconseil/getconf
diff --git a/tests/test_base.py b/tests/test_base.py index c1e9ba6..17673ce 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -106,7 +106,7 @@ class ConfigGetterTestCase(unittest.TestCase): def test_from_directory(self): """Test fetching from a directory.""" getter = getconf.ConfigGetter('TESTNS', config_files=[self.example_directory]) - self.assertEqual([self.example_path, self.example2_path], getter.search_files) + self.assertEqual([os.path.join(self.example_directory, '*')], getter.search_files) self.assertEqual([self.example_path, self.example2_path], getter.found_files) with Environ(TESTNS_FOO='blah'): # A non-file-defined value @@ -123,7 +123,7 @@ class ConfigGetterTestCase(unittest.TestCase): def test_from_directory_and_files(self): """Test fetching from both directories and files""" getter = getconf.ConfigGetter('TESTNS', [self.example_directory, self.example_path]) - self.assertEqual([self.example_path, self.example2_path, self.example_path], getter.search_files) + self.assertEqual([os.path.join(self.example_directory, '*'), self.example_path], getter.search_files) self.assertEqual([self.example_path, self.example2_path, self.example_path], getter.found_files) with Environ(TESTNS_FOO='blah'): # A non-file-defined value @@ -137,6 +137,36 @@ class ConfigGetterTestCase(unittest.TestCase): # A section.key defined in the base file, not overridden self.assertEqual('21', getter.get('section1.otherfoo')) + def test_from_globs(self): + """Test fetching from globs""" + getter = getconf.ConfigGetter('TESTNS', [os.path.join(self.example_directory, '*2.ini')]) + self.assertEqual([os.path.join(self.example_directory, '*2.ini')], getter.search_files) + self.assertEqual([self.example2_path], getter.found_files) + with Environ(TESTNS_FOO='blah'): + # A non-file-defined value + self.assertEqual('blah', getter.get('foo', 'foo')) + # A sectionless file-defined key + self.assertEqual('', getter.get('bar')) + # A section.key file-defined in all three => example wins + self.assertEqual('24', getter.get('section1.foo')) + # A section.key defined in the second file + self.assertEqual('13', getter.get('section2.bar')) + # A section.key defined in the base file, not overridden + self.assertEqual('', getter.get('section1.otherfoo')) + + def test_environ_defined_globs(self): + """Test reading from an environment-defined config globs""" + with Environ(TESTNS_CONFIG=os.path.join(self.example_directory, '*2.ini'), TESTNS_FOO='blah'): + getter = getconf.ConfigGetter('TESTNS', []) + self.assertEqual([os.path.join(self.example_directory, '*2.ini')], getter.search_files) + self.assertEqual([self.example2_path], getter.found_files) + # A non-file-defined value + self.assertEqual('blah', getter.get('foo', 'foo')) + # A sectionless file-defined key + self.assertEqual('', getter.get('bar')) + # A section.key file-defined + self.assertEqual('24', getter.get('section1.foo')) + def test_environ_defined_file(self): """Test reading from an environment-defined config file.""" with Environ(TESTNS_CONFIG=self.example_path, TESTNS_FOO='blah'):
{ "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": 3 }, "num_modified_files": 4 }
1.2
{ "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 -e git+https://github.com/Polyconseil/getconf.git@28028bd9d85df0486e6c5c8f5bb25a9415c06816#egg=getconf iniconfig==2.1.0 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 tomli==2.2.1 typing_extensions==4.13.0
name: getconf 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 - iniconfig==2.1.0 - 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 - tomli==2.2.1 - typing-extensions==4.13.0 prefix: /opt/conda/envs/getconf
[ "tests/test_base.py::ConfigGetterTestCase::test_environ_defined_globs", "tests/test_base.py::ConfigGetterTestCase::test_from_directory", "tests/test_base.py::ConfigGetterTestCase::test_from_directory_and_files", "tests/test_base.py::ConfigGetterTestCase::test_from_globs" ]
[]
[ "tests/test_base.py::ConfigGetterTestCase::test_defaults", "tests/test_base.py::ConfigGetterTestCase::test_defaults_with_directory", "tests/test_base.py::ConfigGetterTestCase::test_defaults_with_file", "tests/test_base.py::ConfigGetterTestCase::test_environ_defined_file", "tests/test_base.py::ConfigGetterTestCase::test_environ_overrides_config", "tests/test_base.py::ConfigGetterTestCase::test_environ_overrides_default", "tests/test_base.py::ConfigGetterTestCase::test_environ_section", "tests/test_base.py::ConfigGetterTestCase::test_environ_settings", "tests/test_base.py::ConfigGetterTestCase::test_file_overide_default", "tests/test_base.py::ConfigGetterTestCase::test_get_section_env", "tests/test_base.py::ConfigGetterTestCase::test_get_section_file", "tests/test_base.py::ConfigGetterTestCase::test_getbool_badvalue", "tests/test_base.py::ConfigGetterTestCase::test_getbool_empty", "tests/test_base.py::ConfigGetterTestCase::test_getbool_false", "tests/test_base.py::ConfigGetterTestCase::test_getbool_nonempty_default", "tests/test_base.py::ConfigGetterTestCase::test_getbool_true", "tests/test_base.py::ConfigGetterTestCase::test_getfloat_bad_format", "tests/test_base.py::ConfigGetterTestCase::test_getfloat_bad_value", "tests/test_base.py::ConfigGetterTestCase::test_getfloat_empty_value", "tests/test_base.py::ConfigGetterTestCase::test_getfloat_value", "tests/test_base.py::ConfigGetterTestCase::test_getint_value", "tests/test_base.py::ConfigGetterTestCase::test_getlist_dirty", "tests/test_base.py::ConfigGetterTestCase::test_getlist_empty", "tests/test_base.py::ConfigGetterTestCase::test_getlist_multi", "tests/test_base.py::ConfigGetterTestCase::test_getlist_nonempty_default", "tests/test_base.py::ConfigGetterTestCase::test_getlist_single", "tests/test_base.py::ConfigGetterTestCase::test_named_arguments", "tests/test_base.py::ConfigGetterTestCase::test_no_settings", "tests/test_base.py::ConfigGetterTestCase::test_nonexistent_file", "tests/test_base.py::ConfigGetterTestCase::test_real_file", "tests/test_base.py::ConfigGetterTestCase::test_real_files", "tests/test_base.py::ConfigGetterTestCase::test_sub_section", "tests/test_base.py::ConfigGetterTestCase::test_unicode" ]
[]
BSD 2-Clause "Simplified" License
88
[ "README.rst", "getconf/base.py", "ChangeLog", "docs/reference.rst" ]
[ "README.rst", "getconf/base.py", "ChangeLog", "docs/reference.rst" ]
softlayer__softlayer-python-518
d6612c3546b5525dc61c48ffd9d755288d42b64b
2015-04-10 16:43:56
200787d4c3bf37bc4e701caf6a52e24dd07d18a3
diff --git a/SoftLayer/API.py b/SoftLayer/API.py index 5b75fd96..fc0494c6 100644 --- a/SoftLayer/API.py +++ b/SoftLayer/API.py @@ -12,11 +12,20 @@ from SoftLayer import consts from SoftLayer import transports +# pylint: disable=invalid-name + + API_PUBLIC_ENDPOINT = consts.API_PUBLIC_ENDPOINT API_PRIVATE_ENDPOINT = consts.API_PRIVATE_ENDPOINT -__all__ = ['Client', 'API_PUBLIC_ENDPOINT', 'API_PRIVATE_ENDPOINT'] - -VALID_CALL_ARGS = set([ +__all__ = [ + 'create_client_from_env', + 'Client', + 'BaseClient', + 'API_PUBLIC_ENDPOINT', + 'API_PRIVATE_ENDPOINT', +] + +VALID_CALL_ARGS = set(( 'id', 'mask', 'filter', @@ -25,11 +34,22 @@ 'raw_headers', 'limit', 'offset', -]) +)) -class Client(object): - """A SoftLayer API client. +def create_client_from_env(username=None, + api_key=None, + endpoint_url=None, + timeout=None, + auth=None, + config_file=None, + proxy=None, + user_agent=None, + transport=None): + """Creates a SoftLayer API client using your environment. + + Settings are loaded via keyword arguments, environemtal variables and + config file. :param username: an optional API username if you wish to bypass the package's built-in username @@ -51,38 +71,62 @@ class Client(object): Usage: >>> import SoftLayer - >>> client = SoftLayer.Client(username="username", api_key="api_key") + >>> client = SoftLayer.create_client_from_env() >>> resp = client['Account'].getObject() >>> resp['companyName'] 'Your Company' """ + settings = config.get_client_settings(username=username, + api_key=api_key, + endpoint_url=endpoint_url, + timeout=timeout, + proxy=proxy, + config_file=config_file) + + # Default the transport to use XMLRPC + if transport is None: + transport = transports.XmlRpcTransport( + endpoint_url=settings.get('endpoint_url'), + proxy=settings.get('proxy'), + timeout=settings.get('timeout'), + user_agent=user_agent, + ) + + # If we have enough information to make an auth driver, let's do it + if auth is None and settings.get('username') and settings.get('api_key'): + + auth = slauth.BasicAuthentication( + settings.get('username'), + settings.get('api_key'), + ) + + return BaseClient(auth=auth, transport=transport) + + +def Client(**kwargs): + """Get a SoftLayer API Client using environmental settings. + + Deprecated in favor of create_client_from_env() + """ + warnings.warn("use SoftLayer.create_client_from_env() instead", + DeprecationWarning) + return create_client_from_env(**kwargs) + + +class BaseClient(object): + """Base SoftLayer API client. + + :param auth: auth driver that looks like SoftLayer.auth.AuthenticationBase + :param transport: An object that's callable with this signature: + transport(SoftLayer.transports.Request) + """ + _prefix = "SoftLayer_" - def __init__(self, username=None, api_key=None, endpoint_url=None, - timeout=None, auth=None, config_file=None, proxy=None, - user_agent=None, transport=None): - - settings = config.get_client_settings(username=username, - api_key=api_key, - endpoint_url=endpoint_url, - timeout=timeout, - auth=auth, - proxy=proxy, - config_file=config_file) - self.auth = settings.get('auth') - - self.endpoint_url = (settings.get('endpoint_url') or - API_PUBLIC_ENDPOINT).rstrip('/') - self.transport = transport or transports.XmlRpcTransport() - - self.timeout = None - if settings.get('timeout'): - self.timeout = float(settings.get('timeout')) - self.proxy = None - if settings.get('proxy'): - self.proxy = settings.get('proxy') - self.user_agent = user_agent + def __init__(self, auth=None, transport=None): + self.auth = auth + self.transport = transport def authenticate_with_password(self, username, password, security_question_id=None, @@ -145,13 +189,10 @@ def call(self, service, method, *args, **kwargs): raise TypeError( 'Invalid keyword arguments: %s' % ','.join(invalid_kwargs)) - if not service.startswith(self._prefix): + if self._prefix and not service.startswith(self._prefix): service = self._prefix + service - http_headers = { - 'User-Agent': self.user_agent or consts.USER_AGENT, - 'Content-Type': 'application/xml', - } + http_headers = {} if kwargs.get('compress', True): http_headers['Accept'] = '*/*' @@ -161,13 +202,10 @@ def call(self, service, method, *args, **kwargs): http_headers.update(kwargs.get('raw_headers')) request = transports.Request() - request.endpoint = self.endpoint_url request.service = service request.method = method request.args = args request.transport_headers = http_headers - request.timeout = self.timeout - request.proxy = self.proxy request.identifier = kwargs.get('id') request.mask = kwargs.get('mask') request.filter = kwargs.get('filter') @@ -244,8 +282,7 @@ def iter_call(self, service, method, *args, **kwargs): break def __repr__(self): - return "<Client: endpoint=%s, user=%r>" % (self.endpoint_url, - self.auth) + return "Client(transport=%r, auth=%r)" % (self.transport, self.auth) __str__ = __repr__ diff --git a/SoftLayer/CLI/config/__init__.py b/SoftLayer/CLI/config/__init__.py index f309ad65..3a45cfff 100644 --- a/SoftLayer/CLI/config/__init__.py +++ b/SoftLayer/CLI/config/__init__.py @@ -12,8 +12,8 @@ def get_settings_from_client(client): settings = { 'username': '', 'api_key': '', - 'timeout': client.timeout or None, - 'endpoint_url': client.endpoint_url, + 'timeout': '', + 'endpoint_url': '', } try: settings['username'] = client.auth.username @@ -21,6 +21,12 @@ def get_settings_from_client(client): except AttributeError: pass + try: + settings['timeout'] = client.transport.transport.timeout + settings['endpoint_url'] = client.transport.transport.endpoint_url + except AttributeError: + pass + return settings diff --git a/SoftLayer/auth.py b/SoftLayer/auth.py index 191351e0..66049232 100644 --- a/SoftLayer/auth.py +++ b/SoftLayer/auth.py @@ -7,7 +7,12 @@ """ # pylint: disable=no-self-use -__all__ = ['BasicAuthentication', 'TokenAuthentication', 'AuthenticationBase'] +__all__ = [ + 'BasicAuthentication', + 'TokenAuthentication', + 'BasicHTTPAuthentication', + 'AuthenticationBase', +] class AuthenticationBase(object): @@ -51,7 +56,7 @@ def get_request(self, request): return request def __repr__(self): - return "<TokenAuthentication: %s %s>" % (self.user_id, self.auth_token) + return "TokenAuthentication(%r)" % self.user_id class BasicAuthentication(AuthenticationBase): @@ -73,4 +78,24 @@ def get_request(self, request): return request def __repr__(self): - return "<BasicAuthentication: %s>" % (self.username) + return "BasicAuthentication(username=%r)" % self.username + + +class BasicHTTPAuthentication(AuthenticationBase): + """Token-based authentication class. + + :param username str: a user's username + :param api_key str: a user's API key + """ + def __init__(self, username, api_key): + self.username = username + self.api_key = api_key + + def get_request(self, request): + """Sets token-based auth headers.""" + request.transport_user = self.username + request.transport_password = self.api_key + return request + + def __repr__(self): + return "BasicHTTPAuthentication(username=%r)" % self.username diff --git a/SoftLayer/config.py b/SoftLayer/config.py index 81030517..8c679e6c 100644 --- a/SoftLayer/config.py +++ b/SoftLayer/config.py @@ -8,7 +8,6 @@ import os import os.path -from SoftLayer import auth from SoftLayer import utils @@ -17,17 +16,13 @@ def get_client_settings_args(**kwargs): :param \\*\\*kwargs: Arguments that are passed into the client instance """ - settings = { + return { 'endpoint_url': kwargs.get('endpoint_url'), - 'timeout': kwargs.get('timeout'), - 'auth': kwargs.get('auth'), + 'timeout': float(kwargs.get('timeout') or 0), 'proxy': kwargs.get('proxy'), + 'username': kwargs.get('username'), + 'api_key': kwargs.get('api_key'), } - username = kwargs.get('username') - api_key = kwargs.get('api_key') - if username and api_key and not settings['auth']: - settings['auth'] = auth.BasicAuthentication(username, api_key) - return settings def get_client_settings_env(**_): @@ -35,14 +30,12 @@ def get_client_settings_env(**_): :param \\*\\*kwargs: Arguments that are passed into the client instance """ - username = os.environ.get('SL_USERNAME') - api_key = os.environ.get('SL_API_KEY') - proxy = os.environ.get('https_proxy') - config = {'proxy': proxy} - if username and api_key: - config['auth'] = auth.BasicAuthentication(username, api_key) - return config + return { + 'proxy': os.environ.get('https_proxy'), + 'username': os.environ.get('SL_USERNAME'), + 'api_key': os.environ.get('SL_API_KEY'), + } def get_client_settings_config_file(**kwargs): @@ -58,7 +51,7 @@ def get_client_settings_config_file(**kwargs): 'username': '', 'api_key': '', 'endpoint_url': '', - 'timeout': '', + 'timeout': '0', 'proxy': '', }) config.read(config_files) @@ -66,16 +59,14 @@ def get_client_settings_config_file(**kwargs): if not config.has_section('softlayer'): return - settings = { + return { 'endpoint_url': config.get('softlayer', 'endpoint_url'), - 'timeout': config.get('softlayer', 'timeout'), + 'timeout': config.getfloat('softlayer', 'timeout'), 'proxy': config.get('softlayer', 'proxy'), + 'username': config.get('softlayer', 'username'), + 'api_key': config.get('softlayer', 'api_key'), } - username = config.get('softlayer', 'username') - api_key = config.get('softlayer', 'api_key') - if username and api_key: - settings['auth'] = auth.BasicAuthentication(username, api_key) - return settings + SETTING_RESOLVERS = [get_client_settings_args, get_client_settings_env, @@ -86,8 +77,7 @@ def get_client_settings(**kwargs): """Parse client settings. Parses settings from various input methods, preferring earlier values - to later ones. Once an 'auth' value is found, it returns the gathered - settings. The settings currently come from explicit user arguments, + to later ones. The settings currently come from explicit user arguments, environmental variables and config files. :param \\*\\*kwargs: Arguments that are passed into the client instance @@ -98,6 +88,5 @@ def get_client_settings(**kwargs): if settings: settings.update((k, v) for k, v in all_settings.items() if v) all_settings = settings - if all_settings.get('auth'): - break + return all_settings diff --git a/SoftLayer/managers/metadata.py b/SoftLayer/managers/metadata.py index acad47b7..405f88da 100644 --- a/SoftLayer/managers/metadata.py +++ b/SoftLayer/managers/metadata.py @@ -56,11 +56,13 @@ class MetadataManager(object): attribs = METADATA_MAPPING def __init__(self, client=None, timeout=5): - url = consts.API_PRIVATE_ENDPOINT_REST.rstrip('/') if client is None: - client = SoftLayer.Client(endpoint_url=url, - timeout=timeout, - transport=transports.RestTransport()) + transport = transports.RestTransport( + timeout=timeout, + endpoint_url=consts.API_PRIVATE_ENDPOINT_REST, + ) + client = SoftLayer.BaseClient(transport=transport) + self.client = client def get(self, name, param=None): @@ -83,7 +85,7 @@ def get(self, name, param=None): try: return self.client.call('Resource_Metadata', self.attribs[name]['call'], - id=param) + param) except exceptions.SoftLayerAPIError as ex: if ex.faultCode == 404: return None diff --git a/SoftLayer/transports.py b/SoftLayer/transports.py index d73e59b7..b30d5552 100644 --- a/SoftLayer/transports.py +++ b/SoftLayer/transports.py @@ -5,6 +5,7 @@ :license: MIT, see LICENSE for more details. """ +from SoftLayer import consts from SoftLayer import exceptions from SoftLayer import utils @@ -19,20 +20,19 @@ # transports.Request does have a lot of instance attributes. :( # pylint: disable=too-many-instance-attributes -__all__ = ['Request', - 'XmlRpcTransport', - 'RestTransport', - 'TimingTransport', - 'FixtureTransport'] +__all__ = [ + 'Request', + 'XmlRpcTransport', + 'RestTransport', + 'TimingTransport', + 'FixtureTransport', +] class Request(object): """Transport request object.""" def __init__(self): - #: The SoftLayer endpoint address. - self.endpoint = None - #: API service name. E.G. SoftLayer_Account self.service = None @@ -45,14 +45,14 @@ def __init__(self): #: API headers, used for authentication, masks, limits, offsets, etc. self.headers = {} - #: Transport headers. - self.transport_headers = {} + #: Transport user. + self.transport_user = None - #: Integer timeout. - self.timeout = None + #: Transport password. + self.transport_password = None - #: URL to proxy API requests to. - self.proxy = None + #: Transport headers. + self.transport_headers = {} #: Boolean specifying if the server certificate should be verified. self.verify = True @@ -78,58 +78,69 @@ def __init__(self): class XmlRpcTransport(object): """XML-RPC transport.""" + def __init__(self, + endpoint_url=None, + timeout=None, + proxy=None, + user_agent=None): + + self.endpoint_url = (endpoint_url or + consts.API_PUBLIC_ENDPOINT).rstrip('/') + self.timeout = timeout or None + self.proxy = proxy + self.user_agent = user_agent or consts.USER_AGENT def __call__(self, request): """Makes a SoftLayer API call against the XML-RPC endpoint. :param request request: Request object """ - try: - largs = list(request.args) + largs = list(request.args) - headers = request.headers + headers = request.headers - if request.identifier is not None: - header_name = request.service + 'InitParameters' - headers[header_name] = {'id': request.identifier} + if request.identifier is not None: + header_name = request.service + 'InitParameters' + headers[header_name] = {'id': request.identifier} - if request.mask is not None: - headers.update(_format_object_mask(request.mask, - request.service)) + if request.mask is not None: + headers.update(_format_object_mask(request.mask, request.service)) - if request.filter is not None: - headers['%sObjectFilter' % request.service] = request.filter + if request.filter is not None: + headers['%sObjectFilter' % request.service] = request.filter - if request.limit: - headers['resultLimit'] = { - 'limit': request.limit, - 'offset': request.offset or 0, - } + if request.limit: + headers['resultLimit'] = { + 'limit': request.limit, + 'offset': request.offset or 0, + } - largs.insert(0, {'headers': headers}) + largs.insert(0, {'headers': headers}) + request.transport_headers.setdefault('Content-Type', 'application/xml') + request.transport_headers.setdefault('User-Agent', self.user_agent) - url = '/'.join([request.endpoint, request.service]) - payload = utils.xmlrpc_client.dumps(tuple(largs), - methodname=request.method, - allow_none=True) - LOGGER.debug("=== REQUEST ===") - LOGGER.info('POST %s', url) - LOGGER.debug(request.transport_headers) - LOGGER.debug(payload) + url = '/'.join([self.endpoint_url, request.service]) + payload = utils.xmlrpc_client.dumps(tuple(largs), + methodname=request.method, + allow_none=True) + LOGGER.debug("=== REQUEST ===") + LOGGER.info('POST %s', url) + LOGGER.debug(request.transport_headers) + LOGGER.debug(payload) + try: response = requests.request('POST', url, data=payload, headers=request.transport_headers, - timeout=request.timeout, + timeout=self.timeout, verify=request.verify, cert=request.cert, - proxies=_proxies_dict(request.proxy)) + proxies=_proxies_dict(self.proxy)) LOGGER.debug("=== RESPONSE ===") LOGGER.debug(response.headers) LOGGER.debug(response.content) response.raise_for_status() - result = utils.xmlrpc_client.loads(response.content,)[0][0] - return result + return utils.xmlrpc_client.loads(response.content)[0][0] except utils.xmlrpc_client.Fault as ex: # These exceptions are formed from the XML-RPC spec # http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php @@ -154,7 +165,23 @@ def __call__(self, request): class RestTransport(object): - """REST transport.""" + """REST transport. + + Currently only supports GET requests (no POST, PUT, DELETE) and lacks + support for masks, filters, limits and offsets. + """ + + def __init__(self, + endpoint_url=None, + timeout=None, + proxy=None, + user_agent=None): + + self.endpoint_url = (endpoint_url or + consts.API_PUBLIC_ENDPOINT_REST).rstrip('/') + self.timeout = timeout or None + self.proxy = proxy + self.user_agent = user_agent or consts.USER_AGENT def __call__(self, request): """Makes a SoftLayer API call against the REST endpoint. @@ -163,9 +190,17 @@ def __call__(self, request): :param request request: Request object """ - url_parts = [request.endpoint, request.service, request.method] + url_parts = [self.endpoint_url, request.service] if request.identifier is not None: url_parts.append(str(request.identifier)) + if request.method is not None: + url_parts.append(request.method) + for arg in request.args: + url_parts.append(str(arg)) + + request.transport_headers.setdefault('Content-Type', + 'application/json') + request.transport_headers.setdefault('User-Agent', self.user_agent) url = '%s.%s' % ('/'.join(url_parts), 'json') @@ -175,10 +210,10 @@ def __call__(self, request): try: resp = requests.request('GET', url, headers=request.transport_headers, - timeout=request.timeout, + timeout=self.timeout, verify=request.verify, cert=request.cert, - proxies=_proxies_dict(request.proxy)) + proxies=_proxies_dict(self.proxy)) LOGGER.debug("=== RESPONSE ===") LOGGER.debug(resp.headers) LOGGER.debug(resp.content)
Solidify Client Construction I want to make the following changes: * Rename SoftLayer.API.Client to SoftLayer.API.BaseClient * Remove all other arguments from SoftLayer.API.BaseClient except for: * transport * auth * Transports will now be constructed with endpoint_url, timeout, proxy and user_agent * a new create_client_from_env() function will take all current arguments as SoftLayer.API.Client's __init__ arguments and behave the same. It will also have an alias to SoftLayer.API.Client in order to maintain backwards compatibility. Using SoftLayer.API.Client will be deprecated. This accomplishes the following goals: * Generally, removes magic from initialization of an API client * Allows for the construction of an API client without possibly loading environmental and file-based configuration options. The fact that this isn't possible has lead to initializing of a client only to set the auth handler to None since it was automatically set by reading config file. * Makes transport-specific defaults for timeouts, endpoints, etc happen in an intuitive place.
softlayer/softlayer-python
diff --git a/SoftLayer/tests/CLI/modules/config_tests.py b/SoftLayer/tests/CLI/modules/config_tests.py index 8299d7b9..73baf54a 100644 --- a/SoftLayer/tests/CLI/modules/config_tests.py +++ b/SoftLayer/tests/CLI/modules/config_tests.py @@ -24,8 +24,8 @@ def test_show(self): self.assertEqual(json.loads(result.output), {'Username': 'default-user', 'API Key': 'default-key', - 'Endpoint URL': 'default-endpoint-url', - 'Timeout': 10.0}) + 'Endpoint URL': 'not set', + 'Timeout': 'not set'}) class TestHelpSetup(testing.TestCase): @@ -80,7 +80,6 @@ def test_get_user_input_private(self, input, getpass): self.assertEqual(username, 'user') self.assertEqual(secret, 'A' * 64) self.assertEqual(endpoint_url, consts.API_PRIVATE_ENDPOINT) - self.assertEqual(timeout, 10) @mock.patch('SoftLayer.CLI.environment.Environment.getpass') @mock.patch('SoftLayer.CLI.environment.Environment.input') diff --git a/SoftLayer/tests/api_tests.py b/SoftLayer/tests/api_tests.py index 6df36510..daae5aed 100644 --- a/SoftLayer/tests/api_tests.py +++ b/SoftLayer/tests/api_tests.py @@ -8,7 +8,6 @@ import SoftLayer import SoftLayer.API -from SoftLayer import consts from SoftLayer import testing TEST_AUTH_HEADERS = { @@ -24,22 +23,21 @@ def test_init(self): self.assertIsInstance(client.auth, SoftLayer.BasicAuthentication) self.assertEqual(client.auth.username, 'doesnotexist') self.assertEqual(client.auth.api_key, 'issurelywrong') - self.assertEqual(client.endpoint_url, + self.assertEqual(client.transport.endpoint_url, SoftLayer.API_PUBLIC_ENDPOINT.rstrip('/')) - self.assertEqual(client.timeout, 10) + self.assertEqual(client.transport.timeout, 10) @mock.patch('SoftLayer.config.get_client_settings') def test_env(self, get_client_settings): auth = mock.Mock() get_client_settings.return_value = { - 'auth': auth, 'timeout': 10, 'endpoint_url': 'http://endpoint_url/', } - client = SoftLayer.Client() + client = SoftLayer.Client(auth=auth) self.assertEqual(client.auth.get_headers(), auth.get_headers()) - self.assertEqual(client.timeout, 10) - self.assertEqual(client.endpoint_url, 'http://endpoint_url') + self.assertEqual(client.transport.timeout, 10) + self.assertEqual(client.transport.endpoint_url, 'http://endpoint_url') class ClientMethods(testing.TestCase): @@ -76,7 +74,6 @@ def test_simple_call(self): self.assertEqual(resp, {"test": "result"}) self.assert_called_with('SoftLayer_SERVICE', 'METHOD', - endpoint=self.client.endpoint_url, mask=None, filter=None, identifier=None, @@ -101,7 +98,6 @@ def test_complex(self): self.assertEqual(resp, {"test": "result"}) self.assert_called_with('SoftLayer_SERVICE', 'METHOD', - endpoint=self.client.endpoint_url, mask={'object': {'attribute': ''}}, filter=_filter, identifier=5678, @@ -111,22 +107,22 @@ def test_complex(self): headers=TEST_AUTH_HEADERS, ) - @mock.patch('SoftLayer.API.Client.iter_call') + @mock.patch('SoftLayer.API.BaseClient.iter_call') def test_iterate(self, _iter_call): self.client['SERVICE'].METHOD(iter=True) _iter_call.assert_called_with('SERVICE', 'METHOD') - @mock.patch('SoftLayer.API.Client.iter_call') + @mock.patch('SoftLayer.API.BaseClient.iter_call') def test_service_iter_call(self, _iter_call): self.client['SERVICE'].iter_call('METHOD', 'ARG') _iter_call.assert_called_with('SERVICE', 'METHOD', 'ARG') - @mock.patch('SoftLayer.API.Client.iter_call') + @mock.patch('SoftLayer.API.BaseClient.iter_call') def test_service_iter_call_with_chunk(self, _iter_call): self.client['SERVICE'].iter_call('METHOD', 'ARG', chunk=2) _iter_call.assert_called_with('SERVICE', 'METHOD', 'ARG', chunk=2) - @mock.patch('SoftLayer.API.Client.call') + @mock.patch('SoftLayer.API.BaseClient.call') def test_iter_call(self, _call): # chunk=100, no limit _call.side_effect = [list(range(100)), list(range(100, 125))] @@ -207,10 +203,8 @@ def test_call_compression_enabled(self): self.client['SERVICE'].METHOD(compress=True) expected_headers = { - 'Content-Type': 'application/xml', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept': '*/*', - 'User-Agent': consts.USER_AGENT, } self.assert_called_with('SoftLayer_SERVICE', 'METHOD', transport_headers=expected_headers) @@ -223,9 +217,7 @@ def test_call_compression_override(self): raw_headers={'Accept-Encoding': 'gzip'}) expected_headers = { - 'Content-Type': 'application/xml', 'Accept-Encoding': 'gzip', - 'User-Agent': consts.USER_AGENT, } self.assert_called_with('SoftLayer_SERVICE', 'METHOD', transport_headers=expected_headers) @@ -245,9 +237,9 @@ def test_init(self, get_client_settings): def test_init_with_proxy(self, get_client_settings): get_client_settings.return_value = {'proxy': 'http://localhost:3128'} client = SoftLayer.Client() - self.assertEqual(client.proxy, 'http://localhost:3128') + self.assertEqual(client.transport.proxy, 'http://localhost:3128') - @mock.patch('SoftLayer.API.Client.call') + @mock.patch('SoftLayer.API.BaseClient.call') def test_authenticate_with_password(self, _call): _call.return_value = { 'userId': 12345, diff --git a/SoftLayer/tests/auth_tests.py b/SoftLayer/tests/auth_tests.py index 240af3a9..6bac999f 100644 --- a/SoftLayer/tests/auth_tests.py +++ b/SoftLayer/tests/auth_tests.py @@ -63,4 +63,23 @@ def test_repr(self): s = repr(self.auth) self.assertIn('TokenAuthentication', s) self.assertIn('12345', s) - self.assertIn('TOKEN', s) + + +class TestBasicHTTPAuthentication(testing.TestCase): + def set_up(self): + self.auth = auth.BasicHTTPAuthentication('USERNAME', 'APIKEY') + + def test_attribs(self): + self.assertEqual(self.auth.username, 'USERNAME') + self.assertEqual(self.auth.api_key, 'APIKEY') + + def test_get_request(self): + req = transports.Request() + authed_req = self.auth.get_request(req) + self.assertEqual(authed_req.transport_user, 'USERNAME') + self.assertEqual(authed_req.transport_password, 'APIKEY') + + def test_repr(self): + s = repr(self.auth) + self.assertIn('BasicHTTPAuthentication', s) + self.assertIn('USERNAME', s) diff --git a/SoftLayer/tests/config_tests.py b/SoftLayer/tests/config_tests.py index 3db988c0..3ef805e9 100644 --- a/SoftLayer/tests/config_tests.py +++ b/SoftLayer/tests/config_tests.py @@ -50,28 +50,10 @@ def test_username_api_key(self): self.assertEqual(result['endpoint_url'], 'http://endpoint/') self.assertEqual(result['timeout'], 10) - self.assertEqual(result['auth'].username, 'username') - self.assertEqual(result['auth'].api_key, 'api_key') + self.assertEqual(result['username'], 'username') + self.assertEqual(result['api_key'], 'api_key') self.assertEqual(result['proxy'], 'https://localhost:3128') - def test_no_auth(self): - result = config.get_client_settings_args() - - self.assertEqual(result, { - 'endpoint_url': None, - 'timeout': None, - 'proxy': None, - 'auth': None, - }) - - def test_with_auth(self): - auth = mock.Mock() - result = config.get_client_settings_args(auth=auth) - - self.assertEqual(result['endpoint_url'], None) - self.assertEqual(result['timeout'], None) - self.assertEqual(result['auth'], auth) - class TestGetClientSettingsEnv(testing.TestCase): @@ -81,15 +63,8 @@ class TestGetClientSettingsEnv(testing.TestCase): def test_username_api_key(self): result = config.get_client_settings_env() - self.assertEqual(result['auth'].username, 'username') - self.assertEqual(result['auth'].api_key, 'api_key') - - @mock.patch.dict('os.environ', {'SL_USERNAME': '', 'SL_API_KEY': ''}) - def test_no_auth(self): - result = config.get_client_settings_env() - - # proxy might get ANY value depending on test env. - self.assertEqual(result, {'proxy': mock.ANY}) + self.assertEqual(result['username'], 'username') + self.assertEqual(result['api_key'], 'api_key') class TestGetClientSettingsConfigFile(testing.TestCase): @@ -99,10 +74,10 @@ def test_username_api_key(self, config_parser): result = config.get_client_settings_config_file() self.assertEqual(result['endpoint_url'], config_parser().get()) - self.assertEqual(result['timeout'], config_parser().get()) + self.assertEqual(result['timeout'], config_parser().getfloat()) self.assertEqual(result['proxy'], config_parser().get()) - self.assertEqual(result['auth'].username, config_parser().get()) - self.assertEqual(result['auth'].api_key, config_parser().get()) + self.assertEqual(result['username'], config_parser().get()) + self.assertEqual(result['api_key'], config_parser().get()) @mock.patch('six.moves.configparser.RawConfigParser') def test_no_section(self, config_parser): diff --git a/SoftLayer/tests/functional_tests.py b/SoftLayer/tests/functional_tests.py index 52383431..53abe6eb 100644 --- a/SoftLayer/tests/functional_tests.py +++ b/SoftLayer/tests/functional_tests.py @@ -38,13 +38,14 @@ def test_failed_auth(self): def test_no_hostname(self): try: request = transports.Request() - request.endpoint = 'http://notvalidsoftlayer.com' request.service = 'SoftLayer_Account' request.method = 'getObject' request.id = 1234 # This test will fail if 'notvalidsoftlayer.com' becomes a thing - transport = transports.XmlRpcTransport() + transport = transports.XmlRpcTransport( + endpoint_url='http://notvalidsoftlayer.com', + ) transport(request) except SoftLayer.SoftLayerAPIError as ex: self.assertIn('not known', str(ex)) diff --git a/SoftLayer/tests/managers/metadata_tests.py b/SoftLayer/tests/managers/metadata_tests.py index 8a5c28cb..9d471265 100644 --- a/SoftLayer/tests/managers/metadata_tests.py +++ b/SoftLayer/tests/managers/metadata_tests.py @@ -21,7 +21,6 @@ def test_get(self): self.assertEqual('dal01', resp) self.assert_called_with('SoftLayer_Resource_Metadata', 'Datacenter', - timeout=10.0, identifier=None) def test_no_param(self): @@ -36,7 +35,7 @@ def test_w_param(self): self.assertEqual([10, 124], resp) self.assert_called_with('SoftLayer_Resource_Metadata', 'Vlans', - identifier='1:2:3:4:5') + args=('1:2:3:4:5',)) def test_user_data(self): resp = self.metadata.get('user_data') diff --git a/SoftLayer/tests/transport_tests.py b/SoftLayer/tests/transport_tests.py index 29b9a7e7..c4977ff0 100644 --- a/SoftLayer/tests/transport_tests.py +++ b/SoftLayer/tests/transport_tests.py @@ -10,6 +10,7 @@ import requests import SoftLayer +from SoftLayer import consts from SoftLayer import testing from SoftLayer import transports @@ -17,7 +18,9 @@ class TestXmlRpcAPICall(testing.TestCase): def set_up(self): - self.transport = transports.XmlRpcTransport() + self.transport = transports.XmlRpcTransport( + endpoint_url='http://something.com', + ) self.response = mock.MagicMock() self.response.content = '''<?xml version="1.0" encoding="utf-8"?> <params> @@ -52,14 +55,14 @@ def test_call(self, request): ''' req = transports.Request() - req.endpoint = 'http://something.com' req.service = 'SoftLayer_Service' req.method = 'getObject' resp = self.transport(req) request.assert_called_with('POST', 'http://something.com/SoftLayer_Service', - headers={}, + headers={'Content-Type': 'application/xml', + 'User-Agent': consts.USER_AGENT}, proxies=None, data=data, timeout=None, @@ -69,7 +72,6 @@ def test_call(self, request): def test_proxy_without_protocol(self): req = transports.Request() - req.endpoint = 'http://something.com' req.service = 'SoftLayer_Service' req.method = 'Resource' req.proxy = 'localhost:3128' @@ -83,21 +85,20 @@ def test_proxy_without_protocol(self): @mock.patch('requests.request') def test_valid_proxy(self, request): request.return_value = self.response + self.transport.proxy = 'http://localhost:3128' req = transports.Request() - req.endpoint = 'http://something.com' req.service = 'SoftLayer_Service' req.method = 'Resource' - req.proxy = 'http://localhost:3128' self.transport(req) request.assert_called_with( 'POST', mock.ANY, - headers={}, proxies={'https': 'http://localhost:3128', 'http': 'http://localhost:3128'}, data=mock.ANY, + headers=mock.ANY, timeout=None, cert=None, verify=True) @@ -237,7 +238,6 @@ def test_request_exception(self, request): request().raise_for_status.side_effect = e req = transports.Request() - req.endpoint = 'http://something.com' req.service = 'SoftLayer_Service' req.method = 'getObject' @@ -247,13 +247,14 @@ def test_request_exception(self, request): class TestRestAPICall(testing.TestCase): def set_up(self): - self.transport = transports.RestTransport() + self.transport = transports.RestTransport( + endpoint_url='http://something.com', + ) @mock.patch('requests.request') def test_basic(self, request): request().content = '{}' req = transports.Request() - req.endpoint = 'http://something.com' req.service = 'SoftLayer_Service' req.method = 'Resource' @@ -261,7 +262,7 @@ def test_basic(self, request): self.assertEqual(resp, {}) request.assert_called_with( 'GET', 'http://something.com/SoftLayer_Service/Resource.json', - headers={}, + headers=mock.ANY, verify=True, cert=None, proxies=None, @@ -281,7 +282,6 @@ def test_basic(self, request): def test_proxy_without_protocol(self): req = transports.Request() - req.endpoint = 'http://something.com' req.service = 'SoftLayer_Service' req.method = 'Resource' req.proxy = 'localhost:3128' @@ -295,12 +295,11 @@ def test_proxy_without_protocol(self): @mock.patch('requests.request') def test_valid_proxy(self, request): request().content = '{}' + self.transport.proxy = 'http://localhost:3128' req = transports.Request() - req.endpoint = 'http://something.com' req.service = 'SoftLayer_Service' req.method = 'Resource' - req.proxy = 'http://localhost:3128' self.transport(req) request.assert_called_with( @@ -317,7 +316,6 @@ def test_with_id(self, request): request().content = '{}' req = transports.Request() - req.endpoint = 'http://something.com' req.service = 'SoftLayer_Service' req.method = 'getObject' req.identifier = 2 @@ -327,8 +325,29 @@ def test_with_id(self, request): self.assertEqual(resp, {}) request.assert_called_with( 'GET', - 'http://something.com/SoftLayer_Service/getObject/2.json', - headers={}, + 'http://something.com/SoftLayer_Service/2/getObject.json', + headers=mock.ANY, + verify=True, + cert=None, + proxies=None, + timeout=None) + + @mock.patch('requests.request') + def test_with_args(self, request): + request().content = '{}' + + req = transports.Request() + req.service = 'SoftLayer_Service' + req.method = 'getObject' + req.args = ('test', 1) + + resp = self.transport(req) + + self.assertEqual(resp, {}) + request.assert_called_with( + 'GET', + 'http://something.com/SoftLayer_Service/getObject/test/1.json', + headers=mock.ANY, verify=True, cert=None, proxies=None, @@ -343,7 +362,6 @@ def test_unknown_error(self, request): request().raise_for_status.side_effect = e req = transports.Request() - req.endpoint = 'http://something.com' req.service = 'SoftLayer_Service' req.method = 'getObject'
{ "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": 2, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 6 }
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@d6612c3546b5525dc61c48ffd9d755288d42b64b#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/config_tests.py::TestHelpShow::test_show", "SoftLayer/tests/api_tests.py::Inititialization::test_env", "SoftLayer/tests/api_tests.py::Inititialization::test_init", "SoftLayer/tests/api_tests.py::APIClient::test_call_compression_enabled", "SoftLayer/tests/api_tests.py::APIClient::test_call_compression_override", "SoftLayer/tests/api_tests.py::APIClient::test_iter_call", "SoftLayer/tests/api_tests.py::APIClient::test_iterate", "SoftLayer/tests/api_tests.py::APIClient::test_service_iter_call", "SoftLayer/tests/api_tests.py::APIClient::test_service_iter_call_with_chunk", "SoftLayer/tests/api_tests.py::UnauthenticatedAPIClient::test_authenticate_with_password", "SoftLayer/tests/api_tests.py::UnauthenticatedAPIClient::test_init_with_proxy", "SoftLayer/tests/auth_tests.py::TestBasicHTTPAuthentication::test_attribs", "SoftLayer/tests/auth_tests.py::TestBasicHTTPAuthentication::test_get_request", "SoftLayer/tests/auth_tests.py::TestBasicHTTPAuthentication::test_repr", "SoftLayer/tests/config_tests.py::TestGetClientSettingsArgs::test_username_api_key", "SoftLayer/tests/config_tests.py::TestGetClientSettingsEnv::test_username_api_key", "SoftLayer/tests/config_tests.py::TestGetClientSettingsConfigFile::test_username_api_key", "SoftLayer/tests/functional_tests.py::UnauthedUser::test_no_hostname", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_w_param", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_call", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_filter", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_identifier", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_limit_offset", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_mask_call_no_mask_prefix", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_mask_call_v2", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_mask_call_v2_dot", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_old_mask", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_proxy_without_protocol", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_request_exception", "SoftLayer/tests/transport_tests.py::TestXmlRpcAPICall::test_valid_proxy", "SoftLayer/tests/transport_tests.py::TestRestAPICall::test_basic", "SoftLayer/tests/transport_tests.py::TestRestAPICall::test_unknown_error", "SoftLayer/tests/transport_tests.py::TestRestAPICall::test_valid_proxy", "SoftLayer/tests/transport_tests.py::TestRestAPICall::test_with_args", "SoftLayer/tests/transport_tests.py::TestRestAPICall::test_with_id" ]
[ "SoftLayer/tests/transport_tests.py::TestRestAPICall::test_proxy_without_protocol" ]
[ "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", "SoftLayer/tests/api_tests.py::ClientMethods::test_len", "SoftLayer/tests/api_tests.py::ClientMethods::test_repr", "SoftLayer/tests/api_tests.py::ClientMethods::test_service_repr", "SoftLayer/tests/api_tests.py::APIClient::test_call_compression_disabled", "SoftLayer/tests/api_tests.py::APIClient::test_call_invalid_arguments", "SoftLayer/tests/api_tests.py::APIClient::test_complex", "SoftLayer/tests/api_tests.py::APIClient::test_simple_call", "SoftLayer/tests/api_tests.py::UnauthenticatedAPIClient::test_init", "SoftLayer/tests/auth_tests.py::TestAuthenticationBase::test_get_request", "SoftLayer/tests/auth_tests.py::TestBasicAuthentication::test_attribs", "SoftLayer/tests/auth_tests.py::TestBasicAuthentication::test_get_request", "SoftLayer/tests/auth_tests.py::TestBasicAuthentication::test_repr", "SoftLayer/tests/auth_tests.py::TestTokenAuthentication::test_attribs", "SoftLayer/tests/auth_tests.py::TestTokenAuthentication::test_get_request", "SoftLayer/tests/auth_tests.py::TestTokenAuthentication::test_repr", "SoftLayer/tests/config_tests.py::TestGetClientSettings::test_inherit", "SoftLayer/tests/config_tests.py::TestGetClientSettings::test_no_resolvers", "SoftLayer/tests/config_tests.py::TestGetClientSettings::test_resolve_one", "SoftLayer/tests/config_tests.py::TestGetClientSettingsConfigFile::test_config_file", "SoftLayer/tests/config_tests.py::TestGetClientSettingsConfigFile::test_no_section", "SoftLayer/tests/functional_tests.py::UnauthedUser::test_failed_auth", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_404", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_error", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_get", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_networks", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_no_param", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_not_exists", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_return_none", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_user_data", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_w_param_error" ]
[]
MIT License
89
[ "SoftLayer/auth.py", "SoftLayer/transports.py", "SoftLayer/CLI/config/__init__.py", "SoftLayer/managers/metadata.py", "SoftLayer/API.py", "SoftLayer/config.py" ]
[ "SoftLayer/auth.py", "SoftLayer/transports.py", "SoftLayer/CLI/config/__init__.py", "SoftLayer/managers/metadata.py", "SoftLayer/API.py", "SoftLayer/config.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
[ "webob/request.py" ]
[ "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
[ "SoftLayer/CLI/call_api.py" ]
[ "SoftLayer/CLI/call_api.py" ]
chimpler__pyhocon-13
4e8c1621c49dac503a790cd46f843135342ae618
2015-04-14 03:15:18
4e8c1621c49dac503a790cd46f843135342ae618
diff --git a/pyhocon/__init__.py b/pyhocon/__init__.py index 2a467e8..5b3b7a5 100644 --- a/pyhocon/__init__.py +++ b/pyhocon/__init__.py @@ -145,7 +145,7 @@ class ConfigParser(object): eol = Word('\n\r').suppress() eol_comma = Word('\n\r,').suppress() - comment = (Optional(eol_comma) + (Literal('#') | Literal('//')) - SkipTo(eol)).suppress() + comment = Suppress(Optional(eol_comma) + (Literal('#') | Literal('//')) - SkipTo(eol)) number_expr = Regex('[+-]?(\d*\.\d+|\d+(\.\d+)?)([eE]\d+)?(?=[ \t]*([\$\}\],#\n\r]|//))', re.DOTALL).setParseAction(convert_number) # multi line string using """ @@ -162,9 +162,7 @@ class ConfigParser(object): substitution_expr = Regex('\$\{[^\}]+\}\s*').setParseAction(create_substitution) string_expr = multiline_string | quoted_string | unquoted_string - value_expr = number_expr | true_expr | false_expr | null_expr | string_expr | substitution_expr - values_expr = ConcatenatedValueParser(value_expr - ZeroOrMore(comment | (value_expr - Optional(Literal('\\') - eol).suppress()) | value_expr)) - # multiline if \ at the end of the line + value_expr = number_expr | true_expr | false_expr | null_expr | string_expr include_expr = (Keyword("include", caseless=True).suppress() - ( quoted_string | ((Keyword('url') | Keyword('file')) - Literal('(').suppress() - quoted_string - Literal(')').suppress())))\ @@ -174,11 +172,13 @@ class ConfigParser(object): # last zeroOrMore is because we can have t = {a:4} {b: 6} {c: 7} which is dictionary concatenation inside_dict_expr = ConfigTreeParser(ZeroOrMore(comment | include_expr | assign_expr | eol_comma)) dict_expr = Suppress('{') - inside_dict_expr - Suppress('}') - list_expr = Suppress('[') - ListParser(ZeroOrMore(comment | dict_expr | values_expr | eol_comma)) - Suppress(']') + list_expr = Suppress('[') - ListParser(ZeroOrMore(comment | dict_expr | value_expr | eol_comma)) - Suppress(']') # special case when we have a value assignment where the string can potentially be the remainder of the line - assign_expr << Group(key - Suppress(Optional(Literal('=') | Literal(':'))) + - (ConcatenatedValueParser(OneOrMore(substitution_expr | list_expr | dict_expr)) | comment | values_expr | eol_comma)) + assign_expr << Group(key - Suppress(Optional(Literal('=') | Literal(':'))) - + (ConcatenatedValueParser( + ZeroOrMore(substitution_expr | list_expr | dict_expr | comment | value_expr | (Literal('\\') - eol).suppress()) + ))) # the file can be { ... } where {} can be omitted or [] config_expr = ZeroOrMore(comment | eol) \ @@ -219,8 +219,11 @@ class ConfigParser(object): else: # replace token by substitution config_values = substitution.parent - # if there is more than one element in the config values then it's a string - config_values.put(substitution.index, resolved_value) + # if it is a string, then add the extra ws that was present in the original string after the substitution + formatted_resolved_value = \ + resolved_value + substitution.ws if isinstance(resolved_value, str) \ + and substitution.index < len(config_values.tokens) - 1 else resolved_value + config_values.put(substitution.index, formatted_resolved_value) transformation = config_values.transform() result = transformation[0] if isinstance(transformation, list) else transformation config_values.parent[config_values.key] = result diff --git a/pyhocon/config_tree.py b/pyhocon/config_tree.py index 42a52ec..f4f5e67 100644 --- a/pyhocon/config_tree.py +++ b/pyhocon/config_tree.py @@ -203,12 +203,18 @@ class ConfigValues(object): self.tokens = iterable self.parent = None self.key = None + for index, token in enumerate(self.tokens): if isinstance(token, ConfigSubstitution): token.parent = self token.index = index # if the last token is an unquoted string then right strip it + + # no value return empty string + if len(self.tokens) == 0: + self.tokens = [''] + if isinstance(self.tokens[-1], ConfigUnquotedString): self.tokens[-1] = self.tokens[-1].rstrip()
String substitution broken? Could it be that the fix for object merging (issue #10) broken string substitution? Expanding on the simple unit test from pyhocon codebase: ``` In [54]: config = ConfigFactory.parse_string( ....: """ ....: { ....: a: { ....: b: { ....: c = buzz ....: } ....: } ....: d = test ${a.b.c} me ....: e = ${a.b.c} me ....: } ....: """ ....: ) In [55]: config['d'] Out[55]: 'test buzzme' In [56]: config['e'] Out[56]: 'buzz' ``` Whereas I expected to get `test buzz me` (with the space between subst expr and the last string) and `buzz me` (here the appended string got lost entirely) Let me know if I'm misunderstanding how string subst is supposed to work.
chimpler/pyhocon
diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py index be865ba..492816d 100644 --- a/tests/test_config_parser.py +++ b/tests/test_config_parser.py @@ -1,6 +1,6 @@ import pytest -from pyhocon import ConfigFactory -from pyhocon.exceptions import ConfigMissingException +from pyhocon import ConfigFactory, ConfigSubstitutionException +from pyhocon.exceptions import ConfigMissingException, ConfigWrongTypeException class TestConfigParser(object): @@ -213,8 +213,98 @@ class TestConfigParser(object): assert config.get('a') == [1, 2, 3, 4, 5, 6] assert config.get_list('a') == [1, 2, 3, 4, 5, 6] - def test_substitutions(self): - config = ConfigFactory.parse_string( + def test_string_substitutions(self): + config1 = ConfigFactory.parse_string( + """ + { + a: { + b: { + c = str + e = "str " + } + } + d = ${a.b.c} + f = ${a.b.e} + } + """ + ) + + assert config1.get('a.b.c') == 'str' + assert config1.get('d') == 'str' + assert config1.get('f') == 'str ' + + config2 = ConfigFactory.parse_string( + """ + { + a: { + b: { + c = str + e = "str " + } + } + d = test ${a.b.c} + f = test ${a.b.e} + } + """ + ) + + assert config2.get('a.b.c') == 'str' + assert config2.get('d') == 'test str' + assert config2.get('f') == 'test str ' + + config3 = ConfigFactory.parse_string( + """ + { + a: { + b: { + c = str + e = "str " + } + } + d = test ${a.b.c} me + f = test ${a.b.e} me + } + """ + ) + + assert config3.get('a.b.c') == 'str' + assert config3.get('d') == 'test str me' + assert config3.get('f') == 'test str me' + + def test_int_substitutions(self): + config1 = ConfigFactory.parse_string( + """ + { + a: { + b: { + c = 5 + } + } + d = ${a.b.c} + } + """ + ) + + assert config1.get('a.b.c') == 5 + assert config1.get('d') == 5 + + config2 = ConfigFactory.parse_string( + """ + { + a: { + b: { + c = 5 + } + } + d = test ${a.b.c} + } + """ + ) + + assert config2.get('a.b.c') == 5 + assert config2.get('d') == 'test 5' + + config3 = ConfigFactory.parse_string( """ { a: { @@ -227,10 +317,10 @@ class TestConfigParser(object): """ ) - assert config.get('a.b.c') == 5 - assert config.get('d') == 'test 5 me' + assert config3.get('a.b.c') == 5 + assert config3.get('d') == 'test 5 me' - def test_cascade_substitutions(self): + def test_cascade_string_substitutions(self): config = ConfigFactory.parse_string( """ { @@ -334,6 +424,117 @@ class TestConfigParser(object): assert config4.get('host_modules') == ['java', 'php', 'python', 'perl'] assert config4.get('full_modules') == ['java', 'php', 'python', 'perl', 'c', 'go'] + def test_non_existent_substitution(self): + with pytest.raises(ConfigSubstitutionException): + ConfigFactory.parse_string( + """ + common_modules = ${non_existent} + """ + ) + + with pytest.raises(ConfigSubstitutionException): + ConfigFactory.parse_string( + """ + common_modules = abc ${non_existent} + """ + ) + + with pytest.raises(ConfigSubstitutionException): + ConfigFactory.parse_string( + """ + common_modules = ${non_existent} abc + """ + ) + + with pytest.raises(ConfigSubstitutionException): + ConfigFactory.parse_string( + """ + common_modules = abc ${non_existent} def + """ + ) + + def test_non_compatible_substitution(self): + with pytest.raises(ConfigWrongTypeException): + ConfigFactory.parse_string( + """ + common_modules = [perl] + host_modules = 55 ${common_modules} + """ + ) + + with pytest.raises(ConfigWrongTypeException): + ConfigFactory.parse_string( + """ + common_modules = [perl] + host_modules = ${common_modules} 55 + """ + ) + + with pytest.raises(ConfigWrongTypeException): + ConfigFactory.parse_string( + """ + common_modules = [perl] + host_modules = aa ${common_modules} bb + """ + ) + + with pytest.raises(ConfigWrongTypeException): + ConfigFactory.parse_string( + """ + common_modules = [perl] + host_modules = aa ${common_modules} + """ + ) + + with pytest.raises(ConfigWrongTypeException): + ConfigFactory.parse_string( + """ + common_modules = [perl] + host_modules = ${common_modules} aa + """ + ) + + with pytest.raises(ConfigWrongTypeException): + ConfigFactory.parse_string( + """ + common_modules = [perl] + host_modules = aa ${common_modules} bb + """ + ) + + def test_concat_multi_line_string(self): + config = ConfigFactory.parse_string( + """ + common_modules = perl \ + java \ + python + """ + ) + + assert [x.strip() for x in config['common_modules'].split() if x.strip(' ') != ''] == ['perl', 'java', 'python'] + + def test_concat_multi_line_list(self): + config = ConfigFactory.parse_string( + """ + common_modules = [perl] \ + [java] \ + [python] + """ + ) + + assert config['common_modules'] == ['perl', 'java', 'python'] + + def test_concat_multi_line_dict(self): + config = ConfigFactory.parse_string( + """ + common_modules = {a:perl} \ + {b:java} \ + {c:python} + """ + ) + + assert config['common_modules'] == {'a': 'perl', 'b': 'java', 'c': 'python'} + def test_include_dict(self): config = ConfigFactory.parse_file("samples/animals.conf") assert config.get('cat.garfield.say') == 'meow'
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 2 }
0.2
{ "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": [ "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 -e git+https://github.com/chimpler/pyhocon.git@4e8c1621c49dac503a790cd46f843135342ae618#egg=pyhocon pyparsing==2.0.3 pytest==8.3.5 tomli==2.2.1
name: pyhocon 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 - pyparsing==2.0.3 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/pyhocon
[ "tests/test_config_parser.py::TestConfigParser::test_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_non_compatible_substitution" ]
[]
[ "tests/test_config_parser.py::TestConfigParser::test_parse_simple_value", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_brace", "tests/test_config_parser.py::TestConfigParser::test_parse_with_enclosing_square_bracket", "tests/test_config_parser.py::TestConfigParser::test_quoted_key_with_dots", "tests/test_config_parser.py::TestConfigParser::test_comma_to_separate_expr", "tests/test_config_parser.py::TestConfigParser::test_parse_with_comments", "tests/test_config_parser.py::TestConfigParser::test_missing_config", "tests/test_config_parser.py::TestConfigParser::test_parse_null", "tests/test_config_parser.py::TestConfigParser::test_parse_empty", "tests/test_config_parser.py::TestConfigParser::test_parse_override", "tests/test_config_parser.py::TestConfigParser::test_concat_dict", "tests/test_config_parser.py::TestConfigParser::test_concat_string", "tests/test_config_parser.py::TestConfigParser::test_concat_list", "tests/test_config_parser.py::TestConfigParser::test_int_substitutions", "tests/test_config_parser.py::TestConfigParser::test_cascade_string_substitutions", "tests/test_config_parser.py::TestConfigParser::test_dict_substitutions", "tests/test_config_parser.py::TestConfigParser::test_list_substitutions", "tests/test_config_parser.py::TestConfigParser::test_non_existent_substitution", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_string", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_list", "tests/test_config_parser.py::TestConfigParser::test_concat_multi_line_dict", "tests/test_config_parser.py::TestConfigParser::test_include_dict", "tests/test_config_parser.py::TestConfigParser::test_list_of_dicts" ]
[]
Apache License 2.0
92
[ "pyhocon/__init__.py", "pyhocon/config_tree.py" ]
[ "pyhocon/__init__.py", "pyhocon/config_tree.py" ]
falconry__falcon-494
92560ebafb8dc20f8aaa6e072536185622c5a88e
2015-04-14 13:58:49
6608a5f10aead236ae5345488813de805b85b064
mcmasterathl: I will rebase this when #495 is merged, as I am pretty sure they conflict. jmvrbanac: @mcmasterathl when you have time, could you rebase your change? Thanks! mcmasterathl: Yup, was working on that right now actually. mcmasterathl: @jmvrbanac All set jmvrbanac: :+1: LGTM
diff --git a/falcon/request.py b/falcon/request.py index 6acb1e6..116af67 100644 --- a/falcon/request.py +++ b/falcon/request.py @@ -617,12 +617,13 @@ class Request(object): try: http_date = self.get_header(header, required=required) - return util.http_date_to_dt(http_date) + return util.http_date_to_dt(http_date, obs_date=True) except TypeError: # When the header does not exist and isn't required return None except ValueError: - msg = ('It must be formatted according to RFC 1123.') + msg = ('It must be formatted according to RFC 7231, ' + 'Section 7.1.1.1') raise HTTPInvalidHeader(msg, header) def get_param(self, name, required=False, store=None, default=None): diff --git a/falcon/util/misc.py b/falcon/util/misc.py index ebfefcf..8922e44 100644 --- a/falcon/util/misc.py +++ b/falcon/util/misc.py @@ -88,19 +88,41 @@ def dt_to_http(dt): return dt.strftime('%a, %d %b %Y %H:%M:%S GMT') -def http_date_to_dt(http_date): +def http_date_to_dt(http_date, obs_date=False): """Converts an HTTP date string to a datetime instance. Args: http_date (str): An RFC 1123 date string, e.g.: "Tue, 15 Nov 1994 12:45:26 GMT". + obs_date (bool): Support obs-date formats according to RFC 7231, e.g.: + "Sunday, 06-Nov-94 08:49:37 GMT" + "Sun Nov 6 08:49:37 1994". Returns: datetime: A UTC datetime instance corresponding to the given HTTP date. + + Raises: + ValueError: http_date doesn't match any of the available time formats """ - return strptime(http_date, '%a, %d %b %Y %H:%M:%S %Z') + time_formats = ['%a, %d %b %Y %H:%M:%S %Z'] + + if obs_date: + time_formats.extend([ + '%A, %d-%b-%y %H:%M:%S %Z', + '%a %b %d %H:%M:%S %Y', + ]) + + # Loop through the formats and return the first that matches + for time_format in time_formats: + try: + return strptime(http_date, time_format) + except ValueError: + continue + + # Did not match any formats + raise ValueError('time data %r does not match known formats' % http_date) def to_query_str(params):
Support obsolete HTTP date formats In looking at [RFC 7231](http://tools.ietf.org/html/rfc7231#section-7.1.1.1), Falcon date parsing is actually restricted to IMF-fixdate and does not support the other two obsolete formats. Should we support those formats? Doing so may have minor performance implications for little benefit. Otherwise, we should update the docstrings and such to reference IMF-fixdate instead of HTTP-Date.
falconry/falcon
diff --git a/tests/test_req_vars.py b/tests/test_req_vars.py index 56a786d..48dfe06 100644 --- a/tests/test_req_vars.py +++ b/tests/test_req_vars.py @@ -527,7 +527,7 @@ class TestReqVars(testing.TestBase): headers = {header: 'Thu, 04 Apr 2013'} expected_desc = ('The value provided for the {0} ' 'header is invalid. It must be formatted ' - 'according to RFC 1123.') + 'according to RFC 7231, Section 7.1.1.1') self._test_error_details(headers, attr, falcon.HTTPInvalidHeader, diff --git a/tests/test_utils.py b/tests/test_utils.py index b5a0d35..29576a8 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -70,6 +70,15 @@ class TestFalconUtils(testtools.TestCase): falcon.http_date_to_dt('Thu, 04 Apr 2013 10:28:54 GMT'), datetime(2013, 4, 4, 10, 28, 54)) + self.assertEqual( + falcon.http_date_to_dt('Sunday, 06-Nov-94 08:49:37 GMT', + obs_date=True), + datetime(1994, 11, 6, 8, 49, 37)) + + self.assertEqual( + falcon.http_date_to_dt('Sun Nov 6 08:49:37 1994', obs_date=True), + datetime(1994, 11, 6, 8, 49, 37)) + def test_pack_query_params_none(self): self.assertEqual( falcon.to_query_str({}),
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "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": "requirements.txt", "pip_packages": [ "nose", "coverage", "ddt", "pyyaml", "requests", "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@92560ebafb8dc20f8aaa6e072536185622c5a88e#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_date_invalid_1___Date____date__", "tests/test_req_vars.py::TestReqVars::test_date_invalid_2___If_Modified_Since____if_modified_since__", "tests/test_req_vars.py::TestReqVars::test_date_invalid_3___If_Unmodified_Since____if_unmodified_since__", "tests/test_utils.py::TestFalconUtils::test_http_date_to_dt" ]
[ "tests/test_req_vars.py::TestReqVars::test_client_accepts", "tests/test_utils.py::TestFalconUtils::test_deprecated_decorator" ]
[ "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_1___Date____date__", "tests/test_req_vars.py::TestReqVars::test_date_2___If_Modified_since____if_modified_since__", "tests/test_req_vars.py::TestReqVars::test_date_3___If_Unmodified_since____if_unmodified_since__", "tests/test_req_vars.py::TestReqVars::test_date_missing_1_date", "tests/test_req_vars.py::TestReqVars::test_date_missing_2_if_modified_since", "tests/test_req_vars.py::TestReqVars::test_date_missing_3_if_unmodified_since", "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_range_invalid", "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", "tests/test_utils.py::TestFalconUtils::test_dt_to_http", "tests/test_utils.py::TestFalconUtils::test_pack_query_params_none", "tests/test_utils.py::TestFalconUtils::test_pack_query_params_one", "tests/test_utils.py::TestFalconUtils::test_pack_query_params_several", "tests/test_utils.py::TestFalconUtils::test_parse_host", "tests/test_utils.py::TestFalconUtils::test_parse_query_string", "tests/test_utils.py::TestFalconUtils::test_prop_uri_decode_models_stdlib_unquote_plus", "tests/test_utils.py::TestFalconUtils::test_prop_uri_encode_models_stdlib_quote", "tests/test_utils.py::TestFalconUtils::test_prop_uri_encode_value_models_stdlib_quote_safe_tilde", "tests/test_utils.py::TestFalconUtils::test_uri_decode", "tests/test_utils.py::TestFalconUtils::test_uri_encode", "tests/test_utils.py::TestFalconUtils::test_uri_encode_value", "tests/test_utils.py::TestFalconTesting::test_decode_empty_result", "tests/test_utils.py::TestFalconTesting::test_none_header_value_in_create_environ", "tests/test_utils.py::TestFalconTesting::test_path_escape_chars_in_create_environ" ]
[]
Apache License 2.0
93
[ "falcon/request.py", "falcon/util/misc.py" ]
[ "falcon/request.py", "falcon/util/misc.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
[ "SoftLayer/CLI/server/detail.py", "SoftLayer/managers/hardware.py" ]
[ "SoftLayer/CLI/server/detail.py", "SoftLayer/managers/hardware.py" ]
Shopify__shopify_python_api-94
77dfd01e6e2bda80767663bd8214234f11b9ebdc
2015-04-14 20:53:47
c29e0ecbed9de67dd923f980a3ac053922dab75e
diff --git a/.gitignore b/.gitignore index f62c50b..ba6c0eb 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ tags /ShopifyAPI.egg-info *.egg /.idea +.DS_Store diff --git a/CHANGELOG b/CHANGELOG index 00fe323..4301098 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,7 +2,6 @@ * Added Checkout resource * Updated to pyactiveresource v2.1.1 which includes a test-related bugfix -* Changed OAuth validation from MD5 to HMAC-SHA256 == Version 2.1.0 diff --git a/README.md b/README.md index 7234905..2f362f1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,3 @@ -[![Build Status](https://travis-ci.org/Shopify/shopify_python_api.svg?branch=master)](https://travis-ci.org/Shopify/shopify_python_api) -[![Package Version](https://pypip.in/version/ShopifyAPI/badge.svg)](https://pypi.python.org/pypi/ShopifyAPI) - # Shopify API The ShopifyAPI library allows Python developers to programmatically @@ -62,11 +59,11 @@ these steps: shop_url = "https://%s:%s@SHOP_NAME.myshopify.com/admin" % (API_KEY, PASSWORD) shopify.ShopifyResource.set_site(shop_url) ``` - + That's it you're done, skip to step 6 and start using the API! For a partner App you will need to supply two parameters to the Session class before you instantiate it: - + ```python shopify.Session.setup(api_key=API_KEY, secret=SHARED_SECRET) ``` @@ -85,27 +82,27 @@ these steps: * scope – Required – The list of required scopes (explained here: http://docs.shopify.com/api/tutorials/oauth) * redirect_uri – Optional – The URL that the merchant will be sent to once authentication is complete. Defaults to the URL specified in the application settings and must be the same host as that URL. ``` - + We've added the create_permision_url method to make this easier, first instantiate your session object: - + ```python session = shopify.Session("SHOP_NAME.myshopify.com") ``` - + Then call: ```python scope=["write_products"] permission_url = session.create_permission_url(scope) ``` - + or if you want a custom redirect_uri: - + ```python permission_url = session.create_permission_url(scope, "https://my_redirect_uri.com") ``` - + 4. Once authorized, the shop redirects the owner to the return URL of your application with a parameter named 'code'. This is a temporary token that the app can exchange for a permanent access token. Make the following call: @@ -119,11 +116,11 @@ these steps: * client_secret – Required – The shared secret for your app * code – Required – The code you received in step 3 ``` - + and you'll get your permanent access token back in the response. - There is a method to make the request and get the token for you. Pass - all the params received from the previous call (shop, code, timestamp, + There is a method to make the request and get the token for you. Pass + all the params received from the previous call (shop, code, timestamp, signature) as a dictionary and the method will verify the params, extract the temp code and then request your token: diff --git a/shopify/resources/recurring_application_charge.py b/shopify/resources/recurring_application_charge.py index f0e3004..5ed4c92 100644 --- a/shopify/resources/recurring_application_charge.py +++ b/shopify/resources/recurring_application_charge.py @@ -1,11 +1,21 @@ from ..base import ShopifyResource +def _get_first_by_status(resources, status): + for resource in resources: + if resource.status == status: + return resource + return None + class RecurringApplicationCharge(ShopifyResource): @classmethod def current(cls): - return cls.find_first(status="active") + """ + Returns first RecurringApplicationCharge object with status=active. + If not found, None will be returned. + """ + return _get_first_by_status(cls.find(), "active") def cancel(self): self._load_attributes_from_response(self.destroy) diff --git a/shopify/session.py b/shopify/session.py index 8741ec4..9058d55 100644 --- a/shopify/session.py +++ b/shopify/session.py @@ -1,6 +1,8 @@ import time -import hmac -from hashlib import sha256 +try: + from hashlib import md5 +except ImportError: + from md5 import md5 try: import simplejson as json except ImportError: @@ -51,7 +53,7 @@ class Session(object): return self.token if not self.validate_params(params): - raise ValidationException('Invalid HMAC: Possibly malicious login') + raise ValidationException('Invalid Signature: Possibly malicious login') code = params['code'] @@ -92,30 +94,18 @@ class Session(object): if int(params['timestamp']) < time.time() - one_day: return False - return cls.validate_hmac(params) + return cls.validate_signature(params) @classmethod - def validate_hmac(cls, params): - if 'hmac' not in params: + def validate_signature(cls, params): + if "signature" not in params: return False - hmac_calculated = cls.calculate_hmac(params) - hmac_to_verify = params['hmac'] + sorted_params = "" + signature = params['signature'] - # Try to use compare_digest() to reduce vulnerability to timing attacks. - # If it's not available, just fall back to regular string comparison. - try: - return hmac.compare_digest(hmac_calculated, hmac_to_verify) - except AttributeError: - return hmac_calculated == hmac_to_verify + for k in sorted(params.keys()): + if k != "signature": + sorted_params += k + "=" + str(params[k]) - @classmethod - def calculate_hmac(cls, params): - """ - Calculate the HMAC of the given parameters in line with Shopify's rules for OAuth authentication. - See http://docs.shopify.com/api/authentication/oauth#verification. - """ - # Sort and combine query parameters into a single string, excluding those that should be removed and joining with '&'. - sorted_params = '&'.join(['{0}={1}'.format(k, params[k]) for k in sorted(params.keys()) if k not in ['signature', 'hmac']]) - # Generate the hex digest for the sorted parameters using the secret. - return hmac.new(cls.secret.encode(), sorted_params.encode(), sha256).hexdigest() + return md5((cls.secret + sorted_params).encode('utf-8')).hexdigest() == signature
RecurringApplicationCharge.current() does not work as expected In RecurringApplicationCharge class there is class method "current" that doesn't work as expexted. ## Problem I have few RecurringApplicationCharge instances for my test shop but none of them has status=active. I was expecting to get None as a result when using current() method but instead a RecurringApplicationCharge with status rejected was returned. ```python class RecurringApplicationCharge(ShopifyResource): @classmethod def current(cls): return cls.find_first(status="active") ``` ## Excpected result First RecurringApplicationCharge object with status=active should be returned or None if no matches found. Anyway I noticed that documentation (http://docs.shopify.com/api/recurringapplicationcharge) states that it is only possible to filter with field "since_id". If this is correct, then this method should be removed.
Shopify/shopify_python_api
diff --git a/test/fixtures/recurring_application_charges.json b/test/fixtures/recurring_application_charges.json new file mode 100644 index 0000000..45b4109 --- /dev/null +++ b/test/fixtures/recurring_application_charges.json @@ -0,0 +1,38 @@ +{ + "recurring_application_charges": [ + { + "activated_on": null, + "api_client_id": 755357713, + "billing_on": "2015-01-15T00:00:00+00:00", + "cancelled_on": null, + "created_at": "2015-01-16T11:45:44-05:00", + "id": 455696195, + "name": "Super Mega Plan", + "price": "15.00", + "return_url": "http://yourapp.com", + "status": "accepted", + "test": null, + "trial_days": 0, + "trial_ends_on": null, + "updated_at": "2015-01-16T11:46:56-05:00", + "decorated_return_url": "http://yourapp.com?charge_id=455696195" + }, + { + "activated_on": "2015-01-15T00:00:00+00:00", + "api_client_id": 755357713, + "billing_on": "2015-01-15T00:00:00+00:00", + "cancelled_on": null, + "created_at": "2015-01-16T11:45:44-05:00", + "id": 455696195, + "name": "Super Mega Plan 2", + "price": "15.00", + "return_url": "http://yourapp.com", + "status": "active", + "test": null, + "trial_days": 0, + "trial_ends_on": null, + "updated_at": "2015-01-16T11:46:56-05:00", + "decorated_return_url": "http://yourapp.com?charge_id=455696195" + } + ] +} \ No newline at end of file diff --git a/test/fixtures/recurring_application_charges_no_active.json b/test/fixtures/recurring_application_charges_no_active.json new file mode 100644 index 0000000..c806aa3 --- /dev/null +++ b/test/fixtures/recurring_application_charges_no_active.json @@ -0,0 +1,38 @@ +{ + "recurring_application_charges": [ + { + "activated_on": null, + "api_client_id": 755357713, + "billing_on": "2015-01-15T00:00:00+00:00", + "cancelled_on": null, + "created_at": "2015-01-16T11:45:44-05:00", + "id": 455696195, + "name": "Super Mega Plan", + "price": "15.00", + "return_url": "http://yourapp.com", + "status": "accepted", + "test": null, + "trial_days": 0, + "trial_ends_on": null, + "updated_at": "2015-01-16T11:46:56-05:00", + "decorated_return_url": "http://yourapp.com?charge_id=455696195" + }, + { + "activated_on": "2015-01-15T00:00:00+00:00", + "api_client_id": 755357713, + "billing_on": "2015-01-15T00:00:00+00:00", + "cancelled_on": null, + "created_at": "2015-01-16T11:45:44-05:00", + "id": 455696195, + "name": "Super Mega Plan 2", + "price": "15.00", + "return_url": "http://yourapp.com", + "status": "rejected", + "test": null, + "trial_days": 0, + "trial_ends_on": null, + "updated_at": "2015-01-16T11:46:56-05:00", + "decorated_return_url": "http://yourapp.com?charge_id=455696195" + } + ] +} \ No newline at end of file diff --git a/test/recurring_charge_test.py b/test/recurring_charge_test.py index eca78e2..70b3660 100644 --- a/test/recurring_charge_test.py +++ b/test/recurring_charge_test.py @@ -7,3 +7,17 @@ class RecurringApplicationChargeTest(TestCase): self.fake("recurring_application_charges/35463/activate", method='POST',headers={'Content-length':'0', 'Content-type': 'application/json'}, body=" ") charge = shopify.RecurringApplicationCharge({'id': 35463}) charge.activate() + + def test_current_method_returns_active_charge(self): + # Test that current() class method correctly returns + # first RecurringApplicationCharge with active status + self.fake("recurring_application_charges") + charge = shopify.RecurringApplicationCharge.current() + self.assertEqual(charge.id, 455696195) + + def test_current_method_returns_none_if_active_not_found(self): + # Test that current() class method correctly returns + # None if RecurringApplicationCharge with active status not found + self.fake("recurring_application_charges", body=self.load_fixture("recurring_application_charges_no_active")) + charge = shopify.RecurringApplicationCharge.current() + self.assertEqual(charge, None) diff --git a/test/session_test.py b/test/session_test.py index c85eb4b..c8c1643 100644 --- a/test/session_test.py +++ b/test/session_test.py @@ -113,54 +113,24 @@ class SessionTest(TestCase): session = shopify.Session("testshop.myshopify.com", "any-token") self.assertEqual("https://testshop.myshopify.com/admin", session.site) - def test_hmac_calculation(self): - # Test using the secret and parameter examples given in the Shopify API documentation. - shopify.Session.secret='hush' - params = { - 'shop': 'some-shop.myshopify.com', - 'code': 'a94a110d86d2452eb3e2af4cfb8a3828', - 'timestamp': '1337178173', - 'signature': '6e39a2ea9e497af6cb806720da1f1bf3', - 'hmac': '2cb1a277650a659f1b11e92a4a64275b128e037f2c3390e3c8fd2d8721dac9e2', - } - self.assertEqual(shopify.Session.calculate_hmac(params), params['hmac']) - - def test_return_token_if_hmac_is_valid(self): + def test_return_token_if_signature_is_valid(self): shopify.Session.secret='secret' params = {'code': 'any-code', 'timestamp': time.time()} - hmac = shopify.Session.calculate_hmac(params) - params['hmac'] = hmac + sorted_params = self.make_sorted_params(params) + signature = md5((shopify.Session.secret + sorted_params).encode('utf-8')).hexdigest() + params['signature'] = signature self.fake(None, url='https://localhost.myshopify.com/admin/oauth/access_token', method='POST', body='{"access_token" : "token"}', has_user_agent=False) session = shopify.Session('http://localhost.myshopify.com') token = session.request_token(params) self.assertEqual("token", token) - def test_return_token_if_hmac_is_valid_but_signature_also_provided(self): - shopify.Session.secret='secret' - params = {'code': 'any-code', 'timestamp': time.time(), 'signature': '6e39a2'} - hmac = shopify.Session.calculate_hmac(params) - params['hmac'] = hmac - - self.fake(None, url='https://localhost.myshopify.com/admin/oauth/access_token', method='POST', body='{"access_token" : "token"}', has_user_agent=False) - session = shopify.Session('http://localhost.myshopify.com') - token = session.request_token(params) - self.assertEqual("token", token) - - def test_raise_error_if_hmac_is_invalid(self): - shopify.Session.secret='secret' - params = {'code': 'any-code', 'timestamp': time.time()} - params['hmac'] = 'a94a110d86d2452e92a4a64275b128e9273be3037f2c339eb3e2af4cfb8a3828' - - with self.assertRaises(shopify.ValidationException): - session = shopify.Session('http://localhost.myshopify.com') - session = session.request_token(params) - - def test_raise_error_if_hmac_does_not_match_expected(self): + def test_raise_error_if_signature_does_not_match_expected(self): shopify.Session.secret='secret' params = {'foo': 'hello', 'timestamp': time.time()} - hmac = shopify.Session.calculate_hmac(params) - params['hmac'] = hmac + sorted_params = self.make_sorted_params(params) + signature = md5((shopify.Session.secret + sorted_params).encode('utf-8')).hexdigest() + params['signature'] = signature params['bar'] = 'world' params['code'] = 'code' @@ -172,13 +142,22 @@ class SessionTest(TestCase): shopify.Session.secret='secret' one_day = 24 * 60 * 60 params = {'code': 'any-code', 'timestamp': time.time()-(2*one_day)} - hmac = shopify.Session.calculate_hmac(params) - params['hmac'] = hmac + sorted_params = self.make_sorted_params(params) + signature = md5((shopify.Session.secret + sorted_params).encode('utf-8')).hexdigest() + params['signature'] = signature with self.assertRaises(shopify.ValidationException): session = shopify.Session('http://localhost.myshopify.com') session = session.request_token(params) + + def make_sorted_params(self, params): + sorted_params = "" + for k in sorted(params.keys()): + if k != "signature": + sorted_params += k + "=" + str(params[k]) + return sorted_params + def normalize_url(self, url): scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url) query = "&".join(sorted(query.split("&")))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks", "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": 5 }
2.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" ], "pre_install": null, "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@77dfd01e6e2bda80767663bd8214234f11b9ebdc#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/recurring_charge_test.py::RecurringApplicationChargeTest::test_current_method_returns_active_charge", "test/recurring_charge_test.py::RecurringApplicationChargeTest::test_current_method_returns_none_if_active_not_found", "test/session_test.py::SessionTest::test_return_token_if_signature_is_valid" ]
[]
[ "test/recurring_charge_test.py::RecurringApplicationChargeTest::test_activate_charge", "test/session_test.py::SessionTest::test_be_valid_with_any_token_and_any_url", "test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_dual_scope_no_redirect_uri", "test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_no_scope_no_redirect_uri", "test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_single_scope_and_redirect_uri", "test/session_test.py::SessionTest::test_create_permission_url_returns_correct_url_with_single_scope_no_redirect_uri", "test/session_test.py::SessionTest::test_not_be_valid_without_a_url", "test/session_test.py::SessionTest::test_not_be_valid_without_token", "test/session_test.py::SessionTest::test_not_raise_error_without_params", "test/session_test.py::SessionTest::test_raise_error_if_params_passed_but_signature_omitted", "test/session_test.py::SessionTest::test_raise_error_if_signature_does_not_match_expected", "test/session_test.py::SessionTest::test_raise_error_if_timestamp_is_too_old", "test/session_test.py::SessionTest::test_raise_exception_if_code_invalid_in_request_token", "test/session_test.py::SessionTest::test_return_site_for_session", "test/session_test.py::SessionTest::test_setup_api_key_and_secret_for_all_sessions", "test/session_test.py::SessionTest::test_temp_reset_shopify_ShopifyResource_site_to_original_value", "test/session_test.py::SessionTest::test_temp_reset_shopify_ShopifyResource_site_to_original_value_when_using_a_non_standard_port", "test/session_test.py::SessionTest::test_temp_works_without_currently_active_session", "test/session_test.py::SessionTest::test_use_https_protocol_by_default_for_all_sessions" ]
[]
MIT License
95
[ ".gitignore", "README.md", "shopify/session.py", "shopify/resources/recurring_application_charge.py", "CHANGELOG" ]
[ ".gitignore", "README.md", "shopify/session.py", "shopify/resources/recurring_application_charge.py", "CHANGELOG" ]
softlayer__softlayer-python-526
200787d4c3bf37bc4e701caf6a52e24dd07d18a3
2015-04-14 21:29:21
200787d4c3bf37bc4e701caf6a52e24dd07d18a3
diff --git a/SoftLayer/managers/metadata.py b/SoftLayer/managers/metadata.py index 405f88da..d6477cc1 100644 --- a/SoftLayer/managers/metadata.py +++ b/SoftLayer/managers/metadata.py @@ -82,10 +82,13 @@ def get(self, name, param=None): raise exceptions.SoftLayerError( 'Parameter required to get this attribute.') + params = tuple() + if param is not None: + params = (param,) try: return self.client.call('Resource_Metadata', self.attribs[name]['call'], - param) + *params) except exceptions.SoftLayerAPIError as ex: if ex.faultCode == 404: return None
'slcli metadata tags' command fails The 'slcli metadata tags' command fails, the following exception is raised when debug is set: slcli -vvv metadata tags === REQUEST === https://api.service.softlayer.com/rest/v3.1/SoftLayer_Resource_Metadata/Tags/None.json {'Content-Type': 'application/json', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept': '*/*', 'User-Agent': 'softlayer-python/v4.0.0'} Starting new HTTPS connection (1): api.service.softlayer.com Setting read timeout to 5 "GET /rest/v3.1/SoftLayer_Resource_Metadata/Tags/None.json HTTP/1.1" 404 70 === RESPONSE === CaseInsensitiveDict({'x-client-ip': '192.168.67.116', 'content-length': '70', 'vary': 'Accept-Encoding', 'server': 'Apache', 'x-backside-transport': 'FAIL FAIL', 'connection': 'close', 'date': 'Tue, 14 Apr 2015 21:15:33 GMT', 'content-type': 'application/json'}) {"error":"Service does not exist","code":"SoftLayer_Exception_Public"} The following commands failed as well slcli metadata backend_ip slcli metadata backend_mac slcli metadata datacenter slcli metadata datacenter_id slcli metadata fqdn slcli metadata frontend_mac slcli metadata id slcli metadata ip slcli metadata network slcli metadata provision_state slcli metadata tags slcli metadata user_data The problem is reproduced using API SoftLayer python client version 4, using version 3 of the client to run the 'sl metadata tags' command works with no problems
softlayer/softlayer-python
diff --git a/SoftLayer/tests/managers/metadata_tests.py b/SoftLayer/tests/managers/metadata_tests.py index 9d471265..1ee2b3bd 100644 --- a/SoftLayer/tests/managers/metadata_tests.py +++ b/SoftLayer/tests/managers/metadata_tests.py @@ -28,7 +28,8 @@ def test_no_param(self): self.assertEqual('dal01', resp) self.assert_called_with('SoftLayer_Resource_Metadata', 'Datacenter', - identifier=None) + identifier=None, + args=tuple()) def test_w_param(self): resp = self.metadata.get('vlans', '1:2:3:4:5')
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "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/managers/metadata_tests.py::MetadataTests::test_no_param" ]
[]
[ "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_404", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_error", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_get", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_networks", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_not_exists", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_return_none", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_user_data", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_w_param", "SoftLayer/tests/managers/metadata_tests.py::MetadataTests::test_w_param_error" ]
[]
MIT License
96
[ "SoftLayer/managers/metadata.py" ]
[ "SoftLayer/managers/metadata.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
[ "falcon/request.py" ]
[ "falcon/request.py" ]
falconry__falcon-511
73d9f4142ff9f04342f6abfe649c98dda409c477
2015-04-15 16:48:05
6608a5f10aead236ae5345488813de805b85b064
diff --git a/doc/user/install.rst b/doc/user/install.rst index 6633e0e..482becd 100644 --- a/doc/user/install.rst +++ b/doc/user/install.rst @@ -21,16 +21,6 @@ type: $ pip install --upgrade falcon -.. note:: - - When using Cython, you should always recompile Falcon after - upgrading Python. To do this, simply run: - - .. code:: bash - - $ pip install --force-reinstall --upgrade cython - $ pip install --force-reinstall --upgrade falcon - Installing Cython on OS X ------------------------- diff --git a/falcon/api.py b/falcon/api.py index b12e16d..ff61dc1 100644 --- a/falcon/api.py +++ b/falcon/api.py @@ -53,7 +53,7 @@ class API(object): \""" def process_resource(self, req, resp, resource): - \"""Process the request and resource *after* routing. + \"""Process the request after routing. Args: req: Request object that will be passed to the diff --git a/falcon/request.py b/falcon/request.py index be8aabf..b52fe13 100644 --- a/falcon/request.py +++ b/falcon/request.py @@ -146,10 +146,10 @@ class Request(object): header is missing. if_none_match (str): Value of the If-None-Match header, or ``None`` if the header is missing. - if_modified_since (str): Value of the If-Modified-Since header, or - ``None`` if the header is missing. - if_unmodified_since (str): Value of the If-Unmodified-Sinc header, + if_modified_since (datetime): Value of the If-Modified-Since header, or ``None`` if the header is missing. + if_unmodified_since (datetime): Value of the If-Unmodified-Since + header, or ``None`` if the header is missing. if_range (str): Value of the If-Range header, or ``None`` if the header is missing. @@ -271,8 +271,6 @@ class Request(object): if_match = helpers.header_property('HTTP_IF_MATCH') if_none_match = helpers.header_property('HTTP_IF_NONE_MATCH') - if_modified_since = helpers.header_property('HTTP_IF_MODIFIED_SINCE') - if_unmodified_since = helpers.header_property('HTTP_IF_UNMODIFIED_SINCE') if_range = helpers.header_property('HTTP_IF_RANGE') @property @@ -326,16 +324,15 @@ class Request(object): @property def date(self): - try: - http_date = self.env['HTTP_DATE'] - except KeyError: - return None + return self.get_header_as_datetime('Date') - try: - return util.http_date_to_dt(http_date) - except ValueError: - msg = ('It must be formatted according to RFC 1123.') - raise HTTPInvalidHeader(msg, 'Date') + @property + def if_modified_since(self): + return self.get_header_as_datetime('If-Modified-Since') + + @property + def if_unmodified_since(self): + return self.get_header_as_datetime('If-Unmodified-Since') @property def range(self): @@ -343,9 +340,6 @@ 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 @@ -574,6 +568,35 @@ class Request(object): raise HTTPMissingParam(name) + def get_header_as_datetime(self, header, required=False): + """Return an HTTP header with HTTP-Date values as a datetime. + + Args: + name (str): Header name, case-insensitive (e.g., 'Date') + required (bool, optional): Set to ``True`` to raise + ``HTTPBadRequest`` instead of returning gracefully when the + header is not found (default ``False``). + + Returns: + datetime: The value of the specified header if it exists, + or ``None`` if the header is not found and is not required. + + Raises: + HTTPBadRequest: The header was not found in the request, but + it was required. + HttpInvalidHeader: The header contained a malformed/invalid value. + """ + + try: + http_date = self.get_header(header, required=required) + return util.http_date_to_dt(http_date) + except TypeError: + # When the header does not exist and isn't required + return None + except ValueError: + msg = ('It must be formatted according to RFC 1123.') + raise HTTPInvalidHeader(msg, header) + def get_param(self, name, required=False, store=None, default=None): """Return the raw value of a query string parameter as a string. diff --git a/tools/clean.sh b/tools/clean.sh deleted file mode 100755 index 5d41474..0000000 --- a/tools/clean.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash - -find $1 \( -name '*.c' -or -name '*.so' -or -name '*.pyc' \) -delete diff --git a/tools/clean_cythoned.sh b/tools/clean_cythoned.sh new file mode 100755 index 0000000..c0c97af --- /dev/null +++ b/tools/clean_cythoned.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +rm -f $1/*.c +rm -f $1/*.so +rm -f $1/*.pyc diff --git a/tox.ini b/tox.ini index 4cc43ed..b950eb4 100644 --- a/tox.ini +++ b/tox.ini @@ -24,13 +24,13 @@ envlist = py26, [testenv] deps = -r{toxinidir}/tools/test-requires -commands = {toxinidir}/tools/clean.sh {toxinidir}/falcon +commands = {toxinidir}/tools/clean_cythoned.sh {toxinidir}/falcon nosetests {posargs} [testenv:py27] deps = -r{toxinidir}/tools/test-requires nose-cprof -commands = {toxinidir}/tools/clean.sh {toxinidir}/falcon +commands = {toxinidir}/tools/clean_cythoned.sh {toxinidir}/falcon nosetests \ --with-cprofile \ --cprofile-stats-erase \ @@ -41,7 +41,7 @@ commands = {toxinidir}/tools/clean.sh {toxinidir}/falcon deps = -r{toxinidir}/tools/test-requires cython basepython = python2.7 -commands = {toxinidir}/tools/clean.sh {toxinidir}/falcon +commands = {toxinidir}/tools/clean_cythoned.sh {toxinidir}/falcon nosetests \ {posargs} @@ -49,7 +49,7 @@ commands = {toxinidir}/tools/clean.sh {toxinidir}/falcon deps = -r{toxinidir}/tools/test-requires cython basepython = python3.3 -commands = {toxinidir}/tools/clean.sh {toxinidir}/falcon +commands = {toxinidir}/tools/clean_cythoned.sh {toxinidir}/falcon nosetests \ {posargs} @@ -57,7 +57,7 @@ commands = {toxinidir}/tools/clean.sh {toxinidir}/falcon deps = -r{toxinidir}/tools/test-requires cython basepython = python3.4 -commands = {toxinidir}/tools/clean.sh {toxinidir}/falcon +commands = {toxinidir}/tools/clean_cythoned.sh {toxinidir}/falcon nosetests \ {posargs}
Return if-modified-since, if-unmodified-since as datetime.datetime Currently, the HTTP date string is returned. It might as well be parsed, since the app will need to do that anyway before it can use the value.
falconry/falcon
diff --git a/falcon/testing/helpers.py b/falcon/testing/helpers.py index a292587..5e1dfb0 100644 --- a/falcon/testing/helpers.py +++ b/falcon/testing/helpers.py @@ -15,28 +15,15 @@ import random import io import sys -from datetime import datetime import six -import falcon from falcon.util import uri # Constants DEFAULT_HOST = 'falconframework.org' -def httpnow(): - """Returns the current UTC time as an RFC 1123 date. - - Returns: - str: An HTTP date string, e.g., "Tue, 15 Nov 1994 12:45:26 GMT". - - """ - - return falcon.dt_to_http(datetime.utcnow()) - - def rand_string(min, max): """Returns a randomly-generated string, of a random length. diff --git a/tests/test_req_vars.py b/tests/test_req_vars.py index 5ee1809..978770e 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': 'bytes=10-'} + headers = {'Range': '10-'} req = Request(testing.create_environ(headers=headers)) self.assertEqual(req.range, (10, -1)) - headers = {'Range': 'bytes=10-20'} + headers = {'Range': '10-20'} req = Request(testing.create_environ(headers=headers)) self.assertEqual(req.range, (10, 20)) - headers = {'Range': 'bytes=-10240'} + headers = {'Range': '-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': 'bytes=10240'} + headers = {'Range': '10240'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=-'} + headers = {'Range': '-'} 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': 'bytes=--'} + headers = {'Range': '--'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=-3-'} + headers = {'Range': '-3-'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=-3-4'} + headers = {'Range': '-3-4'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=3-3-4'} + headers = {'Range': '3-3-4'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=3-3-'} + headers = {'Range': '3-3-'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=3-3- '} + headers = {'Range': '3-3- '} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=fizbit'} + headers = {'Range': 'fizbit'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=a-'} + headers = {'Range': 'a-'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=a-3'} + headers = {'Range': 'a-3'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=-b'} + headers = {'Range': '-b'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=3-b'} + headers = {'Range': '3-b'} req = Request(testing.create_environ(headers=headers)) self.assertRaises(falcon.HTTPBadRequest, lambda: req.range) - headers = {'Range': 'bytes=x-y'} + headers = {'Range': '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,14 +463,6 @@ 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) @@ -505,28 +497,47 @@ class TestReqVars(testing.TestBase): falcon.HTTPInvalidHeader, 'Invalid header value', expected_desc) - def test_date(self): + @ddt.data(('Date', 'date'), + ('If-Modified-since', 'if_modified_since'), + ('If-Unmodified-since', 'if_unmodified_since'), + ) + @ddt.unpack + def test_date(self, header, attr): date = datetime.datetime(2013, 4, 4, 5, 19, 18) - headers = {'date': 'Thu, 04 Apr 2013 05:19:18 GMT'} - req = Request(testing.create_environ(headers=headers)) - self.assertEqual(req.date, date) + date_str = 'Thu, 04 Apr 2013 05:19:18 GMT' + + self._test_header_expected_value(header, date_str, attr, date) - @ddt.data('Thu, 04 Apr 2013', '') - def test_date_invalid(self, http_date): - headers = {'date': http_date} - expected_desc = ('The value provided for the Date ' + @ddt.data(('Date', 'date'), + ('If-Modified-Since', 'if_modified_since'), + ('If-Unmodified-Since', 'if_unmodified_since'), + ) + @ddt.unpack + def test_date_invalid(self, header, attr): + + # Date formats don't conform to RFC 1123 + headers = {header: 'Thu, 04 Apr 2013'} + expected_desc = ('The value provided for the {0} ' 'header is invalid. It must be formatted ' 'according to RFC 1123.') - self._test_error_details(headers, 'date', + + self._test_error_details(headers, attr, falcon.HTTPInvalidHeader, - 'Invalid header value', expected_desc) + 'Invalid header value', + expected_desc.format(header)) + + headers = {header: ''} + self._test_error_details(headers, attr, + falcon.HTTPInvalidHeader, + 'Invalid header value', + expected_desc.format(header)) - def test_date_missing(self): + @ddt.data('date', 'if_modified_since', 'if_unmodified_since') + def test_date_missing(self, attr): req = Request(testing.create_environ()) - self.assertIs(req.date, None) + self.assertIs(getattr(req, attr), None) def test_attribute_headers(self): - date = testing.httpnow() hash = 'fa0d1a60ef6616bb28038515c8ea4cb2' auth = 'HMAC_SHA1 c590afa9bb59191ffab30f223791e82d3fd3e3af' agent = 'testing/1.0.1' @@ -542,12 +553,8 @@ class TestReqVars(testing.TestBase): self._test_attribute_header('Expect', '100-continue', 'expect') self._test_attribute_header('If-Match', hash, 'if_match') - self._test_attribute_header('If-Modified-Since', date, - 'if_modified_since') self._test_attribute_header('If-None-Match', hash, 'if_none_match') self._test_attribute_header('If-Range', hash, 'if_range') - self._test_attribute_header('If-Unmodified-Since', date, - 'if_unmodified_since') self._test_attribute_header('User-Agent', agent, 'user_agent', default=default_agent) @@ -580,6 +587,11 @@ class TestReqVars(testing.TestBase): req = Request(testing.create_environ()) self.assertEqual(getattr(req, attr), default) + def _test_header_expected_value(self, name, value, attr, expected_value): + headers = {name: value} + req = Request(testing.create_environ(headers=headers)) + self.assertEqual(getattr(req, attr), expected_value) + def _test_error_details(self, headers, attr_name, error_type, title, description): req = Request(testing.create_environ(headers=headers))
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_removed_files", "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 4 }
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": [ "pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio", "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 execnet==2.1.1 -e git+https://github.com/falconry/falcon.git@73d9f4142ff9f04342f6abfe649c98dda409c477#egg=falcon idna==3.10 iniconfig==2.1.0 nose==1.3.7 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-mimeparse==2.0.0 PyYAML==6.0.2 requests==2.32.3 six==1.17.0 testtools==2.7.2 tomli==2.2.1 typing_extensions==4.13.0 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 - execnet==2.1.1 - idna==3.10 - iniconfig==2.1.0 - nose==1.3.7 - 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-mimeparse==2.0.0 - pyyaml==6.0.2 - requests==2.32.3 - six==1.17.0 - testtools==2.7.2 - tomli==2.2.1 - typing-extensions==4.13.0 - urllib3==2.3.0 prefix: /opt/conda/envs/falcon
[ "tests/test_req_vars.py::TestReqVars::test_date_2___If_Modified_since____if_modified_since__", "tests/test_req_vars.py::TestReqVars::test_date_3___If_Unmodified_since____if_unmodified_since__", "tests/test_req_vars.py::TestReqVars::test_date_invalid_2___If_Modified_Since____if_modified_since__", "tests/test_req_vars.py::TestReqVars::test_date_invalid_3___If_Unmodified_Since____if_unmodified_since__", "tests/test_req_vars.py::TestReqVars::test_range", "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_1___Date____date__", "tests/test_req_vars.py::TestReqVars::test_date_invalid_1___Date____date__", "tests/test_req_vars.py::TestReqVars::test_date_missing_1_date", "tests/test_req_vars.py::TestReqVars::test_date_missing_2_if_modified_since", "tests/test_req_vars.py::TestReqVars::test_date_missing_3_if_unmodified_since", "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_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
98
[ "falcon/request.py", "tools/clean_cythoned.sh", "falcon/api.py", "tox.ini", "tools/clean.sh", "doc/user/install.rst" ]
[ "falcon/request.py", "tools/clean_cythoned.sh", "falcon/api.py", "tox.ini", "tools/clean.sh", "doc/user/install.rst" ]
typesafehub__conductr-cli-47
e6196516227db9bb9b2027e1d2aa1bd8cb082337
2015-04-16 09:38:43
e5561a7e43d92a0c19e7b6e31a36448455a17fba
diff --git a/conductr_cli/conduct_services.py b/conductr_cli/conduct_services.py index cacec60..2b07544 100644 --- a/conductr_cli/conduct_services.py +++ b/conductr_cli/conduct_services.py @@ -34,10 +34,11 @@ def services(args): service_endpoints = {} for service in data: url = urlparse(service['service']) - try: - service_endpoints[url.path] |= {service['service']} - except KeyError: - service_endpoints[url.path] = {service['service']} + if not (url.path == '' or url.path == '/'): + try: + 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 [] data.insert(0, {'service': 'SERVICE', 'bundle_id': 'BUNDLE ID', 'bundle_name': 'BUNDLE NAME', 'status': 'STATUS'})
Distinct authorities causing spurious warnings on service cmd @edwardcallahan Discovered the following warnings when performing `conduct services` having `http://:8080` and `http://milo.typesafe.com` as endpoint services: ```bash ubuntu@10:~$ conduct services SERVICE BUNDLE ID BUNDLE NAME STATUS http://:8080 d248907 visualizer Running http://milo.typesafe.com 353a913-bbb42aa project-doc Running WARNING: Multiple endpoints found for the following services: WARNING: Service resolution for these services is undefined. ``` Those warnings shouldn't be appearing here as different authorities are used.
typesafehub/conductr-cli
diff --git a/conductr_cli/test/data/two_bundles_no_path.json b/conductr_cli/test/data/two_bundles_no_path.json new file mode 100644 index 0000000..5199179 --- /dev/null +++ b/conductr_cli/test/data/two_bundles_no_path.json @@ -0,0 +1,144 @@ +[ + { + "attributes": { + "bundleName": "multi-comp-multi-endp-1.0.0", + "diskSpace": 100, + "memory": 200, + "nrOfCpus": 1.0, + "roles": [] + }, + "bundleConfig": { + "endpoints": { + "comp1-endp1": { + "protocol": "http", + "services": ["http://:8010/comp1-endp1"] + }, + "comp1-endp2": { + "protocol": "http", + "services": ["http://:8011/comp1-endp2"] + }, + "comp2-endp1": { + "protocol": "http", + "services": ["http://:9010/comp2-endp1"] + }, + "comp2-endp2": { + "protocol": "http", + "services": ["http://:9011"] + } + } + }, + "bundleDigest": "f804d644a01a5ab9f679f76939f5c7e28301e1aecc83627877065cef26de12db", + "bundleExecutions": [ + { + "endpoints": { + "comp1-endp1": { + "bindPort": 8000, + "hostPort": 8000 + }, + "comp1-endp2": { + "bindPort": 8001, + "hostPort": 8001 + }, + "comp2-endp1": { + "bindPort": 9000, + "hostPort": 9000 + }, + "comp2-endp2": { + "bindPort": 9001, + "hostPort": 9001 + } + }, + "host": "172.17.0.4", + "isStarted": true + } + ], + "bundleId": "f804d644a01a5ab9f679f76939f5c7e2", + "bundleInstallations": [ + { + "bundleFile": "file:///tmp/f804d644a01a5ab9f679f76939f5c7e28301e1aecc83627877065cef26de12db.zip", + "uniqueAddress": { + "address": "akka.tcp://[email protected]:9004", + "uid": -29020887 + } + }, + { + "bundleFile": "file:///tmp/f804d644a01a5ab9f679f76939f5c7e28301e1aecc83627877065cef26de12db.zip", + "uniqueAddress": { + "address": "akka.tcp://[email protected]:9004", + "uid": 247035768 + } + } + ] + }, + { + "attributes": { + "bundleName": "multi2-comp-multi-endp-1.0.0", + "diskSpace": 100, + "memory": 200, + "nrOfCpus": 1.0, + "roles": [] + }, + "bundleConfig": { + "endpoints": { + "comp2-endp1": { + "protocol": "http", + "services": ["http://:9010/comp2-endp1"] + }, + "comp2-endp2": { + "protocol": "http", + "services": ["http://:6011"] + }, + "comp3-endp1": { + "protocol": "http", + "services": ["http://:7010/comp3-endp1"] + }, + "comp3-endp2": { + "protocol": "http", + "services": ["http://:7011/comp3-endp2"] + } + } + }, + "bundleDigest": "6e4560ef252cd57322f595627c881c48b2f8bf98c3b6d08073c0b9b5db1e5068", + "bundleExecutions": [ + { + "endpoints": { + "comp2-endp1": { + "bindPort": 6000, + "hostPort": 6000 + }, + "comp2-endp2": { + "bindPort": 6001, + "hostPort": 6001 + }, + "comp3-endp1": { + "bindPort": 7000, + "hostPort": 7000 + }, + "comp3-endp2": { + "bindPort": 7001, + "hostPort": 7001 + } + }, + "host": "172.17.0.4", + "isStarted": true + } + ], + "bundleId": "6e4560ef252cd57322f595627c881c48", + "bundleInstallations": [ + { + "bundleFile": "file:///tmp/6e4560ef252cd57322f595627c881c48b2f8bf98c3b6d08073c0b9b5db1e5068.zip", + "uniqueAddress": { + "address": "akka.tcp://[email protected]:9004", + "uid": -29020887 + } + }, + { + "bundleFile": "file:///tmp/6e4560ef252cd57322f595627c881c48b2f8bf98c3b6d08073c0b9b5db1e5068.zip", + "uniqueAddress": { + "address": "akka.tcp://[email protected]:9004", + "uid": 247035768 + } + } + ] + } +] diff --git a/conductr_cli/test/test_conduct_services.py b/conductr_cli/test/test_conduct_services.py index 8fc4fc8..590794e 100644 --- a/conductr_cli/test/test_conduct_services.py +++ b/conductr_cli/test/test_conduct_services.py @@ -52,6 +52,27 @@ class TestConductServicesCommand(TestCase, CliTestCase): |"""), self.output(stdout)) + def test_two_bundles_mult_components_endpoints_no_path(self): + http_method = self.respond_with_file_contents('data/two_bundles_no_path.json') + stdout = MagicMock() + + with patch('requests.get', http_method), patch('sys.stdout', stdout): + conduct_services.services(MagicMock(**self.default_args)) + + http_method.assert_called_with(self.default_url) + self.assertEqual( + strip_margin("""|SERVICE BUNDLE ID BUNDLE NAME STATUS + |http://:6011 6e4560e multi2-comp-multi-endp-1.0.0 Running + |http://:7010/comp3-endp1 6e4560e multi2-comp-multi-endp-1.0.0 Running + |http://:7011/comp3-endp2 6e4560e multi2-comp-multi-endp-1.0.0 Running + |http://:8010/comp1-endp1 f804d64 multi-comp-multi-endp-1.0.0 Running + |http://:8011/comp1-endp2 f804d64 multi-comp-multi-endp-1.0.0 Running + |http://:9010/comp2-endp1 f804d64 multi-comp-multi-endp-1.0.0 Running + |http://:9010/comp2-endp1 6e4560e multi2-comp-multi-endp-1.0.0 Running + |http://:9011 f804d64 multi-comp-multi-endp-1.0.0 Running + |"""), + self.output(stdout)) + def test_one_bundle_starting(self): http_method = self.respond_with_file_contents('data/one_bundle_starting.json') stdout = MagicMock()
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
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": [ "requests>=2.3.0", "argcomplete>=0.8.1", "pyhocon==0.2.1", "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@e6196516227db9bb9b2027e1d2aa1bd8cb082337#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_services.py::TestConductServicesCommand::test_two_bundles_mult_components_endpoints_no_path" ]
[]
[ "conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_no_bundles", "conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_one_bundle_starting", "conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_one_bundle_starting_long_ids", "conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_two_bundles_mult_components_endpoints" ]
[]
Apache License 2.0
100
[ "conductr_cli/conduct_services.py" ]
[ "conductr_cli/conduct_services.py" ]
mkdocs__mkdocs-464
852996e7e1e17e83ac650a5c5be6834323cca94e
2015-04-18 10:10:36
463c5b647e9ce5992b519708a0b9c4cba891d65c
diff --git a/mkdocs/nav.py b/mkdocs/nav.py index 5a215b28..ee7d6b34 100644 --- a/mkdocs/nav.py +++ b/mkdocs/nav.py @@ -224,6 +224,13 @@ def _generate_site_navigation(pages_config, url_context, use_directory_urls=True filename = path.split(os.path.sep)[0] title = filename_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) + url = utils.get_url_path(path, use_directory_urls) if not child_title:
Regression when building docs I got this when building the Django REST Framework docs with 0.12.1 $ mkdocs build Building documentation to directory: site Directory site contains stale files. Use --clean to remove them. Traceback (most recent call last): File "/home/dougalmatthews/.virtualenvs/mkdocs/bin/mkdocs", line 9, in <module> load_entry_point('mkdocs==0.12.1', 'console_scripts', 'mkdocs')() File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/main.py", line 77, in run_main main(cmd, args=sys.argv[2:], options=dict(opts)) File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/main.py", line 52, in main build(config, clean_site_dir=clean_site_dir) File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/build.py", line 252, in build build_pages(config) File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/build.py", line 209, in build_pages site_navigation = nav.SiteNavigation(config['pages'], config['use_directory_urls']) File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/nav.py", line 37, in __init__ _generate_site_navigation(pages_config, self.url_context, use_directory_urls) File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/nav.py", line 243, in _generate_site_navigation header.children.append(page) AttributeError: 'Page' object has no attribute 'children'
mkdocs/mkdocs
diff --git a/mkdocs/tests/nav_tests.py b/mkdocs/tests/nav_tests.py index 4e8531cd..cdd2bf9f 100644 --- a/mkdocs/tests/nav_tests.py +++ b/mkdocs/tests/nav_tests.py @@ -63,6 +63,30 @@ class SiteNavigationTests(unittest.TestCase): self.assertEqual(len(site_navigation.nav_items), 3) self.assertEqual(len(site_navigation.pages), 6) + def test_indented_toc_missing_child_title(self): + pages = [ + ('index.md', 'Home'), + ('api-guide/running.md', 'API Guide', 'Running'), + ('api-guide/testing.md', 'API Guide'), + ('api-guide/debugging.md', 'API Guide', 'Debugging'), + ('about/release-notes.md', 'About', 'Release notes'), + ('about/license.md', 'About', 'License') + ] + expected = dedent(""" + Home - / + API Guide + Running - /api-guide/running/ + Testing - /api-guide/testing/ + Debugging - /api-guide/debugging/ + About + Release notes - /about/release-notes/ + License - /about/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), 6) + def test_nested_ungrouped(self): pages = [ ('index.md', 'Home'),
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 1 }
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", "click" ], "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" }
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@852996e7e1e17e83ac650a5c5be6834323cca94e#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_indented_toc_missing_child_title" ]
[]
[ "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_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
101
[ "mkdocs/nav.py" ]
[ "mkdocs/nav.py" ]
mahmoud__boltons-31
c9b3d2452e4ffe43920874f4f6f2e8fe425ebf00
2015-04-19 07:14:14
c9b3d2452e4ffe43920874f4f6f2e8fe425ebf00
asottile: I guess I'll fix tbutils to work under python3? Kinda unfortunate for the build to fail because I added tests :( (when it wouldn't have worked before then!)
diff --git a/.travis.yml b/.travis.yml index 9f97722..0df3b47 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,4 +6,4 @@ python: - "pypy" install: "pip install -r requirements-test.txt" -script: "py.test --doctest-modules boltons" +script: "py.test --doctest-modules boltons tests" diff --git a/boltons/tbutils.py b/boltons/tbutils.py index 2ff476d..6f402e9 100644 --- a/boltons/tbutils.py +++ b/boltons/tbutils.py @@ -27,6 +27,12 @@ import sys import linecache +if str is bytes: # py2 + text = unicode +else: # py3 + text = str + + # TODO: chaining primitives? what are real use cases where these help? # TODO: print_* for backwards compatability @@ -691,7 +697,7 @@ class ParsedException(object): Args: tb_str (str): The traceback text (:class:`unicode` or UTF-8 bytes) """ - if not isinstance(tb_str, unicode): + if not isinstance(tb_str, text): tb_str = tb_str.decode('utf-8') tb_lines = tb_str.lstrip().splitlines() @@ -717,21 +723,35 @@ class ParsedException(object): raise ValueError('unrecognized traceback string format') frames = [] - for pair_idx in range(start_line, len(tb_lines), 2): - frame_line = tb_lines[pair_idx].strip() + line_no = start_line + while True: + frame_line = tb_lines[line_no].strip() frame_match = frame_re.match(frame_line) if frame_match: frame_dict = frame_match.groupdict() + next_line = tb_lines[line_no + 1] + next_line_stripped = next_line.strip() + if ( + frame_re.match(next_line_stripped) or + # The exception message will not be indented + # This check is to avoid overrunning on eval-like + # tracebacks where the last frame doesn't have source + # code in the traceback + not next_line.startswith(' ') + ): + frame_dict['source_line'] = '' + else: + frame_dict['source_line'] = next_line_stripped + line_no += 1 else: break - frame_dict['source_line'] = tb_lines[pair_idx + 1].strip() + line_no += 1 frames.append(frame_dict) - exc_line_offset = start_line + len(frames) * 2 try: - exc_line = tb_lines[exc_line_offset] + exc_line = tb_lines[line_no] exc_type, _, exc_msg = exc_line.partition(':') - except: + except Exception: exc_type, exc_msg = '', '' return cls(exc_type, exc_msg, frames) diff --git a/tox.ini b/tox.ini index 928a1dc..e99092f 100644 --- a/tox.ini +++ b/tox.ini @@ -2,4 +2,4 @@ envlist = py27,py34,pypy [testenv] deps = -rrequirements-test.txt -commands = py.test --doctest-modules boltons +commands = py.test --doctest-modules boltons tests
ParsedException.from_string produces wrong result when a frame is missing source (such as from eval) Take this (modified from the original) trace: ``` Traceback (most recent call last): File "<string>", line 2, in _some_function File "myfile.py", line 3, in some_other_function return foo(bar, baz) MyException: ExceptionValue ``` ParsedException gives me an incorrect result: ``` >>> ParsedException.from_string(x) ParsedException(u' return foo(bar, baz)', u'', frames=[{'source_line': u'File "myfile.py", line 3, in some_other_function', 'filepath': u'<string>', 'lineno': u'2', 'funcname': u'_some_function'}]) ```
mahmoud/boltons
diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/tbutils_test.py b/tests/tbutils_test.py new file mode 100644 index 0000000..64eb17a --- /dev/null +++ b/tests/tbutils_test.py @@ -0,0 +1,54 @@ +from __future__ import absolute_import +from __future__ import unicode_literals + +from boltons.tbutils import ParsedException + + +def test_normal_tb(): + tb = '''\ +Traceback (most recent call last): + File "<string>", line 2, in _some_function + return some_other_function(1) + File "myfile.py", line 3, in some_other_function + return foo(bar, baz) +MyException: ExceptionValue +''' + parsed = ParsedException.from_string(tb) + assert parsed.exc_type == 'MyException' + assert parsed.exc_msg == ' ExceptionValue' + assert parsed.frames == [ + { + 'source_line': 'return some_other_function(1)', + 'filepath': '<string>', + 'lineno': '2', + 'funcname': '_some_function' + }, + { + 'source_line': 'return foo(bar, baz)', + 'filepath': 'myfile.py', + 'lineno': '3', + 'funcname': 'some_other_function', + } + ] + + +def test_eval_tb(): + tb = '''\ +Traceback (most recent call last): + File "<string>", line 2, in _some_function + File "myfile.py", line 3, in some_other_function + return foo(bar, baz) +MyException: ExceptionValue +''' + parsed = ParsedException.from_string(tb) + assert parsed.exc_type == 'MyException' + + +def test_last_line_is_eval_like(): + tb = '''\ +Traceback (most recent call last): + File "<string>", line 2, in _some_function +MyException: ExceptionValue +''' + parsed = ParsedException.from_string(tb) + assert parsed.exc_type == 'MyException'
{ "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": 1 }, "num_modified_files": 3 }
0.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": [ "py", "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 -e git+https://github.com/mahmoud/boltons.git@c9b3d2452e4ffe43920874f4f6f2e8fe425ebf00#egg=boltons 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 zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
name: boltons 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/boltons
[ "tests/tbutils_test.py::test_normal_tb", "tests/tbutils_test.py::test_eval_tb", "tests/tbutils_test.py::test_last_line_is_eval_like" ]
[]
[]
[]
BSD License
102
[ "boltons/tbutils.py", ".travis.yml", "tox.ini" ]
[ "boltons/tbutils.py", ".travis.yml", "tox.ini" ]
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
[ "webob/response.py" ]
[ "webob/response.py" ]
joblib__joblib-204
21cb6f3fd32b11a9b6bc1528b86bbf83fce7bb1f
2015-04-23 08:08:27
21cb6f3fd32b11a9b6bc1528b86bbf83fce7bb1f
lesteve: Forgot to say, but I checked that this fix didn't affect the hash of non datetime-like numpy arrays. ogrisel: Other than my comment, LGTM.
diff --git a/joblib/hashing.py b/joblib/hashing.py index 564817c..d3d783a 100644 --- a/joblib/hashing.py +++ b/joblib/hashing.py @@ -154,14 +154,21 @@ class NumpyHasher(Hasher): if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject: # Compute a hash of the object: try: - self._hash.update(self._getbuffer(obj)) + # memoryview is not supported for some dtypes, + # e.g. datetime64, see + # https://github.com/numpy/numpy/issues/4983. The + # workaround is to view the array as bytes before + # taking the memoryview + obj_bytes_view = obj.view(self.np.uint8) + self._hash.update(self._getbuffer(obj_bytes_view)) except (TypeError, BufferError, ValueError): # Cater for non-single-segment arrays: this creates a # copy, and thus aleviates this issue. # XXX: There might be a more efficient way of doing this # Python 3.2's memoryview raise a ValueError instead of a # TypeError or a BufferError - self._hash.update(self._getbuffer(obj.flatten())) + obj_bytes_view = obj.flatten().view(self.np.uint8) + self._hash.update(self._getbuffer(obj_bytes_view)) # We store the class, to be able to distinguish between # Objects with the same binary content, but different
Cannot hash datetime64 ``` In [59]: joblib.hashing.hash(numpy.zeros(dtype="<m8[s]", shape=(10,))) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-59-8b9b8a0f034d> in <module>() ----> 1 joblib.hashing.hash(numpy.zeros(dtype="<m8[s]", shape=(10,))) /export/data/home/gholl/venv/bleeding/lib/python3.4/site-packages/joblib/hashing.py in hash(obj, hash_name, coerce_mmap) 199 else: 200 hasher = Hasher(hash_name=hash_name) --> 201 return hasher.hash(obj) /export/data/home/gholl/venv/bleeding/lib/python3.4/site-packages/joblib/hashing.py in hash(self, obj, return_digest) 51 def hash(self, obj, return_digest=True): 52 try: ---> 53 self.dump(obj) 54 except pickle.PicklingError as e: 55 warnings.warn('PicklingError while hashing %r: %r' % (obj, e)) /usr/lib64/python3.4/pickle.py in dump(self, obj) 408 if self.proto >= 4: 409 self.framer.start_framing() --> 410 self.save(obj) 411 self.write(STOP) 412 self.framer.end_framing() /export/data/home/gholl/venv/bleeding/lib/python3.4/site-packages/joblib/hashing.py in save(self, obj) 162 # Python 3.2's memoryview raise a ValueError instead of a 163 # TypeError or a BufferError --> 164 self._hash.update(self._getbuffer(obj.flatten())) 165 166 # We store the class, to be able to distinguish between ValueError: cannot include dtype 'm' in a buffer ```
joblib/joblib
diff --git a/joblib/test/test_hashing.py b/joblib/test/test_hashing.py index 15a5da9..a1f52b1 100644 --- a/joblib/test/test_hashing.py +++ b/joblib/test/test_hashing.py @@ -133,6 +133,18 @@ def test_hash_numpy(): yield nose.tools.assert_not_equal, hash(arr1), hash(arr1.T) +@with_numpy +def test_numpy_datetime_array(): + # memoryview is not supported for some dtypes e.g. datetime64 + # see https://github.com/joblib/joblib/issues/188 for more details + dtypes = ['datetime64[s]', 'timedelta64[D]'] + + a_hash = hash(np.arange(10)) + arrays = (np.arange(0, 10, dtype=dtype) for dtype in dtypes) + for array in arrays: + nose.tools.assert_not_equal(hash(array), a_hash) + + @with_numpy def test_hash_numpy_noncontiguous(): a = np.asarray(np.arange(6000).reshape((1000, 2, 3)),
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 2 }, "num_modified_files": 1 }
0.8
{ "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@21cb6f3fd32b11a9b6bc1528b86bbf83fce7bb1f#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_numpy_datetime_array" ]
[]
[ "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_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" ]
[]
BSD 3-Clause "New" or "Revised" License
104
[ "joblib/hashing.py" ]
[ "joblib/hashing.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
[ "SoftLayer/CLI/environment.py", "SoftLayer/CLI/formatting.py", "SoftLayer/config.py", "SoftLayer/CLI/config/setup.py", "SoftLayer/CLI/core.py" ]
[ "SoftLayer/CLI/environment.py", "SoftLayer/CLI/formatting.py", "SoftLayer/config.py", "SoftLayer/CLI/config/setup.py", "SoftLayer/CLI/core.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
[ "mne/report.py" ]
[ "mne/report.py" ]
pysmt__pysmt-83
18c4ecb85ed6e799ec4947dcb5a072a21fdf7303
2015-04-25 15:40:24
18c4ecb85ed6e799ec4947dcb5a072a21fdf7303
diff --git a/pysmt/native_nodes/__init__.py b/pysmt/native_nodes/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/pysmt/native_nodes/__init__.py @@ -0,0 +1,1 @@ + diff --git a/pysmt/solvers/eager.py b/pysmt/solvers/eager.py index da3fbc7..9f43040 100644 --- a/pysmt/solvers/eager.py +++ b/pysmt/solvers/eager.py @@ -16,7 +16,7 @@ # limitations under the License. # from pysmt.solvers.solver import Model -from pysmt.shortcuts import get_env, Real, Bool, Int +from pysmt.shortcuts import get_env from pysmt.typing import REAL, BOOL, INT class EagerModel(Model): @@ -34,37 +34,54 @@ class EagerModel(Model): Model.__init__(self, environment) self.environment = environment self.assignment = assignment + # Create a copy of the assignments to memoize completions + self.completed_assignment = dict(self.assignment) + + def get_value(self, formula, model_completion=True): + if model_completion: + syms = formula.get_free_variables() + self._complete_model(syms) + r = formula.substitute(self.completed_assignment) + else: + r = formula.substitute(self.assignment) - def get_value(self, formula): - r = formula.substitute(self.assignment) res = r.simplify() if not res.is_constant(): raise TypeError("Was expecting a constant but got %s" % res) return res - def complete_model(self, symbols): - undefined_symbols = (s for s in symbols if s not in self.assignment) + + def _complete_model(self, symbols): + undefined_symbols = (s for s in symbols + if s not in self.completed_assignment) + mgr = self.environment.formula_manager for s in undefined_symbols: if not s.is_symbol(): raise TypeError("Was expecting a symbol but got %s" %s) - if s.is_symbol(BOOL): - value = Bool(False) - elif s.is_symbol(REAL): - value = Real(0) - elif s.is_symbol(INT): - value = Int(0) + if s.symbol_type().is_bool_type(): + value = mgr.Bool(False) + elif s.symbol_type().is_real_type(): + value = mgr.Real(0) + elif s.symbol_type().is_int_type(): + value = mgr.Int(0) + elif s.symbol_type().is_bv_type(): + value = mgr.BVZero(s.bv_width()) else: raise TypeError("Unhandled type for %s: %s" % (s, s.symbol_type())) - self.assignment[s] = value + self.completed_assignment[s] = value + + + def iterator_over(self, language): + for x in language: + yield x, self.get_value(x, model_completion=True) def __iter__(self): """Overloading of iterator from Model. We iterate only on the - variables defined in the assignment. Call complete_model to - include more variables. + variables defined in the assignment. """ return iter(self.assignment.items()) diff --git a/pysmt/solvers/msat.py b/pysmt/solvers/msat.py index 5770a86..da38c0a 100644 --- a/pysmt/solvers/msat.py +++ b/pysmt/solvers/msat.py @@ -288,10 +288,16 @@ class MathSAT5Solver(IncrementalTrackingSolver, UnsatCoreSolver, def get_model(self): assignment = {} - for s in self.environment.formula_manager.get_all_symbols(): - if s.is_term(): - v = self.get_value(s) - assignment[s] = v + msat_iterator = mathsat.msat_create_model_iterator(self.msat_env) + while mathsat.msat_model_iterator_has_next(msat_iterator): + term, value = mathsat.msat_model_iterator_next(msat_iterator) + pysmt_term = self.converter.back(term) + pysmt_value = self.converter.back(value) + if self.environment.stc.get_type(pysmt_term).is_real_type() and \ + pysmt_value.is_int_constant(): + pysmt_value = self.mgr.Real(pysmt_value.constant_value()) + assignment[pysmt_term] = pysmt_value + mathsat.msat_destroy_model_iterator(msat_iterator) return EagerModel(assignment=assignment, environment=self.environment) diff --git a/pysmt/solvers/solver.py b/pysmt/solvers/solver.py index 3ac613e..f0cf4a0 100644 --- a/pysmt/solvers/solver.py +++ b/pysmt/solvers/solver.py @@ -369,43 +369,46 @@ class Model(object): self.environment = environment self._converter = None - def get_value(self, formula): + def get_value(self, formula, model_completion=True): """ Returns the value of formula in the current model (if one exists). + If model_completion is True, then variables not appearing in the + assignment are given a default value, otherwise an error is generated. + This is a simplified version of the SMT-LIB funtion get_values . """ raise NotImplementedError - def get_values(self, formulae): + def get_values(self, formulae, model_completion=True): """Evaluates the values of the formulae in the current model returning a dictionary. """ res = {} for f in formulae: - v = self.get_value(f) + v = self.get_value(f, model_completion=model_completion) res[f] = v return res - def get_py_value(self, formula): + def get_py_value(self, formula, model_completion=True): """ Returns the value of formula as a python type. E.g., Bool(True) is translated into True. This simplifies writing code that branches on values in the model. """ - res = self.get_value(formula) + res = self.get_value(formula, model_completion=model_completion) assert res.is_constant() return res.constant_value() - def get_py_values(self, formulae): + def get_py_values(self, formulae, model_completion=True): """Evaluates the values of the formulae as python types in the current model returning a dictionary. """ res = {} for f in formulae: - v = self.get_py_value(f) + v = self.get_py_value(f, model_completion=model_completion) res[f] = v return res @@ -419,12 +422,7 @@ class Model(object): self._converter = value def __getitem__(self, idx): - return self.get_value(idx) - - - def __iter__(self): - for var in self.environment.formula_manager.get_all_symbols(): - yield var, self.get_value(var) + return self.get_value(idx, model_completion=True) def __str__(self): return "\n".join([ "%s := %s" % (var, value) for (var, value) in self]) diff --git a/pysmt/solvers/z3.py b/pysmt/solvers/z3.py index ec11e8b..8800911 100644 --- a/pysmt/solvers/z3.py +++ b/pysmt/solvers/z3.py @@ -64,11 +64,29 @@ class Z3Model(Model): self.z3_model = z3_model self.converter = Z3Converter(environment) - def get_value(self, formula): + def get_value(self, formula, model_completion=True): titem = self.converter.convert(formula) - z3_res = self.z3_model.eval(titem, model_completion=True) + z3_res = self.z3_model.eval(titem, model_completion=model_completion) return self.converter.back(z3_res) + def iterator_over(self, language): + for x in language: + yield x, self.get_value(x, model_completion=True) + + def __iter__(self): + """Overloading of iterator from Model. We iterate only on the + variables defined in the assignment. + """ + for d in self.z3_model.decls(): + pysmt_d = self.converter.back(d) + yield pysmt_d, self.get_value(pysmt_d) + + def __contains__(self, x): + """Returns whether the model contains a value for 'x'.""" + z3_x = self.converter.convert(x) + return z3_x in self.z3_model.decls() + + class Z3Solver(IncrementalTrackingSolver, UnsatCoreSolver, SmtLibBasicSolver, SmtLibIgnoreMixin):
Solver.get_model should not try to assign a value to each variable in the environment Implementation of get_model in the solvers using EagerModel, extracts one value for each symbol defined in the environment. This has a few problems: 1. In same cases we are doing much more work than needed 2. We cannot extract "partial models" 3. Symbols of type not supported by the solver (e.g., BV) will cause the solver to fail in the model creation. Ideally, we should use iteration functions from the native solver API to extract models (if these are available).
pysmt/pysmt
diff --git a/pysmt/test/test_eager_model.py b/pysmt/test/test_eager_model.py index aed7433..610908a 100644 --- a/pysmt/test/test_eager_model.py +++ b/pysmt/test/test_eager_model.py @@ -54,7 +54,7 @@ class TestEagerModel(TestCase): model = EagerModel(assignment=d) with self.assertRaises(TypeError): - model.get_value(And(x,y)) + model.get_value(And(x,y), model_completion=False) d2 = {x:TRUE(), y:x} model = EagerModel(assignment=d2) @@ -69,13 +69,21 @@ class TestEagerModel(TestCase): d = {x:TRUE()} model = EagerModel(assignment=d) - model.complete_model([x,y,r,p]) self.assertEqual(model.get_value(x), TRUE()) self.assertEqual(model.get_value(Or(x,y)), TRUE()) self.assertTrue(model.get_value(p).is_constant(INT)) self.assertTrue(model.get_value(r).is_constant(REAL)) + self.assertEqual(model.get_value(x, model_completion=False), TRUE()) + with self.assertRaises(TypeError): + model.get_value(And(x,y), model_completion=False) + with self.assertRaises(TypeError): + model.get_value(p, model_completion=False) + with self.assertRaises(TypeError): + model.get_value(r, model_completion=False) + + def test_contains(self): x, y, z = [FreshSymbol() for _ in xrange(3)] d = {x: TRUE(), y: FALSE()} diff --git a/pysmt/test/test_regressions.py b/pysmt/test/test_regressions.py index 2ce5a75..ce69638 100644 --- a/pysmt/test/test_regressions.py +++ b/pysmt/test/test_regressions.py @@ -180,6 +180,19 @@ class TestRegressions(TestCase): # The modulus operator must be there self.assertIn("%2", str(ex.expression)) + @skipIfSolverNotAvailable("msat") + def test_msat_partial_model(self): + msat = Solver(name="msat") + x, y = Symbol("x"), Symbol("y") + msat.add_assertion(x) + c = msat.solve() + self.assertTrue(c) + + model = msat.get_model() + self.assertNotIn(y, model) + self.assertIn(x, model) + msat.exit() + if __name__ == "__main__": import unittest
{ "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": 2, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 4 }
0.2
{ "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", "nose-cov", "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" }
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@18c4ecb85ed6e799ec4947dcb5a072a21fdf7303#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: - 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 - six==1.17.0 - tomli==2.2.1 prefix: /opt/conda/envs/pysmt
[ "pysmt/test/test_eager_model.py::TestEagerModel::test_complete_model" ]
[]
[ "pysmt/test/test_eager_model.py::TestEagerModel::test_construction", "pysmt/test/test_eager_model.py::TestEagerModel::test_contains", "pysmt/test/test_eager_model.py::TestEagerModel::test_env_default_arguments", "pysmt/test/test_eager_model.py::TestEagerModel::test_result_is_const", "pysmt/test/test_regressions.py::TestRegressions::test_dependencies_not_includes_toreal", "pysmt/test/test_regressions.py::TestRegressions::test_infix_notation_wrong_le", "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_simplifying_int_plus_changes_type_of_expression", "pysmt/test/test_regressions.py::TestRegressions::test_substitute_memoization" ]
[]
Apache License 2.0
108
[ "pysmt/solvers/z3.py", "pysmt/solvers/eager.py", "pysmt/solvers/msat.py", "pysmt/native_nodes/__init__.py", "pysmt/solvers/solver.py" ]
[ "pysmt/solvers/z3.py", "pysmt/solvers/eager.py", "pysmt/solvers/msat.py", "pysmt/native_nodes/__init__.py", "pysmt/solvers/solver.py" ]
albertyw__itolapi-11
18ab55c5526ef6c8f3285af9363fb8e0e22f2bf1
2015-04-26 05:13:26
18ab55c5526ef6c8f3285af9363fb8e0e22f2bf1
diff --git a/examples/example.py b/examples/example.py index e879042..cac8202 100644 --- a/examples/example.py +++ b/examples/example.py @@ -13,9 +13,9 @@ sys.path.append(parent_path) from itolapi import Itol, ItolExport -print 'Running example itol and itolexport script' -print '' -print 'Creating the upload params' +print('Running example itol and itolexport script') +print('') +print('Creating the upload params') #Create the Itol class test = Itol.Itol() @@ -33,24 +33,24 @@ test.add_variable('dataset1Type','multibar') # Check parameters test.print_variables() #Submit the tree -print '' -print 'Uploading the tree. This may take some time depending on how large the tree is and how much load there is on the itol server' +print('') +print('Uploading the tree. This may take some time depending on how large the tree is and how much load there is on the itol server') good_upload = test.upload() if good_upload == False: - print 'There was an error:'+test.comm.upload_output + print('There was an error:'+test.comm.upload_output) sys.exit(1) #Read the tree ID -print 'Tree ID: '+str(test.comm.tree_id) +print('Tree ID: '+str(test.comm.tree_id)) #Read the iTOL API return statement -print 'iTOL output: '+str(test.comm.upload_output) +print('iTOL output: '+str(test.comm.upload_output)) #Website to be redirected to iTOL tree -print 'Tree Web Page URL: '+test.get_webpage() +print('Tree Web Page URL: '+test.get_webpage()) # Warnings associated with the upload -print 'Warnings: '+str(test.comm.warnings) +print('Warnings: '+str(test.comm.warnings)) # Export a pre-made tree to pdf @@ -59,13 +59,13 @@ itol_exporter.set_export_param_value('tree','18793532031912684633930') itol_exporter.set_export_param_value('format', 'pdf') itol_exporter.set_export_param_value('datasetList','dataset1') #itol_exporter.export('example_pdf.pdf') -#print 'exported tree to ',export_location +#print('exported tree to ',export_location) # Export the tree above to pdf -print 'Exporting to pdf' +print('Exporting to pdf') itol_exporter = test.get_itol_export() export_location = 'example_pdf.pdf' itol_exporter.set_export_param_value('format', 'pdf') itol_exporter.set_export_param_value('datasetList','dataset1') itol_exporter.export('example_pdf.pdf') -print 'exported tree to ',export_location +print('exported tree to ',export_location) diff --git a/examples/failures/fatal.py b/examples/failures/fatal.py index 59a2ff7..66b3e07 100644 --- a/examples/failures/fatal.py +++ b/examples/failures/fatal.py @@ -34,6 +34,6 @@ itol_o.add_variable('dataset1PieRadiusMin','20') itol_o.add_variable('dataset1BarSizeMax','20') itol_o.print_variables() good_upload = itol_o.upload() -print 'Tree Web Page URL:\n'+itol_o.get_webpage() + '\n' -print 'Warnings:' -print itol_o.comm.warnings +print('Tree Web Page URL:\n'+itol_o.get_webpage() + '\n') +print('Warnings:') +print(itol_o.comm.warnings) diff --git a/examples/failures/warnings.py b/examples/failures/warnings.py index 66a56f0..c38d816 100644 --- a/examples/failures/warnings.py +++ b/examples/failures/warnings.py @@ -34,6 +34,6 @@ itol_o.add_variable('dataset1PieRadiusMin','20') itol_o.add_variable('dataset1BarSizeMax','20') itol_o.print_variables() good_upload = itol_o.upload() -print 'Tree Web Page URL:\n'+itol_o.get_webpage() + '\n' -print 'Warnings:' -print itol_o.comm.warnings +print('Tree Web Page URL:\n'+itol_o.get_webpage() + '\n') +print('Warnings:') +print(itol_o.comm.warnings) diff --git a/itolapi/Comm.py b/itolapi/Comm.py index 6afe3c1..ab10513 100644 --- a/itolapi/Comm.py +++ b/itolapi/Comm.py @@ -2,6 +2,8 @@ This file is for communication between this API and iTOL servers This also processes and stores information returned from the server """ +from __future__ import unicode_literals + import requests @@ -29,7 +31,7 @@ class Comm: new_params = {} files = {} for k,v in params.items(): - if isinstance(v, file): + if hasattr(v, 'read'): files[k] = v else: new_params[k] = v diff --git a/itolapi/Itol.py b/itolapi/Itol.py index e771ce8..216c930 100644 --- a/itolapi/Itol.py +++ b/itolapi/Itol.py @@ -1,12 +1,20 @@ """ This is the main file for the iTOL API """ +from __future__ import unicode_literals + import argparse import sys import os from itolapi import Comm, ItolExport + +try: + basestring +except NameError: + basestring = str + class Itol: """ This class handles the main itol functionality @@ -18,7 +26,6 @@ class Itol: self.variables = dict() self.comm = Comm.Comm() - def add_variable(self, variable_name, variable_value): """ Add a variable and its value to this upload. This function includes @@ -26,9 +33,9 @@ class Itol: modifying the variables dictionary """ # Variable checking - if not isinstance(variable_name, str): + if not isinstance(variable_name, basestring): raise TypeError('variable name is not a string') - if not isinstance(variable_value, str): + if not isinstance(variable_value, basestring): raise TypeError('variable value should be a string') if self.is_file(variable_name): if not os.path.isfile(variable_value): @@ -67,7 +74,7 @@ class Itol: Get the web page where you can download the Itol tree """ webpage = "http://itol.embl.de/external.cgi?tree="+\ - str(self.comm.tree_id)+"&restore_saved=1" + bytes(self.comm.tree_id)+"&restore_saved=1" return webpage def get_itol_export(self): @@ -85,15 +92,15 @@ class Itol: """ for variable_name, variable_value in self.variables.items(): if isinstance(variable_value, file): - print variable_name+': '+variable_value.name + print(variable_name+': '+variable_value.name) else: - print variable_name+': '+variable_value + print(variable_name+': '+variable_value) def delete_variable(self, variable_name): """ Remove a variable from the dictionary of set variables """ - if self.variables.has_key(variable_name): + if variable_name in self.variables: del self.variables[variable_name] @@ -107,4 +114,4 @@ if __name__ == "__main__": itol_upload = Itol() itol_upload.add_variable('treeFile', tree_file) itol_upload.upload() - print itol_upload.get_webpage() + print(itol_upload.get_webpage()) diff --git a/itolapi/ItolExport.py b/itolapi/ItolExport.py index c98c23c..e44422b 100644 --- a/itolapi/ItolExport.py +++ b/itolapi/ItolExport.py @@ -1,6 +1,8 @@ """ This is the main file for exporting of trees created by iTOL """ +from __future__ import unicode_literals + import argparse import sys @@ -72,7 +74,7 @@ if __name__ == "__main__": itol_exporter.set_export_param_value('datasetList', \ 'dataset1,dataset2,dataset3,dataset4,dataset5,\ dataset6,dataset7,dataset8,dataset9,dataset10') - print 'Exporting tree from server....' + print('Exporting tree from server....') itol_exporter.export(args.file_location) - print 'Exported to ', args.file_location + print('Exported to ', args.file_location) sys.exit(0) diff --git a/setup.py b/setup.py index 6071357..8531d3e 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,8 @@ setup(name='itolapi', scripts=['itolapi/Itol.py', 'itolapi/ItolExport.py'], test_suite="tests", tests_require=[ - 'mock>=1.0.1' + 'mock>=1.0.1', + 'tox', ], classifiers=[ 'Development Status :: 5 - Production/Stable', @@ -30,7 +31,10 @@ setup(name='itolapi', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', - 'Programming Language :: Python :: 2 :: Only', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', 'Topic :: Scientific/Engineering :: Bio-Informatics', ], ) diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..99d2280 --- /dev/null +++ b/tox.ini @@ -0,0 +1,12 @@ +# Tox (http://tox.testrun.org/) is a tool for running tests +# in multiple virtualenvs. This configuration file will run the +# test suite on all supported python versions. To use it, "pip install tox" +# and then run "tox" from this directory. + +[tox] +envlist = py27, py34 + +[testenv] +commands = {envpython} setup.py test +deps = + mock
Support Python 3
albertyw/itolapi
diff --git a/tests/comm.py b/tests/comm.py index 3096f64..b4f5e65 100644 --- a/tests/comm.py +++ b/tests/comm.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals from mock import MagicMock, patch import tempfile import unittest @@ -6,10 +7,16 @@ from itolapi import Comm class PullOutFilesTest(unittest.TestCase): + def setUp(self): + self.tempfile = tempfile.TemporaryFile() + + def tearDown(self): + self.tempfile.close() + def test_pull_out_files(self): params = {} params['asdf'] = 'qwer' - params['zxcv'] = tempfile.TemporaryFile() + params['zxcv'] = self.tempfile new_params, files = Comm.Comm.pull_out_files(params) self.assertEqual(new_params, {'asdf': 'qwer'}) self.assertEqual(files, {'zxcv': params['zxcv']}) @@ -17,7 +24,7 @@ class PullOutFilesTest(unittest.TestCase): def test_doesnt_modify_params(self): params = {} params['asdf'] = 'qwer' - params['zxcv'] = tempfile.TemporaryFile() + params['zxcv'] = self.tempfile Comm.Comm.pull_out_files(params) self.assertTrue('asdf' in params) self.assertTrue('zxcv' in params) @@ -25,12 +32,16 @@ class PullOutFilesTest(unittest.TestCase): class UploadTreeTest(unittest.TestCase): def setUp(self): + self.tempfile = tempfile.TemporaryFile() self.comm = Comm.Comm() self.params = {'asdf': 'qwer'} - self.files = {'zxcv': tempfile.TemporaryFile()} + self.files = {'zxcv': self.tempfile} self.all_params = self.params.copy() self.all_params.update(self.files) + def tearDown(self): + self.tempfile.close() + @patch('itolapi.Comm.Comm.pull_out_files') @patch('itolapi.Comm.requests') @patch('itolapi.Comm.Comm.parse_upload') diff --git a/tests/itol.py b/tests/itol.py index f685ddb..6ec2abd 100644 --- a/tests/itol.py +++ b/tests/itol.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals from mock import MagicMock, patch import unittest diff --git a/tests/itolexport.py b/tests/itolexport.py index d1af1d9..ee2d5b0 100644 --- a/tests/itolexport.py +++ b/tests/itolexport.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals from mock import MagicMock, patch import unittest
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 3, "test_score": 0 }, "num_modified_files": 7 }
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-mock", "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" }
certifi==2025.1.31 charset-normalizer==3.4.1 exceptiongroup==1.2.2 idna==3.10 iniconfig==2.1.0 -e git+https://github.com/albertyw/itolapi.git@18ab55c5526ef6c8f3285af9363fb8e0e22f2bf1#egg=itolapi mock==5.2.0 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-mock==3.14.0 requests==2.32.3 tomli==2.2.1 urllib3==2.3.0
name: itolapi 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 - idna==3.10 - iniconfig==2.1.0 - mock==5.2.0 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - pytest-mock==3.14.0 - requests==2.32.3 - tomli==2.2.1 - urllib3==2.3.0 prefix: /opt/conda/envs/itolapi
[ "tests/comm.py::PullOutFilesTest::test_doesnt_modify_params", "tests/comm.py::PullOutFilesTest::test_pull_out_files", "tests/comm.py::UploadTreeTest::test_upload_tree", "tests/comm.py::ParseUploadTest::test_fatal", "tests/comm.py::ParseUploadTest::test_successful", "tests/comm.py::ParseUploadTest::test_successful_warnings", "tests/comm.py::ExportImageTest::test_export_image", "tests/itol.py::ItolTest::test_add_variable", "tests/itol.py::ItolTest::test_bad_upload", "tests/itol.py::ItolTest::test_checks_file_variable", "tests/itol.py::ItolTest::test_checks_variable_name", "tests/itol.py::ItolTest::test_checks_variable_value", "tests/itol.py::ItolTest::test_delete_variables", "tests/itol.py::ItolTest::test_get_itol_export", "tests/itol.py::ItolTest::test_good_upload", "tests/itol.py::ItolTest::test_initializes", "tests/itol.py::ItolTest::test_is_file", "tests/itol.py::ItolTest::test_print_variables", "tests/itolexport.py::ItolTest::test_add_export_param_dict", "tests/itolexport.py::ItolTest::test_export", "tests/itolexport.py::ItolTest::test_get_export_params", "tests/itolexport.py::ItolTest::test_set_export_param_value" ]
[]
[]
[]
MIT License
109
[ "itolapi/Itol.py", "examples/failures/fatal.py", "examples/example.py", "setup.py", "itolapi/Comm.py", "itolapi/ItolExport.py", "examples/failures/warnings.py", "tox.ini" ]
[ "itolapi/Itol.py", "examples/failures/fatal.py", "examples/example.py", "setup.py", "itolapi/Comm.py", "itolapi/ItolExport.py", "examples/failures/warnings.py", "tox.ini" ]
mne-tools__mne-python-2023
acf8364f01f98233613f7574cac7d533c35183bf
2015-04-26 17:46:14
edceb8f38349d6dc0cade1c9f8384cc0707ce3e8
agramfort: Lgtm Merge when Travis is happy Thx for the quick fix
diff --git a/mne/io/brainvision/brainvision.py b/mne/io/brainvision/brainvision.py index 35fd057a2..81b41fa78 100644 --- a/mne/io/brainvision/brainvision.py +++ b/mne/io/brainvision/brainvision.py @@ -396,6 +396,10 @@ def _get_eeg_info(vhdr_fname, eog, misc): info['filename'] = vhdr_fname eeg_info = {} + ext = os.path.splitext(vhdr_fname)[-1] + if ext != '.vhdr': + raise IOError("The header file must be given to read the data, " + "not the '%s' file." % ext) with open(vhdr_fname, 'r') as f: # extract the first section to resemble a cfg l = f.readline().strip()
check extension of brainvision file I mistakenly tried: raw = mne.io.read_raw_brainvision('test.vmrk') instead of raw = mne.io.read_raw_brainvision('test.vhdr') and got this error, which is not super explicit: --> 402 assert l == 'Brain Vision Data Exchange Header File Version 1.0' to help here we should check file extension and use a properly exception (not this assert). @teonlamont can you take care of that? thanks heaps.
mne-tools/mne-python
diff --git a/mne/io/brainvision/tests/test_brainvision.py b/mne/io/brainvision/tests/test_brainvision.py index 44eb09816..5131d978a 100644 --- a/mne/io/brainvision/tests/test_brainvision.py +++ b/mne/io/brainvision/tests/test_brainvision.py @@ -22,6 +22,7 @@ from mne.io import read_raw_brainvision FILE = inspect.getfile(inspect.currentframe()) data_dir = op.join(op.dirname(op.abspath(FILE)), 'data') vhdr_path = op.join(data_dir, 'test.vhdr') +vmrk_path = op.join(data_dir, 'test.vmrk') vhdr_highpass_path = op.join(data_dir, 'test_highpass.vhdr') montage = op.join(data_dir, 'test.hpts') eeg_bin = op.join(data_dir, 'test_bin_raw.fif') @@ -42,6 +43,7 @@ def test_brainvision_data_filters(): def test_brainvision_data(): """Test reading raw Brain Vision files """ + assert_raises(IOError, read_raw_brainvision, vmrk_path) assert_raises(TypeError, read_raw_brainvision, vhdr_path, montage, preload=True, scale="0") raw_py = read_raw_brainvision(vhdr_path, montage, eog=eog, preload=True)
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 2 }, "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@acf8364f01f98233613f7574cac7d533c35183bf#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/io/brainvision/tests/test_brainvision.py::test_brainvision_data" ]
[]
[ "mne/io/brainvision/tests/test_brainvision.py::test_brainvision_data_filters", "mne/io/brainvision/tests/test_brainvision.py::test_events", "mne/io/brainvision/tests/test_brainvision.py::test_read_segment" ]
[]
BSD 3-Clause "New" or "Revised" License
110
[ "mne/io/brainvision/brainvision.py" ]
[ "mne/io/brainvision/brainvision.py" ]
mkdocs__mkdocs-482
1a0dfb5ee3d5dd290da9c8c03b0946e784aa6959
2015-04-27 19:05:31
463c5b647e9ce5992b519708a0b9c4cba891d65c
ci5er: I never personally had a problem with the old way, but this is pretty dang sweet. Thank you. waylan: Wow, that is a great improvement. At a glance, the page structure is immediately obvious from the config. I like it. d0ugal: This is not supported in the MkDocs theme. ![MkDocs theme](https://dl.dropboxusercontent.com/u/14255217/Screenshots/Screenshot%202015-05-01-10.45.37.Google-chrome.png) d0ugal: ![RTD](https://dl.dropboxusercontent.com/u/14255217/Screenshots/Screenshot%202015-05-01-12.31.48.Google-chrome.png)
diff --git a/docs/index.md b/docs/index.md index 047f6a4e..9f9b1367 100644 --- a/docs/index.md +++ b/docs/index.md @@ -105,8 +105,8 @@ We'd like our documentation site to include some navigation headers, so we'll ed site_name: MkLorum pages: - - [index.md, Home] - - [about.md, About] + - Home: index.md + - About: about.md Refresh the browser and you'll now see a navigation bar with `Home` and `About` headers. @@ -116,9 +116,10 @@ While we're here can also change the configuration file to alter how the documen site_name: MkLorum pages: - - [index.md, Home] - - [about.md, About] -``` + - Home: index.md + - About: about.md + theme: readthedocs + Refresh the browser again, and you'll now see the ReadTheDocs theme being used. diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md index c7dff762..abf7c48f 100644 --- a/docs/user-guide/configuration.md +++ b/docs/user-guide/configuration.md @@ -90,22 +90,23 @@ The setting should be a list. Each row in the list represents information about Here's a simple example that would cause the build stage to create three pages: - pages: - - ['index.md', 'Introduction'] - - ['user-guide.md', 'User Guide'] - - ['about.md', 'About'] + - 'Introduction': 'index.md' + - 'User Guide': 'user-guide.md' + - 'Abut': 'about.md' Assuming the `docs_dir` setting was left with the default value of `docs`, the source files for this site's build process would be `docs/index.md`, `docs/user-guide.md` and `docs/about.md`. If you have a lot of project documentation you might choose to use headings to break up your site navigation by category. You can do so by including an extra string in the page configuration for any pages that require a navigation heading, like so: pages: - - ['index.md', 'Introduction'] - - ['user-guide/creating.md', 'User Guide', 'Creating a new Mashmallow project'] - - ['user-guide/api.md', 'User Guide', 'Mashmallow API guide'] - - ['user-guide/configuration.md', 'User Guide', 'Configuring Mashmallow'] - - ['about/license.md', 'About', 'License'] + - Introduction: 'index.md' + - User Guide: + - 'Creating a new Mashmallow project': 'user-guide/creating.md' + - 'Mashmallow API guide': 'user-guide/api.md' + - 'Configuring Mashmallow': 'user-guide/configuration.md' + - About: + - License: 'about/license.md' See also the section on [configuring pages and navigation](/user-guide/writing-your-docs/#configure-pages-and-navigation) for a more detailed breakdown. diff --git a/docs/user-guide/writing-your-docs.md b/docs/user-guide/writing-your-docs.md index 57620dd7..8ba930bf 100644 --- a/docs/user-guide/writing-your-docs.md +++ b/docs/user-guide/writing-your-docs.md @@ -17,19 +17,21 @@ A simple pages configuration looks like this: With this example we will build two pages at the top level and they will automatically have their titles inferred from the filename. To provide a custom name for these pages, they can be added after the filename. pages: - - ['index.md', 'Home'] - - ['about.md', 'About MkDocs'] + - Home: 'index.md' + - About: 'about.md' ### Multilevel documentation To create a second level in the navigation and group topics, the category can be provided before the page title. This is best demonstrated in a documentation project with more pages and is slighlt more complicated. pages: - - ['index.md', 'Home'] - - ['user-guide/writing-your-docs.md', 'User Guide', 'Writing your docs'] - - ['user-guide/styling-your-docs.md', 'User Guide', 'Styling your docs'] - - ['about/license.md', 'About', 'License'] - - ['about/release-notes.md', 'About', 'Release Notes'] + - Home: 'index.md' + - User Guide: + - 'Writing your docs': 'user-guide/writing-your-docs.md' + - 'Styling your docs': 'user-guide/styling-your-docs.md' + - About: + - 'License': 'about/license.md' + - 'Release Notes': 'about/release-notes.md' With the above configuration we have three top level sections Home, User Guide and About. Then under User Guide we have two pages, Writing your docs and Styling your docs. Under the About section we also have two pages, License and Release Notes diff --git a/mkdocs.yml b/mkdocs.yml index 48c2a31f..ad7ce968 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -5,13 +5,17 @@ site_description: Project documentation with Markdown. repo_url: https://github.com/mkdocs/mkdocs/ pages: -- ['index.md', 'Home'] -- ['user-guide/writing-your-docs.md', 'User Guide', 'Writing your docs'] -- ['user-guide/styling-your-docs.md', 'User Guide', 'Styling your docs'] -- ['user-guide/configuration.md', 'User Guide', 'Configuration'] -- ['about/license.md', 'About', 'License'] -- ['about/release-notes.md', 'About', 'Release Notes'] -- ['about/contributing.md', 'About', 'Contributing'] +- Home: index.md +- User Guide: + - Writing Your Docs: user-guide/writing-your-docs.md + - Styling Your Docs: user-guide/styling-your-docs.md + - Configuration: user-guide/configuration.md +- About: + - License: about/license.md + - Release Notes: about/release-notes.md + - Contributing: about/contributing.md + +use_new_pages_structure: true markdown_extensions: toc: diff --git a/mkdocs/config.py b/mkdocs/config.py index 65744fa9..408e3393 100644 --- a/mkdocs/config.py +++ b/mkdocs/config.py @@ -7,7 +7,7 @@ import os from six.moves.urllib.parse import urlparse -from mkdocs import utils +from mkdocs import utils, legacy from mkdocs.exceptions import ConfigurationError log = logging.getLogger(__name__) @@ -68,7 +68,7 @@ DEFAULT_CONFIG = { # enabling strict mode causes MkDocs to stop the build when a problem is # encountered rather than display an error. - 'strict': False + 'strict': False, } @@ -153,11 +153,27 @@ def validate_config(user_config): check for Windows style paths. If they are found, output a warning and continue. """ + + # TODO: Remove in 1.0 + config_types = set(type(l) for l in config['pages']) + if list in config_types and dict not in config_types: + config['pages'] = legacy.pages_compat_shim(config['pages']) + elif list in config_types: + raise ConfigurationError("") + for page_config in config['pages']: + if isinstance(page_config, str): path = page_config + elif isinstance(page_config, dict): + if len(page_config) > 1: + raise ConfigurationError( + "Invalid page config. Should have one key value only") + _, path = next(iter(page_config.items())) elif len(page_config) in (1, 2, 3): path = page_config[0] + else: + raise ConfigurationError("Unrecognised page config") if ntpath.sep in path: log.warning("The config path contains Windows style paths (\\ " diff --git a/mkdocs/legacy.py b/mkdocs/legacy.py new file mode 100644 index 00000000..0ac6d705 --- /dev/null +++ b/mkdocs/legacy.py @@ -0,0 +1,120 @@ +import logging + +from mkdocs.exceptions import ConfigurationError + +log = logging.getLogger(__name__) + + +def pages_compat_shim(original_pages): + """ + Support legacy pages configuration + + Re-write the pages config fron MkDocs <=0.12 to match the + new nested structure added in 0.13. + + Given a pages configuration in the old style of: + + pages: + - ['index.md', 'Home'] + - ['user-guide/writing-your-docs.md', 'User Guide'] + - ['user-guide/styling-your-docs.md', 'User Guide'] + - ['about/license.md', 'About', 'License'] + - ['about/release-notes.md', 'About'] + - ['help/contributing.md', 'Help', 'Contributing'] + - ['support.md'] + - ['cli.md', 'CLI Guide'] + + Rewrite it to look like: + + pages: + - Home: index.md + - User Guide: + - user-guide/writing-your-docs.md + - user-guide/styling-your-docs.md + - About: + - License: about/license.md + - about/release-notes.md + - Help: + - Contributing: about/contributing.md + - support.md + - CLI Guide: cli.md + + TODO: Remove in 1.0 + """ + + log.warning("The pages config in the mkdocs.yml uses the deprecated " + "structure. This will be removed in the next release of " + "MkDocs. See for details on updating: " + "http://www.mkdocs.org/about/release-notes/") + + new_pages = [] + + for config_line in original_pages: + + if len(config_line) not in (1, 2, 3): + msg = ( + "Line in 'page' config contained {0} items. In Line {1}. " + "Expected 1, 2 or 3 strings.".format( + config_line, len(config_line)) + ) + raise ConfigurationError(msg) + + # First we need to pad out the config line as it could contain + # 1-3 items. + path, category, title = (list(config_line) + [None, None])[:3] + + if len(new_pages) > 0: + # Get the previous top-level page so we can see if the category + # matches up with the one we have now. + prev_cat, subpages = next(iter(new_pages[-1].items())) + else: + # We are on the first page + prev_cat, subpages = None, [] + + # If the category is different, add a new top level category. If the + # previous category is None, the it's another top level one too. + if prev_cat is None or prev_cat != category: + subpages = [] + new_pages.append({category: subpages}) + + # Add the current page to the determined category. + subpages.append({title: path}) + + # We need to do a bit of cleaning up to match the new structure. In the + # above example, pages can either be `- file.md` or `- Title: file.md`. + # For pages without a title we currently have `- None: file.md` - so we + # need to remove those Nones by changing from a dict to just a string with + # the path. + for i, category in enumerate(new_pages): + + # Categories are a dictionary with one key as the name and the value + # is a list of pages. So, grab that from the dict. + category, pages = next(iter(category.items())) + + # If we only have one page, then we can assume it is a top level + # category and no further nesting is required unless that single page + # has a title itself, + if len(pages) == 1: + title, path = pages.pop().popitem() + # If we have a title, it should be a sub page + if title is not None: + pages.append({title: path}) + # if we have a category, but no title it should be a top-level page + elif category is not None: + new_pages[i] = {category: path} + # if we have no category or title, it must be a top level page with + # an atomatic title. + else: + new_pages[i] = path + else: + # We have more than one page, so the category is valid. We just + # need to iterate through and convert any {None: path} dicts to + # be just the path string. + for j, page in enumerate(pages): + title, path = page.popitem() + if title: + pages[j] = {title: path} + else: + pages[j] = path + + return new_pages diff --git a/mkdocs/nav.py b/mkdocs/nav.py index 85d33513..8323c149 100644 --- a/mkdocs/nav.py +++ b/mkdocs/nav.py @@ -28,7 +28,8 @@ def file_to_title(filename): try: with open(filename, 'r') as f: lines = f.read() - _, table_of_contents, meta = utils.convert_markdown(lines, ['meta', 'toc']) + _, 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: @@ -53,8 +54,8 @@ class SiteNavigation(object): def __init__(self, pages_config, use_directory_urls=True): self.url_context = URLContext() self.file_context = FileContext() - self.nav_items, self.pages = \ - _generate_site_navigation(pages_config, self.url_context, use_directory_urls) + self.nav_items, self.pages = _generate_site_navigation( + pages_config, self.url_context, use_directory_urls) self.homepage = self.pages[0] if self.pages else None self.use_directory_urls = use_directory_urls @@ -122,7 +123,8 @@ class URLContext(object): return '.' return url.lstrip('/') # Under Python 2.6, relative_path adds an extra '/' at the end. - relative_path = os.path.relpath(url, start=self.base_path).rstrip('/') + suffix + relative_path = os.path.relpath(url, start=self.base_path) + relative_path = relative_path.rstrip('/') + suffix return utils.path_to_url(relative_path) @@ -154,6 +156,7 @@ class FileContext(object): class Page(object): def __init__(self, title, url, path, url_context): + self.title = title self.abs_url = url self.active = False @@ -177,6 +180,10 @@ class Page(object): def is_homepage(self): return utils.is_homepage(self.input_path) + @property + def is_top_level(self): + return len(self.ancestors) == 0 + def __str__(self): return self._indent_print() @@ -196,10 +203,15 @@ class Header(object): def __init__(self, title, children): self.title, self.children = title, children self.active = False + self.ancestors = [] def __str__(self): return self._indent_print() + @property + def is_top_level(self): + return len(self.ancestors) == 0 + def _indent_print(self, depth=0): indent = ' ' * depth active_marker = ' [*]' if self.active else '' @@ -209,74 +221,102 @@ class Header(object): return ret -def _generate_site_navigation(pages_config, url_context, use_directory_urls=True): +def _path_to_page(path, title, url_context, use_directory_urls): + if title is None: + title = file_to_title(path.split(os.path.sep)[-1]) + url = utils.get_url_path(path, use_directory_urls) + return Page(title=title, url=url, path=path, + url_context=url_context) + + +def _follow(config_line, url_context, use_dir_urls, header=None, title=None): + + if isinstance(config_line, str): + path = os.path.normpath(config_line) + page = _path_to_page(path, title, url_context, use_dir_urls) + + if header: + page.ancestors = [header] + header.children.append(page) + + yield page + raise StopIteration + + elif not isinstance(config_line, dict): + msg = ("Line in 'page' config is of type {0}, dict or string " + "expected. Config: {1}").format(type(config_line), config_line) + raise exceptions.ConfigurationError(msg) + + if len(config_line) > 1: + raise exceptions.ConfigurationError( + "Page configs should be in the format 'name: markdown.md'. The " + "config contains an invalid entry: {0}".format(config_line)) + elif len(config_line) == 0: + log.warning("Ignoring empty line in the pages config.") + raise StopIteration + + next_cat_or_title, subpages_or_path = next(iter(config_line.items())) + + if isinstance(subpages_or_path, str): + path = subpages_or_path + for sub in _follow(path, url_context, use_dir_urls, header=header, title=next_cat_or_title): + yield sub + raise StopIteration + + elif not isinstance(subpages_or_path, list): + msg = ("Line in 'page' config is of type {0}, list or string " + "expected for sub pages. Config: {1}" + ).format(type(config_line), config_line) + raise exceptions.ConfigurationError(msg) + + next_header = Header(title=next_cat_or_title, children=[]) + if header: + next_header.ancestors = [header] + header.children.append(next_header) + yield next_header + + subpages = subpages_or_path + + for subpage in subpages: + for sub in _follow(subpage, url_context, use_dir_urls, next_header): + yield sub + + +def _generate_site_navigation(pages_config, url_context, use_dir_urls=True): """ Returns a list of Page and Header instances that represent the top level site navigation. """ nav_items = [] pages = [] + previous = None for config_line in pages_config: - if isinstance(config_line, str): - path = os.path.normpath(config_line) - title, child_title = None, None - elif len(config_line) in (1, 2, 3): - # Pad any items that don't exist with 'None' - padded_config = (list(config_line) + [None, None])[:3] - path, title, child_title = padded_config - path = os.path.normpath(path) - else: - msg = ( - "Line in 'page' config contained %d items. " - "Expected 1, 2 or 3 strings." % len(config_line) - ) - 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 = file_to_title(filename) - - if title is None: - filename = path.split(os.path.sep)[0] - 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 = file_to_title(filename) - - url = utils.get_url_path(path, use_directory_urls) - - if not child_title: - # New top level page. - page = Page(title=title, url=url, path=path, url_context=url_context) - nav_items.append(page) - elif not nav_items or (nav_items[-1].title != title): - # New second level page. - page = Page(title=child_title, url=url, path=path, url_context=url_context) - header = Header(title=title, children=[page]) - nav_items.append(header) - page.ancestors = [header] - else: - # Additional second level page. - page = Page(title=child_title, url=url, path=path, url_context=url_context) - header = nav_items[-1] - header.children.append(page) - page.ancestors = [header] - # Add in previous and next information. - if previous: - page.previous_page = previous - previous.next_page = page - previous = page + for page_or_header in _follow( + config_line, url_context, use_dir_urls): + + if isinstance(page_or_header, Header): + + if page_or_header.is_top_level: + nav_items.append(page_or_header) + + elif isinstance(page_or_header, Page): + + if page_or_header.is_top_level: + nav_items.append(page_or_header) + + pages.append(page_or_header) + + if previous: + page_or_header.previous_page = previous + previous.next_page = page_or_header + previous = page_or_header - pages.append(page) + if len(pages) == 0: + raise exceptions.ConfigurationError( + "No pages found in the pages config. " + "Remove it entirely to enable automatic page discovery.") return (nav_items, pages) diff --git a/mkdocs/themes/mkdocs/css/base.css b/mkdocs/themes/mkdocs/css/base.css index 3a31ef73..8bfc7de2 100644 --- a/mkdocs/themes/mkdocs/css/base.css +++ b/mkdocs/themes/mkdocs/css/base.css @@ -224,3 +224,52 @@ h1:hover .headerlink, h2:hover .headerlink, h3:hover .headerlink, h4:hover .head font-weight: bold; text-align: left; } + + +.dropdown-submenu { + position: relative; +} + +.dropdown-submenu>.dropdown-menu { + top: 0; + left: 100%; + margin-top: -6px; + margin-left: -1px; + -webkit-border-radius: 0 6px 6px 6px; + -moz-border-radius: 0 6px 6px; + border-radius: 0 6px 6px 6px; +} + +.dropdown-submenu:hover>.dropdown-menu { + display: block; +} + +.dropdown-submenu>a:after { + display: block; + content: " "; + float: right; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; + border-width: 5px 0 5px 5px; + border-left-color: #ccc; + margin-top: 5px; + margin-right: -10px; +} + +.dropdown-submenu:hover>a:after { + border-left-color: #fff; +} + +.dropdown-submenu.pull-left { + float: none; +} + +.dropdown-submenu.pull-left>.dropdown-menu { + left: -100%; + margin-left: 10px; + -webkit-border-radius: 6px 0 6px 6px; + -moz-border-radius: 6px 0 6px 6px; + border-radius: 6px 0 6px 6px; +} diff --git a/mkdocs/themes/mkdocs/nav-sub.html b/mkdocs/themes/mkdocs/nav-sub.html new file mode 100644 index 00000000..76210465 --- /dev/null +++ b/mkdocs/themes/mkdocs/nav-sub.html @@ -0,0 +1,14 @@ +{% if not nav_item.children %} +<li {% if nav_item.active %}class="active"{% endif %}> + <a href="{{ nav_item.url }}">{{ nav_item.title }}</a> +</li> +{% else %} + <li class="dropdown-submenu"> + <a tabindex="-1" href="">{{ nav_item.title }}</a> + <ul class="dropdown-menu"> + {% for nav_item in nav_item.children %} + {% include "nav-sub.html" %} + {% endfor %} + </ul> + </li> +{% endif %} diff --git a/mkdocs/themes/mkdocs/nav.html b/mkdocs/themes/mkdocs/nav.html index 5ab01c90..60cc5ca9 100644 --- a/mkdocs/themes/mkdocs/nav.html +++ b/mkdocs/themes/mkdocs/nav.html @@ -28,9 +28,7 @@ <a href="#" class="dropdown-toggle" data-toggle="dropdown">{{ nav_item.title }} <b class="caret"></b></a> <ul class="dropdown-menu"> {% for nav_item in nav_item.children %} - <li {% if nav_item.active %}class="active"{% endif %}> - <a href="{{ nav_item.url }}">{{ nav_item.title }}</a> - </li> + {% include "nav-sub.html" %} {% endfor %} </ul> </li> diff --git a/mkdocs/themes/readthedocs/base.html b/mkdocs/themes/readthedocs/base.html index fe4c1474..b6b7ba65 100644 --- a/mkdocs/themes/readthedocs/base.html +++ b/mkdocs/themes/readthedocs/base.html @@ -57,7 +57,11 @@ </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> - {% include "toc.html" %} + <ul class="current"> + {% for nav_item in nav %} + <li>{% include "toc.html" %}<li> + {% endfor %} + </ul> </div> &nbsp; </nav> diff --git a/mkdocs/themes/readthedocs/css/theme_extra.css b/mkdocs/themes/readthedocs/css/theme_extra.css index 675760c9..ccb384e9 100644 --- a/mkdocs/themes/readthedocs/css/theme_extra.css +++ b/mkdocs/themes/readthedocs/css/theme_extra.css @@ -25,7 +25,7 @@ h3, h4, h5, h6 { color: #838383; } -.wy-menu-vertical .toctree-l2 a { +.wy-menu-vertical .subnav a { padding: 0.4045em 2.427em; } @@ -116,3 +116,11 @@ code.cs, code.c { padding: 6px 12px; border-color: #D1D4D5; } + +.wy-menu-vertical li ul { + display: inherit; +} + +.wy-menu-vertical li ul.subnav ul.subnav{ + padding-left: 1em; +} diff --git a/mkdocs/themes/readthedocs/toc.html b/mkdocs/themes/readthedocs/toc.html index c7f1d03d..6cd2fc9b 100644 --- a/mkdocs/themes/readthedocs/toc.html +++ b/mkdocs/themes/readthedocs/toc.html @@ -1,38 +1,23 @@ -<ul class="current"> - {% for nav_item in nav %} - {% if nav_item.children %} - <span>{{ nav_item.title }}</span> - {% for nav_item in nav_item.children %} - <li class="toctree-l2 {% if nav_item.active%}current{%endif%}"> - <a class="{% if nav_item.active%}current{%endif%}" href="{{ nav_item.url }}">{{ nav_item.title }}</a> - {% if nav_item == current_page %} - <ul> - {% for toc_item in toc %} - <li class="toctree-l3"><a href="{{ toc_item.url }}">{{ toc_item.title }}</a></li> - {% for toc_item in toc_item.children %} - <li><a class="toctree-l4" href="{{ toc_item.url }}">{{ toc_item.title }}</a></li> - {% endfor %} - {% endfor %} - </ul> - {% endif %} - </li> +{% if nav_item.children %} + <ul class="subnav"> + <li><span>{{ nav_item.title }}</span></li> + + {% for nav_item in nav_item.children %} + {% include 'toc.html' %} + {% endfor %} + </ul> +{% else %} + <li class="toctree-l1 {% if nav_item.active%}current{%endif%}"> + <a class="{% if nav_item.active%}current{%endif%}" href="{{ nav_item.url }}">{{ nav_item.title }}</a> + {% if nav_item == current_page %} + <ul> + {% for toc_item in toc %} + <li class="toctree-l3"><a href="{{ toc_item.url }}">{{ toc_item.title }}</a></li> + {% for toc_item in toc_item.children %} + <li><a class="toctree-l4" href="{{ toc_item.url }}">{{ toc_item.title }}</a></li> + {% endfor %} {% endfor %} - {% else %} - <li class="toctree-l1 {% if nav_item.active%}current{%endif%}"> - <a class="{% if nav_item.active%}current{%endif%}" href="{{ nav_item.url }}">{{ nav_item.title }}</a> - {% if nav_item == current_page %} - <ul> - {% for toc_item in toc %} - <li class="toctree-l3"><a href="{{ toc_item.url }}">{{ toc_item.title }}</a></li> - {% for toc_item in toc_item.children %} - <li><a class="toctree-l4" href="{{ toc_item.url }}">{{ toc_item.title }}</a></li> - {% endfor %} - {% endfor %} - </ul> - {% endif %} - </li> + </ul> {% endif %} - - {% endfor %} -</ul> - + </li> +{% endif %}
Allow nav links with depth > 2 The default theme doesn't necessarily need to deal with styling them, but they should at least be allowed.
mkdocs/mkdocs
diff --git a/mkdocs/tests/build_tests.py b/mkdocs/tests/build_tests.py index 784d8925..728b4c7a 100644 --- a/mkdocs/tests/build_tests.py +++ b/mkdocs/tests/build_tests.py @@ -84,9 +84,9 @@ class BuildTests(unittest.TestCase): def test_convert_internal_media(self): """Test relative image URL's are the same for different base_urls""" pages = [ - ('index.md',), - ('internal.md',), - ('sub/internal.md') + 'index.md', + 'internal.md', + 'sub/internal.md', ] site_navigation = nav.SiteNavigation(pages) @@ -107,9 +107,9 @@ class BuildTests(unittest.TestCase): def test_convert_internal_asbolute_media(self): """Test absolute image URL's are correct for different base_urls""" pages = [ - ('index.md',), - ('internal.md',), - ('sub/internal.md') + 'index.md', + 'internal.md', + 'sub/internal.md', ] site_navigation = nav.SiteNavigation(pages) @@ -129,9 +129,9 @@ class BuildTests(unittest.TestCase): def test_dont_convert_code_block_urls(self): pages = [ - ('index.md',), - ('internal.md',), - ('sub/internal.md') + 'index.md', + 'internal.md', + 'sub/internal.md', ] site_navigation = nav.SiteNavigation(pages) @@ -150,9 +150,9 @@ class BuildTests(unittest.TestCase): def test_anchor_only_link(self): pages = [ - ('index.md',), - ('internal.md',), - ('sub/internal.md') + 'index.md', + 'internal.md', + 'sub/internal.md', ] site_navigation = nav.SiteNavigation(pages) @@ -172,7 +172,7 @@ class BuildTests(unittest.TestCase): md_text = 'An [internal link](internal.md) to another document.' expected = '<p>An <a href="internal/index.html">internal link</a> to another document.</p>' pages = [ - ('internal.md',) + 'internal.md', ] site_navigation = nav.SiteNavigation(pages, use_directory_urls=False) html, toc, meta = build.convert_markdown(md_text, site_navigation=site_navigation) @@ -297,9 +297,9 @@ class BuildTests(unittest.TestCase): def test_strict_mode_valid(self): pages = [ - ('index.md',), - ('internal.md',), - ('sub/internal.md') + 'index.md', + 'internal.md', + 'sub/internal.md', ] site_nav = nav.SiteNavigation(pages) @@ -309,9 +309,9 @@ class BuildTests(unittest.TestCase): def test_strict_mode_invalid(self): pages = [ - ('index.md',), - ('internal.md',), - ('sub/internal.md') + 'index.md', + 'internal.md', + 'sub/internal.md', ] site_nav = nav.SiteNavigation(pages) diff --git a/mkdocs/tests/config_tests.py b/mkdocs/tests/config_tests.py index 53d2e915..0687edfe 100644 --- a/mkdocs/tests/config_tests.py +++ b/mkdocs/tests/config_tests.py @@ -72,7 +72,7 @@ class ConfigTests(unittest.TestCase): expected_result = { 'site_name': 'Example', 'pages': [ - ['index.md', 'Introduction'] + {'Introduction': 'index.md'} ], } file_contents = dedent(""" diff --git a/mkdocs/tests/legacy_tests.py b/mkdocs/tests/legacy_tests.py new file mode 100644 index 00000000..0951fce7 --- /dev/null +++ b/mkdocs/tests/legacy_tests.py @@ -0,0 +1,65 @@ +import unittest + +import yaml + +from mkdocs import legacy + + +class TestCompatabilityShim(unittest.TestCase): + + # TODO: Remove in 1.0 + + def test_convert(self): + + self.maxDiff = None + + pages_yaml_old = """ + pages: + - ['index.md', 'Home'] + - ['user-guide/writing-your-docs.md', 'User Guide'] + - ['user-guide/styling-your-docs.md', 'User Guide'] + - ['about/license.md', 'About', 'License'] + - ['about/release-notes.md', 'About'] + - ['about/contributing.md', 'About', 'Contributing'] + - ['help/contributing.md', 'Help', 'Contributing'] + - ['support.md'] + - ['cli.md', 'CLI Guide'] + """ + + pages_yaml_new = """ + pages: + - Home: index.md + - User Guide: + - user-guide/writing-your-docs.md + - user-guide/styling-your-docs.md + - About: + - License: about/license.md + - about/release-notes.md + - Contributing: about/contributing.md + - Help: + - Contributing: help/contributing.md + - support.md + - CLI Guide: cli.md + """ + self.assertEqual( + legacy.pages_compat_shim(yaml.load(pages_yaml_old)['pages']), + yaml.load(pages_yaml_new)['pages']) + + def test_convert_no_home(self): + + self.maxDiff = None + + pages_yaml_old = """ + pages: + - ['index.md'] + - ['about.md', 'About'] + """ + + pages_yaml_new = """ + pages: + - index.md + - About: about.md + """ + self.assertEqual( + legacy.pages_compat_shim(yaml.load(pages_yaml_old)['pages']), + yaml.load(pages_yaml_new)['pages']) diff --git a/mkdocs/tests/nav_tests.py b/mkdocs/tests/nav_tests.py index 90fc4469..263706a7 100644 --- a/mkdocs/tests/nav_tests.py +++ b/mkdocs/tests/nav_tests.py @@ -5,7 +5,7 @@ import mock import os import unittest -from mkdocs import nav +from mkdocs import nav, legacy from mkdocs.exceptions import ConfigurationError from mkdocs.tests.base import dedent @@ -13,8 +13,8 @@ from mkdocs.tests.base import dedent class SiteNavigationTests(unittest.TestCase): def test_simple_toc(self): pages = [ - ('index.md', 'Home'), - ('about.md', 'About') + {'Home': 'index.md'}, + {'About': 'about.md'} ] expected = dedent(""" Home - / @@ -27,8 +27,8 @@ class SiteNavigationTests(unittest.TestCase): def test_empty_toc_item(self): pages = [ - ('index.md',), - ('about.md', 'About') + 'index.md', + {'About': 'about.md'} ] expected = dedent(""" Home - / @@ -41,36 +41,16 @@ class SiteNavigationTests(unittest.TestCase): def test_indented_toc(self): pages = [ - ('index.md', 'Home'), - ('api-guide/running.md', 'API Guide', 'Running'), - ('api-guide/testing.md', 'API Guide', 'Testing'), - ('api-guide/debugging.md', 'API Guide', 'Debugging'), - ('about/release-notes.md', 'About', 'Release notes'), - ('about/license.md', 'About', 'License') - ] - expected = dedent(""" - Home - / - API Guide - Running - /api-guide/running/ - Testing - /api-guide/testing/ - Debugging - /api-guide/debugging/ - About - Release notes - /about/release-notes/ - License - /about/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), 6) - - def test_indented_toc_missing_child_title(self): - pages = [ - ('index.md', 'Home'), - ('api-guide/running.md', 'API Guide', 'Running'), - ('api-guide/testing.md', 'API Guide'), - ('api-guide/debugging.md', 'API Guide', 'Debugging'), - ('about/release-notes.md', 'About', 'Release notes'), - ('about/license.md', 'About', 'License') + {'Home': 'index.md'}, + {'API Guide': [ + {'Running': 'api-guide/running.md'}, + {'Testing': 'api-guide/testing.md'}, + {'Debugging': 'api-guide/debugging.md'}, + ]}, + {'About': [ + {'Release notes': 'about/release-notes.md'}, + {'License': 'about/license.md'} + ]} ] expected = dedent(""" Home - / @@ -89,9 +69,9 @@ class SiteNavigationTests(unittest.TestCase): def test_nested_ungrouped(self): pages = [ - ('index.md', 'Home'), - ('about/contact.md', 'Contact'), - ('about/sub/license.md', 'License Title') + {'Home': 'index.md'}, + {'Contact': 'about/contact.md'}, + {'License Title': 'about/sub/license.md'}, ] expected = dedent(""" Home - / @@ -105,45 +85,43 @@ class SiteNavigationTests(unittest.TestCase): def test_nested_ungrouped_no_titles(self): pages = [ - ('index.md',), - ('about/contact.md'), - ('about/sub/license.md') + 'index.md', + 'about/contact.md', + 'about/sub/license.md' ] expected = dedent(""" Home - / - About - Contact - /about/contact/ - License - /about/sub/license/ + 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.nav_items), 3) self.assertEqual(len(site_navigation.pages), 3) @mock.patch.object(os.path, 'sep', '\\') def test_nested_ungrouped_no_titles_windows(self): pages = [ - ('index.md',), - ('about\\contact.md'), - ('about\\sub\\license.md') + 'index.md', + 'about\\contact.md', + 'about\\sub\\license.md', ] expected = dedent(""" Home - / - About - Contact - /about/contact/ - License - /about/sub/license/ + 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.nav_items), 3) self.assertEqual(len(site_navigation.pages), 3) def test_walk_simple_toc(self): pages = [ - ('index.md', 'Home'), - ('about.md', 'About') + {'Home': 'index.md'}, + {'About': 'about.md'} ] expected = [ dedent(""" @@ -161,8 +139,8 @@ class SiteNavigationTests(unittest.TestCase): def test_walk_empty_toc(self): pages = [ - ('index.md',), - ('about.md', 'About') + 'index.md', + {'About': 'about.md'} ] expected = [ dedent(""" @@ -180,12 +158,16 @@ class SiteNavigationTests(unittest.TestCase): def test_walk_indented_toc(self): pages = [ - ('index.md', 'Home'), - ('api-guide/running.md', 'API Guide', 'Running'), - ('api-guide/testing.md', 'API Guide', 'Testing'), - ('api-guide/debugging.md', 'API Guide', 'Debugging'), - ('about/release-notes.md', 'About', 'Release notes'), - ('about/license.md', 'About', 'License') + {'Home': 'index.md'}, + {'API Guide': [ + {'Running': 'api-guide/running.md'}, + {'Testing': 'api-guide/testing.md'}, + {'Debugging': 'api-guide/debugging.md'}, + ]}, + {'About': [ + {'Release notes': 'about/release-notes.md'}, + {'License': 'about/license.md'} + ]} ] expected = [ dedent(""" @@ -255,7 +237,7 @@ class SiteNavigationTests(unittest.TestCase): def test_base_url(self): pages = [ - ('index.md',) + 'index.md' ] site_navigation = nav.SiteNavigation(pages, use_directory_urls=False) base_url = site_navigation.url_context.make_relative('/') @@ -263,8 +245,8 @@ class SiteNavigationTests(unittest.TestCase): def test_relative_md_links_have_slash(self): pages = [ - ('index.md',), - ('user-guide/styling-your-docs.md',) + 'index.md', + 'user-guide/styling-your-docs.md' ] site_navigation = nav.SiteNavigation(pages, use_directory_urls=False) site_navigation.url_context.base_path = "/user-guide/configuration" @@ -277,17 +259,17 @@ class SiteNavigationTests(unittest.TestCase): """ pages = [ - ('index.md', ), - ('api-guide/running.md', ), - ('about/notes.md', ), - ('about/sub/license.md', ), + 'index.md', + 'api-guide/running.md', + 'about/notes.md', + 'about/sub/license.md', ] url_context = nav.URLContext() nav_items, pages = nav._generate_site_navigation(pages, url_context) self.assertEqual([n.title for n in nav_items], - ['Home', 'Api guide', 'About']) + ['Home', 'Running', 'Notes', 'License']) self.assertEqual([p.title for p in pages], ['Home', 'Running', 'Notes', 'License']) @@ -297,25 +279,25 @@ class SiteNavigationTests(unittest.TestCase): Verify inferring page titles based on the filename with a windows path """ pages = [ - ('index.md', ), - ('api-guide\\running.md', ), - ('about\\notes.md', ), - ('about\\sub\\license.md', ), + 'index.md', + 'api-guide\\running.md', + 'about\\notes.md', + 'about\\sub\\license.md', ] url_context = nav.URLContext() nav_items, pages = nav._generate_site_navigation(pages, url_context) self.assertEqual([n.title for n in nav_items], - ['Home', 'Api guide', 'About']) + ['Home', 'Running', 'Notes', 'License']) self.assertEqual([p.title for p in pages], ['Home', 'Running', 'Notes', 'License']) def test_invalid_pages_config(self): bad_pages = [ - (), # too short - ('this', 'is', 'too', 'long'), + set(), # should be dict or string only + {"a": "index.md", "b": "index.md"} # extra key ] for bad_page in bad_pages: @@ -325,15 +307,28 @@ class SiteNavigationTests(unittest.TestCase): self.assertRaises(ConfigurationError, _test) + def test_pages_config(self): + + bad_page = {} # empty + + def _test(): + return nav._generate_site_navigation((bad_page, ), None) + + self.assertRaises(ConfigurationError, _test) + def test_ancestors(self): pages = [ - ('index.md', 'Home'), - ('api-guide/running.md', 'API Guide', 'Running'), - ('api-guide/testing.md', 'API Guide', 'Testing'), - ('api-guide/debugging.md', 'API Guide', 'Debugging'), - ('about/release-notes.md', 'About', 'Release notes'), - ('about/license.md', 'About', 'License') + {'Home': 'index.md'}, + {'API Guide': [ + {'Running': 'api-guide/running.md'}, + {'Testing': 'api-guide/testing.md'}, + {'Debugging': 'api-guide/debugging.md'}, + ]}, + {'About': [ + {'Release notes': 'about/release-notes.md'}, + {'License': 'about/license.md'} + ]} ] site_navigation = nav.SiteNavigation(pages) @@ -361,3 +356,197 @@ class SiteNavigationTests(unittest.TestCase): title = nav.file_to_title("mkdocs/tests/resources/no_title_metadata.md") self.assertEqual(title, "Title") + + def test_nesting(self): + + pages_config = [ + {'Home': 'index.md'}, + {'Install': [ + {'Pre-install': 'install/install-pre.md'}, + {'The install': 'install/install-actual.md'}, + {'Post install': 'install/install-post.md'}, + ]}, + {'Guide': [ + {'Tutorial': [ + {'Getting Started': 'guide/tutorial/running.md'}, + {'Advanced Features': 'guide/tutorial/testing.md'}, + {'Further Reading': 'guide/tutorial/debugging.md'}, + ]}, + {'API Reference': [ + {'Feature 1': 'guide/api-ref/running.md'}, + {'Feature 2': 'guide/api-ref/testing.md'}, + {'Feature 3': 'guide/api-ref/debugging.md'}, + ]}, + {'Testing': 'guide/testing.md'}, + {'Deploying': 'guide/deploying.md'}, + ]} + ] + + site_navigation = nav.SiteNavigation(pages_config) + + self.assertEqual([n.title for n in site_navigation.nav_items], + ['Home', 'Install', 'Guide']) + self.assertEqual(len(site_navigation.pages), 12) + + expected = dedent(""" + Home - / + Install + Pre-install - /install/install-pre/ + The install - /install/install-actual/ + Post install - /install/install-post/ + Guide + Tutorial + Getting Started - /guide/tutorial/running/ + Advanced Features - /guide/tutorial/testing/ + Further Reading - /guide/tutorial/debugging/ + API Reference + Feature 1 - /guide/api-ref/running/ + Feature 2 - /guide/api-ref/testing/ + Feature 3 - /guide/api-ref/debugging/ + Testing - /guide/testing/ + Deploying - /guide/deploying/ + """) + + self.maxDiff = None + self.assertEqual(str(site_navigation).strip(), expected) + + +class TestLegacyPagesConfig(unittest.TestCase): + + def test_walk_simple_toc(self): + pages = legacy.pages_compat_shim([ + ('index.md', 'Home'), + ('about.md', 'About') + ]) + expected = [ + dedent(""" + Home - / [*] + About - /about/ + """), + dedent(""" + Home - / + About - /about/ [*] + """) + ] + site_navigation = nav.SiteNavigation(pages) + for index, page in enumerate(site_navigation.walk_pages()): + self.assertEqual(str(site_navigation).strip(), expected[index]) + + def test_walk_empty_toc(self): + pages = legacy.pages_compat_shim([ + ('index.md',), + ('about.md', 'About') + ]) + + expected = [ + dedent(""" + Home - / [*] + About - /about/ + """), + dedent(""" + Home - / + About - /about/ [*] + """) + ] + site_navigation = nav.SiteNavigation(pages) + for index, page in enumerate(site_navigation.walk_pages()): + self.assertEqual(str(site_navigation).strip(), expected[index]) + + def test_walk_indented_toc(self): + pages = legacy.pages_compat_shim([ + ('index.md', 'Home'), + ('api-guide/running.md', 'API Guide', 'Running'), + ('api-guide/testing.md', 'API Guide', 'Testing'), + ('api-guide/debugging.md', 'API Guide', 'Debugging'), + ('about/release-notes.md', 'About', 'Release notes'), + ('about/license.md', 'About', 'License') + ]) + expected = [ + dedent(""" + Home - / [*] + API Guide + Running - /api-guide/running/ + Testing - /api-guide/testing/ + Debugging - /api-guide/debugging/ + About + Release notes - /about/release-notes/ + License - /about/license/ + """), + dedent(""" + Home - / + API Guide [*] + Running - /api-guide/running/ [*] + Testing - /api-guide/testing/ + Debugging - /api-guide/debugging/ + About + Release notes - /about/release-notes/ + License - /about/license/ + """), + dedent(""" + Home - / + API Guide [*] + Running - /api-guide/running/ + Testing - /api-guide/testing/ [*] + Debugging - /api-guide/debugging/ + About + Release notes - /about/release-notes/ + License - /about/license/ + """), + dedent(""" + Home - / + API Guide [*] + Running - /api-guide/running/ + Testing - /api-guide/testing/ + Debugging - /api-guide/debugging/ [*] + About + Release notes - /about/release-notes/ + License - /about/license/ + """), + dedent(""" + Home - / + API Guide + Running - /api-guide/running/ + Testing - /api-guide/testing/ + Debugging - /api-guide/debugging/ + About [*] + Release notes - /about/release-notes/ [*] + License - /about/license/ + """), + dedent(""" + Home - / + API Guide + Running - /api-guide/running/ + Testing - /api-guide/testing/ + Debugging - /api-guide/debugging/ + About [*] + Release notes - /about/release-notes/ + License - /about/license/ [*] + """) + ] + site_navigation = nav.SiteNavigation(pages) + for index, page in enumerate(site_navigation.walk_pages()): + self.assertEqual(str(site_navigation).strip(), expected[index]) + + def test_indented_toc_missing_child_title(self): + pages = legacy.pages_compat_shim([ + ('index.md', 'Home'), + ('api-guide/running.md', 'API Guide', 'Running'), + ('api-guide/testing.md', 'API Guide'), + ('api-guide/debugging.md', 'API Guide', 'Debugging'), + ('about/release-notes.md', 'About', 'Release notes'), + ('about/license.md', 'About', 'License') + ]) + expected = dedent(""" + Home - / + API Guide + Running - /api-guide/running/ + Testing - /api-guide/testing/ + Debugging - /api-guide/debugging/ + About + Release notes - /about/release-notes/ + License - /about/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), 6) diff --git a/mkdocs/tests/search_tests.py b/mkdocs/tests/search_tests.py index c53f40b6..182f2693 100644 --- a/mkdocs/tests/search_tests.py +++ b/mkdocs/tests/search_tests.py @@ -103,8 +103,8 @@ class SearchTests(unittest.TestCase): """ pages = [ - ('index.md', 'Home'), - ('about.md', 'About') + {'Home': 'index.md'}, + {'About': 'about.md'}, ] site_navigation = nav.SiteNavigation(pages) diff --git a/mkdocs/tests/utils_tests.py b/mkdocs/tests/utils_tests.py index 23da4e07..e2854187 100644 --- a/mkdocs/tests/utils_tests.py +++ b/mkdocs/tests/utils_tests.py @@ -54,8 +54,8 @@ class UtilsTests(unittest.TestCase): def test_create_media_urls(self): pages = [ - ('index.md', 'Home'), - ('about.md', 'About') + {'Home': 'index.md'}, + {'About': 'about.md'} ] expected_results = { 'https://media.cdn.org/jq.js': 'https://media.cdn.org/jq.js',
{ "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": 2, "issue_text_score": 0, "test_score": 2 }, "num_modified_files": 11 }
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", "pytest-cov", "pytest-xdist", "pytest-mock", "pytest-asyncio", "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 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 livereload==2.7.1 Markdown==3.7 MarkupSafe==3.0.2 -e git+https://github.com/mkdocs/mkdocs.git@1a0dfb5ee3d5dd290da9c8c03b0946e784aa6959#egg=mkdocs mock==5.2.0 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 tornado==6.4.2 typing_extensions==4.13.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 - 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 - 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 - 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 - tornado==6.4.2 - typing-extensions==4.13.0 - zipp==3.21.0 prefix: /opt/conda/envs/mkdocs
[ "mkdocs/tests/config_tests.py::ConfigTests::test_config_option", "mkdocs/tests/config_tests.py::ConfigTests::test_default_pages", "mkdocs/tests/config_tests.py::ConfigTests::test_doc_dir_in_site_dir", "mkdocs/tests/config_tests.py::ConfigTests::test_empty_config", "mkdocs/tests/config_tests.py::ConfigTests::test_invalid_config", "mkdocs/tests/config_tests.py::ConfigTests::test_missing_config_file", "mkdocs/tests/config_tests.py::ConfigTests::test_missing_site_name", "mkdocs/tests/config_tests.py::ConfigTests::test_nonexistant_config", "mkdocs/tests/config_tests.py::ConfigTests::test_theme", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_file_to_tile", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_invalid_pages_config", "mkdocs/tests/search_tests.py::SearchTests::test_content_parser", "mkdocs/tests/search_tests.py::SearchTests::test_content_parser_content_before_header", "mkdocs/tests/search_tests.py::SearchTests::test_content_parser_no_id", "mkdocs/tests/search_tests.py::SearchTests::test_content_parser_no_sections", "mkdocs/tests/search_tests.py::SearchTests::test_find_toc_by_id", "mkdocs/tests/search_tests.py::SearchTests::test_html_stripper", "mkdocs/tests/utils_tests.py::UtilsTests::test_get_themes", "mkdocs/tests/utils_tests.py::UtilsTests::test_html_path", "mkdocs/tests/utils_tests.py::UtilsTests::test_is_html_file", "mkdocs/tests/utils_tests.py::UtilsTests::test_is_markdown_file", "mkdocs/tests/utils_tests.py::UtilsTests::test_reduce_list", "mkdocs/tests/utils_tests.py::UtilsTests::test_url_path", "mkdocs/tests/utils_tests.py::UtilsTests::test_yaml_load" ]
[ "mkdocs/tests/build_tests.py::BuildTests::test_anchor_only_link", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_asbolute_media", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_differing_directory", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_with_anchor", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_media", "mkdocs/tests/build_tests.py::BuildTests::test_convert_markdown", "mkdocs/tests/build_tests.py::BuildTests::test_convert_multiple_internal_links", "mkdocs/tests/build_tests.py::BuildTests::test_copying_media", "mkdocs/tests/build_tests.py::BuildTests::test_dont_convert_code_block_urls", "mkdocs/tests/build_tests.py::BuildTests::test_empty_document", "mkdocs/tests/build_tests.py::BuildTests::test_extension_config", "mkdocs/tests/build_tests.py::BuildTests::test_ignore_external_link", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_custom_extension", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_duplicate_custom_extension", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_fenced_code_extension", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_table_extension", "mkdocs/tests/build_tests.py::BuildTests::test_not_use_directory_urls", "mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_invalid", "mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_valid", "mkdocs/tests/legacy_tests.py::TestCompatabilityShim::test_convert", "mkdocs/tests/legacy_tests.py::TestCompatabilityShim::test_convert_no_home", "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_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_nesting", "mkdocs/tests/nav_tests.py::SiteNavigationTests::test_pages_config", "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", "mkdocs/tests/nav_tests.py::TestLegacyPagesConfig::test_indented_toc_missing_child_title", "mkdocs/tests/nav_tests.py::TestLegacyPagesConfig::test_walk_empty_toc", "mkdocs/tests/nav_tests.py::TestLegacyPagesConfig::test_walk_indented_toc", "mkdocs/tests/nav_tests.py::TestLegacyPagesConfig::test_walk_simple_toc", "mkdocs/tests/search_tests.py::SearchTests::test_create_search_index", "mkdocs/tests/utils_tests.py::UtilsTests::test_create_media_urls" ]
[]
[]
BSD 2-Clause "Simplified" License
111
[ "docs/index.md", "mkdocs/themes/mkdocs/css/base.css", "docs/user-guide/writing-your-docs.md", "docs/user-guide/configuration.md", "mkdocs/config.py", "mkdocs.yml", "mkdocs/themes/mkdocs/nav.html", "mkdocs/legacy.py", "mkdocs/themes/readthedocs/base.html", "mkdocs/themes/readthedocs/toc.html", "mkdocs/themes/mkdocs/nav-sub.html", "mkdocs/nav.py", "mkdocs/themes/readthedocs/css/theme_extra.css" ]
[ "docs/index.md", "mkdocs/themes/mkdocs/css/base.css", "docs/user-guide/writing-your-docs.md", "docs/user-guide/configuration.md", "mkdocs/config.py", "mkdocs.yml", "mkdocs/themes/mkdocs/nav.html", "mkdocs/legacy.py", "mkdocs/themes/readthedocs/base.html", "mkdocs/themes/readthedocs/toc.html", "mkdocs/themes/mkdocs/nav-sub.html", "mkdocs/nav.py", "mkdocs/themes/readthedocs/css/theme_extra.css" ]
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
[ "yapf/yapflib/__init__.py", "yapf/yapflib/errors.py", "yapf/__init__.py", "yapf/yapflib/style.py" ]
[ "yapf/yapflib/__init__.py", "yapf/yapflib/errors.py", "yapf/__init__.py", "yapf/yapflib/style.py" ]
softlayer__softlayer-python-537
f6722dcb5dc6021cd813280a789fd39e81053da0
2015-04-28 02:21:51
1195b2020ef6efc40462d59eb079f26e5f39a6d8
landscape-bot: [![Code Health](https://landscape.io/badge/153445/landscape.svg?style=flat)](https://landscape.io/diff/140430) Code quality remained the same when pulling **[4a1754c](https://github.com/sudorandom/softlayer-python/commit/4a1754cc1ec2498205c7a24f66e4a883ab705e70) on sudorandom:issue-536** into **[f6722dc](https://github.com/softlayer/softlayer-python/commit/f6722dcb5dc6021cd813280a789fd39e81053da0) on softlayer:master**.
diff --git a/SoftLayer/CLI/server/list.py b/SoftLayer/CLI/server/list.py index dec63ee5..03ba456e 100644 --- a/SoftLayer/CLI/server/list.py +++ b/SoftLayer/CLI/server/list.py @@ -41,7 +41,7 @@ def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tag): tags=tag) table = formatting.Table([ - 'guid', + 'id', 'hostname', 'primary_ip', 'backend_ip', @@ -51,10 +51,8 @@ def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tag): table.sortby = sortby or 'hostname' for server in servers: - # NOTE(kmcdonald): There are cases where a server might not have a - # globalIdentifier or hostname. table.add_row([ - utils.lookup(server, 'globalIdentifier') or server['id'], + utils.lookup(server, 'id'), utils.lookup(server, 'hostname') or formatting.blank(), utils.lookup(server, 'primaryIpAddress') or formatting.blank(), utils.lookup(server, 'primaryBackendIpAddress') or diff --git a/SoftLayer/CLI/virt/list.py b/SoftLayer/CLI/virt/list.py index 8419f02a..8b92acc1 100644 --- a/SoftLayer/CLI/virt/list.py +++ b/SoftLayer/CLI/virt/list.py @@ -50,7 +50,7 @@ def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tags=tag_list) table = formatting.Table([ - 'guid', + 'id', 'hostname', 'primary_ip', 'backend_ip', @@ -61,7 +61,7 @@ def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, for guest in guests: table.add_row([ - utils.lookup(guest, 'globalIdentifier') or guest['id'], + utils.lookup(guest, 'id'), utils.lookup(guest, 'hostname') or formatting.blank(), utils.lookup(guest, 'primaryIpAddress') or formatting.blank(), utils.lookup(guest, 'primaryBackendIpAddress') or
ID > GUID Switch the default display to use an object's ID rather than its GUID. Also use the ID rather than the GUID during confirmation text entries.
softlayer/softlayer-python
diff --git a/SoftLayer/tests/CLI/modules/server_tests.py b/SoftLayer/tests/CLI/modules/server_tests.py index acbab824..a65538cf 100644 --- a/SoftLayer/tests/CLI/modules/server_tests.py +++ b/SoftLayer/tests/CLI/modules/server_tests.py @@ -65,7 +65,7 @@ def test_list_servers(self): 'datacenter': 'TEST00', 'primary_ip': '172.16.1.100', 'hostname': 'hardware-test1', - 'guid': '1a2b3c-1701', + 'id': 1000, 'backend_ip': '10.1.0.2', 'action': 'TXN_NAME', }, @@ -73,7 +73,7 @@ def test_list_servers(self): 'datacenter': 'TEST00', 'primary_ip': '172.16.4.94', 'hostname': 'hardware-test2', - 'guid': '1a2b3c-1702', + 'id': 1001, 'backend_ip': '10.1.0.3', 'action': None, }, @@ -81,7 +81,7 @@ def test_list_servers(self): 'datacenter': 'TEST00', 'primary_ip': '172.16.4.95', 'hostname': 'hardware-bad-memory', - 'guid': 1002, + 'id': 1002, 'backend_ip': '10.1.0.4', 'action': None, } diff --git a/SoftLayer/tests/CLI/modules/vs_tests.py b/SoftLayer/tests/CLI/modules/vs_tests.py index 75459ff0..9c1064bd 100644 --- a/SoftLayer/tests/CLI/modules/vs_tests.py +++ b/SoftLayer/tests/CLI/modules/vs_tests.py @@ -22,13 +22,13 @@ def test_list_vs(self): 'primary_ip': '172.16.240.2', 'hostname': 'vs-test1', 'action': None, - 'guid': '1a2b3c-1701', + 'id': 100, 'backend_ip': '10.45.19.37'}, {'datacenter': 'TEST00', 'primary_ip': '172.16.240.7', 'hostname': 'vs-test2', 'action': None, - 'guid': '05a8ac-6abf0', + 'id': 104, 'backend_ip': '10.45.19.35'}]) def test_detail_vs(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": 0, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 2 }
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@f6722dcb5dc6021cd813280a789fd39e81053da0#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/server_tests.py::ServerCLITests::test_list_servers", "SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_list_vs" ]
[]
[ "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_cancel_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_options", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_missing_required", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_test_flag", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_with_export", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_failed", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata_and_file", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userfile", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_nic_edit_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_cancel_reasons", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_details", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle_negative", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_off", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_on", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_default", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_hard", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_negative", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_soft", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reload", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_update_firmware", "SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_create", "SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_create_options", "SoftLayer/tests/CLI/modules/vs_tests.py::DnsTests::test_detail_vs" ]
[]
MIT License
113
[ "SoftLayer/CLI/virt/list.py", "SoftLayer/CLI/server/list.py" ]
[ "SoftLayer/CLI/virt/list.py", "SoftLayer/CLI/server/list.py" ]
projectmesa__mesa-103
ca1e91c6ea8b5bc476ae0fdbf708c1f28ae55dc4
2015-04-28 14:22:30
ca1e91c6ea8b5bc476ae0fdbf708c1f28ae55dc4
diff --git a/examples/ForestFire/.ipynb_checkpoints/Forest Fire Model-checkpoint.ipynb b/examples/ForestFire/.ipynb_checkpoints/Forest Fire Model-checkpoint.ipynb index 8c8746c5..72b54805 100644 --- a/examples/ForestFire/.ipynb_checkpoints/Forest Fire Model-checkpoint.ipynb +++ b/examples/ForestFire/.ipynb_checkpoints/Forest Fire Model-checkpoint.ipynb @@ -1,584 +1,621 @@ { - "metadata": { - "name": "", - "signature": "sha256:7ad05bb257a0bc7d9176a2a5e02312695873a50206c8335653a47975f4e4ee8c" - }, - "nbformat": 3, - "nbformat_minor": 0, - "worksheets": [ + "cells": [ { - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# The Forest Fire Model\n", - "## A rapid introduction to Mesa\n", - "\n", - "The [Forest Fire Model](http://en.wikipedia.org/wiki/Forest-fire_model) is one of the simplest examples of a model that exhibits self-organized criticality.\n", - "\n", - "Mesa is a new, Pythonic agent-based modeling framework. A big advantage of using Python is that it a great language for interactive data analysis. Unlike some other ABM frameworks, with Mesa you can write a model, run it, and analyze it all in the same environment. (You don't have to, of course. But you can).\n", - "\n", - "In this notebook, we'll go over a rapid-fire (pun intended, sorry) introduction to building and analyzing a model with Mesa." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First, some imports. We'll go over what all the Mesa ones mean just below." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "import random\n", - "\n", - "import numpy as np\n", - "\n", - "import matplotlib.pyplot as plt\n", - "%matplotlib inline\n", - "\n", - "from mesa import Model, Agent\n", - "from mesa.time import RandomActivation\n", - "from mesa.space import Grid\n", - "from mesa.datacollection import DataCollector\n", - "from mesa.batchrunner import BatchRunner " - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 1 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Building the model\n", - "\n", - "Most models consist of basically two things: agents, and an world for the agents to be in. The Forest Fire model has only one kind of agent: a tree. A tree can either be unburned, on fire, or already burned. The environment is a grid, where each cell can either be empty or contain a tree.\n", - "\n", - "First, let's define our tree agent. The agent needs to be assigned **x** and **y** coordinates on the grid, and that's about it. We could assign agents a condition to be in, but for now let's have them all start as being 'Fine'. Since the agent doesn't move, and there is only at most one tree per cell, we can use a tuple of its coordinates as a unique identifier.\n", - "\n", - "Next, we define the agent's **step** method. This gets called whenever the agent needs to act in the world and takes the *model* object to which it belongs as an input. The tree's behavior is simple: If it is currently on fire, it spreads the fire to any trees above, below, to the left and the right of it that are not themselves burned out or on fire; then it burns itself out. " - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "class TreeCell(Agent):\n", - " '''\n", - " A tree cell.\n", - " \n", - " Attributes:\n", - " x, y: Grid coordinates\n", - " condition: Can be \"Fine\", \"On Fire\", or \"Burned Out\"\n", - " unique_id: (x,y) tuple. \n", - " \n", - " unique_id isn't strictly necessary here, but it's good practice to give one to each\n", - " agent anyway.\n", - " '''\n", - " def __init__(self, x, y):\n", - " '''\n", - " Create a new tree.\n", - " Args:\n", - " x, y: The tree's coordinates on the grid.\n", - " '''\n", - " self.x = x\n", - " self.y = y\n", - " self.unique_id = (x, y)\n", - " self.condition = \"Fine\"\n", - " \n", - " def step(self, model):\n", - " '''\n", - " If the tree is on fire, spread it to fine trees nearby.\n", - " '''\n", - " if self.condition == \"On Fire\":\n", - " neighbors = model.grid.get_neighbors(self.x, self.y, moore=False)\n", - " for neighbor in neighbors:\n", - " if neighbor.condition == \"Fine\":\n", - " neighbor.condition = \"On Fire\"\n", - " self.condition = \"Burned Out\"\n", - " " - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 2 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now we need to define the model object itself. The main thing the model needs is the grid, which the trees are placed on. But since the model is dynamic, it also needs to include time -- it needs a schedule, to manage the trees activation as they spread the fire from one to the other.\n", - "\n", - "The model also needs a few parameters: how large the grid is and what the density of trees on it will be. Density will be the key parameter we'll explore below.\n", - "\n", - "Finally, we'll give the model a data collector. This is a Mesa object which collects and stores data on the model as it runs for later analysis.\n", - "\n", - "The constructor needs to do a few things. It instantiates all the model-level variables and objects; it randomly places trees on the grid, based on the density parameter; and it starts the fire by setting all the trees on one edge of the grid (x=0) as being On \"Fire\".\n", - "\n", - "Next, the model needs a **step** method. Like at the agent level, this method defines what happens every step of the model. We want to activate all the trees, one at a time; then we run the data collector, to count how many trees are currently on fire, burned out, or still fine. If there are no trees left on fire, we stop the model by setting its **running** property to False." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "class ForestFire(Model):\n", - " '''\n", - " Simple Forest Fire model.\n", - " '''\n", - " def __init__(self, height, width, density):\n", - " '''\n", - " Create a new forest fire model.\n", - " \n", - " Args:\n", - " height, width: The size of the grid to model\n", - " density: What fraction of grid cells have a tree in them.\n", - " '''\n", - " # Initialize model parameters\n", - " self.height = height\n", - " self.width = width\n", - " self.density = density\n", - " \n", - " # Set up model objects\n", - " self.schedule = RandomActivation(self)\n", - " self.grid = Grid(height, width, torus=False)\n", - " self.dc = DataCollector({\"Fine\": lambda m: self.count_type(m, \"Fine\"),\n", - " \"On Fire\": lambda m: self.count_type(m, \"On Fire\"),\n", - " \"Burned Out\": lambda m: self.count_type(m, \"Burned Out\")})\n", - " \n", - " # Place a tree in each cell with Prob = density\n", - " for x in range(self.width):\n", - " for y in range(self.height):\n", - " if random.random() < self.density:\n", - " # Create a tree\n", - " new_tree = TreeCell(x, y)\n", - " # Set all trees in the first column on fire.\n", - " if x == 0:\n", - " new_tree.condition = \"On Fire\"\n", - " self.grid[y][x] = new_tree\n", - " self.schedule.add(new_tree)\n", - " self.running = True\n", - " \n", - " def step(self):\n", - " '''\n", - " Advance the model by one step.\n", - " '''\n", - " self.schedule.step()\n", - " self.dc.collect(self)\n", - " # Halt if no more fire\n", - " if self.count_type(self, \"On Fire\") == 0:\n", - " self.running = False\n", - " \n", - " @staticmethod\n", - " def count_type(model, tree_condition):\n", - " '''\n", - " Helper method to count trees in a given condition in a given model.\n", - " '''\n", - " count = 0\n", - " for tree in model.schedule.agents:\n", - " if tree.condition == tree_condition:\n", - " count += 1\n", - " return count" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 3 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Running the model\n", - "\n", - "Let's create a model with a 100 x 100 grid, and a tree density of 0.6. Remember, ForestFire takes the arguments *height*, *width*, *density*." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "fire = ForestFire(100, 100, 0.6)" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 4 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To run the model until it's done (that is, until it sets its **running** property to False) just use the **run_model()** method. This is implemented in the Model parent object, so we didn't need to implement it above." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "fire.run_model()" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 5 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "That's all there is to it!\n", - "\n", - "But... so what? This code doesn't include a visualization, after all. \n", - "\n", - "**TODO: Add a MatPlotLib visualization**\n", - "\n", - "Remember the data collector? Now we can put the data it collected into a pandas DataFrame:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "results = fire.dc.get_model_vars_dataframe()" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 6 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And chart it, to see the dynamics." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "results.plot()" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 7, - "text": [ - "<matplotlib.axes._subplots.AxesSubplot at 0x10988b2e8>" - ] - }, - { - "metadata": {}, - "output_type": "display_data", - "png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl4VOXZ+PHvnYXsGwmEsAZe2UFBlKXCS0Tpixa3umHF\nithWi1KXqgVtxbZuuLVqtfWnCC51wV0REETSugIqASRsAYMQISQhC0kI2Z7fH89MMoFAAiSZc4b7\nc13nmjlnzsx57szkPs/c55lzxBiDUkqpwBTk7wYopZRqPZrklVIqgGmSV0qpAKZJXimlApgmeaWU\nCmCa5JVSKoA1K8mLSLyIvCkiG0QkU0RGiEh7EVkqIptFZImIxPusP1NEtojIRhH5qc/yYSKyzvPY\n460RkFJKqXrN7ck/Diw0xvQHTgY2AjOApcaYPsAyzzwiMgC4HBgATACeFhHxvM4/gWuNMb2B3iIy\nocUiUUopdYgmk7yIxAFjjDHPAxhjqo0xxcD5wAue1V4ALvTcvwB41RhTZYzJBrKAESKSAsQYY1Z6\n1nvR5zlKKaVaQXN68j2BPBGZKyLfisizIhIFJBtjcj3r5ALJnvudgZ0+z98JdGlkeY5nuVJKqVbS\nnCQfApwKPG2MORUow1Oa8TL23Ah6fgSllHKYkGassxPYaYxZ5Zl/E5gJ7BaRTsaY3Z5SzB7P4zlA\nN5/nd/W8Ro7nvu/ynIM3JiK6s1BKqaNkjJHGljfZkzfG7AZ2iEgfz6KzgfXAB8DVnmVXA+967r8P\nTBKRdiLSE+gNrPS8TolnZI4AV/k85+BtunqaNWuW39ugcWgcTp00jpafjqQ5PXmA6cC/RaQdsBW4\nBggG5ovItUA2cJknQWeKyHwg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 - "<matplotlib.figure.Figure at 0x10987db70>" - ] - } - ], - "prompt_number": 7 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this case, the fire burned itself out after about 90 steps, with many trees left unburned. \n", - "\n", - "You can try changing the density parameter and rerunning the code above, to see how different densities yield different dynamics. For example:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "fire = ForestFire(100, 100, 0.8)\n", - "fire.run_model()\n", - "results = fire.dc.get_model_vars_dataframe()\n", - "results.plot()" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 8, - "text": [ - "<matplotlib.axes._subplots.AxesSubplot at 0x109c54208>" - ] - }, - { - "metadata": {}, - "output_type": "display_data", - "png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsnXd4FNX3h9+ThN5CkYC0oPTeq0CooqI06SUBRBFpigX0\nq6A/BURQiiBVpElHmnQkAlJCC8VIJ/TeAoQSkvv7YzZkCYGEsLuz5b7Pc5+duXNn5nMyO2cn5945\nV5RSaDQajcY98TJbgEaj0Wjsh3byGo1G48ZoJ6/RaDRujHbyGo1G48ZoJ6/RaDRujHbyGo1G48Yk\n6uRFpL+I/Csi+0TkdxFJJSJZRGSNiBwSkdUi4huv/WEROSAiDazqy1uOcVhERtrLII1Go9HE8VQn\nLyL+QFegnFKqJOANtAb6AWuUUoWAdZZ1RKQY0AooBjQExoqIWA73C9BFKVUQKCgiDW1ujUaj0Wge\nIbEn+QggCkgrIj5AWuAs8BYw1dJmKtDEstwYmKWUilJKhQNHgMoikhPIoJQKsbSbZrWPRqPRaOzE\nU528UuoqMBw4ieHcryul1gB+SqkLlmYXAD/L8ovAaatDnAZyJVB/xlKv0Wg0GjuSWLjmZaAP4I/h\nqNOLSHvrNsrIi6BzI2g0Go0T4pPI9grAZqXUFQARWQhUBc6L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A/sFdSk18D\n8jEpa9FbwIzt+4Bv8n4TXQZet/0AsAt4JX/Xjc9v+29gxPYO4CFgRNLjtCB7wX5ggZWZdm3KbmCP\n7Z22H8ltpeevRZGnsEjK9mWgu0iqkWx/B1xa1TwGHMrbh4DnK+1URWz/Zns+b/9FWgi3lfbkX86b\nm0j3pS7RkuyS7gaeBT4EujNBWpG9YPUMmNLz16XIr7VIamuP+tIrQ7aX8vYSMNTLzlRB0jZgJ3CC\nluSX1CdpnpTxuO2ztCQ78D7wJlB8Pm9bskM6k/9a0ilJL+e20vNXvRjqv8Td3wLbbvp6AUm3AJ8B\n+23/qcJqvybnt30V2CHpNuCYpJFVxxuZXdJzwAXbc5L2rPWZpmYveMz2oqQ7gBlJ54oHy8pflzP5\nX4Dhwv4w6Wy+TZYk3Qkg6S7gQo/7UxpJg6QCP2X7SG5uTX4A238A08DDtCP7o8CYpJ+Bw8ATkqZo\nR3YAbC/m378Dn5OGqUvPX5cifwq4V9I2SZuAceBoj/tUtaPAvry9Dzhyjc9uWEqn7JPAgu0PCoca\nn1/Slu7sCUk3Ak8Bc7Qgu+23bQ/b3g68CMzafokWZAeQdJOkW/P2zcDTwBkqyF+befKSnmHlOfOT\ntid63KXSSDoM7Aa2kMbh3gG+AD4F7gE6wAu2N+abg68hzyb5FjjNyjDdAdLq50bnl/Qg6eZaX/6Z\nsv2epM00PHuRpN3AG7bH2pJd0nbS2TukYfJPbE9Ukb82RT6EEML6q8twTQghhBJEkQ8hhAaLIh9C\nCA0WRT6EEBosinwIITRYFPkQQmiwKPIhhNBgUeRDCKHB/gXedjkAMUGImgAAAABJRU5ErkJggg==\n", - "text": [ - "<matplotlib.figure.Figure at 0x109c517b8>" - ] - } - ], - "prompt_number": 8 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "... But to really understand how the final outcome varies with density, we can't just tweak the parameter by hand over and over again. We need to do a batch run. \n", - "\n", - "## Batch runs\n", - "\n", - "Batch runs, also called parameter sweeps, allow use to systemically vary the density parameter, run the model, and check the output. Mesa provides a BatchRunner object which takes a model class, a dictionary of parameters and the range of values they can take and runs the model at each combination of these values. We can also give it reporters, which collect some data on the model at the end of each run and store it, associated with the parameters that produced it.\n", - "\n", - "For ease of typing and reading, we'll first create the parameters to vary and the reporter, and then assign them to a new BatchRunner." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "param_set = dict(height=50, # Height and width are constant\n", - " width=50,\n", - " # Vary density from 0.01 to 1, in 0.01 increments:\n", - " density=np.linspace(0,1,101)[1:]) " - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 9 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "# At the end of each model run, calculate the fraction of trees which are Burned Out\n", - "model_reporter = {\"BurnedOut\": lambda m: (ForestFire.count_type(m, \"Burned Out\") / \n", - " m.schedule.get_agent_count()) }" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 10 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "# Create the batch runner\n", - "param_run = BatchRunner(ForestFire, param_set, model_reporters=model_reporter)" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 11 - }, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# The Forest Fire Model\n", + "## A rapid introduction to Mesa\n", + "\n", + "The [Forest Fire Model](http://en.wikipedia.org/wiki/Forest-fire_model) is one of the simplest examples of a model that exhibits self-organized criticality.\n", + "\n", + "Mesa is a new, Pythonic agent-based modeling framework. A big advantage of using Python is that it a great language for interactive data analysis. Unlike some other ABM frameworks, with Mesa you can write a model, run it, and analyze it all in the same environment. (You don't have to, of course. But you can).\n", + "\n", + "In this notebook, we'll go over a rapid-fire (pun intended, sorry) introduction to building and analyzing a model with Mesa." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "First, some imports. We'll go over what all the Mesa ones mean just below." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import random\n", + "\n", + "import numpy as np\n", + "\n", + "import matplotlib.pyplot as plt\n", + "%matplotlib inline\n", + "\n", + "from mesa import Model, Agent\n", + "from mesa.time import RandomActivation\n", + "from mesa.space import Grid\n", + "from mesa.datacollection import DataCollector\n", + "from mesa.batchrunner import BatchRunner " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Building the model\n", + "\n", + "Most models consist of basically two things: agents, and an world for the agents to be in. The Forest Fire model has only one kind of agent: a tree. A tree can either be unburned, on fire, or already burned. The environment is a grid, where each cell can either be empty or contain a tree.\n", + "\n", + "First, let's define our tree agent. The agent needs to be assigned **x** and **y** coordinates on the grid, and that's about it. We could assign agents a condition to be in, but for now let's have them all start as being 'Fine'. Since the agent doesn't move, and there is only at most one tree per cell, we can use a tuple of its coordinates as a unique identifier.\n", + "\n", + "Next, we define the agent's **step** method. This gets called whenever the agent needs to act in the world and takes the *model* object to which it belongs as an input. The tree's behavior is simple: If it is currently on fire, it spreads the fire to any trees above, below, to the left and the right of it that are not themselves burned out or on fire; then it burns itself out. " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class TreeCell(Agent):\n", + " '''\n", + " A tree cell.\n", + " \n", + " Attributes:\n", + " x, y: Grid coordinates\n", + " condition: Can be \"Fine\", \"On Fire\", or \"Burned Out\"\n", + " unique_id: (x,y) tuple. \n", + " \n", + " unique_id isn't strictly necessary here, but it's good practice to give one to each\n", + " agent anyway.\n", + " '''\n", + " def __init__(self, x, y):\n", + " '''\n", + " Create a new tree.\n", + " Args:\n", + " x, y: The tree's coordinates on the grid.\n", + " '''\n", + " self.x = x\n", + " self.y = y\n", + " self.unique_id = (x, y)\n", + " self.condition = \"Fine\"\n", + " \n", + " def step(self, model):\n", + " '''\n", + " If the tree is on fire, spread it to fine trees nearby.\n", + " '''\n", + " if self.condition == \"On Fire\":\n", + " neighbors = model.grid.get_neighbors(self.x, self.y, moore=False)\n", + " for neighbor in neighbors:\n", + " if neighbor.condition == \"Fine\":\n", + " neighbor.condition = \"On Fire\"\n", + " self.condition = \"Burned Out\"\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we need to define the model object itself. The main thing the model needs is the grid, which the trees are placed on. But since the model is dynamic, it also needs to include time -- it needs a schedule, to manage the trees activation as they spread the fire from one to the other.\n", + "\n", + "The model also needs a few parameters: how large the grid is and what the density of trees on it will be. Density will be the key parameter we'll explore below.\n", + "\n", + "Finally, we'll give the model a data collector. This is a Mesa object which collects and stores data on the model as it runs for later analysis.\n", + "\n", + "The constructor needs to do a few things. It instantiates all the model-level variables and objects; it randomly places trees on the grid, based on the density parameter; and it starts the fire by setting all the trees on one edge of the grid (x=0) as being On \"Fire\".\n", + "\n", + "Next, the model needs a **step** method. Like at the agent level, this method defines what happens every step of the model. We want to activate all the trees, one at a time; then we run the data collector, to count how many trees are currently on fire, burned out, or still fine. If there are no trees left on fire, we stop the model by setting its **running** property to False." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class ForestFire(Model):\n", + " '''\n", + " Simple Forest Fire model.\n", + " '''\n", + " def __init__(self, height, width, density):\n", + " '''\n", + " Create a new forest fire model.\n", + " \n", + " Args:\n", + " height, width: The size of the grid to model\n", + " density: What fraction of grid cells have a tree in them.\n", + " '''\n", + " # Initialize model parameters\n", + " self.height = height\n", + " self.width = width\n", + " self.density = density\n", + " \n", + " # Set up model objects\n", + " self.schedule = RandomActivation(self)\n", + " self.grid = Grid(height, width, torus=False)\n", + " self.dc = DataCollector({\"Fine\": lambda m: self.count_type(m, \"Fine\"),\n", + " \"On Fire\": lambda m: self.count_type(m, \"On Fire\"),\n", + " \"Burned Out\": lambda m: self.count_type(m, \"Burned Out\")})\n", + " \n", + " # Place a tree in each cell with Prob = density\n", + " for x in range(self.width):\n", + " for y in range(self.height):\n", + " if random.random() < self.density:\n", + " # Create a tree\n", + " new_tree = TreeCell(x, y)\n", + " # Set all trees in the first column on fire.\n", + " if x == 0:\n", + " new_tree.condition = \"On Fire\"\n", + " self.grid[y][x] = new_tree\n", + " self.schedule.add(new_tree)\n", + " self.running = True\n", + " \n", + " def step(self):\n", + " '''\n", + " Advance the model by one step.\n", + " '''\n", + " self.schedule.step()\n", + " self.dc.collect(self)\n", + " # Halt if no more fire\n", + " if self.count_type(self, \"On Fire\") == 0:\n", + " self.running = False\n", + " \n", + " @staticmethod\n", + " def count_type(model, tree_condition):\n", + " '''\n", + " Helper method to count trees in a given condition in a given model.\n", + " '''\n", + " count = 0\n", + " for tree in model.schedule.agents:\n", + " if tree.condition == tree_condition:\n", + " count += 1\n", + " return count" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Running the model\n", + "\n", + "Let's create a model with a 100 x 100 grid, and a tree density of 0.6. Remember, ForestFire takes the arguments *height*, *width*, *density*." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fire = ForestFire(100, 100, 0.6)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To run the model until it's done (that is, until it sets its **running** property to False) just use the **run_model()** method. This is implemented in the Model parent object, so we didn't need to implement it above." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fire.run_model()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "That's all there is to it!\n", + "\n", + "But... so what? This code doesn't include a visualization, after all. \n", + "\n", + "**TODO: Add a MatPlotLib visualization**\n", + "\n", + "Remember the data collector? Now we can put the data it collected into a pandas DataFrame:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "results = fire.dc.get_model_vars_dataframe()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And chart it, to see the dynamics." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ { - "cell_type": "markdown", + "data": { + "text/plain": [ + "<matplotlib.axes._subplots.AxesSubplot at 0x109a3eda0>" + ] + }, + "execution_count": 7, "metadata": {}, - "source": [ - "Now the BatchRunner, which we've named param_run, is ready to go. To run the model at every combination of parameters (in this case, every density value), just use the **run_all()** method." - ] + "output_type": "execute_result" }, { - "cell_type": "code", - "collapsed": false, - "input": [ - "param_run.run_all()" - ], - "language": "python", + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXsAAAEACAYAAABS29YJAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJztnXncVFX9x98fFlEWWUQBWTU3MM0lFUsDFwzLvYRMVNQy\nw1SyVCjzOtXPrSyztFJJXErFJc0lFFHTMsVMlERFVExIEBQEVBTk+/vjnHkYludhnoeZuXfm+b5f\nr/uauedun3vn3u898z3f8z0yMxzHcZzapkXaAhzHcZzy48becRynGeDG3nEcpxngxt5xHKcZ4Mbe\ncRynGeDG3nEcpxlQlLGX1EnS7ZJelDRd0l6SukiaJGmGpAcldSpYf6ykVyS9JOmggvLdJU2Ly35V\njhNyHMdx1qbYmv2vgPvNrD+wM/ASMAaYZGbbAZPjPJIGAMOBAcBQ4CpJivv5LXCymW0LbCtpaMnO\nxHEcx6mX9Rp7SR2Bfc3sDwBmtsLM3gMOA66Pq10PHBG/Hw7cbGbLzWwWMBPYS1IPoIOZTYnr3VCw\njeM4jlNGiqnZbwXMl3SdpH9LukZSO6Cbmc2L68wDusXvWwKzC7afDfRcR/mcWO44juOUmWKMfStg\nN+AqM9sNeJ/ossljIeeC511wHMfJKK2KWGc2MNvMno7ztwNjgbmSupvZ3OiieTsunwP0Lti+V9zH\nnPi9sHzOmgeT5C8Nx3GcRmJmWt8K652Ax4Dt4vcLgEvjdG4sGwNcHL8PAKYCGxFcQK8CisueAvYC\nBNwPDF3HsawYTWlOwAVpa3CNrtE1usaCclvftsXU7AFOB/4oa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Xrqqfbhhx/WLb/00kut\nR48e1rNnTxs3bpxJsldffXUt3StXrrQ+ffrYz372s7XKP/3pT9v5559vZmZJktiIESPqlr/++usm\nyVasWGE/+MEPrGXLlrbxxhtb+/bt7fTTT1/nNarGZ8+n1Z69Btfxmn0TKMwpLTEYuJAQYvluWprW\npBpyc1ea+FDwwQcfcOutt7L33nvXLZO03trv3XffzdNPP8306dMxM+bNm8fixYv53//+x7hx4zjt\ntNN4772QQmXMmDHMnDmT5557jpkzZzJnzhx+/OMfAzBx4kQuu+wyHnroIWbMmMFDDz1U7zFffvll\n3nzzTY4++ujVyiXxla98hUmTJjWoWRL/93//x7777suVV17JkiVLuOKKdWYOKCvVcD/WukY39huA\nRHfgZuBYM2akrSfrSKWZmoKZccQRR9C5c2c6derE5MmT+f73v9+ofYwdO5ZOnTrRpk0bAFq3bs35\n559Py5YtOfjgg2nfvj0vv/wyZsY111zDL37xCzp16kT79u0ZO3Yst9xyCwATJkzgpJNOYsCAAbRt\n25ZcLlfvMRcsWABAjx491lrWvXv3uuXFkH/ZOc0T71TVBMzs0Th04HWEPPT1V81SwjLmfwRI09ZI\n4u6772b//ffHzLjrrrsYNGgQL774IltssUVR++jdu/dq85ttthktWqyqL7Vt25alS5cyf/58Pvjg\nA3bfffe6ZWbGypWhx/xbb73FHnvsUbesT58+9R6za9euddv07dt3tWVvvfUWm2++eVHaIV2/fRbv\nxzWpdY1es286pwGbAfVXy5xMIokjjzySli1b8ve//x2Adu3a8f7779etM3fu3HVuVwxdu3Zlk002\nYfr06SxcuJCFCxeyaNEiFi8Ogyj16NGD//73v3XrF35fk+23355evXoxYcKE1cpXrlzJHXfcwQEH\nHFCn/4MPPqhXf9oNtE76uLFvAtLRJxAGUT/WjOVp61kX1eB/rDR5N4aZcffdd7Nw4UL69+8PwC67\n7MKdd97Jhx9+yMyZMzcoTLFFixZ885vfZPTo0cyfPx+AOXPm8OCDDwIwbNgwxo8fz4svvsgHH3zQ\noBtHEj//+c/56U9/ys0338yyZ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DfNBoFPaWqPeQayKxsmURkISq6cJ+U3uJETjZE3jOYSX0DRCw2fr\ntDUS/q39j5Aj503gxIY0EVwTMwkvry+mpPEkQtK4Nwqem6syovGj/HVcY/lrxGictDTWpzPehzfG\n+/IZYHBTdHqnKsdxnGZAVtw4juM4ThlxY+84jtMMcGPvOI7TDHBj7ziO0wxwY+84jtMMcGPvOI7T\nDHBj7ziO0wxwY+84jtMM+H8bqxBDsJagjAAAAABJRU5ErkJggg==\n", + "text/plain": [ + "<matplotlib.figure.Figure at 0x109a3e5f8>" + ] + }, "metadata": {}, - "outputs": [], - "prompt_number": 12 - }, + "output_type": "display_data" + } + ], + "source": [ + "results.plot()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this case, the fire burned itself out after about 90 steps, with many trees left unburned. \n", + "\n", + "You can try changing the density parameter and rerunning the code above, to see how different densities yield different dynamics. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ { - "cell_type": "markdown", + "data": { + "text/plain": [ + "<matplotlib.axes._subplots.AxesSubplot at 0x109e2b470>" + ] + }, + "execution_count": 8, "metadata": {}, - "source": [ - "Like with the data collector, we can extract the data the batch runner collected into a dataframe:" - ] + "output_type": "execute_result" }, { - "cell_type": "code", - "collapsed": false, - "input": [ - "df = param_run.get_model_vars_dataframe()" - ], - "language": "python", + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsnXe4FNX5xz/fexWkF1FABLGAgg1FxRoxikFjbImoUYSI\nRgMWbBHUOHfsIWLUWJKfDUsEscQuggajiQUbSkREoqggIChVQCnv748ze1kul1t3d3Znz+d55tmZ\nM+377uy+e/Y957xHZobH4/F4kklJ3AI8Ho/Hkz28k/d4PJ4E4528x+PxJBjv5D0ejyfBeCfv8Xg8\nCcY7eY/H40kw1T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0ZlSXNxg3I9WCojVGUrb9RTuWCt11SU+Bx4HwzW+oGUzqSYKO5wTM9\nJLUAXpR0SIX9BW2jXHqGb8zs/Y1NFlLoNkYcYGZzJG0BTJA0LX1nQmzcgHypyc8GOqZtd8TV5pPI\nPMmlLJXUHjccumCRtCnOwT9oZk9GxYmyMYWZLcZlIOxJsmzcHzha0ufAaOCnkh4kWTZiZnOi1/nA\nP3Bh4kTZWBn54uTfAbpI6iyX2+NE4OmYNf1/O3eM0kAUBnH8P5aKjdha5ACeIZWCjWWwkRzCSi+Q\nwsYLpBIRrNQDpPACgoK1rZ03GIu3kjSxiSHLx/xgYWG32GmG5e3bb12egXF3PgYe/7i319Re2afA\nh+2bhUuVMu7/7rhQm+NzBLxSKKPtK9sHtgfAGTCzfU6hjJK2Je125zvAMfBOoYzL9GafvKQT5nPm\np7YnG36klUm6B4a0WRdftJnUT8ADbUjRJzCy/b2pZ1xFt8vkBXhjvuR2SfuTuUrGQ9oHua3uuLV9\nLWmPIhkXSRoCF7ZPK2WUNKC9vUNbpr6zPamUcZnelHxERPy/vizXRETEGqTkIyIKS8lHRBSWko+I\nKCwlHxFRWEo+IqKwlHxERGEp+YiIwn4A7VrCBdJQ0o4AAAAASUVORK5CYII=\n", + "text/plain": [ + "<matplotlib.figure.Figure at 0x109a3e5c0>" + ] + }, "metadata": {}, - "outputs": [], - "prompt_number": 13 - }, + "output_type": "display_data" + } + ], + "source": [ + "fire = ForestFire(100, 100, 0.8)\n", + "fire.run_model()\n", + "results = fire.dc.get_model_vars_dataframe()\n", + "results.plot()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "... But to really understand how the final outcome varies with density, we can't just tweak the parameter by hand over and over again. We need to do a batch run. \n", + "\n", + "## Batch runs\n", + "\n", + "Batch runs, also called parameter sweeps, allow use to systemically vary the density parameter, run the model, and check the output. Mesa provides a BatchRunner object which takes a model class, a dictionary of parameters and the range of values they can take and runs the model at each combination of these values. We can also give it reporters, which collect some data on the model at the end of each run and store it, associated with the parameters that produced it.\n", + "\n", + "For ease of typing and reading, we'll first create the parameters to vary and the reporter, and then assign them to a new BatchRunner." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "param_set = dict(height=50, # Height and width are constant\n", + " width=50,\n", + " # Vary density from 0.01 to 1, in 0.01 increments:\n", + " density=np.linspace(0,1,101)[1:]) " + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# At the end of each model run, calculate the fraction of trees which are Burned Out\n", + "model_reporter = {\"BurnedOut\": lambda m: (ForestFire.count_type(m, \"Burned Out\") / \n", + " m.schedule.get_agent_count()) }" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Create the batch runner\n", + "param_run = BatchRunner(ForestFire, param_set, model_reporters=model_reporter)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now the BatchRunner, which we've named param_run, is ready to go. To run the model at every combination of parameters (in this case, every density value), just use the **run_all()** method." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "param_run.run_all()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Like with the data collector, we can extract the data the batch runner collected into a dataframe:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df = param_run.get_model_vars_dataframe()" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ { - "cell_type": "code", - "collapsed": false, - "input": [ - "df.head()" - ], - "language": "python", + "data": { + "text/html": [ + "<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n", + "<table border=\"1\" class=\"dataframe\">\n", + " <thead>\n", + " <tr style=\"text-align: right;\">\n", + " <th></th>\n", + " <th>BurnedOut</th>\n", + " <th>Run</th>\n", + " <th>density</th>\n", + " <th>height</th>\n", + " <th>width</th>\n", + " </tr>\n", + " </thead>\n", + " <tbody>\n", + " <tr>\n", + " <th>0</th>\n", + " <td> 0.009288</td>\n", + " <td> 11</td>\n", + " <td> 0.12</td>\n", + " <td> 50</td>\n", + " <td> 50</td>\n", + " </tr>\n", + " <tr>\n", + " <th>1</th>\n", + " <td> 1.000000</td>\n", + " <td> 98</td>\n", + " <td> 0.99</td>\n", + " <td> 50</td>\n", + " <td> 50</td>\n", + " </tr>\n", + " <tr>\n", + " <th>2</th>\n", + " <td> 0.092608</td>\n", + " <td> 48</td>\n", + " <td> 0.49</td>\n", + " <td> 50</td>\n", + " <td> 50</td>\n", + " </tr>\n", + " <tr>\n", + " <th>3</th>\n", + " <td> 0.024691</td>\n", + " <td> 3</td>\n", + " <td> 0.04</td>\n", + " <td> 50</td>\n", + " <td> 50</td>\n", + " </tr>\n", + " <tr>\n", + " <th>4</th>\n", + " <td> 0.060748</td>\n", + " <td> 42</td>\n", + " <td> 0.43</td>\n", + " <td> 50</td>\n", + " <td> 50</td>\n", + " </tr>\n", + " </tbody>\n", + "</table>\n", + "</div>" + ], + "text/plain": [ + " BurnedOut Run density height width\n", + "0 0.009288 11 0.12 50 50\n", + "1 1.000000 98 0.99 50 50\n", + "2 0.092608 48 0.49 50 50\n", + "3 0.024691 3 0.04 50 50\n", + "4 0.060748 42 0.43 50 50" + ] + }, + "execution_count": 14, "metadata": {}, - "outputs": [ - { - "html": [ - "<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n", - "<table border=\"1\" class=\"dataframe\">\n", - " <thead>\n", - " <tr style=\"text-align: right;\">\n", - " <th></th>\n", - " <th>BurnedOut</th>\n", - " <th>Run</th>\n", - " <th>density</th>\n", - " <th>height</th>\n", - " <th>width</th>\n", - " </tr>\n", - " </thead>\n", - " <tbody>\n", - " <tr>\n", - " <th>0</th>\n", - " <td> 0.142256</td>\n", - " <td> 45</td>\n", - " <td> 0.46</td>\n", - " <td> 50</td>\n", - " <td> 50</td>\n", - " </tr>\n", - " <tr>\n", - " <th>1</th>\n", - " <td> 0.946026</td>\n", - " <td> 68</td>\n", - " <td> 0.69</td>\n", - " <td> 50</td>\n", - " <td> 50</td>\n", - " </tr>\n", - " <tr>\n", - " <th>2</th>\n", - " <td> 0.978022</td>\n", - " <td> 71</td>\n", - " <td> 0.72</td>\n", - " <td> 50</td>\n", - " <td> 50</td>\n", - " </tr>\n", - " <tr>\n", - " <th>3</th>\n", - " <td> 0.027190</td>\n", - " <td> 12</td>\n", - " <td> 0.13</td>\n", - " <td> 50</td>\n", - " <td> 50</td>\n", - " </tr>\n", - " <tr>\n", - " <th>4</th>\n", - " <td> 0.082645</td>\n", - " <td> 43</td>\n", - " <td> 0.44</td>\n", - " <td> 50</td>\n", - " <td> 50</td>\n", - " </tr>\n", - " </tbody>\n", - "</table>\n", - "</div>" - ], - "metadata": {}, - "output_type": "pyout", - "prompt_number": 14, - "text": [ - " BurnedOut Run density height width\n", - "0 0.142256 45 0.46 50 50\n", - "1 0.946026 68 0.69 50 50\n", - "2 0.978022 71 0.72 50 50\n", - "3 0.027190 12 0.13 50 50\n", - "4 0.082645 43 0.44 50 50" - ] - } - ], - "prompt_number": 14 - }, + "output_type": "execute_result" + } + ], + "source": [ + "df.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As you can see, each row here is a run of the model, identified by its parameter values (and given a unique index by the Run column). To view how the BurnedOut fraction varies with density, we can easily just plot them:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ { - "cell_type": "markdown", + "data": { + "text/plain": [ + "(0, 1)" + ] + }, + "execution_count": 15, "metadata": {}, - "source": [ - "As you can see, each row here is a run of the model, identified by its parameter values (and given a unique index by the Run column). To view how the BurnedOut fraction varies with density, we can easily just plot them:" - ] + "output_type": "execute_result" }, { - "cell_type": "code", - "collapsed": false, - "input": [ - "plt.scatter(df.density, df.BurnedOut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/jrH4iPA7wJk5t9GxA+B9wKPDaWGS8e8c3OYXT2PAWdG\nxOkRcTxwKcWXwKp2Af8OICLWAz/J6fsBjZM5j0VEvBv4JnB5Zu4bQR2HZc5jkZk/n5lnZOYZFP38\nvzGGoQ/1/kb+DNgQESsiYiXFYN73h1zPYahzLPYCnwQo+7TfC/xgqLVcGuadm0Nr8Wfm4Yi4BthN\nMWJ/Z2buiYiry+V3ZOb9EXFhROwDfgZcOaz6DVOdYwF8CXgncFvZ0j2UmeeMqs6LpeaxaIWafyN7\nI+IBii9FHqX4suTYBX/N/xdfBu6KiKcoGrG/nZmvj6zSiyQivgGcB6yNiBeBGym6/AbOTb/AJUkt\n46MXJallDH5JahmDX5JaxuCXpJYx+CWpZQx+SWoZg1+SWsbgl6SW+f9ehOb1bB9nvQAAAABJRU5E\nrkJggg==\n", + "text/plain": [ + "<matplotlib.figure.Figure at 0x10a095748>" + ] + }, "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 15, - "text": [ - "(0, 1)" - ] - }, - { - "metadata": {}, - "output_type": "display_data", - "png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAGS9JREFUeJzt3X+M3PV95/Hn24Y9bXTHgePKuQAJKUdyORqQQQGnzp03\nl+yuw0lQ7FM5GnJukhbudKRttE0MtS5slKQVulpBNBIBQsASStAphNY5cbv2tRkaI8IFCoYzNsVJ\nkfjRoDikUa9nyfb5fX/MrHd2PDs7M9/dmd35Ph/Sivnu9zPf72e/eF/z2ffnM9+JzESSVB6r+t0B\nSVJvGfySVDIGvySVjMEvSSVj8EtSyRj8klQyhYM/Ir4REW9ExPPz7P9YROyPiOci4vGIuKToOSVJ\n3VuMEf/9wOYW+38M/OvMvAT4InDPIpxTktSlwsGfmd8Hft5i/xOZ+Yva5pPAeUXPKUnqXq9r/J8C\nHu3xOSVJdc7o1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CZ0dEy/cHrFALXovMfCIzf1HbfBI4r8d97JV2/l0AfJrqkuCf9rJzPdbOtfgN4OHM\nfBUgM4/0uI+90s61+FvgrNrjs4CfZeaJHvaxJzLz+8DPWzTpODd7GfznAq/Ubb9a+95CbQYx8Nq5\nFvU+BTy6pD3qnwWvRUScS/WX/q7atwZ1YqqdfxcXAWtq98B6KiI+3rPe9VY71+Je4OKIeB3YD/xu\nj/q23HScm0WWc3aq3V/WxqWdg/hL3vbPFBEfAj4JbFy67vRVO9fiDuCWzMzaEuFBXf7bzrU4E7gM\n+DDwFuCJiPhBZr60pD3rvXauxR8Az2bmSERcCOyNiEsz8++XuG/LUUe52cvgfw04v277fKqvTK3a\nnFf73qBp51pQm9C9F9icma3+1FvJ2rkWlwMPVTOftcBHI+J4Zu7uTRd7pp1r8QpwJDOPAkcj4i+B\nS4FBC/52rsWvAl8GyMwfRcTfAO8BnupJD5ePjnOzl6Wep4CLIuKCiBgCrqP6JrB6u4H/ABARG4C/\ny9n7AQ2SBa9FRLwD+A5wQ2Ye7kMfe2XBa5GZv5yZ78rMd1Gt8/+nAQx9aO935M+AD0bE6oh4C9XJ\nvBd63M9eaOdaHAI+AlCrab8H+HFPe7k8dJybPRvxZ+aJiLgZmKY6Y39fZh6MiJtq++/OzEcj4qqI\nOAz8A/CJXvWvl9q5FsDngXOAu2oj3eOZeUW/+rxU2rwWpdDm78ihiJii+qbIk1TfLDlwwd/mv4s/\nBO6PiP1UB7Gfy8w3+9bpJRIR3wI2AWsj4hXgNqolv65z0zdwSVLJ+NGLklQyBr8klYzBL0klY/BL\nUskY/JJUMga/JJWMwS9JJWPwS1LJ/H90HnxhfKFFXgAAAABJRU5ErkJggg==\n", - "text": [ - "<matplotlib.figure.Figure at 0x10a339828>" - ] - } - ], - "prompt_number": 15 - }, + "output_type": "display_data" + } + ], + "source": [ + "plt.scatter(df.density, df.BurnedOut)\n", + "plt.xlim(0,1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And we see the very clear emergence of a critical value around 0.5, where the model quickly shifts from almost no trees being burned, to almost all of them.\n", + "\n", + "In this case we ran the model only once at each value. However, it's easy to have the BatchRunner execute multiple runs at each parameter combination, in order to generate more statistically reliable results. We do this using the *iteration* argument.\n", + "\n", + "Let's run the model 5 times at each parameter point, and export and plot the results as above." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ { - "cell_type": "markdown", + "data": { + "text/plain": [ + "(0, 1)" + ] + }, + "execution_count": 16, "metadata": {}, - "source": [ - "And we see the very clear emergence of a critical value around 0.5, where the model quickly shifts from almost no trees being burned, to almost all of them.\n", - "\n", - "In this case we ran the model only once at each value. However, it's easy to have the BatchRunner execute multiple runs at each parameter combination, in order to generate more statistically reliable results. We do this using the *iteration* argument.\n", - "\n", - "Let's run the model 5 times at each parameter point, and export and plot the results as above." - ] + "output_type": "execute_result" }, { - "cell_type": "code", - "collapsed": false, - "input": [ - "param_run = BatchRunner(ForestFire, param_set, iterations=5, model_reporters=model_reporter)\n", - "param_run.run_all()\n", - "df = param_run.get_model_vars_dataframe()\n", - "plt.scatter(df.density, df.BurnedOut)\n", - "plt.xlim(0,1)" - ], - "language": "python", + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X+QHOV95/H3V9J6rQWvpF0lOCAwBLBxbGF+XEBnOFif\nLaSQijnDVSgCOYwdgo3JGrQ67MiU0ZUxse+QTHQuDFawUF185nIhPkRCQOTMVlIum7PELwULkGzI\ngYi5SALWoB/sar/3x/O0pmemZ3Z2e3dmdvvzqupS9/TT3c+2dr/9zLefftrcHRERKY5Zra6AiIg0\nlwK/iEjBKPCLiBSMAr+ISMEo8IuIFIwCv4hIweQO/Gb2HTN71cy21Vh/uZk9ZWZPm9kPzezUvMcU\nEZGJm4wW/wZgeZ31PwfOc/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/F7wH3u/jKAu+9uch2bpZFz8c9Ad5zvBva4+0gT69gU7v4PwGt1iow7bjYz\n8B8DvJRafjl+NlaZmRjwGjkXaZ8GHpzSGrXOmOfCzI4h/NF/K340U29MNfJ7cTLQE8fA2mJmv9+0\n2jVXI+diPfABM3sFeAr4fJPq1m7GHTfzdOccr0b/WCu7ds7EP/KGfyYz+wjwKeCcqatOSzVyLm4H\nvujuHrsIz9Tuv42ciw7gDOCjQBfwIzP7sbvvmNKaNV8j52IV8KS795nZicAjZvYhd//lFNetHY0r\nbjYz8O8Cjk0tH0u4MtUrsyh+NtM0ci6IN3TXA8vdvd5XvemskXNxJnBviPksBH7LzIbdfVNzqtg0\njZyLl4Dd7r4f2G9mfw98CJhpgb+Rc/Fh4KsA7v4zM3sBeB+wpSk1bB/jjpvNTPVsAU42s+PN7B3A\npYSHwNI2Af8BwMyWAK97aTygmWTMc2FmxwF/BVzh7jtbUMdmGfNcuPuvu/sJ7n4CIc//2RkY9KGx\nv5H7gXPNbLaZdRFu5v20yfVshkbOxbPAxwBiTvt9wM+bWsv2MO642bQWv7uPmNl1wMOEO/Z3u/t2\nM7smrr/L3R80swvNbCfwFnBVs+rXTI2cC+DLwALgW7GlO+zuZ7WqzlOlwXNRCA3+jTxrZg8RHooc\nJTwsOeMCf4O/F7cCG8zsKUIj9kZ339uySk8RM/secD6w0MxeAm4mpPwmHDf1AJeISMHo1YsiIgWj\nwC8iUjAK/CIiBaPALyJSMAr8IiIFo8AvIlIwCvwiIgWjwC8iUjD/H15+d1SmsbWuAAAAAElFTkSu\nQmCC\n", + "text/plain": [ + "<matplotlib.figure.Figure at 0x10a417710>" + ] + }, "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 16, - "text": [ - "(0, 1)" - ] - }, - { - "metadata": {}, - "output_type": "display_data", - "png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALE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XsAM4yszPMLA18gOAmsLge4E8AzGwZ8Esfng9oOhnxXJjZIuBbwLXuvr8KdayUEc+F\nu5/p7m909zcS5Pn/bBoGfSjtb+T/AO80s3ozm0XQmfejCtezEko5F/uAywDCnPbZwMGK1nJyGHXc\nrFiL390HzexGoJegx/5r7v6smd0Qbr/H3R8xsyvMbD/wn8B1lapfJZVyLoDPAPOBr4Yt3dfc/eJq\n1XmilHguakKJfyP7zGwrwU2Rxwhulpx2gb/EfxefA+43sz0Ejdib3L2/apWeIGb2D8ByoNHMXgA+\nS5DyG3Pc1A1cIiI1Ro9eFBGpMQr8IiI1RoFfRKTGKPCLiNQYBX4RkRqjwC8iUmMU+EVEaowCv4hI\njfn/vIVXkfM6S7gAAAAASUVORK5CYII=\n", - "text": [ - "<matplotlib.figure.Figure at 0x109eb1be0>" - ] - } - ], - "prompt_number": 16 + "output_type": "display_data" } ], - "metadata": {} + "source": [ + "param_run = BatchRunner(ForestFire, param_set, iterations=5, model_reporters=model_reporter)\n", + "param_run.run_all()\n", + "df = param_run.get_model_vars_dataframe()\n", + "plt.scatter(df.density, df.BurnedOut)\n", + "plt.xlim(0,1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] } - ] -} \ No newline at end of file + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.2" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/examples/ForestFire/Forest Fire Model.ipynb b/examples/ForestFire/Forest Fire Model.ipynb index 8c8746c5..72b54805 100644 --- a/examples/ForestFire/Forest Fire Model.ipynb +++ b/examples/ForestFire/Forest Fire Model.ipynb @@ -1,584 +1,621 @@ { - "metadata": { - "name": "", - "signature": "sha256:7ad05bb257a0bc7d9176a2a5e02312695873a50206c8335653a47975f4e4ee8c" - }, - "nbformat": 3, - "nbformat_minor": 0, - "worksheets": [ + "cells": [ { - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# The Forest Fire Model\n", - "## A rapid introduction to Mesa\n", - "\n", - "The [Forest Fire Model](http://en.wikipedia.org/wiki/Forest-fire_model) is one of the simplest examples of a model that exhibits self-organized criticality.\n", - "\n", - "Mesa is a new, Pythonic agent-based modeling framework. A big advantage of using Python is that it a great language for interactive data analysis. Unlike some other ABM frameworks, with Mesa you can write a model, run it, and analyze it all in the same environment. (You don't have to, of course. But you can).\n", - "\n", - "In this notebook, we'll go over a rapid-fire (pun intended, sorry) introduction to building and analyzing a model with Mesa." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "First, some imports. We'll go over what all the Mesa ones mean just below." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "import random\n", - "\n", - "import numpy as np\n", - "\n", - "import matplotlib.pyplot as plt\n", - "%matplotlib inline\n", - "\n", - "from mesa import Model, Agent\n", - "from mesa.time import RandomActivation\n", - "from mesa.space import Grid\n", - "from mesa.datacollection import DataCollector\n", - "from mesa.batchrunner import BatchRunner " - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 1 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Building the model\n", - "\n", - "Most models consist of basically two things: agents, and an world for the agents to be in. The Forest Fire model has only one kind of agent: a tree. A tree can either be unburned, on fire, or already burned. The environment is a grid, where each cell can either be empty or contain a tree.\n", - "\n", - "First, let's define our tree agent. The agent needs to be assigned **x** and **y** coordinates on the grid, and that's about it. We could assign agents a condition to be in, but for now let's have them all start as being 'Fine'. Since the agent doesn't move, and there is only at most one tree per cell, we can use a tuple of its coordinates as a unique identifier.\n", - "\n", - "Next, we define the agent's **step** method. This gets called whenever the agent needs to act in the world and takes the *model* object to which it belongs as an input. The tree's behavior is simple: If it is currently on fire, it spreads the fire to any trees above, below, to the left and the right of it that are not themselves burned out or on fire; then it burns itself out. " - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "class TreeCell(Agent):\n", - " '''\n", - " A tree cell.\n", - " \n", - " Attributes:\n", - " x, y: Grid coordinates\n", - " condition: Can be \"Fine\", \"On Fire\", or \"Burned Out\"\n", - " unique_id: (x,y) tuple. \n", - " \n", - " unique_id isn't strictly necessary here, but it's good practice to give one to each\n", - " agent anyway.\n", - " '''\n", - " def __init__(self, x, y):\n", - " '''\n", - " Create a new tree.\n", - " Args:\n", - " x, y: The tree's coordinates on the grid.\n", - " '''\n", - " self.x = x\n", - " self.y = y\n", - " self.unique_id = (x, y)\n", - " self.condition = \"Fine\"\n", - " \n", - " def step(self, model):\n", - " '''\n", - " If the tree is on fire, spread it to fine trees nearby.\n", - " '''\n", - " if self.condition == \"On Fire\":\n", - " neighbors = model.grid.get_neighbors(self.x, self.y, moore=False)\n", - " for neighbor in neighbors:\n", - " if neighbor.condition == \"Fine\":\n", - " neighbor.condition = \"On Fire\"\n", - " self.condition = \"Burned Out\"\n", - " " - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 2 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now we need to define the model object itself. The main thing the model needs is the grid, which the trees are placed on. But since the model is dynamic, it also needs to include time -- it needs a schedule, to manage the trees activation as they spread the fire from one to the other.\n", - "\n", - "The model also needs a few parameters: how large the grid is and what the density of trees on it will be. Density will be the key parameter we'll explore below.\n", - "\n", - "Finally, we'll give the model a data collector. This is a Mesa object which collects and stores data on the model as it runs for later analysis.\n", - "\n", - "The constructor needs to do a few things. It instantiates all the model-level variables and objects; it randomly places trees on the grid, based on the density parameter; and it starts the fire by setting all the trees on one edge of the grid (x=0) as being On \"Fire\".\n", - "\n", - "Next, the model needs a **step** method. Like at the agent level, this method defines what happens every step of the model. We want to activate all the trees, one at a time; then we run the data collector, to count how many trees are currently on fire, burned out, or still fine. If there are no trees left on fire, we stop the model by setting its **running** property to False." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "class ForestFire(Model):\n", - " '''\n", - " Simple Forest Fire model.\n", - " '''\n", - " def __init__(self, height, width, density):\n", - " '''\n", - " Create a new forest fire model.\n", - " \n", - " Args:\n", - " height, width: The size of the grid to model\n", - " density: What fraction of grid cells have a tree in them.\n", - " '''\n", - " # Initialize model parameters\n", - " self.height = height\n", - " self.width = width\n", - " self.density = density\n", - " \n", - " # Set up model objects\n", - " self.schedule = RandomActivation(self)\n", - " self.grid = Grid(height, width, torus=False)\n", - " self.dc = DataCollector({\"Fine\": lambda m: self.count_type(m, \"Fine\"),\n", - " \"On Fire\": lambda m: self.count_type(m, \"On Fire\"),\n", - " \"Burned Out\": lambda m: self.count_type(m, \"Burned Out\")})\n", - " \n", - " # Place a tree in each cell with Prob = density\n", - " for x in range(self.width):\n", - " for y in range(self.height):\n", - " if random.random() < self.density:\n", - " # Create a tree\n", - " new_tree = TreeCell(x, y)\n", - " # Set all trees in the first column on fire.\n", - " if x == 0:\n", - " new_tree.condition = \"On Fire\"\n", - " self.grid[y][x] = new_tree\n", - " self.schedule.add(new_tree)\n", - " self.running = True\n", - " \n", - " def step(self):\n", - " '''\n", - " Advance the model by one step.\n", - " '''\n", - " self.schedule.step()\n", - " self.dc.collect(self)\n", - " # Halt if no more fire\n", - " if self.count_type(self, \"On Fire\") == 0:\n", - " self.running = False\n", - " \n", - " @staticmethod\n", - " def count_type(model, tree_condition):\n", - " '''\n", - " Helper method to count trees in a given condition in a given model.\n", - " '''\n", - " count = 0\n", - " for tree in model.schedule.agents:\n", - " if tree.condition == tree_condition:\n", - " count += 1\n", - " return count" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 3 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Running the model\n", - "\n", - "Let's create a model with a 100 x 100 grid, and a tree density of 0.6. Remember, ForestFire takes the arguments *height*, *width*, *density*." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "fire = ForestFire(100, 100, 0.6)" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 4 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To run the model until it's done (that is, until it sets its **running** property to False) just use the **run_model()** method. This is implemented in the Model parent object, so we didn't need to implement it above." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "fire.run_model()" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 5 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "That's all there is to it!\n", - "\n", - "But... so what? This code doesn't include a visualization, after all. \n", - "\n", - "**TODO: Add a MatPlotLib visualization**\n", - "\n", - "Remember the data collector? Now we can put the data it collected into a pandas DataFrame:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "results = fire.dc.get_model_vars_dataframe()" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 6 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And chart it, to see the dynamics." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "results.plot()" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 7, - "text": [ - "<matplotlib.axes._subplots.AxesSubplot at 0x10988b2e8>" - ] - }, - { - "metadata": {}, - "output_type": "display_data", - "png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl4VOXZ+PHvnYXsGwmEsAZe2UFBlKXCS0Tpixa3umHF\nithWi1KXqgVtxbZuuLVqtfWnCC51wV0REETSugIqASRsAYMQISQhC0kI2Z7fH89MMoFAAiSZc4b7\nc13nmjlnzsx57szkPs/c55lzxBiDUkqpwBTk7wYopZRqPZrklVIqgGmSV0qpAKZJXimlApgmeaWU\nCmCa5JVSKoA1K8mLSLyIvCkiG0QkU0RGiEh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HfD9ubdKldEOgGISAqwx8/taRYRCcUm+JeMMe96FrsyFgBjTDHwITAM98XxE+B8\nEfkeeBUYJyIv4b44MMbs8tzmAe9gz2Hltjh2AjuNMas8829ik/5up8fhlCT/NdBbRFJFpB1wOfC+\nn9t0PN4Hrvbcvxpb33Y0ERFgDpBpjPm7z0OuikVEkrwjHEQkAhgPrMZlcRhj7jTGdDPG9AQmAZ8Y\nY67CZXGISKSIxHjuRwE/BdbhsjiMMbuBHSLSx7PobGA98AFOj8PfBwV8DmCcg/01bBYw09/tOYp2\nv4r99W4l9rjCNUB77AGzzcASIN7f7WxGHKOxtd8MbFJcjR015KpYgMHAt5441gK3e5a7Ko6DYhoL\nvO/GOLC17AzP9J33f9ttcXjafAr2QP4a4G3swVjHx6E/hlJKqQDmlHKNUkqpVqBJXimlApgmeaWU\nCmCa5JVSKoBpkldKqQCmSV4ppQKYJnmllApgmuSVUiqA/X9Qq9l5Pb7B1AAAAABJRU5ErkJggg==\n", - "text": [ - "<matplotlib.figure.Figure at 0x10987db70>" - ] - } - ], - "prompt_number": 7 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this case, the fire burned itself out after about 90 steps, with many trees left unburned. \n", - "\n", - "You can try changing the density parameter and rerunning the code above, to see how different densities yield different dynamics. For example:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "fire = ForestFire(100, 100, 0.8)\n", - "fire.run_model()\n", - "results = fire.dc.get_model_vars_dataframe()\n", - "results.plot()" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 8, - "text": [ - "<matplotlib.axes._subplots.AxesSubplot at 0x109c54208>" - ] - }, - { - "metadata": {}, - "output_type": "display_data", - "png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsnXd4FNX3h9+ThN5CkYC0oPTeq0C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Avry9Dzhyjc9uWEqn7JPAgu0PCoca\nn1/Slu7sCUk3Ak8Bc7Qgu+23bQ/b3g68CMzafokWZAeQdJOkW/P2zcDTwBkqyF+befKSnmHlOfOT\ntid63KXSSDoM7Aa2kMbh3gG+AD4F7gE6wAu2N+abg68hzyb5FjjNyjDdAdLq50bnl/Qg6eZaX/6Z\nsv2epM00PHuRpN3AG7bH2pJd0nbS2TukYfJPbE9Ukb82RT6EEML6q8twTQghhBJEkQ8hhAaLIh9C\nCA0WRT6EEBosinwIITRYFPkQQmiwKPIhhNBgUeRDCKHB/gXedjkAMUGImgAAAABJRU5ErkJggg==\n", - "text": [ - "<matplotlib.figure.Figure at 0x109c517b8>" - ] - } - ], - "prompt_number": 8 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "... But to really understand how the final outcome varies with density, we can't just tweak the parameter by hand over and over again. We need to do a batch run. \n", - "\n", - "## Batch runs\n", - "\n", - "Batch runs, also called parameter sweeps, allow use to systemically vary the density parameter, run the model, and check the output. Mesa provides a BatchRunner object which takes a model class, a dictionary of parameters and the range of values they can take and runs the model at each combination of these values. We can also give it reporters, which collect some data on the model at the end of each run and store it, associated with the parameters that produced it.\n", - "\n", - "For ease of typing and reading, we'll first create the parameters to vary and the reporter, and then assign them to a new BatchRunner." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "param_set = dict(height=50, # Height and width are constant\n", - " width=50,\n", - " # Vary density from 0.01 to 1, in 0.01 increments:\n", - " density=np.linspace(0,1,101)[1:]) " - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 9 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "# At the end of each model run, calculate the fraction of trees which are Burned Out\n", - "model_reporter = {\"BurnedOut\": lambda m: (ForestFire.count_type(m, \"Burned Out\") / \n", - " m.schedule.get_agent_count()) }" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 10 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "# Create the batch runner\n", - "param_run = BatchRunner(ForestFire, param_set, model_reporters=model_reporter)" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 11 - }, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# The Forest Fire Model\n", + "## A rapid introduction to Mesa\n", + "\n", + "The [Forest Fire Model](http://en.wikipedia.org/wiki/Forest-fire_model) is one of the simplest examples of a model that exhibits self-organized criticality.\n", + "\n", + "Mesa is a new, Pythonic agent-based modeling framework. A big advantage of using Python is that it a great language for interactive data analysis. Unlike some other ABM frameworks, with Mesa you can write a model, run it, and analyze it all in the same environment. (You don't have to, of course. But you can).\n", + "\n", + "In this notebook, we'll go over a rapid-fire (pun intended, sorry) introduction to building and analyzing a model with Mesa." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "First, some imports. We'll go over what all the Mesa ones mean just below." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import random\n", + "\n", + "import numpy as np\n", + "\n", + "import matplotlib.pyplot as plt\n", + "%matplotlib inline\n", + "\n", + "from mesa import Model, Agent\n", + "from mesa.time import RandomActivation\n", + "from mesa.space import Grid\n", + "from mesa.datacollection import DataCollector\n", + "from mesa.batchrunner import BatchRunner " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Building the model\n", + "\n", + "Most models consist of basically two things: agents, and an world for the agents to be in. The Forest Fire model has only one kind of agent: a tree. A tree can either be unburned, on fire, or already burned. The environment is a grid, where each cell can either be empty or contain a tree.\n", + "\n", + "First, let's define our tree agent. The agent needs to be assigned **x** and **y** coordinates on the grid, and that's about it. We could assign agents a condition to be in, but for now let's have them all start as being 'Fine'. Since the agent doesn't move, and there is only at most one tree per cell, we can use a tuple of its coordinates as a unique identifier.\n", + "\n", + "Next, we define the agent's **step** method. This gets called whenever the agent needs to act in the world and takes the *model* object to which it belongs as an input. The tree's behavior is simple: If it is currently on fire, it spreads the fire to any trees above, below, to the left and the right of it that are not themselves burned out or on fire; then it burns itself out. " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class TreeCell(Agent):\n", + " '''\n", + " A tree cell.\n", + " \n", + " Attributes:\n", + " x, y: Grid coordinates\n", + " condition: Can be \"Fine\", \"On Fire\", or \"Burned Out\"\n", + " unique_id: (x,y) tuple. \n", + " \n", + " unique_id isn't strictly necessary here, but it's good practice to give one to each\n", + " agent anyway.\n", + " '''\n", + " def __init__(self, x, y):\n", + " '''\n", + " Create a new tree.\n", + " Args:\n", + " x, y: The tree's coordinates on the grid.\n", + " '''\n", + " self.x = x\n", + " self.y = y\n", + " self.unique_id = (x, y)\n", + " self.condition = \"Fine\"\n", + " \n", + " def step(self, model):\n", + " '''\n", + " If the tree is on fire, spread it to fine trees nearby.\n", + " '''\n", + " if self.condition == \"On Fire\":\n", + " neighbors = model.grid.get_neighbors(self.x, self.y, moore=False)\n", + " for neighbor in neighbors:\n", + " if neighbor.condition == \"Fine\":\n", + " neighbor.condition = \"On Fire\"\n", + " self.condition = \"Burned Out\"\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we need to define the model object itself. The main thing the model needs is the grid, which the trees are placed on. But since the model is dynamic, it also needs to include time -- it needs a schedule, to manage the trees activation as they spread the fire from one to the other.\n", + "\n", + "The model also needs a few parameters: how large the grid is and what the density of trees on it will be. Density will be the key parameter we'll explore below.\n", + "\n", + "Finally, we'll give the model a data collector. This is a Mesa object which collects and stores data on the model as it runs for later analysis.\n", + "\n", + "The constructor needs to do a few things. It instantiates all the model-level variables and objects; it randomly places trees on the grid, based on the density parameter; and it starts the fire by setting all the trees on one edge of the grid (x=0) as being On \"Fire\".\n", + "\n", + "Next, the model needs a **step** method. Like at the agent level, this method defines what happens every step of the model. We want to activate all the trees, one at a time; then we run the data collector, to count how many trees are currently on fire, burned out, or still fine. If there are no trees left on fire, we stop the model by setting its **running** property to False." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class ForestFire(Model):\n", + " '''\n", + " Simple Forest Fire model.\n", + " '''\n", + " def __init__(self, height, width, density):\n", + " '''\n", + " Create a new forest fire model.\n", + " \n", + " Args:\n", + " height, width: The size of the grid to model\n", + " density: What fraction of grid cells have a tree in them.\n", + " '''\n", + " # Initialize model parameters\n", + " self.height = height\n", + " self.width = width\n", + " self.density = density\n", + " \n", + " # Set up model objects\n", + " self.schedule = RandomActivation(self)\n", + " self.grid = Grid(height, width, torus=False)\n", + " self.dc = DataCollector({\"Fine\": lambda m: self.count_type(m, \"Fine\"),\n", + " \"On Fire\": lambda m: self.count_type(m, \"On Fire\"),\n", + " \"Burned Out\": lambda m: self.count_type(m, \"Burned Out\")})\n", + " \n", + " # Place a tree in each cell with Prob = density\n", + " for x in range(self.width):\n", + " for y in range(self.height):\n", + " if random.random() < self.density:\n", + " # Create a tree\n", + " new_tree = TreeCell(x, y)\n", + " # Set all trees in the first column on fire.\n", + " if x == 0:\n", + " new_tree.condition = \"On Fire\"\n", + " self.grid[y][x] = new_tree\n", + " self.schedule.add(new_tree)\n", + " self.running = True\n", + " \n", + " def step(self):\n", + " '''\n", + " Advance the model by one step.\n", + " '''\n", + " self.schedule.step()\n", + " self.dc.collect(self)\n", + " # Halt if no more fire\n", + " if self.count_type(self, \"On Fire\") == 0:\n", + " self.running = False\n", + " \n", + " @staticmethod\n", + " def count_type(model, tree_condition):\n", + " '''\n", + " Helper method to count trees in a given condition in a given model.\n", + " '''\n", + " count = 0\n", + " for tree in model.schedule.agents:\n", + " if tree.condition == tree_condition:\n", + " count += 1\n", + " return count" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Running the model\n", + "\n", + "Let's create a model with a 100 x 100 grid, and a tree density of 0.6. Remember, ForestFire takes the arguments *height*, *width*, *density*." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fire = ForestFire(100, 100, 0.6)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To run the model until it's done (that is, until it sets its **running** property to False) just use the **run_model()** method. This is implemented in the Model parent object, so we didn't need to implement it above." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fire.run_model()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "That's all there is to it!\n", + "\n", + "But... so what? This code doesn't include a visualization, after all. \n", + "\n", + "**TODO: Add a MatPlotLib visualization**\n", + "\n", + "Remember the data collector? Now we can put the data it collected into a pandas DataFrame:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "results = fire.dc.get_model_vars_dataframe()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And chart it, to see the dynamics." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [ { - "cell_type": "markdown", + "data": { + "text/plain": [ + "<matplotlib.axes._subplots.AxesSubplot at 0x109a3eda0>" + ] + }, + "execution_count": 7, "metadata": {}, - "source": [ - "Now the BatchRunner, which we've named param_run, is ready to go. To run the model at every combination of parameters (in this case, every density value), just use the **run_all()** method." - ] + "output_type": "execute_result" }, { - "cell_type": "code", - "collapsed": false, - "input": [ - "param_run.run_all()" - ], - "language": "python", + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXsAAAEACAYAAABS29YJAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJztnXncVFX9x98fFlEWWUQBWTU3MM0lFUsDFwzLvYRMVNQy\nw1SyVCjzOtXPrSyztFJJXErFJc0lFFHTMsVMlERFVExIEBQEVBTk+/vjnHkYludhnoeZuXfm+b5f\nr/uauedun3vn3u898z3f8z0yMxzHcZzapkXaAhzHcZzy48becRynGeDG3nEcpxngxt5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jPyCeNeMOOsigtbTYv77KuJFi1aMHPmTLbeOr0svu6z\nT19jDAX9LHA88DVCWvgnCe6e+7iAPZvqs/cxaEuERAtCY+xHwDkpy3HWoF+/frRt25YOHTrQpUsX\nDjnkEGbPrp6R7+6991723HNP2rdvT9euXRkxYgRz5swpevvBgwczbty4Mip0SoElZpbY05bY6YTG\n3W8Tony+AfyPYVwUE8Cdq5yOUU4HKKf9itm3G/smUM/b/yJga0LkzYrKKlqbtGsoWUMS9957L0uW\nLOGtt96iW7dunH766U3a14oVlf15b7/9do499ljOOuss3nnnHV544QXatGnDPvvsw6JFxY3aJ6X7\nZ7ka7sesabTEPrbEnrTEfmmJfRHYjgFcDLwEdCWM9HcecH5xOzTL1BQkpa+jcZrtZLAZYF3S1pKB\n3y6T9OvXzyZPnlw3f99999l2221XNz9o0CC79tpr6+avu+4622effermJdmVV15p22yzjW299db2\n6KOPWs+ePe2yyy6zLbbYwnr06GHXXXdd3frLli2z733ve9anTx/r1q2bnXrqqfbhhx/WLb/00kut\nR48e1rNnTxs3bpxJsldffXUt3StXrrQ+ffrYz372s7XKP/3pT9v5559vZmZJktiIESPqlr/++usm\nyVasWGE/+MEPrGXLlrbxxhtb+/bt7fTTT1/nNarGZ8+n1Z69Btfxmn0TKMwpLTEYuJAQYvluWprW\npBpyc1ea+FDwwQcfcOutt7L33nvXLZO03trv3XffzdNPP8306dMxM+bNm8fixYv53//+x7hx4zjt\ntNN4772QQmXMmDHMnDmT5557jpkzZzJnzhx+/OMfAzBx4kQuu+wyHnroIWbMmMFDDz1U7zFffvll\n3nzzTY4++ujVyiXxla98hUmTJjWoWRL/93//x7777suVV17JkiVLuOKKdWYOKCvVcD/WukY39huA\nRHfgZuBYM2akrSfrSKWZmoKZccQRR9C5c2c6derE5MmT+f73v9+ofYwdO5ZOnTrRpk0bAFq3bs35\n559Py5YtOfjgg2nfvj0vv/wyZsY111zDL37xCzp16kT79u0ZO3Yst9xyCwATJkzgpJNOYsCAAbRt\n25ZcLlfvMRcsWABAjx491lrWvXv3uuXFkH/ZOc0T71TVBMzs0Th04HWEPPT1V81SwjLmfwRI09ZI\n4u6772b//ffHzLjrrrsYNGgQL774IltssUVR++jdu/dq85ttthktWqyqL7Vt25alS5cyf/58Pvjg\nA3bfffe6ZWbGypWhx/xbb73FHnvsUbesT58+9R6za9euddv07dt3tWVvvfUWm2++eVHaIV2/fRbv\nxzWpdY1es286pwGbAfVXy5xMIokjjzySli1b8ve//x2Adu3a8f7779etM3fu3HVuVwxdu3Zlk002\nYfr06SxcuJCFCxeyaNEiFi8Ogyj16NGD//73v3XrF35fk+23355evXoxYcKE1cpXrlzJHXfcwQEH\nHFCn/4MPPqhXf9oNtE76uLFvAtLRJxAGUT/WjOVp61kX1eB/rDR5N4aZcffdd7Nw4UL69+8PwC67\n7MKdd97Jhx9+yMyZMzcoTLFFixZ885vfZPTo0cyfPx+AOXPm8OCDDwIwbNgwxo8fz4svvsgHH3zQ\noBtHEj//+c/56U9/ys0338yyZcuYO3cu3/jGN1i6dCnf/e53Adh111157LHHePPNN3nvvfe46KKL\nVttPt27dePXVV5t8ThtKNdyPta7RjX0jkWgDI38EjDXDR7evIg499FA6dOhAx44d+dGPfsQNN9xQ\nZ+y/+93vstFGG9GtWzdOPPFERowYsVpteF0144Zqy5dccgnbbLMNAwcOpGPHjgwZMoQZM0KzztCh\nQxk9ejT7778/2223HQcccECD+xo2bBg33ngjv/zlL+natSs77rgjH330Ef/4xz/o3LkzAAceeCDD\nhw9n5513Zo899uDQQw9dbZ9nnnkmt99+O126dGH06NGNu3BOTeA9aBuJxM+BTwFHmfmA4IV4D9rq\nxtMlVC+e9bLESBwAHAN8xg294zjVhLtxiiQmOBsPnAj6dMpy1ks1+B+d5kM13I+1rtGNffH8Drjd\njAfTFuI4jtNY3GdfBBJfINTqB5hR1gEGqhn32Vc37rOvXjzrZQmInad+AvzYDb3jONWKG/v1cwBh\nSLGb8gW17ttznFJTDfdjrWt0Y98ABbX6nGUgbbHjOE5TcZ99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IxhSukrVHSp4DRhL/DWwLtJY0oXCdtjeui\nCE2p6pX0Q+BjM/tTA6tVXKOktsAPgKSwuIFN0n5+OpvZQEKlbkID69arMyvGfg7Bd5anN6u/sVJD\noTv/HcCNZnZXLJ4nqXtc3oPQizAtPgccJul14GZgf0k3ZkzjbEIN6uk4fzvB+M/NkMbPAk+Y2TsW\nuqXfCeydMY156vtt13yOesWyVJA0kuBePLagOCsa8z2pn4vPTi/gGUndyI7GPLMJ9yPxGVopqSuN\n1JkVY/8vYFtJ/RRSDwwH/pKyJiQJGAdMN7PLCxb9hdB4R/y8a81tK4WZ/cDMepvZVsDXgIfN7LiM\naZwLvClpu1h0IKHb+z1kRCMhB9JASZvE3/1AYDrZ0pinvt/2L8DXJG0kaSvC3/8pKehD0lBCLfRw\nMyvszp8JjWY2zcy6mdlW8dmZDewW3WOZ0FjAXYQUK8RnaCMzW0BjdVaihbnIVuiDCdEuM4GxaeuJ\nmvYh+MGnEpKjPUvIj9IFeIiQDfNBoFPaWqPeQayKxsmURkISq6cJ+U3uJETjZE3jOYSX0DRCw2fr\ntDUS/q39j5Aj503gxIY0EVwTMwkvry+mpPEkQtK4Nwqem6syovGj/HVcY/lrxGictDTWpzPehzfG\n+/IZYHBTdHqnKsdxnGZAVtw4juM4ThlxY+84jtMMcGPvOI7TDHBj7ziO0wxwY+84jtMMcGPvOI7T\nDHBj7ziO0wxwY+84jtMM+H8bqxBDsJagjAAAAABJRU5ErkJggg==\n", + "text/plain": [ + "<matplotlib.figure.Figure at 0x109a3e5f8>" + ] + }, "metadata": {}, - "outputs": [], - "prompt_number": 12 - }, + "output_type": "display_data" + } + ], + "source": [ + "results.plot()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this case, the fire burned itself out after about 90 steps, with many trees left unburned. \n", + "\n", + "You can try changing the density parameter and rerunning the code above, to see how different densities yield different dynamics. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ { - "cell_type": "markdown", + "data": { + "text/plain": [ + "<matplotlib.axes._subplots.AxesSubplot at 0x109e2b470>" + ] + }, + "execution_count": 8, "metadata": {}, - "source": [ - "Like with the data collector, we can extract the data the batch runner collected into a dataframe:" - ] + "output_type": "execute_result" }, { - "cell_type": "code", - "collapsed": false, - "input": [ - "df = param_run.get_model_vars_dataframe()" - ], - "language": "python", + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXkAAAEACAYAAABWLgY0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsnXe4FNX5xz/fexWkF1FABLGAgg1FxRoxikFjbImoUYSI\nRgMWbBHUOHfsIWLUWJKfDUsEscQuggajiQUbSkREoqggIChVQCnv748ze1kul1t3d3Znz+d55tmZ\nM+377uy+e/Y957xHZobH4/F4kklJ3AI8Ho/Hkz28k/d4PJ4E4528x+PxJBjv5D0ejyfBeCfv8Xg8\nCcY7eY/H40kw1Tp5ScMlfSRpiqSHJTWU1FrSBEnTJY2X1LLC8Z9Kmibp8LTyntE1PpV0S7YM8ng8\nHs86qnTykjoDZwJ7mtmuQClwEjAMmGBmXYGXo20kdQdOBLoDfYE7JCm63J3AIDPrAnSR1Dfj1ng8\nHo9nPaqryS8BVgGNJW0CNAa+Bo4G7o+OuR84Nlo/BhhtZqvMbCYwA+glqT3QzMwmRcc9kHaOx+Px\neLJElU7ezL4DRgJf4pz7IjObALQ1s3nRYfOAttH6VsCstEvMAjpUUj47Kvd4PB5PFqkuXLM9MBTo\njHPUTSWdmn6MubwIPjeCx+Px5CGbVLN/L+B1M/sWQNITwH7AXEntzGxuFIr5Jjp+NtAx7fytcTX4\n2dF6evnsym4oyf9geDweTy0xM1VWXp2Tnwb8QVIjYCVwGDAJ+B4YAPwxen0yOv5p4GFJN+HCMV2A\nSWZmkpZI6hWd3x+4tbZik4CkMjMri1tHNvE2Fj5Jtw/itVFCQAucn2wPtI6WVhXWW1RYmgMNgbW4\n9t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SRoCF7ZPK2WUNKC9vUNbpr6zPamUcZnelHxERPy/vizXRETEGqTkIyIKS8lHRBSWko+I\nKCwlHxFRWEo+IqKwlHxERGEp+YiIwn4A7VrCBdJQ0o4AAAAASUVORK5CYII=\n", + "text/plain": [ + "<matplotlib.figure.Figure at 0x109a3e5c0>" + ] + }, "metadata": {}, - "outputs": [], - "prompt_number": 13 - }, + "output_type": "display_data" + } + ], + "source": [ + "fire = ForestFire(100, 100, 0.8)\n", + "fire.run_model()\n", + "results = fire.dc.get_model_vars_dataframe()\n", + "results.plot()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "... But to really understand how the final outcome varies with density, we can't just tweak the parameter by hand over and over again. We need to do a batch run. \n", + "\n", + "## Batch runs\n", + "\n", + "Batch runs, also called parameter sweeps, allow use to systemically vary the density parameter, run the model, and check the output. Mesa provides a BatchRunner object which takes a model class, a dictionary of parameters and the range of values they can take and runs the model at each combination of these values. We can also give it reporters, which collect some data on the model at the end of each run and store it, associated with the parameters that produced it.\n", + "\n", + "For ease of typing and reading, we'll first create the parameters to vary and the reporter, and then assign them to a new BatchRunner." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "param_set = dict(height=50, # Height and width are constant\n", + " width=50,\n", + " # Vary density from 0.01 to 1, in 0.01 increments:\n", + " density=np.linspace(0,1,101)[1:]) " + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# At the end of each model run, calculate the fraction of trees which are Burned Out\n", + "model_reporter = {\"BurnedOut\": lambda m: (ForestFire.count_type(m, \"Burned Out\") / \n", + " m.schedule.get_agent_count()) }" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Create the batch runner\n", + "param_run = BatchRunner(ForestFire, param_set, model_reporters=model_reporter)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now the BatchRunner, which we've named param_run, is ready to go. To run the model at every combination of parameters (in this case, every density value), just use the **run_all()** method." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "param_run.run_all()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Like with the data collector, we can extract the data the batch runner collected into a dataframe:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df = param_run.get_model_vars_dataframe()" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [ { - "cell_type": "code", - "collapsed": false, - "input": [ - "df.head()" - ], - "language": "python", + "data": { + "text/html": [ + "<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n", + "<table border=\"1\" class=\"dataframe\">\n", + " <thead>\n", + " <tr style=\"text-align: right;\">\n", + " <th></th>\n", + " <th>BurnedOut</th>\n", + " <th>Run</th>\n", + " <th>density</th>\n", + " <th>height</th>\n", + " <th>width</th>\n", + " </tr>\n", + " </thead>\n", + " <tbody>\n", + " <tr>\n", + " <th>0</th>\n", + " <td> 0.009288</td>\n", + " <td> 11</td>\n", + " <td> 0.12</td>\n", + " <td> 50</td>\n", + " <td> 50</td>\n", + " </tr>\n", + " <tr>\n", + " <th>1</th>\n", + " <td> 1.000000</td>\n", + " <td> 98</td>\n", + " <td> 0.99</td>\n", + " <td> 50</td>\n", + " <td> 50</td>\n", + " </tr>\n", + " <tr>\n", + " <th>2</th>\n", + " <td> 0.092608</td>\n", + " <td> 48</td>\n", + " <td> 0.49</td>\n", + " <td> 50</td>\n", + " <td> 50</td>\n", + " </tr>\n", + " <tr>\n", + " <th>3</th>\n", + " <td> 0.024691</td>\n", + " <td> 3</td>\n", + " <td> 0.04</td>\n", + " <td> 50</td>\n", + " <td> 50</td>\n", + " </tr>\n", + " <tr>\n", + " <th>4</th>\n", + " <td> 0.060748</td>\n", + " <td> 42</td>\n", + " <td> 0.43</td>\n", + " <td> 50</td>\n", + " <td> 50</td>\n", + " </tr>\n", + " </tbody>\n", + "</table>\n", + "</div>" + ], + "text/plain": [ + " BurnedOut Run density height width\n", + "0 0.009288 11 0.12 50 50\n", + "1 1.000000 98 0.99 50 50\n", + "2 0.092608 48 0.49 50 50\n", + "3 0.024691 3 0.04 50 50\n", + "4 0.060748 42 0.43 50 50" + ] + }, + "execution_count": 14, "metadata": {}, - "outputs": [ - { - "html": [ - "<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n", - "<table border=\"1\" class=\"dataframe\">\n", - " <thead>\n", - " <tr style=\"text-align: right;\">\n", - " <th></th>\n", - " <th>BurnedOut</th>\n", - " <th>Run</th>\n", - " <th>density</th>\n", - " <th>height</th>\n", - " <th>width</th>\n", - " </tr>\n", - " </thead>\n", - " <tbody>\n", - " <tr>\n", - " <th>0</th>\n", - " <td> 0.142256</td>\n", - " <td> 45</td>\n", - " <td> 0.46</td>\n", - " <td> 50</td>\n", - " <td> 50</td>\n", - " </tr>\n", - " <tr>\n", - " <th>1</th>\n", - " <td> 0.946026</td>\n", - " <td> 68</td>\n", - " <td> 0.69</td>\n", - " <td> 50</td>\n", - " <td> 50</td>\n", - " </tr>\n", - " <tr>\n", - " <th>2</th>\n", - " <td> 0.978022</td>\n", - " <td> 71</td>\n", - " <td> 0.72</td>\n", - " <td> 50</td>\n", - " <td> 50</td>\n", - " </tr>\n", - " <tr>\n", - " <th>3</th>\n", - " <td> 0.027190</td>\n", - " <td> 12</td>\n", - " <td> 0.13</td>\n", - " <td> 50</td>\n", - " <td> 50</td>\n", - " </tr>\n", - " <tr>\n", - " <th>4</th>\n", - " <td> 0.082645</td>\n", - " <td> 43</td>\n", - " <td> 0.44</td>\n", - " <td> 50</td>\n", - " <td> 50</td>\n", - " </tr>\n", - " </tbody>\n", - "</table>\n", - "</div>" - ], - "metadata": {}, - "output_type": "pyout", - "prompt_number": 14, - "text": [ - " BurnedOut Run density height width\n", - "0 0.142256 45 0.46 50 50\n", - "1 0.946026 68 0.69 50 50\n", - "2 0.978022 71 0.72 50 50\n", - "3 0.027190 12 0.13 50 50\n", - "4 0.082645 43 0.44 50 50" - ] - } - ], - "prompt_number": 14 - }, + "output_type": "execute_result" + } + ], + "source": [ + "df.head()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As you can see, each row here is a run of the model, identified by its parameter values (and given a unique index by the Run column). To view how the BurnedOut fraction varies with density, we can easily just plot them:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [ { - "cell_type": "markdown", + "data": { + "text/plain": [ + "(0, 1)" + ] + }, + "execution_count": 15, "metadata": {}, - "source": [ - "As you can see, each row here is a run of the model, identified by its parameter values (and given a unique index by the Run column). To view how the BurnedOut fraction varies with density, we can easily just plot them:" - ] + "output_type": "execute_result" }, { - "cell_type": "code", - "collapsed": false, - "input": [ - "plt.scatter(df.density, df.BurnedOut)\n", - "plt.xlim(0,1)" - ], - "language": "python", + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAGXpJREFUeJzt3X+sJeV93/H3l+WHWLdbvLsSbgAL4lLHRdjyWoG1vTXX\nsmE3VCoFV0HEpAQ7iMYlG7prBUwts1ITR0iwQhvHgLcYiBKZVolp1hVlIY2vHCFMDYQfwbuEjU3F\njwSZxTapWbb749s/Zi537rnnnDv3zL3n3Hvm/ZJGe+fMMzPPmbv3M895njkzkZlIktrjmFFXQJI0\nXAa/JLWMwS9JLWPwS1LLGPyS1DIGvyS1TOPgj4ivR8SrEfFMj+WfjoinIuLpiHg4It7fdJ+SpMEt\nRIv/LmBTn+U/AD6Wme8H/jPwtQXYpyRpQI2DPzP/Evhxn+WPZOZPy9lHgVOb7lOSNLhh9/F/Frh/\nyPuUJFUcO6wdRcTHgc8AHx3WPiVJ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4THYhvwe1PHAdgPHDvqui/CsfiXFJfC\nP9Nj+bxzc5gt/nOAfZn5QmYeAu4FLuoo8/aXwjLzUeCkiOj7/YBlas5jkZmPZOZPy9lHgVOHXMdh\nqfP/AuA3KS4J/tEwKzdkdY7FrwB/mpkvAWTma0Ou47DUORZ/B6wqf14F7M/Mw0Os41Bk5l8CP+5T\nZN65OczgPwV4sTL/UvnaXGXGMfDqHIuqzwL3L2qNRmfOYxERp1D80d9WvjSuA1N1/l+cCawu74H1\nWET86tBqN1x1jsVO4KyIeAV4CvitIdVtqZl3bja5nHO+6v6xdl7aOY5/5LXfU0R8HPgM8NHFq85I\n1TkWtwLXZ2aWlwiP6+W/dY7FccA64BPASuCRiPhuZj6/qDUbvjrH4gbgycyciIj3AA9FxAcy8x8W\nuW5L0bxyc5jB/zJwWmX+NIozU78yp5avjZs6x4JyQHcnsCkz+33UW87qHIsPAfcWmc9a4Jci4lBm\n7hpOFYemzrF4EXgtMw8AByLiO8AHgHEL/jrH4iPA7wJk5t9GxA+B9wKPDaWGS8e8c3OYXT2PAWdG\nxOkRcTxwKcWXwKp2Af8OICLWAz/J6fsBjZM5j0VEvBv4JnB5Zu4bQR2HZc5jkZk/n5lnZOYZFP38\nvzGGoQ/1/kb+DNgQESsiYiXFYN73h1zPYahzLPYCnwQo+7TfC/xgqLVcGuadm0Nr8Wfm4Yi4BthN\nMWJ/Z2buiYiry+V3ZOb9EXFhROwDfgZcOaz6DVOdYwF8CXgncFvZ0j2UmeeMqs6LpeaxaIWafyN7\nI+IBii9FHqX4suTYBX/N/xdfBu6KiKcoGrG/nZmvj6zSiyQivgGcB6yNiBeBGym6/AbOTb/AJUkt\n46MXJallDH5JahmDX5JaxuCXpJYx+CWpZQx+SWoZg1+SWsbgl6SW+f9ehOb1bB9nvQAAAABJRU5E\nrkJggg==\n", + "text/plain": [ + "<matplotlib.figure.Figure at 0x10a095748>" + ] + }, "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 15, - "text": [ - "(0, 1)" - ] - }, - { - "metadata": {}, - "output_type": "display_data", - "png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAGS9JREFUeJzt3X+M3PV95/Hn24Y9bXTHgePKuQAJKUdyORqQQQGnzp03\nl+yuw0lQ7FM5GnJukhbudKRttE0MtS5slKQVulpBNBIBQsASStAphNY5cbv2tRkaI8IFCoYzNsVJ\nkfjRoDikUa9nyfb5fX/MrHd2PDs7M9/dmd35Ph/Sivnu9zPf72e/eF/z2ffnM9+JzESSVB6r+t0B\nSVJvGfySVDIGvySVjMEvSSVj8EtSyRj8klQyhYM/Ir4REW9ExPPz7P9YROyPiOci4vGIuKToOSVJ\n3VuMEf/9wOYW+38M/OvMvAT4InDPIpxTktSlwsGfmd8Hft5i/xOZ+Yva5pPAeUXPKUnqXq9r/J8C\nHu3xOSVJdc7o1Yki4kPAJ4GNvTqnJOl0PQn+2oTuvcDmzDytLBQR3jBIkrqQmdHpc5a81BMR7wC+\nA9yQmYfna5eZfmVy22239b0Py+XLa+G18Fq0/upW4RF/RHwL2ASsjYhXgNuAM2thfjfweeAc4K6I\nADiemVcUPa8kqTuFgz8zr19g/28Bv1X0PJKkxeE7d5eZkZGRfndh2fBazPJazPJaFBdF6kSL1omI\nXA79kKSVJCLI5Ti5K0laXgx+SSoZg1+SSsbgl6SSMfglqWQMfkkqGYNfkkrG4JekkjH4JalkDH5J\nKhmDX5JKxuCXpJIx+CWpZAx+SSoZg1+SSsbgl6SSMfglqWQMfkkqGYNfkkrG4JekkjH4JalkCgV/\nRHwjIt6IiOdbtLkzIl6KiP0Rsb7I+SRJxRUd8d8PbJ5vZ0RcBfzzzLwIuBG4q+D5JEkFFQr+zPw+\n8PMWTa4GdtXaPgmcHRHripxTklTMUtf4zwVeqdt+FThvic8pSWrhjB6cIxq2s1mjycnJU49HRkYY\nGRlZuh5JUp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2SBa9FRLwD+A5wQ2Ye7kMfe2XBa5GZv5yZ78rMd1Gt8/+nAQx9aO935M+AD0bE6oh4C9XJ\nvBd63M9eaOdaHAI+AlCrab8H+HFPe7k8dJybPRvxZ+aJiLgZmKY6Y39fZh6MiJtq++/OzEcj4qqI\nOAz8A/CJXvWvl9q5FsDngXOAu2oj3eOZeUW/+rxU2rwWpdDm78ihiJii+qbIk1TfLDlwwd/mv4s/\nBO6PiP1UB7Gfy8w3+9bpJRIR3wI2AWsj4hXgNqolv65z0zdwSVLJ+NGLklQyBr8klYzBL0klY/BL\nUskY/JJUMga/JJWMwS9JJWPwS1LJ/H90HnxhfKFFXgAAAABJRU5ErkJggg==\n", - "text": [ - "<matplotlib.figure.Figure at 0x10a339828>" - ] - } - ], - "prompt_number": 15 - }, + "output_type": "display_data" + } + ], + "source": [ + "plt.scatter(df.density, df.BurnedOut)\n", + "plt.xlim(0,1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And we see the very clear emergence of a critical value around 0.5, where the model quickly shifts from almost no trees being burned, to almost all of them.\n", + "\n", + "In this case we ran the model only once at each value. However, it's easy to have the BatchRunner execute multiple runs at each parameter combination, in order to generate more statistically reliable results. We do this using the *iteration* argument.\n", + "\n", + "Let's run the model 5 times at each parameter point, and export and plot the results as above." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ { - "cell_type": "markdown", + "data": { + "text/plain": [ + "(0, 1)" + ] + }, + "execution_count": 16, "metadata": {}, - "source": [ - "And we see the very clear emergence of a critical value around 0.5, where the model quickly shifts from almost no trees being burned, to almost all of them.\n", - "\n", - "In this case we ran the model only once at each value. However, it's easy to have the BatchRunner execute multiple runs at each parameter combination, in order to generate more statistically reliable results. We do this using the *iteration* argument.\n", - "\n", - "Let's run the model 5 times at each parameter point, and export and plot the results as above." - ] + "output_type": "execute_result" }, { - "cell_type": "code", - "collapsed": false, - "input": [ - "param_run = BatchRunner(ForestFire, param_set, iterations=5, model_reporters=model_reporter)\n", - "param_run.run_all()\n", - "df = param_run.get_model_vars_dataframe()\n", - "plt.scatter(df.density, df.BurnedOut)\n", - "plt.xlim(0,1)" - ], - "language": "python", + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X+QHOV95/H3V9J6rQWvpF0lOCAwBLBxbGF+XEBnOFif\nLaSQijnDVSgCOYwdgo3JGrQ67MiU0ZUxse+QTHQuDFawUF185nIhPkRCQOTMVlIum7PELwULkGzI\ngYi5SALWoB/sar/3x/O0pmemZ3Z2e3dmdvvzqupS9/TT3c+2dr/9zLefftrcHRERKY5Zra6AiIg0\nlwK/iEjBKPCLiBSMAr+ISMEo8IuIFIwCv4hIweQO/Gb2HTN71cy21Vh/uZk9ZWZPm9kPzezUvMcU\nEZGJm4wW/wZgeZ31PwfOc/dTga8A356EY4qIyATlDvzu/g/Aa3XW/8jd34iLjwGL8h5TREQmrtk5\n/k8DDzb5mCIikjKnWQcys48AnwLOadYxRUSkWlMCf7yhux5Y7u5VaSEz04BBIiIT4O423m2mPPCb\n2XHAXwFXuPvOWuUmUvmZyMxWu/vqVtejHehclOhclOhclEy00Zw78JvZ94DzgYVm9hJwM9AB4O53\nAV8GFgDfMjOAYXc/K+9xRURkYnIHfne/bIz1fwD8Qd7jiIjI5NCTu+1nsNUVaCODra5AGxlsdQXa\nyGCrKzDdWTu8iMXMXDl+EZHxmWjsVItfRKRgFPhFRApGgV9EpGAU+EVECkaBX0SkYBT4RUQKRoFf\nRKRgFPhFRApGgV9EpGAU+EVECkaBX0SkYBT4RUQKRoFfRKRgFPhFRApGgV9EpGAU+EVECkaBX0Sk\nYBT4RUQKRoFfRKRgFPhFRApGgV9EpGByBX4z+46ZvWpm2+qUWWdmO8zsKTM7Pc/xREQkv7wt/g3A\n8lorzexC4CR3Pxn4Q+BbOY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LaZdRFu5v20yfVshkbOxbPAxwBiTvt9wM+bWsv2MO642bQWv7uPmNl1wMOEO/Z3u/t2\nM7smrr/L3R80swvNbCfwFnBVs+rXTI2cC+DLwALgW7GlO+zuZ7WqzlOlwXNRCA3+jTxrZg8RHooc\nJTwsOeMCf4O/F7cCG8zsKUIj9kZ339uySk8RM/secD6w0MxeAm4mpPwmHDf1AJeISMHo1YsiIgWj\nwC8iUjAK/CIiBaPALyJSMAr8IiIFo8AvIlIwCvwiIgWjwC8iUjD/H15+d1SmsbWuAAAAAElFTkSu\nQmCC\n", + "text/plain": [ + "<matplotlib.figure.Figure at 0x10a417710>" + ] + }, "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 16, - "text": [ - "(0, 1)" - ] - }, - { - "metadata": {}, - "output_type": "display_data", - "png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAEACAYAAAC08h1NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X90HOV97/H3V1rW2LGNvRI/DMYmKAQIMSCTELfkxsoF\nIYcGp9g9SSikuqQxpC1xUsmBEJvEt5bCyQ84XJrc8KMpdpO03HtK6BX3gIWTRk7hQFL/iHEJTrFN\ncqEmnNjKD2icCOHv/WNmpNnZH1pppV1J+3mds4eZnWdnnh2s7zz7fZ55xtwdERGpHXXVroCIiFSW\nAr+ISI1R4BcRqTEK/CIiNUaBX0Skxijwi4jUmLIDv5n9rZm9bGZ7C2y/xsz2mNnTZvaEmZ1f7jFF\nRGTsxqPFfz+wosj2g8C73P18YBNw7zgcU0RExqjswO/u/wL8osj2J939V+Hq94GF5R5TRETGrtI5\n/j8FHqnwMUVEJCZVqQOZ2buBDwOXVOqYIiKSqyKBP+zQvQ9Y4e45aSEz04RBIiJj4O422s9MeKrH\nzBYB3wKudff9hcq5u17ufPazn616HSbLS+dC50LnovhrrMpu8ZvZPwDLgUYzewH4LHBcGMzvAT4D\nzAe+amY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m5WssV/MbDf3X/i7q8BDwDvS5QZuinM3b8PzDOzovcHTFEjngt3\nf9LdfxWufh9YWOE6Vkop/y4APkYwJPjnlaxchZVyLv4YeNDdXwRw98MVrmOllHIuXgLmhstzgSPu\nPljBOlaEu/8L8IsiRUYdNysZ+E8DXoitvxi+N1KZ6RjwSjkXcX8KPDKhNaqeEc+FmZ1G8Ef/1fCt\n6doxVcq/i7OATDgH1g4z+1DFaldZpZyL+4DzzOwQsAf4eIXqNtmMOm6WM5xztEr9Y00O7ZyOf+Ql\nfyczezfwYeCSiatOVZVyLu4EPuXuHg4Rnq7Df0s5F8cBS4FLgVnAk2b2lLs/N6E1q7xSzsWngR+6\ne4uZNQHbzOwCd39lgus2GY0qblYy8P8HcHps/XSCK1OxMgvD96abUs4FYYfufcAKdy/2U28qK+Vc\nXAQ8EMR8GoH3mNlr7t5TmSpWTCnn4gXgsLsfBY6a2feAC4DpFvhLORe/D3QDuPsBM3seOBvYUZEa\nTh6jjpuVTPXsAM4yszPMLA18gOAmsLge4E8AzGwZ8Esfng9oOhnxXJjZIuBbwLXuvr8KdayUEc+F\nu5/p7m909zcS5Pn/bBoGfSjtb+T/AO80s3ozm0XQmfejCtezEko5F/uAywDCnPbZwMGK1nJyGHXc\nrFiL390HzexGoJegx/5r7v6smd0Qbr/H3R8xsyvMbD/wn8B1lapfJZVyLoDPAPOBr4Yt3dfc/eJq\n1XmilHguakKJfyP7zGwrwU2Rxwhulpx2gb/EfxefA+43sz0Ejdib3L2/apWeIGb2D8ByoNHMXgA+\nS5DyG3Pc1A1cIiI1Ro9eFBGpMQr8IiI1RoFfRKTGKPCLiNQYBX4RkRqjwC8iUmMU+EVEaowCv4hI\njfn/vIVXkfM6S7gAAAAASUVORK5CYII=\n", - "text": [ - "<matplotlib.figure.Figure at 0x109eb1be0>" - ] - } - ], - "prompt_number": 16 + "output_type": "display_data" } ], - "metadata": {} + "source": [ + "param_run = BatchRunner(ForestFire, param_set, iterations=5, model_reporters=model_reporter)\n", + "param_run.run_all()\n", + "df = param_run.get_model_vars_dataframe()\n", + "plt.scatter(df.density, df.BurnedOut)\n", + "plt.xlim(0,1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] } - ] -} \ No newline at end of file + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.2" + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} diff --git a/mesa/datacollection.py b/mesa/datacollection.py index 4836d16c..0a4a9290 100644 --- a/mesa/datacollection.py +++ b/mesa/datacollection.py @@ -3,20 +3,27 @@ Mesa Data Collection Module ===================================================== DataCollector is meant to provide a simple, standard way to collect data -generated by a Mesa model. It collects two types of data: model-level and -agent-level data. +generated by a Mesa model. It collects three types of data: model-level data, +agent-level data, and tables. A DataCollector is instantiated with two dictionaries of reporter names and associated functions for each, one for model-level data and one for -agent-level data. When the collect() method is called, each model-level -function is called, with the model as the argument, and the results associated -with the relevant variable. Then the agent-level functions are called on each +agent-level data; a third dictionary provides table names and columns. + +When the collect() method is called, each model-level function is called, with +the model as the argument, and the results associated with the relevant +variable. Then the agent-level functions are called on each agent in the model scheduler. -The DataCollector then stores the data it collects in two dictionaries: +Additionally, other objects can write directly to tables by passing in an +appropriate dictionary object for a table row. + +The DataCollector then stores the data it collects in dictionaries: * model_vars maps each reporter to a list of its values * agent_vars maps each reporter to a list of lists, where each nested list stores (agent_id, value) pairs. + * tables maps each table to a dictionary, with each column as a key with a + list as its value. Finally, DataCollector can create a pandas DataFrame from each collection. @@ -43,10 +50,11 @@ class DataCollector(object): model_vars = {} agent_vars = {} + tables = {} model = None - def __init__(self, model_reporters=None, agent_reporters=None): + def __init__(self, model_reporters={}, agent_reporters={}, tables={}): ''' Instantiate a DataCollector with lists of model and agent reporters. @@ -59,21 +67,62 @@ class DataCollector(object): it might look like this: {"energy": lambda a: a.energy} + The tables arg accepts a dictionary mapping names of tables to lists of + columns. For example, if we want to allow agents to write their age + when they are destroyed (to keep track of lifespans), it might look + like: + {"Lifespan": ["unique_id", "age"]} + Args: model_reporters: Dictionary of reporter names and functions. agent_reporters: Dictionary of reporter names and functions. ''' - self.model_reporters = model_reporters - self.agent_reporters = agent_reporters + self.model_reporters = {} + self.agent_reporters = {} + self.tables = {} - if self.model_reporters: - for var in self.model_reporters: - self.model_vars[var] = [] + for name, func in model_reporters.items(): + self._new_model_reporter(name, func) - if self.agent_reporters: - for var in self.agent_reporters: - self.agent_vars[var] = [] + for name, func in agent_reporters.items(): + self._new_agent_reporter(name, func) + + for name, columns in tables.items(): + self._new_table(name, columns) + + def _new_model_reporter(self, reporter_name, reporter_function): + ''' + Add a new model-level reporter to collect. + Args: + reporter_name: Name of the model-level variable to collect. + reporter_function: Function object that returns the variable when + given a model instance. + ''' + + self.model_reporters[reporter_name] = reporter_function + self.model_vars[reporter_name] = [] + + def _new_agent_reporter(self, reporter_name, reporter_function): + ''' + Add a new agent-level reporter to collect. + Args: + reporter_name: Name of the agent-level variable to collect. + reporter_function: Function object that returns the variable when + given an agent object. + ''' + self.agent_reporters[reporter_name] = reporter_function + self.agent_vars[reporter_name] = [] + + def _new_table(self, table_name, table_columns): + ''' + Add a new table that objects can write to. + Args: + table_name: Name of the new table. + table_columns: List of columns to add to the table. + ''' + new_table = {column: [] for column in table_columns} + self.tables[table_name] = new_table def collect(self, model): ''' @@ -90,6 +139,27 @@ class DataCollector(object): agent_records.append((agent.unique_id, reporter(agent))) self.agent_vars[var].append(agent_records) + def add_table_row(self, table_name, row, ignore_missing=False): + ''' + Add a row dictionary to a specific table. + + Args: + table_name: Name of the table to append a row to. + row: A dictionary of the form {column_name: value...} + ignore_missing: If True, fill any missing columns with Nones; + if False, throw an error if any columns are missing + ''' + if table_name not in self.tables: + raise Exception("Table does not exist.") + + for column in self.tables[table_name]: + if column in row: + self.tables[table_name][column].append(row[column]) + elif ignore_missing: + self.tables[table_name][column].append(None) + else: + raise Exception("Could not insert row with missing column") + def get_model_vars_dataframe(self): ''' Create a pandas DataFrame from the model variables. @@ -115,3 +185,14 @@ class DataCollector(object): df = pd.DataFrame.from_dict(data, orient="index") df.index.names = ["Step", "AgentID"] return df + + def get_table_dataframe(self, table_name): + ''' + Create a pandas DataFrame from a particular table. + + Args: + table_name: The name of the table to convert. + ''' + if table_name not in self.tables: + raise Exception("No such table.") + return pd.DataFrame(self.tables[table_name])
Add data collection features Discovered a need for these two features while using Mesa "in production": - Break apart the constructor to allow variables to be added later - Create tables that the model and/or agents can write to directly as needed, rather than data collected automatically every step.
projectmesa/mesa
diff --git a/tests/test_datacollector.py b/tests/test_datacollector.py new file mode 100644 index 00000000..e1115978 --- /dev/null +++ b/tests/test_datacollector.py @@ -0,0 +1,119 @@ +''' +Test the DataCollector +''' +import unittest + +from mesa import Model, Agent +from mesa.time import BaseScheduler +from mesa.datacollection import DataCollector + + +class MockAgent(Agent): + ''' + Minimalistic agent for testing purposes. + ''' + def __init__(self, unique_id, val): + self.unique_id = unique_id + self.val = val + + def step(self, model): + ''' + Increment val by 1. + ''' + self.val += 1 + + def write_final_values(self, model): + ''' + Write the final value to the appropriate table. + ''' + row = {"agent_id": self.unique_id, "final_value": self.val} + model.datacollector.add_table_row("Final_Values", row) + + +class MockModel(Model): + ''' + Minimalistic model for testing purposes. + ''' + + schedule = BaseScheduler(None) + + def __init__(self): + self.schedule = BaseScheduler(self) + for i in range(10): + a = MockAgent(i, i) + self.schedule.add(a) + self.datacollector = DataCollector( + {"total_agents": lambda m: m.schedule.get_agent_count()}, + {"value": lambda a: a.val}, + {"Final_Values": ["agent_id", "final_value"]}) + + def step(self): + self.schedule.step() + self.datacollector.collect(self) + + +class TestDataCollector(unittest.TestCase): + def setUp(self): + ''' + Create the model and run it a set number of steps. + ''' + self.model = MockModel() + for i in range(7): + self.model.step() + # Write to table: + for agent in self.model.schedule.agents: + agent.write_final_values(self.model) + + def test_model_vars(self): + ''' + Test model-level variable collection. + ''' + data_collector = self.model.datacollector + assert "total_agents" in data_collector.model_vars + assert len(data_collector.model_vars["total_agents"]) == 7 + for element in data_collector.model_vars["total_agents"]: + assert element == 10 + + def test_agent_vars(self): + ''' + Test agent-level variable collection. + ''' + data_collector = self.model.datacollector + assert len(data_collector.agent_vars["value"]) == 7 + for step in data_collector.agent_vars["value"]: + assert len(step) == 10 + for record in step: + assert len(record) == 2 + + def test_table_rows(self): + ''' + Test table collection + ''' + data_collector = self.model.datacollector + assert len(data_collector.tables["Final_Values"]) == 2 + assert "agent_id" in data_collector.tables["Final_Values"] + assert "final_value" in data_collector.tables["Final_Values"] + for key, data in data_collector.tables["Final_Values"].items(): + assert len(data) == 10 + + with self.assertRaises(Exception): + data_collector.add_table_row("error_table", {}) + + with self.assertRaises(Exception): + data_collector.add_table_row("Final_Values", {"final_value": 10}) + + def test_exports(self): + ''' + Test DataFrame exports + ''' + data_collector = self.model.datacollector + model_vars = data_collector.get_model_vars_dataframe() + agent_vars = data_collector.get_agent_vars_dataframe() + table_df = data_collector.get_table_dataframe("Final_Values") + + assert model_vars.shape == (7, 1) + assert agent_vars.shape == (70, 1) + assert table_df.shape == (10, 2) + + with self.assertRaises(Exception): + table_df = data_collector.get_table_dataframe("not a real table")
{ "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": -1 }, "num_modified_files": 3 }
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", "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@ca1e91c6ea8b5bc476ae0fdbf708c1f28ae55dc4#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_datacollector.py::TestDataCollector::test_agent_vars", "tests/test_datacollector.py::TestDataCollector::test_exports", "tests/test_datacollector.py::TestDataCollector::test_model_vars", "tests/test_datacollector.py::TestDataCollector::test_table_rows" ]
[]
[]
[]
Apache License 2.0
114
[ "examples/ForestFire/Forest", "mesa/datacollection.py", "examples/ForestFire/Forest Fire Model.ipynb", "examples/ForestFire/.ipynb_checkpoints/Forest", "examples/ForestFire/.ipynb_checkpoints/Forest Fire Model-checkpoint.ipynb" ]
[ "examples/ForestFire/Forest Fire Model.ipynb", "examples/ForestFire/.ipynb_checkpoints/Forest Fire Model-checkpoint.ipynb", "mesa/datacollection.py", "re" ]
sjagoe__usagi-49
66dccaaca17941c7cd587d7c8828f68cc87f41f0
2015-04-28 17:51:59
66dccaaca17941c7cd587d7c8828f68cc87f41f0
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index ef6028e..27fa8ce 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -10,6 +10,8 @@ Enhancements * Added an option to the body assertion to filter json responses with a ``jq`` (https://pypi.python.org/pypi/jq) filter (#44). +* Added an option to cases and tests to allow setting the + unittest.TestCase.maxDiff parameter (#47). Version 0.2.0 diff --git a/usagi/schema.py b/usagi/schema.py index 20915a9..5b0f11a 100644 --- a/usagi/schema.py +++ b/usagi/schema.py @@ -118,12 +118,18 @@ SCHEMA = { }, 'minItems': 1, }, + 'max-diff': { + '$ref': '#/definitions/max-diff', + }, }, 'required': ['name', 'tests'], }, 'test': { 'type': 'object', 'properties': { + 'max-diff': { + '$ref': '#/definitions/max-diff', + }, 'parameters': {'type': 'object'}, 'url': { 'oneOf': [ @@ -155,5 +161,9 @@ SCHEMA = { }, 'required': ['url', 'name'], }, + 'max-diff': { + 'type': ['number', 'null'], + 'description': 'Set the case maxDiff option to control error output', # noqa + }, }, }
Allow setting maxDiff at the testCase level and test level Currently if a body assertion fails there is no way to see the whole diff to resolve the issue. We need a mechanism to set the underlying TestCase `maxDiff` attribute on a test-case level and an individual test level.
sjagoe/usagi
diff --git a/usagi/tests/test_schema.py b/usagi/tests/test_schema.py index 21fac64..f270e32 100644 --- a/usagi/tests/test_schema.py +++ b/usagi/tests/test_schema.py @@ -337,3 +337,137 @@ class TestSchema(unittest.TestCase): # Validation fails with self.assertRaises(ValidationError): jsonschema.validate(test_data, SCHEMA) + + def test_schema_case_max_diff_null(self): + # Given + test_yaml = textwrap.dedent(""" + version: '1.0' + + config: + host: test.domain + + cases: + - name: "Basic" + max-diff: null + tests: + - name: "Another URL" + url: "/another" + + """) + + test_data = yaml.safe_load(test_yaml) + + # Validation succeeds + jsonschema.validate(test_data, SCHEMA) + + def test_schema_case_max_diff_number(self): + # Given + test_yaml = textwrap.dedent(""" + version: '1.0' + + config: + host: test.domain + + cases: + - name: "Basic" + max-diff: 12345 + tests: + - name: "Another URL" + url: "/another" + + """) + + test_data = yaml.safe_load(test_yaml) + + # Validation succeeds + jsonschema.validate(test_data, SCHEMA) + + def test_schema_case_max_diff_string(self): + # Given + test_yaml = textwrap.dedent(""" + version: '1.0' + + config: + host: test.domain + + cases: + - name: "Basic" + max-diff: '12345' + tests: + - name: "Another URL" + url: "/another" + + """) + + test_data = yaml.safe_load(test_yaml) + + # Validation fails + with self.assertRaises(ValidationError): + jsonschema.validate(test_data, SCHEMA) + + def test_schema_test_max_diff_null(self): + # Given + test_yaml = textwrap.dedent(""" + version: '1.0' + + config: + host: test.domain + + cases: + - name: "Basic" + tests: + - name: "Another URL" + url: "/another" + max-diff: null + + """) + + test_data = yaml.safe_load(test_yaml) + + # Validation succeeds + jsonschema.validate(test_data, SCHEMA) + + def test_schema_test_max_diff_number(self): + # Given + test_yaml = textwrap.dedent(""" + version: '1.0' + + config: + host: test.domain + + cases: + - name: "Basic" + tests: + - name: "Another URL" + url: "/another" + max-diff: 12345 + + """) + + test_data = yaml.safe_load(test_yaml) + + # Validation succeeds + jsonschema.validate(test_data, SCHEMA) + + def test_schema_test_max_diff_string(self): + # Given + test_yaml = textwrap.dedent(""" + version: '1.0' + + config: + host: test.domain + + cases: + - name: "Basic" + tests: + - name: "Another URL" + url: "/another" + max-diff: '12345' + + """) + + test_data = yaml.safe_load(test_yaml) + + # Validation fails + with self.assertRaises(ValidationError): + jsonschema.validate(test_data, SCHEMA) diff --git a/usagi/tests/test_web_test.py b/usagi/tests/test_web_test.py index 266f86c..4a72983 100644 --- a/usagi/tests/test_web_test.py +++ b/usagi/tests/test_web_test.py @@ -25,7 +25,7 @@ from ..plugins.test_parameters import ( ) from ..config import Config from ..utils import create_session -from ..web_test import WebPoll, WebTest +from ..web_test import WebPoll, WebTest, _Default class TestWebTest(unittest.TestCase): @@ -72,6 +72,77 @@ class TestWebTest(unittest.TestCase): # Then self.assertIs(test.session, session) self.assertIs(test.config, config) + self.assertIs(test.max_diff, _Default) + self.assertEqual(test.name, name) + self.assertEqual(test.url, expected_url) + self.assertEqual(self._get_web_test_method(test), 'GET') + self.assertEqual(len(test.assertions), 0) + + def test_from_dict_null_max_diff(self): + # Given + config = Config.from_dict({'host': 'test.invalid'}, __file__) + session = create_session() + name = 'A test' + url = '/api/test' + test_spec = { + 'name': name, + 'url': url, + 'max-diff': None, + } + expected_url = urllib.parse.urlunparse( + urllib.parse.ParseResult( + config.scheme, + config.host, + url, + None, + None, + None, + ), + ) + + # When + test = WebTest.from_dict( + session, test_spec, config, {}, self.test_parameter_plugins) + + # Then + self.assertIs(test.session, session) + self.assertIs(test.config, config) + self.assertIsNone(test.max_diff) + self.assertEqual(test.name, name) + self.assertEqual(test.url, expected_url) + self.assertEqual(self._get_web_test_method(test), 'GET') + self.assertEqual(len(test.assertions), 0) + + def test_from_dict_integer_max_diff(self): + # Given + config = Config.from_dict({'host': 'test.invalid'}, __file__) + session = create_session() + name = 'A test' + url = '/api/test' + test_spec = { + 'name': name, + 'url': url, + 'max-diff': 5001, + } + expected_url = urllib.parse.urlunparse( + urllib.parse.ParseResult( + config.scheme, + config.host, + url, + None, + None, + None, + ), + ) + + # When + test = WebTest.from_dict( + session, test_spec, config, {}, self.test_parameter_plugins) + + # Then + self.assertIs(test.session, session) + self.assertIs(test.config, config) + self.assertEqual(test.max_diff, 5001) self.assertEqual(test.name, name) self.assertEqual(test.url, expected_url) self.assertEqual(self._get_web_test_method(test), 'GET') @@ -106,6 +177,7 @@ class TestWebTest(unittest.TestCase): # Then self.assertIs(test.session, session) self.assertIs(test.config, config) + self.assertIs(test.max_diff, _Default) self.assertEqual(test.name, name) self.assertEqual(test.url, expected_url) self.assertEqual(self._get_web_test_method(test), 'POST') @@ -208,6 +280,73 @@ class TestWebTest(unittest.TestCase): self.assertEqual(args, (204, 200)) self.assertIn('msg', kwargs) + # No maxDiff has been set + self.assertIsInstance(case.maxDiff, Mock) + + @responses.activate + def test_run_null_max_diff(self): + # Given + config = Config.from_dict({'host': 'test.invalid'}, __file__) + session = create_session() + name = 'A test' + url = '/api/test' + test_spec = { + 'name': name, + 'url': url, + 'max-diff': None, + } + assertions = {} + + test = WebTest.from_dict( + session, test_spec, config, assertions, + self.test_parameter_plugins) + + responses.add( + self._get_web_test_method(test), + test.url, + status=204, + ) + + # When + case = Mock() + test.run(case) + + # Then + # maxDiff set to None + self.assertIs(case.maxDiff, None) + + @responses.activate + def test_run_int_max_diff(self): + # Given + config = Config.from_dict({'host': 'test.invalid'}, __file__) + session = create_session() + name = 'A test' + url = '/api/test' + test_spec = { + 'name': name, + 'url': url, + 'max-diff': 2121, + } + assertions = {} + + test = WebTest.from_dict( + session, test_spec, config, assertions, + self.test_parameter_plugins) + + responses.add( + self._get_web_test_method(test), + test.url, + status=204, + ) + + # When + case = Mock() + test.run(case) + + # Then + # maxDiff set to value + self.assertEqual(case.maxDiff, 2121) + def test_connection_error(self): # Given config = Config.from_dict({'host': 'test.invalid'}, __file__) diff --git a/usagi/tests/test_yaml_test_loader.py b/usagi/tests/test_yaml_test_loader.py index 1527b0e..0dcd22d 100644 --- a/usagi/tests/test_yaml_test_loader.py +++ b/usagi/tests/test_yaml_test_loader.py @@ -316,3 +316,69 @@ class TestYamlTestLoader(unittest.TestCase): self.assertEqual(test.request.url, 'http://test.domain/another') self.assertEqual(post_1.request.url, 'http://test.domain/one') self.assertEqual(post_2.request.url, 'http://test.domain/two') + + def test_load_yaml_tests_case_max_diff_null(self): + # Given + test_yaml = textwrap.dedent(""" + --- + version: '1.0' + + config: + host: test.domain + + cases: + - name: "Basic" + max-diff: null + tests: + - name: "Test root URL" + url: "/" + - name: "Test sub URL" + url: "/sub/" + + """) + + test_data = yaml.safe_load(test_yaml) + + # When + suite = self.loader.load_tests_from_yaml( + test_data, '/path/to/foo.yaml') + + # Then + self.assertIsInstance(suite, TestSuite) + self.assertEqual(suite.countTestCases(), 2) + cls1, cls2 = [type(case) for case in find_test_cases(suite)] + self.assertIs(cls1, cls2) + self.assertIsNone(cls1.maxDiff) + + def test_load_yaml_tests_case_max_diff_number(self): + # Given + test_yaml = textwrap.dedent(""" + --- + version: '1.0' + + config: + host: test.domain + + cases: + - name: "Basic" + max-diff: 1234 + tests: + - name: "Test root URL" + url: "/" + - name: "Test sub URL" + url: "/sub/" + + """) + + test_data = yaml.safe_load(test_yaml) + + # When + suite = self.loader.load_tests_from_yaml( + test_data, '/path/to/foo.yaml') + + # Then + self.assertIsInstance(suite, TestSuite) + self.assertEqual(suite.countTestCases(), 2) + cls1, cls2 = [type(case) for case in find_test_cases(suite)] + self.assertIs(cls1, cls2) + self.assertEqual(cls1.maxDiff, 1234) diff --git a/usagi/web_test.py b/usagi/web_test.py index db205c6..b410e84 100644 --- a/usagi/web_test.py +++ b/usagi/web_test.py @@ -33,6 +33,9 @@ def initialize_test_parameter_loaders(test_parameter_plugins, parameter_specs): yield cls.from_dict({name: value}) +_Default = object() + + class WebTest(object): """The main entry-point into a single web test case. @@ -42,7 +45,7 @@ class WebTest(object): """ def __init__(self, session, config, name, path, assertions, - parameter_loaders): + parameter_loaders, max_diff): super(WebTest, self).__init__() self.session = session self.name = name @@ -50,6 +53,7 @@ class WebTest(object): self.path = path self.assertions = assertions self.parameter_loaders = parameter_loaders + self.max_diff = max_diff @property def url(self): @@ -80,6 +84,8 @@ class WebTest(object): spec = spec.copy() name = spec.pop('name') + max_diff = spec.pop('max-diff', _Default) + assertion_specs = spec.pop('assertions', []) assertions = initialize_assertions( assertions_map, assertion_specs) @@ -100,6 +106,7 @@ class WebTest(object): path=spec['url'], assertions=list(assertions), parameter_loaders=list(parameter_loaders), + max_diff=max_diff, ) def run(self, case): @@ -111,6 +118,9 @@ class WebTest(object): The ``TestCase`` instance used to record test results. """ + if self.max_diff is not _Default: + case.maxDiff = self.max_diff + try: url = self.url except InvalidVariableType as exc: diff --git a/usagi/yaml_test_loader.py b/usagi/yaml_test_loader.py index 373a7ca..5a2457f 100644 --- a/usagi/yaml_test_loader.py +++ b/usagi/yaml_test_loader.py @@ -98,6 +98,9 @@ def create_test_case_for_case(filename, config, case, assertions_map, ) class_dict[TEST_NAME_ATTRIBUTE] = case['name'] + if 'max-diff' in case: + class_dict['maxDiff'] = case['max-diff'] + def __str__(self): method = getattr(self, self._testMethodName) template = '{0!r} ({1})'
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "issue_text_score": 1, "test_score": 3 }, "num_modified_files": 2 }
0.2
{ "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": [ "coverage", "mock", "responses", "pytest" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.4", "reqs_path": [ "test_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 docutils==0.18.1 enum34==1.1.10 haas==0.9.0 idna==3.10 importlib-metadata==4.8.3 iniconfig==1.1.1 jq==0.1.8 jsonschema==3.2.0 mock==5.2.0 packaging==21.3 pbr==6.1.1 pluggy==1.0.0 py==1.11.0 pyparsing==3.1.4 pyrsistent==0.18.0 pytest==7.0.1 PyYAML==6.0.1 requests==2.27.1 responses==0.17.0 six==1.17.0 statistics==1.0.3.5 stevedore==3.5.2 tomli==1.2.3 typing_extensions==4.1.1 urllib3==1.26.20 -e git+https://github.com/sjagoe/usagi.git@66dccaaca17941c7cd587d7c8828f68cc87f41f0#egg=usagi zipp==3.6.0
name: usagi 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 - docutils==0.18.1 - enum34==1.1.10 - haas==0.9.0 - idna==3.10 - importlib-metadata==4.8.3 - iniconfig==1.1.1 - jq==0.1.8 - jsonschema==3.2.0 - mock==5.2.0 - packaging==21.3 - pbr==6.1.1 - pluggy==1.0.0 - py==1.11.0 - pyparsing==3.1.4 - pyrsistent==0.18.0 - pytest==7.0.1 - pyyaml==6.0.1 - requests==2.27.1 - responses==0.17.0 - six==1.17.0 - statistics==1.0.3.5 - stevedore==3.5.2 - tomli==1.2.3 - typing-extensions==4.1.1 - urllib3==1.26.20 - zipp==3.6.0 prefix: /opt/conda/envs/usagi
[ "usagi/tests/test_schema.py::TestSchema::test_schema_case_max_diff_string", "usagi/tests/test_schema.py::TestSchema::test_schema_test_max_diff_string" ]
[ "usagi/tests/test_web_test.py::TestWebTest::test_poll_fail", "usagi/tests/test_web_test.py::TestWebTest::test_poll_success", "usagi/tests/test_web_test.py::TestWebTest::test_run" ]
[ "usagi/tests/test_schema.py::TestSchema::test_schema", "usagi/tests/test_schema.py::TestSchema::test_schema_assertions", "usagi/tests/test_schema.py::TestSchema::test_schema_bad_host", "usagi/tests/test_schema.py::TestSchema::test_schema_bad_pre_definition", "usagi/tests/test_schema.py::TestSchema::test_schema_case_max_diff_null", "usagi/tests/test_schema.py::TestSchema::test_schema_case_max_diff_number", "usagi/tests/test_schema.py::TestSchema::test_schema_empty_assertions", "usagi/tests/test_schema.py::TestSchema::test_schema_invalid_assertions", "usagi/tests/test_schema.py::TestSchema::test_schema_missing_config", "usagi/tests/test_schema.py::TestSchema::test_schema_missing_host", "usagi/tests/test_schema.py::TestSchema::test_schema_no_cases", "usagi/tests/test_schema.py::TestSchema::test_schema_pre_definitions_case_setup", "usagi/tests/test_schema.py::TestSchema::test_schema_test_max_diff_null", "usagi/tests/test_schema.py::TestSchema::test_schema_test_max_diff_number", "usagi/tests/test_schema.py::TestSchema::test_schema_top_level_single_test", "usagi/tests/test_schema.py::TestSchema::test_schema_top_level_tests", "usagi/tests/test_web_test.py::TestWebTest::test_connection_error", "usagi/tests/test_web_test.py::TestWebTest::test_create_invlalid_assertions", "usagi/tests/test_web_test.py::TestWebTest::test_create_with_assertions", "usagi/tests/test_web_test.py::TestWebTest::test_create_with_body", "usagi/tests/test_web_test.py::TestWebTest::test_create_with_headers", "usagi/tests/test_web_test.py::TestWebTest::test_create_with_invalid_parameter", "usagi/tests/test_web_test.py::TestWebTest::test_from_dict", "usagi/tests/test_web_test.py::TestWebTest::test_from_dict_integer_max_diff", "usagi/tests/test_web_test.py::TestWebTest::test_from_dict_null_max_diff", "usagi/tests/test_web_test.py::TestWebTest::test_from_different_method", "usagi/tests/test_web_test.py::TestWebTest::test_invalid_url", "usagi/tests/test_web_test.py::TestWebTest::test_run_int_max_diff", "usagi/tests/test_web_test.py::TestWebTest::test_run_null_max_diff", "usagi/tests/test_web_test.py::TestWebTest::test_templating_url", "usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_case_dunder_str", "usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_case_setup", "usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_execute_single_case", "usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_execute_single_case_failure", "usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_load_invalid_yaml_tests", "usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_load_yaml_tests", "usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_load_yaml_tests_case_max_diff_null", "usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_load_yaml_tests_case_max_diff_number", "usagi/tests/test_yaml_test_loader.py::TestYamlTestLoader::test_plugins_loaded" ]
[]
BSD 3-Clause "New" or "Revised" License
115
[ "CHANGELOG.rst", "usagi/schema.py" ]
[ "CHANGELOG.rst", "usagi/schema.py" ]
WikiWatershed__tr-55-21
9f2680961841099dcbebaabdb460b11f8789a4ae
2015-04-30 20:03:55
9f2680961841099dcbebaabdb460b11f8789a4ae
diff --git a/README.md b/README.md index 72023c1..0bda9ed 100644 --- a/README.md +++ b/README.md @@ -4,73 +4,174 @@ A Python implementation of TR-55. ## Functions -`simulate_all_tiles` and `simulate_year` are the two functions intended for consumers of this module. +`simulate_day`, `simulate_year`, `simulate_modifications` are the three functions most likely to be of direct interest for users of this module. -### `simulate_all_tiles` +### `simulate_day` -The `simulate_all_tiles` function simulates the events of a single day. It takes three arguments: +The `simulate_day` function simulates the events of a single day. It takes four arguments: - 1. `parameters` which is either a `date` object (which is mapped to *precipitation* and *evapotranspiration* using sample year data) or that argument is a single day's *precipitation* and *evapotranspiration* as a tuple of two floats (in units of inches). + 1. `day` has one of two types. If it is an integer, it representing the day of the year (where `day == 0` represents October 15th) and is used to retrieve the precipitation and evapotranspiration for that day from the sample year table. Alternatively, `day` can be a tuple of precipitation and evapotranspiration. If the sample year data are to be considered typical, *precipitation* should generally be between 0 and 3 inches daily, and *evapotranspiration* should be between 0 and 0.2 inches daily. - 2. `tile_census` is a dictionary containing the number of appearances of each type of tile in the query area, e.g. + 2. `tile_census` is a dictionary containing the number of appearances of each type of tile in the query area, as well as modifications, e.g. ```Python - { - "result": { - "cell_count": 147, - "distribution": { - "d:hi_residential": 33, - "c:commercial": 42, - "a:deciduous_forest": 72 - } - } - } + { + "cell_count": 147, + "distribution": { + "d:hi_residential": {"cell_count": 33}, + "c:commercial": {"cell_count": 42}, + "a:deciduous_forest": {"cell_count": 72} + }, + "modifications": { + ":no_till": { + "cell_count": 30, + "distribution": { + "d:hi_residential": {"cell_count": 10}, + "c:commercial": {"cell_count": 20} + } + }, + "d:rock": { + "cell_count": 5, + "distribution": { + "a:deciduous_forest": {"cell_count": 5} + } + } + } + } ``` - Here, `"d:hi_residential"` indicates *High-Intensity Residential* land use on top of *Type D* soil. + Here, `"d:hi_residential"` indicates *High-Intensity Residential* land use on top of *Type D* soil, `"c:commerical"` indicates *Commercial* land use on top of *Type C* soil, and so on. - 3. `pre_columbian` is a boolean argument which controls whether or not to simulate the given area under pre-Columbian conditions. When this is set to true, all land-uses other than *water* and *wetland* are treated as *mixed forest*. + The `":no_till"` key and its value say that 10 units of `"d:hi_residential"` should be turned into `"d:no_till"` and 20 units of `"c:commercial"` should be turned into `"c:no_till"`. The `"d:rock"` key and its value say that 5 units of `"a:deciduous_forest"` should be reclassified as `"d:rock"`. -The algorithm used is close to TR-55 (the algorithm found in [the USDA's Technical Release 55, revised 1986](http://www.cpesc.org/reference/tr55.pdf)), but with a few differences. The main differences are: + 3. `subst` is a substitution that should be performed on the census. It is used to implement the BMPs/reclassifications mentioned above. When `subst` is a colon followed by a BMP, then the BMP is superimposed on all of the tiles in the census. When `subst` is a soil type and a land use, then all tiles in the census are treated as if they have that soil type and land use. + + 4. `pre_columbian` is a boolean argument which controls whether or not to simulate the given area under pre-Columbian conditions. When it set to true, all land-uses other than *water* and *wetland* are treated as *mixed forest*. + +The algorithm implemented by this code is close to TR-55, the algorithm found in [the USDA's Technical Release 55, revised 1986](http://www.cpesc.org/reference/tr55.pdf), but with a few differences. The main differences are: * it applies the TR-55 algorithm on a tile-by-tile basis and aggregates the results rather than running the TR-55 algorithm once over the entire area * it uses the *Pitt Small Storm Hydrology Model* on tiles which are of a "built-type" when precipitation is two inches or less -and there are numerous other small differences, as well. +and there are numerous other small differences. -`simulate_all_tiles` returns a triple of *runoff*, *evapotranspiration*, and *infiltration* (all in units of inches). +`simulate_day` returns a dictionary with `runoff`, `et`, and `inf` keys. All three of these numbers are in units of inches. ### `simulate_year` -The `simulate_year` function takes two parameters, `tile_census` and `pre_columbian` as described above, and simulates an entire year using a year's worth of sample precipitation and evapotranspiration data. It returns a triple of *runoff*, *evapotranspiration*, and *infiltration* for the given area over the entire sample year. +The `simulate_year` and simulates an entire year using one year of sample precipitation and evapotranspiration data. It returns a dictionary of with `runoff`, `et`, and `inf` keys, and also keys which map associated with various pollutant loads. + +The function takes four parameters. `tile_census`, `subst`, and `pre_columbian` as described above. The `cell_res` argument gives the resolution in meters of the data. + +### `simulate_modifications` + +This function takes three parameters, `tile_census`, `cell_res`, and `pre_columbian`, all as described above. The output of this function is similar to that of `simulate_year`, except it shows the results both with and without modifications. ## Usage Example The following program: ```Python -from tr55.model import simulate_year +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + +import pprint + +from tr55.model import simulate_modifications tiles = { - "result": { - "cell_count": 147, - "distribution": { - "d:hi_residential": 33, - "c:commercial": 42, - "a:deciduous_forest": 72 + "cell_count": 147, + "distribution": { + "d:hi_residential": {"cell_count": 33}, + "c:commercial": {"cell_count": 42}, + "a:deciduous_forest": {"cell_count": 72} + }, + "modifications": { + ":no_till": { + "cell_count": 30, + "distribution": { + "d:hi_residential": {"cell_count": 10}, + "c:commercial": {"cell_count": 20} + } + }, + "d:rock": { + "cell_count": 5, + "distribution": { + "a:deciduous_forest": {"cell_count": 5} + } } } } -(q, et, inf) = simulate_year(tiles) -print("%f inches of runoff" % q) -print("%f inches of et" % et) -print("%f inches of infiltration" % inf) +pprint.pprint(simulate_modifications(tiles)) ``` should produce the following output: -``` -17.614212 inches of runoff -15.167862 inches of et -20.245580 inches of infiltration +```Python +{u'modified': {u'bod': 1155.5832690023512, + u'cell_count': 147, + u'distribution': {u'a:deciduous_forest': {u'bod': 1.9676947491691286, + u'cell_count': 72, + u'et': 24.675262500000017, + u'inf': 34.53218880673186, + u'runoff': 0.7999320266014792, + u'tn': 0.006128885284297285, + u'tp': 0.00019354374581991428, + u'tss': 1.258034347829443}, + u'c:commercial': {u'bod': 619.3321622220828, + u'cell_count': 42, + u'et': 17.42526, + u'inf': 16.198443763932524, + u'runoff': 21.23295052178176, + u'tn': 4.545098932436254, + u'tp': 0.7192244464514511, + u'tss': 126.3137934080361}, + u'd:hi_residential': {u'bod': 534.2834120310993, + u'cell_count': 33, + u'et': 15.08352545454543, + u'inf': 13.967458770273502, + u'runoff': 24.498158107332266, + u'tn': 3.101560485095788, + u'tp': 0.5206999354540374, + u'tss': 63.842339912190674}}, + u'et': 20.450586122448982, + u'inf': 24.67740388835977, + u'runoff': 11.957947247429287, + u'tn': 7.652788302816338, + u'tp': 1.2401179256513084, + u'tss': 191.41416766805622}, + u'unmodified': {u'bod': 1762.555509187117, + u'cell_count': 147, + u'distribution': {u'a:deciduous_forest': {u'bod': 0.0, + u'cell_count': 72, + u'et': 26.51670000000007, + u'inf': 34.91810000000001, + u'runoff': 0.0, + u'tn': 0.0, + u'tp': 0.0, + u'tss': 0.0}, + u'c:commercial': {u'bod': 1061.0138827829708, + u'cell_count': 42, + u'et': 2.272860000000005, + u'inf': 4.430079770137537, + u'runoff': 36.375400229862464, + u'tn': 7.786472849455671, + u'tp': 1.2321451541995787, + u'tss': 216.39549270630107}, + u'd:hi_residential': {u'bod': 701.5416264041463, + u'cell_count': 33, + u'et': 6.818579999999993, + u'inf': 8.361629213022574, + u'runoff': 32.167342828759615, + u'tn': 4.072508593956273, + u'tp': 0.6837058223430238, + u'tss': 83.8282790872751}}, + u'et': 15.167861632653095, + u'inf': 20.24558036990151, + u'runoff': 17.614211721110824, + u'tn': 11.858981443411944, + u'tp': 1.9158509765426026, + u'tss': 300.2237717935762}} ``` ## Testing diff --git a/tr55/model.py b/tr55/model.py index 4e4cfc9..3ec4b0e 100644 --- a/tr55/model.py +++ b/tr55/model.py @@ -1,3 +1,8 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + """ TR-55 Model Implementation @@ -10,32 +15,34 @@ and variables used in this program are as follows: * `init_abs` is Ia, the initial abstraction, another form of infiltration """ -from datetime import date, timedelta -from tr55.tablelookup import days_in_sample_year -from tr55.tablelookup import lookup_et, lookup_p, lookup_cn -from tr55.tablelookup import lookup_bmp_infiltration, is_bmp, is_built_type +import sys + +from tr55.tablelookup import lookup_pet, lookup_cn, lookup_bmp_infiltration, \ + is_bmp, is_built_type, precolumbian, get_pollutants +from tr55.water_quality import get_volume_of_runoff, get_pollutant_load +from tr55.operations import dict_minus, dict_plus def runoff_pitt(precip, land_use): """ - The Pitt Small Storm Hydrology method. This comes from Table D in - the 2010/12/27 document. The output is a runoff value in inches. + The Pitt Small Storm Hydrology method. The output is a runoff + value in inches. """ - co1 = +3.638858398e-2 - co2 = -1.243464039e-1 - co3 = +1.295682223e-1 - co4 = +9.375868043e-1 - co5 = -2.235170859e-2 - co6 = +0.170228067e0 - co7 = -3.971810782e-1 - co8 = +3.887275538e-1 - co9 = -2.289321859e-2 - pr4 = pow(precip, 4) - pr3 = pow(precip, 3) - pr2 = pow(precip, 2) - - impervious = (co1 * pr3) + (co2 * pr2) + (co3 * precip) + co4 - urb_grass = (co5 * pr4) + (co6 * pr3) + (co7 * pr2) + (co8 * precip) + co9 + c1 = +3.638858398e-2 + c2 = -1.243464039e-1 + c3 = +1.295682223e-1 + c4 = +9.375868043e-1 + c5 = -2.235170859e-2 + c6 = +0.170228067e0 + c7 = -3.971810782e-1 + c8 = +3.887275538e-1 + c9 = -2.289321859e-2 + p4 = pow(precip, 4) + p3 = pow(precip, 3) + p2 = pow(precip, 2) + + impervious = (c1 * p3) + (c2 * p2) + (c3 * precip) + c4 + urb_grass = (c5 * p4) + (c6 * p3) + (c7 * p2) + (c8 * precip) + c9 runoff_vals = { 'water': impervious, @@ -47,8 +54,9 @@ def runoff_pitt(precip, land_use): 'transportation': impervious, 'urban_grass': urb_grass } + if land_use not in runoff_vals: - raise Exception('Land use %s not a built-type' % land_use) + raise Exception('Land use %s not a built-type.' % land_use) else: return min(runoff_vals[land_use], precip) @@ -71,7 +79,7 @@ def runoff_nrcs(precip, evaptrans, soil_type, land_use): """ curve_number = lookup_cn(soil_type, land_use) if nrcs_cutoff(precip, curve_number): - return 0 + return 0.0 potential_retention = (1000.0 / curve_number) - 10 initial_abs = 0.2 * potential_retention precip_minus_initial_abs = precip - initial_abs @@ -81,55 +89,43 @@ def runoff_nrcs(precip, evaptrans, soil_type, land_use): return min(runoff, precip - evaptrans) -def simulate_tile(parameters, tile_string, pre_columbian=False): +def simulate_tile(parameters, tile_string): """ - Simulate a tile on a given day using the method given in the - flowchart 2011_06_16_Stroud_model_diagram_revised.PNG and as - revised by various emails. + Simulate a single tile with some particular precipitation and + evapotranspiration. - The first argument can be one of two types. It can either be a - date object, in which case the precipitation and - evapotranspiration are looked up from the sample year table. - Alternatively, those two values can be supplied directly via this - argument as a tuple. + The first argument contains the precipitation and + evapotranspiration as a tuple. The second argument is a string which contains a soil type and - land use separted by a colon. - - The third argument is a boolean which is true if pre-Columbian - circumstances are to be simulated and false otherwise. + land use separated by a colon. - The return value is a triple of runoff, evapotranspiration, and + The return value is a dictionary of runoff, evapotranspiration, and infiltration. """ - tile_string = tile_string.lower(); - soil_type, land_use = tile_string.split(':') - - pre_columbian_land_uses = set([ - 'water', - 'woody_wetland', - 'herbaceous_wetland' - ]) - - if pre_columbian: - if land_use not in pre_columbian_land_uses: - land_use = 'mixed_forest' - - if type(parameters) is date: - precip = lookup_p(parameters) # precipitation - evaptrans = lookup_et(parameters, land_use) # evapotranspiration - elif type(parameters) is tuple: + if type(parameters) is tuple: precip, evaptrans = parameters else: - raise Exception('First argument must be a date or a (P,ET) pair') + raise Exception('First argument must be a (P,ET) pair') + + tile_string = tile_string.lower() + soil_type, land_use = tile_string.split(':') if precip == 0.0: - return (0.0, evaptrans, 0.0) + return { + 'runoff': 0.0, + 'et': evaptrans, + 'inf': 0.0, + } if is_bmp(land_use) and land_use != 'rain_garden': inf = lookup_bmp_infiltration(soil_type, land_use) # infiltration runoff = precip - (evaptrans + inf) # runoff - return (runoff, evaptrans, inf) # Q, ET, Inf. + return { + 'runoff': runoff, + 'et': evaptrans, + 'inf': inf, + } elif land_use == 'rain_garden': # Here, return a mixture of 20% ideal rain garden and 80% high # intensity residential. @@ -137,9 +133,11 @@ def simulate_tile(parameters, tile_string, pre_columbian=False): runoff = precip - (evaptrans + inf) hi_res_tile = soil_type + ':hi_residential' hi_res = simulate_tile((precip, evaptrans), hi_res_tile) - return (0.2 * runoff + 0.8 * hi_res[0], - 0.2 * evaptrans + 0.8 * hi_res[1], - 0.2 * inf + 0.8 * hi_res[2]) + return { + 'runoff': 0.2 * runoff + 0.8 * hi_res[0], + 'et': 0.2 * evaptrans + 0.8 * hi_res[1], + 'inf': 0.2 * inf + 0.8 * hi_res[2], + } if is_built_type(land_use) and precip <= 2.0: runoff = runoff_pitt(precip, land_use) @@ -150,75 +148,176 @@ def simulate_tile(parameters, tile_string, pre_columbian=False): else: runoff = runoff_nrcs(precip, evaptrans, soil_type, land_use) inf = precip - (evaptrans + runoff) - return (runoff, evaptrans, max(inf, 0.0)) + return { + 'runoff': runoff, + 'et': evaptrans, + 'inf': max(inf, 0.0), + } -def simulate_all_tiles(parameters, tile_census, pre_columbian=False): + +def simulate_day(day, tile_census, subst=None, pre_columbian=False): """ Simulate each tile for one day and return the overall results. - The first argument is either a day or a P,ET double (as in simulate_tile). + The first argument is an integer representing the day of the year + (day == 0 represents October 15th) or a precip, et pair. - The second argument is a dictionary (presumably converted from - JSON) that gives the number of each type of tile in the query - polygon. + The second argument is a dictionary that gives a census of all of the + tiles in the query area. - The output is a runoff, evapotranspiration, infiltration triple - which is an average of those produced by all of the tiles. - """ - if 'result' not in tile_census: - raise Exception('No "result" key') - elif 'cell_count' not in tile_census['result']: - raise Exception('No "result.cell_count" key') - elif 'distribution' not in tile_census['result']: - raise Exception('No "result.distribution" key') + The third argument is the tile string substitution to be applied + to each tile. This is used for simulating BMPs and + reclassifications. - global_count = tile_census['result']['cell_count'] + The fourth argument is a boolean which is true if pre-Columbian + circumstances are to be simulated and false otherwise. When this + argument is true, all land uses except for water and wetland are + transformed to mixed forest. - def simulate(tile_string, local_count): - """ - A local helper function which captures various values. - """ - return [(x * local_count) / global_count - for x in simulate_tile(parameters, tile_string, pre_columbian)] + The output is a runoff, evapotranspiration, infiltration dictionary. + """ + if 'cell_count' not in tile_census: + raise Exception('No "cell_count" key.') + elif 'distribution' not in tile_census: + raise Exception('No "distribution" key.') - def simulate_plus(left, right): + def simulate(tile, n): """ - Add two simulations. + Return the three values in units of inch-tiles instead of inches. + Inches are an inconvenient unit to work with. """ - (a, b, c) = left - (x, y, z) = right - return (a+x, b+y, c+z) + (soil_type, land_use) = tile.split(':') + + # If a substitution has been supplied, apply it. + if sys.version_info.major == 3: + types = (str) + else: + types = (str, unicode) + if isinstance(subst, types) and subst.find(':') >= 0: + (subst_soil_type, subst_land_use) = subst.split(':') + if len(subst_soil_type) > 0: + soil_type = subst_soil_type + land_use = subst_land_use + + # If a Pre-Columbian simulation has been requested, change the + # land use type. + if pre_columbian: + land_use = precolumbian(land_use) + + # Retrieve the precipitation and evapotranspiration, then run + # the simulation. + if isinstance(day, int): + parameters = lookup_pet(day, land_use) + else: + parameters = day + + retval = simulate_tile(parameters, soil_type + ':' + land_use) + for key in retval.keys(): + retval[key] *= n + return retval + + results = {tile: simulate(tile, d['cell_count']) + for tile, d in tile_census['distribution'].items()} + + return { + 'distribution': results + } - results = [simulate(tile, n) - for tile, n in tile_census['result']['distribution'].items()] - area_sum = (0.0, 0.0, 0.0) - for result in results: - area_sum = simulate_plus(area_sum, result) +def simulate_year(tile_census, cell_res=10, subst=None, pre_columbian=False): + """ + Simulate an entire year, including water quality. - return area_sum + The first argument is a tile census as described in `simulate_day`. + The second argument is the tile resolution in meters. -def simulate_year(tile_census, pre_columbian=False): - """ - Simulate an entire year. - """ - year = [date(1, 1, 1) + timedelta(days=i) - for i in range(days_in_sample_year())] - simulated_year = [simulate_all_tiles(day, tile_census, pre_columbian) - for day in year] + The third parameter is the tile string substitution to be performed. - def day_plus(one, two): - """ - Add two simulated days. - """ - (runoff1, et1, inf1) = one - (runoff2, et2, inf2) = two - return (runoff1 + runoff2, et1 + et2, inf1 + inf2) + The fourth parameter is as in `simulate_day`. + """ + # perform a daily simulation for each day of the year + simulated_year = [simulate_day(day, tile_census, subst, pre_columbian) + for day in range(365)] - year_sum = (0.0, 0.0, 0.0) + # add those simulations together + year_sum = {} for day in simulated_year: - year_sum = day_plus(year_sum, day) + year_sum = dict_plus(year_sum, day) - return year_sum + # add the results into the census + retval = dict_plus(year_sum, tile_census) + + # get the land use after the modification. + if isinstance(subst, str): + use_after = subst.split(':')[1] + else: + user_after = None # noqa + + # perform water quality computations + for (pair, result) in retval['distribution'].items(): + use_before = pair.split(':')[1] + runoff = result['runoff'] + n = result['cell_count'] + liters = get_volume_of_runoff(runoff / n, n, cell_res) + for pol in get_pollutants(): + # Try to compute the pollutant load with the land use + # after the modifications. If that is impossible (there + # is no modification, the use is modified to a BMP, et + # cetera) then use the previous land use. + try: + load = get_pollutant_load(use_after, pol, liters) + except: + load = get_pollutant_load(use_before, pol, liters) + result[pol] = load + + return retval + + +def simulate_modifications(tile_census, cell_res=10, pre_columbian=False): + """ + Simulate an entire year, including effects of modifications. + """ + def rescale(result): + if isinstance(result, dict): + if 'cell_count' in result: + n = float(result['cell_count']) + result['runoff'] /= n + result['et'] /= n + result['inf'] /= n + for (key, val) in result.items(): + rescale(val) + + def tally_subresults(result): + retval = result.copy() + total = {} + for (pair, subresult) in result['distribution'].items(): + total = dict_plus(total, subresult) + retval.update(total) + retval.pop('modifications', None) + rescale(retval) + return retval + + # compute unmodified results + orig_result = simulate_year(tile_census, cell_res, None, pre_columbian) + + # Compute the census ex-modifications and the subresults for each + # of the modifications. + mod_census = tile_census.copy() + subresults = [] + if 'modifications' in tile_census: + for (subst, census) in tile_census['modifications'].items(): + mod_census = dict_minus(mod_census, census) + subresult = simulate_year(census, cell_res, subst, pre_columbian) + subresults.append(subresult) + + # Compute the result with modifications taken into account. + mod_result = simulate_year(mod_census, cell_res, None, pre_columbian) + for subresult in subresults: + mod_result = dict_plus(mod_result, subresult) + + return { + 'unmodified': tally_subresults(orig_result), + 'modified': tally_subresults(mod_result) + } diff --git a/tr55/operations.py b/tr55/operations.py new file mode 100644 index 0000000..ae66328 --- /dev/null +++ b/tr55/operations.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + +import sys + + +def tandem_walk(op, pred, left, right): + """ + Walk two similarly-structured dictionaries in tandem, performing + the given operation when both halves satisfy the given predicate. + Otherwise, if both haves are dictionaries, recurse. + """ + if pred(left) and pred(right): + return op(left, right) + elif isinstance(left, dict) and isinstance(right, dict): + retval = left.copy() + left_set = set(left.keys()) + right_set = set(right.keys()) + intersection = left_set & right_set + difference = right_set - left_set + for key in intersection: + retval[key] = tandem_walk(op, pred, left[key], right[key]) + for key in difference: + retval[key] = right[key] + return retval + + +def isnumber(obj): + """ + Is obj a number? + """ + if sys.version_info.major == 3: + types = (int, float) + else: + types = (int, long, float) + return isinstance(obj, types) + + +def plus(x, y): + """ + Sum of two numbers. + """ + return x + y + + +def minus(x, y): + """ + Difference of two numbers. + """ + return x - y + + +def dict_plus(left, right): + """ + Sum of two similarly-structured dictionaries. + """ + return tandem_walk(plus, isnumber, left, right) + + +def dict_minus(left, right): + """ + Difference of two similarly-structured dictionaries. + """ + return tandem_walk(minus, isnumber, left, right) diff --git a/tr55/tablelookup.py b/tr55/tablelookup.py index 562b55c..eb5115e 100644 --- a/tr55/tablelookup.py +++ b/tr55/tablelookup.py @@ -1,80 +1,42 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + """ Various routines to do table lookups. """ -from datetime import date -from tr55.tables import SAMPLE_YEAR, BMPS, BUILT_TYPES, LAND_USE_VALUES +from tr55.tables import SAMPLE_YEAR, BMPS, BUILT_TYPES, LAND_USE_VALUES, \ + PRE_COLUMBIAN_LAND_USES, POLLUTANTS, POLLUTION_LOADS def lookup_ki(land_use): """ Lookup the landuse coefficient. """ - if land_use not in LAND_USE_VALUES or 'ki' not in LAND_USE_VALUES[land_use]: + if land_use not in LAND_USE_VALUES \ + or 'ki' not in LAND_USE_VALUES[land_use]: raise Exception('Unknown land use: %s' % land_use) else: return LAND_USE_VALUES[land_use]['ki'] -def lookup_et(simulation_day, land_use): +def lookup_pet(day, land_use): """ Lookup/compute evapotranspiration from the tables. """ - fixed_year = SAMPLE_YEAR['year_start'].year - simulation_day = date(fixed_year, simulation_day.month, simulation_day.day) - - # Compute $ET_{\max}$ based on the time of year - grow_start = SAMPLE_YEAR['growing_start'] - grow_end = SAMPLE_YEAR['growing_end'] - grow_et = SAMPLE_YEAR['growing_etmax'] - nongrow_et = SAMPLE_YEAR['nongrowing_etmax'] - if grow_start <= simulation_day and simulation_day <= grow_end: - et_max = grow_et - else: - et_max = nongrow_et - - # Compute the landuse coefficient - landuse_coefficient = LAND_USE_VALUES[land_use]['ki'] - - # Report $ET$, the evapotranspiration - return et_max * landuse_coefficient - - -def days_in_sample_year(): - """ - Return the number of days in the sample year. - """ - return SAMPLE_YEAR['days_per_year'] - - -def lookup_p(simulation_day): - """ - Lookup percipitation from the SAMPLE_YEAR table. - """ - fixed_year = SAMPLE_YEAR['year_start'].year - simulation_day = date(fixed_year, simulation_day.month, simulation_day.day) - seconds_per_day = 60 * 60 * 24 - days_per_year = SAMPLE_YEAR['days_per_year'] - day_delta = simulation_day - SAMPLE_YEAR['year_start'] - seconds_from_start = day_delta.total_seconds() - days_from_start = int(seconds_from_start / seconds_per_day) - - days = (days_from_start + days_per_year) % days_per_year - # This is a bit unattractive. If it turns out to be a performance - # problem (which is unlikely), an interval tree can be used or the - # SAMPLE_YEAR table itself can be reorganized. - for consecutive_days, precipitation in SAMPLE_YEAR['precipitation']: - if 0 <= days and days < consecutive_days: - return precipitation - days -= consecutive_days - raise Exception('No percipitation data for %s' % simulation_day) + (precip, et_max) = SAMPLE_YEAR[day] + ki = LAND_USE_VALUES[land_use]['ki'] + return (precip, et_max * ki) def lookup_bmp_infiltration(soil_type, bmp): """ Lookup the amount of infiltration causes by a particular BMP. """ - if bmp not in LAND_USE_VALUES or 'infiltration' not in LAND_USE_VALUES[bmp]: + if bmp not in LAND_USE_VALUES \ + or 'infiltration' not in LAND_USE_VALUES[bmp]: raise Exception('%s not a BMP' % bmp) elif soil_type not in LAND_USE_VALUES[bmp]['infiltration']: raise Exception('BMP %s incompatible with soil %s' % (bmp, soil_type)) @@ -88,7 +50,8 @@ def lookup_cn(soil_type, land_use): """ if land_use not in LAND_USE_VALUES: raise Exception('Unknown land use %s' % land_use) - elif 'cn' not in LAND_USE_VALUES[land_use] or soil_type not in LAND_USE_VALUES[land_use]['cn']: + elif 'cn' not in LAND_USE_VALUES[land_use] \ + or soil_type not in LAND_USE_VALUES[land_use]['cn']: raise Exception('Unknown soil type %s' % soil_type) else: return LAND_USE_VALUES[land_use]['cn'][soil_type] @@ -106,3 +69,48 @@ def is_built_type(land_use): Test to see if the land use is a "built type". """ return land_use in BUILT_TYPES + + +def precolumbian(land_use): + """ + Project the given land use to a Pre-Columbian one. + """ + if not land_use in PRE_COLUMBIAN_LAND_USES: + return 'mixed_forest' + else: + return land_use + + +def lookup_load(nlcd_class, pollutant): + """ + Get the Event Mean Concentration of `pollutant` for land use + class `nlcd_class` + """ + if pollutant not in ['tn', 'tp', 'bod', 'tss']: + raise Exception('Unknown pollutant type: %s' % pollutant) + + if nlcd_class not in POLLUTION_LOADS: + raise Exception('Unknown NLCD class: %s' % nlcd_class) + + return POLLUTION_LOADS[nlcd_class][pollutant] + + +def lookup_nlcd(land_use): + """ + Get the NLCD number for a particular human-readable land use. + """ + if land_use not in LAND_USE_VALUES: + raise Exception('Unknown land use type: %s' % land_use) + + if 'nlcd' not in LAND_USE_VALUES[land_use]: + raise Exception('Land use type %s does not have an NLCD class defined', + land_use) + + return LAND_USE_VALUES[land_use]['nlcd'] + + +def get_pollutants(): + """ + Return the list of pollutants. + """ + return POLLUTANTS diff --git a/tr55/tables.py b/tr55/tables.py index f94909a..a3ef230 100644 --- a/tr55/tables.py +++ b/tr55/tables.py @@ -1,146 +1,416 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + """ TR-55 tables """ -from datetime import date - -# The 'year_start' key points to the date on which this year-long -# dataset starts. The 'growing_start' and 'growing_end' keys point to -# dates giving the respective start and end of growing season. The -# values in the array associated with the 'precipitation' key are -# tuples of a number of consecutive days, and the amount of -# precipitation during that run of days. -SAMPLE_YEAR = { - 'year_start': date(1, 10, 15), # Sample year starts on 10/15 - 'days_per_year': 365, # The number of days in the sample year - - 'growing_start': date(1, 4, 15), # Growing season starts on 4/15 - 'growing_end': date(1, 10, 14), # The last day of growing season is 10/14 - 'growing_etmax': 0.207, # Max. e/t during growing season - 'nongrowing_etmax': 0.0, # ditto non-growing season +# The values in the array are tuples of inches of precipitation and +# evapotranspiration. October 15th is at index 0. +SAMPLE_YEAR = [ + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.0, 0.00), + (0.01, 0.0), + (0.01, 0.0), + (0.01, 0.0), + (0.01, 0.0), + (0.01, 0.0), + (0.01, 0.0), + (0.01, 0.0), + (0.02, 0.0), + (0.02, 0.0), + (0.02, 0.0), + (0.02, 0.0), + (0.03, 0.0), + (0.03, 0.0), + (0.03, 0.0), + (0.04, 0.0), + (0.04, 0.0), + (0.05, 0.0), + (0.05, 0.0), + (0.06, 0.0), + (0.06, 0.0), + (0.07, 0.0), + (0.07, 0.0), + (0.08, 0.0), + (0.09, 0.0), + (0.09, 0.0), + (0.10, 0.0), + (0.11, 0.0), + (0.11, 0.0), + (0.12, 0.0), + (0.14, 0.0), + (0.15, 0.0), + (0.16, 0.0), + (0.17, 0.0), + (0.18, 0.0), + (0.20, 0.0), + (0.21, 0.0), + (0.23, 0.0), + (0.25, 0.0), + (0.26, 0.0), + (0.28, 0.0), + (0.30, 0.0), + (0.33, 0.0), + (0.34, 0.0), + (0.37, 0.0), + (0.38, 0.0), + (0.41, 0.0), + (0.44, 0.0), + (0.48, 0.0), + (0.52, 0.0), + (0.55, 0.0), + (0.59, 0.0), + (0.63, 0.0), + (0.67, 0.0), + (0.72, 0.0), + (0.77, 0.0), + (0.82, 0.0), + (0.89, 0.0), + (0.98, 0.0), + (1.09, 0.0), + (1.22, 0.0), + (1.42, 0.0), + (1.92, 0.0), + (2.71, 0.207), + (1.88, 0.207), + (1.57, 0.207), + (1.33, 0.207), + (1.18, 0.207), + (1.06, 0.207), + (0.95, 0.207), + (0.86, 0.207), + (0.76, 0.207), + (0.69, 0.207), + (0.63, 0.207), + (0.57, 0.207), + (0.54, 0.207), + (0.50, 0.207), + (0.46, 0.207), + (0.43, 0.207), + (0.40, 0.207), + (0.37, 0.207), + (0.34, 0.207), + (0.33, 0.207), + (0.30, 0.207), + (0.28, 0.207), + (0.26, 0.207), + (0.25, 0.207), + (0.23, 0.207), + (0.22, 0.207), + (0.20, 0.207), + (0.18, 0.207), + (0.17, 0.207), + (0.16, 0.207), + (0.15, 0.207), + (0.13, 0.207), + (0.12, 0.207), + (0.11, 0.207), + (0.10, 0.207), + (0.10, 0.207), + (0.09, 0.207), + (0.08, 0.207), + (0.08, 0.207), + (0.07, 0.207), + (0.07, 0.207), + (0.06, 0.207), + (0.05, 0.207), + (0.05, 0.207), + (0.04, 0.207), + (0.04, 0.207), + (0.04, 0.207), + (0.03, 0.207), + (0.03, 0.207), + (0.03, 0.207), + (0.02, 0.207), + (0.02, 0.207), + (0.02, 0.207), + (0.02, 0.207), + (0.01, 0.207), + (0.01, 0.207), + (0.01, 0.207), + (0.01, 0.207), + (0.01, 0.207), + (0.01, 0.207), + (0.01, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207), + (0.00, 0.207) +] - 'precipitation': [ - (120, 0.00), - (7, 0.01), - (4, 0.02), - (3, 0.03), - (2, 0.04), - (2, 0.05), - (2, 0.06), - (2, 0.07), - (1, 0.08), - (2, 0.09), - (1, 0.10), - (2, 0.11), - (1, 0.12), - (1, 0.14), - (1, 0.15), - (1, 0.16), - (1, 0.17), - (1, 0.18), - (1, 0.20), - (1, 0.21), - (1, 0.23), - (1, 0.25), - (1, 0.26), - (1, 0.28), - (1, 0.30), - (1, 0.33), - (1, 0.34), - (1, 0.37), - (1, 0.38), - (1, 0.41), - (1, 0.44), - (1, 0.48), - (1, 0.52), - (1, 0.55), - (1, 0.59), - (1, 0.63), - (1, 0.67), - (1, 0.72), - (1, 0.77), - (1, 0.82), - (1, 0.89), - (1, 0.98), - (1, 1.09), - (1, 1.22), - (1, 1.42), - (1, 1.92), - - (1, 2.71), - (1, 1.88), - (1, 1.57), - (1, 1.33), - (1, 1.18), - (1, 1.06), - (1, 0.95), - (1, 0.86), - (1, 0.76), - (1, 0.69), - (1, 0.63), - (1, 0.57), - (1, 0.54), - (1, 0.50), - (1, 0.46), - (1, 0.43), - (1, 0.40), - (1, 0.37), - (1, 0.34), - (1, 0.33), - (1, 0.30), - (1, 0.28), - (1, 0.26), - (1, 0.25), - (1, 0.23), - (1, 0.22), - (1, 0.20), - (1, 0.18), - (1, 0.17), - (1, 0.16), - (1, 0.15), - (1, 0.13), - (1, 0.12), - (1, 0.11), - (2, 0.10), - (1, 0.09), - (2, 0.08), - (2, 0.07), - (1, 0.06), - (2, 0.05), - (3, 0.04), - (3, 0.03), - (4, 0.02), - (7, 0.01), - (122, 0.00) - ] -} +# Land use descriptions may map to the same nlcd code and have the same values +# but could be handled differently in the model execution (ex, commercial, +# industrial, transportation). Describes the NLCD class value, the landscape +# factor (ki) and the Curve Numbers for each hydrologic soil group for that use +# type. +# NOTE: Missing NLCD types 12 & 52 (plus all Alaska only types (51, 72-74) LAND_USE_VALUES = { - 'water': {'ki': 0.0, 'cn': {'a': 100, 'b': 100, 'c': 100, 'd': 100}}, - 'li_residential': {'ki': 0.42, 'cn': {'a': 51, 'b': 68, 'c': 79, 'd': 84}}, - 'hi_residential': {'ki': 0.18, 'cn': {'a': 77, 'b': 85, 'c': 90, 'd': 92}}, - 'commercial': {'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}}, - 'industrial': {'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}}, - 'transportation': {'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}}, - 'rock': {'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}}, - 'sand': {'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}}, - 'clay': {'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}}, - 'deciduous_forest': {'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}}, - 'evergreen_forest': {'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}}, - 'mixed_forest': {'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}}, - 'grassland': {'ki': 0.6, 'cn': {'a': 30, 'b': 58, 'c': 71, 'd': 78}}, - 'pasture': {'ki': 0.6, 'cn': {'a': 39, 'b': 61, 'c': 74, 'd': 80}}, - 'hay': {'ki': 0.6, 'cn': {'a': 39, 'b': 61, 'c': 74, 'd': 80}}, - 'row_crop': {'ki': 0.9, 'cn': {'a': 67, 'b': 78, 'c': 85, 'd': 89}}, - 'urban_grass': {'ki': 0.7, 'cn': {'a': 68, 'b': 79, 'c': 86, 'd': 89}}, - 'woody_wetland': {'ki': 1, 'cn': {'a': 98, 'b': 98, 'c': 98, 'd': 98}}, - 'herbaceous_wetland': {'ki': 1, 'cn': {'a': 98, 'b': 98, 'c': 98, 'd': 98}}, - 'green_roof': {'ki': 0.4, 'infiltration': {'a': 1.6, 'b': 1.6, 'c': 1.6, 'd': 1.6}}, - 'porous_paving': {'ki': 0.0, 'infiltration': {'a': 7.73, 'b': 4.13, 'c': 1.73}}, - 'rain_garden': {'ki': 0.08, 'infiltration': {'a': 1.2, 'b': 0.6, 'c': 0.2}}, - 'infiltration_trench': {'ki': 0.0, 'infiltration': {'a': 2.4, 'b': 1.8, 'c': 1.4}}, - 'cluster_housing': {'ki': 0.42}, - 'no_till': {'ki': 0.9, 'cn': {'a': 57, 'b': 73, 'c': 82, 'd': 86}} + 'water': {'nlcd': 11, 'ki': 0.0, 'cn': {'a': 100, 'b': 100, 'c': 100, 'd': 100}}, # noqa + 'li_residential': {'nlcd': 22, 'ki': 0.42, 'cn': {'a': 51, 'b': 68, 'c': 79, 'd': 84}}, # noqa + 'hi_residential': {'nlcd': 23, 'ki': 0.18, 'cn': {'a': 77, 'b': 85, 'c': 90, 'd': 92}}, # noqa + 'commercial': {'nlcd': 24, 'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}}, # noqa + 'industrial': {'nlcd': 24, 'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}}, # noqa + 'transportation': {'nlcd': 24, 'ki': 0.06, 'cn': {'a': 89, 'b': 92, 'c': 94, 'd': 95}}, # noqa + 'rock': {'nlcd': 31, 'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}}, # noqa + 'sand': {'nlcd': 31, 'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}}, # noqa + 'clay': {'nlcd': 31, 'ki': 0.0, 'cn': {'a': 77, 'b': 86, 'c': 86, 'd': 91}}, # noqa + 'deciduous_forest': {'nlcd': 41, 'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}}, # noqa + 'evergreen_forest': {'nlcd': 42, 'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}}, # noqa + 'mixed_forest': {'nlcd': 43, 'ki': 0.7, 'cn': {'a': 30, 'b': 55, 'c': 70, 'd': 77}}, # noqa + 'grassland': {'nlcd': 71, 'ki': 0.6, 'cn': {'a': 30, 'b': 58, 'c': 71, 'd': 78}}, # noqa + 'pasture': {'nlcd': 81, 'ki': 0.6, 'cn': {'a': 39, 'b': 61, 'c': 74, 'd': 80}}, # noqa + 'hay': {'nlcd': 81, 'ki': 0.6, 'cn': {'a': 39, 'b': 61, 'c': 74, 'd': 80}}, # noqa + 'row_crop': {'nlcd': 82, 'ki': 0.9, 'cn': {'a': 67, 'b': 78, 'c': 85, 'd': 89}}, # noqa + 'urban_grass': {'nlcd': 21, 'ki': 0.7, 'cn': {'a': 68, 'b': 79, 'c': 86, 'd': 89}}, # noqa + 'woody_wetland': {'nlcd': 90, 'ki': 1, 'cn': {'a': 98, 'b': 98, 'c': 98, 'd': 98}}, # noqa + 'herbaceous_wetland': {'nlcd': 95, 'ki': 1, 'cn': {'a': 98, 'b': 98, 'c': 98, 'd': 98}}, # noqa + + 'green_roof': {'ki': 0.4, 'infiltration': {'a': 1.6, 'b': 1.6, 'c': 1.6, 'd': 1.6}}, # noqa + 'porous_paving': {'ki': 0.0, 'infiltration': {'a': 7.73, 'b': 4.13, 'c': 1.73}}, # noqa + 'rain_garden': {'ki': 0.08, 'infiltration': {'a': 1.2, 'b': 0.6, 'c': 0.2}}, # noqa + 'infiltration_trench': {'ki': 0.0, 'infiltration': {'a': 2.4, 'b': 1.8, 'c': 1.4}}, # noqa + 'cluster_housing': {'ki': 0.42}, + 'no_till': {'ki': 0.9, 'cn': {'a': 57, 'b': 73, 'c': 82, 'd': 86}} # noqa } # The set of best management practices that we know about. The @@ -151,4 +421,49 @@ BMPS = set(['green_roof', 'porous_paving', # The set of "built" land uses BUILT_TYPES = set(['li_residential', 'hi_residential', 'cluster_housing', - 'commercial', 'industrial', 'transportation', 'urban_grass']) + 'commercial', 'industrial', 'transportation', + 'urban_grass']) + +PRE_COLUMBIAN_LAND_USES = set([ + 'water', + 'woody_wetland', + 'herbaceous_wetland' +]) + +# The set of pollutants that we are concerned with. +POLLUTANTS = set(['tn', 'tp', 'bod', 'tss']) + +# Event mean concentrations (mg/l) by pollutant and NLCD type +# tn: Total Nitrogen, tp: Total Phosphorus, +# bod: Biochemical Oxygen Demand, tss: Total Suspended Solids +POLLUTION_LOADS = { + 11: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0}, + 12: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0}, + 21: {'tn': 2.8, 'tp': 0.62, 'bod': 61, 'tss': 155.6}, + 22: {'tn': 4.15, 'tp': 0.8, 'bod': 309, 'tss': 147.1}, + 23: {'tn': 6.85, 'tp': 1.15, 'bod': 1180, 'tss': 141.0}, + 24: {'tn': 9.1, 'tp': 1.44, 'bod': 1240, 'tss': 252.9}, + 31: {'tn': 0.1, 'tp': 0.01, 'bod': 1320, 'tss': 10}, + 32: {'tn': 0.1, 'tp': 0.01, 'bod': 30, 'tss': 10}, + 41: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 39}, + 42: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 39}, + 43: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 39}, + 51: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0}, + 52: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 39}, + 71: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 47}, + 72: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0}, + 73: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0}, + 74: {'tn': 0, 'tp': 0, 'bod': 0, 'tss': 0}, + 81: {'tn': 23.0, 'tp': 3.0, 'bod': 1000, 'tss': 500}, + 82: {'tn': 23.0, 'tp': 3.0, 'bod': 1000, 'tss': 1000}, + 90: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0}, + 91: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0}, + 92: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0}, + 93: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0}, + 94: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0}, + 95: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0}, + 96: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0}, + 97: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0}, + 98: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0}, + 99: {'tn': 0.19, 'tp': 0.006, 'bod': 61, 'tss': 0} +} diff --git a/tr55/water_quality.py b/tr55/water_quality.py new file mode 100644 index 0000000..1abae85 --- /dev/null +++ b/tr55/water_quality.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + +from tr55.tablelookup import lookup_load, lookup_nlcd + + +def get_volume_of_runoff(runoff, cell_count, cell_resolution): + """ + Calculate the volume of runoff over the entire modeled area + + Args: + runoff (number): Q from TR55, averaged amount of runoff over a number + of cells. + + cell_count (integer): The number of cells included in the area + + tile_resolution (integer): The size in meters that a cell represents + + Returns: + The volume of runoff liters in of the total area of interest + """ + + # Runoff is in inches, so convert to meters which is the units for the cell + # area and compute the meter-cells in the group. Multiply the resolution + # of the cell to get the runoff volume in cubic meters. + inch_to_meter = 0.0254 + + runoff_m = runoff * inch_to_meter + meter_cells = runoff_m * cell_count + volume_cubic_meters = meter_cells * cell_resolution # XXX + + liters = volume_cubic_meters * 1000 + + return liters + + +def get_pollutant_load(use_type, pollutant, runoff_liters): + """ + Calculate the pollutant load over a particular land use type given an + amount of runoff generated on that area and an event mean concentration + of the pollutant. Returns the pollutant load in lbs. + """ + mg_per_kg = 1000000 + lbs_per_kg = 2.205 + + nlcd = lookup_nlcd(use_type) + emc = lookup_load(nlcd, pollutant) + + load_mg_l = emc * runoff_liters + + return (load_mg_l / mg_per_kg) * lbs_per_kg
Add simple water quality routine. Barry Evans has provided an algorithm to extend TR-55 results with simple water quality predictions based on the same workflow of the existing model.
WikiWatershed/tr-55
diff --git a/test/test_model.py b/test/test_model.py index ac66ae5..201b339 100644 --- a/test/test_model.py +++ b/test/test_model.py @@ -1,25 +1,28 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + """ Model test set """ import unittest -from datetime import date from math import sqrt -from tr55.tablelookup import lookup_ki, is_built_type -from tr55.model import runoff_nrcs, simulate_tile, simulate_all_tiles -from tr55.model import simulate_year + +from tr55.tablelookup import lookup_ki +from tr55.model import runoff_nrcs, simulate_tile, simulate_day # These data are taken directly from Table 2-1 of the revised (1986) # TR-55 report. The data in the PS array are various precipitation # levels, and each respective CNx array is the calculated runoff for # that particular curve number with the given level of precipitation # corresponding to that in PS. -PS = [1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0] -CN55 = [0.000, 0.000, 0.000, 0.000, 0.000, 0.020, 0.080, 0.190, 0.350, 0.530, 0.740, 0.980, 1.520, 2.120, 2.780, 3.490, 4.230, 5.000, 5.790, 6.610, 7.440, 8.290] -CN70 = [0.000, 0.030, 0.060, 0.110, 0.170, 0.240, 0.460, 0.710, 1.010, 1.330, 1.670, 2.040, 2.810, 3.620, 4.460, 5.330, 6.220, 7.130, 8.050, 8.980, 9.910, 10.85] -CN80 = [0.080, 0.150, 0.240, 0.340, 0.440, 0.560, 0.890, 1.250, 1.640, 2.040, 2.460, 2.890, 3.780, 4.690, 5.630, 6.570, 7.520, 8.480, 9.450, 10.42, 11.39, 12.37] -CN90 = [0.320, 0.460, 0.610, 0.760, 0.930, 1.090, 1.530, 1.980, 2.450, 2.920, 3.400, 3.880, 4.850, 5.820, 6.810, 7.790, 8.780, 9.770, 10.76, 11.76, 12.75, 13.74] - +PS = [1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0] # noqa +CN55 = [0.000, 0.000, 0.000, 0.000, 0.000, 0.020, 0.080, 0.190, 0.350, 0.530, 0.740, 0.980, 1.520, 2.120, 2.780, 3.490, 4.230, 5.000, 5.790, 6.610, 7.440, 8.290] # noqa +CN70 = [0.000, 0.030, 0.060, 0.110, 0.170, 0.240, 0.460, 0.710, 1.010, 1.330, 1.670, 2.040, 2.810, 3.620, 4.460, 5.330, 6.220, 7.130, 8.050, 8.980, 9.910, 10.85] # noqa +CN80 = [0.080, 0.150, 0.240, 0.340, 0.440, 0.560, 0.890, 1.250, 1.640, 2.040, 2.460, 2.890, 3.780, 4.690, 5.630, 6.570, 7.520, 8.480, 9.450, 10.42, 11.39, 12.37] # noqa +CN90 = [0.320, 0.460, 0.610, 0.760, 0.930, 1.090, 1.530, 1.980, 2.450, 2.920, 3.400, 3.880, 4.850, 5.820, 6.810, 7.790, 8.780, 9.770, 10.76, 11.76, 12.75, 13.74] # noqa # INPUT and OUTPUT are data that were emailed to Azavea in a # spreadsheet for testing the TR-55 model implementation. INPUT = [ @@ -592,23 +595,26 @@ OUTPUT = [ def simulate(precip, tile_string): soil_type, land_use = tile_string.split(':') ki = lookup_ki(land_use) - return simulate_tile((precip, 0.209 * ki), tile_string) + return simulate_tile((precip, 0.207 * ki), tile_string) + def average(l): return reduce(lambda x, y: x + y, l) / len(l) + class TestModel(unittest.TestCase): """ - Model test set + Model test set. """ def test_nrcs(self): """ Test the implementation of the runoff equation. """ - # This pair has CN=55 in Table C of the 2010/12/27 memo + # This pair has CN=55 runoffs = [round(runoff_nrcs(precip, 0.0, 'b', 'deciduous_forest'), 2) for precip in PS] - self.assertEqual(runoffs[4:], CN55[4:]) # Low curve number and low P cause too-high runoff + # Low curve number and low P cause too-high runoff + self.assertEqual(runoffs[4:], CN55[4:]) # This pair has CN=70 runoffs = [round(runoff_nrcs(precip, 0.0, 'c', 'deciduous_forest'), 2) @@ -625,104 +631,174 @@ class TestModel(unittest.TestCase): for precip in PS] self.assertEqual(runoffs, CN90) - def test_simulate_tile_horizontal(self): + def test_simulate_tile_1(self): """ - Test the one-day simulation using sample input/output. The number - 0.04 is not very meaningful, this test just attempts to give - you some idea about the mean error of the three quantities - relative to precipitation. + Test the tile simulation using sample input/output. + + The number 0.04 is not very meaningful, this test just + attempts to give some idea about the mean error of the three + quantities relative to precipitation. """ def similar(incoming, expected): precip, tile_string = incoming results = simulate(precip, tile_string) - me = average(map(lambda x, y: abs(x - y) / precip, results, expected)) + results = (results['runoff'], results['et'], results['inf']) + lam = lambda x, y: abs(x - y) / precip + me = average(map(lam, results, expected)) # Precipitation levels <= 2 inches are known to be # problematic. It is unclear why the 'rock' type is # giving trouble on soil types C and D. - if precip > 2 and tile_string != 'c:rock' and tile_string != 'd:rock': + if precip > 2 and tile_string != 'c:rock' \ + and tile_string != 'd:rock': self.assertTrue(me < 0.04, tile_string + ' ' + str(me)) map(similar, INPUT, OUTPUT) - def test_simulate_tiles_vertical(self): + def test_simulate_tile_2(self): """ - Test the RMSE of the runoff levels produced by the one-day - simulation against values sample input/output. The number - 0.13 is not very meaningful, this test just attempts to show - to deviation. + Test the RMSE of the runoff levels produced by the tile simulation + against values sample input/output. The number 0.13 is not + very meaningful, this test just attempts to put a bound on the + deviation. """ - results = [simulate(precip, tile_string)[0] / precip + results = [simulate(precip, tile_string)['runoff'] / precip for precip, tile_string in INPUT - if precip > 2 and tile_string != 'c:rock' and tile_string != 'd:rock'] + if precip > 2 and tile_string != 'c:rock' and + tile_string != 'd:rock'] expected = [OUTPUT[i][0] / INPUT[i][0] for i in range(len(INPUT)) - if INPUT[i][0] > 2 and INPUT[i][1] != 'c:rock' and INPUT[i][1] != 'd:rock'] - rmse = sqrt(average(map(lambda x, y: pow((x - y), 2), results, expected))) + if INPUT[i][0] > 2 and INPUT[i][1] != 'c:rock' and + INPUT[i][1] != 'd:rock'] + lam = lambda x, y: pow((x - y), 2) + rmse = sqrt(average(map(lam, results, expected))) self.assertTrue(rmse < 0.13) - def test_simulate_all_tiles(self): + def test_simulate_day_invalid(self): """ - Test the tile-by-tile simulation. + Test the daily simulation with bad responses. """ - # Test invalid responses + non_response1 = { + "cell_count": 1 + } + non_response2 = { - "result": { # No "distribution" key - "cell_count": 1 + "distribution": {} + } + + self.assertRaises(Exception, simulate_day, (0, non_response1)) + self.assertRaises(Exception, simulate_day, (0, non_response2)) + + def test_simulate_day_valid(self): + """ + Test the daily simulation with valid responses. + """ + response1 = { + "cell_count": 2, + "distribution": { + "a:pasture": 1, + "c:rock": 1 } } - non_response3 = { - "result": { # No "cell_count" key - "distribution": {} + + response2 = { + "cell_count": 20, + "distribution": { + "a:pasture": 10, + "c:rock": 10 } } - self.assertRaises(Exception, simulate_all_tiles, (date.today(), non_response2)) - self.assertRaises(Exception, simulate_all_tiles, (date.today(), non_response3)) - # Test valid responses + self.assertEqual( + simulate_day(0, response1), + simulate_day(0, response2)) + + def test_simulate_day_precolumbian(self): + """ + Test the daily simulation in Pre-Columbian times. + """ response1 = { - "result": { - "cell_count": 2, - "distribution": { - "a:pasture": 1, - "c:rock": 1 - } + "cell_count": 1, + "distribution": { + "d:hi_residential": 1 } } + response2 = { - "result": { - "cell_count": 20, - "distribution": { - "a:pasture": 10, - "c:rock": 10 - } + "cell_count": 10, + "distribution": { + "d:pasture": 10 } } - map(self.assertAlmostEqual, - simulate_all_tiles(date.today(), response1), - simulate_all_tiles(date.today(), response2)) - - # Test Pre-Columbian calculation - response3 = { - "result": { - "cell_count": 1, - "distribution": { - "d:hi_residential": 1 - } + + result1 = simulate_day(182, response1) + result2 = simulate_day(182, response2) + self.assertNotEqual( + result1['distribution']['d:hi_residential'], + result2['distribution']['d:pasture']) + + result3 = simulate_day(182, response1, pre_columbian=True) + result4 = simulate_day(182, response2, pre_columbian=True) + self.assertEqual( + result3['distribution']['d:hi_residential'], + result4['distribution']['d:pasture']) + + def test_simulate_day_subst_1(self): + """ + Test the daily simulation with BMP substitution. + """ + response1 = { + "cell_count": 1, + "distribution": { + "d:hi_residential": 1 } } - response4 = { - "result": { - "cell_count": 10, - "distribution": { - "d:pasture": 10 - } + + response2 = { + "cell_count": 1, + "distribution": { + "d:no_till": 1 } } - map(self.assertNotEqual, - simulate_all_tiles(date(1, 4, 15), response3), - simulate_all_tiles(date(1, 4, 15), response4)) - map(self.assertEqual, - simulate_all_tiles(date(1, 4, 15), response3, True), - simulate_all_tiles(date(1, 4, 15), response4, True)) + + result1 = simulate_day(182, response1) + result2 = simulate_day(182, response2) + self.assertNotEqual( + result1['distribution']['d:hi_residential'], + result2['distribution']['d:no_till']) + + result1 = simulate_day(182, response1, subst=':no_till') + self.assertEqual( + result1['distribution']['d:hi_residential'], + result2['distribution']['d:no_till']) + + def test_simulate_day_subst_2(self): + """ + Test the daily simulation with reclassification. + """ + response1 = { + "cell_count": 1, + "distribution": { + "d:mixed_forest": 1 + } + } + + response2 = { + "cell_count": 1, + "distribution": { + "a:rock": 1 + } + } + + result1 = simulate_day(182, response1) + result2 = simulate_day(182, response2) + self.assertNotEqual( + result1['distribution']['d:mixed_forest'], + result2['distribution']['a:rock']) + + result1 = simulate_day(182, response1, subst='a:rock') + self.assertEqual( + result1['distribution']['d:mixed_forest'], + result2['distribution']['a:rock']) + if __name__ == "__main__": unittest.main() diff --git a/test/test_operations.py b/test/test_operations.py new file mode 100644 index 0000000..5c5a77e --- /dev/null +++ b/test/test_operations.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + +""" +Operation tests. +""" + +import unittest + +from tr55.operations import dict_plus, dict_minus + + +class TestOperations(unittest.TestCase): + """ + Dictionary operation test set. + """ + def test_plus(self): + """ + Test dictionary addition. + """ + a = {'x': {'y': {'z': {'a': 1, 'b': 3, 'c': 13}}}} + b = {'x': {'y': {'z': {'a': 1, 'b': 5, 'c': 21}}}} + c = {'x': {'y': {'z': {'a': 2, 'b': 8, 'c': 34}}}} + self.assertEqual(dict_plus(a, b), c) + + def test_minus(self): + """ + Test dictionary subtraction. + """ + a = {'x': {'y': {'z': {'a': 34, 'b': 144, 'c': 610}}}} + b = {'x': {'y': {'z': {'a': 21, 'b': 89, 'c': 377}}}} + c = {'x': {'y': {'z': {'a': 13, 'b': 55, 'c': 233}}}} + self.assertEqual(dict_minus(a, b), c) + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_tablelookup.py b/test/test_tablelookup.py index f1b1e83..b9398b6 100644 --- a/test/test_tablelookup.py +++ b/test/test_tablelookup.py @@ -1,36 +1,32 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + """ -Table Lookup test set +Table Lookup test set. """ import unittest -from datetime import date -from tr55.tables import LAND_USE_VALUES -from tr55.tablelookup import lookup_et, lookup_p, lookup_bmp_infiltration, lookup_cn + +from tr55.tablelookup import lookup_pet, lookup_bmp_infiltration, lookup_cn class TestTablelookups(unittest.TestCase): """ Table Lookup test set """ - def test_lookup_p(self): + def test_lookup_pet(self): """ Do some spot-checks on the SampleYear data. """ - self.assertEqual(lookup_p(date(1, 10, 15)), 0.0) - self.assertEqual(lookup_p(date(1, 2, 12)), 0.01) - self.assertEqual(lookup_p(date(1, 2, 15)), 0.01) - self.assertEqual(lookup_p(date(1, 2, 19)), 0.02) - self.assertEqual(lookup_p(date(1, 10, 14)), 0.0) - - def test_lookup_et(self): - """ - Do some spot-checks on the data from Table A. - """ - self.assertEqual(lookup_et(date(1, 4, 15), 'woody_wetland'), 0.207) - self.assertEqual(lookup_et(date(1, 10, 14), 'woody_wetland'), 0.207) - self.assertTrue(lookup_et(date(1, 6, 15), 'commercial') > 0.0) - self.assertEqual(lookup_et(date(1, 4, 14), 'woody_wetland'), 0.0) - self.assertEqual(lookup_et(date(1, 10, 15), 'woody_wetland'), 0.0) + self.assertEqual(lookup_pet(0, 'water')[0], 0.0) + self.assertEqual(lookup_pet(52, 'hi_residential')[1], 0.0) + self.assertEqual(lookup_pet(104, 'green_roof')[1], 0.0) + self.assertEqual(lookup_pet(156, 'cluster_housing')[0], 0.23) + self.assertEqual(lookup_pet(208, 'grassland')[0], 0.2) + self.assertEqual(lookup_pet(260, 'woody_wetland')[1], 0.207) + self.assertEqual(lookup_pet(352, 'hay')[1], 0.207 * 0.6) def test_lookup_bmp_infiltration(self): """ @@ -39,7 +35,7 @@ class TestTablelookups(unittest.TestCase): self.assertEqual(lookup_bmp_infiltration('d', 'green_roof'), 1.6) self.assertEqual(lookup_bmp_infiltration('c', 'porous_paving'), 1.73) self.assertEqual(lookup_bmp_infiltration('b', 'rain_garden'), 0.6) - self.assertEqual(lookup_bmp_infiltration('a', 'infiltration_trench'), 2.4) + self.assertEqual(lookup_bmp_infiltration('a', 'infiltration_trench'), 2.4) # noqa def test_lookup_cn(self): """ diff --git a/test/test_water_quality.py b/test/test_water_quality.py new file mode 100644 index 0000000..f3cf6b7 --- /dev/null +++ b/test/test_water_quality.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + +import unittest +from tr55.water_quality import get_volume_of_runoff, get_pollutant_load +from tr55.tables import POLLUTION_LOADS + + +class TestWaterQuality(unittest.TestCase): + + def test_volume(self): + """ + Test the water volume computation. + """ + cell_res = 30 # meters + cell_count = 100 + runoff = 0.4 # inches + liters = get_volume_of_runoff(runoff, cell_count, cell_res) + + self.assertEquals(30480, liters, + "Did not calculate the correct runoff volume") + + def test_load(self): + """ + Test the pollutant load computation. + """ + nlcd = 24 + pollutant = 'tn' + emc = POLLUTION_LOADS[nlcd][pollutant] + runoff_liters = 1000 + + expected = ((runoff_liters * emc) / 1000000) * 2.205 + load = get_pollutant_load('commercial', pollutant, runoff_liters) + + self.assertEquals(expected, load) + + def test_load_bad_nlcd(self): + self.assertRaises(Exception, get_pollutant_load, 'asdf', 'tn', 1000) + + def test_load_bad_pollutant(self): + self.assertRaises(Exception, get_pollutant_load, 'commercial', + 'asdf', 1000)
{ "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": 3, "issue_text_score": 3, "test_score": 3 }, "num_modified_files": 4 }
unknown
{ "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" ], "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" }
exceptiongroup==1.2.2 iniconfig==2.1.0 nose==1.3.4 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 tomli==2.2.1 -e git+https://github.com/WikiWatershed/tr-55.git@9f2680961841099dcbebaabdb460b11f8789a4ae#egg=tr55
name: tr-55 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.4 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - tomli==2.2.1 prefix: /opt/conda/envs/tr-55
[ "test/test_model.py::TestModel::test_simulate_day_invalid", "test/test_model.py::TestModel::test_simulate_tile_1", "test/test_operations.py::TestOperations::test_minus", "test/test_operations.py::TestOperations::test_plus", "test/test_tablelookup.py::TestTablelookups::test_lookup_bmp_infiltration", "test/test_tablelookup.py::TestTablelookups::test_lookup_cn", "test/test_tablelookup.py::TestTablelookups::test_lookup_pet", "test/test_water_quality.py::TestWaterQuality::test_load", "test/test_water_quality.py::TestWaterQuality::test_load_bad_nlcd", "test/test_water_quality.py::TestWaterQuality::test_load_bad_pollutant", "test/test_water_quality.py::TestWaterQuality::test_volume" ]
[ "test/test_model.py::TestModel::test_nrcs", "test/test_model.py::TestModel::test_simulate_day_precolumbian", "test/test_model.py::TestModel::test_simulate_day_subst_1", "test/test_model.py::TestModel::test_simulate_day_subst_2", "test/test_model.py::TestModel::test_simulate_day_valid", "test/test_model.py::TestModel::test_simulate_tile_2" ]
[]
[]
Apache License 2.0
116
[ "tr55/model.py", "tr55/water_quality.py", "tr55/tablelookup.py", "README.md", "tr55/operations.py", "tr55/tables.py" ]
[ "tr55/model.py", "tr55/water_quality.py", "tr55/tablelookup.py", "README.md", "tr55/operations.py", "tr55/tables.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
[ "conductr_cli/bundle_utils.py", "conductr_cli/conduct_services.py", "conductr_cli/conduct_load.py", "conductr_cli/conduct_stop.py", "conductr_cli/conduct_logging.py", "conductr_cli/conduct_info.py", "conductr_cli/conduct_unload.py", "conductr_cli/conduct_version.py", "conductr_cli/conduct_run.py", "conductr_cli/conduct.py" ]
[ "conductr_cli/bundle_utils.py", "conductr_cli/conduct_services.py", "conductr_cli/conduct_load.py", "conductr_cli/conduct_stop.py", "conductr_cli/conduct_logging.py", "conductr_cli/conduct_info.py", "conductr_cli/conduct_unload.py", "conductr_cli/conduct_version.py", "conductr_cli/conduct_run.py", "conductr_cli/conduct.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
[ "falcon/routing/compiled.py" ]
[ "falcon/routing/compiled.py" ]
mne-tools__mne-python-2053
1164d58d954f4dae9266b551d9d3efb979c3f597
2015-05-02 21:12:47
edceb8f38349d6dc0cade1c9f8384cc0707ce3e8
diff --git a/mne/io/meas_info.py b/mne/io/meas_info.py index 6e850b71a..b55a983b6 100644 --- a/mne/io/meas_info.py +++ b/mne/io/meas_info.py @@ -31,7 +31,7 @@ from ..externals.six import b, BytesIO, string_types, text_type _kind_dict = dict( - eeg=(FIFF.FIFFV_EEG_CH, FIFF.FIFFV_COIL_NONE, FIFF.FIFF_UNIT_V), + eeg=(FIFF.FIFFV_EEG_CH, FIFF.FIFFV_COIL_EEG, FIFF.FIFF_UNIT_V), mag=(FIFF.FIFFV_MEG_CH, FIFF.FIFFV_COIL_VV_MAG_T3, FIFF.FIFF_UNIT_T), grad=(FIFF.FIFFV_MEG_CH, FIFF.FIFFV_COIL_VV_PLANAR_T1, FIFF.FIFF_UNIT_T_M), misc=(FIFF.FIFFV_MISC_CH, FIFF.FIFFV_COIL_NONE, FIFF.FIFF_UNIT_NONE),
Initialise coil types How to initialize coil types in info object? ``` chans = mne.channels.read_montage('BrainAmpMRIPlus_32sfp', ch_names=None, path= datapath, unit='mm', transform=False) chanNames = chans.ch_names info = mne.create_info(chanNames, 250.0, ch_types='eeg') layout = mne.channels.find_layout(info, ch_type='eeg', exclude=None) eventOnset = np.array(range(1,41))*2 eventZero = np.ones(40) eventId = np.ones(40) events = np.transpose(np.vstack((eventOnset, eventZero, eventId))) epochs = mne.EpochsArray(cueLtemp, info, events, tmin=0, event_id=None, reject=None, flat=None, reject_tmin=None, reject_tmax=None, verbose=None) epochs.set_montage(chans) epochs.plot_projs_topomap(ch_type='eeg', layout=layout) ``` I get RuntimeError: No EEG channels present. Cannot find EEG layout. when I run mne.channels.find_layout() If I use create_info with ch_types = 'eeg' shouldn't the coil type be eeg also? what exactly is the coil type and coil trans anyway? Should they be initialised? Since I am learning mne is all this stuff explained somewhere or is this the only place I can ask questions? I went through the examples and they all use standard data sets. I am coming from matlab and my data is preprocessed in matlab. Thanks for helping me out guys
mne-tools/mne-python
diff --git a/mne/io/tests/test_meas_info.py b/mne/io/tests/test_meas_info.py index 7668f36dd..588ac65a1 100644 --- a/mne/io/tests/test_meas_info.py +++ b/mne/io/tests/test_meas_info.py @@ -24,6 +24,15 @@ hsp_fname = op.join(data_dir, 'test_hsp.txt') elp_fname = op.join(data_dir, 'test_elp.txt') +def test_make_info(): + """Test some create_info properties + """ + n_ch = 1 + info = create_info(n_ch, 1000., 'eeg') + coil_types = set([ch['coil_type'] for ch in info['chs']]) + assert_true(FIFF.FIFFV_COIL_EEG in coil_types) + + def test_fiducials_io(): """Test fiducials i/o""" tempdir = _TempDir()
{ "commit_name": "head_commit", "failed_lite_validators": [], "has_test_patch": true, "is_lite": true, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "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@1164d58d954f4dae9266b551d9d3efb979c3f597#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/io/tests/test_meas_info.py::test_make_info" ]
[]
[ "mne/io/tests/test_meas_info.py::test_fiducials_io", "mne/io/tests/test_meas_info.py::test_info", "mne/io/tests/test_meas_info.py::test_read_write_info", "mne/io/tests/test_meas_info.py::test_io_dig_points", "mne/io/tests/test_meas_info.py::test_make_dig_points" ]
[]
BSD 3-Clause "New" or "Revised" License
119
[ "mne/io/meas_info.py" ]
[ "mne/io/meas_info.py" ]
softlayer__softlayer-python-542
6ece88935972d6165adba9f2ea19e56020967c55
2015-05-03 21:31:29
1195b2020ef6efc40462d59eb079f26e5f39a6d8
diff --git a/SoftLayer/CLI/formatting.py b/SoftLayer/CLI/formatting.py index 138e5318..b7f25a5c 100644 --- a/SoftLayer/CLI/formatting.py +++ b/SoftLayer/CLI/formatting.py @@ -192,8 +192,8 @@ def no_going_back(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): + ans = click.prompt(prompt, default='', show_default=False) + if ans.lower() == str(confirmation): return True return False diff --git a/SoftLayer/managers/messaging.py b/SoftLayer/managers/messaging.py index 6c7e0237..8c273b6b 100644 --- a/SoftLayer/managers/messaging.py +++ b/SoftLayer/managers/messaging.py @@ -168,7 +168,12 @@ def _make_request(self, method, path, **kwargs): url = '/'.join((self.endpoint, 'v1', self.account_id, path)) resp = requests.request(method, url, **kwargs) - resp.raise_for_status() + try: + resp.raise_for_status() + except requests.HTTPError as ex: + content = json.loads(ex.response.content) + raise exceptions.SoftLayerAPIError(ex.response.status_code, + content['message']) return resp def authenticate(self, username, api_key, auth_token=None):
dns record-remove AttributeError I think the transcript speaks for itself. :) ``` $ slcli --version slcli (SoftLayer Command-line), version 4.0.1 $ slcli dns record-remove 56530852 This action cannot be undone! Type "yes" or press Enter to abort: yes An unexpected error has occured: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/SoftLayer/CLI/core.py", line 180, in main cli.main() File "/usr/local/lib/python2.7/site-packages/click/core.py", line 644, in main rv = self.invoke(ctx) File "/usr/local/lib/python2.7/site-packages/click/core.py", line 991, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python2.7/site-packages/click/core.py", line 991, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python2.7/site-packages/click/core.py", line 837, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python2.7/site-packages/click/core.py", line 464, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/click/decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args[1:], **kwargs) File "/usr/local/lib/python2.7/site-packages/click/core.py", line 464, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/SoftLayer/CLI/dns/record_remove.py", line 20, in cli if not (env.skip_confirmations or formatting.no_going_back('yes')): File "/usr/local/lib/python2.7/site-packages/SoftLayer/CLI/formatting.py", line 195, in no_going_back ans = click.confirm(prompt, default='', show_default=False).lower() AttributeError: 'bool' object has no attribute 'lower' Feel free to report this error as it is likely a bug: https://github.com/softlayer/softlayer-python/issues ```
softlayer/softlayer-python
diff --git a/SoftLayer/tests/CLI/helper_tests.py b/SoftLayer/tests/CLI/helper_tests.py index 1dea9ab4..d6017355 100644 --- a/SoftLayer/tests/CLI/helper_tests.py +++ b/SoftLayer/tests/CLI/helper_tests.py @@ -41,21 +41,21 @@ def test_fail(self): class PromptTests(testing.TestCase): - @mock.patch('click.confirm') - def test_do_or_die(self, confirm_mock): + @mock.patch('click.prompt') + def test_do_or_die(self, prompt_mock): confirmed = '37347373737' - confirm_mock.return_value = confirmed + prompt_mock.return_value = confirmed result = formatting.no_going_back(confirmed) self.assertTrue(result) # no_going_back should cast int's to str() confirmed = '4712309182309' - confirm_mock.return_value = confirmed + prompt_mock.return_value = confirmed result = formatting.no_going_back(int(confirmed)) self.assertTrue(result) confirmed = None - confirm_mock.return_value = '' + prompt_mock.return_value = '' result = formatting.no_going_back(confirmed) self.assertFalse(result)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 1, "test_score": 0 }, "num_modified_files": 2 }
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@6ece88935972d6165adba9f2ea19e56020967c55#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/helper_tests.py::PromptTests::test_do_or_die" ]
[]
[ "SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_default", "SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_fail", "SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_confirmation", "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" ]
[]
MIT License
120
[ "SoftLayer/CLI/formatting.py", "SoftLayer/managers/messaging.py" ]
[ "SoftLayer/CLI/formatting.py", "SoftLayer/managers/messaging.py" ]
softlayer__softlayer-python-543
6ece88935972d6165adba9f2ea19e56020967c55
2015-05-03 23:26:15
1195b2020ef6efc40462d59eb079f26e5f39a6d8
diff --git a/SoftLayer/CLI/formatting.py b/SoftLayer/CLI/formatting.py index 138e5318..41556a9a 100644 --- a/SoftLayer/CLI/formatting.py +++ b/SoftLayer/CLI/formatting.py @@ -73,6 +73,7 @@ def format_prettytable(table): for i, row in enumerate(table.rows): for j, item in enumerate(row): table.rows[i][j] = format_output(item) + ptable = table.prettytable() ptable.hrules = prettytable.FRAME ptable.horizontal_char = '.' @@ -83,12 +84,15 @@ def format_prettytable(table): def format_no_tty(table): """Converts SoftLayer.CLI.formatting.Table instance to a prettytable.""" + for i, row in enumerate(table.rows): for j, item in enumerate(row): table.rows[i][j] = format_output(item, fmt='raw') ptable = table.prettytable() + for col in table.columns: ptable.align[col] = 'l' + ptable.hrules = prettytable.NONE ptable.border = False ptable.header = False @@ -304,6 +308,30 @@ def __str__(self): __repr__ = __str__ + # Implement sorting methods. + # NOTE(kmcdonald): functools.total_ordering could be used once support for + # Python 2.6 is dropped + def __eq__(self, other): + return self.original == getattr(other, 'original', other) + + def __lt__(self, other): + if self.original is None: + return True + + other_val = getattr(other, 'original', other) + if other_val is None: + return False + return self.original < other_val + + def __gt__(self, other): + return not (self < other or self == other) + + def __le__(self, other): + return self < other or self == other + + def __ge__(self, other): + return not self < other + def _format_python_value(value): """If the value has to_python() defined then return that.""" diff --git a/SoftLayer/CLI/server/list.py b/SoftLayer/CLI/server/list.py index 03ba456e..d6f45622 100644 --- a/SoftLayer/CLI/server/list.py +++ b/SoftLayer/CLI/server/list.py @@ -14,7 +14,7 @@ @click.command() @click.option('--sortby', help='Column to sort by', - type=click.Choice(['guid', + type=click.Choice(['id', 'hostname', 'primary_ip', 'backend_ip',
unable to pipe out the `slcli server list commands` Running `slcli server list` works fine, but it throws an error when piping to another file (or grep) `slcli vs list` can pipe to another unix commands fine. `slcli server list | tee /tmp/a` An unexpected error has occured: Traceback (most recent call last): File "/usr/local/lib/python3.4/site-packages/SoftLayer-4.0.1-py3.4.egg/SoftLayer/CLI/core.py", line 180, in main cli.main() File "/usr/local/lib/python3.4/site-packages/click/core.py", line 644, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.4/site-packages/click/core.py", line 991, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python3.4/site-packages/click/core.py", line 959, in _process_result **ctx.params) File "/usr/local/lib/python3.4/site-packages/click/core.py", line 464, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python3.4/site-packages/SoftLayer-4.0.1-py3.4.egg/SoftLayer/CLI/core.py", line 162, in output_result output = env.fmt(result) File "/usr/local/lib/python3.4/site-packages/SoftLayer-4.0.1-py3.4.egg/SoftLayer/CLI/environment.py", line 45, in fmt return formatting.format_output(output, fmt=self.format) File "/usr/local/lib/python3.4/site-packages/SoftLayer-4.0.1-py3.4.egg/SoftLayer/CLI/formatting.py", line 38, in format_output return str(format_no_tty(data)) File "/usr/local/lib/python3.4/site-packages/prettytable.py", line 237, in __str__ return self.__unicode__() File "/usr/local/lib/python3.4/site-packages/prettytable.py", line 243, in __unicode__ return self.get_string() File "/usr/local/lib/python3.4/site-packages/prettytable.py", line 984, in get_string rows = self._get_rows(options) File "/usr/local/lib/python3.4/site-packages/prettytable.py", line 933, in _get_rows rows.sort(reverse=options["reversesort"], key=options["sort_key"]) TypeError: unorderable types: FormattedItem() < str() Feel free to report this error as it is likely a bug: https://github.com/softlayer/softlayer-python/issues
softlayer/softlayer-python
diff --git a/SoftLayer/testing/fixtures/SoftLayer_Account.py b/SoftLayer/testing/fixtures/SoftLayer_Account.py index 994d5fb6..9e1a43da 100644 --- a/SoftLayer/testing/fixtures/SoftLayer_Account.py +++ b/SoftLayer/testing/fixtures/SoftLayer_Account.py @@ -136,7 +136,7 @@ 'friendlyName': 'Friendly Transaction Name', 'id': 6660 } - } + }, }, { 'id': 1001, 'globalIdentifier': '1a2b3c-1702', @@ -224,6 +224,8 @@ 'id': 19082 }, ] +}, { + 'id': 1003, }] getDomains = [{'name': 'example.com', 'id': 12345, diff --git a/SoftLayer/tests/CLI/helper_tests.py b/SoftLayer/tests/CLI/helper_tests.py index 1dea9ab4..e693535a 100644 --- a/SoftLayer/tests/CLI/helper_tests.py +++ b/SoftLayer/tests/CLI/helper_tests.py @@ -131,6 +131,27 @@ def test_blank(self): self.assertEqual('-', item.formatted) self.assertEqual('NULL', str(item)) + def test_sort_mixed(self): + blank = formatting.blank() + items = [10, blank] + sorted_items = sorted(items) + self.assertEqual(sorted_items, [blank, 10]) + + items = [blank, 10] + sorted_items = sorted(items) + self.assertEqual(sorted_items, [blank, 10]) + + items = [blank, "10"] + sorted_items = sorted(items) + self.assertEqual(sorted_items, [blank, "10"]) + + def test_sort(self): + items = [10, formatting.FormattedItem(20), formatting.FormattedItem(5)] + sorted_items = sorted(items) + self.assertEqual(sorted_items, [formatting.FormattedItem(5), + 10, + formatting.FormattedItem(20)]) + class FormattedListTests(testing.TestCase): def test_init(self): diff --git a/SoftLayer/tests/CLI/modules/server_tests.py b/SoftLayer/tests/CLI/modules/server_tests.py index a65538cf..85df2f42 100644 --- a/SoftLayer/tests/CLI/modules/server_tests.py +++ b/SoftLayer/tests/CLI/modules/server_tests.py @@ -84,11 +84,19 @@ def test_list_servers(self): 'id': 1002, 'backend_ip': '10.1.0.4', 'action': None, - } + }, + { + 'action': None, + 'backend_ip': None, + 'datacenter': None, + 'hostname': None, + 'id': 1003, + 'primary_ip': None, + }, ] self.assertEqual(result.exit_code, 0) - self.assertEqual(json.loads(result.output), expected) + self.assertEqual(expected, json.loads(result.output)) @mock.patch('SoftLayer.CLI.formatting.no_going_back') @mock.patch('SoftLayer.HardwareManager.reload') diff --git a/SoftLayer/tests/managers/hardware_tests.py b/SoftLayer/tests/managers/hardware_tests.py index 79aa5025..efec2591 100644 --- a/SoftLayer/tests/managers/hardware_tests.py +++ b/SoftLayer/tests/managers/hardware_tests.py @@ -78,7 +78,7 @@ def test_list_hardware_with_filters(self): def test_resolve_ids_ip(self): _id = self.hardware._get_ids_from_ip('172.16.1.100') - self.assertEqual(_id, [1000, 1001, 1002]) + self.assertEqual(_id, [1000, 1001, 1002, 1003]) _id = self.hardware._get_ids_from_ip('nope') self.assertEqual(_id, []) @@ -93,7 +93,7 @@ def test_resolve_ids_ip(self): def test_resolve_ids_hostname(self): _id = self.hardware._get_ids_from_hostname('hardware-test1') - self.assertEqual(_id, [1000, 1001, 1002]) + self.assertEqual(_id, [1000, 1001, 1002, 1003]) def test_get_hardware(self): result = self.hardware.get_hardware(1000)
{ "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": 2, "issue_text_score": 0, "test_score": 0 }, "num_modified_files": 2 }
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@6ece88935972d6165adba9f2ea19e56020967c55#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/helper_tests.py::FormattedItemTests::test_sort", "SoftLayer/tests/CLI/helper_tests.py::FormattedItemTests::test_sort_mixed" ]
[]
[ "SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_default", "SoftLayer/tests/CLI/helper_tests.py::CLIJSONEncoderTest::test_fail", "SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_confirmation", "SoftLayer/tests/CLI/helper_tests.py::PromptTests::test_do_or_die", "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/server_tests.py::ServerCLITests::test_cancel_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_options", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_missing_required", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_test_flag", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_create_server_with_export", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_failed", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userdata_and_file", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_edit_server_userfile", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_list_servers", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_nic_edit_server", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_cancel_reasons", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_details", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_cycle_negative", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_off", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_power_on", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_default", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_hard", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_negative", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reboot_soft", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_server_reload", "SoftLayer/tests/CLI/modules/server_tests.py::ServerCLITests::test_update_firmware", "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
121
[ "SoftLayer/CLI/formatting.py", "SoftLayer/CLI/server/list.py" ]
[ "SoftLayer/CLI/formatting.py", "SoftLayer/CLI/server/list.py" ]
falconry__falcon-540
3791b3a1c9e210e2e04a8a57f64561101685ef0e
2015-05-04 22:59:32
b78ffaac7c412d3b3d6cd3c70dd05024d79d2cce
diff --git a/falcon/request.py b/falcon/request.py index b16e154..74915a0 100644 --- a/falcon/request.py +++ b/falcon/request.py @@ -599,7 +599,7 @@ class Request(object): if not required: return None - raise HTTPMissingParam(name) + raise HTTPMissingHeader(name) def get_header_as_datetime(self, header, required=False): """Return an HTTP header with HTTP-Date values as a datetime.
Request.get_header raises the wrong exception Found an issue that is making exception-handling not very intuitive when dealing with required headers... ``` try: my_header = req.get_header('My-Header', required=True) except falcon.HTTPMissingHeader: print 'Missing header' except falcon.HTTPMissingParam: print 'Missing param' # Prints "Missing param" ``` Basically, calling ``get_header()`` with ``required=True`` should raise a ``HTTPMissingHeader`` exception, when actually what gets raised is ``HTTPMissingParam``. This also leads to confusing error response messages, since the response title and header refer to a missing, required "query parameter" instead of a "header".
falconry/falcon
diff --git a/tests/test_headers.py b/tests/test_headers.py index f2a689a..654eee9 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -183,9 +183,14 @@ class TestHeaders(testing.TestBase): def test_required_header(self): self.simulate_request(self.test_route) - self.assertRaises(falcon.HTTPBadRequest, - self.resource.req.get_header, 'X-Not-Found', - required=True) + try: + self.resource.req.get_header('X-Not-Found', required=True) + self.fail('falcon.HTTPMissingHeader not raised') + except falcon.HTTPMissingHeader as ex: + self.assertIsInstance(ex, falcon.HTTPBadRequest) + self.assertEqual(ex.title, 'Missing header value') + expected_desc = 'The X-Not-Found header is required.' + self.assertEqual(ex.description, expected_desc) def test_no_body_on_100(self): self.resource = StatusTestResource(falcon.HTTP_100) diff --git a/tests/test_query_params.py b/tests/test_query_params.py index 893afda..d6adbf8 100644 --- a/tests/test_query_params.py +++ b/tests/test_query_params.py @@ -94,6 +94,7 @@ class _TestQueryParams(testing.TestBase): getattr(req, method_name)('marker', required=True) self.fail('falcon.HTTPMissingParam not raised') except falcon.HTTPMissingParam as ex: + self.assertIsInstance(ex, falcon.HTTPBadRequest) self.assertEqual(ex.title, 'Missing query parameter') expected_desc = 'The "marker" query parameter is required.' self.assertEqual(ex.description, expected_desc)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 0, "issue_text_score": 0, "test_score": 3 }, "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": [ "nose", "nose-cov", "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 cov-core==1.15.0 coverage==7.8.0 ddt==1.7.2 exceptiongroup==1.2.2 -e git+https://github.com/falconry/falcon.git@3791b3a1c9e210e2e04a8a57f64561101685ef0e#egg=falcon idna==3.10 iniconfig==2.1.0 nose==1.3.7 nose-cov==1.6 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 - cov-core==1.15.0 - coverage==7.8.0 - ddt==1.7.2 - exceptiongroup==1.2.2 - idna==3.10 - iniconfig==2.1.0 - nose==1.3.7 - nose-cov==1.6 - 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_headers.py::TestHeaders::test_required_header" ]
[]
[ "tests/test_headers.py::TestHeaders::test_add_link_complex", "tests/test_headers.py::TestHeaders::test_add_link_multiple", "tests/test_headers.py::TestHeaders::test_add_link_single", "tests/test_headers.py::TestHeaders::test_add_link_with_anchor", "tests/test_headers.py::TestHeaders::test_add_link_with_hreflang", "tests/test_headers.py::TestHeaders::test_add_link_with_hreflang_multi", "tests/test_headers.py::TestHeaders::test_add_link_with_title", "tests/test_headers.py::TestHeaders::test_add_link_with_title_star", "tests/test_headers.py::TestHeaders::test_add_link_with_type_hint", "tests/test_headers.py::TestHeaders::test_content_header_missing", "tests/test_headers.py::TestHeaders::test_content_length", "tests/test_headers.py::TestHeaders::test_custom_content_type", "tests/test_headers.py::TestHeaders::test_custom_media_type", "tests/test_headers.py::TestHeaders::test_default_media_type", "tests/test_headers.py::TestHeaders::test_default_value", "tests/test_headers.py::TestHeaders::test_get_raw_headers", "tests/test_headers.py::TestHeaders::test_no_body_on_100", "tests/test_headers.py::TestHeaders::test_no_body_on_101", "tests/test_headers.py::TestHeaders::test_no_body_on_204", "tests/test_headers.py::TestHeaders::test_no_body_on_304", "tests/test_headers.py::TestHeaders::test_no_content_type", "tests/test_headers.py::TestHeaders::test_passthrough_req_headers", "tests/test_headers.py::TestHeaders::test_passthrough_resp_headers", "tests/test_headers.py::TestHeaders::test_response_append_header", "tests/test_headers.py::TestHeaders::test_response_header_helpers_on_get", "tests/test_headers.py::TestHeaders::test_response_set_header", "tests/test_headers.py::TestHeaders::test_unicode_location_headers", "tests/test_headers.py::TestHeaders::test_vary_header", "tests/test_headers.py::TestHeaders::test_vary_headers", "tests/test_headers.py::TestHeaders::test_vary_headers_tuple", "tests/test_headers.py::TestHeaders::test_vary_star", "tests/test_query_params.py::_TestQueryParams::test_allowed_names", "tests/test_query_params.py::_TestQueryParams::test_blank", "tests/test_query_params.py::_TestQueryParams::test_boolean", "tests/test_query_params.py::_TestQueryParams::test_boolean_blank", "tests/test_query_params.py::_TestQueryParams::test_get_date_invalid", "tests/test_query_params.py::_TestQueryParams::test_get_date_missing_param", "tests/test_query_params.py::_TestQueryParams::test_get_date_store", "tests/test_query_params.py::_TestQueryParams::test_get_date_valid", "tests/test_query_params.py::_TestQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::_TestQueryParams::test_int", "tests/test_query_params.py::_TestQueryParams::test_int_neg", "tests/test_query_params.py::_TestQueryParams::test_list_transformer", "tests/test_query_params.py::_TestQueryParams::test_list_type", "tests/test_query_params.py::_TestQueryParams::test_list_type_blank", "tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys", "tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::_TestQueryParams::test_none", "tests/test_query_params.py::_TestQueryParams::test_param_property", "tests/test_query_params.py::_TestQueryParams::test_percent_encoded", "tests/test_query_params.py::_TestQueryParams::test_required_1_get_param", "tests/test_query_params.py::_TestQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::_TestQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::_TestQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::_TestQueryParams::test_simple", "tests/test_query_params.py::PostQueryParams::test_allowed_names", "tests/test_query_params.py::PostQueryParams::test_blank", "tests/test_query_params.py::PostQueryParams::test_boolean", "tests/test_query_params.py::PostQueryParams::test_boolean_blank", "tests/test_query_params.py::PostQueryParams::test_get_date_invalid", "tests/test_query_params.py::PostQueryParams::test_get_date_missing_param", "tests/test_query_params.py::PostQueryParams::test_get_date_store", "tests/test_query_params.py::PostQueryParams::test_get_date_valid", "tests/test_query_params.py::PostQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::PostQueryParams::test_int", "tests/test_query_params.py::PostQueryParams::test_int_neg", "tests/test_query_params.py::PostQueryParams::test_list_transformer", "tests/test_query_params.py::PostQueryParams::test_list_type", "tests/test_query_params.py::PostQueryParams::test_list_type_blank", "tests/test_query_params.py::PostQueryParams::test_multiple_form_keys", "tests/test_query_params.py::PostQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::PostQueryParams::test_non_ascii", "tests/test_query_params.py::PostQueryParams::test_none", "tests/test_query_params.py::PostQueryParams::test_param_property", "tests/test_query_params.py::PostQueryParams::test_percent_encoded", "tests/test_query_params.py::PostQueryParams::test_required_1_get_param", "tests/test_query_params.py::PostQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::PostQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::PostQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::PostQueryParams::test_simple", "tests/test_query_params.py::GetQueryParams::test_allowed_names", "tests/test_query_params.py::GetQueryParams::test_blank", "tests/test_query_params.py::GetQueryParams::test_boolean", "tests/test_query_params.py::GetQueryParams::test_boolean_blank", "tests/test_query_params.py::GetQueryParams::test_get_date_invalid", "tests/test_query_params.py::GetQueryParams::test_get_date_missing_param", "tests/test_query_params.py::GetQueryParams::test_get_date_store", "tests/test_query_params.py::GetQueryParams::test_get_date_valid", "tests/test_query_params.py::GetQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::GetQueryParams::test_int", "tests/test_query_params.py::GetQueryParams::test_int_neg", "tests/test_query_params.py::GetQueryParams::test_list_transformer", "tests/test_query_params.py::GetQueryParams::test_list_type", "tests/test_query_params.py::GetQueryParams::test_list_type_blank", "tests/test_query_params.py::GetQueryParams::test_multiple_form_keys", "tests/test_query_params.py::GetQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::GetQueryParams::test_none", "tests/test_query_params.py::GetQueryParams::test_param_property", "tests/test_query_params.py::GetQueryParams::test_percent_encoded", "tests/test_query_params.py::GetQueryParams::test_required_1_get_param", "tests/test_query_params.py::GetQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::GetQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::GetQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::GetQueryParams::test_simple" ]
[]
Apache License 2.0
122
[ "falcon/request.py" ]
[ "falcon/request.py" ]
falconry__falcon-541
6912cdc1232754f8e8be4bd25ce150f9485012c2
2015-05-05 00:11:45
b78ffaac7c412d3b3d6cd3c70dd05024d79d2cce
diff --git a/doc/api/routing.rst b/doc/api/routing.rst index b76ba4f..c0ce2d2 100644 --- a/doc/api/routing.rst +++ b/doc/api/routing.rst @@ -43,4 +43,4 @@ A custom routing engine may be specified when instantiating api = API(router=fancy) .. automodule:: falcon.routing - :members: create_http_method_map, CompiledRouter + :members: create_http_method_map, compile_uri_template, CompiledRouter diff --git a/falcon/request.py b/falcon/request.py index 74915a0..b16e154 100644 --- a/falcon/request.py +++ b/falcon/request.py @@ -599,7 +599,7 @@ class Request(object): if not required: return None - raise HTTPMissingHeader(name) + raise HTTPMissingParam(name) def get_header_as_datetime(self, header, required=False): """Return an HTTP header with HTTP-Date values as a datetime. diff --git a/falcon/routing/__init__.py b/falcon/routing/__init__.py index 6498a47..9ced8d6 100644 --- a/falcon/routing/__init__.py +++ b/falcon/routing/__init__.py @@ -14,6 +14,7 @@ from falcon.routing.compiled import CompiledRouter from falcon.routing.util import create_http_method_map # NOQA +from falcon.routing.util import compile_uri_template # NOQA DefaultRouter = CompiledRouter diff --git a/falcon/routing/util.py b/falcon/routing/util.py index 40625af..e4f258e 100644 --- a/falcon/routing/util.py +++ b/falcon/routing/util.py @@ -12,10 +12,72 @@ # See the License for the specific language governing permissions and # limitations under the License. +import re + +import six + from falcon import HTTP_METHODS, responders from falcon.hooks import _wrap_with_hooks +# NOTE(kgriffs): Published method; take care to avoid breaking changes. +def compile_uri_template(template): + """Compile the given URI template string into a pattern matcher. + + This function can be used to construct custom routing engines that + iterate through a list of possible routes, attempting to match + an incoming request against each route's compiled regular expression. + + Each field is converted to a named group, so that when a match + is found, the fields can be easily extracted using + :py:meth:`re.MatchObject.groupdict`. + + This function does not support the more flexible templating + syntax used in the default router. Only simple paths with bracketed + field expressions are recognized. For example:: + + / + /books + /books/{isbn} + /books/{isbn}/characters + /books/{isbn}/characters/{name} + + Also, note that if the template contains a trailing slash character, + it will be stripped in order to normalize the routing logic. + + Args: + template(str): The template to compile. Note that field names are + restricted to ASCII a-z, A-Z, and the underscore character. + + Returns: + tuple: (template_field_names, template_regex) + """ + + if not isinstance(template, six.string_types): + raise TypeError('uri_template is not a string') + + if not template.startswith('/'): + raise ValueError("uri_template must start with '/'") + + if '//' in template: + raise ValueError("uri_template may not contain '//'") + + if template != '/' and template.endswith('/'): + template = template[:-1] + + expression_pattern = r'{([a-zA-Z][a-zA-Z_]*)}' + + # Get a list of field names + fields = set(re.findall(expression_pattern, template)) + + # Convert Level 1 var patterns to equivalent named regex groups + escaped = re.sub(r'[\.\(\)\[\]\?\*\+\^\|]', r'\\\g<0>', template) + pattern = re.sub(expression_pattern, r'(?P<\1>[^/]+)', escaped) + pattern = r'\A' + pattern + r'\Z' + + return fields, re.compile(pattern, re.IGNORECASE) + + def create_http_method_map(resource, before, after): """Maps HTTP methods (e.g., 'GET', 'POST') to methods of a resource object.
Has compile_uri_template been removed? I can't see it in the code any more.
falconry/falcon
diff --git a/tests/test_headers.py b/tests/test_headers.py index 654eee9..f2a689a 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -183,14 +183,9 @@ class TestHeaders(testing.TestBase): def test_required_header(self): self.simulate_request(self.test_route) - try: - self.resource.req.get_header('X-Not-Found', required=True) - self.fail('falcon.HTTPMissingHeader not raised') - except falcon.HTTPMissingHeader as ex: - self.assertIsInstance(ex, falcon.HTTPBadRequest) - self.assertEqual(ex.title, 'Missing header value') - expected_desc = 'The X-Not-Found header is required.' - self.assertEqual(ex.description, expected_desc) + self.assertRaises(falcon.HTTPBadRequest, + self.resource.req.get_header, 'X-Not-Found', + required=True) def test_no_body_on_100(self): self.resource = StatusTestResource(falcon.HTTP_100) diff --git a/tests/test_query_params.py b/tests/test_query_params.py index d6adbf8..893afda 100644 --- a/tests/test_query_params.py +++ b/tests/test_query_params.py @@ -94,7 +94,6 @@ class _TestQueryParams(testing.TestBase): getattr(req, method_name)('marker', required=True) self.fail('falcon.HTTPMissingParam not raised') except falcon.HTTPMissingParam as ex: - self.assertIsInstance(ex, falcon.HTTPBadRequest) self.assertEqual(ex.title, 'Missing query parameter') expected_desc = 'The "marker" query parameter is required.' self.assertEqual(ex.description, expected_desc) diff --git a/tests/test_uri_templates_legacy.py b/tests/test_uri_templates_legacy.py new file mode 100644 index 0000000..538f4be --- /dev/null +++ b/tests/test_uri_templates_legacy.py @@ -0,0 +1,96 @@ +import ddt + +import falcon +from falcon import routing +import falcon.testing as testing + + [email protected] +class TestUriTemplates(testing.TestBase): + + def test_string_type_required(self): + self.assertRaises(TypeError, routing.compile_uri_template, 42) + self.assertRaises(TypeError, routing.compile_uri_template, falcon.API) + + def test_template_must_start_with_slash(self): + self.assertRaises(ValueError, routing.compile_uri_template, 'this') + self.assertRaises(ValueError, routing.compile_uri_template, 'this/that') + + def test_template_may_not_contain_double_slash(self): + self.assertRaises(ValueError, routing.compile_uri_template, '//') + self.assertRaises(ValueError, routing.compile_uri_template, 'a//') + self.assertRaises(ValueError, routing.compile_uri_template, '//b') + self.assertRaises(ValueError, routing.compile_uri_template, 'a//b') + self.assertRaises(ValueError, routing.compile_uri_template, 'a/b//') + self.assertRaises(ValueError, routing.compile_uri_template, 'a/b//c') + + def test_root(self): + fields, pattern = routing.compile_uri_template('/') + self.assertFalse(fields) + self.assertFalse(pattern.match('/x')) + + result = pattern.match('/') + self.assertTrue(result) + self.assertFalse(result.groupdict()) + + @ddt.data('/hello', '/hello/world', '/hi/there/how/are/you') + def test_no_fields(self, path): + fields, pattern = routing.compile_uri_template(path) + self.assertFalse(fields) + self.assertFalse(pattern.match(path[:-1])) + + result = pattern.match(path) + self.assertTrue(result) + self.assertFalse(result.groupdict()) + + def test_one_field(self): + fields, pattern = routing.compile_uri_template('/{name}') + self.assertEqual(fields, set(['name'])) + + result = pattern.match('/Kelsier') + self.assertTrue(result) + self.assertEqual(result.groupdict(), {'name': 'Kelsier'}) + + fields, pattern = routing.compile_uri_template('/character/{name}') + self.assertEqual(fields, set(['name'])) + + result = pattern.match('/character/Kelsier') + self.assertTrue(result) + self.assertEqual(result.groupdict(), {'name': 'Kelsier'}) + + fields, pattern = routing.compile_uri_template('/character/{name}/profile') + self.assertEqual(fields, set(['name'])) + + self.assertFalse(pattern.match('/character')) + self.assertFalse(pattern.match('/character/Kelsier')) + self.assertFalse(pattern.match('/character/Kelsier/')) + + result = pattern.match('/character/Kelsier/profile') + self.assertTrue(result) + self.assertEqual(result.groupdict(), {'name': 'Kelsier'}) + + @ddt.data('', '/') + def test_two_fields(self, postfix): + path = '/book/{id}/characters/{name}' + postfix + fields, pattern = routing.compile_uri_template(path) + self.assertEqual(fields, set(['name', 'id'])) + + result = pattern.match('/book/0765350386/characters/Vin') + self.assertTrue(result) + self.assertEqual(result.groupdict(), {'name': 'Vin', 'id': '0765350386'}) + + def test_three_fields(self): + fields, pattern = routing.compile_uri_template('/{a}/{b}/x/{c}') + self.assertEqual(fields, set('abc')) + + result = pattern.match('/one/2/x/3') + self.assertTrue(result) + self.assertEqual(result.groupdict(), {'a': 'one', 'b': '2', 'c': '3'}) + + def test_malformed_field(self): + fields, pattern = routing.compile_uri_template('/{a}/{1b}/x/{c}') + self.assertEqual(fields, set('ac')) + + result = pattern.match('/one/{1b}/x/3') + self.assertTrue(result) + self.assertEqual(result.groupdict(), {'a': 'one', 'c': '3'})
{ "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": 2, "issue_text_score": 2, "test_score": 2 }, "num_modified_files": 4 }
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@6912cdc1232754f8e8be4bd25ce150f9485012c2#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_uri_templates_legacy.py::TestUriTemplates::test_malformed_field", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_no_fields_1__hello", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_no_fields_2__hello_world", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_no_fields_3__hi_there_how_are_you", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_one_field", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_root", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_string_type_required", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_template_may_not_contain_double_slash", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_template_must_start_with_slash", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_three_fields", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_two_fields_1_", "tests/test_uri_templates_legacy.py::TestUriTemplates::test_two_fields_2__" ]
[]
[ "tests/test_headers.py::TestHeaders::test_add_link_complex", "tests/test_headers.py::TestHeaders::test_add_link_multiple", "tests/test_headers.py::TestHeaders::test_add_link_single", "tests/test_headers.py::TestHeaders::test_add_link_with_anchor", "tests/test_headers.py::TestHeaders::test_add_link_with_hreflang", "tests/test_headers.py::TestHeaders::test_add_link_with_hreflang_multi", "tests/test_headers.py::TestHeaders::test_add_link_with_title", "tests/test_headers.py::TestHeaders::test_add_link_with_title_star", "tests/test_headers.py::TestHeaders::test_add_link_with_type_hint", "tests/test_headers.py::TestHeaders::test_content_header_missing", "tests/test_headers.py::TestHeaders::test_content_length", "tests/test_headers.py::TestHeaders::test_custom_content_type", "tests/test_headers.py::TestHeaders::test_custom_media_type", "tests/test_headers.py::TestHeaders::test_default_media_type", "tests/test_headers.py::TestHeaders::test_default_value", "tests/test_headers.py::TestHeaders::test_get_raw_headers", "tests/test_headers.py::TestHeaders::test_no_body_on_100", "tests/test_headers.py::TestHeaders::test_no_body_on_101", "tests/test_headers.py::TestHeaders::test_no_body_on_204", "tests/test_headers.py::TestHeaders::test_no_body_on_304", "tests/test_headers.py::TestHeaders::test_no_content_type", "tests/test_headers.py::TestHeaders::test_passthrough_req_headers", "tests/test_headers.py::TestHeaders::test_passthrough_resp_headers", "tests/test_headers.py::TestHeaders::test_required_header", "tests/test_headers.py::TestHeaders::test_response_append_header", "tests/test_headers.py::TestHeaders::test_response_header_helpers_on_get", "tests/test_headers.py::TestHeaders::test_response_set_header", "tests/test_headers.py::TestHeaders::test_unicode_location_headers", "tests/test_headers.py::TestHeaders::test_vary_header", "tests/test_headers.py::TestHeaders::test_vary_headers", "tests/test_headers.py::TestHeaders::test_vary_headers_tuple", "tests/test_headers.py::TestHeaders::test_vary_star", "tests/test_query_params.py::_TestQueryParams::test_allowed_names", "tests/test_query_params.py::_TestQueryParams::test_blank", "tests/test_query_params.py::_TestQueryParams::test_boolean", "tests/test_query_params.py::_TestQueryParams::test_boolean_blank", "tests/test_query_params.py::_TestQueryParams::test_get_date_invalid", "tests/test_query_params.py::_TestQueryParams::test_get_date_missing_param", "tests/test_query_params.py::_TestQueryParams::test_get_date_store", "tests/test_query_params.py::_TestQueryParams::test_get_date_valid", "tests/test_query_params.py::_TestQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::_TestQueryParams::test_int", "tests/test_query_params.py::_TestQueryParams::test_int_neg", "tests/test_query_params.py::_TestQueryParams::test_list_transformer", "tests/test_query_params.py::_TestQueryParams::test_list_type", "tests/test_query_params.py::_TestQueryParams::test_list_type_blank", "tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys", "tests/test_query_params.py::_TestQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::_TestQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::_TestQueryParams::test_none", "tests/test_query_params.py::_TestQueryParams::test_param_property", "tests/test_query_params.py::_TestQueryParams::test_percent_encoded", "tests/test_query_params.py::_TestQueryParams::test_required_1_get_param", "tests/test_query_params.py::_TestQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::_TestQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::_TestQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::_TestQueryParams::test_simple", "tests/test_query_params.py::PostQueryParams::test_allowed_names", "tests/test_query_params.py::PostQueryParams::test_blank", "tests/test_query_params.py::PostQueryParams::test_boolean", "tests/test_query_params.py::PostQueryParams::test_boolean_blank", "tests/test_query_params.py::PostQueryParams::test_get_date_invalid", "tests/test_query_params.py::PostQueryParams::test_get_date_missing_param", "tests/test_query_params.py::PostQueryParams::test_get_date_store", "tests/test_query_params.py::PostQueryParams::test_get_date_valid", "tests/test_query_params.py::PostQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::PostQueryParams::test_int", "tests/test_query_params.py::PostQueryParams::test_int_neg", "tests/test_query_params.py::PostQueryParams::test_list_transformer", "tests/test_query_params.py::PostQueryParams::test_list_type", "tests/test_query_params.py::PostQueryParams::test_list_type_blank", "tests/test_query_params.py::PostQueryParams::test_multiple_form_keys", "tests/test_query_params.py::PostQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::PostQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::PostQueryParams::test_non_ascii", "tests/test_query_params.py::PostQueryParams::test_none", "tests/test_query_params.py::PostQueryParams::test_param_property", "tests/test_query_params.py::PostQueryParams::test_percent_encoded", "tests/test_query_params.py::PostQueryParams::test_required_1_get_param", "tests/test_query_params.py::PostQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::PostQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::PostQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::PostQueryParams::test_simple", "tests/test_query_params.py::GetQueryParams::test_allowed_names", "tests/test_query_params.py::GetQueryParams::test_blank", "tests/test_query_params.py::GetQueryParams::test_boolean", "tests/test_query_params.py::GetQueryParams::test_boolean_blank", "tests/test_query_params.py::GetQueryParams::test_get_date_invalid", "tests/test_query_params.py::GetQueryParams::test_get_date_missing_param", "tests/test_query_params.py::GetQueryParams::test_get_date_store", "tests/test_query_params.py::GetQueryParams::test_get_date_valid", "tests/test_query_params.py::GetQueryParams::test_get_date_valid_with_format", "tests/test_query_params.py::GetQueryParams::test_int", "tests/test_query_params.py::GetQueryParams::test_int_neg", "tests/test_query_params.py::GetQueryParams::test_list_transformer", "tests/test_query_params.py::GetQueryParams::test_list_type", "tests/test_query_params.py::GetQueryParams::test_list_type_blank", "tests/test_query_params.py::GetQueryParams::test_multiple_form_keys", "tests/test_query_params.py::GetQueryParams::test_multiple_form_keys_as_list", "tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_bool", "tests/test_query_params.py::GetQueryParams::test_multiple_keys_as_int", "tests/test_query_params.py::GetQueryParams::test_none", "tests/test_query_params.py::GetQueryParams::test_param_property", "tests/test_query_params.py::GetQueryParams::test_percent_encoded", "tests/test_query_params.py::GetQueryParams::test_required_1_get_param", "tests/test_query_params.py::GetQueryParams::test_required_2_get_param_as_int", "tests/test_query_params.py::GetQueryParams::test_required_3_get_param_as_bool", "tests/test_query_params.py::GetQueryParams::test_required_4_get_param_as_list", "tests/test_query_params.py::GetQueryParams::test_simple" ]
[]
Apache License 2.0
123
[ "falcon/request.py", "falcon/routing/util.py", "falcon/routing/__init__.py", "doc/api/routing.rst" ]
[ "falcon/request.py", "falcon/routing/util.py", "falcon/routing/__init__.py", "doc/api/routing.rst" ]
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
[ "mkdocs/utils.py", "mkdocs/nav.py", "mkdocs/build.py" ]
[ "mkdocs/utils.py", "mkdocs/nav.py", "mkdocs/build.py" ]
sensiblecodeio__xypath-76
2de90e58b881b271a743ae5c60c5e03904d2ef7f
2015-05-05 12:42:50
2de90e58b881b271a743ae5c60c5e03904d2ef7f
diff --git a/.travis.yml b/.travis.yml index 1e8f611..ea3c474 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,8 @@ language: python python: - "2.7" + - "3.4" + - "3.5" # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors install: - pip install setuptools --upgrade # fix for html5lib diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..201d0c7 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM ubuntu:16.04 + +RUN apt-get update && \ + apt-get install -y \ + python-pip \ + python3-pip + +RUN locale-gen en_GB.UTF-8 + +RUN mkdir /home/nobody && \ + chown nobody /home/nobody + +USER nobody +ENV HOME=/home/nobody \ + PATH=/home/nobody/.local/bin:$PATH \ + LANG=en_GB.UTF-8 +# LANG needed for httpretty install on Py3 + +WORKDIR /home/nobody + +RUN pip install --user nose messytables pyhamcrest +RUN pip3 install --user nose messytables pyhamcrest + +COPY . /home/nobody/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..688d376 --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +run: build + @docker run --rm --tty --interactive xypath + +build: + @docker build --tag xypath . + +.PHONY: run build diff --git a/requirements.txt b/requirements.txt index 21c6ad0..f0559e8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,3 @@ -messytables==0.15.0 +messytables==0.15.1 nose coverage diff --git a/setup.py b/setup.py index 9d40510..14947e8 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ navigating around and extracting values from tabular data. setup( name='xypath', - version='1.0.12', + version='1.1.0', description="Extract fields from tabular data with complex expressions.", long_description=long_desc, classifiers=[ @@ -16,7 +16,10 @@ setup( "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: POSIX :: Linux", - "Programming Language :: Python", + "Operating System :: Microsoft :: Windows", + "Programming Language :: Python 2.7", + "Programming Language :: Python 3.4", + "Programming Language :: Python 3.5", ], keywords='', author='The Sensible Code Company Ltd', @@ -28,7 +31,7 @@ setup( include_package_data=False, zip_safe=False, install_requires=[ - 'messytables==0.15', + 'messytables==0.15.1', ], tests_require=[], entry_points=\ diff --git a/xypath/__init__.py b/xypath/__init__.py index a5b930b..0b1a2c3 100644 --- a/xypath/__init__.py +++ b/xypath/__init__.py @@ -1,2 +1,3 @@ -from xypath import * -import xyzzy +from __future__ import absolute_import +from .xypath import * +from . import xyzzy diff --git a/xypath/contrib/excel.py b/xypath/contrib/excel.py index 64399ce..622a989 100644 --- a/xypath/contrib/excel.py +++ b/xypath/contrib/excel.py @@ -1,8 +1,12 @@ +from __future__ import absolute_import +from __future__ import print_function import sys from itertools import product -from ..extern.tabulate import tabulate +from xypath.extern.tabulate import tabulate import xypath import re +from six.moves import range +from six.moves import zip class InvalidExcelReference(Exception): pass @@ -96,7 +100,7 @@ def filter_one(self, filter_by): elif filter_length > 1: foundmsg = "{}: {}".format( filter_length, - filtered.excel_locations(filtered) + filtered.excel_locations() ) return filtered.assert_one( @@ -126,9 +130,9 @@ def as_list(self, collapse_empty=False, excel_labels=False): width, height = xmax-xmin+1, ymax-ymin+1 - result = [[None]*width for i in xrange(height)] + result = [[None]*width for i in range(height)] - for x, y in product(xrange(xmin, xmax+1), xrange(ymin, ymax+1)): + for x, y in product(range(xmin, xmax+1), range(ymin, ymax+1)): cell = self.table.get_at(x, y) result[y-ymin][x-xmin] = cell.value if cell in self else None @@ -186,6 +190,6 @@ def pprint(self, collapse_empty=False, row[i] = cell if excel_labels: - print >>stream, tabulate(result[1:], headers=result[0]) + print(tabulate(result[1:], headers=result[0]), file=stream) else: - print >>stream, tabulate(result) + print(tabulate(result), file=stream) diff --git a/xypath/extern/tabulate.py b/xypath/extern/tabulate.py index 6735275..e4cadff 100644 --- a/xypath/extern/tabulate.py +++ b/xypath/extern/tabulate.py @@ -31,9 +31,14 @@ from __future__ import print_function from __future__ import unicode_literals +from __future__ import absolute_import from collections import namedtuple from platform import python_version_tuple import re +from six.moves import map +import six +from six.moves import range +from six.moves import zip if python_version_tuple()[0] < "3": @@ -41,7 +46,7 @@ if python_version_tuple()[0] < "3": _none_type = type(None) _int_type = int _float_type = float - _text_type = unicode + _text_type = six.text_type _binary_type = str else: from itertools import zip_longest as izip_longest @@ -345,7 +350,7 @@ def _align_column(strings, alignment, minwidth=0, has_invisible=True): else: width_fn = len - maxwidth = max(max(map(width_fn, strings)), minwidth) + maxwidth = max(max(list(map(width_fn, strings))), minwidth) padded_strings = [padfn(maxwidth, s, has_invisible) for s in strings] return padded_strings @@ -432,11 +437,11 @@ def _normalize_tabular_data(tabular_data, headers): # dict-like and pandas.DataFrame? if hasattr(tabular_data.values, "__call__"): # likely a conventional dict - keys = tabular_data.keys() - rows = list(izip_longest(*tabular_data.values())) # columns have to be transposed + keys = list(tabular_data.keys()) + rows = list(izip_longest(*list(tabular_data.values()))) # columns have to be transposed elif hasattr(tabular_data, "index"): # values is a property, has .index => it's likely a pandas.DataFrame (pandas 0.11.0) - keys = tabular_data.keys() + keys = list(tabular_data.keys()) vals = tabular_data.values # values matrix doesn't need to be transposed names = tabular_data.index rows = [[v]+list(row) for v,row in zip(names, vals)] @@ -450,7 +455,7 @@ def _normalize_tabular_data(tabular_data, headers): rows = list(tabular_data) if headers == "keys" and len(rows) > 0: # keys are column indices - headers = list(map(_text_type, range(len(rows[0])))) + headers = list(map(_text_type, list(range(len(rows[0]))))) # take headers from the first row if necessary if headers == "firstrow" and len(rows) > 0: diff --git a/xypath/loader.py b/xypath/loader.py index 6cbc179..ac8a4e2 100644 --- a/xypath/loader.py +++ b/xypath/loader.py @@ -1,5 +1,7 @@ +from __future__ import absolute_import import messytables -import xypath +from . import xypath +import six def table_set(filename, *args, **kwargs): """get all the tables for a single spreadsheet""" @@ -27,7 +29,7 @@ def get_sheets(mt_tableset, ids): xy_table.index = table_index return xy_table - if isinstance(ids, (int, basestring)) or callable(ids): + if isinstance(ids, (int, six.string_types)) or callable(ids): # it's a single thing, listify it ids = (ids, ) @@ -38,7 +40,7 @@ def get_sheets(mt_tableset, ids): elif isinstance(identifier, int): if identifier == table_index: yield xy() - elif isinstance(identifier, basestring): + elif isinstance(identifier, six.string_types): if identifier.strip() == mt_table.name.strip(): yield xy() elif callable(identifier): diff --git a/xypath/xypath.py b/xypath/xypath.py index eb7ffdb..e5ebd76 100755 --- a/xypath/xypath.py +++ b/xypath/xypath.py @@ -5,10 +5,14 @@ Everyone agrees that col 2, row 1 is (2,1) which is xy ordered. This works well with the name. Remember that the usual iterators (over a list-of-lists) is outer loop y first.""" +from __future__ import absolute_import import re import messytables import os +import six +from six.moves import range +from six.moves import zip try: import hamcrest have_ham = True @@ -19,7 +23,7 @@ from collections import defaultdict from copy import copy from itertools import product, takewhile -import contrib.excel +from xypath.contrib import excel as contrib_excel UP = (0, -1) RIGHT = (1, 0) @@ -30,6 +34,12 @@ DOWN_RIGHT = (1, 1) UP_LEFT = (-1, -1) DOWN_LEFT = (-1, 1) +def cmp(x, y): + if x<y: + return -1 + if x>y: + return 1 + return 0 class XYPathError(Exception): """Problems with spreadsheet layouts should raise this or a descendant.""" @@ -62,7 +72,7 @@ class NoLookupError(AssertionError, XYPathError): def describe_filter_method(filter_by): if callable(filter_by): return "matching a function called {}".format(filter_by.__name__) - if isinstance(filter_by, basestring): + if isinstance(filter_by, six.string_types): return "containing the string {!r}".format(filter_by) if have_ham and isinstance(filter_by, hamcrest.matcher.Matcher): return "containing "+str(filter_by) @@ -113,7 +123,7 @@ class _XYCell(object): (self.value, self.x, self.y) def __unicode__(self): - return unicode(self.value) + return six.text_type(self.value) def lookup(self, header_bag, direction, strict=False): """ @@ -242,16 +252,16 @@ class _XYCell(object): class CoreBag(object): """Has a collection of _XYCells""" def pprint(self, *args, **kwargs): - return contrib.excel.pprint(self, *args, **kwargs) + return contrib_excel.pprint(self, *args, **kwargs) def as_list(self, *args, **kwargs): - return contrib.excel.as_list(self, *args, **kwargs) + return contrib_excel.as_list(self, *args, **kwargs) def filter_one(self, filter_by): - return contrib.excel.filter_one(self, filter_by) + return contrib_excel.filter_one(self, filter_by) def excel_locations(self, *args, **kwargs): - return contrib.excel.excel_locations(self, *args, **kwargs) + return contrib_excel.excel_locations(self, *args, **kwargs) def __init__(self, table): self.__store = set() @@ -389,13 +399,13 @@ class CoreBag(object): """ if callable(filter_by): return self._filter_internal(filter_by) - elif isinstance(filter_by, basestring): - return self._filter_internal(lambda cell: unicode(cell.value).strip() == filter_by) + elif isinstance(filter_by, six.string_types): + return self._filter_internal(lambda cell: six.text_type(cell.value).strip() == filter_by) elif have_ham and isinstance(filter_by, hamcrest.matcher.Matcher): return self._filter_internal(lambda cell: filter_by.matches(cell.value)) elif isinstance(filter_by, re._pattern_type): return self._filter_internal( - lambda cell: re.match(filter_by, unicode(cell.value))) + lambda cell: re.match(filter_by, six.text_type(cell.value))) else: raise ValueError("filter_by must be function, hamcrest filter, compiled regex or string.") @@ -646,14 +656,14 @@ class Bag(CoreBag): """ if dx < 0: - dxs = range(0, dx - 1, -1) + dxs = list(range(0, dx - 1, -1)) else: - dxs = range(0, dx + 1, +1) + dxs = list(range(0, dx + 1, +1)) if dy < 0: - dys = range(0, dy - 1, -1) + dys = list(range(0, dy - 1, -1)) else: - dys = range(0, dy + 1, +1) + dys = list(range(0, dy + 1, +1)) bag = Bag(table=self.table) for cell in self.unordered_cells: @@ -693,7 +703,7 @@ class Bag(CoreBag): return lambda value: self.filter(lambda cell: not cell.properties[name[:-7]] == value) if name.endswith("_is"): return lambda value: self.filter(lambda cell: cell.properties[name[:-3]] == value) - raise AttributeError, "Bag has no attribute {!r}".format(name) + raise AttributeError("Bag has no attribute {!r}".format(name)) class Table(Bag): @@ -709,6 +719,9 @@ class Table(Bag): self.sheet = None self.name = name + def __hash__(self): + return id(self) + def rows(self): """Get bags containing each row's cells, in order""" for row_num in range(0, self._max_y + 1): # inclusive @@ -720,8 +733,8 @@ class Table(Bag): yield self._x_index[col_num] def col(self, column): - if isinstance(column, basestring): - c_num = contrib.excel.excel_column_number(column, index=0) + if isinstance(column, six.string_types): + c_num = contrib_excel.excel_column_number(column, index=0) return self.col(c_num) else: assert isinstance(column, int) diff --git a/xypath/xyzzy.py b/xypath/xyzzy.py index 7cbb9d8..4e2b9c6 100755 --- a/xypath/xyzzy.py +++ b/xypath/xyzzy.py @@ -1,8 +1,9 @@ +from __future__ import absolute_import #!/usr/bin/env python from collections import OrderedDict from itertools import groupby -from xypath import Bag +from .xypath import Bag class LookupFailureError(Exception): @@ -36,15 +37,16 @@ def are_distinct(fields): allbags = set() bagcount = 0 for field in fields: - for bag in field.values(): - allbags = allbags.union(bag) + for bag in list(field.values()): + allbags = allbags.union([cell._cell for cell in bag]) bagcount = bagcount + len(bag) return len(allbags) == bagcount def xyzzy(self, fields, valuename='_value'): # XYZZY - assert are_distinct(fields.values()) - fieldkeys = fields.keys() + # assert are_distinct(list(fields.values())) + # function fixed: wasn't distinct in first place + fieldkeys = list(fields.keys()) assert valuename not in fieldkeys def fieldlookup(cell):
Python 3 support I get this error installing with pip3: ``` Running setup.py install for xypath File "/usr/local/lib/python3.5/dist-packages/xypath/xypath.py", line 696 raise AttributeError, "Bag has no attribute {!r}".format(name) ^ SyntaxError: invalid syntax ```
sensiblecodeio/xypath
diff --git a/test/tcore.py b/test/tcore.py index 7c3b5da..fed0cab 100755 --- a/test/tcore.py +++ b/test/tcore.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import #!/usr/bin/env python import sys import unittest @@ -50,7 +51,7 @@ class TCore(unittest.TestCase): self.fail('No exception was raised') except Exception as inst: self.assertIsInstance(inst, exception_type) - self.assertEqual(inst.message, msg) + self.assertEqual(str(inst), msg) class TMissing(unittest.TestCase): @classmethod diff --git a/test/test_bag.py b/test/test_bag.py index 8b3c24c..3248ac6 100644 --- a/test/test_bag.py +++ b/test/test_bag.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import #!/usr/bin/env python import sys sys.path.append('xypath') @@ -8,7 +9,7 @@ import unittest class Test_Bag(tcore.TCore): def test_bag_from_list(self): "That Bag.from_list works and table is preserved" - true_bag = self.table.filter(lambda b: b.value > "F") + true_bag = self.table.filter(lambda b: b.x % 2 and b.y % 2) fake_bag = list(true_bag.table) self.assertEqual(type(fake_bag), list) remade_bag = xypath.Bag.from_list(fake_bag) diff --git a/test/test_contrib.py b/test/test_contrib.py index aebe68c..5f042ae 100644 --- a/test/test_contrib.py +++ b/test/test_contrib.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import #!/usr/bin/env python import unittest import xypath.contrib.excel diff --git a/test/test_excel.py b/test/test_excel.py index 5fdbc7d..cbb8870 100644 --- a/test/test_excel.py +++ b/test/test_excel.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import import unittest from nose.tools import assert_raises, assert_equal import xypath.contrib.excel as exceltool diff --git a/test/test_fill.py b/test/test_fill.py index 0f15fa6..0ef4f20 100644 --- a/test/test_fill.py +++ b/test/test_fill.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import #!/usr/bin/env python import sys sys.path.append('xypath') diff --git a/test/test_filter.py b/test/test_filter.py index af90609..8b846ed 100644 --- a/test/test_filter.py +++ b/test/test_filter.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import #!/usr/bin/env python import sys diff --git a/test/test_filter_one.py b/test/test_filter_one.py index f3b4445..0d26af1 100644 --- a/test/test_filter_one.py +++ b/test/test_filter_one.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import +from __future__ import print_function #!/usr/bin/env python import sys @@ -26,11 +28,10 @@ class TestFilterOne(tcore.TCore): try: self.table.filter_one(re.compile(r'.*Europe.*')) except xypath.MultipleCellsAssertionError as e: - pass + assert "We expected to find one cell matching the regex '.*Europe.*', but we found 4: " in str(e) + + cells = "C158, C147, C172, C189".split(', ') + assert len([cell for cell in cells if cell in str(e)]) >= 3 else: assert False, "Didn't get a MultipleCellsAssertionError" - assert "We expected to find one cell matching the regex '.*Europe.*', but we found 4: " in str(e) - print e - for cell in "C158, C147, C172, C189".split(', '): - assert cell in str(e) diff --git a/test/test_import.py b/test/test_import.py index 124ffdd..c24208a 100644 --- a/test/test_import.py +++ b/test/test_import.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import #!/usr/bin/env python import sys import unittest diff --git a/test/test_junction.py b/test/test_junction.py index 6f97ebc..1c5d1f6 100644 --- a/test/test_junction.py +++ b/test/test_junction.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import #!/usr/bin/env python import sys sys.path.append('xypath') diff --git a/test/test_loader.py b/test/test_loader.py index 0649356..29a8263 100644 --- a/test/test_loader.py +++ b/test/test_loader.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import import unittest import xypath.loader from nose.tools import assert_equal diff --git a/test/test_pprint.py b/test/test_pprint.py index 8f8190e..22980b8 100644 --- a/test/test_pprint.py +++ b/test/test_pprint.py @@ -1,7 +1,8 @@ +from __future__ import absolute_import import tcore import xypath from textwrap import dedent -from cStringIO import StringIO +from io import StringIO class TestPPrint(tcore.TCore): diff --git a/test/test_table.py b/test/test_table.py index ec21e5d..82d2549 100644 --- a/test/test_table.py +++ b/test/test_table.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import #!/usr/bin/env python import sys sys.path.append('xypath') diff --git a/test/test_xycell.py b/test/test_xycell.py index 31386b0..923806e 100644 --- a/test/test_xycell.py +++ b/test/test_xycell.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import +from __future__ import print_function import tcore import xypath.xypath as xypath # no privacy @@ -12,7 +14,7 @@ class Test_Lookup(unittest.TestCase): cls.messy, cls.table = tcore.get_messytables_fixture(cls.wpp_filename) def test_cell_lookup(self): - print self.table + print(self.table) v = self.table.filter("V")._cell a = self.table.filter("A") b = self.table.filter("B") diff --git a/test/test_xyzzy.py b/test/test_xyzzy.py index f7f3bbb..9909bf5 100644 --- a/test/test_xyzzy.py +++ b/test/test_xyzzy.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import import xypath import xypath.xyzzy from collections import OrderedDict @@ -46,5 +47,7 @@ def xtract_by_numbers(table, rows, columns): def test_xyzzy_kinda_works(): things = xtract_by_numbers(xy, dimensions_horizontal, dimensions_vertical) - sorted_things = [thing.values() for thing in sorted(things)] - assert sorted_things == output + + unsorted_things = [list(thing.values()) for thing in things] + sorted_things = sorted(unsorted_things) + assert sorted_things == output, sorted_things
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 3, "issue_text_score": 2, "test_score": 0 }, "num_modified_files": 9 }
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" ], "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" }
certifi==2025.1.31 chardet==5.2.0 charset-normalizer==3.4.1 coverage==7.8.0 exceptiongroup==1.2.2 html5lib==1.1 idna==3.10 iniconfig==2.1.0 json-table-schema==0.2.1 lxml==5.3.1 messytables==0.15.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 python-dateutil==2.9.0.post0 python-magic==0.4.27 requests==2.32.3 six==1.17.0 tomli==2.2.1 urllib3==2.3.0 webencodings==0.5.1 xlrd==2.0.1 -e git+https://github.com/sensiblecodeio/xypath.git@2de90e58b881b271a743ae5c60c5e03904d2ef7f#egg=xypath
name: xypath 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 - chardet==5.2.0 - charset-normalizer==3.4.1 - coverage==7.8.0 - exceptiongroup==1.2.2 - html5lib==1.1 - idna==3.10 - iniconfig==2.1.0 - json-table-schema==0.2.1 - lxml==5.3.1 - messytables==0.15.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pytest==8.3.5 - python-dateutil==2.9.0.post0 - python-magic==0.4.27 - requests==2.32.3 - six==1.17.0 - tomli==2.2.1 - urllib3==2.3.0 - webencodings==0.5.1 - xlrd==2.0.1 prefix: /opt/conda/envs/xypath
[ "test/test_contrib.py::Test_Contrib::test_excel_address_coordinate", "test/test_contrib.py::Test_Contrib::test_excel_nums", "test/test_excel.py::Test_Loader::test_col_label", "test/test_excel.py::Test_Loader::test_excel_address", "test/test_excel.py::Test_Loader::test_excel_col", "test/test_excel.py::Test_Loader::test_invalid_excel_address", "test/test_xycell.py::XYCellTests::test_cell_copy", "test/test_xycell.py::XYCellTests::test_cell_equality", "test/test_xycell.py::XYCellTests::test_cell_identity", "test/test_xycell.py::XYCellTests::test_cell_identity_not_equal_different_tables", "test/test_xycell.py::XYCellTests::test_cell_identity_not_equal_different_x", "test/test_xycell.py::XYCellTests::test_cell_identity_not_equal_different_y", "test/test_xycell.py::XYCellTests::test_cell_shift_takes_tuples", "test/test_xyzzy.py::test_xyzzy_kinda_works" ]
[ "test/test_loader.py::Test_Loader::test_foo" ]
[]
[]
BSD 2-Clause "Simplified" License
125
[ "Makefile", "xypath/extern/tabulate.py", "setup.py", "xypath/xyzzy.py", "xypath/__init__.py", "requirements.txt", ".travis.yml", "xypath/contrib/excel.py", "xypath/loader.py", "Dockerfile", "xypath/xypath.py" ]
[ "Makefile", "xypath/extern/tabulate.py", "setup.py", "xypath/xyzzy.py", "xypath/__init__.py", "requirements.txt", ".travis.yml", "xypath/contrib/excel.py", "xypath/loader.py", "Dockerfile", "xypath/xypath.py" ]
box__box-python-sdk-46
221ef994e215b78b4049847db9656fcc83d10d79
2015-05-05 20:17:27
221ef994e215b78b4049847db9656fcc83d10d79
diff --git a/HISTORY.rst b/HISTORY.rst index b38b2b1..c2dfaf0 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -3,6 +3,13 @@ Release History --------------- +Upcoming +++++++++ + +- Added support for setting shared link expiration dates. +- Added support for setting shared link permissions. + + 1.1.6 (2015-04-17) ++++++++++++++++++ @@ -19,13 +26,6 @@ Release History - Added support to the search endpoint for metadata filters. - Added support to the search endpoint for filtering based on result type and content types. -1.1.3 (2015-03-26) -++++++++++++++++++ - -- Added support for the /shared_items endpoint. `client.get_shared_item` can be used to get information about - a shared link. See https://developers.box.com/docs/#shared-items - - 1.1.3 (2015-03-26) ++++++++++++++++++ diff --git a/boxsdk/object/item.py b/boxsdk/object/item.py index e507e86..26fb391 100644 --- a/boxsdk/object/item.py +++ b/boxsdk/object/item.py @@ -159,7 +159,7 @@ def move(self, parent_folder): } return self.update_info(data) - def get_shared_link(self, access=None, etag=None): + def get_shared_link(self, access=None, etag=None, unshared_at=None, allow_download=None, allow_preview=None): """Get a shared link for the item with the given access permissions. :param access: @@ -171,6 +171,21 @@ def get_shared_link(self, access=None, etag=None): If specified, instruct the Box API to create the link only if the current version's etag matches. :type etag: `unicode` or None + :param unshared_at: + The date on which this link should be disabled. May only be set if the current user is not a free user + and has permission to set expiration dates. + :type unshared_at: + :class:`datetime.date` or None + :param allow_download: + Whether or not the item being shared can be downloaded when accessed via the shared link. + If this parameter is None, the default setting will be used. + :type allow_download: + `bool` or None + :param allow_preview: + Whether or not the item being shared can be previewed when accessed via the shared link. + If this parameter is None, the default setting will be used. + :type allow_preview: + `bool` or None :returns: The URL of the shared link. :rtype: @@ -182,6 +197,17 @@ def get_shared_link(self, access=None, etag=None): 'access': access } } + + if unshared_at is not None: + data['shared_link']['unshared_at'] = unshared_at.isoformat() + + if allow_download is not None or allow_preview is not None: + data['shared_link']['permissions'] = permissions = {} + if allow_download is not None: + permissions['can_download'] = allow_download + if allow_preview is not None: + permissions['can_preview'] = allow_preview + item = self.update_info(data, etag=etag) return item.shared_link['url'] diff --git a/tox.ini b/tox.ini index 211ff3d..8eb5920 100644 --- a/tox.ini +++ b/tox.ini @@ -28,6 +28,7 @@ deps = commands = rst2html.py --strict README.rst rst2html.py --strict HISTORY.rst + rst2html.py --strict CONTRIBUTING.rst [testenv:pep8] commands =
Add ability to set expiration date on shared links `get_shared_link()` only takes access and etag as parameters. The create shared link API supports many other parameters, including unshared_at, permissions, can_download, can_preview. https://box-content.readme.io/#page-create-a-shared-link-for-a-file
box/box-python-sdk
diff --git a/test/unit/object/test_item.py b/test/unit/object/test_item.py index 1bfa2f1..32721fc 100644 --- a/test/unit/object/test_item.py +++ b/test/unit/object/test_item.py @@ -1,6 +1,7 @@ # coding: utf-8 from __future__ import unicode_literals +from datetime import date import json import pytest @@ -55,12 +56,33 @@ def test_move_item(test_item_and_response, mock_box_session, test_folder, mock_o assert isinstance(move_response, test_item.__class__) [email protected]('access,expected_access_data', [(None, {}), ('open', {'access': 'open'})]) [email protected](params=(True, False, None)) +def shared_link_can_download(request): + return request.param + + [email protected](params=(True, False, None)) +def shared_link_can_preview(request): + return request.param + + [email protected](params=('open', None)) +def shared_link_access(request): + return request.param + + [email protected](params=(date(2015, 5, 5), None)) +def shared_link_unshared_at(request): + return request.param + + def test_get_shared_link( test_item_and_response, mock_box_session, - access, - expected_access_data, + shared_link_access, + shared_link_unshared_at, + shared_link_can_download, + shared_link_can_preview, test_url, etag, if_match_header, @@ -69,10 +91,27 @@ def test_get_shared_link( test_item, _ = test_item_and_response expected_url = test_item.get_url() mock_box_session.put.return_value.json.return_value = {'shared_link': {'url': test_url}} - url = test_item.get_shared_link(access, etag=etag) + expected_data = {'shared_link': {}} + if shared_link_access is not None: + expected_data['shared_link']['access'] = shared_link_access + if shared_link_unshared_at is not None: + expected_data['shared_link']['unshared_at'] = shared_link_unshared_at.isoformat() + if shared_link_can_download is not None or shared_link_can_preview is not None: + expected_data['shared_link']['permissions'] = permissions = {} + if shared_link_can_download is not None: + permissions['can_download'] = shared_link_can_download + if shared_link_can_preview is not None: + permissions['can_preview'] = shared_link_can_preview + url = test_item.get_shared_link( + etag=etag, + access=shared_link_access, + unshared_at=shared_link_unshared_at, + allow_download=shared_link_can_download, + allow_preview=shared_link_can_preview, + ) mock_box_session.put.assert_called_once_with( expected_url, - data=json.dumps({'shared_link': expected_access_data}), + data=json.dumps(expected_data), headers=if_match_header, params=None, )
{ "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": 1, "test_score": 2 }, "num_modified_files": 3 }
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-xdist", "mock", "sqlalchemy", "bottle" ], "pre_install": [ "apt-get update", "apt-get install -y gcc" ], "python": "3.9", "reqs_path": [ "requirements.txt", "requirements-dev.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
alabaster==0.7.16 astroid==3.3.9 babel==2.17.0 bottle==0.13.2 -e git+https://github.com/box/box-python-sdk.git@221ef994e215b78b4049847db9656fcc83d10d79#egg=boxsdk 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 dill==0.3.9 distlib==0.3.9 docutils==0.21.2 enum34==1.1.10 exceptiongroup==1.2.2 execnet==2.1.1 filelock==3.18.0 greenlet==3.1.1 idna==3.10 imagesize==1.4.1 importlib_metadata==8.6.1 iniconfig==2.1.0 isort==6.0.1 Jinja2==3.1.6 jsonpatch==1.33 jsonpointer==3.0.0 MarkupSafe==3.0.2 mccabe==0.7.0 mock==5.2.0 ordereddict==1.1 packaging==24.2 pep8==1.7.1 platformdirs==4.3.7 pluggy==1.5.0 Pygments==2.19.1 pylint==3.3.6 pyproject-api==1.9.0 pytest==8.3.5 pytest-cov==6.0.0 pytest-xdist==3.6.1 requests==2.32.3 six==1.17.0 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 SQLAlchemy==2.0.40 tomli==2.2.1 tomlkit==0.13.2 tox==4.25.0 typing_extensions==4.13.0 urllib3==2.3.0 virtualenv==20.29.3 zipp==3.21.0
name: box-python-sdk 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 - astroid==3.3.9 - babel==2.17.0 - bottle==0.13.2 - 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 - dill==0.3.9 - distlib==0.3.9 - docutils==0.21.2 - enum34==1.1.10 - exceptiongroup==1.2.2 - execnet==2.1.1 - filelock==3.18.0 - greenlet==3.1.1 - idna==3.10 - imagesize==1.4.1 - importlib-metadata==8.6.1 - iniconfig==2.1.0 - isort==6.0.1 - jinja2==3.1.6 - jsonpatch==1.33 - jsonpointer==3.0.0 - markupsafe==3.0.2 - mccabe==0.7.0 - mock==5.2.0 - ordereddict==1.1 - packaging==24.2 - pep8==1.7.1 - platformdirs==4.3.7 - pluggy==1.5.0 - pygments==2.19.1 - pylint==3.3.6 - pyproject-api==1.9.0 - pytest==8.3.5 - pytest-cov==6.0.0 - pytest-xdist==3.6.1 - requests==2.32.3 - six==1.17.0 - 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 - sqlalchemy==2.0.40 - tomli==2.2.1 - tomlkit==0.13.2 - 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/box-python-sdk
[ "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-True-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-False-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-shared_link_unshared_at0-None-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-True-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-False-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-open-None-None-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-True-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-False-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-shared_link_unshared_at0-None-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-True-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-False-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-True-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-False-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-None-None]", "test/unit/object/test_item.py::test_get_shared_link[file-None-None-None-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-True-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-False-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-shared_link_unshared_at0-None-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-True-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-False-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-open-None-None-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-True-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-False-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-shared_link_unshared_at0-None-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-True-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-False-None-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-True-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-True-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-False-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-False-etag]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-None-None]", "test/unit/object/test_item.py::test_get_shared_link[folder-None-None-None-None-etag]" ]
[]
[ "test/unit/object/test_item.py::test_update_info[file-None]", "test/unit/object/test_item.py::test_update_info[file-etag]", "test/unit/object/test_item.py::test_update_info[folder-None]", "test/unit/object/test_item.py::test_update_info[folder-etag]", "test/unit/object/test_item.py::test_rename_item[file]", "test/unit/object/test_item.py::test_rename_item[folder]", "test/unit/object/test_item.py::test_copy_item[file]", "test/unit/object/test_item.py::test_copy_item[folder]", "test/unit/object/test_item.py::test_move_item[file]", "test/unit/object/test_item.py::test_move_item[folder]", "test/unit/object/test_item.py::test_remove_shared_link[file-None]", "test/unit/object/test_item.py::test_remove_shared_link[file-etag]", "test/unit/object/test_item.py::test_remove_shared_link[folder-None]", "test/unit/object/test_item.py::test_remove_shared_link[folder-etag]", "test/unit/object/test_item.py::test_get[file-None-None]", "test/unit/object/test_item.py::test_get[file-None-fields1]", "test/unit/object/test_item.py::test_get[file-etag-None]", "test/unit/object/test_item.py::test_get[file-etag-fields1]", "test/unit/object/test_item.py::test_get[folder-None-None]", "test/unit/object/test_item.py::test_get[folder-None-fields1]", "test/unit/object/test_item.py::test_get[folder-etag-None]", "test/unit/object/test_item.py::test_get[folder-etag-fields1]" ]
[]
Apache License 2.0
126
[ "HISTORY.rst", "boxsdk/object/item.py", "tox.ini" ]
[ "HISTORY.rst", "boxsdk/object/item.py", "tox.ini" ]
mkdocs__mkdocs-501
7cc47645d357fa96bf7197e30b519f331e77a3d5
2015-05-06 12:18:45
463c5b647e9ce5992b519708a0b9c4cba891d65c
landscape-bot: [![Code Health](https://landscape.io/badge/159489/landscape.svg?style=flat)](https://landscape.io/diff/146595) Repository health decreased by 0.24% when pulling **[f42c054](https://github.com/d0ugal/mkdocs/commit/f42c054a9b0fc86f7ed40de43fec8ebb53ab4191) on d0ugal:auto-pages** into **[7cc4764](https://github.com/mkdocs/mkdocs/commit/7cc47645d357fa96bf7197e30b519f331e77a3d5) on mkdocs:master**. * [1 new problem was found](https://landscape.io/diff/146595) (including 0 errors and 1 code smell). * No problems were fixed. landscape-bot: [![Code Health](https://landscape.io/badge/159492/landscape.svg?style=flat)](https://landscape.io/diff/146599) Code quality remained the same when pulling **[7fc3de2](https://github.com/d0ugal/mkdocs/commit/7fc3de2959a6c94556be4f0e9c5a0cf27d451318) on d0ugal:auto-pages** into **[7cc4764](https://github.com/mkdocs/mkdocs/commit/7cc47645d357fa96bf7197e30b519f331e77a3d5) on mkdocs:master**. landscape-bot: [![Code Health](https://landscape.io/badge/159492/landscape.svg?style=flat)](https://landscape.io/diff/146599) Code quality remained the same when pulling **[7fc3de2](https://github.com/d0ugal/mkdocs/commit/7fc3de2959a6c94556be4f0e9c5a0cf27d451318) on d0ugal:auto-pages** into **[7cc4764](https://github.com/mkdocs/mkdocs/commit/7cc47645d357fa96bf7197e30b519f331e77a3d5) on mkdocs:master**. landscape-bot: [![Code Health](https://landscape.io/badge/159508/landscape.svg?style=flat)](https://landscape.io/diff/146619) Code quality remained the same when pulling **[d49f3a0](https://github.com/d0ugal/mkdocs/commit/d49f3a09fb5431351d5bd975e71f40a3cd69cdd4) on d0ugal:auto-pages** into **[7cc4764](https://github.com/mkdocs/mkdocs/commit/7cc47645d357fa96bf7197e30b519f331e77a3d5) on mkdocs:master**.
diff --git a/mkdocs.yml b/mkdocs.yml index ad7ce968..930ccd95 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -4,19 +4,6 @@ site_description: Project documentation with Markdown. repo_url: https://github.com/mkdocs/mkdocs/ -pages: -- Home: index.md -- User Guide: - - Writing Your Docs: user-guide/writing-your-docs.md - - Styling Your Docs: user-guide/styling-your-docs.md - - Configuration: user-guide/configuration.md -- About: - - License: about/license.md - - Release Notes: about/release-notes.md - - Contributing: about/contributing.md - -use_new_pages_structure: true - markdown_extensions: toc: permalink: "" diff --git a/mkdocs/config.py b/mkdocs/config.py index 408e3393..71451244 100644 --- a/mkdocs/config.py +++ b/mkdocs/config.py @@ -145,6 +145,8 @@ def validate_config(user_config): elif utils.is_template_file(filename): extra_templates.append(filename) + pages = utils.nest_paths(pages) + if config['pages'] is None: config['pages'] = pages else: diff --git a/mkdocs/nav.py b/mkdocs/nav.py index 58b5bc14..d70628d3 100644 --- a/mkdocs/nav.py +++ b/mkdocs/nav.py @@ -22,13 +22,7 @@ def filename_to_title(filename): if utils.is_homepage(filename): return 'Home' - title = os.path.splitext(filename)[0] - title = title.replace('-', ' ').replace('_', ' ') - # Capitalize if the filename was all lowercase, otherwise leave it as-is. - if title.lower() == title: - title = title.capitalize() - - return title + return utils.filename_to_title(filename) class SiteNavigation(object): diff --git a/mkdocs/utils.py b/mkdocs/utils.py index 971ce480..685e90aa 100644 --- a/mkdocs/utils.py +++ b/mkdocs/utils.py @@ -307,3 +307,60 @@ def get_theme_names(): """Return a list containing all the names of all the builtin themes.""" return os.listdir(os.path.join(os.path.dirname(__file__), 'themes')) + + +def filename_to_title(filename): + + title = os.path.splitext(filename)[0] + title = title.replace('-', ' ').replace('_', ' ') + # Capitalize if the filename was all lowercase, otherwise leave it as-is. + if title.lower() == title: + title = title.capitalize() + + return title + + +def find_or_create_node(branch, key): + """ + Given a list, look for dictionary with a key matching key and return it's + value. If it doesn't exist, create it with the value of an empty list and + return that. + """ + + for node in branch: + if not isinstance(node, dict): + continue + + if key in node: + return node[key] + + new_branch = [] + node = {key: new_branch} + branch.append(node) + return new_branch + + +def nest_paths(paths): + """ + Given a list of paths, convert them into a nested structure that will match + the pages config. + """ + nested = [] + + for path in paths: + + if os.path.sep not in path: + nested.append(path) + continue + + directory, _ = os.path.split(path) + parts = directory.split(os.path.sep) + + branch = nested + for part in parts: + part = filename_to_title(part) + branch = find_or_create_node(branch, part) + + branch.append(path) + + return nested
Regression with automatic pages config Caused by: 7849e71b8401608f86e81b48e7b29d18e8408663
mkdocs/mkdocs
diff --git a/mkdocs/tests/utils_tests.py b/mkdocs/tests/utils_tests.py index e2854187..41d066e6 100644 --- a/mkdocs/tests/utils_tests.py +++ b/mkdocs/tests/utils_tests.py @@ -1,6 +1,7 @@ #!/usr/bin/env python # coding: utf-8 +import os import unittest from mkdocs import nav, utils @@ -108,3 +109,32 @@ class UtilsTests(unittest.TestCase): sorted(['flatly', 'cerulean', 'slate', 'bootstrap', 'yeti', 'spacelab', 'united', 'readable', 'simplex', 'mkdocs', 'cosmo', 'journal', 'cyborg', 'readthedocs', 'amelia'])) + + def test_nest_paths(self): + + j = os.path.join + + result = utils.nest_paths([ + 'index.md', + j('user-guide', 'configuration.md'), + j('user-guide', 'styling-your-docs.md'), + j('user-guide', 'writing-your-docs.md'), + j('about', 'contributing.md'), + j('about', 'license.md'), + j('about', 'release-notes.md'), + ]) + + self.assertEqual( + result, + [ + 'index.md', + {'User guide': [ + j('user-guide', 'configuration.md'), + j('user-guide', 'styling-your-docs.md'), + j('user-guide', 'writing-your-docs.md')]}, + {'About': [ + j('about', 'contributing.md'), + j('about', 'license.md'), + j('about', 'release-notes.md')]} + ] + )
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_git_commit_hash", "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": 4 }
0.12
{ "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.7", "reqs_path": [ "requirements/project.txt" ], "test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning" }
certifi @ file:///croot/certifi_1671487769961/work/certifi click==8.1.8 exceptiongroup==1.2.2 ghp-import==2.1.0 importlib-metadata==6.7.0 iniconfig==2.0.0 Jinja2==3.1.6 livereload==2.7.1 Markdown==3.4.4 MarkupSafe==2.1.5 -e git+https://github.com/mkdocs/mkdocs.git@7cc47645d357fa96bf7197e30b519f331e77a3d5#egg=mkdocs packaging==24.0 pluggy==1.2.0 pytest==7.4.4 python-dateutil==2.9.0.post0 PyYAML==6.0.1 six==1.17.0 tomli==2.0.1 tornado==6.2 typing_extensions==4.7.1 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: - click==8.1.8 - exceptiongroup==1.2.2 - ghp-import==2.1.0 - importlib-metadata==6.7.0 - iniconfig==2.0.0 - jinja2==3.1.6 - livereload==2.7.1 - markdown==3.4.4 - markupsafe==2.1.5 - packaging==24.0 - pluggy==1.2.0 - pytest==7.4.4 - python-dateutil==2.9.0.post0 - pyyaml==6.0.1 - six==1.17.0 - tomli==2.0.1 - tornado==6.2 - typing-extensions==4.7.1 - zipp==3.15.0 prefix: /opt/conda/envs/mkdocs
[ "mkdocs/tests/utils_tests.py::UtilsTests::test_nest_paths" ]
[ "mkdocs/tests/utils_tests.py::UtilsTests::test_create_media_urls" ]
[ "mkdocs/tests/utils_tests.py::UtilsTests::test_get_themes", "mkdocs/tests/utils_tests.py::UtilsTests::test_html_path", "mkdocs/tests/utils_tests.py::UtilsTests::test_is_html_file", "mkdocs/tests/utils_tests.py::UtilsTests::test_is_markdown_file", "mkdocs/tests/utils_tests.py::UtilsTests::test_reduce_list", "mkdocs/tests/utils_tests.py::UtilsTests::test_url_path", "mkdocs/tests/utils_tests.py::UtilsTests::test_yaml_load" ]
[]
BSD 2-Clause "Simplified" License
127
[ "mkdocs/config.py", "mkdocs/utils.py", "mkdocs.yml", "mkdocs/nav.py" ]
[ "mkdocs/config.py", "mkdocs/utils.py", "mkdocs.yml", "mkdocs/nav.py" ]
typesafehub__conductr-cli-52
e5561a7e43d92a0c19e7b6e31a36448455a17fba
2015-05-06 15:35:08
e5561a7e43d92a0c19e7b6e31a36448455a17fba
diff --git a/.gitignore b/.gitignore index b8b187e..896a06a 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ deb_dist/* .idea *.iml *.pyc +.tox diff --git a/.travis.yml b/.travis.yml index 4374097..817f35a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,8 @@ language: python -python: -- '3.4' -script: python3 setup.py test +install: + - pip3 install --user virtualenv +script: + - python3 setup.py test deploy: provider: pypi user: typesafehub diff --git a/conductr_cli/conduct_logging.py b/conductr_cli/conduct_logging.py index 159999f..3d9feb8 100644 --- a/conductr_cli/conduct_logging.py +++ b/conductr_cli/conduct_logging.py @@ -26,7 +26,7 @@ def connection_error(err, args): def pretty_json(s): s_json = json.loads(s) - print(json.dumps(s_json, sort_keys=True, indent=2)) + print(json.dumps(s_json, sort_keys=True, indent=2, separators=(',', ': '))) def handle_connection_error(func): diff --git a/conductr_cli/shazar.py b/conductr_cli/shazar.py index 5c97b3d..cac7342 100755 --- a/conductr_cli/shazar.py +++ b/conductr_cli/shazar.py @@ -11,10 +11,10 @@ import tempfile import zipfile -def run(): +def run(argv=None): parser = build_parser() argcomplete.autocomplete(parser) - args = parser.parse_args() + args = parser.parse_args(argv) args.func(args) @@ -45,10 +45,8 @@ def shazar(args): else: zip_file.write(args.source, source_base_name) - dest = shutil.move( - temp_file, - os.path.join(args.output_dir, '{}-{}.zip'.format(source_base_name, create_digest(temp_file))) - ) + dest = os.path.join(args.output_dir, '{}-{}.zip'.format(source_base_name, create_digest(temp_file))) + shutil.move(temp_file, dest) print('Created digested ZIP archive at {}'.format(dest)) diff --git a/setup.py b/setup.py index 535fada..03f23f9 100644 --- a/setup.py +++ b/setup.py @@ -1,10 +1,46 @@ import os +import sys from setuptools import setup, find_packages from conductr_cli import __version__ +from setuptools.command.test import test # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) +install_requires = [ + 'requests>=2.3.0', + 'argcomplete>=0.8.1', + 'pyhocon==0.2.1' +] +if sys.version_info[:2] == (3, 2): + install_requires.extend([ + 'pathlib==1.0.1', + 'mock==1.0.1' + ]) + + +class Tox(test): + user_options = [('tox-args=', 'a', 'Arguments to pass to tox')] + + def initialize_options(self): + test.initialize_options(self) + self.tox_args = None + + def finalize_options(self): + test.finalize_options(self) + self.test_args = [] + self.test_suite = True + + def run_tests(self): + # import here, cause outside the eggs aren't loaded + import tox + import shlex + args = self.tox_args + if args: + args = shlex.split(self.tox_args) + errno = tox.cmdline(args=args) + sys.exit(errno) + setup( name='conductr-cli', version=__version__, @@ -17,13 +53,12 @@ setup( ], }, - install_requires=[ - 'requests>=2.3.0', - 'argcomplete>=0.8.1', - 'pyhocon==0.2.1' - ], + install_requires=install_requires, + tests_require=['tox'], test_suite='conductr_cli.test', + cmdclass={'test': Tox}, + license='Apache 2', description='A CLI client for Typesafe ConductR', url='https://github.com/typesafehub/conductr-cli', diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..5b12aef --- /dev/null +++ b/tox.ini @@ -0,0 +1,6 @@ +[tox] +envlist = py32, py34 + +[testenv] +deps = nose +commands = nosetests
Improve CLI message From @rpokrywka shazar: “Created digested ZIP archive at None” - the message should be giving more information. @rpokrywka Can you provide a reproducible test case?
typesafehub/conductr-cli
diff --git a/conductr_cli/test/cli_test_case.py b/conductr_cli/test/cli_test_case.py index cbad63c..7467a38 100644 --- a/conductr_cli/test/cli_test_case.py +++ b/conductr_cli/test/cli_test_case.py @@ -1,9 +1,13 @@ import os import shutil import tempfile -from unittest.mock import MagicMock from requests.exceptions import ConnectionError, HTTPError +try: + from unittest.mock import MagicMock # 3.3 and beyond +except ImportError: + from mock import MagicMock + class CliTestCase(): """Provides test case common functionality""" diff --git a/conductr_cli/test/test_conduct_info.py b/conductr_cli/test/test_conduct_info.py index 6188067..234f94d 100644 --- a/conductr_cli/test/test_conduct_info.py +++ b/conductr_cli/test/test_conduct_info.py @@ -1,8 +1,12 @@ from unittest import TestCase -from unittest.mock import patch, MagicMock from conductr_cli.test.cli_test_case import CliTestCase, strip_margin from conductr_cli import conduct_info +try: + from unittest.mock import patch, MagicMock # 3.3 and beyond +except ImportError: + from mock import patch, MagicMock + class TestConductInfoCommand(TestCase, CliTestCase): diff --git a/conductr_cli/test/test_conduct_load.py b/conductr_cli/test/test_conduct_load.py index 378215f..eb3b983 100644 --- a/conductr_cli/test/test_conduct_load.py +++ b/conductr_cli/test/test_conduct_load.py @@ -1,10 +1,14 @@ 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 +try: + from unittest.mock import call, patch, MagicMock # 3.3 and beyond +except ImportError: + from mock import call, patch, MagicMock + class TestConductLoadCommand(TestCase, CliTestCase): diff --git a/conductr_cli/test/test_conduct_run.py b/conductr_cli/test/test_conduct_run.py index 9f18628..2bdc26b 100644 --- a/conductr_cli/test/test_conduct_run.py +++ b/conductr_cli/test/test_conduct_run.py @@ -1,8 +1,12 @@ from unittest import TestCase -from unittest.mock import patch, MagicMock from conductr_cli.test.cli_test_case import CliTestCase, strip_margin from conductr_cli import conduct_run +try: + from unittest.mock import patch, MagicMock # 3.3 and beyond +except ImportError: + from mock import patch, MagicMock + class TestConductRunCommand(TestCase, CliTestCase): diff --git a/conductr_cli/test/test_conduct_services.py b/conductr_cli/test/test_conduct_services.py index 590794e..431afef 100644 --- a/conductr_cli/test/test_conduct_services.py +++ b/conductr_cli/test/test_conduct_services.py @@ -1,8 +1,12 @@ from unittest import TestCase -from unittest.mock import patch, MagicMock from conductr_cli.test.cli_test_case import CliTestCase, strip_margin from conductr_cli import conduct_services +try: + from unittest.mock import patch, MagicMock # 3.3 and beyond +except ImportError: + from mock import patch, MagicMock + class TestConductServicesCommand(TestCase, CliTestCase): diff --git a/conductr_cli/test/test_conduct_stop.py b/conductr_cli/test/test_conduct_stop.py index 2c3ab19..39a4e00 100644 --- a/conductr_cli/test/test_conduct_stop.py +++ b/conductr_cli/test/test_conduct_stop.py @@ -1,8 +1,12 @@ from unittest import TestCase -from unittest.mock import patch, MagicMock from conductr_cli.test.cli_test_case import CliTestCase, strip_margin from conductr_cli import conduct_stop +try: + from unittest.mock import patch, MagicMock # 3.3 and beyond +except ImportError: + from mock import patch, MagicMock + class TestConductStopCommand(TestCase, CliTestCase): diff --git a/conductr_cli/test/test_conduct_unload.py b/conductr_cli/test/test_conduct_unload.py index 1cbf7c2..bcff6ac 100644 --- a/conductr_cli/test/test_conduct_unload.py +++ b/conductr_cli/test/test_conduct_unload.py @@ -1,8 +1,12 @@ from unittest import TestCase -from unittest.mock import patch, MagicMock from conductr_cli.test.cli_test_case import CliTestCase, strip_margin from conductr_cli import conduct_unload +try: + from unittest.mock import patch, MagicMock # 3.3 and beyond +except ImportError: + from mock import patch, MagicMock + class TestConductUnloadCommand(TestCase, CliTestCase): diff --git a/conductr_cli/test/test_shazar.py b/conductr_cli/test/test_shazar.py index c8d0407..adfd475 100644 --- a/conductr_cli/test/test_shazar.py +++ b/conductr_cli/test/test_shazar.py @@ -1,7 +1,14 @@ from unittest import TestCase +import shutil import tempfile from os import remove -from conductr_cli.shazar import create_digest, build_parser +from conductr_cli.shazar import create_digest, build_parser, run +from conductr_cli.test.cli_test_case import CliTestCase + +try: + from unittest.mock import patch, MagicMock # 3.3 and beyond +except ImportError: + from mock import patch, MagicMock class TestShazar(TestCase): @@ -23,3 +30,25 @@ class TestShazar(TestCase): self.assertEqual(args.output_dir, 'output-dir') self.assertEqual(args.source, 'source') + + +class TestIntegration(TestCase, CliTestCase): + + def setUp(self): # noqa + self.tmpdir = tempfile.mkdtemp() + self.tmpfile = tempfile.NamedTemporaryFile(mode='w+b', delete=False) + self.tmpfile.write(b'test file data') + + def test(self): + stdout = MagicMock() + with patch('sys.stdout', stdout): + run('--output-dir {} {}'.format(self.tmpdir, self.tmpfile.name).split()) + + self.assertRegex( + self.output(stdout), + 'Created digested ZIP archive at /tmp/tmp[a-z0-9_]{6,8}/tmp[a-z0-9_]{6,8}-[a-f0-9]{64}\.zip' + ) + + def tearDown(self): # noqa + shutil.rmtree(self.tmpdir) + remove(self.tmpfile.name)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "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": 5 }
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": null, "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@e5561a7e43d92a0c19e7b6e31a36448455a17fba#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_shazar.py::TestIntegration::test" ]
[]
[ "conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_double_digits", "conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_failure_invalid_address", "conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_has_error", "conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_long_ids", "conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_no_bundles", "conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_one_running_one_starting_one_stopped", "conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_one_running_one_stopped_verbose", "conductr_cli/test/test_conduct_info.py::TestConductInfoCommand::test_stopped_bundle", "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_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", "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_run.py::TestConductRunCommand::test_failure", "conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_failure_invalid_address", "conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_success", "conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_success_long_ids", "conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_success_verbose", "conductr_cli/test/test_conduct_run.py::TestConductRunCommand::test_success_with_configuration", "conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_no_bundles", "conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_one_bundle_starting", "conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_one_bundle_starting_long_ids", "conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_two_bundles_mult_components_endpoints", "conductr_cli/test/test_conduct_services.py::TestConductServicesCommand::test_two_bundles_mult_components_endpoints_no_path", "conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_failure", "conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_failure_invalid_address", "conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_success", "conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_success_long_ids", "conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_success_verbose", "conductr_cli/test/test_conduct_stop.py::TestConductStopCommand::test_success_with_configuration", "conductr_cli/test/test_conduct_unload.py::TestConductUnloadCommand::test_failure", "conductr_cli/test/test_conduct_unload.py::TestConductUnloadCommand::test_failure_invalid_address", "conductr_cli/test/test_conduct_unload.py::TestConductUnloadCommand::test_success", "conductr_cli/test/test_conduct_unload.py::TestConductUnloadCommand::test_success_verbose", "conductr_cli/test/test_conduct_unload.py::TestConductUnloadCommand::test_success_with_configuration", "conductr_cli/test/test_shazar.py::TestShazar::test_create_digest", "conductr_cli/test/test_shazar.py::TestShazar::test_parser_success" ]
[]
Apache License 2.0
128
[ "conductr_cli/shazar.py", "setup.py", "conductr_cli/conduct_logging.py", ".gitignore", ".travis.yml", "tox.ini" ]
[ "conductr_cli/shazar.py", "setup.py", "conductr_cli/conduct_logging.py", ".gitignore", ".travis.yml", "tox.ini" ]
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
[ "premailer/premailer.py" ]
[ "premailer/premailer.py" ]
DinoTools__python-overpy-18
ac7df97ef4302d7eda46a6bb34a887e9b275748c
2015-05-09 07:36:00
7b0e0d999acb0549b57a271f31830fc020471731
diff --git a/overpy/__init__.py b/overpy/__init__.py index 454e1f5..cf48898 100644 --- a/overpy/__init__.py +++ b/overpy/__init__.py @@ -1,5 +1,6 @@ from collections import OrderedDict from decimal import Decimal +from xml.sax import handler, make_parser import json import re import sys @@ -14,6 +15,9 @@ from overpy.__about__ import ( PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 +XML_PARSER_DOM = 1 +XML_PARSER_SAX = 2 + if PY2: from urllib2 import urlopen from urllib2 import HTTPError @@ -41,10 +45,12 @@ class Overpass(object): """ default_read_chunk_size = 4096 - def __init__(self, read_chunk_size=None): + def __init__(self, read_chunk_size=None, xml_parser=XML_PARSER_SAX): """ :param read_chunk_size: Max size of each chunk read from the server response :type read_chunk_size: Integer + :param xml_parser: The xml parser to use + :type xml_parser: Integer """ self.url = "http://overpass-api.de/api/interpreter" self._regex_extract_error_msg = re.compile(b"\<p\>(?P<msg>\<strong\s.*?)\</p\>") @@ -52,6 +58,7 @@ class Overpass(object): if read_chunk_size is None: read_chunk_size = self.default_read_chunk_size self.read_chunk_size = read_chunk_size + self.xml_parser = xml_parser def query(self, query): """ @@ -131,7 +138,7 @@ class Overpass(object): data = json.loads(data, parse_float=Decimal) return Result.from_json(data, api=self) - def parse_xml(self, data, encoding="utf-8"): + def parse_xml(self, data, encoding="utf-8", parser=None): """ :param data: Raw XML Data @@ -141,14 +148,16 @@ class Overpass(object): :return: Result object :rtype: overpy.Result """ + if parser is None: + parser = self.xml_parser + if isinstance(data, bytes): data = data.decode(encoding) if PY2 and not isinstance(data, str): # Python 2.x: Convert unicode strings data = data.encode(encoding) - import xml.etree.ElementTree as ET - root = ET.fromstring(data) - return Result.from_xml(root, api=self) + + return Result.from_xml(data, api=self, parser=parser) class Result(object): @@ -262,7 +271,7 @@ class Result(object): return result @classmethod - def from_xml(cls, root, api=None): + def from_xml(cls, data, api=None, parser=XML_PARSER_SAX): """ Create a new instance and load data from xml object. @@ -270,15 +279,34 @@ class Result(object): :type data: xml.etree.ElementTree.Element :param api: :type api: Overpass + :param parser: Specify the parser to use(DOM or SAX) + :type parser: Integer :return: New instance of Result object :rtype: Result """ result = cls(api=api) - for elem_cls in [Node, Way, Relation]: - for child in root: - if child.tag.lower() == elem_cls._type_value: - result.append(elem_cls.from_xml(child, result=result)) + if parser == XML_PARSER_DOM: + import xml.etree.ElementTree as ET + root = ET.fromstring(data) + for elem_cls in [Node, Way, Relation]: + for child in root: + if child.tag.lower() == elem_cls._type_value: + result.append(elem_cls.from_xml(child, result=result)) + + elif parser == XML_PARSER_SAX: + if PY2: + from StringIO import StringIO + else: + from io import StringIO + source = StringIO(data) + sax_handler = OSMSAXHandler(result) + parser = make_parser() + parser.setContentHandler(sax_handler) + parser.parse(source) + else: + # ToDo: better exception + raise Exception("Unknown XML parser") return result def get_node(self, node_id, resolve_missing=False): @@ -952,3 +980,185 @@ class RelationRelation(RelationMember): def __repr__(self): return "<overpy.RelationRelation ref={} role={}>".format(self.ref, self.role) + + +class OSMSAXHandler(handler.ContentHandler): + """ + SAX parser for Overpass XML response. + """ + #: Tuple of opening elements to ignore + ignore_start = ('osm', 'meta', 'note') + #: Tuple of closing elements to ignore + ignore_end = ('osm', 'meta', 'note', 'tag', 'nd', 'member') + + def __init__(self, result): + """ + :param result: Append results to this result set. + :type result: overpy.Result + """ + handler.ContentHandler.__init__(self) + self._result = result + self._curr = {} + + def startElement(self, name, attrs): + """ + Handle opening elements. + + :param name: Name of the element + :type name: String + :param attrs: Attributes of the element + :type attrs: Dict + """ + if name in self.ignore_start: + return + try: + handler = getattr(self, '_handle_start_%s' % name) + except AttributeError: + raise KeyError("Unknown element start '%s'" % name) + handler(attrs) + + def endElement(self, name): + """ + Handle closing elements + + :param name: Name of the element + :type name: String + """ + if name in self.ignore_end: + return + try: + handler = getattr(self, '_handle_end_%s' % name) + except AttributeError: + raise KeyError("Unknown element start '%s'" % name) + handler() + + def _handle_start_tag(self, attrs): + """ + Handle opening tag element + + :param attrs: Attributes of the element + :type attrs: Dict + """ + try: + tag_key = attrs['k'] + except KeyError: + raise ValueError("Tag without name/key.") + self._curr['tags'][tag_key] = attrs.get('v') + + def _handle_start_node(self, attrs): + """ + Handle opening node element + + :param attrs: Attributes of the element + :type attrs: Dict + """ + self._curr = { + 'attributes': dict(attrs), + 'lat': None, + 'lon': None, + 'node_id': None, + 'tags': {} + } + if attrs.get('id', None) is not None: + self._curr['node_id'] = int(attrs['id']) + del self._curr['attributes']['id'] + if attrs.get('lat', None) is not None: + self._curr['lat'] = Decimal(attrs['lat']) + del self._curr['attributes']['lat'] + if attrs.get('lon', None) is not None: + self._curr['lon'] = Decimal(attrs['lon']) + del self._curr['attributes']['lon'] + + def _handle_end_node(self): + """ + Handle closing node element + """ + self._result.append(Node(result=self._result, **self._curr)) + self._curr = {} + + def _handle_start_way(self, attrs): + """ + Handle opening way element + + :param attrs: Attributes of the element + :type attrs: Dict + """ + self._curr = { + 'attributes': dict(attrs), + 'node_ids': [], + 'tags': {}, + 'way_id': None + } + if attrs.get('id', None) is not None: + self._curr['way_id'] = int(attrs['id']) + del self._curr['attributes']['id'] + + def _handle_end_way(self): + """ + Handle closing way element + """ + self._result.append(Way(result=self._result, **self._curr)) + self._curr = {} + + def _handle_start_nd(self, attrs): + """ + Handle opening nd element + + :param attrs: Attributes of the element + :type attrs: Dict + """ + try: + node_ref = attrs['ref'] + except KeyError: + raise ValueError("Unable to find required ref value.") + self._curr['node_ids'].append(int(node_ref)) + + def _handle_start_relation(self, attrs): + """ + Handle opening relation element + + :param attrs: Attributes of the element + :type attrs: Dict + """ + self._curr = { + 'attributes': dict(attrs), + 'members': [], + 'rel_id': None, + 'tags': {} + } + if attrs.get('id', None) is not None: + self._curr['rel_id'] = int(attrs['id']) + del self._curr['attributes']['id'] + + def _handle_end_relation(self): + """ + Handle closing relation element + """ + self._result.append(Relation(result=self._result, **self._curr)) + self._curr = {} + + def _handle_start_member(self, attrs): + """ + Handle opening member element + + :param attrs: Attributes of the element + :type attrs: Dict + """ + params = { + 'ref': None, + 'result': self._result, + 'role': None + } + if attrs.get('ref', None): + params['ref'] = int(attrs['ref']) + if attrs.get('role', None): + params['role'] = attrs['role'] + + if attrs['type'] == 'node': + self._curr['members'].append(RelationNode(**params)) + elif attrs['type'] == 'way': + self._curr['members'].append(RelationWay(**params)) + elif attrs['type'] == 'relation': + self._curr['members'].append(RelationRelation(**params)) + else: + raise ValueError("Undefined type for member: '%s'" % attrs['type'])
Less memory-consuming xml parsing Currently the whole xml-result is first parsed into a xml.etree.ElementTree and than processed to create overpy structures. While this is perfectly fine for small amounts of data, larger files or requests consume a lot of memory that is not freed after the overpy result is constructed. A SAX-style parser could reduce the memory footprint and both overpy's architecture and osm_xml's structure would easily support such a parser.
DinoTools/python-overpy
diff --git a/tests/test_xml.py b/tests/test_xml.py index 2f6d02a..e0c7397 100644 --- a/tests/test_xml.py +++ b/tests/test_xml.py @@ -9,31 +9,51 @@ from tests.base_class import read_file class TestNodes(BaseTestNodes): def test_node01(self): api = overpy.Overpass() - result = api.parse_xml(read_file("xml/node-01.xml")) + # DOM + result = api.parse_xml(read_file("xml/node-01.xml"), parser=overpy.XML_PARSER_DOM) + self._test_node01(result) + # SAX + result = api.parse_xml(read_file("xml/node-01.xml"), parser=overpy.XML_PARSER_SAX) self._test_node01(result) class TestRelation(BaseTestRelation): def test_relation01(self): api = overpy.Overpass() - result = api.parse_xml(read_file("xml/relation-01.xml")) + # DOM + result = api.parse_xml(read_file("xml/relation-01.xml"), parser=overpy.XML_PARSER_DOM) + self._test_relation01(result) + # SAX + result = api.parse_xml(read_file("xml/relation-01.xml"), parser=overpy.XML_PARSER_SAX) self._test_relation01(result) def test_relation02(self): api = overpy.Overpass() - result = api.parse_xml(read_file("xml/relation-02.xml")) + # DOM + result = api.parse_xml(read_file("xml/relation-02.xml"), parser=overpy.XML_PARSER_DOM) + self._test_relation02(result) + # SAX + result = api.parse_xml(read_file("xml/relation-02.xml"), parser=overpy.XML_PARSER_SAX) self._test_relation02(result) class TestWay(BaseTestWay): def test_way01(self): api = overpy.Overpass() - result = api.parse_xml(read_file("xml/way-01.xml")) + # DOM + result = api.parse_xml(read_file("xml/way-01.xml"), parser=overpy.XML_PARSER_DOM) + self._test_way01(result) + # SAX + result = api.parse_xml(read_file("xml/way-01.xml"), parser=overpy.XML_PARSER_SAX) self._test_way01(result) def test_way02(self): api = overpy.Overpass() - result = api.parse_xml(read_file("xml/way-02.xml")) + # DOM + result = api.parse_xml(read_file("xml/way-02.xml"), parser=overpy.XML_PARSER_DOM) + self._test_way02(result) + # SAX + result = api.parse_xml(read_file("xml/way-02.xml"), parser=overpy.XML_PARSER_SAX) self._test_way02(result)
{ "commit_name": "head_commit", "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false, "llm_score": { "difficulty_score": 2, "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": [ "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 -e git+https://github.com/DinoTools/python-overpy.git@ac7df97ef4302d7eda46a6bb34a887e9b275748c#egg=overpy 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: python-overpy 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/python-overpy
[ "tests/test_xml.py::TestNodes::test_node01", "tests/test_xml.py::TestRelation::test_relation01", "tests/test_xml.py::TestRelation::test_relation02", "tests/test_xml.py::TestWay::test_way01", "tests/test_xml.py::TestWay::test_way02" ]
[]
[ "tests/test_xml.py::TestDataError::test_element_wrong_type", "tests/test_xml.py::TestDataError::test_node_missing_data", "tests/test_xml.py::TestDataError::test_relation_missing_data", "tests/test_xml.py::TestDataError::test_way_missing_data" ]
[]
MIT License
130
[ "overpy/__init__.py" ]
[ "overpy/__init__.py" ]
mkdocs__mkdocs-510
5b8bae094b2cfbc3cb9ef2f77cee4c1271abd3e2
2015-05-09 20:09:55
463c5b647e9ce5992b519708a0b9c4cba891d65c
diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md index a619e5ea..97824ff0 100644 --- a/docs/user-guide/configuration.md +++ b/docs/user-guide/configuration.md @@ -163,6 +163,13 @@ Set a list of JavaScript files to be included by the theme. **default**: By default `extra_javascript` will contain a list of all the JavaScript files found within the `docs_dir`, if none are found it will be `[]` (an empty list). + +### extra + +A set of key value pairs, where the values can be any valid YAML construct, that will be passed to the template. This allows for great flexibility when creating custom themes. + +**default**: By default `extra` will be an empty key value mapping. + ## Preview controls ### use_directory_urls diff --git a/docs/user-guide/styling-your-docs.md b/docs/user-guide/styling-your-docs.md index af7d6ef7..78d510b3 100644 --- a/docs/user-guide/styling-your-docs.md +++ b/docs/user-guide/styling-your-docs.md @@ -119,15 +119,11 @@ Article content from each page specified in `mkdocs.yml` is inserted using the ` ### Template Variables -Each template in a theme is built with a template context. These are the variables that are available to theme. The context varies depending on the template that is being built. At the moment templates are either built with -the global context or with a page specific context. The global context is used -for HTML pages that don't represent an individual Markdown document, for -example a 404.html page or search.html. - +Each template in a theme is built with a template context. These are the variables that are available to themes. The context varies depending on the template that is being built. At the moment templates are either built with the global context or with a page specific context. The global context is used for HTML pages that don't represent an individual Markdown document, for example a 404.html page or search.html. #### Global Context -The following variables in the context map directly the the configuration file. +The following variables in the context map directly the the [configuration options](/user-guide/configuration/). Variable Name | Configuration name ----------------- | ------------------- | @@ -140,6 +136,7 @@ repo_name | repo_name | site_url | site_url | extra_css | extra_css | extra_javascript | extra_javascript | +extra | extra | include_nav | include_nav | include_next_prev | include_next_prev | copyright | copyright | @@ -237,6 +234,34 @@ The page object for the previous page. The isage is the same as for ##### next_page The page object for the next page.The isage is the same as for `current_page`. +#### Extra Context + +Additional variables can be passed to the template with the [`extra`](/user-guide/configuration/#extra) configuration option. This is a set of key value pairs that can make custom templates far more flexible. + +For example, this could be used to include the project version of all pages and a list of links related to the project. This can be achieved with the following `extra` configuration: + +```yaml +extra: + version: 0.13.0 + links: + - https://github.com/mkdocs + - https://docs.readthedocs.org/en/latest/builds.html#mkdocs + - http://www.mkdocs.org/ +``` + +And then displayed with this HTML in the custom theme. + +```html +{{ extra.version }} + +{% if extra.links %} + <ul> + {% for link in extra.links %} + <li>{{ link }}</li> + {% endfor %} + </ul> +{% endif %} +``` ### Search and themes diff --git a/mkdocs/build.py b/mkdocs/build.py index 1bd28e88..55dd4d47 100644 --- a/mkdocs/build.py +++ b/mkdocs/build.py @@ -1,4 +1,5 @@ # coding: utf-8 +from __future__ import print_function from datetime import datetime from io import open @@ -90,7 +91,9 @@ def get_global_context(nav, config): 'google_analytics': config['google_analytics'], 'mkdocs_version': mkdocs.__version__, - 'build_date_utc': datetime.utcnow() + 'build_date_utc': datetime.utcnow(), + + 'extra': config['extra'] } @@ -149,7 +152,7 @@ def build_sitemap(config, env, site_navigation): def build_template(template_name, env, config, site_navigation=None): - log.debug("Building template: %s", template_name) + log.debug("Building %s page", template_name) try: template = env.get_template(template_name) @@ -279,12 +282,12 @@ def build(config, live_server=False, dump_json=False, clean_site_dir=False): Perform a full site build. """ if clean_site_dir: - log.info("Cleaning site directory") + print("Cleaning site directory") utils.clean_directory(config['site_dir']) if not live_server: - log.info("Building documentation to directory: %s", config['site_dir']) + print("Building documentation to directory: %s" % config['site_dir']) if not clean_site_dir and site_directory_contains_stale_files(config['site_dir']): - log.info("The directory contains stale files. Use --clean to remove them.") + print("Directory %s contains stale files. Use --clean to remove them." % config['site_dir']) if dump_json: build_pages(config, dump_json=True) diff --git a/mkdocs/cli.py b/mkdocs/cli.py index 91ad8d34..06aa8a86 100644 --- a/mkdocs/cli.py +++ b/mkdocs/cli.py @@ -19,16 +19,11 @@ def configure_logging(is_verbose=False): '''When a --verbose flag is passed, increase the verbosity of mkdocs''' logger = logging.getLogger('mkdocs') - logger.propagate = False - stream = logging.StreamHandler() - formatter = logging.Formatter("%(levelname)-7s - %(message)s ") - stream.setFormatter(formatter) - logger.addHandler(stream) if is_verbose: logger.setLevel(logging.DEBUG) else: - logger.setLevel(logging.INFO) + logger.setLevel(logging.WARNING) clean_help = "Remove old files from the site_dir before building" diff --git a/mkdocs/config/defaults.py b/mkdocs/config/defaults.py index b3b14146..6ce0922e 100644 --- a/mkdocs/config/defaults.py +++ b/mkdocs/config/defaults.py @@ -96,4 +96,11 @@ DEFAULT_SCHEMA = ( # enabling strict mode causes MkDocs to stop the build when a problem is # encountered rather than display an error. ('strict', config_options.Type(bool, default=False)), + + # extra is a mapping/dictionary of data that is passed to the template. + # This allows template authors to require extra configuration that not + # relevant to all themes and doesn't need to be explicitly supported by + # MkDocs itself. A good example here would be including the current + # project version. + ('extra', config_options.Type(dict, default={})), ) diff --git a/mkdocs/gh_deploy.py b/mkdocs/gh_deploy.py index 4e07a0a5..f5692d2d 100644 --- a/mkdocs/gh_deploy.py +++ b/mkdocs/gh_deploy.py @@ -1,19 +1,15 @@ -import logging +from __future__ import print_function import subprocess import os -log = logging.getLogger(__name__) - def gh_deploy(config): if not os.path.exists('.git'): - log.info('Cannot deploy - this directory does not appear to be a git ' - 'repository') + print('Cannot deploy - this directory does not appear to be a git repository') return - log.info("Copying '%s' to `gh-pages` branch and pushing to GitHub.", - config['site_dir']) + print("Copying '%s' to `gh-pages` branch and pushing to GitHub." % config['site_dir']) try: command = ['ghp-import', '-p', config['site_dir']] if 'remote_branch' in config: @@ -27,16 +23,13 @@ def gh_deploy(config): # This GitHub pages repository has a CNAME configured. with(open('CNAME', 'r')) as f: cname_host = f.read().strip() - log.info('Based on your CNAME file, your documentation should be ' - 'available shortly at: http://%s', cname_host) - log.info('NOTE: Your DNS records must be configured appropriately for ' - 'your CNAME URL to work.') + print('Based on your CNAME file, your documentation should be available shortly at: http://%s' % cname_host) + print('NOTE: Your DNS records must be configured appropriately for your CNAME URL to work.') return # No CNAME found. We will use the origin URL to determine the GitHub # pages location. - url = subprocess.check_output(["git", "config", "--get", - "remote.origin.url"]) + url = subprocess.check_output(["git", "config", "--get", "remote.origin.url"]) url = url.decode('utf-8').strip() host = None @@ -48,10 +41,10 @@ def gh_deploy(config): if host is None: # This could be a GitHub Enterprise deployment. - log.info('Your documentation should be available shortly.') + print('Your documentation should be available shortly.') else: username, repo = path.split('/', 1) if repo.endswith('.git'): repo = repo[:-len('.git')] url = 'http://%s.github.io/%s' % (username, repo) - log.info('Your documentation should shortly be available at: ' + url) + print('Your documentation should shortly be available at: ' + url) diff --git a/mkdocs/new.py b/mkdocs/new.py index 165d124d..4f3420f9 100644 --- a/mkdocs/new.py +++ b/mkdocs/new.py @@ -1,8 +1,7 @@ # coding: utf-8 -from __future__ import unicode_literals +from __future__ import print_function, unicode_literals import os -import logging from io import open config_text = 'site_name: My Docs\n' @@ -25,8 +24,6 @@ For full documentation visit [mkdocs.org](http://mkdocs.org). ... # Other markdown pages, images and other files. """ -log = logging.getLogger(__name__) - def new(output_dir): @@ -35,20 +32,20 @@ def new(output_dir): index_path = os.path.join(docs_dir, 'index.md') if os.path.exists(config_path): - log.info('Project already exists.') + print('Project already exists.') return if not os.path.exists(output_dir): - log.info('Creating project directory: %s', output_dir) + print('Creating project directory: %s' % output_dir) os.mkdir(output_dir) - log.info('Writing config file: %s', config_path) + print('Writing config file: %s' % config_path) open(config_path, 'w', encoding='utf-8').write(config_text) if os.path.exists(index_path): return - log.info('Writing initial docs: %s', index_path) + print('Writing initial docs: %s' % index_path) if not os.path.exists(docs_dir): os.mkdir(docs_dir) open(index_path, 'w', encoding='utf-8').write(index_text)
Global template variables? This is more of a question (and potentially a feature request if this isn't supported) than an issue – is there some way to declare global variables? For example, in my config.yml, I'd like to define some global variable, `version-num` that, of course, represents the current version of the library that I'm documenting. I'd naturally like to use this all over in my documentation and have only one place to update the version number when releasing a new version – in config.yml. Though I've tried to do this and beyond the pre-defined variables in the mkdocs documentation, nothing that I declare seems to be picked up. Is there some way to do this that I don't see? PS, Jekyll allows for this, so I'm basically assuming the same semantics as Jekyll, i.e., that user-defined variables in config.yml are globally accessible
mkdocs/mkdocs
diff --git a/mkdocs/tests/build_tests.py b/mkdocs/tests/build_tests.py index 7f2a04a7..96f3b5b0 100644 --- a/mkdocs/tests/build_tests.py +++ b/mkdocs/tests/build_tests.py @@ -7,6 +7,7 @@ import tempfile import unittest from six.moves import zip +import mock from mkdocs import build, nav from mkdocs.config import base as config_base, defaults as config_defaults @@ -343,3 +344,22 @@ class BuildTests(unittest.TestCase): """) self.assertEqual(html.strip(), expected_html) + + def test_extra_context(self): + + # Same as the default schema, but don't verify the docs_dir exists. + config = config_base.Config(schema=config_defaults.DEFAULT_SCHEMA) + config.load_dict({ + 'site_name': "Site", + 'extra': { + 'a': 1 + } + }) + + self.assertEqual(config.validate(), ([], [])) + + context = build.get_global_context(mock.Mock(), config) + + self.assertEqual(context['extra'], { + 'a': 1 + })
{ "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": 1 }, "num_modified_files": 7 }
0.12
{ "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", "flake8", "nose", "mock", "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 coverage==7.8.0 exceptiongroup==1.2.2 flake8==7.2.0 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 mccabe==0.7.0 -e git+https://github.com/mkdocs/mkdocs.git@5b8bae094b2cfbc3cb9ef2f77cee4c1271abd3e2#egg=mkdocs mock==5.2.0 nose==1.3.7 packaging==24.2 pluggy==1.5.0 pycodestyle==2.13.0 pyflakes==3.3.1 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 - coverage==7.8.0 - exceptiongroup==1.2.2 - flake8==7.2.0 - 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 - mccabe==0.7.0 - mock==5.2.0 - nose==1.3.7 - packaging==24.2 - pluggy==1.5.0 - pycodestyle==2.13.0 - pyflakes==3.3.1 - 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/build_tests.py::BuildTests::test_extra_context" ]
[ "mkdocs/tests/build_tests.py::BuildTests::test_anchor_only_link", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_asbolute_media", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_differing_directory", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_link_with_anchor", "mkdocs/tests/build_tests.py::BuildTests::test_convert_internal_media", "mkdocs/tests/build_tests.py::BuildTests::test_convert_markdown", "mkdocs/tests/build_tests.py::BuildTests::test_convert_multiple_internal_links", "mkdocs/tests/build_tests.py::BuildTests::test_copying_media", "mkdocs/tests/build_tests.py::BuildTests::test_dont_convert_code_block_urls", "mkdocs/tests/build_tests.py::BuildTests::test_empty_document", "mkdocs/tests/build_tests.py::BuildTests::test_extension_config", "mkdocs/tests/build_tests.py::BuildTests::test_ignore_external_link", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_custom_extension", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_duplicate_custom_extension", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_fenced_code_extension", "mkdocs/tests/build_tests.py::BuildTests::test_markdown_table_extension", "mkdocs/tests/build_tests.py::BuildTests::test_not_use_directory_urls", "mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_invalid", "mkdocs/tests/build_tests.py::BuildTests::test_strict_mode_valid" ]
[]
[]
BSD 2-Clause "Simplified" License
131
[ "mkdocs/cli.py", "mkdocs/config/defaults.py", "docs/user-guide/styling-your-docs.md", "mkdocs/gh_deploy.py", "docs/user-guide/configuration.md", "mkdocs/new.py", "mkdocs/build.py" ]
[ "mkdocs/cli.py", "mkdocs/config/defaults.py", "docs/user-guide/styling-your-docs.md", "mkdocs/gh_deploy.py", "docs/user-guide/configuration.md", "mkdocs/new.py", "mkdocs/build.py" ]