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 864
values | install_config
dict | requirements
stringlengths 93
34.2k
⌀ | environment
stringlengths 760
20.5k
⌀ | FAIL_TO_PASS
sequencelengths 1
9.39k
| FAIL_TO_FAIL
sequencelengths 0
2.69k
| PASS_TO_PASS
sequencelengths 0
7.87k
| PASS_TO_FAIL
sequencelengths 0
192
| license_name
stringclasses 56
values | __index_level_0__
int64 0
21.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
|
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 |
|
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 |
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 |
sympy__sympy-8627 | 65f7c8c2c9c1927eaa8520c4ce06864f93a20ad1 | 2014-12-17 18:23:53 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | glyg: bumb?
Is this ok? I'd like to go back to using master...
jcrist: Please look at how other tests are written in sympy. Tests should be enclosed in their own function. For example, see the [existing tests for lagrange](https://github.com/sympy/sympy/blob/master/sympy/physics/mechanics/tests/test_lagrange.py).
glyg: is it ok like that, or are the `assert` statements too dumb?
jcrist: If they thoroughly test the issue you're fixing, then they're fine. If you could fix my two inline comments, and then squash your commits, this is good to go.
| diff --git a/sympy/physics/mechanics/lagrange.py b/sympy/physics/mechanics/lagrange.py
index 7e90313170..5206d7687e 100644
--- a/sympy/physics/mechanics/lagrange.py
+++ b/sympy/physics/mechanics/lagrange.py
@@ -210,10 +210,9 @@ def form_lagranges_equations(self):
if self.forcelist:
N = self.inertial
self._term4 = zeros(n, 1)
- flist = zip(*_f_list_parser(self.forcelist, N))
for i, qd in enumerate(qds):
- for obj, force in self.forcelist:
- self._term4[i] = sum(v.diff(qd, N) & f for (v, f) in flist)
+ flist = zip(*_f_list_parser(self.forcelist, N))
+ self._term4[i] = sum(v.diff(qd, N) & f for (v, f) in flist)
else:
self._term4 = zeros(n, 1)
| bug in physics/mechanics/lagrange.py
When providing a `forcelist` with more than one force, not all terms are computed,
this comes from the fact that the iterator `flist = zip(*_f_list_parser(self.forcelist, N))` is consumed in the first iteration of the loop.
I propose a following PR that fixes the bug, let me know if I need to also provide a test case.
Best,
Guillaume | sympy/sympy | diff --git a/sympy/physics/mechanics/tests/test_lagrange2.py b/sympy/physics/mechanics/tests/test_lagrange2.py
new file mode 100644
index 0000000000..2b2cca808a
--- /dev/null
+++ b/sympy/physics/mechanics/tests/test_lagrange2.py
@@ -0,0 +1,46 @@
+from sympy import symbols
+from sympy.physics.mechanics import dynamicsymbols
+from sympy.physics.mechanics import ReferenceFrame, Point, Particle
+from sympy.physics.mechanics import LagrangesMethod, Lagrangian
+
+### This test asserts that a system with more than one external forces
+### is acurately formed with Lagrange method (see issue #8626)
+
+def test_lagrange_2forces():
+ ### Equations for two damped springs in serie with two forces
+
+ ### generalized coordinates
+ qs = q1, q2 = dynamicsymbols('q1, q2')
+ ### generalized speeds
+ qds = q1d, q2d = dynamicsymbols('q1, q2', 1)
+
+ ### Mass, spring strength, friction coefficient
+ m, k, nu = symbols('m, k, nu')
+
+ N = ReferenceFrame('N')
+ O = Point('O')
+
+ ### Two points
+ P1 = O.locatenew('P1', q1 * N.x)
+ P1.set_vel(N, q1d * N.x)
+ P2 = O.locatenew('P1', q2 * N.x)
+ P2.set_vel(N, q2d * N.x)
+
+ pP1 = Particle('pP1', P1, m)
+ pP1.set_potential_energy(k * q1**2 / 2)
+
+ pP2 = Particle('pP2', P2, m)
+ pP2.set_potential_energy(k * (q1 - q2)**2 / 2)
+
+ #### Friction forces
+ forcelist = [(P1, - nu * q1d * N.x),
+ (P2, - nu * q2d * N.x)]
+ lag = Lagrangian(N, pP1, pP2)
+
+ l_method = LagrangesMethod(lag, (q1, q2), forcelist=forcelist, frame=N)
+ l_method.form_lagranges_equations()
+
+ eq1 = l_method.eom[0]
+ assert eq1.diff(q1d) == nu
+ eq2 = l_method.eom[1]
+ assert eq2.diff(q2d) == nu
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 3,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"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
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
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
-e git+https://github.com/sympy/sympy.git@65f7c8c2c9c1927eaa8520c4ce06864f93a20ad1#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/physics/mechanics/tests/test_lagrange2.py::test_lagrange_2forces"
] | [] | [] | [] | BSD | 4 |
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 |
|
sympy__sympy-8688 | 747f8d596dda58a9bf89cd3604045d7c51364627 | 2014-12-24 19:27:39 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/integrals/heurisch.py b/sympy/integrals/heurisch.py
index 82ddcd6ef9..ffe74bed7c 100644
--- a/sympy/integrals/heurisch.py
+++ b/sympy/integrals/heurisch.py
@@ -559,7 +559,8 @@ def find_non_syms(expr):
if solution is None:
return None
else:
- solution = [ (k.as_expr(), v.as_expr()) for k, v in solution.items() ]
+ # If the ring is RR k.as_expr() will be 1.0*A
+ solution = [ (k.as_expr().as_coeff_Mul()[1], v.as_expr()) for k, v in solution.items() ]
return candidate.subs(solution).subs(list(zip(coeffs, [S.Zero]*len(coeffs))))
if not (F.free_symbols - set(V)):
| Wrong result from integrate
Reported on the mailing list:
```
Hello, I am clearly making a stupid mistake, but what?
Arc length calculation:
x = Symbol('x')
formula = 2 * x**2
d = diff(formula, x)
i = integrate(sqrt(1 + d**2), (x, 5.0, 10.0))
gives a result of 150.087
but changing the formula to this:
formula = 0.26666 * x**2
gives a result of zero. In fact any coefficient less than one gives a result of zero.
```
The problem seems to be in heurisch. | sympy/sympy | diff --git a/sympy/integrals/tests/test_heurisch.py b/sympy/integrals/tests/test_heurisch.py
index c12380bbad..0a6a8b24e4 100644
--- a/sympy/integrals/tests/test_heurisch.py
+++ b/sympy/integrals/tests/test_heurisch.py
@@ -277,6 +277,12 @@ def omega(x):
assert heurisch(f, x) == g
+def test_RR():
+ # Make sure the algorithm does the right thing if the ring is RR. See
+ # issue 8685.
+ assert heurisch(sqrt(1 + 0.25*x**2), x, hints=[]) == \
+ 0.5*x*sqrt(0.25*x**2 + 1) + 1.0*asinh(0.5*x)
+
# TODO: convert the rest of PMINT tests:
# Airy functions
# f = (x - AiryAi(x)*AiryAi(1, x)) / (x**2 - AiryAi(x)**2)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"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.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
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/sympy/sympy.git@747f8d596dda58a9bf89cd3604045d7c51364627#egg=sympy
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: sympy
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/sympy
| [
"sympy/integrals/tests/test_heurisch.py::test_RR"
] | [] | [
"sympy/integrals/tests/test_heurisch.py::test_components",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_polynomials",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_fractions",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_log",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_exp",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_trigonometric",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_hyperbolic",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_mixed",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_radicals",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_special",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_symbolic_coeffs",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_symbolic_coeffs_1130",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_hacking",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_function",
"sympy/integrals/tests/test_heurisch.py::test_heurisch_wrapper",
"sympy/integrals/tests/test_heurisch.py::test_issue_3609",
"sympy/integrals/tests/test_heurisch.py::test_pmint_rat",
"sympy/integrals/tests/test_heurisch.py::test_pmint_trig",
"sympy/integrals/tests/test_heurisch.py::test_pmint_logexp",
"sympy/integrals/tests/test_heurisch.py::test_pmint_LambertW",
"sympy/integrals/tests/test_heurisch.py::test_pmint_WrightOmega"
] | [] | BSD | 6 |
|
sympy__sympy-8693 | 4ad1da4f9b569938b73176afea6d7e4a40e46026 | 2014-12-25 09:10:11 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/functions/special/gamma_functions.py b/sympy/functions/special/gamma_functions.py
index 6b839d6730..6532b69e24 100644
--- a/sympy/functions/special/gamma_functions.py
+++ b/sympy/functions/special/gamma_functions.py
@@ -162,9 +162,6 @@ def _eval_is_real(self):
def _eval_rewrite_as_tractable(self, z):
return C.exp(loggamma(z))
- def _eval_rewrite_as_factorial(self, z):
- return C.factorial(z - 1)
-
def _eval_nseries(self, x, n, logx):
x0 = self.args[0].limit(x, 0)
if not (x0.is_Integer and x0 <= 0):
diff --git a/sympy/plotting/plot.py b/sympy/plotting/plot.py
index 3f9a1661d9..cb4f41ca45 100644
--- a/sympy/plotting/plot.py
+++ b/sympy/plotting/plot.py
@@ -922,13 +922,13 @@ def process_series(self):
if len(points) == 2:
#interval math plotting
x, y = _matplotlib_list(points[0])
- self.ax.fill(x, y, facecolor='b', edgecolor='None' )
+ self.ax.fill(x, y, facecolor=s.line_color, edgecolor='None')
else:
# use contourf or contour depending on whether it is
# an inequality or equality.
#XXX: ``contour`` plots multiple lines. Should be fixed.
ListedColormap = self.matplotlib.colors.ListedColormap
- colormap = ListedColormap(["white", "blue"])
+ colormap = ListedColormap(["white", s.line_color])
xarray, yarray, zarray, plot_type = points
if plot_type == 'contour':
self.ax.contour(xarray, yarray, zarray,
diff --git a/sympy/plotting/plot_implicit.py b/sympy/plotting/plot_implicit.py
index 5514c35210..0cd490ebd8 100644
--- a/sympy/plotting/plot_implicit.py
+++ b/sympy/plotting/plot_implicit.py
@@ -45,7 +45,8 @@ class ImplicitSeries(BaseSeries):
is_implicit = True
def __init__(self, expr, var_start_end_x, var_start_end_y,
- has_equality, use_interval_math, depth, nb_of_points):
+ has_equality, use_interval_math, depth, nb_of_points,
+ line_color):
super(ImplicitSeries, self).__init__()
self.expr = sympify(expr)
self.var_x = sympify(var_start_end_x[0])
@@ -60,6 +61,7 @@ def __init__(self, expr, var_start_end_x, var_start_end_y,
self.nb_of_points = nb_of_points
self.use_interval_math = use_interval_math
self.depth = 4 + depth
+ self.line_color = line_color
def __str__(self):
return ('Implicit equation: %s for '
@@ -231,6 +233,11 @@ def plot_implicit(expr, x_var=None, y_var=None, **kwargs):
- ``ylabel`` string. The label for the y-axis
+ Aesthetics options:
+
+ - ``line_color``: float or string. Specifies the color for the plot.
+ See ``Plot`` to see how to set color for the plots.
+
plot_implicit, by default, uses interval arithmetic to plot functions. If
the expression cannot be plotted using interval arithmetic, it defaults to
a generating a contour using a mesh grid of fixed number of points. By
@@ -345,6 +352,7 @@ def _range_tuple(s):
use_interval = kwargs.pop('adaptive', True)
nb_of_points = kwargs.pop('points', 300)
depth = kwargs.pop('depth', 0)
+ line_color = kwargs.pop('line_color', "blue")
#Check whether the depth is greater than 4 or less than 0.
if depth > 4:
depth = 4
@@ -353,7 +361,7 @@ def _range_tuple(s):
series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y,
has_equality, use_interval, depth,
- nb_of_points)
+ nb_of_points, line_color)
show = kwargs.pop('show', True)
#set the x and y limits
| plot_implicit lacks a line_color option
```
Unlike many of the other plotting functions in the new plotting module, plot_implicit lacks the ability to set the color of the line via a line_color function.
Implementing the option should be very similar to implementing line_color in plot.
```
Original issue for #6688: http://code.google.com/p/sympy/issues/detail?id=3589
Original author: https://code.google.com/u/111207639578282893178/
| sympy/sympy | diff --git a/sympy/functions/special/tests/test_gamma_functions.py b/sympy/functions/special/tests/test_gamma_functions.py
index a1f991a732..ddeb42baf9 100644
--- a/sympy/functions/special/tests/test_gamma_functions.py
+++ b/sympy/functions/special/tests/test_gamma_functions.py
@@ -70,10 +70,6 @@ def test_gamma():
assert gamma(3*exp_polar(I*pi)/4).is_nonpositive is True
-def test_gamma_rewrite():
- assert gamma(n).rewrite(factorial) == factorial(n - 1)
-
-
def test_gamma_series():
assert gamma(x + 1).series(x, 0, 3) == \
1 - EulerGamma*x + x**2*(EulerGamma**2/2 + pi**2/12) + O(x**3)
diff --git a/sympy/plotting/tests/test_plot_implicit.py b/sympy/plotting/tests/test_plot_implicit.py
index 1eb6d88549..d90004c7a1 100644
--- a/sympy/plotting/tests/test_plot_implicit.py
+++ b/sympy/plotting/tests/test_plot_implicit.py
@@ -1,5 +1,5 @@
import warnings
-from sympy import (plot_implicit, cos, Symbol, Eq, sin, re, And, Or, exp, I,
+from sympy import (plot_implicit, cos, Symbol, symbols, Eq, sin, re, And, Or, exp, I,
tan, pi)
from sympy.plotting.plot import unset_show
from tempfile import NamedTemporaryFile
@@ -57,9 +57,17 @@ def plot_and_save(name):
assert issubclass(w[-1].category, UserWarning)
assert 'No labeled objects found' in str(w[0].message)
+def test_line_color():
+ x, y = symbols('x, y')
+ p = plot_implicit(x**2 + y**2 - 1, line_color="green", show=False)
+ assert p._series[0].line_color == "green"
+ p = plot_implicit(x**2 + y**2 - 1, line_color='r', show=False)
+ assert p._series[0].line_color == "r"
+
def test_matplotlib():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
plot_and_save('test')
+ test_line_color()
else:
skip("Matplotlib not the default backend")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"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": 2
},
"num_modified_files": 3
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y python3-dev python3-pip"
],
"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
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
mpmath==1.3.0
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/sympy/sympy.git@4ad1da4f9b569938b73176afea6d7e4a40e46026#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/plotting/tests/test_plot_implicit.py::test_line_color"
] | [] | [
"sympy/functions/special/tests/test_gamma_functions.py::test_gamma",
"sympy/functions/special/tests/test_gamma_functions.py::test_gamma_series",
"sympy/functions/special/tests/test_gamma_functions.py::test_lowergamma",
"sympy/functions/special/tests/test_gamma_functions.py::test_uppergamma",
"sympy/functions/special/tests/test_gamma_functions.py::test_polygamma",
"sympy/functions/special/tests/test_gamma_functions.py::test_polygamma_expand_func",
"sympy/functions/special/tests/test_gamma_functions.py::test_loggamma",
"sympy/functions/special/tests/test_gamma_functions.py::test_polygamma_expansion"
] | [] | BSD | 7 |
|
sympy__sympy-8723 | 7d7eb6731562f9a7cf25f92264613f0331f72119 | 2015-01-01 08:20:20 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/functions/combinatorial/factorials.py b/sympy/functions/combinatorial/factorials.py
index 280238d9df..dadf12d5c0 100644
--- a/sympy/functions/combinatorial/factorials.py
+++ b/sympy/functions/combinatorial/factorials.py
@@ -173,8 +173,8 @@ def _eval_is_positive(self):
return True
def _eval_is_real(self):
- if ((self.args[0].is_negative and self.args[0].is_noninteger) or
- self.args[0].is_nonnegative):
+ x = self.args[0]
+ if x.is_nonnegative or x.is_noninteger:
return True
| factorial(x) is not known to be real when x is a noninteger
I guess this is very much related to #8658.
When `x` is a noninteger real, `factorial(x)` is simply `gamma(x+1)`, which is gamma of a number which is not a nonpositive integer, hence it must be real. Thus, `factorial(x).is_real` should return `True` (but now it returns `None`).
| sympy/sympy | diff --git a/sympy/functions/combinatorial/tests/test_comb_factorials.py b/sympy/functions/combinatorial/tests/test_comb_factorials.py
index d00a55776e..355d89770a 100644
--- a/sympy/functions/combinatorial/tests/test_comb_factorials.py
+++ b/sympy/functions/combinatorial/tests/test_comb_factorials.py
@@ -88,8 +88,9 @@ def test_factorial():
n = Symbol('n', integer=True)
k = Symbol('k', integer=True, nonnegative=True)
r = Symbol('r', integer=False)
- s = Symbol('s', integer = False, negative = True)
+ s = Symbol('s', integer=False, negative=True)
t = Symbol('t', nonnegative=True)
+ u = Symbol('u', noninteger=True)
assert factorial(-2) == zoo
assert factorial(0) == 1
@@ -110,6 +111,7 @@ def test_factorial():
assert factorial(r).is_real is None
assert factorial(s).is_real is True
assert factorial(t).is_real is True
+ assert factorial(u).is_real is True
assert factorial(oo) == oo
| {
"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
} | 0.7 | {
"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.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
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/sympy/sympy.git@7d7eb6731562f9a7cf25f92264613f0331f72119#egg=sympy
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: sympy
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/sympy
| [
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial"
] | [] | [
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_rf_eval_apply",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_ff_eval_apply",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_diff",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_series",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_rewrite",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial2",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial_diff",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial_rewrite",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_subfactorial"
] | [] | BSD | 8 |
|
sympy__sympy-8744 | ba69df110637a54a57875b2c43d632c8de799e57 | 2015-01-03 23:46:40 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/functions/combinatorial/factorials.py b/sympy/functions/combinatorial/factorials.py
index dadf12d5c0..280238d9df 100644
--- a/sympy/functions/combinatorial/factorials.py
+++ b/sympy/functions/combinatorial/factorials.py
@@ -173,8 +173,8 @@ def _eval_is_positive(self):
return True
def _eval_is_real(self):
- x = self.args[0]
- if x.is_nonnegative or x.is_noninteger:
+ if ((self.args[0].is_negative and self.args[0].is_noninteger) or
+ self.args[0].is_nonnegative):
return True
diff --git a/sympy/functions/elementary/complexes.py b/sympy/functions/elementary/complexes.py
index bf1cd9c2b6..1a3e152b61 100644
--- a/sympy/functions/elementary/complexes.py
+++ b/sympy/functions/elementary/complexes.py
@@ -439,6 +439,8 @@ def eval(cls, arg):
obj = arg._eval_Abs()
if obj is not None:
return obj
+ if not isinstance(arg, C.Expr):
+ raise TypeError("Bad argument type for Abs(): %s" % type(arg))
# handle what we can
arg = signsimp(arg, evaluate=False)
if arg.is_Mul:
| An absolute value of an interval issues a deprecation warning
If we don't wish to support an absolute value of an interval, we should raise a `ValueError`. If we wish to support it (as a pointwise function on the interval), we don't need to issue the warning. However, the current situation is weird:
```python
>>> Abs(Interval(2, 3))
```
issues
```
sympy/functions/elementary/complexes.py:492: SymPyDeprecationWarning:
is_real has been deprecated since SymPy 0.7.6. Use is_subset(Reals)
instead. See https://github.com/sympy/sympy/issues/6212 for more info.
if arg.is_real is False and arg.is_imaginary is False:
```
As the warning suggests, this is probably related to #6212. | sympy/sympy | diff --git a/sympy/functions/combinatorial/tests/test_comb_factorials.py b/sympy/functions/combinatorial/tests/test_comb_factorials.py
index 355d89770a..d00a55776e 100644
--- a/sympy/functions/combinatorial/tests/test_comb_factorials.py
+++ b/sympy/functions/combinatorial/tests/test_comb_factorials.py
@@ -88,9 +88,8 @@ def test_factorial():
n = Symbol('n', integer=True)
k = Symbol('k', integer=True, nonnegative=True)
r = Symbol('r', integer=False)
- s = Symbol('s', integer=False, negative=True)
+ s = Symbol('s', integer = False, negative = True)
t = Symbol('t', nonnegative=True)
- u = Symbol('u', noninteger=True)
assert factorial(-2) == zoo
assert factorial(0) == 1
@@ -111,7 +110,6 @@ def test_factorial():
assert factorial(r).is_real is None
assert factorial(s).is_real is True
assert factorial(t).is_real is True
- assert factorial(u).is_real is True
assert factorial(oo) == oo
diff --git a/sympy/functions/elementary/tests/test_complexes.py b/sympy/functions/elementary/tests/test_complexes.py
index d9af2b0739..dde0640604 100644
--- a/sympy/functions/elementary/tests/test_complexes.py
+++ b/sympy/functions/elementary/tests/test_complexes.py
@@ -1,9 +1,9 @@
from sympy import (
Abs, adjoint, arg, atan2, conjugate, cos, DiracDelta, E, exp, expand,
- Expr, Function, Heaviside, I, im, log, nan, oo, pi, Rational, re, S,
+ Expr, Function, Heaviside, I, im, log, nan, oo, pi, Rational, re, S, C,
sign, sin, sqrt, Symbol, symbols, transpose, zoo, exp_polar, Piecewise
)
-from sympy.utilities.pytest import XFAIL
+from sympy.utilities.pytest import XFAIL, raises
from sympy.utilities.randtest import comp
@@ -308,6 +308,8 @@ def test_sign_issue_3068():
def test_Abs():
+ raises(TypeError, lambda: Abs(C.Interval(2, 3))) # issue 8717
+
x, y = symbols('x,y')
assert sign(sign(x)) == sign(x)
assert sign(x*y).func is sign
| {
"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.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y python3-dev python3-pip"
],
"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
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
mpmath==1.3.0
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/sympy/sympy.git@ba69df110637a54a57875b2c43d632c8de799e57#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/functions/elementary/tests/test_complexes.py::test_Abs"
] | [] | [
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_rf_eval_apply",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_ff_eval_apply",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_diff",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_series",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_rewrite",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial2",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial_diff",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial_rewrite",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_subfactorial",
"sympy/functions/elementary/tests/test_complexes.py::test_re",
"sympy/functions/elementary/tests/test_complexes.py::test_im",
"sympy/functions/elementary/tests/test_complexes.py::test_sign",
"sympy/functions/elementary/tests/test_complexes.py::test_as_real_imag",
"sympy/functions/elementary/tests/test_complexes.py::test_Abs_rewrite",
"sympy/functions/elementary/tests/test_complexes.py::test_Abs_real",
"sympy/functions/elementary/tests/test_complexes.py::test_Abs_properties",
"sympy/functions/elementary/tests/test_complexes.py::test_abs",
"sympy/functions/elementary/tests/test_complexes.py::test_arg",
"sympy/functions/elementary/tests/test_complexes.py::test_arg_rewrite",
"sympy/functions/elementary/tests/test_complexes.py::test_adjoint",
"sympy/functions/elementary/tests/test_complexes.py::test_conjugate",
"sympy/functions/elementary/tests/test_complexes.py::test_conjugate_transpose",
"sympy/functions/elementary/tests/test_complexes.py::test_transpose",
"sympy/functions/elementary/tests/test_complexes.py::test_issue_4035",
"sympy/functions/elementary/tests/test_complexes.py::test_issue_3206",
"sympy/functions/elementary/tests/test_complexes.py::test_issue_4754_derivative_conjugate",
"sympy/functions/elementary/tests/test_complexes.py::test_derivatives_issue_4757",
"sympy/functions/elementary/tests/test_complexes.py::test_periodic_argument",
"sympy/functions/elementary/tests/test_complexes.py::test_principal_branch"
] | [] | BSD | 9 |
|
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 |
|
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 |
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 |
|
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 |
|
sympy__sympy-8765 | c10daac083cfb83f7fa5a5a454942b8b6d6b2c22 | 2015-01-07 16:11:36 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | skirpichev: Product, not product!
aktech: I think you mean : symbol 'i' (for dummy variable i)
as If I use `i = Dummy('i')` , the output would look like this:
`Product(_i, (_i, 1, k))`
skirpichev: > I think you mean : symbol
No. I mean Dummy.
aktech: If I use i = Dummy('i') , the output would be `Product(_i, (_i, 1, k))' (Notice _i)
and if I put that into tests that would give an Error.
skirpichev: You can compare e.g. strings. See other similar tests in the function (e.g. Sum rewrite).
aktech: Oh! fine, that would be good.
Thanks.
pelegm: +1.
aktech: Fixed.
@skirpichev
Thanks | diff --git a/sympy/functions/combinatorial/factorials.py b/sympy/functions/combinatorial/factorials.py
index dc2ed2b5b2..185ae0d56c 100644
--- a/sympy/functions/combinatorial/factorials.py
+++ b/sympy/functions/combinatorial/factorials.py
@@ -1,6 +1,6 @@
from __future__ import print_function, division
-from sympy.core import S, C, sympify
+from sympy.core import S, C, sympify, Dummy
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.logic import fuzzy_and
from sympy.ntheory import sieve
@@ -164,6 +164,11 @@ def eval(cls, n):
def _eval_rewrite_as_gamma(self, n):
return C.gamma(n + 1)
+ def _eval_rewrite_as_Product(self, n):
+ if n.is_nonnegative and n.is_integer:
+ i = Dummy('i', integer=True)
+ return C.Product(i, (i, 1, n))
+
def _eval_is_integer(self):
if self.args[0].is_integer and self.args[0].is_nonnegative:
return True
| Rewrite factorial as a product
It would be nice that if, say,
```python
>>> k = Symbol('k', integer=True, nonnegative=True)
```
then the following would hold
```python
>>> factorial(k).rewrite(product)
Product(i, (i, 1, k))
```
(for a dummy positive integer `i`)
| sympy/sympy | diff --git a/sympy/functions/combinatorial/tests/test_comb_factorials.py b/sympy/functions/combinatorial/tests/test_comb_factorials.py
index eba850cbb8..727c5fc999 100644
--- a/sympy/functions/combinatorial/tests/test_comb_factorials.py
+++ b/sympy/functions/combinatorial/tests/test_comb_factorials.py
@@ -1,6 +1,6 @@
from sympy import (Symbol, symbols, factorial, factorial2, binomial,
rf, ff, gamma, polygamma, EulerGamma, O, pi, nan,
- oo, zoo, simplify, expand_func, C, S)
+ oo, zoo, simplify, expand_func, C, S, Product)
from sympy.functions.combinatorial.factorials import subfactorial
from sympy.utilities.pytest import XFAIL, raises
@@ -146,8 +146,10 @@ def test_factorial_series():
def test_factorial_rewrite():
n = Symbol('n', integer=True)
+ k = Symbol('k', integer=True, nonnegative=True)
assert factorial(n).rewrite(gamma) == gamma(n + 1)
+ assert str(factorial(k).rewrite(Product)) == 'Product(_i, (_i, 1, k))'
def test_factorial2():
| {
"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": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "mpmath>=0.19",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.7",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi @ file:///croot/certifi_1671487769961/work/certifi
exceptiongroup==1.2.2
importlib-metadata==6.7.0
iniconfig==2.0.0
mpmath==1.2.1
packaging==24.0
pluggy==1.2.0
pytest==7.4.4
-e git+https://github.com/sympy/sympy.git@c10daac083cfb83f7fa5a5a454942b8b6d6b2c22#egg=sympy
tomli==2.0.1
typing_extensions==4.7.1
zipp==3.15.0
| name: sympy
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
- mpmath=1.2.1=py37h06a4308_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=22.3.1=py37h06a4308_0
- python=3.7.16=h7a1cb2a_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py37h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.38.4=py37h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- exceptiongroup==1.2.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- packaging==24.0
- pluggy==1.2.0
- pytest==7.4.4
- tomli==2.0.1
- typing-extensions==4.7.1
- zipp==3.15.0
prefix: /opt/conda/envs/sympy
| [
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_rewrite"
] | [
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_simplify_fail"
] | [
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_rf_eval_apply",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_ff_eval_apply",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_diff",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_series",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial2",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial_diff",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial_rewrite",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_subfactorial"
] | [] | BSD | 14 |
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 |
|
sympy__sympy-8778 | c958e5f72e8c4eab02e644810f7102a817d62b72 | 2015-01-08 15:28:17 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/doc/src/install.rst b/doc/src/install.rst
index 7a67b2d296..e281939c48 100644
--- a/doc/src/install.rst
+++ b/doc/src/install.rst
@@ -3,12 +3,12 @@
Installation
------------
-The SymPy CAS can be installed on virtually any computer with Python
-2.6 or above. SymPy does require `mpmath`_ Python library to be
-installed first. The current recommended method of installation is
-directly from the source files. Alternatively, executables are
-available for Windows, and some Linux distributions have SymPy
-packages available.
+The SymPy CAS can be installed on virtually any computer with Python 2.6 or
+above. SymPy does not require any special Python modules: let us know if you
+have any problems with SymPy on a standard Python install. The current
+recommended method of installation is directly from the source files.
+Alternatively, executables are available for Windows, and some Linux
+distributions have SymPy packages available.
SymPy officially supports Python 2.6, 2.7, 3.2, 3.3, 3.4, and PyPy.
@@ -120,4 +120,3 @@ an `issue ticket`_.
.. _Gitter: https://gitter.im/sympy/sympy
.. _issue ticket: https://github.com/sympy/sympy/issues
.. _mailing list: http://groups.google.com/group/sympy
-.. _mpmath: http://mpmath.org/
diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py
index 6f0411cf8d..abbb6aacb7 100644
--- a/sympy/core/numbers.py
+++ b/sympy/core/numbers.py
@@ -2267,6 +2267,7 @@ class Infinity(with_metaclass(Singleton, Number)):
is_positive = True
is_infinite = True
is_number = True
+ is_prime = False
__slots__ = []
@@ -2828,6 +2829,7 @@ class ComplexInfinity(with_metaclass(Singleton, AtomicExpr)):
is_commutative = True
is_infinite = True
is_number = True
+ is_prime = False
__slots__ = []
| oo.is_prime is not False
`oo.is_prime` should be False, I guess, and same with `zoo.is_prime`. | sympy/sympy | diff --git a/sympy/core/tests/test_assumptions.py b/sympy/core/tests/test_assumptions.py
index 0d6d9b5086..81e87efdc9 100644
--- a/sympy/core/tests/test_assumptions.py
+++ b/sympy/core/tests/test_assumptions.py
@@ -119,7 +119,7 @@ def test_infinity():
assert oo.is_finite is False
assert oo.is_infinite is True
assert oo.is_comparable is True
- assert oo.is_prime is None
+ assert oo.is_prime is False
assert oo.is_composite is None
assert oo.is_number is True
| {
"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": 0
},
"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": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"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
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
mpmath==1.3.0
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/sympy/sympy.git@c958e5f72e8c4eab02e644810f7102a817d62b72#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_assumptions.py::test_infinity"
] | [] | [
"sympy/core/tests/test_assumptions.py::test_symbol_unset",
"sympy/core/tests/test_assumptions.py::test_zero",
"sympy/core/tests/test_assumptions.py::test_one",
"sympy/core/tests/test_assumptions.py::test_negativeone",
"sympy/core/tests/test_assumptions.py::test_neg_infinity",
"sympy/core/tests/test_assumptions.py::test_nan",
"sympy/core/tests/test_assumptions.py::test_pos_rational",
"sympy/core/tests/test_assumptions.py::test_neg_rational",
"sympy/core/tests/test_assumptions.py::test_pi",
"sympy/core/tests/test_assumptions.py::test_E",
"sympy/core/tests/test_assumptions.py::test_I",
"sympy/core/tests/test_assumptions.py::test_symbol_real",
"sympy/core/tests/test_assumptions.py::test_symbol_zero",
"sympy/core/tests/test_assumptions.py::test_symbol_positive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_positive",
"sympy/core/tests/test_assumptions.py::test_symbol_nonpositive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_nonpositive",
"sympy/core/tests/test_assumptions.py::test_symbol_falsepositive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsepositive",
"sympy/core/tests/test_assumptions.py::test_symbol_falsepositive_real",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsepositive_real",
"sympy/core/tests/test_assumptions.py::test_symbol_falsenonnegative",
"sympy/core/tests/test_assumptions.py::test_symbol_falsenonnegative_real",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsenonnegative_real",
"sympy/core/tests/test_assumptions.py::test_prime",
"sympy/core/tests/test_assumptions.py::test_composite",
"sympy/core/tests/test_assumptions.py::test_prime_symbol",
"sympy/core/tests/test_assumptions.py::test_symbol_noncommutative",
"sympy/core/tests/test_assumptions.py::test_other_symbol",
"sympy/core/tests/test_assumptions.py::test_issue_3825",
"sympy/core/tests/test_assumptions.py::test_issue_4822",
"sympy/core/tests/test_assumptions.py::test_hash_vs_typeinfo",
"sympy/core/tests/test_assumptions.py::test_hash_vs_typeinfo_2",
"sympy/core/tests/test_assumptions.py::test_hash_vs_eq",
"sympy/core/tests/test_assumptions.py::test_Add_is_pos_neg",
"sympy/core/tests/test_assumptions.py::test_Add_is_imaginary",
"sympy/core/tests/test_assumptions.py::test_Add_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Mul_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Pow_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Mul_is_infinite",
"sympy/core/tests/test_assumptions.py::test_special_is_rational",
"sympy/core/tests/test_assumptions.py::test_sanitize_assumptions",
"sympy/core/tests/test_assumptions.py::test_special_assumptions",
"sympy/core/tests/test_assumptions.py::test_inconsistent",
"sympy/core/tests/test_assumptions.py::test_issue_6631",
"sympy/core/tests/test_assumptions.py::test_issue_2730",
"sympy/core/tests/test_assumptions.py::test_issue_4149",
"sympy/core/tests/test_assumptions.py::test_issue_2920",
"sympy/core/tests/test_assumptions.py::test_issue_7899",
"sympy/core/tests/test_assumptions.py::test_issue_8075",
"sympy/core/tests/test_assumptions.py::test_issue_8642"
] | [] | BSD | 16 |
|
sympy__sympy-8784 | b5b6b45f65b828f37f09a4a09c90c68367e3b802 | 2015-01-09 06:48:01 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | smichr: +1
smichr: Will commit in 24h if neither @hargup nor @skirpichev have further comments.
hargup: +1, but I'm not very sure if the concerns by @skirpichev in https://github.com/sympy/sympy/pull/8259 are addressed here. I think we should wait for him to give a +1.
skirpichev: We have funny things in this pr:
```python
In [4]: solve(x >= oo)
Out[4]: x = ∞
In [3]: solve(x <= oo)
Out[3]: x = ∞
```
pelegm: > We have funny things in this pr
I'm ok with these "funny" things, as long as the assumptions on `x` allow it. For example, if `x` is real (but not `extended_real`), then the solution should be `[]` (or `False`, I'm not sure what is the convention).
However, as these assumptions are not properly handled in the real assumption system, I wouldn't bother to handle this now.
pelegm: Oh, I apologize: I was talking only about the **first** "funny" thing. The second funny thing is indeed funny, in the sense that we should consider it as a bug...
aktech: I think the first funny thing is related to this #8260 , which is a part of solvers, since inequality solver is dependent on solvers, that should be good for now.
For second funny thing `x <= oo`: which is read as x is less OR equal to infinity for that solution should be: `And(-oo < x, x < oo)` , I have FIXED that.
skirpichev: > For second funny thing x <= oo: which is read as x is less OR equal to infinity for that solution should be: And(-oo < x, x < oo) , I have FIXED that.
I don't think so:
```python
In [1]: solve(x <= oo)
Out[1]: -∞ < x ∧ x < ∞
```
Maybe it's a documentation bug, i.e. we disallow oo as solution (i.e. we search for solutions over real/complex domains, not in extended reals). | diff --git a/AUTHORS b/AUTHORS
index bbe66d9108..f90115794e 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -375,4 +375,3 @@ Cody Herbst <[email protected]>
AMiT Kumar <[email protected]>
Nishith Shah <[email protected]>
Guillaume Gay <[email protected]>
-Ray Cathcart <[email protected]>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index affa4e79de..55d17a1dcf 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -380,7 +380,6 @@ want to be mentioned here, so see our repository history for a full list).
#. AMiT Kumar: fix sign error in unrad
#. Nishith Shah: fix solving of Piecewise functions
#. Guillaume Gay: bugfix for LagrangesMethod
-#. Ray Cathcart: improve error handling in _random
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
diff --git a/doc/src/install.rst b/doc/src/install.rst
index 7a67b2d296..e281939c48 100644
--- a/doc/src/install.rst
+++ b/doc/src/install.rst
@@ -3,12 +3,12 @@
Installation
------------
-The SymPy CAS can be installed on virtually any computer with Python
-2.6 or above. SymPy does require `mpmath`_ Python library to be
-installed first. The current recommended method of installation is
-directly from the source files. Alternatively, executables are
-available for Windows, and some Linux distributions have SymPy
-packages available.
+The SymPy CAS can be installed on virtually any computer with Python 2.6 or
+above. SymPy does not require any special Python modules: let us know if you
+have any problems with SymPy on a standard Python install. The current
+recommended method of installation is directly from the source files.
+Alternatively, executables are available for Windows, and some Linux
+distributions have SymPy packages available.
SymPy officially supports Python 2.6, 2.7, 3.2, 3.3, 3.4, and PyPy.
@@ -120,4 +120,3 @@ an `issue ticket`_.
.. _Gitter: https://gitter.im/sympy/sympy
.. _issue ticket: https://github.com/sympy/sympy/issues
.. _mailing list: http://groups.google.com/group/sympy
-.. _mpmath: http://mpmath.org/
diff --git a/doc/src/modules/functions/combinatorial.rst b/doc/src/modules/functions/combinatorial.rst
index 21148aec87..d5c4a5d756 100644
--- a/doc/src/modules/functions/combinatorial.rst
+++ b/doc/src/modules/functions/combinatorial.rst
@@ -41,12 +41,6 @@ factorial
.. autoclass:: sympy.functions.combinatorial.factorials.factorial
:members:
-subfactorial
-------------
-
-.. autoclass:: sympy.functions.combinatorial.factorials.subfactorial
- :members:
-
factorial2 / double factorial
-----------------------------
diff --git a/sympy/core/expr.py b/sympy/core/expr.py
index 2b6875fabd..c6f4f9fd84 100644
--- a/sympy/core/expr.py
+++ b/sympy/core/expr.py
@@ -369,7 +369,7 @@ def _random(self, n=None, re_min=-1, im_min=-1, re_max=1, im_max=1):
for zi in free])))
try:
nmag = abs(self.evalf(2, subs=reps))
- except (ValueError, TypeError):
+ except TypeError:
# if an out of range value resulted in evalf problems
# then return None -- XXX is there a way to know how to
# select a good random number for a given expression?
diff --git a/sympy/core/function.py b/sympy/core/function.py
index 900cb31161..be6798e036 100644
--- a/sympy/core/function.py
+++ b/sympy/core/function.py
@@ -1556,7 +1556,9 @@ def _hashable_content(self):
def _eval_subs(self, old, new):
if old in self.variables:
- return self
+ pts = list(self.point.args)
+ pts[self.variables.index(old)] = new
+ return self.func(self.expr, self.variables, pts)
def _eval_derivative(self, s):
if s not in self.free_symbols:
diff --git a/sympy/functions/combinatorial/factorials.py b/sympy/functions/combinatorial/factorials.py
index 185ae0d56c..20ffd3718c 100644
--- a/sympy/functions/combinatorial/factorials.py
+++ b/sympy/functions/combinatorial/factorials.py
@@ -1,6 +1,6 @@
from __future__ import print_function, division
-from sympy.core import S, C, sympify, Dummy
+from sympy.core import S, C, sympify
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.logic import fuzzy_and
from sympy.ntheory import sieve
@@ -164,11 +164,6 @@ def eval(cls, n):
def _eval_rewrite_as_gamma(self, n):
return C.gamma(n + 1)
- def _eval_rewrite_as_Product(self, n):
- if n.is_nonnegative and n.is_integer:
- i = Dummy('i', integer=True)
- return C.Product(i, (i, 1, n))
-
def _eval_is_integer(self):
if self.args[0].is_integer and self.args[0].is_nonnegative:
return True
@@ -205,15 +200,9 @@ class subfactorial(CombinatorialFunction):
It can also be written as int(round(n!/exp(1))) but the recursive
definition with caching is implemented for this function.
- This function is generalized to noninteger arguments [2]_ as
-
- .. math:: !x = \Gamma(x + 1, -1)/e
-
References
==========
-
.. [1] http://en.wikipedia.org/wiki/Subfactorial
- .. [2] http://mathworld.wolfram.com/Subfactorial.html
Examples
========
@@ -227,35 +216,32 @@ class subfactorial(CombinatorialFunction):
See Also
========
-
- sympy.functions.combinatorial.factorials.factorial,
- sympy.utilities.iterables.generate_derangements,
- sympy.functions.special.gamma_functions.uppergamma
+ factorial, sympy.utilities.iterables.generate_derangements
"""
@classmethod
@cacheit
def _eval(self, n):
if not n:
- return S.One
+ return 1
elif n == 1:
- return S.Zero
+ return 0
return (n - 1)*(self._eval(n - 1) + self._eval(n - 2))
@classmethod
def eval(cls, arg):
- if arg.is_Number:
- if arg.is_Integer and arg.is_nonnegative:
- return cls._eval(arg)
- elif arg is S.Infinity:
- return arg
+ try:
+ arg = as_int(arg)
+ if arg < 0:
+ raise ValueError
+ return C.Integer(cls._eval(arg))
+ except ValueError:
+ if sympify(arg).is_Number:
+ raise ValueError("argument must be a nonnegative integer")
def _eval_is_integer(self):
- if self.args[0].is_integer and self.args[0].is_nonnegative:
- return True
-
- def _eval_rewrite_as_uppergamma(self, arg):
- return C.uppergamma(arg + 1, -1)/S.Exp1
+ return fuzzy_and((self.args[0].is_integer,
+ self.args[0].is_nonnegative))
class factorial2(CombinatorialFunction):
diff --git a/sympy/physics/hep/gamma_matrices.py b/sympy/physics/hep/gamma_matrices.py
index 013c771f0e..2fe6756854 100644
--- a/sympy/physics/hep/gamma_matrices.py
+++ b/sympy/physics/hep/gamma_matrices.py
@@ -1,7 +1,7 @@
from sympy import S
from sympy.tensor.tensor import TensorIndexType, TensorIndex,\
TensMul, TensorHead, tensorsymmetry, TensorType,\
- TensAdd, tensor_mul, get_lines, Tensor
+ TensAdd, tensor_mul, get_lines
from sympy.core.containers import Tuple
@@ -86,18 +86,13 @@ def extract_type_tens(expression):
"""
- if isinstance(expression, Tensor):
- sp = [expression]
- elif isinstance(expression, TensMul):
- sp = expression.args
- else:
- raise ValueError('wrong type')
+ sp = expression.split()
# Collect all gamma matrices of the same dimension
new_expr = S.One
residual_expr = S.One
for i in sp:
- if isinstance(i, Tensor) and isinstance(i.args[0], GammaMatrixHead):
+ if isinstance(i.args[1][0], GammaMatrixHead):
new_expr *= i
else:
residual_expr *= i
@@ -167,8 +162,8 @@ def _simplify_gpgp(ex):
if not ta:
ta = ex.split()
mu = TensorIndex('mu', GammaMatrix.LorentzIndex)
- ind1 = ta[ai[0]].get_indices()[1]
- ind2 = ta[ai[0] + 1].get_indices()[2]
+ ind1 = ta[ai[0]].args[-1][1]
+ ind2 = ta[ai[0] + 1].args[-1][2]
hit = True
if i == 0:
coeff = ex.coeff
@@ -377,7 +372,7 @@ def _trace_single_line1(t):
if isinstance(t, TensAdd):
a = [x.coeff*_trace_single_line1(x) for x in t.args]
return TensAdd(*a)
- elif isinstance(t, (Tensor, TensMul)):
+ elif isinstance(t, TensMul):
r = t.coeff*_trace_single_line1(t)
return r
else:
@@ -393,14 +388,14 @@ def _gamma_trace1(self, *a):
#return TensMul.from_data(S.Zero, [], [], [])
return S.Zero
if n == 2:
- ind0 = a[0].get_indices()[0]
- ind1 = a[1].get_indices()[0]
+ ind0 = a[0].args[-1][0]
+ ind1 = a[1].args[-1][0]
return gctr*g(ind0, ind1)
if n == 4:
- ind0 = a[0].get_indices()[0]
- ind1 = a[1].get_indices()[0]
- ind2 = a[2].get_indices()[0]
- ind3 = a[3].get_indices()[0]
+ ind0 = a[0].args[-1][0]
+ ind1 = a[1].args[-1][0]
+ ind2 = a[2].args[-1][0]
+ ind3 = a[3].args[-1][0]
return gctr*(g(ind0, ind1)*g(ind2, ind3) - \
g(ind0, ind2)*g(ind1, ind3) + g(ind0, ind3)*g(ind1, ind2))
@@ -467,7 +462,7 @@ def _kahane_simplify(coeff, tids):
>>> tc = 3*G(i0)*G(i1)
>>> G._kahane_simplify(tc.coeff, tc._tids)
- 3*gamma(i0, auto_left, S_0)*gamma(i1, -S_0, -auto_right)
+ 3*gamma(i0, auto_left, -S_0)*gamma(i1, S_0, -auto_right)
References
==========
diff --git a/sympy/polys/rootoftools.py b/sympy/polys/rootoftools.py
index f889495708..d3d9a03457 100644
--- a/sympy/polys/rootoftools.py
+++ b/sympy/polys/rootoftools.py
@@ -554,41 +554,39 @@ def _eval_evalf(self, prec):
while True:
if self.is_real:
- a = mpf(str(interval.a))
- b = mpf(str(interval.b))
- if a == b:
- root = a
- break
x0 = mpf(str(interval.center))
else:
- ax = mpf(str(interval.ax))
- bx = mpf(str(interval.bx))
- ay = mpf(str(interval.ay))
- by = mpf(str(interval.by))
- if ax == bx and ay == by:
- root = ax + S.ImaginaryUnit*by
- break
x0 = mpc(*map(str, interval.center))
-
try:
- root = findroot(func, x0)
+ root = findroot(func, x0, verify=False)
# If the (real or complex) root is not in the 'interval',
# then keep refining the interval. This happens if findroot
# accidentally finds a different root outside of this
# interval because our initial estimate 'x0' was not close
- # enough. It is also possible that the secant method will
- # get trapped by a max/min in the interval; the root
- # verification by findroot will raise a ValueError in this
- # case and the interval will then be tightened -- and
- # eventually the root will be found.
+ # enough.
if self.is_real:
- if (a < root < b):
+ a = mpf(str(interval.a))
+ b = mpf(str(interval.b))
+ if a == b:
+ root = a
+ break
+ if not (a < root < b):
+ raise ValueError("Root not in the interval.")
+ else:
+ ax = mpf(str(interval.ax))
+ bx = mpf(str(interval.bx))
+ ay = mpf(str(interval.ay))
+ by = mpf(str(interval.by))
+ if ax == bx and ay == by:
+ root = ax + S.ImaginaryUnit*by
break
- elif (ax < root.real < bx and ay < root.imag < by):
- break
+ if not (ax < root.real < bx and ay < root.imag < by):
+ raise ValueError("Root not in the interval.")
except ValueError:
- pass
- interval = interval.refine()
+ interval = interval.refine()
+ continue
+ else:
+ break
return Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec)
diff --git a/sympy/printing/str.py b/sympy/printing/str.py
index b7658005de..4c0b8bfa65 100644
--- a/sympy/printing/str.py
+++ b/sympy/printing/str.py
@@ -364,9 +364,6 @@ def _print_TensorIndex(self, expr):
def _print_TensorHead(self, expr):
return expr._print()
- def _print_Tensor(self, expr):
- return expr._print()
-
def _print_TensMul(self, expr):
return expr._print()
diff --git a/sympy/solvers/inequalities.py b/sympy/solvers/inequalities.py
index 33afd9742a..102e38e279 100644
--- a/sympy/solvers/inequalities.py
+++ b/sympy/solvers/inequalities.py
@@ -432,6 +432,12 @@ def valid(x):
raise NotImplementedError('sorting of these roots is not supported')
for x in reals:
end = x
+
+ if ((end is S.NegativeInfinity and expr.rel_op in ['>', '>=']) or
+ (end is S.Infinity and expr.rel_op in ['<', '<='])):
+ sol_sets.append(Interval(start, S.Infinity, True, True))
+ break
+
if valid((start + end)/2 if start != S.NegativeInfinity else end - 1):
sol_sets.append(Interval(start, end, True, True))
diff --git a/sympy/tensor/tensor.py b/sympy/tensor/tensor.py
index b28aa45651..70bbc2b256 100644
--- a/sympy/tensor/tensor.py
+++ b/sympy/tensor/tensor.py
@@ -49,7 +49,7 @@
class TIDS(CantSympify):
"""
- Tensor-index data structure. This contains internal data structures about
+ Tensor internal data structure. This contains internal data structures about
components of a tensor expression, its free and dummy indices.
To create a ``TIDS`` object via the standard constructor, the required
@@ -107,22 +107,6 @@ def __init__(self, components, free, dum):
self.free = free
self.dum = dum
self._ext_rank = len(self.free) + 2*len(self.dum)
- self.dum.sort(key=lambda x: (x[2], x[0]))
-
- def get_tensors(self):
- """
- Get a list of ``Tensor`` objects having the same ``TIDS`` if multiplied
- by one another.
- """
- indices = self.get_indices()
- components = self.components
- tensors = [None for i in components] # pre-allocate list
- ind_pos = 0
- for i, component in enumerate(components):
- prev_pos = ind_pos
- ind_pos += component.rank
- tensors[i] = Tensor(component, indices[prev_pos:ind_pos])
- return tensors
def get_components_with_free_indices(self):
"""
@@ -220,9 +204,28 @@ def from_components_and_indices(components, indices):
return tids
- @deprecated(useinstead="get_indices")
def to_indices(self):
- return self.get_indices()
+ """
+ Get a list of indices, creating new tensor indices to complete dummy indices.
+ """
+ component_indices = []
+ for i in self.components:
+ component_indices.append([None]*i.rank)
+
+ for i in self.free:
+ component_indices[i[2]][i[1]] = i[0]
+
+ for i, dummy_pos in enumerate(self.dum):
+ tensor_index_type = self.components[dummy_pos[2]].args[1].args[0][0]
+ dummy_index = TensorIndex('dummy_index_{0}'.format(i), tensor_index_type)
+ component_indices[dummy_pos[2]][dummy_pos[0]] = dummy_index
+ component_indices[dummy_pos[3]][dummy_pos[1]] = -dummy_index
+
+ indices = []
+ for i in component_indices:
+ indices.extend(i)
+
+ return indices
@staticmethod
def free_dum_from_indices(*indices):
@@ -283,59 +286,6 @@ def free_dum_from_indices(*indices):
free.sort()
return free, dum
- @staticmethod
- def _check_matrix_indices(f_free, g_free, nc1):
- # This "private" method checks matrix indices.
- # Matrix indices are special as there are only two, and observe
- # anomalous substitution rules to determine contractions.
-
- dum = []
- # make sure that free indices appear in the same order as in their component:
- f_free.sort(key=lambda x: (x[2], x[1]))
- g_free.sort(key=lambda x: (x[2], x[1]))
- matrix_indices_storage = {}
- transform_right_to_left = {}
- f_pop_pos = []
- g_pop_pos = []
- for free_pos, (ind, i, c) in enumerate(f_free):
- index_type = ind._tensortype
- if ind not in (index_type.auto_left, -index_type.auto_right):
- continue
- matrix_indices_storage[ind] = (free_pos, i, c)
-
- for free_pos, (ind, i, c) in enumerate(g_free):
- index_type = ind._tensortype
- if ind not in (index_type.auto_left, -index_type.auto_right):
- continue
-
- if ind == index_type.auto_left:
- if -index_type.auto_right in matrix_indices_storage:
- other_pos, other_i, other_c = matrix_indices_storage.pop(-index_type.auto_right)
- dum.append((other_i, i, other_c, c + nc1))
- # mark to remove other_pos and free_pos from free:
- g_pop_pos.append(free_pos)
- f_pop_pos.append(other_pos)
- continue
- if ind in matrix_indices_storage:
- other_pos, other_i, other_c = matrix_indices_storage.pop(ind)
- dum.append((other_i, i, other_c, c + nc1))
- # mark to remove other_pos and free_pos from free:
- g_pop_pos.append(free_pos)
- f_pop_pos.append(other_pos)
- transform_right_to_left[-index_type.auto_right] = c
- continue
-
- if ind in transform_right_to_left:
- other_c = transform_right_to_left.pop(ind)
- if c == other_c:
- g_free[free_pos] = (index_type.auto_left, i, c)
-
- for i in reversed(sorted(f_pop_pos)):
- f_free.pop(i)
- for i in reversed(sorted(g_pop_pos)):
- g_free.pop(i)
- return dum
-
@staticmethod
def mul(f, g):
"""
@@ -379,24 +329,18 @@ def mul(f, g):
"""
index_up = lambda u: u if u.is_up else -u
- # lambda returns True is index is not a matrix index:
- notmat = lambda i: i not in (i._tensortype.auto_left, -i._tensortype.auto_right)
- f_free = f.free[:]
- g_free = g.free[:]
- nc1 = len(f.components)
- dum = TIDS._check_matrix_indices(f_free, g_free, nc1)
-
# find out which free indices of f and g are contracted
- free_dict1 = dict([(i if i.is_up else -i, (pos, cpos, i)) for i, pos, cpos in f_free])
- free_dict2 = dict([(i if i.is_up else -i, (pos, cpos, i)) for i, pos, cpos in g_free])
+ free_dict1 = dict([(i if i.is_up else -i, (pos, cpos, i)) for i, pos, cpos in f.free])
+ free_dict2 = dict([(i if i.is_up else -i, (pos, cpos, i)) for i, pos, cpos in g.free])
+
free_names = set(free_dict1.keys()) & set(free_dict2.keys())
# find the new `free` and `dum`
-
+ nc1 = len(f.components)
dum2 = [(i1, i2, c1 + nc1, c2 + nc1) for i1, i2, c1, c2 in g.dum]
- free1 = [(ind, i, c) for ind, i, c in f_free if index_up(ind) not in free_names]
- free2 = [(ind, i, c + nc1) for ind, i, c in g_free if index_up(ind) not in free_names]
+ free1 = [(ind, i, c) for ind, i, c in f.free if index_up(ind) not in free_names]
+ free2 = [(ind, i, c + nc1) for ind, i, c in g.free if index_up(ind) not in free_names]
free = free1 + free2
- dum.extend(f.dum + dum2)
+ dum = f.dum + dum2
for name in free_names:
ipos1, cpos1, ind1 = free_dict1[name]
ipos2, cpos2, ind2 = free_dict2[name]
@@ -452,14 +396,6 @@ def sorted_components(self):
return TIDS(components, free, dum), sign
- def _get_sorted_free_indices_for_canon(self):
- sorted_free = self.free[:]
- sorted_free.sort(key=lambda x: x[0])
- return sorted_free
-
- def _get_sorted_dum_indices_for_canon(self):
- return sorted(self.dum, key=lambda x: (x[2], x[0]))
-
def canon_args(self):
"""
Returns ``(g, dummies, msym, v)``, the entries of ``canonicalize``
@@ -482,7 +418,7 @@ def canon_args(self):
# then the dummy indices, ordered by types and contravariant before
# covariant
# g[position in tensor] = position in ordered indices
- for i, (indx, ipos, cpos) in enumerate(self._get_sorted_free_indices_for_canon()):
+ for i, (indx, ipos, cpos) in enumerate(self.free):
pos = vpos[cpos] + ipos
g[pos] = i
pos = len(self.free)
@@ -491,7 +427,7 @@ def canon_args(self):
prev = None
a = []
msym = []
- for ipos1, ipos2, cpos1, cpos2 in self._get_sorted_dum_indices_for_canon():
+ for ipos1, ipos2, cpos1, cpos2 in self.dum:
pos1 = vpos[cpos1] + ipos1
pos2 = vpos[cpos2] + ipos2
g[pos1] = j
@@ -542,7 +478,8 @@ def perm2tensor(self, g, canon_bp=False):
for t in components:
vpos.append(pos)
pos += t._rank
- sorted_free = [i[0] for i in self._get_sorted_free_indices_for_canon()]
+ sorted_free = [x[0] for x in self.free]
+ sorted_free.sort()
nfree = len(sorted_free)
rank = self._ext_rank
dum = [[None]*4 for i in range((rank - nfree)//2)]
@@ -570,175 +507,6 @@ def perm2tensor(self, g, canon_bp=False):
return TIDS(components, free, dum)
- def get_indices(self):
- """
- Get a list of indices, creating new tensor indices to complete dummy indices.
- """
- components = self.components
- free = self.free
- dum = self.dum
- indices = [None]*self._ext_rank
- start = 0
- pos = 0
- vpos = []
- for t in components:
- vpos.append(pos)
- pos += t.rank
- cdt = defaultdict(int)
- # if the free indices have names with dummy_fmt, start with an
- # index higher than those for the dummy indices
- # to avoid name collisions
- for indx, ipos, cpos in free:
- if indx._name.split('_')[0] == indx._tensortype._dummy_fmt[:-3]:
- cdt[indx._tensortype] = max(cdt[indx._tensortype], int(indx._name.split('_')[1]) + 1)
- start = vpos[cpos]
- indices[start + ipos] = indx
- for ipos1, ipos2, cpos1, cpos2 in dum:
- start1 = vpos[cpos1]
- start2 = vpos[cpos2]
- typ1 = components[cpos1].index_types[ipos1]
- assert typ1 == components[cpos2].index_types[ipos2]
- fmt = typ1._dummy_fmt
- nd = cdt[typ1]
- indices[start1 + ipos1] = TensorIndex(fmt % nd, typ1)
- indices[start2 + ipos2] = TensorIndex(fmt % nd, typ1, False)
- cdt[typ1] += 1
- return indices
-
- def contract_metric(self, g):
- """
- Returns new TIDS and sign.
-
- Sign is either 1 or -1, to correct the sign after metric contraction
- (for spinor indices).
- """
- components = self.components
- antisym = g.index_types[0].metric_antisym
- #if not any(x == g for x in components):
- # return self
- # list of positions of the metric ``g``
- gpos = [i for i, x in enumerate(components) if x == g]
- if not gpos:
- return self, 1
- sign = 1
- dum = self.dum[:]
- free = self.free[:]
- elim = set()
- for gposx in gpos:
- if gposx in elim:
- continue
- free1 = [x for x in free if x[-1] == gposx]
- dum1 = [x for x in dum if x[-2] == gposx or x[-1] == gposx]
- if not dum1:
- continue
- elim.add(gposx)
- if len(dum1) == 2:
- if not antisym:
- dum10, dum11 = dum1
- if dum10[3] == gposx:
- # the index with pos p0 and component c0 is contravariant
- c0 = dum10[2]
- p0 = dum10[0]
- else:
- # the index with pos p0 and component c0 is covariant
- c0 = dum10[3]
- p0 = dum10[1]
- if dum11[3] == gposx:
- # the index with pos p1 and component c1 is contravariant
- c1 = dum11[2]
- p1 = dum11[0]
- else:
- # the index with pos p1 and component c1 is covariant
- c1 = dum11[3]
- p1 = dum11[1]
- dum.append((p0, p1, c0, c1))
- else:
- dum10, dum11 = dum1
- # change the sign to bring the indices of the metric to contravariant
- # form; change the sign if dum10 has the metric index in position 0
- if dum10[3] == gposx:
- # the index with pos p0 and component c0 is contravariant
- c0 = dum10[2]
- p0 = dum10[0]
- if dum10[1] == 1:
- sign = -sign
- else:
- # the index with pos p0 and component c0 is covariant
- c0 = dum10[3]
- p0 = dum10[1]
- if dum10[0] == 0:
- sign = -sign
- if dum11[3] == gposx:
- # the index with pos p1 and component c1 is contravariant
- c1 = dum11[2]
- p1 = dum11[0]
- sign = -sign
- else:
- # the index with pos p1 and component c1 is covariant
- c1 = dum11[3]
- p1 = dum11[1]
- dum.append((p0, p1, c0, c1))
-
- elif len(dum1) == 1:
- if not antisym:
- dp0, dp1, dc0, dc1 = dum1[0]
- if dc0 == dc1:
- # g(i, -i)
- typ = g.index_types[0]
- if typ._dim is None:
- raise ValueError('dimension not assigned')
- sign = sign*typ._dim
-
- else:
- # g(i0, i1)*p(-i1)
- if dc0 == gposx:
- p1 = dp1
- c1 = dc1
- else:
- p1 = dp0
- c1 = dc0
- ind, p, c = free1[0]
- free.append((ind, p1, c1))
- else:
- dp0, dp1, dc0, dc1 = dum1[0]
- if dc0 == dc1:
- # g(i, -i)
- typ = g.index_types[0]
- if typ._dim is None:
- raise ValueError('dimension not assigned')
- sign = sign*typ._dim
-
- if dp0 < dp1:
- # g(i, -i) = -D with antisymmetric metric
- sign = -sign
- else:
- # g(i0, i1)*p(-i1)
- if dc0 == gposx:
- p1 = dp1
- c1 = dc1
- if dp0 == 0:
- sign = -sign
- else:
- p1 = dp0
- c1 = dc0
- ind, p, c = free1[0]
- free.append((ind, p1, c1))
- dum = [x for x in dum if x not in dum1]
- free = [x for x in free if x not in free1]
-
- shift = 0
- shifts = [0]*len(components)
- for i in range(len(components)):
- if i in elim:
- shift += 1
- continue
- shifts[i] = shift
- free = [(ind, p, c - shifts[c]) for (ind, p, c) in free if c not in elim]
- dum = [(p0, p1, c0 - shifts[c0], c1 - shifts[c1]) for i, (p0, p1, c0, c1) in enumerate(dum) if c0 not in elim and c1 not in elim]
- components = [c for i, c in enumerate(components) if i not in elim]
- tids = TIDS(components, free, dum)
- return tids, sign
-
class VTIDS(TIDS):
"""
@@ -826,16 +594,6 @@ def _get(self, key):
if isinstance(key, TensorHead):
return None
- if isinstance(key, Tensor):
- # special case to handle metrics. Metric tensors cannot be
- # constructed through contraction by the metric, their
- # components show if they are a matrix or its inverse.
- signature = tuple([i.is_up for i in key.get_indices()])
- srch = (key.component,) + signature
- if srch in self._substitutions_dict_tensmul:
- return self._substitutions_dict_tensmul[srch]
- return self.data_tensmul_from_tensorhead(key, key.component)
-
if isinstance(key, TensMul):
tensmul_list = key.split()
if len(tensmul_list) == 1 and len(tensmul_list[0].components) == 1:
@@ -1676,7 +1434,6 @@ def __neg__(self):
(not self._is_up))
return t1
-
def tensor_indices(s, typ):
"""
Returns list of tensor indices given their names and their types
@@ -2227,7 +1984,7 @@ def _check_auto_matrix_indices_in_call(self, *indices):
if not self._matrix_behavior:
raise ValueError('wrong number of indices')
- # Take the last one or two missing
+ # _matrix_behavior is True, so take the last one or two missing
# indices as auto-matrix indices:
ldiff = len(self.index_types) - len(indices)
if ldiff > 2:
@@ -2265,7 +2022,7 @@ def _check_auto_matrix_indices_in_call(self, *indices):
return indices, matrix_behavior_kinds
- def __call__(self, *indices, **kw_args):
+ def __call__(self, *indices):
"""
Returns a tensor with indices.
@@ -2314,7 +2071,7 @@ def __call__(self, *indices, **kw_args):
Auto-matrix indices are automatically contracted upon multiplication,
>>> r*s
- A(auto_left, L_0)*B(-L_0, -auto_right, auto_left, -auto_right)
+ A(auto_left, -L_0)*B(L_0, -auto_right, auto_left, -auto_right)
The multiplication algorithm has found an ``auto_right`` index in ``A``
and an ``auto_left`` index in ``B`` referring to the same
@@ -2340,8 +2097,14 @@ def __call__(self, *indices, **kw_args):
"""
indices, matrix_behavior_kinds = self._check_auto_matrix_indices_in_call(*indices)
- tensor = Tensor._new_with_dummy_replacement(self, indices, **kw_args)
- return tensor
+
+ components = [self]
+ tids = TIDS.from_components_and_indices(components, indices)
+
+ tmul = TensMul.from_TIDS(S.One, tids)
+ tmul._matrix_behavior_kinds = matrix_behavior_kinds
+
+ return tmul
def __pow__(self, other):
if self.data is None:
@@ -2613,26 +2376,20 @@ def __new__(cls, *args, **kw_args):
if not args:
return S.Zero
- if len(args) == 1 and not isinstance(args[0], TensExpr):
- return args[0]
-
# replace auto-matrix indices so that they are the same in all addends
args = TensAdd._tensAdd_check_automatrix(args)
# now check that all addends have the same indices:
TensAdd._tensAdd_check(args)
+ args = Tuple(*args)
# if TensAdd has only 1 TensMul element in its `args`:
if len(args) == 1 and isinstance(args[0], TensMul):
obj = Basic.__new__(cls, *args, **kw_args)
return obj
- # TODO: do not or do canonicalize by default?
- # Technically, one may wish to have additions of non-canonicalized
- # tensors. This feature should be removed in the future.
- # Unfortunately this would require to rewrite a lot of tests.
# canonicalize all TensMul
- args = [canon_bp(x) for x in args if x]
+ args = [x.canon_bp() for x in args if x]
args = [x for x in args if x]
# if there are no more args (i.e. have cancelled out),
@@ -2640,22 +2397,18 @@ def __new__(cls, *args, **kw_args):
if not args:
return S.Zero
- if len(args) == 1:
- return args[0]
-
# collect canonicalized terms
- def sort_key(t):
- x = get_tids(t)
- return (x.components, x.free, x.dum)
- args.sort(key=sort_key)
- args = TensAdd._tensAdd_collect_terms(args)
- if not args:
+ args.sort(key=lambda x: (x.components, x.free, x.dum))
+ a = TensAdd._tensAdd_collect_terms(args)
+ if not a:
return S.Zero
# it there is only a component tensor return it
- if len(args) == 1:
- return args[0]
+ if len(a) == 1:
+ return a[0]
+ args = Tuple(*args)
obj = Basic.__new__(cls, *args, **kw_args)
+ obj._args = tuple(a)
return obj
@staticmethod
@@ -2670,7 +2423,7 @@ def _tensAdd_flatten(args):
args1.extend(list(x.args))
else:
args1.append(x)
- args1 = [x for x in args1 if isinstance(x, TensExpr) and x.coeff]
+ args1 = [x for x in args1 if isinstance(x, TensExpr) and x._coeff]
args2 = [x for x in args if not isinstance(x, TensExpr)]
t1 = TensMul.from_data(Add(*args2), [], [], [])
args = [t1] + args1
@@ -2680,7 +2433,7 @@ def _tensAdd_flatten(args):
a.extend(list(x.args))
else:
a.append(x)
- args = [x for x in a if x.coeff]
+ args = [x for x in a if x._coeff]
return args
@staticmethod
@@ -2699,7 +2452,7 @@ def _tensAdd_check_automatrix(args):
for i, arg in enumerate(args):
arg_auto_left_types = set([])
arg_auto_right_types = set([])
- for index in get_indices(arg):
+ for index in arg.get_indices():
# @type index: TensorIndex
if index in (index._tensortype.auto_left, -index._tensortype.auto_left):
auto_left_types.add(index._tensortype)
@@ -2723,8 +2476,8 @@ def _tensAdd_check_automatrix(args):
@staticmethod
def _tensAdd_check(args):
# check that all addends have the same free indices
- indices0 = set([x[0] for x in get_tids(args[0]).free])
- list_indices = [set([y[0] for y in get_tids(x).free]) for x in args[1:]]
+ indices0 = set([x[0] for x in args[0].free])
+ list_indices = [set([y[0] for y in x.free]) for x in args[1:]]
if not all(x == indices0 for x in list_indices):
raise ValueError('all tensors must have the same indices')
@@ -2733,16 +2486,14 @@ def _tensAdd_collect_terms(args):
# collect TensMul terms differing at most by their coefficient
a = []
prev = args[0]
- prev_coeff = get_coeff(prev)
+ prev_coeff = prev._coeff
changed = False
for x in args[1:]:
# if x and prev have the same tensor, update the coeff of prev
- x_tids = get_tids(x)
- prev_tids = get_tids(prev)
- if x_tids.components == prev_tids.components \
- and x_tids.free == prev_tids.free and x_tids.dum == prev_tids.dum:
- prev_coeff = prev_coeff + get_coeff(x)
+ if x.components == prev.components \
+ and x.free == prev.free and x.dum == prev.dum:
+ prev_coeff = prev_coeff + x._coeff
changed = True
op = 0
else:
@@ -2753,18 +2504,18 @@ def _tensAdd_collect_terms(args):
else:
# get a tensor from prev with coeff=prev_coeff and store it
if prev_coeff:
- t = TensMul.from_data(prev_coeff, prev_tids.components,
- prev_tids.free, prev_tids.dum)
+ t = TensMul.from_data(prev_coeff, prev.components,
+ prev.free, prev.dum)
a.append(t)
# move x to prev
op = 1
pprev, prev = prev, x
- pprev_coeff, prev_coeff = prev_coeff, get_coeff(x)
+ pprev_coeff, prev_coeff = prev_coeff, x._coeff
changed = False
# if the case op=0 prev was not stored; store it now
# in the case op=1 x was not stored; store it now (as prev)
if op == 0 and prev_coeff:
- prev = TensMul.from_data(prev_coeff, prev_tids.components, prev_tids.free, prev_tids.dum)
+ prev = TensMul.from_data(prev_coeff, prev.components, prev.free, prev.dum)
a.append(prev)
elif op == 1:
a.append(prev)
@@ -2809,7 +2560,7 @@ def __call__(self, *indices):
if indices == free_args:
return self
index_tuples = list(zip(free_args, indices))
- a = [x.func(*x.fun_eval(*index_tuples).args) for x in self.args]
+ a = [TensMul(*x.fun_eval(*index_tuples).args) for x in self.args]
res = TensAdd(*a)
return res
@@ -2899,7 +2650,7 @@ def contract_metric(self, g):
see the ``TensorIndexType`` docstring for the contraction conventions
"""
- args = [contract_metric(x, g) for x in self.args]
+ args = [x.contract_metric(g) for x in self.args]
t = TensAdd(*args)
return canon_bp(t)
@@ -3024,369 +2775,98 @@ def __iter__(self):
@doctest_depends_on(modules=('numpy',))
-class Tensor(TensExpr):
+class TensMul(TensExpr):
"""
- Base tensor class, i.e. this represents a tensor, the single unit to be
- put into an expression.
+ Product of tensors
- This object is usually created from a ``TensorHead``, by attaching indices
- to it. Indices preceded by a minus sign are considered contravariant,
- otherwise covariant.
+ Parameters
+ ==========
- Examples
- ========
+ coeff : SymPy coefficient of the tensor
+ args
- >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensorhead
- >>> Lorentz = TensorIndexType("Lorentz", dummy_fmt="L")
- >>> mu, nu = tensor_indices('mu nu', Lorentz)
- >>> A = tensorhead("A", [Lorentz, Lorentz], [[1], [1]])
- >>> A(mu, -nu)
- A(mu, -nu)
- >>> A(mu, -mu)
- A(L_0, -L_0)
+ Attributes
+ ==========
+
+ ``components`` : list of ``TensorHead`` of the component tensors
+ ``types`` : list of nonrepeated ``TensorIndexType``
+ ``free`` : list of ``(ind, ipos, icomp)``, see Notes
+ ``dum`` : list of ``(ipos1, ipos2, icomp1, icomp2)``, see Notes
+ ``ext_rank`` : rank of the tensor counting the dummy indices
+ ``rank`` : rank of the tensor
+ ``coeff`` : SymPy coefficient of the tensor
+ ``free_args`` : list of the free indices in sorted order
+ ``is_canon_bp`` : ``True`` if the tensor in in canonical form
+
+ Notes
+ =====
+
+ ``args[0]`` list of ``TensorHead`` of the component tensors.
+
+ ``args[1]`` list of ``(ind, ipos, icomp)``
+ where ``ind`` is a free index, ``ipos`` is the slot position
+ of ``ind`` in the ``icomp``-th component tensor.
+
+ ``args[2]`` list of tuples representing dummy indices.
+ ``(ipos1, ipos2, icomp1, icomp2)`` indicates that the contravariant
+ dummy index is the ``ipos1``-th slot position in the ``icomp1``-th
+ component tensor; the corresponding covariant index is
+ in the ``ipos2`` slot position in the ``icomp2``-th component tensor.
"""
- is_commutative = False
+ def __new__(cls, coeff, *args, **kw_args):
+ coeff = sympify(coeff)
+
+ if len(args) == 2:
+ components = args[0]
+ indices = args[1]
+ tids = TIDS.from_components_and_indices(components, indices)
+ elif len(args) == 1:
+ tids = args[0]
+ components = tids.components
+ indices = tids.to_indices()
+ else:
+ raise TypeError("wrong construction")
- def __new__(cls, tensor_head, indices, **kw_args):
- tids = TIDS.from_components_and_indices((tensor_head,), indices)
- obj = Basic.__new__(cls, tensor_head, Tuple(*indices), **kw_args)
+ for i in indices:
+ if not isinstance(i, TensorIndex):
+ raise TypeError("i should be of type TensorIndex")
+
+ t_components = Tuple(*components)
+ t_indices = Tuple(*indices)
+
+ obj = Basic.__new__(cls, coeff, t_components, t_indices)
+ obj._types = []
+ for t in tids.components:
+ obj._types.extend(t._types)
obj._tids = tids
- obj._indices = indices
+ obj._ext_rank = len(obj._tids.free) + 2*len(obj._tids.dum)
+ obj._coeff = coeff
obj._is_canon_bp = kw_args.get('is_canon_bp', False)
+ obj._matrix_behavior_kinds = dict()
return obj
@staticmethod
- def _new_with_dummy_replacement(tensor_head, indices, **kw_args):
- tids = TIDS.from_components_and_indices((tensor_head,), indices)
- indices = tids.get_indices()
- return Tensor(tensor_head, indices, **kw_args)
+ def from_data(coeff, components, free, dum, **kw_args):
+ tids = TIDS(components, free, dum)
+ return TensMul.from_TIDS(coeff, tids, **kw_args)
+
+ @staticmethod
+ def from_TIDS(coeff, tids, **kw_args):
+ return TensMul(coeff, tids, **kw_args)
@property
- def is_canon_bp(self):
- return self._is_canon_bp
+ def free_args(self):
+ return sorted([x[0] for x in self.free])
@property
- def indices(self):
- return self._indices
+ def components(self):
+ return self._tids.components[:]
@property
def free(self):
- return self._tids.free
-
- @property
- def dum(self):
- return self._tids.dum
-
- @property
- def rank(self):
- return len(self.free)
-
- @property
- def free_args(self):
- return sorted([x[0] for x in self.free])
-
- def perm2tensor(self, g, canon_bp=False):
- """
- Returns the tensor corresponding to the permutation ``g``
-
- For further details, see the method in ``TIDS`` with the same name.
- """
- return perm2tensor(self, g, canon_bp)
-
- def canon_bp(self):
- if self._is_canon_bp:
- return self
- g, dummies, msym, v = self._tids.canon_args()
- can = canonicalize(g, dummies, msym, *v)
- if can == 0:
- return S.Zero
- tensor = self.perm2tensor(can, True)
- return tensor
-
- @property
- def types(self):
- return get_tids(self).components[0]._types
-
- @property
- def coeff(self):
- return S.One
-
- @property
- def component(self):
- return self.args[0]
-
- @property
- def components(self):
- return [self.args[0]]
-
- def split(self):
- return [self]
-
- def expand(self):
- return self
-
- def sorted_components(self):
- return self
-
- def get_indices(self):
- """
- Get a list of indices, corresponding to those of the tensor.
- """
- return self._tids.get_indices()
-
- def as_base_exp(self):
- return self, S.One
-
- def substitute_indices(self, *index_tuples):
- return substitute_indices(self, *index_tuples)
-
- def __call__(self, *indices):
- """Returns tensor with ordered free indices replaced by ``indices``
-
- Examples
- ========
-
- >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensorhead
- >>> Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
- >>> i0,i1,i2,i3,i4 = tensor_indices('i0:5', Lorentz)
- >>> A = tensorhead('A', [Lorentz]*5, [[1]*5])
- >>> t = A(i2, i1, -i2, -i3, i4)
- >>> t
- A(L_0, i1, -L_0, -i3, i4)
- >>> t(i1, i2, i3)
- A(L_0, i1, -L_0, i2, i3)
- """
-
- free_args = self.free_args
- indices = list(indices)
- if [x._tensortype for x in indices] != [x._tensortype for x in free_args]:
- raise ValueError('incompatible types')
- if indices == free_args:
- return self
- t = self.fun_eval(*list(zip(free_args, indices)))
-
- # object is rebuilt in order to make sure that all contracted indices
- # get recognized as dummies, but only if there are contracted indices.
- if len(set(i if i.is_up else -i for i in indices)) != len(indices):
- return t.func(*t.args)
- return t
-
- def fun_eval(self, *index_tuples):
- free = self.free
- free1 = []
- for j, ipos, cpos in free:
- # search j in index_tuples
- for i, v in index_tuples:
- if i == j:
- free1.append((v, ipos, cpos))
- break
- else:
- free1.append((j, ipos, cpos))
- return TensMul.from_data(self.coeff, self.components, free1, self.dum)
-
- # TODO: put this into TensExpr?
- def __iter__(self):
- return self.data.flatten().__iter__()
-
- # TODO: put this into TensExpr?
- def __getitem__(self, item):
- return self.data[item]
-
- @property
- def data(self):
- return _tensor_data_substitution_dict[self]
-
- @data.setter
- def data(self, data):
- # TODO: check data compatibility with properties of tensor.
- _tensor_data_substitution_dict[self] = data
-
- @data.deleter
- def data(self):
- if self in _tensor_data_substitution_dict:
- del _tensor_data_substitution_dict[self]
- if self.metric in _tensor_data_substitution_dict:
- del _tensor_data_substitution_dict[self.metric]
-
- def __mul__(self, other):
- if isinstance(other, TensAdd):
- return TensAdd(*[self*arg for arg in other.args])
- tmul = TensMul(self, other)
- return tmul
-
- def __rmul__(self, other):
- return TensMul(other, self)
-
- def __div__(self, other):
- if isinstance(other, TensExpr):
- raise ValueError('cannot divide by a tensor')
- return TensMul(self, S.One/other, is_canon_bp=self.is_canon_bp)
-
- def __rdiv__(self, other):
- raise ValueError('cannot divide by a tensor')
-
- def __add__(self, other):
- return TensAdd(self, other)
-
- def __radd__(self, other):
- return TensAdd(other, self)
-
- def __sub__(self, other):
- return TensAdd(self, -other)
-
- def __rsub__(self, other):
- return TensAdd(other, self)
-
- __truediv__ = __div__
- __rtruediv__ = __rdiv__
-
- def __neg__(self):
- return TensMul(S.NegativeOne, self)
-
- def _print(self):
- indices = [str(ind) for ind in self.indices]
- component = self.component
- if component.rank > 0:
- return ('%s(%s)' % (component.name, ', '.join(indices)))
- else:
- return ('%s' % component.name)
-
- def equals(self, other):
- if other == 0:
- return self.coeff == 0
- other = sympify(other)
- if not isinstance(other, TensExpr):
- assert not self.components
- return S.One == other
-
- def _get_compar_comp(self):
- t = self.canon_bp()
- r = (t.coeff, tuple(t.components), \
- tuple(sorted(t.free)), tuple(sorted(t.dum)))
- return r
-
- return _get_compar_comp(self) == _get_compar_comp(other)
-
- def contract_metric(self, metric):
- tids, sign = get_tids(self).contract_metric(metric)
- return TensMul.from_TIDS(sign, tids)
-
- def contract_delta(self, metric):
- return self.contract_metric(metric)
-
-
-@doctest_depends_on(modules=('numpy',))
-class TensMul(TensExpr):
- """
- Product of tensors
-
- Parameters
- ==========
-
- coeff : SymPy coefficient of the tensor
- args
-
- Attributes
- ==========
-
- ``components`` : list of ``TensorHead`` of the component tensors
- ``types`` : list of nonrepeated ``TensorIndexType``
- ``free`` : list of ``(ind, ipos, icomp)``, see Notes
- ``dum`` : list of ``(ipos1, ipos2, icomp1, icomp2)``, see Notes
- ``ext_rank`` : rank of the tensor counting the dummy indices
- ``rank`` : rank of the tensor
- ``coeff`` : SymPy coefficient of the tensor
- ``free_args`` : list of the free indices in sorted order
- ``is_canon_bp`` : ``True`` if the tensor in in canonical form
-
- Notes
- =====
-
- ``args[0]`` list of ``TensorHead`` of the component tensors.
-
- ``args[1]`` list of ``(ind, ipos, icomp)``
- where ``ind`` is a free index, ``ipos`` is the slot position
- of ``ind`` in the ``icomp``-th component tensor.
-
- ``args[2]`` list of tuples representing dummy indices.
- ``(ipos1, ipos2, icomp1, icomp2)`` indicates that the contravariant
- dummy index is the ``ipos1``-th slot position in the ``icomp1``-th
- component tensor; the corresponding covariant index is
- in the ``ipos2`` slot position in the ``icomp2``-th component tensor.
-
- """
-
- def __new__(cls, *args, **kw_args):
- # make sure everything is sympified:
- args = [sympify(arg) for arg in args]
-
- # flatten:
- args = TensMul._flatten(args)
-
- is_canon_bp = kw_args.get('is_canon_bp', False)
- if not any([isinstance(arg, TensExpr) for arg in args]):
- tids = TIDS([], [], [])
- else:
- tids_list = [arg._tids for arg in args if isinstance(arg, (Tensor, TensMul))]
- if len(tids_list) == 1:
- for arg in args:
- if not isinstance(arg, Tensor):
- continue
- is_canon_bp = kw_args.get('is_canon_bp', arg._is_canon_bp)
- tids = functools.reduce(lambda a, b: a*b, tids_list)
-
- if any([isinstance(arg, TensAdd) for arg in args]):
- add_args = TensAdd._tensAdd_flatten(args)
- return TensAdd(*add_args)
- coeff = functools.reduce(lambda a, b: a*b, [S.One] + [arg for arg in args if not isinstance(arg, TensExpr)])
- args = tids.get_tensors()
- if coeff != 1:
- args = [coeff] + args
- if len(args) == 1:
- return args[0]
-
- obj = Basic.__new__(cls, *args)
- obj._types = []
- for t in tids.components:
- obj._types.extend(t._types)
- obj._tids = tids
- obj._ext_rank = len(obj._tids.free) + 2*len(obj._tids.dum)
- obj._coeff = coeff
- obj._is_canon_bp = is_canon_bp
- return obj
-
- @staticmethod
- def _flatten(args):
- a = []
- for arg in args:
- if isinstance(arg, TensMul):
- a.extend(arg.args)
- else:
- a.append(arg)
- return a
-
- @staticmethod
- def from_data(coeff, components, free, dum, **kw_args):
- tids = TIDS(components, free, dum)
- return TensMul.from_TIDS(coeff, tids, **kw_args)
-
- @staticmethod
- def from_TIDS(coeff, tids, **kw_args):
- return TensMul(coeff, *tids.get_tensors(), **kw_args)
-
- @property
- def free_args(self):
- return sorted([x[0] for x in self.free])
-
- @property
- def components(self):
- return self._tids.components[:]
-
- @property
- def free(self):
- return self._tids.free[:]
+ return self._tids.free[:]
@property
def coeff(self):
@@ -3414,7 +2894,7 @@ def equals(self, other):
def _get_compar_comp(self):
t = self.canon_bp()
- r = (get_coeff(t), tuple(t.components), \
+ r = (t._coeff, tuple(t.components), \
tuple(sorted(t.free)), tuple(sorted(t.dum)))
return r
@@ -3441,7 +2921,34 @@ def get_indices(self):
>>> t.get_indices()
[m1, m0, m2]
"""
- return self._tids.get_indices()
+ indices = [None]*self._ext_rank
+ start = 0
+ pos = 0
+ vpos = []
+ components = self.components
+ for t in components:
+ vpos.append(pos)
+ pos += t._rank
+ cdt = defaultdict(int)
+ # if the free indices have names with dummy_fmt, start with an
+ # index higher than those for the dummy indices
+ # to avoid name collisions
+ for indx, ipos, cpos in self.free:
+ if indx._name.split('_')[0] == indx._tensortype._dummy_fmt[:-3]:
+ cdt[indx._tensortype] = max(cdt[indx._tensortype], int(indx._name.split('_')[1]) + 1)
+ start = vpos[cpos]
+ indices[start + ipos] = indx
+ for ipos1, ipos2, cpos1, cpos2 in self.dum:
+ start1 = vpos[cpos1]
+ start2 = vpos[cpos2]
+ typ1 = components[cpos1].index_types[ipos1]
+ assert typ1 == components[cpos2].index_types[ipos2]
+ fmt = typ1._dummy_fmt
+ nd = cdt[typ1]
+ indices[start1 + ipos1] = TensorIndex(fmt % nd, typ1)
+ indices[start2 + ipos2] = TensorIndex(fmt % nd, typ1, False)
+ cdt[typ1] += 1
+ return indices
def split(self):
"""
@@ -3464,17 +2971,18 @@ def split(self):
>>> t.split()
[A(a, L_0), B(-L_0, c)]
"""
- if self.args == ():
- return [self]
- splitp = []
- res = 1
- for arg in self.args:
- if isinstance(arg, Tensor):
- splitp.append(res*arg)
- res = 1
- else:
- res *= arg
- return splitp
+ indices = self.get_indices()
+ pos = 0
+ components = self.components
+ if not components:
+ return [TensMul.from_data(self._coeff, [], [], [])]
+ res = []
+ for t in components:
+ t1 = t(*indices[pos:pos + t._rank])
+ pos += t._rank
+ res.append(t1)
+ res[0] = TensMul.from_data(self._coeff, res[0].components, res[0]._tids.free, res[0]._tids.dum, is_canon_bp=res[0]._is_canon_bp)
+ return res
def __add__(self, other):
return TensAdd(self, other)
@@ -3510,21 +3018,55 @@ def __mul__(self, other):
"""
other = sympify(other)
if not isinstance(other, TensExpr):
- coeff = self.coeff*other
+ coeff = self._coeff*other
tmul = TensMul.from_TIDS(coeff, self._tids, is_canon_bp=self._is_canon_bp)
+ tmul._matrix_behavior_kinds = self._matrix_behavior_kinds
return tmul
if isinstance(other, TensAdd):
return TensAdd(*[self*x for x in other.args])
- new_tids = self._tids*other._tids
- coeff = self.coeff*other.coeff
+ matrix_behavior_kinds = dict()
+
+ self_matrix_behavior_kinds = self._matrix_behavior_kinds
+ other_matrix_behavior_kinds = other._matrix_behavior_kinds
+ self2 = self
+
+ for key, v1 in self_matrix_behavior_kinds.items():
+ if key in other_matrix_behavior_kinds:
+ v2 = other_matrix_behavior_kinds[key]
+ if len(v1) == 1:
+ other = other.substitute_indices((v2[0], -v1[0]))
+ if len(v2) == 2:
+ matrix_behavior_kinds[key] = (v2[1],)
+ elif len(v1) == 2:
+ auto_index = v1[1]._tensortype.auto_index
+ self2 = self2.substitute_indices((v1[1], -auto_index))
+ other = other.substitute_indices((v2[0], auto_index))
+ if len(v2) == 1:
+ matrix_behavior_kinds[key] = (v1[0],)
+ elif len(v2) == 2:
+ matrix_behavior_kinds[key] = (v1[0], v2[1])
+ else:
+ matrix_behavior_kinds[key] = v1
+
+ for key, v2 in other_matrix_behavior_kinds.items():
+ if key in self_matrix_behavior_kinds:
+ continue
+ matrix_behavior_kinds[key] = v2
+
+ new_tids = self2._tids*other._tids
+ coeff = self2._coeff*other._coeff
tmul = TensMul.from_TIDS(coeff, new_tids)
+ if isinstance(tmul, TensExpr):
+ tmul._matrix_behavior_kinds = matrix_behavior_kinds
+
return tmul
def __rmul__(self, other):
other = sympify(other)
coeff = other*self._coeff
tmul = TensMul.from_TIDS(coeff, self._tids)
+ tmul._matrix_behavior_kinds = self._matrix_behavior_kinds
return tmul
def __div__(self, other):
@@ -3533,6 +3075,7 @@ def __div__(self, other):
raise ValueError('cannot divide by a tensor')
coeff = self._coeff/other
tmul = TensMul.from_TIDS(coeff, self._tids, is_canon_bp=self._is_canon_bp)
+ tmul._matrix_behavior_kinds = self._matrix_behavior_kinds
return tmul
def __rdiv__(self, other):
@@ -3550,7 +3093,7 @@ def sorted_components(self):
calling the corresponding method in a ``TIDS`` object.
"""
new_tids, sign = self._tids.sorted_components()
- coeff = -self.coeff if sign == -1 else self.coeff
+ coeff = -self._coeff if sign == -1 else self._coeff
t = TensMul.from_TIDS(coeff, new_tids)
return t
@@ -3560,7 +3103,13 @@ def perm2tensor(self, g, canon_bp=False):
For further details, see the method in ``TIDS`` with the same name.
"""
- return perm2tensor(self, g, canon_bp)
+ new_tids = self._tids.perm2tensor(g, canon_bp)
+ coeff = self._coeff
+ if g[-1] != len(g) - 1:
+ coeff = -coeff
+ res = TensMul.from_TIDS(coeff, new_tids, is_canon_bp=canon_bp)
+ res._matrix_behavior_kinds = self._matrix_behavior_kinds
+ return res
def canon_bp(self):
"""
@@ -3591,6 +3140,7 @@ def canon_bp(self):
if can == 0:
return S.Zero
tmul = t.perm2tensor(can, True)
+ tmul._matrix_behavior_kinds = self._matrix_behavior_kinds
return tmul
def contract_delta(self, delta):
@@ -3625,12 +3175,173 @@ def contract_metric(self, g):
>>> t.contract_metric(g).canon_bp()
p(L_0)*q(-L_0)
"""
- tids, sign = get_tids(self).contract_metric(g)
- res = TensMul.from_TIDS(sign*self.coeff, tids)
+ components = self.components
+ antisym = g.index_types[0].metric_antisym
+ #if not any(x == g for x in components):
+ # return self
+ # list of positions of the metric ``g``
+ gpos = [i for i, x in enumerate(components) if x == g]
+ if not gpos:
+ return self
+ coeff = self._coeff
+ tids = self._tids
+ dum = tids.dum[:]
+ free = tids.free[:]
+ elim = set()
+ for gposx in gpos:
+ if gposx in elim:
+ continue
+ free1 = [x for x in free if x[-1] == gposx]
+ dum1 = [x for x in dum if x[-2] == gposx or x[-1] == gposx]
+ if not dum1:
+ continue
+ elim.add(gposx)
+ if len(dum1) == 2:
+ if not antisym:
+ dum10, dum11 = dum1
+ if dum10[3] == gposx:
+ # the index with pos p0 and component c0 is contravariant
+ c0 = dum10[2]
+ p0 = dum10[0]
+ else:
+ # the index with pos p0 and component c0 is covariant
+ c0 = dum10[3]
+ p0 = dum10[1]
+ if dum11[3] == gposx:
+ # the index with pos p1 and component c1 is contravariant
+ c1 = dum11[2]
+ p1 = dum11[0]
+ else:
+ # the index with pos p1 and component c1 is covariant
+ c1 = dum11[3]
+ p1 = dum11[1]
+ dum.append((p0, p1, c0, c1))
+ else:
+ dum10, dum11 = dum1
+ # change the sign to bring the indices of the metric to contravariant
+ # form; change the sign if dum10 has the metric index in position 0
+ if dum10[3] == gposx:
+ # the index with pos p0 and component c0 is contravariant
+ c0 = dum10[2]
+ p0 = dum10[0]
+ if dum10[1] == 1:
+ coeff = -coeff
+ else:
+ # the index with pos p0 and component c0 is covariant
+ c0 = dum10[3]
+ p0 = dum10[1]
+ if dum10[0] == 0:
+ coeff = -coeff
+ if dum11[3] == gposx:
+ # the index with pos p1 and component c1 is contravariant
+ c1 = dum11[2]
+ p1 = dum11[0]
+ coeff = -coeff
+ else:
+ # the index with pos p1 and component c1 is covariant
+ c1 = dum11[3]
+ p1 = dum11[1]
+ dum.append((p0, p1, c0, c1))
+
+ elif len(dum1) == 1:
+ if not antisym:
+ dp0, dp1, dc0, dc1 = dum1[0]
+ if dc0 == dc1:
+ # g(i, -i)
+ typ = g.index_types[0]
+ if typ._dim is None:
+ raise ValueError('dimension not assigned')
+ coeff = coeff*typ._dim
+
+ else:
+ # g(i0, i1)*p(-i1)
+ if dc0 == gposx:
+ p1 = dp1
+ c1 = dc1
+ else:
+ p1 = dp0
+ c1 = dc0
+ ind, p, c = free1[0]
+ free.append((ind, p1, c1))
+ else:
+ dp0, dp1, dc0, dc1 = dum1[0]
+ if dc0 == dc1:
+ # g(i, -i)
+ typ = g.index_types[0]
+ if typ._dim is None:
+ raise ValueError('dimension not assigned')
+ coeff = coeff*typ._dim
+
+ if dp0 < dp1:
+ # g(i, -i) = -D with antisymmetric metric
+ coeff = -coeff
+ else:
+ # g(i0, i1)*p(-i1)
+ if dc0 == gposx:
+ p1 = dp1
+ c1 = dc1
+ if dp0 == 0:
+ coeff = -coeff
+ else:
+ p1 = dp0
+ c1 = dc0
+ ind, p, c = free1[0]
+ free.append((ind, p1, c1))
+ dum = [x for x in dum if x not in dum1]
+ free = [x for x in free if x not in free1]
+
+ shift = 0
+ shifts = [0]*len(components)
+ for i in range(len(components)):
+ if i in elim:
+ shift += 1
+ continue
+ shifts[i] = shift
+ free = [(ind, p, c - shifts[c]) for (ind, p, c) in free if c not in elim]
+ dum = [(p0, p1, c0 - shifts[c0], c1 - shifts[c1]) for i, (p0, p1, c0, c1) in enumerate(dum) if c0 not in elim and c1 not in elim]
+ components = [c for i, c in enumerate(components) if i not in elim]
+ tids = TIDS(components, free, dum)
+ res = TensMul.from_TIDS(coeff, tids)
return res
def substitute_indices(self, *index_tuples):
- return substitute_indices(self, *index_tuples)
+ """
+ Return a tensor with free indices substituted according to ``index_tuples``
+
+ ``index_types`` list of tuples ``(old_index, new_index)``
+
+ Note: this method will neither raise or lower the indices, it will just replace their symbol.
+
+ Examples
+ ========
+
+ >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensorhead
+ >>> Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
+ >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz)
+ >>> A, B = tensorhead('A,B', [Lorentz]*2, [[1]*2])
+ >>> t = A(i, k)*B(-k, -j); t
+ A(i, L_0)*B(-L_0, -j)
+ >>> t.substitute_indices((i,j), (j, k))
+ A(j, L_0)*B(-L_0, -k)
+ """
+ free = self.free
+ free1 = []
+ for j, ipos, cpos in free:
+ for i, v in index_tuples:
+ if i._name == j._name and i._tensortype == j._tensortype:
+ if i._is_up == j._is_up:
+ free1.append((v, ipos, cpos))
+ else:
+ free1.append((-v, ipos, cpos))
+ break
+ else:
+ free1.append((j, ipos, cpos))
+
+ t = TensMul.from_data(self._coeff, self.components, free1, self.dum)
+
+ # object is rebuilt in order to make sure that all contracted indices get recognized as dummies.
+ # t2 = TensMul(*t.args)
+ return t
def fun_eval(self, *index_tuples):
"""
@@ -3660,10 +3371,10 @@ def fun_eval(self, *index_tuples):
break
else:
free1.append((j, ipos, cpos))
- return TensMul.from_data(self.coeff, self.components, free1, self.dum)
+ return TensMul.from_data(self._coeff, self.components, free1, self.dum)
def __call__(self, *indices):
- """Returns tensor product with ordered free indices replaced by ``indices``
+ """Returns tensor with ordered free indices replaced by ``indices``
Examples
========
@@ -3694,19 +3405,26 @@ def __call__(self, *indices):
return t
def _print(self):
- args = self.args
- get_str = lambda arg: str(arg) if arg.is_Atom or isinstance(arg, TensExpr) else ("(%s)" % str(arg))
-
- if not args:
- # no arguments is equivalent to "1", i.e. TensMul().
- # If tensors are constructed correctly, this should never occur.
- return "1"
- if self.coeff == S.NegativeOne:
- # expressions like "-A(a)"
- return "-"+"*".join([get_str(arg) for arg in args[1:]])
-
- # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)"
- return "*".join([get_str(arg) for arg in self.args])
+ if len(self.components) == 0:
+ return str(self._coeff)
+ indices = [str(ind) for ind in self.get_indices()]
+ pos = 0
+ a = []
+ for t in self.components:
+ if t._rank > 0:
+ a.append('%s(%s)' % (t.name, ', '.join(indices[pos:pos + t._rank])))
+ else:
+ a.append('%s' % t.name)
+ pos += t._rank
+ res = '*'. join(a)
+ if self._coeff == S.One:
+ return res
+ elif self._coeff == -S.One:
+ return '-%s' % res
+ if self._coeff.is_Atom:
+ return '%s*%s' % (self._coeff, res)
+ else:
+ return '(%s)*%s' %(self._coeff, res)
@property
def data(self):
@@ -3717,11 +3435,13 @@ def data(self):
@data.setter
def data(self, data):
- raise ValueError("Not possible to set component data to a tensor expression")
+ # TODO: check data compatibility with properties of tensor.
+ _tensor_data_substitution_dict[self] = data
@data.deleter
def data(self):
- raise ValueError("Not possible to delete component data to a tensor expression")
+ if self in _tensor_data_substitution_dict:
+ del _tensor_data_substitution_dict[self]
def __iter__(self):
if self.data is None:
@@ -3782,7 +3502,7 @@ def riemann_cyclic(t2):
>>> riemann_cyclic(t)
0
"""
- if isinstance(t2, (TensMul, Tensor)):
+ if isinstance(t2, TensMul):
args = [t2]
else:
args = t2.args
@@ -3807,7 +3527,6 @@ def _join_lines(a):
while i < len(a):
x = a[i]
xend = x[-1]
- xstart = x[0]
hit = True
while hit:
hit = False
@@ -3819,27 +3538,6 @@ def _join_lines(a):
x.extend(a[j][1:])
xend = x[-1]
a.pop(j)
- continue
- if a[j][0] == xstart:
- hit = True
- a[i] = reversed(a[j][1:]) + x
- x = a[i]
- xstart = a[i][0]
- a.pop(j)
- continue
- if a[j][-1] == xend:
- hit = True
- x.extend(reversed(a[j][:-1]))
- xend = x[-1]
- a.pop(j)
- continue
- if a[j][-1] == xstart:
- hit = True
- a[i] = a[j][:-1] + x
- x = a[i]
- xstart = x[0]
- a.pop(j)
- continue
i += 1
return a
@@ -3910,80 +3608,3 @@ def _join_lines(a):
rest = [x for x in range(len(components)) if x not in rest]
return lines, traces, rest
-
-def get_indices(t):
- if not isinstance(t, TensExpr):
- return ()
- return t.get_indices()
-
-def get_tids(t):
- if isinstance(t, TensExpr):
- return t._tids
- return TIDS([], [], [])
-
-def get_coeff(t):
- if isinstance(t, Tensor):
- return S.One
- if isinstance(t, TensMul):
- return t.coeff
- if isinstance(t, TensExpr):
- raise ValueError("no coefficient associated to this tensor expression")
- return t
-
-def contract_metric(t, g):
- if isinstance(t, TensExpr):
- return t.contract_metric(g)
- return t
-
-def perm2tensor(t, g, canon_bp=False):
- """
- Returns the tensor corresponding to the permutation ``g``
-
- For further details, see the method in ``TIDS`` with the same name.
- """
- if not isinstance(t, TensExpr):
- return t
- new_tids = get_tids(t).perm2tensor(g, canon_bp)
- coeff = get_coeff(t)
- if g[-1] != len(g) - 1:
- coeff = -coeff
- res = TensMul.from_TIDS(coeff, new_tids, is_canon_bp=canon_bp)
- return res
-
-def substitute_indices(t, *index_tuples):
- """
- Return a tensor with free indices substituted according to ``index_tuples``
-
- ``index_types`` list of tuples ``(old_index, new_index)``
-
- Note: this method will neither raise or lower the indices, it will just replace their symbol.
-
- Examples
- ========
-
- >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensorhead
- >>> Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
- >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz)
- >>> A, B = tensorhead('A,B', [Lorentz]*2, [[1]*2])
- >>> t = A(i, k)*B(-k, -j); t
- A(i, L_0)*B(-L_0, -j)
- >>> t.substitute_indices((i,j), (j, k))
- A(j, L_0)*B(-L_0, -k)
- """
- if not isinstance(t, TensExpr):
- return t
- free = t.free
- free1 = []
- for j, ipos, cpos in free:
- for i, v in index_tuples:
- if i._name == j._name and i._tensortype == j._tensortype:
- if i._is_up == j._is_up:
- free1.append((v, ipos, cpos))
- else:
- free1.append((-v, ipos, cpos))
- break
- else:
- free1.append((j, ipos, cpos))
-
- t = TensMul.from_data(t.coeff, t.components, free1, t.dum)
- return t
| solve(x < oo) and solve(x > -oo) returns False
```python
>>> x = symbols('x')
>>> solve(x < oo)
>>> False
>>> solve(x > -oo)
>>> False
```
It should return `And(x > -oo, x < oo)`. | sympy/sympy | diff --git a/sympy/core/tests/test_args.py b/sympy/core/tests/test_args.py
index c1bdff1441..93d35e1939 100644
--- a/sympy/core/tests/test_args.py
+++ b/sympy/core/tests/test_args.py
@@ -3039,17 +3039,6 @@ def test_sympy__tensor__tensor__TensAdd():
assert _test_args(TensAdd(t1, t2))
-def test_sympy__tensor__tensor__Tensor():
- from sympy.core import S
- from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, TensorType, get_symmetric_group_sgs, tensor_indices, TensMul, TIDS
- Lorentz = TensorIndexType('Lorentz', dummy_fmt='L')
- a, b = tensor_indices('a,b', Lorentz)
- sym = TensorSymmetry(get_symmetric_group_sgs(1))
- S1 = TensorType([Lorentz], sym)
- p = S1('p')
- assert _test_args(p(a))
-
-
def test_sympy__tensor__tensor__TensMul():
from sympy.core import S
from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, TensorType, get_symmetric_group_sgs, tensor_indices, TensMul, TIDS
@@ -3058,8 +3047,8 @@ def test_sympy__tensor__tensor__TensMul():
sym = TensorSymmetry(get_symmetric_group_sgs(1))
S1 = TensorType([Lorentz], sym)
p = S1('p')
- q = S1('q')
- assert _test_args(3*p(a)*q(b))
+ free, dum = TIDS.free_dum_from_indices(a)
+ assert _test_args(TensMul.from_data(S.One, [p], free, dum))
def test_as_coeff_add():
diff --git a/sympy/core/tests/test_expr.py b/sympy/core/tests/test_expr.py
index 118bd92ddc..ee1be6bdfc 100644
--- a/sympy/core/tests/test_expr.py
+++ b/sympy/core/tests/test_expr.py
@@ -6,7 +6,7 @@
Piecewise, Mul, Pow, nsimplify, ratsimp, trigsimp, radsimp, powsimp,
simplify, together, collect, factorial, apart, combsimp, factor, refine,
cancel, Tuple, default_sort_key, DiracDelta, gamma, Dummy, Sum, E,
- exp_polar, Lambda, expand, diff, O, Heaviside, Si, Max)
+ exp_polar, Lambda, expand, diff, O, Heaviside, Si)
from sympy.core.function import AppliedUndef
from sympy.physics.secondquant import FockState
from sympy.physics.units import meter
@@ -1531,9 +1531,6 @@ def test_random():
assert posify(x)[0]._random() is not None
assert lucas(n)._random(2, -2, 0, -1, 1) is None
- # issue 8662
- assert Piecewise((Max(x, y), z))._random() is None
-
def test_round():
from sympy.abc import x
diff --git a/sympy/core/tests/test_function.py b/sympy/core/tests/test_function.py
index 304cf5f421..0645b8f890 100644
--- a/sympy/core/tests/test_function.py
+++ b/sympy/core/tests/test_function.py
@@ -183,7 +183,7 @@ def test_Lambda_equality():
def test_Subs():
assert Subs(x, x, 0) == Subs(y, y, 0)
- assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 0)
+ assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 1)
assert Subs(y, x, 0).subs(y, 1) == Subs(1, x, 0)
assert Subs(f(x), x, 0).doit() == f(0)
assert Subs(f(x**2), x**2, 0).doit() == f(0)
@@ -206,7 +206,7 @@ def test_Subs():
assert Subs(f(x)*y, (x, y), (0, 1)) == Subs(f(y)*x, (y, x), (0, 1))
assert Subs(f(x)*y, (x, y), (1, 1)) == Subs(f(y)*x, (x, y), (1, 1))
- assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0)
+ assert Subs(f(x), x, 0).subs(x, 1).doit() == f(1)
assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0)
assert Subs(y*f(x), x, y).subs(y, 2) == Subs(2*f(x), x, 2)
assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2*y
@@ -235,9 +235,6 @@ def test_Subs():
Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).evalf(2) == \
z + Rational('1/2').n(2)*f(0)
- assert f(x).diff(x).subs(x, 0).subs(x, y) == f(x).diff(x).subs(x, 0)
- assert (x*f(x).diff(x).subs(x, 0)).subs(x, y) == y*f(x).diff(x).subs(x, 0)
-
@XFAIL
def test_Subs2():
diff --git a/sympy/functions/combinatorial/tests/test_comb_factorials.py b/sympy/functions/combinatorial/tests/test_comb_factorials.py
index 727c5fc999..9761dd2d6c 100644
--- a/sympy/functions/combinatorial/tests/test_comb_factorials.py
+++ b/sympy/functions/combinatorial/tests/test_comb_factorials.py
@@ -1,6 +1,6 @@
from sympy import (Symbol, symbols, factorial, factorial2, binomial,
rf, ff, gamma, polygamma, EulerGamma, O, pi, nan,
- oo, zoo, simplify, expand_func, C, S, Product)
+ oo, zoo, simplify, expand_func)
from sympy.functions.combinatorial.factorials import subfactorial
from sympy.utilities.pytest import XFAIL, raises
@@ -146,10 +146,8 @@ def test_factorial_series():
def test_factorial_rewrite():
n = Symbol('n', integer=True)
- k = Symbol('k', integer=True, nonnegative=True)
assert factorial(n).rewrite(gamma) == gamma(n + 1)
- assert str(factorial(k).rewrite(Product)) == 'Product(_i, (_i, 1, k))'
def test_factorial2():
@@ -264,11 +262,8 @@ def test_factorial_simplify_fail():
def test_subfactorial():
assert all(subfactorial(i) == ans for i, ans in enumerate(
[1, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496]))
- assert subfactorial(oo) == oo
-
- x = Symbol('x')
- assert subfactorial(x).rewrite(C.uppergamma) == \
- C.uppergamma(x + 1, -1)/S.Exp1
+ raises(ValueError, lambda: subfactorial(0.1))
+ raises(ValueError, lambda: subfactorial(-2))
tt = Symbol('tt', integer=True, nonnegative=True)
tf = Symbol('tf', integer=True, nonnegative=False)
@@ -280,11 +275,11 @@ def test_subfactorial():
nf = Symbol('nf', nonnegative=False)
nn = Symbol('nf')
assert subfactorial(tt).is_integer
- assert subfactorial(tf).is_integer is None
+ assert subfactorial(tf).is_integer is False
assert subfactorial(tn).is_integer is None
- assert subfactorial(ft).is_integer is None
- assert subfactorial(ff).is_integer is None
- assert subfactorial(fn).is_integer is None
+ assert subfactorial(ft).is_integer is False
+ assert subfactorial(ff).is_integer is False
+ assert subfactorial(fn).is_integer is False
assert subfactorial(nt).is_integer is None
- assert subfactorial(nf).is_integer is None
+ assert subfactorial(nf).is_integer is False
assert subfactorial(nn).is_integer is None
diff --git a/sympy/logic/tests/test_boolalg.py b/sympy/logic/tests/test_boolalg.py
index 64be048911..6e9fb597c4 100644
--- a/sympy/logic/tests/test_boolalg.py
+++ b/sympy/logic/tests/test_boolalg.py
@@ -667,3 +667,11 @@ def test_all_or_nothing():
def test_canonical_atoms():
assert true.canonical == true
assert false.canonical == false
+
+
+def test_issue_8777():
+ x = symbols('x')
+ assert And(x > 2, x < oo).as_set() == Interval(2, oo, left_open=True)
+ assert And(x >= 1, x < oo).as_set() == Interval(1, oo)
+ assert (x < oo).as_set() == Interval(-oo, oo)
+ assert (x > -oo).as_set() == Interval(-oo, oo)
diff --git a/sympy/physics/hep/tests/test_gamma_matrices.py b/sympy/physics/hep/tests/test_gamma_matrices.py
index d0c018761c..dcbcc81c44 100644
--- a/sympy/physics/hep/tests/test_gamma_matrices.py
+++ b/sympy/physics/hep/tests/test_gamma_matrices.py
@@ -435,18 +435,18 @@ def test_get_lines():
G(i4,s4,-s5)*G(i5,s6,-s7)*G(i10,s11,-s12)*G(i6,s7,-s8)*G(i7,s8,-s9)*\
G(i8,s9,-s6)*G(i9,s10,-s0)
r = get_lines(t, DiracSpinorIndex)
- assert r == ([[7, 1], [0, 3, 4, 5]], [[6, 8, 9, 10], [2, 11]], [])
+ assert r == ([[0, 3, 4, 5], [7, 1]], [[6, 8, 9, 10], [2, 11]], [])
t = G(i4,s4,-s5)*G(i5,s6,-s7)*G(i10,s11,-s12)*G(i6,s7,-s8)*G(i7,s8,-s9)*\
G(i8,s9,-s6)*G(i9,s10,-s0)*\
G(i1,s1,-s2)*G(i11,s12,-s13)*G(i0,s0,-s10)*G(i2,s2,-s3)*G(i3,s3,-s4)
r = get_lines(t, DiracSpinorIndex)
- assert r == ([[7, 10, 11, 0], [2, 8]], [[1, 3, 4, 5], [6, 9]], [])
+ assert r == ([[2, 8], [7, 10, 11, 0]], [[1, 3, 4, 5], [6, 9]], [])
t = G(i8,s9,-s6)*G(i9,s10,-s0)*G(i4,s4,-s5)*G(i13,s14,-s15)*\
G(i10,s11,-s12)*G(i1,s1,-s2)*G(i11,s12,-s13)*\
G(i0,s0,-s10)*G(i6,s7,-s8)*G(i7,s8,-s9)*\
G(i2,s2,-s3)*G(i12,s13,-s14)*G(i3,s3,-s4)*G(i5,s6,-s7)
r = get_lines(t, DiracSpinorIndex)
- assert r == ([[5, 10, 12, 2], [4, 6, 11, 3]], [[1, 7], [0, 13, 8, 9]], [])
+ assert r == ([[4, 6, 11, 3], [5, 10, 12, 2]], [[1, 7], [0, 13, 8, 9]], [])
def test_simplify_lines():
i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12 = tensor_indices('i0:13', G.LorentzIndex)
diff --git a/sympy/polys/tests/test_rootoftools.py b/sympy/polys/tests/test_rootoftools.py
index 60c7bedd99..40e2fa7e61 100644
--- a/sympy/polys/tests/test_rootoftools.py
+++ b/sympy/polys/tests/test_rootoftools.py
@@ -228,9 +228,6 @@ def test_RootOf_evalf():
ans = [w.n(2) for w in solve(x**3 - x - 4)]
assert RootOf(exp(x)**3 - exp(x) - 4, 0).n(2) in ans
- # make sure verification is used in case a max/min traps the "root"
- assert str(RootOf(4*x**5 + 16*x**3 + 12*x**2 + 7, 0).n(3)) == '-0.976'
-
def test_RootOf_evalf_caching_bug():
r = RootOf(x**5 - 5*x + 12, 1)
diff --git a/sympy/series/tests/test_limits.py b/sympy/series/tests/test_limits.py
index 07c795444c..5b030ffaf2 100644
--- a/sympy/series/tests/test_limits.py
+++ b/sympy/series/tests/test_limits.py
@@ -3,7 +3,7 @@
from sympy import (
limit, exp, oo, log, sqrt, Limit, sin, floor, cos, ceiling,
atan, gamma, Symbol, S, pi, Integral, cot, Rational, I, zoo,
- tan, cot, integrate, Sum, sign, Function, subfactorial)
+ tan, cot, integrate, Sum, sign, Function)
from sympy.series.limits import heuristics
from sympy.series.order import Order
@@ -433,7 +433,3 @@ def test_issue_4503():
dx = Symbol('dx')
assert limit((sqrt(1 + exp(x + dx)) - sqrt(1 + exp(x)))/dx, dx, 0) == \
exp(x)/(2*sqrt(exp(x) + 1))
-
-
-def test_issue_8730():
- assert limit(subfactorial(x), x, oo) == oo
diff --git a/sympy/solvers/tests/test_inequalities.py b/sympy/solvers/tests/test_inequalities.py
index d4bcc8ea3b..e2902de685 100644
--- a/sympy/solvers/tests/test_inequalities.py
+++ b/sympy/solvers/tests/test_inequalities.py
@@ -304,3 +304,11 @@ def test_issue_8545():
assert reduce_abs_inequality(eq, '<', x) == ans
eq = 1 - x - sqrt((1 - x)**2)
assert reduce_inequalities(eq < 0) == ans
+
+
+def test_issue_8783():
+ x = Symbol('x')
+ assert solve(x > -oo) == And(-oo < x, x < oo)
+ assert solve(x < oo) == And(-oo < x, x < oo)
+ assert solve(x > oo) == False
+ assert solve(x < -oo) == False
diff --git a/sympy/tensor/tests/test_tensor.py b/sympy/tensor/tests/test_tensor.py
index d893c90797..bfc0c5196d 100644
--- a/sympy/tensor/tests/test_tensor.py
+++ b/sympy/tensor/tests/test_tensor.py
@@ -655,15 +655,6 @@ def test_mul():
assert sorted(t.free) == [(a, 0, 0), (b, 1, 0)]
assert t.components == [A]
- ts = A(a, b)
- assert str(ts) == 'A(a, b)'
- assert ts.types == [Lorentz]
- assert ts.rank == 2
- assert ts.dum == []
- assert ts.coeff == 1
- assert sorted(ts.free) == [(a, 0, 0), (b, 1, 0)]
- assert ts.components == [A]
-
t = A(-b, a)*B(-a, c)*A(-c, d)
t1 = tensor_mul(*t.split())
assert t == t(-b, d)
@@ -1196,7 +1187,7 @@ def test_hidden_indices_for_matrix_multiplication():
B1 = B(m1)
assert _is_equal((B1*A0*B0), B(m1, s0)*A(m0, -s0, s1)*B(-m0, -s1))
- assert _is_equal((B0*A0), B(-m0, s0)*A(m0, -s0, S.auto_left))
+ assert _is_equal((B0*A0), B(-m0, s0)*A(m0, -s0, -S.auto_right))
assert _is_equal((A0*B0), A(m0, S.auto_left, s0)*B(-m0, -s0))
C = tensorhead('C', [L, L], [[1]*2])
| {
"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": 3,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 12
} | 0.7 | {
"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 build-essential"
],
"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
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
mpmath==1.3.0
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/sympy/sympy.git@b5b6b45f65b828f37f09a4a09c90c68367e3b802#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_args.py::test_all_classes_are_tested",
"sympy/core/tests/test_function.py::test_Subs",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_subfactorial",
"sympy/logic/tests/test_boolalg.py::test_issue_8777",
"sympy/physics/hep/tests/test_gamma_matrices.py::test_get_lines",
"sympy/solvers/tests/test_inequalities.py::test_issue_8783",
"sympy/tensor/tests/test_tensor.py::test_hidden_indices_for_matrix_multiplication"
] | [] | [
"sympy/core/tests/test_args.py::test_sympy__assumptions__assume__AppliedPredicate",
"sympy/core/tests/test_args.py::test_sympy__assumptions__assume__Predicate",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__subsets__Subset",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__perm_groups__PermutationGroup",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__polyhedron__Polyhedron",
"sympy/core/tests/test_args.py::test_sympy__combinatorics__partitions__Partition",
"sympy/core/tests/test_args.py::test_sympy__concrete__products__Product",
"sympy/core/tests/test_args.py::test_sympy__concrete__summations__Sum",
"sympy/core/tests/test_args.py::test_sympy__core__add__Add",
"sympy/core/tests/test_args.py::test_sympy__core__basic__Atom",
"sympy/core/tests/test_args.py::test_sympy__core__basic__Basic",
"sympy/core/tests/test_args.py::test_sympy__core__containers__Dict",
"sympy/core/tests/test_args.py::test_sympy__core__containers__Tuple",
"sympy/core/tests/test_args.py::test_sympy__core__expr__AtomicExpr",
"sympy/core/tests/test_args.py::test_sympy__core__expr__Expr",
"sympy/core/tests/test_args.py::test_sympy__core__function__Application",
"sympy/core/tests/test_args.py::test_sympy__core__function__AppliedUndef",
"sympy/core/tests/test_args.py::test_sympy__core__function__Derivative",
"sympy/core/tests/test_args.py::test_sympy__core__function__Lambda",
"sympy/core/tests/test_args.py::test_sympy__core__function__Subs",
"sympy/core/tests/test_args.py::test_sympy__core__function__WildFunction",
"sympy/core/tests/test_args.py::test_sympy__core__mod__Mod",
"sympy/core/tests/test_args.py::test_sympy__core__mul__Mul",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Catalan",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__ComplexInfinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__EulerGamma",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Exp1",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Float",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__GoldenRatio",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Half",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__ImaginaryUnit",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Infinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Integer",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NaN",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NegativeInfinity",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NegativeOne",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Number",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__NumberSymbol",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__One",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Pi",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Rational",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__Zero",
"sympy/core/tests/test_args.py::test_sympy__core__power__Pow",
"sympy/core/tests/test_args.py::test_sympy__core__relational__Equality",
"sympy/core/tests/test_args.py::test_sympy__core__relational__GreaterThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__LessThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__StrictGreaterThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__StrictLessThan",
"sympy/core/tests/test_args.py::test_sympy__core__relational__Unequality",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__EmptySet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__UniversalSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__FiniteSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Interval",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__ProductSet",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Intersection",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Union",
"sympy/core/tests/test_args.py::test_sympy__sets__sets__Complement",
"sympy/core/tests/test_args.py::test_sympy__core__trace__Tr",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Naturals",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Naturals0",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Integers",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Reals",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__ImageSet",
"sympy/core/tests/test_args.py::test_sympy__sets__fancysets__Range",
"sympy/core/tests/test_args.py::test_sympy__sets__contains__Contains",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__SingleContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ProductContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ConditionalContinuousDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__SingleContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ProductContinuousPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__drv__SingleDiscreteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__drv__SingleDiscretePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__RandomDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__SingleDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ConditionalDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__PSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__RandomSymbol",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ProductPSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__ProductDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__DiscreteUniformDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__DieDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__BernoulliDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__BinomialDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__HypergeometricDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__RademacherDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__FiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__SingleFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ProductFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ConditionalFiniteDomain",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__FinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__SingleFinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv__ProductFinitePSpace",
"sympy/core/tests/test_args.py::test_sympy__stats__frv_types__FiniteDistributionHandmade",
"sympy/core/tests/test_args.py::test_sympy__stats__crv__ContinuousDistributionHandmade",
"sympy/core/tests/test_args.py::test_sympy__stats__rv__Density",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ArcsinDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BeniniDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BetaDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__BetaPrimeDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__CauchyDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiNoncentralDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ChiSquaredDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__DagumDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ExponentialDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FDistributionDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FisherZDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__FrechetDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__GammaInverseDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__GammaDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__KumaraswamyDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LaplaceDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LogisticDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__LogNormalDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__MaxwellDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__NakagamiDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__NormalDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__ParetoDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__QuadraticUDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__RaisedCosineDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__RayleighDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__StudentTDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__TriangularDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__UniformDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__UniformSumDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__VonMisesDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__WeibullDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__crv_types__WignerSemicircleDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__drv_types__PoissonDistribution",
"sympy/core/tests/test_args.py::test_sympy__stats__drv_types__GeometricDistribution",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Dummy",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Symbol",
"sympy/core/tests/test_args.py::test_sympy__core__symbol__Wild",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__FallingFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__MultiFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__RisingFactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__binomial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__subfactorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__factorial",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__factorials__factorial2",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__bell",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__bernoulli",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__catalan",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__euler",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__fibonacci",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__harmonic",
"sympy/core/tests/test_args.py::test_sympy__functions__combinatorial__numbers__lucas",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__Abs",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__adjoint",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__arg",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__conjugate",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__im",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__re",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__sign",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__polar_lift",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__periodic_argument",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__principal_branch",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__complexes__transpose",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__LambertW",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__exp",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__exp_polar",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__exponential__log",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__acosh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__acoth",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__asinh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__atanh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__cosh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__coth",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__csch",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__sech",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__sinh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__hyperbolic__tanh",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__ceiling",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__integers__floor",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__IdentityFunction",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__Max",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__miscellaneous__Min",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__piecewise__ExprCondPair",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__piecewise__Piecewise",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acos",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acot",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__asin",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__asec",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__acsc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__atan",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__atan2",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__cos",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__csc",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__cot",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sin",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__sec",
"sympy/core/tests/test_args.py::test_sympy__functions__elementary__trigonometric__tan",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besseli",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besselj",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__besselk",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__bessely",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__hankel1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__hankel2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__jn",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__yn",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__AiryBase",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airyai",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airybi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airyaiprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__bessel__airybiprime",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_k",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_f",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_e",
"sympy/core/tests/test_args.py::test_sympy__functions__special__elliptic_integrals__elliptic_pi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__delta_functions__DiracDelta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__delta_functions__Heaviside",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfinv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfcinv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erf2inv",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__fresnels",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__fresnelc",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__erfs",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Ei",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__li",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Li",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Si",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Ci",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Shi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__Chi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__error_functions__expint",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__gamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__loggamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__lowergamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__polygamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__gamma_functions__uppergamma",
"sympy/core/tests/test_args.py::test_sympy__functions__special__beta_functions__beta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__hyper",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__meijerg",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_power1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_power2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_log1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_atanh",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_asin1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_asin2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sqrts1",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sqrts2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_log2",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_cosasin",
"sympy/core/tests/test_args.py::test_sympy__functions__special__hyper__HyperRep_sinasin",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__jacobi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__gegenbauer",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevt",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevt_root",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevu",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__chebyshevu_root",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__hermite",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__legendre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__assoc_legendre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__laguerre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__polynomials__assoc_laguerre",
"sympy/core/tests/test_args.py::test_sympy__functions__special__spherical_harmonics__Ynm",
"sympy/core/tests/test_args.py::test_sympy__functions__special__spherical_harmonics__Znm",
"sympy/core/tests/test_args.py::test_sympy__functions__special__tensor_functions__LeviCivita",
"sympy/core/tests/test_args.py::test_sympy__functions__special__tensor_functions__KroneckerDelta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__dirichlet_eta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__zeta",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__lerchphi",
"sympy/core/tests/test_args.py::test_sympy__functions__special__zeta_functions__polylog",
"sympy/core/tests/test_args.py::test_sympy__integrals__integrals__Integral",
"sympy/core/tests/test_args.py::test_sympy__integrals__risch__NonElementaryIntegral",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__MellinTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseMellinTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__LaplaceTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseLaplaceTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseFourierTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__FourierTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseSineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__SineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseCosineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__CosineTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__InverseHankelTransform",
"sympy/core/tests/test_args.py::test_sympy__integrals__transforms__HankelTransform",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__And",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanFunction",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanTrue",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__BooleanFalse",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Equivalent",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__ITE",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Implies",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Nand",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Nor",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Not",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Or",
"sympy/core/tests/test_args.py::test_sympy__logic__boolalg__Xor",
"sympy/core/tests/test_args.py::test_sympy__matrices__matrices__DeferredVector",
"sympy/core/tests/test_args.py::test_sympy__matrices__immutable__ImmutableMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__immutable__ImmutableSparseMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__slice__MatrixSlice",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__blockmatrix__BlockMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__inverse__Inverse",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matadd__MatAdd",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__Identity",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__MatrixElement",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matexpr__ZeroMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matmul__MatMul",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__diagonal__DiagonalMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__diagonal__DiagonalOf",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__hadamard__HadamardProduct",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__matpow__MatPow",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__transpose__Transpose",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__adjoint__Adjoint",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__trace__Trace",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__determinant__Determinant",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__funcmatrix__FunctionMatrix",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__fourier__DFT",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__fourier__IDFT",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__LofLU",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofLU",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__QofQR",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__RofQR",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__LofCholesky",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofCholesky",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__EigenVectors",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__EigenValues",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__UofSVD",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__VofSVD",
"sympy/core/tests/test_args.py::test_sympy__matrices__expressions__factorizations__SofSVD",
"sympy/core/tests/test_args.py::test_sympy__physics__vector__frame__CoordinateSym",
"sympy/core/tests/test_args.py::test_sympy__physics__paulialgebra__Pauli",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__anticommutator__AntiCommutator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionBra3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionKet3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PositionState3D",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__PxOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__XOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__YOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cartesian__ZOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__CG",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner3j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner6j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__cg__Wigner9j",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__circuitplot__Mz",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__circuitplot__Mx",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__commutator__Commutator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__constants__HBar",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__dagger__Dagger",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CGateS",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__CNotGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__Gate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__HadamardGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__IdentityGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__OneQubitGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__PhaseGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__SwapGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__TGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__TwoQubitGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__UGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__XGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__YGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__gate__ZGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__grover__WGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__ComplexSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__FockSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__HilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__L2",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__innerproduct__InnerProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__DifferentialOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__HermitianOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__IdentityOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__Operator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__OuterProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__operator__UnitaryOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonFockKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonFockBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonCoherentKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__boson__BosonCoherentBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionFockKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__fermion__FermionFockBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaOpBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaX",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaY",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZ",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaMinus",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaPlus",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__pauli__SigmaZBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABHamiltonian",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__piab__PIABKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qexpr__QExpr",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__Fourier",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__IQFT",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__QFT",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qft__RkGate",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubit",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubitBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__IntQubitState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__Qubit",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__QubitBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__qubit__QubitState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__density__Density",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__CoupledSpinState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__J2Op",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JminusOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JplusOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JxOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JyOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzBraCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzKetCoupled",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__JzOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__Rotation",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__SpinState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__spin__WignerD",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Bra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__BraBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Ket",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__KetBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__State",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__StateBase",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepBra",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__TimeDepState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__state__Wavefunction",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__tensorproduct__TensorProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__identitysearch__GateIdentity",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__RaisingOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__LoweringOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__NumberOp",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__Hamiltonian",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOState",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOKet",
"sympy/core/tests/test_args.py::test_sympy__physics__quantum__sho1d__SHOBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AnnihilateBoson",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AnnihilateFermion",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__AntiSymmetricTensor",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__BosonState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__Commutator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__CreateBoson",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__CreateFermion",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__Dagger",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FermionState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FermionicOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockState",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBosonBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBosonKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateFermionBra",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateFermionKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__FockStateKet",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__InnerProduct",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__NO",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__PermutationOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__SqOperator",
"sympy/core/tests/test_args.py::test_sympy__physics__secondquant__TensorSymbol",
"sympy/core/tests/test_args.py::test_sympy__physics__units__Unit",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__dimensions__Dimension",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__quantities__Quantity",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__units__Constant",
"sympy/core/tests/test_args.py::test_sympy__physics__unitsystems__units__Unit",
"sympy/core/tests/test_args.py::test_sympy__core__numbers__AlgebraicNumber",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__GroebnerBasis",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__Poly",
"sympy/core/tests/test_args.py::test_sympy__polys__polytools__PurePoly",
"sympy/core/tests/test_args.py::test_sympy__polys__rootoftools__RootOf",
"sympy/core/tests/test_args.py::test_sympy__polys__rootoftools__RootSum",
"sympy/core/tests/test_args.py::test_sympy__series__limits__Limit",
"sympy/core/tests/test_args.py::test_sympy__series__order__Order",
"sympy/core/tests/test_args.py::test_sympy__simplify__hyperexpand__Hyper_Function",
"sympy/core/tests/test_args.py::test_sympy__simplify__hyperexpand__G_Function",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__Idx",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__Indexed",
"sympy/core/tests/test_args.py::test_sympy__tensor__indexed__IndexedBase",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorIndexType",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorSymmetry",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorType",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorHead",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensorIndex",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensAdd",
"sympy/core/tests/test_args.py::test_sympy__tensor__tensor__TensMul",
"sympy/core/tests/test_args.py::test_as_coeff_add",
"sympy/core/tests/test_args.py::test_sympy__geometry__curve__Curve",
"sympy/core/tests/test_args.py::test_sympy__geometry__point__Point",
"sympy/core/tests/test_args.py::test_sympy__geometry__point3d__Point3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__ellipse__Ellipse",
"sympy/core/tests/test_args.py::test_sympy__geometry__ellipse__Circle",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Line",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Ray",
"sympy/core/tests/test_args.py::test_sympy__geometry__line__Segment",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Line3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Segment3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__line3d__Ray3D",
"sympy/core/tests/test_args.py::test_sympy__geometry__plane__Plane",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__Polygon",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__RegularPolygon",
"sympy/core/tests/test_args.py::test_sympy__geometry__polygon__Triangle",
"sympy/core/tests/test_args.py::test_sympy__geometry__entity__GeometryEntity",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Manifold",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Patch",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__CoordSystem",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__BaseScalarField",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__BaseVectorField",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Differential",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__Commutator",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__TensorProduct",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__WedgeProduct",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__LieDerivative",
"sympy/core/tests/test_args.py::test_sympy__diffgeom__diffgeom__CovarDerivativeOp",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Class",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Object",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__IdentityMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__NamedMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__CompositeMorphism",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Diagram",
"sympy/core/tests/test_args.py::test_sympy__categories__baseclasses__Category",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___totient",
"sympy/core/tests/test_args.py::test_sympy__ntheory__factor___divisor_sigma",
"sympy/core/tests/test_args.py::test_sympy__ntheory__residue_ntheory__mobius",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__waves__TWave",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__gaussopt__BeamParameter",
"sympy/core/tests/test_args.py::test_sympy__physics__optics__medium__Medium",
"sympy/core/tests/test_args.py::test_sympy__printing__codeprinter__Assignment",
"sympy/core/tests/test_args.py::test_sympy__vector__coordsysrect__CoordSysCartesian",
"sympy/core/tests/test_args.py::test_sympy__vector__point__Point",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependent",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentMul",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__basisdependent__BasisDependentZero",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__BaseVector",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorMul",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__VectorZero",
"sympy/core/tests/test_args.py::test_sympy__vector__vector__Vector",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__Dyadic",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__BaseDyadic",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicMul",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicAdd",
"sympy/core/tests/test_args.py::test_sympy__vector__dyadic__DyadicZero",
"sympy/core/tests/test_args.py::test_sympy__vector__deloperator__Del",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__Orienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__ThreeAngleOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__AxisOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__BodyOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__SpaceOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__orienters__QuaternionOrienter",
"sympy/core/tests/test_args.py::test_sympy__vector__scalar__BaseScalar",
"sympy/core/tests/test_expr.py::test_basic",
"sympy/core/tests/test_expr.py::test_ibasic",
"sympy/core/tests/test_expr.py::test_relational",
"sympy/core/tests/test_expr.py::test_relational_assumptions",
"sympy/core/tests/test_expr.py::test_relational_noncommutative",
"sympy/core/tests/test_expr.py::test_basic_nostr",
"sympy/core/tests/test_expr.py::test_series_expansion_for_uniform_order",
"sympy/core/tests/test_expr.py::test_leadterm",
"sympy/core/tests/test_expr.py::test_as_leading_term",
"sympy/core/tests/test_expr.py::test_leadterm2",
"sympy/core/tests/test_expr.py::test_leadterm3",
"sympy/core/tests/test_expr.py::test_as_leading_term2",
"sympy/core/tests/test_expr.py::test_as_leading_term3",
"sympy/core/tests/test_expr.py::test_as_leading_term4",
"sympy/core/tests/test_expr.py::test_as_leading_term_stub",
"sympy/core/tests/test_expr.py::test_atoms",
"sympy/core/tests/test_expr.py::test_is_polynomial",
"sympy/core/tests/test_expr.py::test_is_rational_function",
"sympy/core/tests/test_expr.py::test_is_algebraic_expr",
"sympy/core/tests/test_expr.py::test_SAGE1",
"sympy/core/tests/test_expr.py::test_SAGE2",
"sympy/core/tests/test_expr.py::test_SAGE3",
"sympy/core/tests/test_expr.py::test_len",
"sympy/core/tests/test_expr.py::test_doit",
"sympy/core/tests/test_expr.py::test_attribute_error",
"sympy/core/tests/test_expr.py::test_args",
"sympy/core/tests/test_expr.py::test_noncommutative_expand_issue_3757",
"sympy/core/tests/test_expr.py::test_as_numer_denom",
"sympy/core/tests/test_expr.py::test_as_independent",
"sympy/core/tests/test_expr.py::test_replace",
"sympy/core/tests/test_expr.py::test_find",
"sympy/core/tests/test_expr.py::test_count",
"sympy/core/tests/test_expr.py::test_has_basics",
"sympy/core/tests/test_expr.py::test_has_multiple",
"sympy/core/tests/test_expr.py::test_has_piecewise",
"sympy/core/tests/test_expr.py::test_has_iterative",
"sympy/core/tests/test_expr.py::test_has_integrals",
"sympy/core/tests/test_expr.py::test_has_tuple",
"sympy/core/tests/test_expr.py::test_has_units",
"sympy/core/tests/test_expr.py::test_has_polys",
"sympy/core/tests/test_expr.py::test_has_physics",
"sympy/core/tests/test_expr.py::test_as_poly_as_expr",
"sympy/core/tests/test_expr.py::test_nonzero",
"sympy/core/tests/test_expr.py::test_is_number",
"sympy/core/tests/test_expr.py::test_as_coeff_add",
"sympy/core/tests/test_expr.py::test_as_coeff_mul",
"sympy/core/tests/test_expr.py::test_as_coeff_exponent",
"sympy/core/tests/test_expr.py::test_extractions",
"sympy/core/tests/test_expr.py::test_coeff",
"sympy/core/tests/test_expr.py::test_coeff2",
"sympy/core/tests/test_expr.py::test_coeff2_0",
"sympy/core/tests/test_expr.py::test_coeff_expand",
"sympy/core/tests/test_expr.py::test_integrate",
"sympy/core/tests/test_expr.py::test_as_base_exp",
"sympy/core/tests/test_expr.py::test_issue_4963",
"sympy/core/tests/test_expr.py::test_action_verbs",
"sympy/core/tests/test_expr.py::test_as_powers_dict",
"sympy/core/tests/test_expr.py::test_as_coefficients_dict",
"sympy/core/tests/test_expr.py::test_args_cnc",
"sympy/core/tests/test_expr.py::test_new_rawargs",
"sympy/core/tests/test_expr.py::test_issue_5226",
"sympy/core/tests/test_expr.py::test_free_symbols",
"sympy/core/tests/test_expr.py::test_issue_5300",
"sympy/core/tests/test_expr.py::test_as_coeff_Mul",
"sympy/core/tests/test_expr.py::test_as_coeff_Add",
"sympy/core/tests/test_expr.py::test_expr_sorting",
"sympy/core/tests/test_expr.py::test_as_ordered_factors",
"sympy/core/tests/test_expr.py::test_as_ordered_terms",
"sympy/core/tests/test_expr.py::test_sort_key_atomic_expr",
"sympy/core/tests/test_expr.py::test_issue_4199",
"sympy/core/tests/test_expr.py::test_eval_interval_zoo",
"sympy/core/tests/test_expr.py::test_primitive",
"sympy/core/tests/test_expr.py::test_issue_5843",
"sympy/core/tests/test_expr.py::test_is_constant",
"sympy/core/tests/test_expr.py::test_equals",
"sympy/core/tests/test_expr.py::test_random",
"sympy/core/tests/test_expr.py::test_round",
"sympy/core/tests/test_expr.py::test_round_exception_nostr",
"sympy/core/tests/test_expr.py::test_extract_branch_factor",
"sympy/core/tests/test_expr.py::test_identity_removal",
"sympy/core/tests/test_expr.py::test_float_0",
"sympy/core/tests/test_expr.py::test_issue_6325",
"sympy/core/tests/test_expr.py::test_issue_7426",
"sympy/core/tests/test_function.py::test_f_expand_complex",
"sympy/core/tests/test_function.py::test_bug1",
"sympy/core/tests/test_function.py::test_general_function",
"sympy/core/tests/test_function.py::test_derivative_subs_bug",
"sympy/core/tests/test_function.py::test_derivative_subs_self_bug",
"sympy/core/tests/test_function.py::test_derivative_linearity",
"sympy/core/tests/test_function.py::test_derivative_evaluate",
"sympy/core/tests/test_function.py::test_diff_symbols",
"sympy/core/tests/test_function.py::test_Function",
"sympy/core/tests/test_function.py::test_nargs",
"sympy/core/tests/test_function.py::test_Lambda",
"sympy/core/tests/test_function.py::test_IdentityFunction",
"sympy/core/tests/test_function.py::test_Lambda_symbols",
"sympy/core/tests/test_function.py::test_Lambda_arguments",
"sympy/core/tests/test_function.py::test_Lambda_equality",
"sympy/core/tests/test_function.py::test_expand_function",
"sympy/core/tests/test_function.py::test_function_comparable",
"sympy/core/tests/test_function.py::test_deriv1",
"sympy/core/tests/test_function.py::test_deriv2",
"sympy/core/tests/test_function.py::test_func_deriv",
"sympy/core/tests/test_function.py::test_suppressed_evaluation",
"sympy/core/tests/test_function.py::test_function_evalf",
"sympy/core/tests/test_function.py::test_extensibility_eval",
"sympy/core/tests/test_function.py::test_function_non_commutative",
"sympy/core/tests/test_function.py::test_function_complex",
"sympy/core/tests/test_function.py::test_function__eval_nseries",
"sympy/core/tests/test_function.py::test_doit",
"sympy/core/tests/test_function.py::test_evalf_default",
"sympy/core/tests/test_function.py::test_issue_5399",
"sympy/core/tests/test_function.py::test_derivative_numerically",
"sympy/core/tests/test_function.py::test_fdiff_argument_index_error",
"sympy/core/tests/test_function.py::test_deriv_wrt_function",
"sympy/core/tests/test_function.py::test_diff_wrt_value",
"sympy/core/tests/test_function.py::test_diff_wrt",
"sympy/core/tests/test_function.py::test_diff_wrt_func_subs",
"sympy/core/tests/test_function.py::test_diff_wrt_not_allowed",
"sympy/core/tests/test_function.py::test_klein_gordon_lagrangian",
"sympy/core/tests/test_function.py::test_sho_lagrangian",
"sympy/core/tests/test_function.py::test_straight_line",
"sympy/core/tests/test_function.py::test_sort_variable",
"sympy/core/tests/test_function.py::test_unhandled",
"sympy/core/tests/test_function.py::test_issue_4711",
"sympy/core/tests/test_function.py::test_nfloat",
"sympy/core/tests/test_function.py::test_issue_7068",
"sympy/core/tests/test_function.py::test_issue_7231",
"sympy/core/tests/test_function.py::test_issue_7687",
"sympy/core/tests/test_function.py::test_issue_7688",
"sympy/core/tests/test_function.py::test_mexpand",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_rf_eval_apply",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_ff_eval_apply",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_diff",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_series",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial_rewrite",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_factorial2",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial_diff",
"sympy/functions/combinatorial/tests/test_comb_factorials.py::test_binomial_rewrite",
"sympy/logic/tests/test_boolalg.py::test_overloading",
"sympy/logic/tests/test_boolalg.py::test_And",
"sympy/logic/tests/test_boolalg.py::test_Or",
"sympy/logic/tests/test_boolalg.py::test_Xor",
"sympy/logic/tests/test_boolalg.py::test_Not",
"sympy/logic/tests/test_boolalg.py::test_Nand",
"sympy/logic/tests/test_boolalg.py::test_Nor",
"sympy/logic/tests/test_boolalg.py::test_Implies",
"sympy/logic/tests/test_boolalg.py::test_Equivalent",
"sympy/logic/tests/test_boolalg.py::test_equals",
"sympy/logic/tests/test_boolalg.py::test_simplification",
"sympy/logic/tests/test_boolalg.py::test_bool_map",
"sympy/logic/tests/test_boolalg.py::test_bool_symbol",
"sympy/logic/tests/test_boolalg.py::test_subs",
"sympy/logic/tests/test_boolalg.py::test_commutative",
"sympy/logic/tests/test_boolalg.py::test_and_associativity",
"sympy/logic/tests/test_boolalg.py::test_or_assicativity",
"sympy/logic/tests/test_boolalg.py::test_double_negation",
"sympy/logic/tests/test_boolalg.py::test_eliminate_implications",
"sympy/logic/tests/test_boolalg.py::test_conjuncts",
"sympy/logic/tests/test_boolalg.py::test_disjuncts",
"sympy/logic/tests/test_boolalg.py::test_distribute",
"sympy/logic/tests/test_boolalg.py::test_to_nnf",
"sympy/logic/tests/test_boolalg.py::test_to_cnf",
"sympy/logic/tests/test_boolalg.py::test_to_dnf",
"sympy/logic/tests/test_boolalg.py::test_to_int_repr",
"sympy/logic/tests/test_boolalg.py::test_is_nnf",
"sympy/logic/tests/test_boolalg.py::test_is_cnf",
"sympy/logic/tests/test_boolalg.py::test_is_dnf",
"sympy/logic/tests/test_boolalg.py::test_ITE",
"sympy/logic/tests/test_boolalg.py::test_is_literal",
"sympy/logic/tests/test_boolalg.py::test_operators",
"sympy/logic/tests/test_boolalg.py::test_true_false",
"sympy/logic/tests/test_boolalg.py::test_bool_as_set",
"sympy/logic/tests/test_boolalg.py::test_all_or_nothing",
"sympy/logic/tests/test_boolalg.py::test_canonical_atoms",
"sympy/physics/hep/tests/test_gamma_matrices.py::test_kahane_algorithm",
"sympy/physics/hep/tests/test_gamma_matrices.py::test_kahane_simplify1",
"sympy/physics/hep/tests/test_gamma_matrices.py::test_gamma_matrix_class",
"sympy/physics/hep/tests/test_gamma_matrices.py::test_gamma_matrix_trace",
"sympy/physics/hep/tests/test_gamma_matrices.py::test_simple_trace_cases_symbolic_dim",
"sympy/physics/hep/tests/test_gamma_matrices.py::test_simplify_lines",
"sympy/polys/tests/test_rootoftools.py::test_RootOf___new__",
"sympy/polys/tests/test_rootoftools.py::test_RootOf_attributes",
"sympy/polys/tests/test_rootoftools.py::test_RootOf___eq__",
"sympy/polys/tests/test_rootoftools.py::test_RootOf___eval_Eq__",
"sympy/polys/tests/test_rootoftools.py::test_RootOf_is_real",
"sympy/polys/tests/test_rootoftools.py::test_RootOf_is_complex",
"sympy/polys/tests/test_rootoftools.py::test_RootOf_subs",
"sympy/polys/tests/test_rootoftools.py::test_RootOf_diff",
"sympy/polys/tests/test_rootoftools.py::test_RootOf_evalf",
"sympy/polys/tests/test_rootoftools.py::test_RootOf_evalf_caching_bug",
"sympy/polys/tests/test_rootoftools.py::test_RootOf_real_roots",
"sympy/polys/tests/test_rootoftools.py::test_RootOf_all_roots",
"sympy/polys/tests/test_rootoftools.py::test_RootOf_eval_rational",
"sympy/polys/tests/test_rootoftools.py::test_RootSum___new__",
"sympy/polys/tests/test_rootoftools.py::test_RootSum_free_symbols",
"sympy/polys/tests/test_rootoftools.py::test_RootSum___eq__",
"sympy/polys/tests/test_rootoftools.py::test_RootSum_doit",
"sympy/polys/tests/test_rootoftools.py::test_RootSum_evalf",
"sympy/polys/tests/test_rootoftools.py::test_RootSum_diff",
"sympy/polys/tests/test_rootoftools.py::test_RootSum_subs",
"sympy/polys/tests/test_rootoftools.py::test_RootSum_rational",
"sympy/polys/tests/test_rootoftools.py::test_RootSum_independent",
"sympy/polys/tests/test_rootoftools.py::test_issue_7876",
"sympy/polys/tests/test_rootoftools.py::test_issue_8316",
"sympy/series/tests/test_limits.py::test_basic1",
"sympy/series/tests/test_limits.py::test_basic2",
"sympy/series/tests/test_limits.py::test_basic3",
"sympy/series/tests/test_limits.py::test_basic4",
"sympy/series/tests/test_limits.py::test_basic5",
"sympy/series/tests/test_limits.py::test_issue_3885",
"sympy/series/tests/test_limits.py::test_Limit",
"sympy/series/tests/test_limits.py::test_floor",
"sympy/series/tests/test_limits.py::test_floor_requires_robust_assumptions",
"sympy/series/tests/test_limits.py::test_ceiling",
"sympy/series/tests/test_limits.py::test_ceiling_requires_robust_assumptions",
"sympy/series/tests/test_limits.py::test_atan",
"sympy/series/tests/test_limits.py::test_abs",
"sympy/series/tests/test_limits.py::test_heuristic",
"sympy/series/tests/test_limits.py::test_issue_3871",
"sympy/series/tests/test_limits.py::test_exponential",
"sympy/series/tests/test_limits.py::test_doit",
"sympy/series/tests/test_limits.py::test_issue_3792",
"sympy/series/tests/test_limits.py::test_issue_4090",
"sympy/series/tests/test_limits.py::test_issue_4547",
"sympy/series/tests/test_limits.py::test_issue_5164",
"sympy/series/tests/test_limits.py::test_issue_5183",
"sympy/series/tests/test_limits.py::test_issue_5184",
"sympy/series/tests/test_limits.py::test_issue_5229",
"sympy/series/tests/test_limits.py::test_issue_4546",
"sympy/series/tests/test_limits.py::test_issue_3934",
"sympy/series/tests/test_limits.py::test_calculate_series",
"sympy/series/tests/test_limits.py::test_issue_5955",
"sympy/series/tests/test_limits.py::test_newissue",
"sympy/series/tests/test_limits.py::test_extended_real_line",
"sympy/series/tests/test_limits.py::test_issue_5436",
"sympy/series/tests/test_limits.py::test_Limit_dir",
"sympy/series/tests/test_limits.py::test_polynomial",
"sympy/series/tests/test_limits.py::test_rational",
"sympy/series/tests/test_limits.py::test_issue_5740",
"sympy/series/tests/test_limits.py::test_issue_6366",
"sympy/series/tests/test_limits.py::test_factorial",
"sympy/series/tests/test_limits.py::test_issue_6560",
"sympy/series/tests/test_limits.py::test_issue_5172",
"sympy/series/tests/test_limits.py::test_issue_7088",
"sympy/series/tests/test_limits.py::test_issue_6364",
"sympy/series/tests/test_limits.py::test_issue_4099",
"sympy/series/tests/test_limits.py::test_issue_4503",
"sympy/solvers/tests/test_inequalities.py::test_solve_poly_inequality",
"sympy/solvers/tests/test_inequalities.py::test_reduce_poly_inequalities_real_interval",
"sympy/solvers/tests/test_inequalities.py::test_reduce_poly_inequalities_complex_relational",
"sympy/solvers/tests/test_inequalities.py::test_reduce_rational_inequalities_real_relational",
"sympy/solvers/tests/test_inequalities.py::test_reduce_abs_inequalities",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_general",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_boolean",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_multivariate",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_errors",
"sympy/solvers/tests/test_inequalities.py::test_hacky_inequalities",
"sympy/solvers/tests/test_inequalities.py::test_issue_6343",
"sympy/solvers/tests/test_inequalities.py::test_issue_8235",
"sympy/solvers/tests/test_inequalities.py::test_issue_5526",
"sympy/solvers/tests/test_inequalities.py::test_solve_univariate_inequality",
"sympy/solvers/tests/test_inequalities.py::test_slow_general_univariate",
"sympy/solvers/tests/test_inequalities.py::test_issue_8545",
"sympy/tensor/tests/test_tensor.py::test_canonicalize_no_slot_sym",
"sympy/tensor/tests/test_tensor.py::test_canonicalize_no_dummies",
"sympy/tensor/tests/test_tensor.py::test_no_metric_symmetry",
"sympy/tensor/tests/test_tensor.py::test_canonicalize1",
"sympy/tensor/tests/test_tensor.py::test_bug_correction_tensor_indices",
"sympy/tensor/tests/test_tensor.py::test_riemann_invariants",
"sympy/tensor/tests/test_tensor.py::test_riemann_products",
"sympy/tensor/tests/test_tensor.py::test_canonicalize2",
"sympy/tensor/tests/test_tensor.py::test_canonicalize3",
"sympy/tensor/tests/test_tensor.py::test_TensorIndexType",
"sympy/tensor/tests/test_tensor.py::test_indices",
"sympy/tensor/tests/test_tensor.py::test_tensorsymmetry",
"sympy/tensor/tests/test_tensor.py::test_TensorType",
"sympy/tensor/tests/test_tensor.py::test_TensExpr",
"sympy/tensor/tests/test_tensor.py::test_TensorHead",
"sympy/tensor/tests/test_tensor.py::test_add1",
"sympy/tensor/tests/test_tensor.py::test_special_eq_ne",
"sympy/tensor/tests/test_tensor.py::test_add2",
"sympy/tensor/tests/test_tensor.py::test_mul",
"sympy/tensor/tests/test_tensor.py::test_substitute_indices",
"sympy/tensor/tests/test_tensor.py::test_riemann_cyclic_replace",
"sympy/tensor/tests/test_tensor.py::test_riemann_cyclic",
"sympy/tensor/tests/test_tensor.py::test_div",
"sympy/tensor/tests/test_tensor.py::test_contract_metric1",
"sympy/tensor/tests/test_tensor.py::test_contract_metric2",
"sympy/tensor/tests/test_tensor.py::test_metric_contract3",
"sympy/tensor/tests/test_tensor.py::test_epsilon",
"sympy/tensor/tests/test_tensor.py::test_contract_delta1",
"sympy/tensor/tests/test_tensor.py::test_fun",
"sympy/tensor/tests/test_tensor.py::test_TensorManager",
"sympy/tensor/tests/test_tensor.py::test_hash",
"sympy/tensor/tests/test_tensor.py::test_valued_metric_inverse",
"sympy/tensor/tests/test_tensor.py::test_valued_canon_bp_swapaxes",
"sympy/tensor/tests/test_tensor.py::test_pprint",
"sympy/tensor/tests/test_tensor.py::test_contract_automatrix_and_data"
] | [] | BSD | 17 |
sympy__sympy-8785 | b0e448e58369b168e9b28f683dad4d2699117314 | 2015-01-09 10:59:19 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/functions/combinatorial/numbers.py b/sympy/functions/combinatorial/numbers.py
index 0ba8ee91c7..455f068534 100644
--- a/sympy/functions/combinatorial/numbers.py
+++ b/sympy/functions/combinatorial/numbers.py
@@ -292,6 +292,10 @@ def eval(cls, n, sym=None):
raise ValueError("Bernoulli numbers are defined only"
" for nonnegative integer indices.")
+ if sym is None:
+ if n.is_odd and (n - 1).is_positive:
+ return S.Zero
+
#----------------------------------------------------------------------------#
# #
| bernoulli(2*n+1) should return 0 for a positive integer n
Bernoulli numbers vanish on all odd indexes >1. Thus, the following
```python
>>> n = Symbol('n', integer=True, positive=True)
>>> bernoulli(2*n + 1)
```
should be evaluated to 0. | sympy/sympy | diff --git a/sympy/functions/combinatorial/tests/test_comb_numbers.py b/sympy/functions/combinatorial/tests/test_comb_numbers.py
index ed081841cd..764788dbfb 100644
--- a/sympy/functions/combinatorial/tests/test_comb_numbers.py
+++ b/sympy/functions/combinatorial/tests/test_comb_numbers.py
@@ -39,6 +39,14 @@ def test_bernoulli():
b = bernoulli(10**6, evaluate=False).evalf()
assert str(b) == '-2.23799235765713e+4767529'
+ # Issue #8527
+ l = Symbol('l', integer=True)
+ m = Symbol('m', integer=True, nonnegative=True)
+ n = Symbol('n', integer=True, positive=True)
+ assert isinstance(bernoulli(2 * l + 1), bernoulli)
+ assert isinstance(bernoulli(2 * m + 1), bernoulli)
+ assert bernoulli(2 * n + 1) == 0
+
def test_fibonacci():
assert [fibonacci(n) for n in range(-3, 5)] == [2, -1, 1, 0, 1, 1, 2, 3]
| {
"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": 0,
"test_score": 1
},
"num_modified_files": 1
} | 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": [
"mpmath>=0.19",
"pytest",
"pytest-cov"
],
"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==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.3.0
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
-e git+https://github.com/sympy/sympy.git@b0e448e58369b168e9b28f683dad4d2699117314#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
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
- mpmath==1.3.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/sympy
| [
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_bernoulli"
] | [] | [
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_fibonacci",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_bell",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_rational",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_evalf",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_rewrite_polygamma",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_rewrite_sum",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_euler",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_catalan",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_nC_nP_nT",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_issue_8496"
] | [] | BSD | 18 |
|
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 |
|
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 |
|
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 |
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 |
|
sympy__sympy-8826 | 50b4f3d9cd37aa56fde564ecd13b2928f22f4316 | 2015-01-15 14:55:54 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | cbm755: I'm fixing it in Float, because when I tried to fix it in `sympify` it got messy.
https://github.com/cbm755/sympy/tree/sympify_hiprec_str
Plus, I think Float should work like this too!
smichr: So if I understand, you are using a string 'min15' so we can differentiate between the case of a desired 15 and the default "15 or higher if it's a string" case. Why not just set the default to None so the user has to read the docstring to know what the default is -- which is probably what they will need to do to understand 'min15', anyway? (I think 'min15' is a sane choice but using None is more pythonic.)
cbm755: Thank you @smichr that is nicer, done as you describe.
Also, fixed up documentation.
Finally, fixed the failing test. So in total, this changes two existing tests (long int in test_numbers.py is an improvement, nfloat perhaps less obvious: my test change just maintains the status quo there). | diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py
index 5b57771f13..d80101460d 100644
--- a/sympy/core/numbers.py
+++ b/sympy/core/numbers.py
@@ -456,9 +456,7 @@ def cofactors(self, other):
class Float(Number):
- """
- Represents a floating point number. It is capable of representing
- arbitrary-precision floating-point numbers.
+ """Represent a floating-point number of arbitrary precision.
Examples
========
@@ -469,16 +467,38 @@ class Float(Number):
>>> Float(3)
3.00000000000000
- Floats can be created from a string representations of Python floats
- to force ints to Float or to enter high-precision (> 15 significant
- digits) values:
+ Creating Floats from strings (and Python ``int`` and ``long``
+ types) will give a minimum precision of 15 digits, but the
+ precision will automatically increase to capture all digits
+ entered.
+
+ >>> Float(1)
+ 1.00000000000000
+ >>> Float(10**20)
+ 100000000000000000000.
+ >>> Float('1e20')
+ 100000000000000000000.
+
+ However, *floating-point* numbers (Python ``float`` types) retain
+ only 15 digits of precision:
+
+ >>> Float(1e20)
+ 1.00000000000000e+20
+ >>> Float(1.23456789123456789)
+ 1.23456789123457
+
+ It may be preferable to enter high-precision decimal numbers
+ as strings:
+
+ Float('1.23456789123456789')
+ 1.23456789123456789
+
+ The desired number of digits can also be specified:
- >>> Float('.0010')
- 0.00100000000000000
- >>> Float('1e-3')
- 0.00100000000000000
>>> Float('1e-3', 3)
0.00100
+ >>> Float(100, 4)
+ 100.0
Float can automatically count significant figures if a null string
is sent for the precision; space are also allowed in the string. (Auto-
@@ -602,7 +622,7 @@ class Float(Number):
is_Float = True
- def __new__(cls, num, prec=15):
+ def __new__(cls, num, prec=None):
if isinstance(num, string_types):
num = num.replace(' ', '')
if num.startswith('.') and len(num) > 1:
@@ -616,7 +636,20 @@ def __new__(cls, num, prec=15):
elif isinstance(num, mpmath.mpf):
num = num._mpf_
- if prec == '':
+ if prec is None:
+ dps = 15
+ if isinstance(num, string_types) and _literal_float(num):
+ try:
+ Num = decimal.Decimal(num)
+ except decimal.InvalidOperation:
+ pass
+ else:
+ isint = '.' not in num
+ num, dps = _decimal_to_Rational_prec(Num)
+ if num.is_Integer and isint:
+ dps = max(dps, len(str(num).lstrip('-')))
+ dps = max(15, dps)
+ elif prec == '':
if not isinstance(num, string_types):
raise ValueError('The null string can only be used when '
'the number to Float is passed as a string or an integer.')
| N(<decimal string>) limited to double precision
Is input like `N('1.23')` supposed to work? It is limited to double precision.
````
In [18]: s = str(pi.evalf(1024)) # very accurate pi string
In [19]: a = Float(s, 128)
In [20]: sin(a) # looks good
Out[20]: -3.3218e-130
In [21]:
In [21]: b = N(s, 128)
In [22]: sin(b) # not good
Out[22]: 0.00000000000000012246467991473531772260659322749979970830539012997919494882577162608696099732581037750932552756901365545642854007441419
````
Let's look at the `N` code:
````
return sympify(x).evalf(n, **options
````
So this happens because `N` runs `sympify(str)` which has no knowledge of `n`.
It should be easy enough to special-case strings that contain a decimal point (and only digits). We could call Float directly in those cases.
Even so, some cases that would still lose precision: `N('1.0*x')`, `N('1.0/3.0',128)` but meh, diminishing returns at some point! | sympy/sympy | diff --git a/sympy/core/tests/test_evalf.py b/sympy/core/tests/test_evalf.py
index a09c932276..e5d222bb24 100644
--- a/sympy/core/tests/test_evalf.py
+++ b/sympy/core/tests/test_evalf.py
@@ -1,7 +1,7 @@
-from sympy import (Add, ceiling, cos, E, Eq, exp, factorial, fibonacci, floor,
- Function, GoldenRatio, I, log, Mul, oo, pi, Pow, Rational,
- sin, sqrt, sstr, sympify, S, integrate, atan, product,
- Sum, Product, Integral)
+from sympy import (Abs, Add, atan, ceiling, cos, E, Eq, exp, factorial,
+ fibonacci, floor, Function, GoldenRatio, I, Integral,
+ integrate, log, Mul, N, oo, pi, Pow, product, Product,
+ Rational, S, Sum, sin, sqrt, sstr, sympify)
from sympy.core.evalf import complex_accuracy, PrecisionExhausted, scaled_zero
from sympy.core.compatibility import long
from mpmath import inf, ninf
@@ -447,3 +447,11 @@ def test_evalf_integral():
# test that workprec has to increase in order to get a result other than 0
eps = Rational(1, 1000000)
assert Integral(sin(x), (x, -pi, pi + eps)).n(2)._prec == 10
+
+
+def test_issue_8821_highprec_from_str():
+ s = str(pi.evalf(128))
+ p = N(s)
+ assert Abs(sin(p)) < 1e-15
+ p = N(s, 64)
+ assert Abs(sin(p)) < 1e-64
diff --git a/sympy/core/tests/test_function.py b/sympy/core/tests/test_function.py
index c2e0a18695..8701480bc7 100644
--- a/sympy/core/tests/test_function.py
+++ b/sympy/core/tests/test_function.py
@@ -603,10 +603,11 @@ def test_nfloat():
eq = x**(S(4)/3) + 4*x**(x/3)/3
assert _aresame(nfloat(eq), x**(S(4)/3) + (4.0/3)*x**(x/3))
big = 12345678901234567890
- Float_big = Float(big)
- assert _aresame(nfloat(x**big, exponent=True),
- x**Float_big)
+ # specify precision to match value used in nfloat
+ Float_big = Float(big, 15)
assert _aresame(nfloat(big), Float_big)
+ assert _aresame(nfloat(big*x), Float_big*x)
+ assert _aresame(nfloat(x**big, exponent=True), x**Float_big)
assert nfloat({x: sqrt(2)}) == {x: nfloat(sqrt(2))}
assert nfloat({sqrt(2): x}) == {sqrt(2): x}
assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2)))
diff --git a/sympy/core/tests/test_numbers.py b/sympy/core/tests/test_numbers.py
index 0f5cc1a10e..58b5980cab 100644
--- a/sympy/core/tests/test_numbers.py
+++ b/sympy/core/tests/test_numbers.py
@@ -403,11 +403,13 @@ def teq(a):
teq(2*pi)
teq(cos(0.1, evaluate=False))
+ # long integer
i = 12345678901234567890
assert _aresame(Float(12, ''), Float('12', ''))
assert _aresame(Float(Integer(i), ''), Float(i, ''))
assert _aresame(Float(i, ''), Float(str(i), 20))
- assert not _aresame(Float(str(i)), Float(i, ''))
+ assert _aresame(Float(str(i)), Float(i, ''))
+ assert _aresame(Float(i), Float(i, ''))
# inexact floats (repeating binary = denom not multiple of 2)
# cannot have precision greater than 15
@@ -451,6 +453,11 @@ def teq(a):
assert '{0:.35f}'.format(Float(pi.n(40), 40)) == '3.14159265358979323846264338327950288'
+def test_Float_default_to_highprec_from_str():
+ s = str(pi.evalf(128))
+ assert _aresame(Float(s), Float(s, ''))
+
+
def test_Float_eval():
a = Float(3.2)
assert (a**2).is_Float
diff --git a/sympy/core/tests/test_sympify.py b/sympy/core/tests/test_sympify.py
index 147c9dcdd7..2dff7a3b1e 100644
--- a/sympy/core/tests/test_sympify.py
+++ b/sympy/core/tests/test_sympify.py
@@ -1,6 +1,6 @@
-from sympy import Symbol, exp, Integer, Float, sin, cos, log, Poly, Lambda, \
- Function, I, S, sqrt, srepr, Rational, Tuple, Matrix, Interval, Add, Mul,\
- Pow, Or, true, false
+from sympy import (Symbol, exp, Integer, Float, sin, cos, log, Poly, Lambda,
+ Function, I, S, sqrt, srepr, Rational, Tuple, Matrix, Interval, Add, Mul,
+ Pow, Or, true, false, Abs, pi)
from sympy.abc import x, y
from sympy.core.sympify import sympify, _sympify, SympifyError, kernS
from sympy.core.decorators import _sympifyit
@@ -486,3 +486,9 @@ def test_issue_5596():
locals = {}
exec_("from sympy.abc import Q, C", locals)
assert str(S('C&Q', locals)) == 'And(C, Q)'
+
+
+def test_issue_8821_highprec_from_str():
+ s = str(pi.evalf(128))
+ p = sympify(s)
+ assert Abs(sin(p)) < 1e-127
| {
"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.7 | {
"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",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"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
coverage==6.2
execnet==1.9.0
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
mpmath==1.3.0
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
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
-e git+https://github.com/sympy/sympy.git@50b4f3d9cd37aa56fde564ecd13b2928f22f4316#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tomli==1.2.3
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==6.2
- execnet==1.9.0
- mpmath==1.3.0
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- tomli==1.2.3
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_evalf.py::test_issue_8821_highprec_from_str",
"sympy/core/tests/test_numbers.py::test_Float",
"sympy/core/tests/test_numbers.py::test_Float_default_to_highprec_from_str",
"sympy/core/tests/test_sympify.py::test_issue_8821_highprec_from_str"
] | [
"sympy/core/tests/test_sympify.py::test_lambda_raises"
] | [
"sympy/core/tests/test_evalf.py::test_evalf_helpers",
"sympy/core/tests/test_evalf.py::test_evalf_basic",
"sympy/core/tests/test_evalf.py::test_cancellation",
"sympy/core/tests/test_evalf.py::test_evalf_powers",
"sympy/core/tests/test_evalf.py::test_evalf_rump",
"sympy/core/tests/test_evalf.py::test_evalf_complex",
"sympy/core/tests/test_evalf.py::test_evalf_complex_powers",
"sympy/core/tests/test_evalf.py::test_evalf_exponentiation",
"sympy/core/tests/test_evalf.py::test_evalf_complex_cancellation",
"sympy/core/tests/test_evalf.py::test_evalf_logs",
"sympy/core/tests/test_evalf.py::test_evalf_trig",
"sympy/core/tests/test_evalf.py::test_evalf_near_integers",
"sympy/core/tests/test_evalf.py::test_evalf_ramanujan",
"sympy/core/tests/test_evalf.py::test_evalf_bugs",
"sympy/core/tests/test_evalf.py::test_evalf_integer_parts",
"sympy/core/tests/test_evalf.py::test_evalf_trig_zero_detection",
"sympy/core/tests/test_evalf.py::test_evalf_sum",
"sympy/core/tests/test_evalf.py::test_evalf_divergent_series",
"sympy/core/tests/test_evalf.py::test_evalf_product",
"sympy/core/tests/test_evalf.py::test_evalf_py_methods",
"sympy/core/tests/test_evalf.py::test_evalf_power_subs_bugs",
"sympy/core/tests/test_evalf.py::test_evalf_arguments",
"sympy/core/tests/test_evalf.py::test_implemented_function_evalf",
"sympy/core/tests/test_evalf.py::test_evaluate_false",
"sympy/core/tests/test_evalf.py::test_evalf_relational",
"sympy/core/tests/test_evalf.py::test_issue_5486",
"sympy/core/tests/test_evalf.py::test_issue_5486_bug",
"sympy/core/tests/test_evalf.py::test_bugs",
"sympy/core/tests/test_evalf.py::test_subs",
"sympy/core/tests/test_evalf.py::test_issue_4956_5204",
"sympy/core/tests/test_evalf.py::test_old_docstring",
"sympy/core/tests/test_evalf.py::test_issue_4806",
"sympy/core/tests/test_evalf.py::test_evalf_mul",
"sympy/core/tests/test_evalf.py::test_scaled_zero",
"sympy/core/tests/test_evalf.py::test_chop_value",
"sympy/core/tests/test_evalf.py::test_infinities",
"sympy/core/tests/test_evalf.py::test_to_mpmath",
"sympy/core/tests/test_evalf.py::test_issue_6632_evalf",
"sympy/core/tests/test_evalf.py::test_issue_4945",
"sympy/core/tests/test_evalf.py::test_evalf_integral",
"sympy/core/tests/test_function.py::test_f_expand_complex",
"sympy/core/tests/test_function.py::test_bug1",
"sympy/core/tests/test_function.py::test_general_function",
"sympy/core/tests/test_function.py::test_derivative_subs_bug",
"sympy/core/tests/test_function.py::test_derivative_subs_self_bug",
"sympy/core/tests/test_function.py::test_derivative_linearity",
"sympy/core/tests/test_function.py::test_derivative_evaluate",
"sympy/core/tests/test_function.py::test_diff_symbols",
"sympy/core/tests/test_function.py::test_Function",
"sympy/core/tests/test_function.py::test_nargs",
"sympy/core/tests/test_function.py::test_Lambda",
"sympy/core/tests/test_function.py::test_IdentityFunction",
"sympy/core/tests/test_function.py::test_Lambda_symbols",
"sympy/core/tests/test_function.py::test_Lambda_arguments",
"sympy/core/tests/test_function.py::test_Lambda_equality",
"sympy/core/tests/test_function.py::test_Subs",
"sympy/core/tests/test_function.py::test_expand_function",
"sympy/core/tests/test_function.py::test_function_comparable",
"sympy/core/tests/test_function.py::test_deriv1",
"sympy/core/tests/test_function.py::test_deriv2",
"sympy/core/tests/test_function.py::test_func_deriv",
"sympy/core/tests/test_function.py::test_suppressed_evaluation",
"sympy/core/tests/test_function.py::test_function_evalf",
"sympy/core/tests/test_function.py::test_extensibility_eval",
"sympy/core/tests/test_function.py::test_function_non_commutative",
"sympy/core/tests/test_function.py::test_function_complex",
"sympy/core/tests/test_function.py::test_function__eval_nseries",
"sympy/core/tests/test_function.py::test_doit",
"sympy/core/tests/test_function.py::test_evalf_default",
"sympy/core/tests/test_function.py::test_issue_5399",
"sympy/core/tests/test_function.py::test_derivative_numerically",
"sympy/core/tests/test_function.py::test_fdiff_argument_index_error",
"sympy/core/tests/test_function.py::test_deriv_wrt_function",
"sympy/core/tests/test_function.py::test_diff_wrt_value",
"sympy/core/tests/test_function.py::test_diff_wrt",
"sympy/core/tests/test_function.py::test_diff_wrt_func_subs",
"sympy/core/tests/test_function.py::test_diff_wrt_not_allowed",
"sympy/core/tests/test_function.py::test_klein_gordon_lagrangian",
"sympy/core/tests/test_function.py::test_sho_lagrangian",
"sympy/core/tests/test_function.py::test_straight_line",
"sympy/core/tests/test_function.py::test_sort_variable",
"sympy/core/tests/test_function.py::test_unhandled",
"sympy/core/tests/test_function.py::test_issue_4711",
"sympy/core/tests/test_function.py::test_nfloat",
"sympy/core/tests/test_function.py::test_issue_7068",
"sympy/core/tests/test_function.py::test_issue_7231",
"sympy/core/tests/test_function.py::test_issue_7687",
"sympy/core/tests/test_function.py::test_issue_7688",
"sympy/core/tests/test_function.py::test_mexpand",
"sympy/core/tests/test_numbers.py::test_integers_cache",
"sympy/core/tests/test_numbers.py::test_seterr",
"sympy/core/tests/test_numbers.py::test_mod",
"sympy/core/tests/test_numbers.py::test_divmod",
"sympy/core/tests/test_numbers.py::test_igcd",
"sympy/core/tests/test_numbers.py::test_ilcm",
"sympy/core/tests/test_numbers.py::test_igcdex",
"sympy/core/tests/test_numbers.py::test_Integer_new",
"sympy/core/tests/test_numbers.py::test_Rational_new",
"sympy/core/tests/test_numbers.py::test_Number_new",
"sympy/core/tests/test_numbers.py::test_Rational_cmp",
"sympy/core/tests/test_numbers.py::test_Float_eval",
"sympy/core/tests/test_numbers.py::test_Float_issue_2107",
"sympy/core/tests/test_numbers.py::test_Infinity",
"sympy/core/tests/test_numbers.py::test_Infinity_2",
"sympy/core/tests/test_numbers.py::test_Mul_Infinity_Zero",
"sympy/core/tests/test_numbers.py::test_Div_By_Zero",
"sympy/core/tests/test_numbers.py::test_Infinity_inequations",
"sympy/core/tests/test_numbers.py::test_NaN",
"sympy/core/tests/test_numbers.py::test_special_numbers",
"sympy/core/tests/test_numbers.py::test_powers",
"sympy/core/tests/test_numbers.py::test_integer_nthroot_overflow",
"sympy/core/tests/test_numbers.py::test_powers_Integer",
"sympy/core/tests/test_numbers.py::test_powers_Rational",
"sympy/core/tests/test_numbers.py::test_powers_Float",
"sympy/core/tests/test_numbers.py::test_abs1",
"sympy/core/tests/test_numbers.py::test_accept_int",
"sympy/core/tests/test_numbers.py::test_dont_accept_str",
"sympy/core/tests/test_numbers.py::test_int",
"sympy/core/tests/test_numbers.py::test_long",
"sympy/core/tests/test_numbers.py::test_real_bug",
"sympy/core/tests/test_numbers.py::test_bug_sqrt",
"sympy/core/tests/test_numbers.py::test_pi_Pi",
"sympy/core/tests/test_numbers.py::test_no_len",
"sympy/core/tests/test_numbers.py::test_issue_3321",
"sympy/core/tests/test_numbers.py::test_issue_3692",
"sympy/core/tests/test_numbers.py::test_issue_3423",
"sympy/core/tests/test_numbers.py::test_issue_3449",
"sympy/core/tests/test_numbers.py::test_Integer_factors",
"sympy/core/tests/test_numbers.py::test_Rational_factors",
"sympy/core/tests/test_numbers.py::test_issue_4107",
"sympy/core/tests/test_numbers.py::test_IntegerInteger",
"sympy/core/tests/test_numbers.py::test_Rational_gcd_lcm_cofactors",
"sympy/core/tests/test_numbers.py::test_Float_gcd_lcm_cofactors",
"sympy/core/tests/test_numbers.py::test_issue_4611",
"sympy/core/tests/test_numbers.py::test_conversion_to_mpmath",
"sympy/core/tests/test_numbers.py::test_relational",
"sympy/core/tests/test_numbers.py::test_Integer_as_index",
"sympy/core/tests/test_numbers.py::test_Rational_int",
"sympy/core/tests/test_numbers.py::test_zoo",
"sympy/core/tests/test_numbers.py::test_issue_4122",
"sympy/core/tests/test_numbers.py::test_GoldenRatio_expand",
"sympy/core/tests/test_numbers.py::test_as_content_primitive",
"sympy/core/tests/test_numbers.py::test_hashing_sympy_integers",
"sympy/core/tests/test_numbers.py::test_issue_4172",
"sympy/core/tests/test_numbers.py::test_Catalan_EulerGamma_prec",
"sympy/core/tests/test_numbers.py::test_Float_eq",
"sympy/core/tests/test_numbers.py::test_int_NumberSymbols",
"sympy/core/tests/test_numbers.py::test_issue_6640",
"sympy/core/tests/test_numbers.py::test_issue_6349",
"sympy/core/tests/test_numbers.py::test_mpf_norm",
"sympy/core/tests/test_numbers.py::test_latex",
"sympy/core/tests/test_numbers.py::test_issue_7742",
"sympy/core/tests/test_numbers.py::test_simplify_AlgebraicNumber",
"sympy/core/tests/test_sympify.py::test_issue_3538",
"sympy/core/tests/test_sympify.py::test_sympify1",
"sympy/core/tests/test_sympify.py::test_sympify_Fraction",
"sympy/core/tests/test_sympify.py::test_sympify_gmpy",
"sympy/core/tests/test_sympify.py::test_sympify_mpmath",
"sympy/core/tests/test_sympify.py::test_sympify2",
"sympy/core/tests/test_sympify.py::test_sympify3",
"sympy/core/tests/test_sympify.py::test_sympify_keywords",
"sympy/core/tests/test_sympify.py::test_sympify_float",
"sympy/core/tests/test_sympify.py::test_sympify_bool",
"sympy/core/tests/test_sympify.py::test_sympyify_iterables",
"sympy/core/tests/test_sympify.py::test_sympify4",
"sympy/core/tests/test_sympify.py::test_sympify_text",
"sympy/core/tests/test_sympify.py::test_sympify_function",
"sympy/core/tests/test_sympify.py::test_sympify_poly",
"sympy/core/tests/test_sympify.py::test_sympify_factorial",
"sympy/core/tests/test_sympify.py::test_sage",
"sympy/core/tests/test_sympify.py::test_issue_3595",
"sympy/core/tests/test_sympify.py::test_lambda",
"sympy/core/tests/test_sympify.py::test_sympify_raises",
"sympy/core/tests/test_sympify.py::test__sympify",
"sympy/core/tests/test_sympify.py::test_sympifyit",
"sympy/core/tests/test_sympify.py::test_int_float",
"sympy/core/tests/test_sympify.py::test_evaluate_false",
"sympy/core/tests/test_sympify.py::test_issue_4133",
"sympy/core/tests/test_sympify.py::test_issue_3982",
"sympy/core/tests/test_sympify.py::test_S_sympify",
"sympy/core/tests/test_sympify.py::test_issue_4788",
"sympy/core/tests/test_sympify.py::test_issue_4798_None",
"sympy/core/tests/test_sympify.py::test_issue_3218",
"sympy/core/tests/test_sympify.py::test_issue_4988_builtins",
"sympy/core/tests/test_sympify.py::test_geometry",
"sympy/core/tests/test_sympify.py::test_kernS",
"sympy/core/tests/test_sympify.py::test_issue_6540_6552",
"sympy/core/tests/test_sympify.py::test_issue_5596"
] | [] | BSD | 23 |
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 |
|
sympy__sympy-8835 | 50b4f3d9cd37aa56fde564ecd13b2928f22f4316 | 2015-01-16 19:22:37 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index d4dc69328e..99384d5de7 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -683,6 +683,12 @@ class Interval(Set, EvalfMixin):
[0, 1]
>>> Interval(0, 1, False, True)
[0, 1)
+ >>> Interval.Ropen(0, 1)
+ [0, 1)
+ >>> Interval.Lopen(0, 1)
+ (0, 1]
+ >>> Interval.open(0, 1)
+ (0, 1)
>>> a = Symbol('a', real=True)
>>> Interval(0, a)
@@ -763,6 +769,21 @@ def start(self):
_inf = left = start
+ @classmethod
+ def open(cls, a, b):
+ """Return an interval including neither boundary."""
+ return cls(a, b, True, True)
+
+ @classmethod
+ def Lopen(cls, a, b):
+ """Return an interval not including the left boundary."""
+ return cls(a, b, True, False)
+
+ @classmethod
+ def Ropen(cls, a, b):
+ """Return an interval not including the right boundary."""
+ return cls(a, b, False, True)
+
@property
def end(self):
"""
| Interval convenience methods
In one of the tests files I noticed helper functions (OpenInterval, RightOpenInterval, LeftOpenInterval) that might be good to add. Here's one suggestion of how to do so with slightly different names:
```diff
diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index d6df8bd..972f80e 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -683,6 +683,8 @@ class Interval(Set, EvalfMixin):
[0, 1]
>>> Interval(0, 1, False, True)
[0, 1)
+ >>> Interval.Ropen(0, 1)
+ [0, 1)
>>> a = Symbol('a', real=True)
>>> Interval(0, a)
@@ -763,6 +765,21 @@ def start(self):
_inf = left = start
+ @classmethod
+ def open(cls, a, b):
+ """Return an interval including neither boundary."""
+ return cls(a, b, True, True)
+
+ @classmethod
+ def Lopen(cls, a, b):
+ """Return an interval not including the left boundary."""
+ return cls(a, b, True, False)
+
+ @classmethod
+ def Ropen(cls, a, b):
+ """Return an interval not including the right boundary."""
+ return cls(a, b, False, True)
+
@property
def end(self):
"""
``` | sympy/sympy | diff --git a/sympy/solvers/tests/test_inequalities.py b/sympy/solvers/tests/test_inequalities.py
index 09358bb75b..e6f5622167 100644
--- a/sympy/solvers/tests/test_inequalities.py
+++ b/sympy/solvers/tests/test_inequalities.py
@@ -138,42 +138,35 @@ def test_reduce_poly_inequalities_complex_relational():
def test_reduce_rational_inequalities_real_relational():
- def OpenInterval(a, b):
- return Interval(a, b, True, True)
- def LeftOpenInterval(a, b):
- return Interval(a, b, True, False)
- def RightOpenInterval(a, b):
- return Interval(a, b, False, True)
-
assert reduce_rational_inequalities([], x) == False
assert reduce_rational_inequalities(
[[(x**2 + 3*x + 2)/(x**2 - 16) >= 0]], x, relational=False) == \
- Union(OpenInterval(-oo, -4), Interval(-2, -1), OpenInterval(4, oo))
+ Union(Interval.open(-oo, -4), Interval(-2, -1), Interval.open(4, oo))
assert reduce_rational_inequalities(
[[((-2*x - 10)*(3 - x))/((x**2 + 5)*(x - 2)**2) < 0]], x,
relational=False) == \
- Union(OpenInterval(-5, 2), OpenInterval(2, 3))
+ Union(Interval.open(-5, 2), Interval.open(2, 3))
assert reduce_rational_inequalities([[(x + 1)/(x - 5) <= 0]], x,
relational=False) == \
- RightOpenInterval(-1, 5)
+ Interval.Ropen(-1, 5)
assert reduce_rational_inequalities([[(x**2 + 4*x + 3)/(x - 1) > 0]], x,
relational=False) == \
- Union(OpenInterval(-3, -1), OpenInterval(1, oo))
+ Union(Interval.open(-3, -1), Interval.open(1, oo))
assert reduce_rational_inequalities([[(x**2 - 16)/(x - 1)**2 < 0]], x,
relational=False) == \
- Union(OpenInterval(-4, 1), OpenInterval(1, 4))
+ Union(Interval.open(-4, 1), Interval.open(1, 4))
assert reduce_rational_inequalities([[(3*x + 1)/(x + 4) >= 1]], x,
relational=False) == \
- Union(OpenInterval(-oo, -4), RightOpenInterval(S(3)/2, oo))
+ Union(Interval.open(-oo, -4), Interval.Ropen(S(3)/2, oo))
assert reduce_rational_inequalities([[(x - 8)/x <= 3 - x]], x,
relational=False) == \
- Union(LeftOpenInterval(-oo, -2), LeftOpenInterval(0, 4))
+ Union(Interval.Lopen(-oo, -2), Interval.Lopen(0, 4))
def test_reduce_abs_inequalities():
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"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
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
mpmath==1.3.0
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/sympy/sympy.git@50b4f3d9cd37aa56fde564ecd13b2928f22f4316#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/solvers/tests/test_inequalities.py::test_reduce_rational_inequalities_real_relational"
] | [] | [
"sympy/solvers/tests/test_inequalities.py::test_solve_poly_inequality",
"sympy/solvers/tests/test_inequalities.py::test_reduce_poly_inequalities_real_interval",
"sympy/solvers/tests/test_inequalities.py::test_reduce_poly_inequalities_complex_relational",
"sympy/solvers/tests/test_inequalities.py::test_reduce_abs_inequalities",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_general",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_boolean",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_multivariate",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_errors",
"sympy/solvers/tests/test_inequalities.py::test_hacky_inequalities",
"sympy/solvers/tests/test_inequalities.py::test_issue_6343",
"sympy/solvers/tests/test_inequalities.py::test_issue_8235",
"sympy/solvers/tests/test_inequalities.py::test_issue_5526",
"sympy/solvers/tests/test_inequalities.py::test_solve_univariate_inequality",
"sympy/solvers/tests/test_inequalities.py::test_slow_general_univariate",
"sympy/solvers/tests/test_inequalities.py::test_issue_8545"
] | [] | BSD | 25 |
|
sympy__sympy-8837 | 998a9100f3c8493a2b6f1ff10c02024f36d48811 | 2015-01-16 20:55:40 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | asmeurer: Why not use `a**(k/n)`?
smichr: I guess the former can be used for 0<k<n; what I have is correct for arbitrary integer values (so one may index the roots with negative values if desired. If the user specifies an integer for k, I could use your form, otherwise the form that I have. How does sound?
smichr: > Why not use a**(k/n)
I think you mean (for a < 0): `a**(1/n)*(-1)**(k/n)`...or maybe I am misunderstanding something:
```
>>> from sympy.polys.polyutils import _nsort
>>> _nsort([(2*(-1)**(i/S(5))).n(2) for i in range(1,6)])
[-2.0, -1.6 + 1.2*I, -0.62 + 1.9*I, 0.62 + 1.9*I, 1.6 + 1.2*I]
>>> _nsort([(2**(S(1)/5)*(-1)**(i/S(5))).n(2) for i in range(1,6)])
[-1.1, -0.93 + 0.67*I, -0.35 + 1.1*I, 0.35 + 1.1*I, 0.93 + 0.67*I]
>>> _nsort([(2**(S(1)/5)*(-1)**(i/S(5))).n(2) for i in range(1,6)])
[-1.1, -0.93 + 0.67*I, -0.35 + 1.1*I, 0.35 + 1.1*I, 0.93 + 0.67*I]
```
asmeurer: Yes I think I mean that.
smichr: Ahh...kth nth root of x is `root(x, n)*(-1)**(2*k/n)` (note the factor of 2). This has been rewritten in those terms. You can see the doctests for examples. | diff --git a/sympy/functions/elementary/exponential.py b/sympy/functions/elementary/exponential.py
index 1b1c03f781..54bc5031d3 100644
--- a/sympy/functions/elementary/exponential.py
+++ b/sympy/functions/elementary/exponential.py
@@ -157,7 +157,11 @@ def _eval_evalf(self, prec):
""" Careful! any evalf of polar numbers is flaky """
from sympy import im, pi, re
i = im(self.args[0])
- if i <= -pi or i > pi:
+ try:
+ bad = (i <= -pi or i > pi)
+ except TypeError:
+ bad = True
+ if bad:
return self # cannot evalf for this argument
res = exp(self.args[0])._eval_evalf(prec)
if i > 0 and im(res) < 0:
diff --git a/sympy/functions/elementary/miscellaneous.py b/sympy/functions/elementary/miscellaneous.py
index 5684ea665f..cbdbe08603 100644
--- a/sympy/functions/elementary/miscellaneous.py
+++ b/sympy/functions/elementary/miscellaneous.py
@@ -162,10 +162,9 @@ def cbrt(arg):
return C.Pow(arg, C.Rational(1, 3))
-def root(arg, n):
- """The n-th root function (a shortcut for ``arg**(1/n)``)
-
- root(x, n) -> Returns the principal n-th root of x.
+def root(arg, n, k=0):
+ """root(x, n, k) -> Returns the k-th n-th root of x, defaulting to the
+ principle root (k=0).
Examples
@@ -186,6 +185,10 @@ def root(arg, n):
>>> root(x, -Rational(2, 3))
x**(-3/2)
+ To get the k-th n-th root, specify k:
+
+ >>> root(-2, 3, 2)
+ -(-1)**(2/3)*2**(1/3)
To get all n n-th roots you can use the RootOf function.
The following examples show the roots of unity for n
@@ -193,13 +196,13 @@ def root(arg, n):
>>> from sympy import RootOf, I
- >>> [ RootOf(x**2-1,i) for i in (0,1) ]
+ >>> [ RootOf(x**2 - 1, i) for i in range(2) ]
[-1, 1]
- >>> [ RootOf(x**3-1,i) for i in (0,1,2) ]
+ >>> [ RootOf(x**3 - 1,i) for i in range(3) ]
[1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2]
- >>> [ RootOf(x**4-1,i) for i in (0,1,2,3) ]
+ >>> [ RootOf(x**4 - 1,i) for i in range(4) ]
[-1, 1, -I, I]
SymPy, like other symbolic algebra systems, returns the
@@ -211,8 +214,8 @@ def root(arg, n):
>>> root(-8, 3)
2*(-1)**(1/3)
- The real_root function can be used to either make such a result
- real or simply return the real root in the first place:
+ The real_root function can be used to either make the principle
+ result real (or simply to return the real root directly):
>>> from sympy import real_root
>>> real_root(_)
@@ -220,6 +223,12 @@ def root(arg, n):
>>> real_root(-32, 5)
-2
+ Alternatively, the n//2-th n-th root of a negative number can be
+ computed with root:
+
+ >>> root(-32, 5, 5//2)
+ -2
+
See Also
========
@@ -238,12 +247,16 @@ def root(arg, n):
"""
n = sympify(n)
+ if k:
+ return C.Pow(arg, S.One/n)*S.NegativeOne**(2*k/n)
return C.Pow(arg, 1/n)
def real_root(arg, n=None):
"""Return the real nth-root of arg if possible. If n is omitted then
- all instances of (-n)**(1/odd) will be changed to -n**(1/odd).
+ all instances of (-n)**(1/odd) will be changed to -n**(1/odd); this
+ will only create a real root of a principle root -- the presence of
+ other factors may cause the result to not be real.
Examples
========
@@ -258,6 +271,15 @@ def real_root(arg, n=None):
>>> real_root(_)
-2
+ If one creates a non-principle root and applies real_root, the
+ result will not be real (so use with caution):
+
+ >>> root(-8, 3, 2)
+ -2*(-1)**(2/3)
+ >>> real_root(_)
+ -2*(-1)**(2/3)
+
+
See Also
========
@@ -266,10 +288,20 @@ def real_root(arg, n=None):
root, sqrt
"""
if n is not None:
- n = as_int(n)
- rv = C.Pow(arg, Rational(1, n))
- if n % 2 == 0:
- return rv
+ try:
+ n = as_int(n)
+ arg = sympify(arg)
+ if arg.is_positive or arg.is_negative:
+ rv = root(arg, n)
+ else:
+ raise ValueError
+ except ValueError:
+ return root(arg, n)*C.Piecewise(
+ (S.One, ~C.Equality(C.im(arg), 0)),
+ (C.Pow(S.NegativeOne, S.One/n)**(2*C.floor(n/2)), C.And(
+ C.Equality(n % 2, 1),
+ arg < 0)),
+ (S.One, True))
else:
rv = sympify(arg)
n1pow = Transform(lambda x: -(-x.base)**x.exp,
diff --git a/sympy/solvers/solvers.py b/sympy/solvers/solvers.py
index 306ffa845e..f3c6dc5752 100644
--- a/sympy/solvers/solvers.py
+++ b/sympy/solvers/solvers.py
@@ -741,14 +741,12 @@ def solve(f, *symbols, **flags):
>>> expr = root(x, 3) - root(x, 5)
We will construct a known value for this expression at x = 3 by selecting
- a non-principle root for each (i.e. multiplying by a power of the same
- root of -1):
+ the 1-th root for each radical:
- >>> expr1 = root(x, 3)*root(-1, 3)**2 - root(x, 5)*root(-1, 5)**2
+ >>> expr1 = root(x, 3, 1) - root(x, 5, 1)
>>> v = expr1.subs(x, -3)
- The solve function is unable to find any exact roots to this equation in
- either form:
+ The solve function is unable to find any exact roots to this equation:
>>> eq = Eq(expr, v); eq1 = Eq(expr1, v)
>>> solve(eq, check=False), solve(eq1, check=False)
| create Root object
Although some of this is discussed in [here](https://groups.google.com/forum/#!searchin/sympy/Fateman/sympy/40d-NGT_gF4/SJCETmfTfbkJ) I did not want this issue to get buried in the discussion. When solving a radical expression like the following, SymPy's use of the principle root make solve miss a solution:
```
>>> eq
-x + (x**3 - 3*x**2)**(1/3) + 4/3
>>> solve(_, check=0)
[-8*sqrt(6)/9 + 8/3, 8*sqrt(6)/9 + 8/3] <--------- both are solutions (as can be seen graphically)
>>> [eq.subs(x,i).n() for i in _]
[1.2659863237109 + 0.730917544784875*I, 0.e-124] <-- the first one does not appear to be a soln
Here's a case where the root is rational:
>>> eq=eq-S(1)/3; eq
-x + (x**3 - 3*x**2)**(1/3) + 4/3
>>> solve(eq)
[]
>>> solve(eq, check=False)
[1/3]
>>> eq.subs(x,S(1)/3)
2/3 + 2*(-1)**(1/3)/3
```
The 1/3 does not appear to be a solution because the principle value of the root is being used rather than the real value:
```
>>> root(-1,3).n()
0.5 + 0.866025403784439*I
>>> real_root(-1, 3)
-1
```
Note that nsolve cannot find the root either because of this issue:
```
>>> nsolve(eq,.33)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "sympy\solvers\solvers.py", line 2532, in nsolve
return findroot(f, x0, **kwargs)
File "c:\Python26\lib\site-packages\mpmath\calculus\optimization.py", line 975
, in findroot
% (norm(f(*xl))**2, tol))
ValueError: Could not find root within given tolerance. (2.60832 > 2.1684e-19)
Try another starting point or tweak arguments.
>>> nsolve(eq,.33+.01j) # try an initial guess that is off the real axis
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "sympy\solvers\solvers.py", line 2532, in nsolve
return findroot(f, x0, **kwargs)
File "c:\Python26\lib\site-packages\mpmath\calculus\optimization.py", line 975
, in findroot
% (norm(f(*xl))**2, tol))
ValueError: Could not find root within given tolerance. (2.60832 > 2.1684e-19)
Try another starting point or tweak arguments.
```
How should a formula be written that will allow one to verify that 1/3 is a solution? | sympy/sympy | diff --git a/sympy/functions/elementary/tests/test_miscellaneous.py b/sympy/functions/elementary/tests/test_miscellaneous.py
index 883ad265f8..a2b68fb296 100644
--- a/sympy/functions/elementary/tests/test_miscellaneous.py
+++ b/sympy/functions/elementary/tests/test_miscellaneous.py
@@ -185,6 +185,7 @@ def test_issue_8413():
def test_root():
from sympy.abc import x
n = Symbol('n', integer=True)
+ k = Symbol('k', integer=True)
assert root(2, 2) == sqrt(2)
assert root(2, 1) == 2
@@ -206,6 +207,8 @@ def test_root():
assert root(x, n) == x**(1/n)
assert root(x, -n) == x**(-1/n)
+ assert root(x, n, k) == x**(1/n)*(-1)**(2*k/n)
+
def test_real_root():
assert real_root(-8, 3) == -2
@@ -218,6 +221,16 @@ def test_real_root():
assert real_root(r1 + r2 + r3) == -1 + r2 + r3
assert real_root(root(-2, 3)) == -root(2, 3)
assert real_root(-8., 3) == -2
+ x = Symbol('x')
+ n = Symbol('n')
+ g = real_root(x, n)
+ assert g.subs(dict(x=-8, n=3)) == -2
+ assert g.subs(dict(x=8, n=3)) == 2
+ # give principle root if there is no real root -- if this is not desired
+ # then maybe a Root class is needed to raise an error instead
+ assert g.subs(dict(x=I, n=3)) == cbrt(I)
+ assert g.subs(dict(x=-8, n=2)) == sqrt(-8)
+ assert g.subs(dict(x=I, n=2)) == sqrt(I)
def test_rewrite_MaxMin_as_Heaviside():
| {
"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": 2,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 3
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "mpmath>=0.19",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"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
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.2.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
-e git+https://github.com/sympy/sympy.git@998a9100f3c8493a2b6f1ff10c02024f36d48811#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
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
- mpmath=1.2.1=py36h06a4308_0
- 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
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/sympy
| [
"sympy/functions/elementary/tests/test_miscellaneous.py::test_root",
"sympy/functions/elementary/tests/test_miscellaneous.py::test_real_root"
] | [] | [
"sympy/functions/elementary/tests/test_miscellaneous.py::test_Min",
"sympy/functions/elementary/tests/test_miscellaneous.py::test_Max",
"sympy/functions/elementary/tests/test_miscellaneous.py::test_issue_8413",
"sympy/functions/elementary/tests/test_miscellaneous.py::test_rewrite_MaxMin_as_Heaviside"
] | [] | BSD | 26 |
sympy__sympy-8841 | 50b4f3d9cd37aa56fde564ecd13b2928f22f4316 | 2015-01-17 20:39:55 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/simplify/simplify.py b/sympy/simplify/simplify.py
index d08a81fea1..b6e9604548 100755
--- a/sympy/simplify/simplify.py
+++ b/sympy/simplify/simplify.py
@@ -2703,9 +2703,13 @@ def update(b):
bases = []
for b, e in c_powers:
b, e = bkey(b, e)
- common_b[b] = e
+ if b in common_b.keys():
+ common_b[b] = common_b[b] + e
+ else:
+ common_b[b] = e
if b[1] != 1 and b[0].is_Mul:
bases.append(b)
+ c_powers = [(b, e) for b, e in common_b.items() if e]
bases.sort(key=default_sort_key) # this makes tie-breaking canonical
bases.sort(key=measure, reverse=True) # handle longest first
for base in bases:
| powsimp drops factor
```python
>>> a,b=exp(I*pi/3),root(-1,3)
>>> powsimp(a)
exp(I*pi/3)
>>> powsimp(b)
(-1)**(1/3)
>>> a*b
(-1)**(1/3)*exp(I*pi/3)
>>> powsimp(_)
(-1)**(1/3)
>>> _.n(2)
0.5 + 0.87*I
>>> (a*b).n(2)
-0.5 + 0.87*I
```
The problem is with bkey which, for exp(I*pi/3), returns
```python
>>> bkey(exp(I*pi/3))
((-1, 3), 1)
``` | sympy/sympy | diff --git a/sympy/simplify/tests/test_simplify.py b/sympy/simplify/tests/test_simplify.py
index 2b20e608a7..a189d5d29d 100644
--- a/sympy/simplify/tests/test_simplify.py
+++ b/sympy/simplify/tests/test_simplify.py
@@ -682,6 +682,8 @@ def test_powsimp():
assert all(powsimp(e) == e for e in (sqrt(x**a), sqrt(x**2)))
+ # issue 8836
+ assert str( powsimp(exp(I*pi/3)*root(-1,3)) ) == '(-1)**(2/3)'
def test_issue_6367():
z = -5*sqrt(2)/(2*sqrt(2*sqrt(29) + 29)) + sqrt(-sqrt(29)/29 + S(1)/2)
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"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.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
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
mpmath==1.3.0
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/sympy/sympy.git@50b4f3d9cd37aa56fde564ecd13b2928f22f4316#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/simplify/tests/test_simplify.py::test_powsimp"
] | [] | [
"sympy/simplify/tests/test_simplify.py::test_ratsimp",
"sympy/simplify/tests/test_simplify.py::test_ratsimpmodprime",
"sympy/simplify/tests/test_simplify.py::test_trigsimp1",
"sympy/simplify/tests/test_simplify.py::test_trigsimp1a",
"sympy/simplify/tests/test_simplify.py::test_trigsimp2",
"sympy/simplify/tests/test_simplify.py::test_issue_4373",
"sympy/simplify/tests/test_simplify.py::test_trigsimp3",
"sympy/simplify/tests/test_simplify.py::test_issue_4661",
"sympy/simplify/tests/test_simplify.py::test_issue_4494",
"sympy/simplify/tests/test_simplify.py::test_issue_5948",
"sympy/simplify/tests/test_simplify.py::test_issue_4775",
"sympy/simplify/tests/test_simplify.py::test_issue_4280",
"sympy/simplify/tests/test_simplify.py::test_issue_3210",
"sympy/simplify/tests/test_simplify.py::test_issue_7263",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_issues",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_issue_2515",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_issue_3826",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_issue_4032",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_issue_7761",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_noncommutative",
"sympy/simplify/tests/test_simplify.py::test_hyperbolic_simp",
"sympy/simplify/tests/test_simplify.py::test_trigsimp_groebner",
"sympy/simplify/tests/test_simplify.py::test_simplify_expr",
"sympy/simplify/tests/test_simplify.py::test_issue_3557",
"sympy/simplify/tests/test_simplify.py::test_simplify_other",
"sympy/simplify/tests/test_simplify.py::test_simplify_complex",
"sympy/simplify/tests/test_simplify.py::test_simplify_ratio",
"sympy/simplify/tests/test_simplify.py::test_simplify_measure",
"sympy/simplify/tests/test_simplify.py::test_simplify_issue_1308",
"sympy/simplify/tests/test_simplify.py::test_issue_5652",
"sympy/simplify/tests/test_simplify.py::test_simplify_fail1",
"sympy/simplify/tests/test_simplify.py::test_fraction",
"sympy/simplify/tests/test_simplify.py::test_issue_6367",
"sympy/simplify/tests/test_simplify.py::test_powsimp_negated_base",
"sympy/simplify/tests/test_simplify.py::test_issue_6440",
"sympy/simplify/tests/test_simplify.py::test_powsimp_polar",
"sympy/simplify/tests/test_simplify.py::test_powsimp_nc",
"sympy/simplify/tests/test_simplify.py::test_nthroot",
"sympy/simplify/tests/test_simplify.py::test_nthroot1",
"sympy/simplify/tests/test_simplify.py::test_collect_1",
"sympy/simplify/tests/test_simplify.py::test_collect_2",
"sympy/simplify/tests/test_simplify.py::test_collect_3",
"sympy/simplify/tests/test_simplify.py::test_collect_4",
"sympy/simplify/tests/test_simplify.py::test_collect_5",
"sympy/simplify/tests/test_simplify.py::test_collect_D",
"sympy/simplify/tests/test_simplify.py::test_collect_D_0",
"sympy/simplify/tests/test_simplify.py::test_collect_Wild",
"sympy/simplify/tests/test_simplify.py::test_collect_func",
"sympy/simplify/tests/test_simplify.py::test_collect_order",
"sympy/simplify/tests/test_simplify.py::test_rcollect",
"sympy/simplify/tests/test_simplify.py::test_separatevars",
"sympy/simplify/tests/test_simplify.py::test_separatevars_advanced_factor",
"sympy/simplify/tests/test_simplify.py::test_hypersimp",
"sympy/simplify/tests/test_simplify.py::test_nsimplify",
"sympy/simplify/tests/test_simplify.py::test_extract_minus_sign",
"sympy/simplify/tests/test_simplify.py::test_diff",
"sympy/simplify/tests/test_simplify.py::test_logcombine_1",
"sympy/simplify/tests/test_simplify.py::test_logcombine_complex_coeff",
"sympy/simplify/tests/test_simplify.py::test_posify",
"sympy/simplify/tests/test_simplify.py::test_powdenest",
"sympy/simplify/tests/test_simplify.py::test_powdenest_polar",
"sympy/simplify/tests/test_simplify.py::test_issue_5805",
"sympy/simplify/tests/test_simplify.py::test_issue_4194",
"sympy/simplify/tests/test_simplify.py::test_combsimp",
"sympy/simplify/tests/test_simplify.py::test_issue_5615",
"sympy/simplify/tests/test_simplify.py::test_issue_5728",
"sympy/simplify/tests/test_simplify.py::test_as_content_primitive",
"sympy/simplify/tests/test_simplify.py::test_radsimp",
"sympy/simplify/tests/test_simplify.py::test_radsimp_issue_3214",
"sympy/simplify/tests/test_simplify.py::test_collect_const",
"sympy/simplify/tests/test_simplify.py::test_issue_5933",
"sympy/simplify/tests/test_simplify.py::test_fraction_expand",
"sympy/simplify/tests/test_simplify.py::test_combsimp_gamma",
"sympy/simplify/tests/test_simplify.py::test_polarify",
"sympy/simplify/tests/test_simplify.py::test_unpolarify",
"sympy/simplify/tests/test_simplify.py::test_issue_6097",
"sympy/simplify/tests/test_simplify.py::test_signsimp",
"sympy/simplify/tests/test_simplify.py::test_besselsimp",
"sympy/simplify/tests/test_simplify.py::test_Piecewise",
"sympy/simplify/tests/test_simplify.py::test_polymorphism",
"sympy/simplify/tests/test_simplify.py::test_issue_from_PR1599",
"sympy/simplify/tests/test_simplify.py::test_issue_6811",
"sympy/simplify/tests/test_simplify.py::test_issue_6920",
"sympy/simplify/tests/test_simplify.py::test_issue_7001",
"sympy/simplify/tests/test_simplify.py::test_exptrigsimp",
"sympy/simplify/tests/test_simplify.py::test_issue_2827_trigsimp_methods",
"sympy/simplify/tests/test_simplify.py::test_powsimp_on_numbers",
"sympy/simplify/tests/test_simplify.py::test_inequality_no_auto_simplify"
] | [] | BSD | 27 |
|
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 |
|
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 |
|
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 |
|
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 |
|
sympy__sympy-8846 | 998a9100f3c8493a2b6f1ff10c02024f36d48811 | 2015-01-19 17:12:47 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | smichr: OK, this can be rebased over #8864 and the tests can be added.
aktech: @smichr
Thanks, I will add tests when #8864 gets merged, so that test doesn't fails for this PR.
smichr: Could you pull my evalf branch and rebase this over that and force push it here again? There was another change that needed to be made. Then the other PR can just be closed (since tests will fail) and this one will contain the work of both PRs. If you want to wait until tests pass [here](https://travis-ci.org/smichr/sympy/builds/47805947), however, that would be best.
smichr: (After doing the above then you should be able to add the tests that we talked about in this PR.)
smichr: in commit title: ceilling -> ceiling
aktech: I have squashed all commits to one, shall I push that?
smichr: sure...let's see what that looks like.
aktech: I accidentally messed with that, let me fix that.
aktech: I have squashed all commits in to one. | diff --git a/sympy/core/evalf.py b/sympy/core/evalf.py
index 2d2fc08099..d628fc20a7 100644
--- a/sympy/core/evalf.py
+++ b/sympy/core/evalf.py
@@ -320,7 +320,7 @@ def get_integer_part(expr, no, options, return_ints=False):
def calc_part(expr, nexpr):
nint = int(to_int(nexpr, rnd))
n, c, p, b = nexpr
- if c != 1 and p != 0:
+ if (c != 1 and p != 0) or p < 0:
expr = C.Add(expr, -nint, evaluate=False)
x, _, x_acc, _ = evalf(expr, 10, options)
try:
diff --git a/sympy/functions/special/gamma_functions.py b/sympy/functions/special/gamma_functions.py
index 54f13f745f..21341206e9 100644
--- a/sympy/functions/special/gamma_functions.py
+++ b/sympy/functions/special/gamma_functions.py
@@ -160,6 +160,13 @@ def _eval_is_real(self):
if x.is_positive or x.is_noninteger:
return True
+ def _eval_is_positive(self):
+ x = self.args[0]
+ if x.is_positive:
+ return True
+ elif x.is_noninteger:
+ return floor(x).is_even
+
def _eval_rewrite_as_tractable(self, z):
return C.exp(loggamma(z))
| gamma._eval_is_positive is broken?
The first line in `gamma._eval_is_positive` is `if self.is_number`. Perhaps I don't understand it well, but even if `n` is a positive integer, `gamma(n).is_number` is `False`, and in particular, not positive.
I believe that the following code:
```python
>>> n = Symbol('n', real=True, positive=True)
>>> gamma(n).is_positive
```
should return `True`. | sympy/sympy | diff --git a/sympy/core/tests/test_evalf.py b/sympy/core/tests/test_evalf.py
index e5d222bb24..2d54ba1c4f 100644
--- a/sympy/core/tests/test_evalf.py
+++ b/sympy/core/tests/test_evalf.py
@@ -1,8 +1,9 @@
from sympy import (Abs, Add, atan, ceiling, cos, E, Eq, exp, factorial,
fibonacci, floor, Function, GoldenRatio, I, Integral,
integrate, log, Mul, N, oo, pi, Pow, product, Product,
- Rational, S, Sum, sin, sqrt, sstr, sympify)
-from sympy.core.evalf import complex_accuracy, PrecisionExhausted, scaled_zero
+ Rational, S, Sum, sin, sqrt, sstr, sympify, Symbol)
+from sympy.core.evalf import (complex_accuracy, PrecisionExhausted,
+ scaled_zero, get_integer_part)
from sympy.core.compatibility import long
from mpmath import inf, ninf
from sympy.abc import n, x, y
@@ -455,3 +456,16 @@ def test_issue_8821_highprec_from_str():
assert Abs(sin(p)) < 1e-15
p = N(s, 64)
assert Abs(sin(p)) < 1e-64
+
+
+def test_issue_8853():
+ p = Symbol('x', even=True, positive=True)
+ assert floor(-p - S.Half).is_even == False
+ assert floor(-p + S.Half).is_even == True
+ assert ceiling(p - S.Half).is_even == True
+ assert ceiling(p + S.Half).is_even == False
+
+ assert get_integer_part(S.Half, -1, {}, True) == (0, 0)
+ assert get_integer_part(S.Half, 1, {}, True) == (1, 0)
+ assert get_integer_part(-S.Half, -1, {}, True) == (-1, 0)
+ assert get_integer_part(-S.Half, 1, {}, True) == (0, 0)
diff --git a/sympy/functions/special/tests/test_gamma_functions.py b/sympy/functions/special/tests/test_gamma_functions.py
index 0ae9bc6ba5..ea2e7832ae 100644
--- a/sympy/functions/special/tests/test_gamma_functions.py
+++ b/sympy/functions/special/tests/test_gamma_functions.py
@@ -400,3 +400,21 @@ def test_issue_8657():
assert gamma(o).is_real is True
assert gamma(p).is_real is True
assert gamma(w).is_real is None
+
+
+def test_issue_8524():
+ x = Symbol('x', positive=True)
+ y = Symbol('y', negative=True)
+ z = Symbol('z', positive=False)
+ p = Symbol('p', negative=False)
+ q = Symbol('q', integer=True)
+ r = Symbol('r', integer=False)
+ e = Symbol('e', even=True, negative=True)
+ assert gamma(x).is_positive is True
+ assert gamma(y).is_positive is None
+ assert gamma(z).is_positive is None
+ assert gamma(p).is_positive is None
+ assert gamma(q).is_positive is None
+ assert gamma(r).is_positive is None
+ assert gamma(e + S.Half).is_positive is True
+ assert gamma(e - S.Half).is_positive is False
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"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": "pytest",
"pip_packages": [
"mpmath>=0.19",
"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
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
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
-e git+https://github.com/sympy/sympy.git@998a9100f3c8493a2b6f1ff10c02024f36d48811#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_evalf.py::test_issue_8853",
"sympy/functions/special/tests/test_gamma_functions.py::test_issue_8524"
] | [] | [
"sympy/core/tests/test_evalf.py::test_evalf_helpers",
"sympy/core/tests/test_evalf.py::test_evalf_basic",
"sympy/core/tests/test_evalf.py::test_cancellation",
"sympy/core/tests/test_evalf.py::test_evalf_powers",
"sympy/core/tests/test_evalf.py::test_evalf_rump",
"sympy/core/tests/test_evalf.py::test_evalf_complex",
"sympy/core/tests/test_evalf.py::test_evalf_complex_powers",
"sympy/core/tests/test_evalf.py::test_evalf_exponentiation",
"sympy/core/tests/test_evalf.py::test_evalf_complex_cancellation",
"sympy/core/tests/test_evalf.py::test_evalf_logs",
"sympy/core/tests/test_evalf.py::test_evalf_trig",
"sympy/core/tests/test_evalf.py::test_evalf_near_integers",
"sympy/core/tests/test_evalf.py::test_evalf_ramanujan",
"sympy/core/tests/test_evalf.py::test_evalf_bugs",
"sympy/core/tests/test_evalf.py::test_evalf_integer_parts",
"sympy/core/tests/test_evalf.py::test_evalf_trig_zero_detection",
"sympy/core/tests/test_evalf.py::test_evalf_sum",
"sympy/core/tests/test_evalf.py::test_evalf_divergent_series",
"sympy/core/tests/test_evalf.py::test_evalf_product",
"sympy/core/tests/test_evalf.py::test_evalf_py_methods",
"sympy/core/tests/test_evalf.py::test_evalf_power_subs_bugs",
"sympy/core/tests/test_evalf.py::test_evalf_arguments",
"sympy/core/tests/test_evalf.py::test_implemented_function_evalf",
"sympy/core/tests/test_evalf.py::test_evaluate_false",
"sympy/core/tests/test_evalf.py::test_evalf_relational",
"sympy/core/tests/test_evalf.py::test_issue_5486",
"sympy/core/tests/test_evalf.py::test_issue_5486_bug",
"sympy/core/tests/test_evalf.py::test_bugs",
"sympy/core/tests/test_evalf.py::test_subs",
"sympy/core/tests/test_evalf.py::test_issue_4956_5204",
"sympy/core/tests/test_evalf.py::test_old_docstring",
"sympy/core/tests/test_evalf.py::test_issue_4806",
"sympy/core/tests/test_evalf.py::test_evalf_mul",
"sympy/core/tests/test_evalf.py::test_scaled_zero",
"sympy/core/tests/test_evalf.py::test_chop_value",
"sympy/core/tests/test_evalf.py::test_infinities",
"sympy/core/tests/test_evalf.py::test_to_mpmath",
"sympy/core/tests/test_evalf.py::test_issue_6632_evalf",
"sympy/core/tests/test_evalf.py::test_issue_4945",
"sympy/core/tests/test_evalf.py::test_evalf_integral",
"sympy/core/tests/test_evalf.py::test_issue_8821_highprec_from_str",
"sympy/functions/special/tests/test_gamma_functions.py::test_gamma",
"sympy/functions/special/tests/test_gamma_functions.py::test_gamma_rewrite",
"sympy/functions/special/tests/test_gamma_functions.py::test_gamma_series",
"sympy/functions/special/tests/test_gamma_functions.py::test_lowergamma",
"sympy/functions/special/tests/test_gamma_functions.py::test_uppergamma",
"sympy/functions/special/tests/test_gamma_functions.py::test_polygamma",
"sympy/functions/special/tests/test_gamma_functions.py::test_polygamma_expand_func",
"sympy/functions/special/tests/test_gamma_functions.py::test_loggamma",
"sympy/functions/special/tests/test_gamma_functions.py::test_polygamma_expansion",
"sympy/functions/special/tests/test_gamma_functions.py::test_issue_8657"
] | [] | BSD | 32 |
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 |
|
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 |
|
sympy__sympy-8935 | c179b51706776fec3ea37daa6920615c0cb4988d | 2015-02-02 20:40:49 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/core/evalf.py b/sympy/core/evalf.py
index d628fc20a7..8d9f470307 100644
--- a/sympy/core/evalf.py
+++ b/sympy/core/evalf.py
@@ -853,7 +853,7 @@ def evalf_bernoulli(expr, prec, options):
def as_mpmath(x, prec, options):
x = sympify(x)
- if isinstance(x, C.Zero):
+ if isinstance(x, C.Zero) or x == 0:
return mpf(0)
if isinstance(x, C.Infinity):
return mpf('inf')
| nsimplify(Integral(x, (x, 0.0, 1.0))) gives TypeError: cannot create mpf from None
See https://github.com/sympy/sympy/issues/2884#issuecomment-38794481
```pytb
nsimplify(Integral(x, (x, 0.0, 1.0)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/mn/anatu/cma-u3/tmac/usr/lib/python2.6/site-packages/sympy/simplify/simplify.py", line 3861, in nsimplify
exprval = expr.evalf(prec, chop=True)
File "/mn/anatu/cma-u3/tmac/usr/lib/python2.6/site-packages/sympy/core/evalf.py", line 1284, in evalf
result = evalf(self, prec + 4, options)
File "/mn/anatu/cma-u3/tmac/usr/lib/python2.6/site-packages/sympy/core/evalf.py", line 1184, in evalf
r = rf(x, prec, options)
File "/mn/anatu/cma-u3/tmac/usr/lib/python2.6/site-packages/sympy/core/evalf.py", line 959, in evalf_integral
result = do_integral(expr, workprec, options)
File "/mn/anatu/cma-u3/tmac/usr/lib/python2.6/site-packages/sympy/core/evalf.py", line 875, in do_integral
xlow = as_mpmath(xlow, prec + 15, options)
File "/mn/anatu/cma-u3/tmac/usr/lib/python2.6/site-packages/sympy/core/evalf.py", line 862, in as_mpmath
return mpf(re)
File "/mn/anatu/cma-u3/tmac/usr/lib/python2.6/site-packages/sympy/mpmath/ctx_mp_python.py", line 77, in __new__
v._mpf_ = mpf_pos(cls.mpf_convert_arg(val, prec, rounding), prec, rounding)
File "/mn/anatu/cma-u3/tmac/usr/lib/python2.6/site-packages/sympy/mpmath/ctx_mp_python.py", line 96, in mpf_convert_arg
raise TypeError("cannot create mpf from " + repr(x))
TypeError: cannot create mpf from None
```
| sympy/sympy | diff --git a/sympy/core/tests/test_evalf.py b/sympy/core/tests/test_evalf.py
index 2d54ba1c4f..e93316af8b 100644
--- a/sympy/core/tests/test_evalf.py
+++ b/sympy/core/tests/test_evalf.py
@@ -3,7 +3,7 @@
integrate, log, Mul, N, oo, pi, Pow, product, Product,
Rational, S, Sum, sin, sqrt, sstr, sympify, Symbol)
from sympy.core.evalf import (complex_accuracy, PrecisionExhausted,
- scaled_zero, get_integer_part)
+ scaled_zero, get_integer_part, as_mpmath)
from sympy.core.compatibility import long
from mpmath import inf, ninf
from sympy.abc import n, x, y
@@ -226,6 +226,9 @@ def test_evalf_bugs():
assert (5+E**(oo)).n() == S.Infinity
assert (5-E**(oo)).n() == S.NegativeInfinity
+ #issue 7416
+ assert as_mpmath(0.0, 10, {'chop': True}) == 0
+
def test_evalf_integer_parts():
a = floor(log(8)/log(2) - exp(-1000), evaluate=False)
| {
"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": 3
},
"num_modified_files": 1
} | 0.7 | {
"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.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
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
mpmath==1.3.0
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/sympy/sympy.git@c179b51706776fec3ea37daa6920615c0cb4988d#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_evalf.py::test_evalf_bugs"
] | [] | [
"sympy/core/tests/test_evalf.py::test_evalf_helpers",
"sympy/core/tests/test_evalf.py::test_evalf_basic",
"sympy/core/tests/test_evalf.py::test_cancellation",
"sympy/core/tests/test_evalf.py::test_evalf_powers",
"sympy/core/tests/test_evalf.py::test_evalf_rump",
"sympy/core/tests/test_evalf.py::test_evalf_complex",
"sympy/core/tests/test_evalf.py::test_evalf_complex_powers",
"sympy/core/tests/test_evalf.py::test_evalf_exponentiation",
"sympy/core/tests/test_evalf.py::test_evalf_complex_cancellation",
"sympy/core/tests/test_evalf.py::test_evalf_logs",
"sympy/core/tests/test_evalf.py::test_evalf_trig",
"sympy/core/tests/test_evalf.py::test_evalf_near_integers",
"sympy/core/tests/test_evalf.py::test_evalf_ramanujan",
"sympy/core/tests/test_evalf.py::test_evalf_integer_parts",
"sympy/core/tests/test_evalf.py::test_evalf_trig_zero_detection",
"sympy/core/tests/test_evalf.py::test_evalf_sum",
"sympy/core/tests/test_evalf.py::test_evalf_divergent_series",
"sympy/core/tests/test_evalf.py::test_evalf_product",
"sympy/core/tests/test_evalf.py::test_evalf_py_methods",
"sympy/core/tests/test_evalf.py::test_evalf_power_subs_bugs",
"sympy/core/tests/test_evalf.py::test_evalf_arguments",
"sympy/core/tests/test_evalf.py::test_implemented_function_evalf",
"sympy/core/tests/test_evalf.py::test_evaluate_false",
"sympy/core/tests/test_evalf.py::test_evalf_relational",
"sympy/core/tests/test_evalf.py::test_issue_5486",
"sympy/core/tests/test_evalf.py::test_issue_5486_bug",
"sympy/core/tests/test_evalf.py::test_bugs",
"sympy/core/tests/test_evalf.py::test_subs",
"sympy/core/tests/test_evalf.py::test_issue_4956_5204",
"sympy/core/tests/test_evalf.py::test_old_docstring",
"sympy/core/tests/test_evalf.py::test_issue_4806",
"sympy/core/tests/test_evalf.py::test_evalf_mul",
"sympy/core/tests/test_evalf.py::test_scaled_zero",
"sympy/core/tests/test_evalf.py::test_chop_value",
"sympy/core/tests/test_evalf.py::test_infinities",
"sympy/core/tests/test_evalf.py::test_to_mpmath",
"sympy/core/tests/test_evalf.py::test_issue_6632_evalf",
"sympy/core/tests/test_evalf.py::test_issue_4945",
"sympy/core/tests/test_evalf.py::test_evalf_integral",
"sympy/core/tests/test_evalf.py::test_issue_8821_highprec_from_str",
"sympy/core/tests/test_evalf.py::test_issue_8853"
] | [] | BSD | 35 |
|
sympy__sympy-8976 | b159009a6c4c96130712b3b92843c1d853afdadb | 2015-02-10 18:20:28 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/.gitignore b/.gitignore
index 0f8a7d6857..c8cf3a3d61 100644
--- a/.gitignore
+++ b/.gitignore
@@ -55,7 +55,6 @@ doc/sphinx/
# pdf files generated from svg files (cd doc; make latex)
doc/src/modules/physics/mechanics/*.pdf
-doc/src/modules/physics/vector/*.pdf
# Mac OS X Junk
.DS_Store
@@ -68,4 +67,3 @@ sample.tex
# IPython Notebook Checkpoints
.ipynb_checkpoints/
-
diff --git a/.travis.yml b/.travis.yml
index 287d7db54f..f6fd26b80e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -117,14 +117,7 @@ before_install:
sudo apt-get install sagemath-upstream-binary;
fi
install:
-#The install cycle below is to test installation on systems without setuptools.
- - if [[ "${TEST_AUTOWRAP}" == "true" ]]; then
- pip uninstall -y setuptools;
- python setup.py install;
- pip uninstall -y sympy;
- pip install setuptools;
- python setup.py install;
- elif [[ "${TEST_SAGE}" != "true" ]]; then
+ - if [[ "${TEST_SAGE}" != "true" ]]; then
python setup.py install;
fi
script:
diff --git a/README.rst b/README.rst
index b30fa5217d..cf0a9c420c 100644
--- a/README.rst
+++ b/README.rst
@@ -38,7 +38,7 @@ To get the git version do
$ git clone git://github.com/sympy/sympy.git
-For other options (tarballs, debs, etc.), see
+For other options (tarballs, debs, etc.), see See
http://docs.sympy.org/dev/install.html.
Documentation and usage
diff --git a/setup.py b/setup.py
index 26ae363efb..762f57aa10 100755
--- a/setup.py
+++ b/setup.py
@@ -34,7 +34,7 @@
try:
from setuptools import setup, Command
except ImportError:
- from distutils.core import setup, Command
+ from distutils import setup, Command
# handle mpmath deps in the hard way:
from distutils.version import LooseVersion
@@ -50,7 +50,6 @@
import subprocess
import os
import shutil
-import glob
PY3 = sys.version_info[0] > 2
@@ -191,11 +190,6 @@ def run(self):
elif os.path.isdir(f):
shutil.rmtree(f)
- for name in glob.glob(os.path.join(dir_setup, "doc", "src", "modules", \
- "physics", "vector", "*.pdf")):
- if os.path.isfile(name):
- os.remove(name)
-
os.chdir(curr_dir)
diff --git a/sympy/physics/mechanics/kane.py b/sympy/physics/mechanics/kane.py
index 842bf548a9..4a6a050454 100644
--- a/sympy/physics/mechanics/kane.py
+++ b/sympy/physics/mechanics/kane.py
@@ -132,9 +132,9 @@ def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None,
self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent,
u_auxiliary)
- self._initialize_kindiffeq_matrices(kd_eqs)
self._initialize_constraint_matrices(configuration_constraints,
velocity_constraints, acceleration_constraints)
+ self._initialize_kindiffeq_matrices(kd_eqs)
def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux):
"""Initialize the coordinate and speed vectors."""
@@ -193,14 +193,6 @@ def _initialize_constraint_matrices(self, config, vel, acc):
u_zero = dict((i, 0) for i in self.u)
udot_zero = dict((i, 0) for i in self._udot)
- # When calling kanes_equations, another class instance will be
- # created if auxiliary u's are present. In this case, the
- # computation of kinetic differential equation matrices will be
- # skipped as this was computed during the original KanesMethod
- # object, and the qd_u_map will not be available.
- if self._qdot_u_map is not None:
- vel = vel.subs(self._qdot_u_map)
-
self._f_nh = vel.subs(u_zero)
self._k_nh = (vel - self._f_nh).jacobian(self.u)
# If no acceleration constraints given, calculate them.
@@ -209,8 +201,6 @@ def _initialize_constraint_matrices(self, config, vel, acc):
self._f_nh.diff(dynamicsymbols._t))
self._k_dnh = self._k_nh
else:
- if self._qdot_u_map is not None:
- acc = acc.subs(self._qdot_u_map)
self._f_dnh = acc.subs(udot_zero)
self._k_dnh = (acc - self._f_dnh).jacobian(self._udot)
diff --git a/sympy/solvers/inequalities.py b/sympy/solvers/inequalities.py
index 58274f056b..4982a72097 100644
--- a/sympy/solvers/inequalities.py
+++ b/sympy/solvers/inequalities.py
@@ -410,6 +410,7 @@ def solve_univariate_inequality(expr, gen, relational=True):
singularities.extend(solve(d, gen))
include_x = expr.func(0, 0)
+
def valid(x):
v = e.subs(gen, x)
r = expr.func(v, 0)
@@ -432,10 +433,10 @@ def valid(x):
for x in reals:
end = x
- if ((end is S.NegativeInfinity and expr.rel_op in ['>', '>=']) or
- (end is S.Infinity and expr.rel_op in ['<', '<='])):
- sol_sets.append(Interval(start, S.Infinity, True, True))
- break
+ if end in [S.NegativeInfinity, S.Infinity]:
+ if valid(S(0)):
+ sol_sets.append(Interval(start, S.Infinity, True, True))
+ break
if valid((start + end)/2 if start != S.NegativeInfinity else end - 1):
sol_sets.append(Interval(start, end, True, True))
| solveset(-oo < x) & solveset(oo > x) returns EmptySet()
```python
In [8]: x = Symbol('x', real=True)
In [9]: solveset(-oo < x)
Out[9]: EmptySet()
In [10]: solveset(oo > x)
Out[10]: EmptySet()
```
Though reversing the relational expression works. | sympy/sympy | diff --git a/sympy/logic/tests/test_boolalg.py b/sympy/logic/tests/test_boolalg.py
index bd8ed6fa45..90be72dc9c 100644
--- a/sympy/logic/tests/test_boolalg.py
+++ b/sympy/logic/tests/test_boolalg.py
@@ -684,3 +684,9 @@ def test_issue_8777():
assert And(x >= 1, x < oo).as_set() == Interval(1, oo)
assert (x < oo).as_set() == Interval(-oo, oo)
assert (x > -oo).as_set() == Interval(-oo, oo)
+
+
+def test_issue_8975():
+ x = symbols('x')
+ assert Or(And(-oo < x, x <= -2), And(2 <= x, x < oo)).as_set() == \
+ Interval(-oo, -2) + Interval(2, oo)
diff --git a/sympy/physics/mechanics/tests/test_kane2.py b/sympy/physics/mechanics/tests/test_kane2.py
index e2cec1737c..fb0ec6f142 100644
--- a/sympy/physics/mechanics/tests/test_kane2.py
+++ b/sympy/physics/mechanics/tests/test_kane2.py
@@ -1,5 +1,5 @@
from sympy.core.compatibility import range
-from sympy import cos, Matrix, simplify, sin, solve, tan, pi
+from sympy import cos, Matrix, simplify, sin, solve
from sympy import symbols, trigsimp, zeros
from sympy.physics.mechanics import (cross, dot, dynamicsymbols, KanesMethod,
inertia, inertia_of_point_mass,
@@ -373,83 +373,3 @@ def test_sub_qdot():
fr, fr_star = km.kanes_equations(forces, bodies)
assert (fr.expand() == fr_expected.expand())
assert (trigsimp(fr_star).expand() == fr_star_expected.expand())
-
-def test_sub_qdot2():
- # This test solves exercises 8.3 from Kane 1985 and defines
- # all velocities in terms of q, qdot. We check that the generalized active
- # forces are correctly computed if u terms are only defined in the
- # kinematic differential equations.
- #
- # This functionality was added in PR 8948. Without qdot/u substitution, the
- # KanesMethod constructor will fail during the constraint initialization as
- # the B matrix will be poorly formed and inversion of the dependent part
- # will fail.
-
- g, m, Px, Py, Pz, R, t = symbols('g m Px Py Pz R t')
- q = dynamicsymbols('q:5')
- qd = dynamicsymbols('q:5', level=1)
- u = dynamicsymbols('u:5')
-
- ## Define inertial, intermediate, and rigid body reference frames
- A = ReferenceFrame('A')
- B_prime = A.orientnew('B_prime', 'Axis', [q[0], A.z])
- B = B_prime.orientnew('B', 'Axis', [pi/2 - q[1], B_prime.x])
- C = B.orientnew('C', 'Axis', [q[2], B.z])
-
- ## Define points of interest and their velocities
- pO = Point('O')
- pO.set_vel(A, 0)
-
- # R is the point in plane H that comes into contact with disk C.
- pR = pO.locatenew('R', q[3]*A.x + q[4]*A.y)
- pR.set_vel(A, pR.pos_from(pO).diff(t, A))
- pR.set_vel(B, 0)
-
- # C^ is the point in disk C that comes into contact with plane H.
- pC_hat = pR.locatenew('C^', 0)
- pC_hat.set_vel(C, 0)
-
- # C* is the point at the center of disk C.
- pCs = pC_hat.locatenew('C*', R*B.y)
- pCs.set_vel(C, 0)
- pCs.set_vel(B, 0)
-
- # calculate velocites of points C* and C^ in frame A
- pCs.v2pt_theory(pR, A, B) # points C* and R are fixed in frame B
- pC_hat.v2pt_theory(pCs, A, C) # points C* and C^ are fixed in frame C
-
- ## Define forces on each point of the system
- R_C_hat = Px*A.x + Py*A.y + Pz*A.z
- R_Cs = -m*g*A.z
- forces = [(pC_hat, R_C_hat), (pCs, R_Cs)]
-
- ## Define kinematic differential equations
- # let ui = omega_C_A & bi (i = 1, 2, 3)
- # u4 = qd4, u5 = qd5
- u_expr = [C.ang_vel_in(A) & uv for uv in B]
- u_expr += qd[3:]
- kde = [ui - e for ui, e in zip(u, u_expr)]
- km1 = KanesMethod(A, q, u, kde)
- fr1, _ = km1.kanes_equations(forces, [])
-
- ## Calculate generalized active forces if we impose the condition that the
- # disk C is rolling without slipping
- u_indep = u[:3]
- u_dep = list(set(u) - set(u_indep))
- vc = [pC_hat.vel(A) & uv for uv in [A.x, A.y]]
- km2 = KanesMethod(A, q, u_indep, kde,
- u_dependent=u_dep, velocity_constraints=vc)
- fr2, _ = km2.kanes_equations(forces, [])
-
- fr1_expected = Matrix([
- -R*g*m*sin(q[1]),
- -R*(Px*cos(q[0]) + Py*sin(q[0]))*tan(q[1]),
- R*(Px*cos(q[0]) + Py*sin(q[0])),
- Px,
- Py])
- fr2_expected = Matrix([
- -R*g*m*sin(q[1]),
- 0,
- 0])
- assert (trigsimp(fr1.expand()) == trigsimp(fr1_expected.expand()))
- assert (trigsimp(fr2.expand()) == trigsimp(fr2_expected.expand()))
diff --git a/sympy/solvers/tests/test_inequalities.py b/sympy/solvers/tests/test_inequalities.py
index e6f5622167..c5f8ff4287 100644
--- a/sympy/solvers/tests/test_inequalities.py
+++ b/sympy/solvers/tests/test_inequalities.py
@@ -297,3 +297,8 @@ def test_issue_8545():
assert reduce_abs_inequality(eq, '<', x) == ans
eq = 1 - x - sqrt((1 - x)**2)
assert reduce_inequalities(eq < 0) == ans
+
+
+def test_issue_8974():
+ assert isolve(-oo < x, x) == And(-oo < x, x < oo)
+ assert isolve(oo > x, x) == And(-oo < x, x < oo)
| {
"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": 2,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 6
} | 0.7 | {
"env_vars": null,
"env_yml_path": [],
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "mpmath>=0.19",
"pip_packages": [
"pytest"
],
"pre_install": [],
"python": "3.6",
"reqs_path": [],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.2.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
-e git+https://github.com/sympy/sympy.git@b159009a6c4c96130712b3b92843c1d853afdadb#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
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
- mpmath=1.2.1=py36h06a4308_0
- 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
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/sympy
| [
"sympy/logic/tests/test_boolalg.py::test_issue_8975",
"sympy/solvers/tests/test_inequalities.py::test_issue_8974"
] | [] | [
"sympy/logic/tests/test_boolalg.py::test_overloading",
"sympy/logic/tests/test_boolalg.py::test_And",
"sympy/logic/tests/test_boolalg.py::test_Or",
"sympy/logic/tests/test_boolalg.py::test_Xor",
"sympy/logic/tests/test_boolalg.py::test_Not",
"sympy/logic/tests/test_boolalg.py::test_Nand",
"sympy/logic/tests/test_boolalg.py::test_Nor",
"sympy/logic/tests/test_boolalg.py::test_Implies",
"sympy/logic/tests/test_boolalg.py::test_Equivalent",
"sympy/logic/tests/test_boolalg.py::test_equals",
"sympy/logic/tests/test_boolalg.py::test_simplification",
"sympy/logic/tests/test_boolalg.py::test_bool_map",
"sympy/logic/tests/test_boolalg.py::test_bool_symbol",
"sympy/logic/tests/test_boolalg.py::test_is_boolean",
"sympy/logic/tests/test_boolalg.py::test_subs",
"sympy/logic/tests/test_boolalg.py::test_commutative",
"sympy/logic/tests/test_boolalg.py::test_and_associativity",
"sympy/logic/tests/test_boolalg.py::test_or_assicativity",
"sympy/logic/tests/test_boolalg.py::test_double_negation",
"sympy/logic/tests/test_boolalg.py::test_eliminate_implications",
"sympy/logic/tests/test_boolalg.py::test_conjuncts",
"sympy/logic/tests/test_boolalg.py::test_disjuncts",
"sympy/logic/tests/test_boolalg.py::test_distribute",
"sympy/logic/tests/test_boolalg.py::test_to_nnf",
"sympy/logic/tests/test_boolalg.py::test_to_cnf",
"sympy/logic/tests/test_boolalg.py::test_to_dnf",
"sympy/logic/tests/test_boolalg.py::test_to_int_repr",
"sympy/logic/tests/test_boolalg.py::test_is_nnf",
"sympy/logic/tests/test_boolalg.py::test_is_cnf",
"sympy/logic/tests/test_boolalg.py::test_is_dnf",
"sympy/logic/tests/test_boolalg.py::test_ITE",
"sympy/logic/tests/test_boolalg.py::test_is_literal",
"sympy/logic/tests/test_boolalg.py::test_operators",
"sympy/logic/tests/test_boolalg.py::test_true_false",
"sympy/logic/tests/test_boolalg.py::test_bool_as_set",
"sympy/logic/tests/test_boolalg.py::test_all_or_nothing",
"sympy/logic/tests/test_boolalg.py::test_canonical_atoms",
"sympy/logic/tests/test_boolalg.py::test_issue_8777",
"sympy/physics/mechanics/tests/test_kane2.py::test_aux_dep",
"sympy/physics/mechanics/tests/test_kane2.py::test_non_central_inertia",
"sympy/physics/mechanics/tests/test_kane2.py::test_sub_qdot",
"sympy/solvers/tests/test_inequalities.py::test_solve_poly_inequality",
"sympy/solvers/tests/test_inequalities.py::test_reduce_poly_inequalities_real_interval",
"sympy/solvers/tests/test_inequalities.py::test_reduce_poly_inequalities_complex_relational",
"sympy/solvers/tests/test_inequalities.py::test_reduce_rational_inequalities_real_relational",
"sympy/solvers/tests/test_inequalities.py::test_reduce_abs_inequalities",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_general",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_boolean",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_multivariate",
"sympy/solvers/tests/test_inequalities.py::test_reduce_inequalities_errors",
"sympy/solvers/tests/test_inequalities.py::test_hacky_inequalities",
"sympy/solvers/tests/test_inequalities.py::test_issue_6343",
"sympy/solvers/tests/test_inequalities.py::test_issue_8235",
"sympy/solvers/tests/test_inequalities.py::test_issue_5526",
"sympy/solvers/tests/test_inequalities.py::test_solve_univariate_inequality",
"sympy/solvers/tests/test_inequalities.py::test_slow_general_univariate",
"sympy/solvers/tests/test_inequalities.py::test_issue_8545"
] | [] | BSD | 36 |
|
sympy__sympy-8985 | 510e474f86df2180b9909f21cbeb131c952e7280 | 2015-02-13 23:12:44 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index e512c9edd7..ffd155c9c6 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -89,7 +89,7 @@
# Brackets
'norm': lambda s: r'\left\lVert{'+s+r'}\right\rVert',
'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle',
- 'abs': lambda s: r'\left\lvert{'+s+r'}\right\rvert',
+ 'abs': lambda s: r'\left\|{'+s+r'}\right\|',
'mag': lambda s: r'\left\lvert{'+s+r'}\right\rvert',
}
@@ -753,7 +753,7 @@ def _print_ceiling(self, expr, exp=None):
return tex
def _print_Abs(self, expr, exp=None):
- tex = r"\left\lvert{%s}\right\rvert" % self._print(expr.args[0])
+ tex = r"\left\|{%s}\right\|" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
| Use \left \| instead of \lvert in latex(Abs)
See https://groups.google.com/forum/#!topic/sympy/4kVZq27x6T0. It looks like `\lvert` isn't supported by matplotlib. Is there any good reason to use `\lvert` over `\|`? | sympy/sympy | diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index a3b68b7b40..4ded4f4845 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -232,7 +232,7 @@ def test_latex_functions():
assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
- assert latex(Abs(x)) == r"\left\lvert{x}\right\rvert"
+ assert latex(Abs(x)) == r"\left\|{x}\right\|"
assert latex(re(x)) == r"\Re{x}"
assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
assert latex(im(x)) == r"\Im{x}"
@@ -1178,7 +1178,7 @@ def test_modifiers():
assert latex(symbols("xDot")) == r"\dot{x}"
assert latex(symbols("xBar")) == r"\bar{x}"
assert latex(symbols("xVec")) == r"\vec{x}"
- assert latex(symbols("xAbs")) == r"\left\lvert{x}\right\rvert"
+ assert latex(symbols("xAbs")) == r"\left\|{x}\right\|"
assert latex(symbols("xMag")) == r"\left\lvert{x}\right\rvert"
assert latex(symbols("xPrM")) == r"{x}'"
assert latex(symbols("xBM")) == r"\boldsymbol{x}"
@@ -1208,7 +1208,7 @@ def test_modifiers():
assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}"
assert latex(symbols("xHATNorm")) == r"\left\lVert{\hat{x}}\right\rVert"
# Check a couple big, ugly combinations
- assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == r"\boldsymbol{\mathring{x}}^{\left\lvert{\breve{z}}\right\rvert}_{{\check{y}}'}"
+ assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == r"\boldsymbol{\mathring{x}}^{\left\|{\breve{z}}\right\|}_{{\check{y}}'}"
assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}"
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y python3-pip"
],
"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
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
mpmath==1.3.0
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/sympy/sympy.git@510e474f86df2180b9909f21cbeb131c952e7280#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_modifiers"
] | [] | [
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117"
] | [] | BSD | 37 |
|
sympy__sympy-9010 | c02585aaf870926a65f147592cbf7c22bf64eea5 | 2015-02-16 22:42:36 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/matrices/expressions/matexpr.py b/sympy/matrices/expressions/matexpr.py
index 01b7420823..b07b3750ad 100644
--- a/sympy/matrices/expressions/matexpr.py
+++ b/sympy/matrices/expressions/matexpr.py
@@ -322,6 +322,14 @@ class MatrixElement(Expr):
j = property(lambda self: self.args[2])
_diff_wrt = True
+ def doit(self, **kwargs):
+ deep = kwargs.get('deep', True)
+ if deep:
+ args = [arg.doit(**kwargs) for arg in self.args]
+ else:
+ args = self.args
+ return args[0][args[1], args[2]]
+
class MatrixSymbol(MatrixExpr):
"""Symbolic representation of a Matrix object
| MatrixSymbol's are not evaluated
This issue was discussed in Google Group: https://groups.google.com/forum/#!topic/sympy/cHiX1dY5nUM
Here is simple test:
```
from sympy import MatrixSymbol, ImmutableMatrix
u = MatrixSymbol('u', 2,1)
print "\n\ntest1:"
print u.subs(u, ImmutableMatrix([3,5]))[0,0] # evaluates fine
print "\n\ntest2:"
print u[0,0].subs(u, ImmutableMatrix([3,5])) # do not evaluate
print "\n\ntest3:"
print u[0,0].subs(u, ImmutableMatrix([3,5])).evalf() # sill not evaluated
print "\n\ntest4:"
print u[0,0].subs(u, ImmutableMatrix([3,5])).doit() # sill not evaluated
print "\n\ntest5:"
print u[0,0].subs(u, ImmutableMatrix([3,5])).doit().evalf() # sill not evaluated
print "\n\ntest6:"
print u[0,0].subs(u, ImmutableMatrix([3,5])).evalf().doit() # sill not evaluated
```
Here is an output of the code:
```
test1:
3
test2:
Matrix([
[3],
[5]])[0, 0]
test3:
Matrix([
[3],
[5]])[0, 0]
test4:
Matrix([
[3],
[5]])[0, 0]
test5:
Matrix([
[3],
[5]])[0, 0]
test6:
Matrix([
[3],
[5]])[0, 0]
```
The expected result is 3 in all six tests (as in test1).
| sympy/sympy | diff --git a/sympy/matrices/expressions/tests/test_matrix_exprs.py b/sympy/matrices/expressions/tests/test_matrix_exprs.py
index 77a8f1f9ed..d1f0dcbb23 100644
--- a/sympy/matrices/expressions/tests/test_matrix_exprs.py
+++ b/sympy/matrices/expressions/tests/test_matrix_exprs.py
@@ -207,3 +207,9 @@ def test_single_indexing():
def test_MatrixElement_diff():
assert (A[3, 0]*A[0, 0]).diff(A[0, 0]) == A[3, 0]
+
+
+def test_MatrixElement_doit():
+ u = MatrixSymbol('u', 2, 1)
+ v = ImmutableMatrix([3, 5])
+ assert u[0, 0].subs(u, v).doit() == v[0, 0]
| {
"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": 2
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "mpmath>=0.19",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"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
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.2.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
-e git+https://github.com/sympy/sympy.git@c02585aaf870926a65f147592cbf7c22bf64eea5#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
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
- mpmath=1.2.1=py36h06a4308_0
- 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
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/sympy
| [
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatrixElement_doit"
] | [] | [
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_shape",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matexpr",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_subs",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_ZeroMatrix",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_ZeroMatrix_doit",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_Identity",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_Identity_doit",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_addition",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_multiplication",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatPow",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatrixSymbol",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_dense_conversion",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_free_symbols",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_zero_matmul",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matadd_simplify",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matmul_simplify",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_invariants",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_indexing",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_single_indexing",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatrixElement_diff"
] | [] | BSD | 38 |
|
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 |
|
sympy__sympy-9040 | 90ce1edccd8102400e8f5e59e0c75caa7ed7535b | 2015-02-21 05:03:44 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | smichr: Maybe `if me.is_complex and me.is_real is False:` could just be changed to `if me.is_complex and me.is_real is False or me is S.ComplexInfinity:`.
aktech: Yes, that would be better.
Thanks.
aktech: This Example is failing:
in [sympy/integrals/transforms.py](https://github.com/sympy/sympy/blob/master/sympy/integrals/transforms.py#L881)
```python
>>> from sympy.integrals.transforms import _simplifyconds as simp
>>> from sympy.abc import x
>>> from sympy import sympify as S
>>> simp(abs(x**2) < 1, x, 0)
Abs(x**2) < 1
```
I am not sure about the cause.
smichr: > I am not sure about the cause.
```
File "sympy\integrals\transforms.py", line 919, in bigger
return bigger(1/ex2, 1/ex1)
```
When ex* is 0 this test is going to fail because a zoo will be generated.
aktech: @smichr Thanks, for reply.
I should probably Except that error, using try - except.
smichr: The following passes tests, too. What do you think about this:
```diff
diff --git a/sympy/core/expr.py b/sympy/core/expr.py
index f3a733f..42c9960 100644
--- a/sympy/core/expr.py
+++ b/sympy/core/expr.py
@@ -235,7 +235,8 @@ def __ge__(self, other):
except SympifyError:
raise TypeError("Invalid comparison %s >= %s" % (self, other))
for me in (self, other):
- if me.is_complex and me.is_real is False:
+ if (me.is_complex and me.is_real is False) or \
+ me.has(S.ComplexInfinity):
raise TypeError("Invalid comparison of complex %s" % me)
if me is S.NaN:
raise TypeError("Invalid NaN comparison")
@@ -252,7 +253,8 @@ def __le__(self, other):
except SympifyError:
raise TypeError("Invalid comparison %s <= %s" % (self, other))
for me in (self, other):
- if me.is_complex and me.is_real is False:
+ if (me.is_complex and me.is_real is False) or \
+ me.has(S.ComplexInfinity):
raise TypeError("Invalid comparison of complex %s" % me)
if me is S.NaN:
raise TypeError("Invalid NaN comparison")
@@ -269,7 +271,8 @@ def __gt__(self, other):
except SympifyError:
raise TypeError("Invalid comparison %s > %s" % (self, other))
for me in (self, other):
- if me.is_complex and me.is_real is False:
+ if (me.is_complex and me.is_real is False) or \
+ me.has(S.ComplexInfinity):
raise TypeError("Invalid comparison of complex %s" % me)
if me is S.NaN:
raise TypeError("Invalid NaN comparison")
@@ -286,7 +289,8 @@ def __lt__(self, other):
except SympifyError:
raise TypeError("Invalid comparison %s < %s" % (self, other))
for me in (self, other):
- if me.is_complex and me.is_real is False:
+ if (me.is_complex and me.is_real is False) or \
+ me.has(S.ComplexInfinity):
raise TypeError("Invalid comparison of complex %s" % me)
if me is S.NaN:
raise TypeError("Invalid NaN comparison")
```
aktech: > The following passes tests, too.
Have you tried `./bin/doctest integrals` ?
(The Failed case is in Example docs). It Fails on my system.
```
__________________ sympy.integrals.transforms._simplifyconds ___________________
File "sympy/integrals/transforms.py", line 881, in sympy.integrals.transforms._simplifyconds
Failed example:
simp(abs(x**2) < 1, x, 0)
Exception raised:
Traceback (most recent call last):
File "/usr/lib/python2.7/doctest.py", line 1315, in __run
compileflags, 1) in test.globs
File "<doctest sympy.integrals.transforms._simplifyconds[5]>", line 1, in <module>
simp(abs(x**2) < 1, x, 0)
File "sympy/integrals/transforms.py", line 948, in _simplifyconds
expr = repl(expr, StrictLessThan, replie)
File "sympy/integrals/transforms.py", line 947, in repl
return ex.replace(*args)
File "sympy/core/basic.py", line 1351, in replace
rv = bottom_up(self, rec_replace, atoms=True)
File "sympy/simplify/simplify.py", line 4083, in bottom_up
rv = F(rv)
File "sympy/core/basic.py", line 1336, in rec_replace
new = _value(expr, result)
File "sympy/core/basic.py", line 1280, in <lambda>
_value = lambda expr, result: value(*expr.args)
File "sympy/integrals/transforms.py", line 933, in replie
r = bigger(x, y)
File "sympy/integrals/transforms.py", line 919, in bigger
return bigger(1/ex2, 1/ex1)
File "sympy/integrals/transforms.py", line 925, in bigger
if n < 0 and (abs(ex1) >= abs(a)**n) == True:
File "sympy/core/numbers.py", line 1806, in __ge__
return Rational.__ge__(self, other)
File "sympy/core/numbers.py", line 1457, in __ge__
return Expr.__ge__(expr, other)
File "sympy/core/expr.py", line 240, in __ge__
raise TypeError("Invalid comparison of complex %s" % me)
TypeError: Invalid comparison of complex zoo
```
Probably you have tried `sympy/integrals/tests/test_transforms.py` .
smichr: > Have you tried
the diff I gave was on top of your current branch so the catching of the TypeError was not shown in the diff | diff --git a/sympy/core/expr.py b/sympy/core/expr.py
index f3a733fa63..42c9960175 100644
--- a/sympy/core/expr.py
+++ b/sympy/core/expr.py
@@ -235,7 +235,8 @@ def __ge__(self, other):
except SympifyError:
raise TypeError("Invalid comparison %s >= %s" % (self, other))
for me in (self, other):
- if me.is_complex and me.is_real is False:
+ if (me.is_complex and me.is_real is False) or \
+ me.has(S.ComplexInfinity):
raise TypeError("Invalid comparison of complex %s" % me)
if me is S.NaN:
raise TypeError("Invalid NaN comparison")
@@ -252,7 +253,8 @@ def __le__(self, other):
except SympifyError:
raise TypeError("Invalid comparison %s <= %s" % (self, other))
for me in (self, other):
- if me.is_complex and me.is_real is False:
+ if (me.is_complex and me.is_real is False) or \
+ me.has(S.ComplexInfinity):
raise TypeError("Invalid comparison of complex %s" % me)
if me is S.NaN:
raise TypeError("Invalid NaN comparison")
@@ -269,7 +271,8 @@ def __gt__(self, other):
except SympifyError:
raise TypeError("Invalid comparison %s > %s" % (self, other))
for me in (self, other):
- if me.is_complex and me.is_real is False:
+ if (me.is_complex and me.is_real is False) or \
+ me.has(S.ComplexInfinity):
raise TypeError("Invalid comparison of complex %s" % me)
if me is S.NaN:
raise TypeError("Invalid NaN comparison")
@@ -286,7 +289,8 @@ def __lt__(self, other):
except SympifyError:
raise TypeError("Invalid comparison %s < %s" % (self, other))
for me in (self, other):
- if me.is_complex and me.is_real is False:
+ if (me.is_complex and me.is_real is False) or \
+ me.has(S.ComplexInfinity):
raise TypeError("Invalid comparison of complex %s" % me)
if me is S.NaN:
raise TypeError("Invalid NaN comparison")
diff --git a/sympy/integrals/transforms.py b/sympy/integrals/transforms.py
index 9a949884c6..188d13d2b9 100644
--- a/sympy/integrals/transforms.py
+++ b/sympy/integrals/transforms.py
@@ -916,7 +916,10 @@ def bigger(ex1, ex2):
if ex2.func is Abs:
ex2 = ex2.args[0]
if ex1.has(s):
- return bigger(1/ex2, 1/ex1)
+ try:
+ return bigger(1/ex2, 1/ex1)
+ except TypeError:
+ return None
n = power(ex2)
if n is None:
return None
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index a8c905c383..e72a25676e 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -89,7 +89,7 @@
# Brackets
'norm': lambda s: r'\left\lVert{'+s+r'}\right\rVert',
'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle',
- 'abs': lambda s: r'\left|{'+s+r'}\right|',
+ 'abs': lambda s: r'\left\|{'+s+r'}\right\|',
'mag': lambda s: r'\left\lvert{'+s+r'}\right\rvert',
}
@@ -753,7 +753,7 @@ def _print_ceiling(self, expr, exp=None):
return tex
def _print_Abs(self, expr, exp=None):
- tex = r"\left|{%s}\right|" % self._print(expr.args[0])
+ tex = r"\left\|{%s}\right\|" % self._print(expr.args[0])
if exp is not None:
return r"%s^{%s}" % (tex, exp)
| inequalities involving zoo should raise TypeError
Since `I > 0` raises a TypeError, `zoo > 0` should probably do the same. Actually, anything even *containing* `zoo` should probably be disallowed since such an expression will become `zoo` (e.g. `zoo*1`) or `NaN` (e.g. `zoo*0`). See #7834 for an example of how to make the changes. | sympy/sympy | diff --git a/sympy/core/tests/test_relational.py b/sympy/core/tests/test_relational.py
index 21fc0ef58c..f7024122a0 100644
--- a/sympy/core/tests/test_relational.py
+++ b/sympy/core/tests/test_relational.py
@@ -455,10 +455,17 @@ def test_nan_inequality_raise_errors():
def test_nan_complex_inequalities():
# Comparisons of NaN with non-real raise errors, we're not too
# fussy whether its the NaN error or complex error.
- for r in (I, Symbol('z', imaginary=True)):
+ for r in (I, zoo, Symbol('z', imaginary=True)):
assert_all_ineq_raise_TypeError(r, nan)
+def test_complex_infinity_inequalities():
+ raises(TypeError, lambda: zoo > 0)
+ raises(TypeError, lambda: zoo >= 0)
+ raises(TypeError, lambda: zoo < 0)
+ raises(TypeError, lambda: zoo <= 0)
+
+
def test_inequalities_symbol_name_same():
"""Using the operator and functional forms should give same results."""
# We test all combinations from a set
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index b1b031df5a..081d9de92e 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -231,7 +231,7 @@ def test_latex_functions():
assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
- assert latex(Abs(x)) == r"\left|{x}\right|"
+ assert latex(Abs(x)) == r"\left\|{x}\right\|"
assert latex(re(x)) == r"\Re{x}"
assert latex(re(x + y)) == r"\Re{x} + \Re{y}"
assert latex(im(x)) == r"\Im{x}"
@@ -1177,7 +1177,7 @@ def test_modifiers():
assert latex(symbols("xDot")) == r"\dot{x}"
assert latex(symbols("xBar")) == r"\bar{x}"
assert latex(symbols("xVec")) == r"\vec{x}"
- assert latex(symbols("xAbs")) == r"\left|{x}\right|"
+ assert latex(symbols("xAbs")) == r"\left\|{x}\right\|"
assert latex(symbols("xMag")) == r"\left\lvert{x}\right\rvert"
assert latex(symbols("xPrM")) == r"{x}'"
assert latex(symbols("xBM")) == r"\boldsymbol{x}"
@@ -1207,7 +1207,7 @@ def test_modifiers():
assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}"
assert latex(symbols("xHATNorm")) == r"\left\lVert{\hat{x}}\right\rVert"
# Check a couple big, ugly combinations
- assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}"
+ assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == r"\boldsymbol{\mathring{x}}^{\left\|{\breve{z}}\right\|}_{{\check{y}}'}"
assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}"
| {
"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": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 3
} | 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": [
"mpmath>=0.19",
"pytest",
"pytest-cov"
],
"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==22.2.0
certifi==2021.5.30
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.3.0
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
-e git+https://github.com/sympy/sympy.git@90ce1edccd8102400e8f5e59e0c75caa7ed7535b#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
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
- mpmath==1.3.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_relational.py::test_complex_infinity_inequalities",
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_modifiers"
] | [] | [
"sympy/core/tests/test_relational.py::test_rel_ne",
"sympy/core/tests/test_relational.py::test_rel_subs",
"sympy/core/tests/test_relational.py::test_wrappers",
"sympy/core/tests/test_relational.py::test_Eq",
"sympy/core/tests/test_relational.py::test_rel_Infinity",
"sympy/core/tests/test_relational.py::test_bool",
"sympy/core/tests/test_relational.py::test_rich_cmp",
"sympy/core/tests/test_relational.py::test_doit",
"sympy/core/tests/test_relational.py::test_new_relational",
"sympy/core/tests/test_relational.py::test_relational_bool_output",
"sympy/core/tests/test_relational.py::test_relational_logic_symbols",
"sympy/core/tests/test_relational.py::test_univariate_relational_as_set",
"sympy/core/tests/test_relational.py::test_Not",
"sympy/core/tests/test_relational.py::test_evaluate",
"sympy/core/tests/test_relational.py::test_imaginary_compare_raises_TypeError",
"sympy/core/tests/test_relational.py::test_complex_compare_not_real",
"sympy/core/tests/test_relational.py::test_imaginary_and_inf_compare_raises_TypeError",
"sympy/core/tests/test_relational.py::test_complex_pure_imag_not_ordered",
"sympy/core/tests/test_relational.py::test_x_minus_y_not_same_as_x_lt_y",
"sympy/core/tests/test_relational.py::test_nan_equality_exceptions",
"sympy/core/tests/test_relational.py::test_nan_inequality_raise_errors",
"sympy/core/tests/test_relational.py::test_nan_complex_inequalities",
"sympy/core/tests/test_relational.py::test_inequalities_symbol_name_same",
"sympy/core/tests/test_relational.py::test_inequalities_symbol_name_same_complex",
"sympy/core/tests/test_relational.py::test_inequalities_cant_sympify_other",
"sympy/core/tests/test_relational.py::test_ineq_avoid_wild_symbol_flip",
"sympy/core/tests/test_relational.py::test_issue_8245",
"sympy/core/tests/test_relational.py::test_issue_8449",
"sympy/core/tests/test_relational.py::test_simplify",
"sympy/core/tests/test_relational.py::test_equals",
"sympy/core/tests/test_relational.py::test_reversed",
"sympy/core/tests/test_relational.py::test_canonical",
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117"
] | [] | BSD | 40 |
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 |
|
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 |
|
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 |
|
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

| 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 |
|
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 |
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 |
|
sympy__sympy-9063 | aa175f44f96e3b94c08804645d2388b2a79df13c | 2015-02-27 11:41:18 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | lokeshh: There needs to be little change in the summary.
Instead of
> It has been fixed by evaluating trace(MatAdd(X, Y)) to
trace(Z) where Z is what we have after evaluating
MatAdd(X, Y).
it should be
> It has been fixed by evaluating trace(MatAdd(X, Y)) to
Add(trace(X), trace(Y)).
| diff --git a/sympy/matrices/expressions/matadd.py b/sympy/matrices/expressions/matadd.py
index 345615d763..92c75aeb47 100644
--- a/sympy/matrices/expressions/matadd.py
+++ b/sympy/matrices/expressions/matadd.py
@@ -50,8 +50,8 @@ def _eval_adjoint(self):
return MatAdd(*[adjoint(arg) for arg in self.args]).doit()
def _eval_trace(self):
- from trace import Trace
- return MatAdd(*[Trace(arg) for arg in self.args]).doit()
+ from .trace import trace
+ return Add(*[trace(arg) for arg in self.args]).doit()
def doit(self, **kwargs):
deep = kwargs.get('deep', True)
| Trace of MatAdd can fail with error: "mix of Matrix and Scalar symbols"
````
In [18]: X = Matrix([[1, 2], [3, 4]])
In [19]: q = MatAdd(X, 2*X)
In [20]: Trace(q).doit(deep=False)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-038504dfa7f5> in <module>()
----> 1 Trace(q).doit(deep=False)
/home/cbm/work/octsympy/octsympy.git/inst/sympy/matrices/expressions/trace.pyc in doit(self, **kwargs)
42 arg = self.arg
43 try:
---> 44 return arg._eval_trace()
45 except (AttributeError, NotImplementedError):
46 return Trace(arg)
/home/cbm/work/octsympy/octsympy.git/inst/sympy/matrices/expressions/matadd.pyc in _eval_trace(self)
52 def _eval_trace(self):
53 from trace import Trace
---> 54 return MatAdd(*[Trace(arg) for arg in self.args]).doit()
55
56 def doit(self, **kwargs):
/home/cbm/work/octsympy/octsympy.git/inst/sympy/matrices/expressions/matadd.pyc in __new__(cls, *args, **kwargs)
34 obj = Basic.__new__(cls, *args)
35 if check:
---> 36 validate(*args)
37 return obj
38
/home/cbm/work/octsympy/octsympy.git/inst/sympy/matrices/expressions/matadd.pyc in validate(*args)
64 def validate(*args):
65 if not all(arg.is_Matrix for arg in args):
---> 66 raise TypeError("Mix of Matrix and Scalar symbols")
67
68 A = args[0]
TypeError: Mix of Matrix and Scalar symbols
````
I will look into this. | sympy/sympy | diff --git a/sympy/matrices/expressions/tests/test_matmul.py b/sympy/matrices/expressions/tests/test_matmul.py
index b0f6ca3598..58d48f027c 100644
--- a/sympy/matrices/expressions/tests/test_matmul.py
+++ b/sympy/matrices/expressions/tests/test_matmul.py
@@ -7,6 +7,7 @@
MatMul, xxinv, any_zeros, unpack, only_squares)
from sympy.strategies import null_safe
from sympy import refine, Q
+from sympy.utilities.pytest import XFAIL
n, m, l, k = symbols('n m l k', integer=True)
A = MatrixSymbol('A', n, m)
@@ -99,6 +100,13 @@ def test_doit_deep_false_still_canonical():
(2, C, Transpose(D*C)))
+@XFAIL
+def test_matmul_scalar_Matrix_doit():
+ # Issue 9053
+ X = Matrix([[1, 2], [3, 4]])
+ assert MatMul(2, X).doit() == 2*X
+
+
def test_matmul_sympify():
assert isinstance(MatMul(eye(1), eye(1)).args[0], Basic)
diff --git a/sympy/matrices/expressions/tests/test_trace.py b/sympy/matrices/expressions/tests/test_trace.py
index 55b13c5ca6..77a50adc4a 100644
--- a/sympy/matrices/expressions/tests/test_trace.py
+++ b/sympy/matrices/expressions/tests/test_trace.py
@@ -1,10 +1,10 @@
from sympy.core import Lambda, S, symbols
from sympy.concrete import Sum
from sympy.functions import adjoint, conjugate, transpose
-from sympy.matrices import eye, Matrix, ShapeError
+from sympy.matrices import eye, Matrix, ShapeError, ImmutableMatrix
from sympy.matrices.expressions import (
Adjoint, Identity, FunctionMatrix, MatrixExpr, MatrixSymbol, Trace,
- ZeroMatrix, trace, MatPow, MatAdd
+ ZeroMatrix, trace, MatPow, MatAdd, MatMul
)
from sympy.utilities.pytest import raises, XFAIL
@@ -30,7 +30,7 @@ def test_Trace():
# Some easy simplifications
assert trace(Identity(5)) == 5
assert trace(ZeroMatrix(5, 5)) == 0
- assert trace(2*A*B) == 2 * trace(A*B)
+ assert trace(2*A*B) == 2*Trace(A*B)
assert trace(A.T) == trace(A)
i, j = symbols('i j')
@@ -44,13 +44,27 @@ def test_Trace():
assert str(trace(A)) == str(Trace(A).doit())
-def test_Trace_doit():
+def test_Trace_A_plus_B():
+ assert trace(A + B) == Trace(A) + Trace(B)
+ assert Trace(A + B).arg == MatAdd(A, B)
+ assert Trace(A + B).doit() == Trace(A) + Trace(B)
+
+
+def test_Trace_MatAdd_doit():
+ # See issue #9028
+ X = ImmutableMatrix([[1, 2, 3]]*3)
+ Y = MatrixSymbol('Y', 3, 3)
+ q = MatAdd(X, 2*X, Y, -3*Y)
+ assert Trace(q).arg == q
+ assert Trace(q).doit() == 18 - 2*Trace(Y)
+
+
+def test_Trace_MatPow_doit():
X = Matrix([[1, 2], [3, 4]])
assert Trace(X).doit() == 5
q = MatPow(X, 2)
assert Trace(q).arg == q
assert Trace(q).doit() == 29
- assert Trace(q).doit(deep=False).arg == q
def test_Trace_MutableMatrix_plus():
@@ -60,11 +74,22 @@ def test_Trace_MutableMatrix_plus():
@XFAIL
-def test_Trace_MatAdd_doit():
- # FIXME: Issue #9028.
+def test_Trace_doit_deep_False():
X = Matrix([[1, 2], [3, 4]])
+ q = MatPow(X, 2)
+ assert Trace(q).doit(deep=False).arg == q
q = MatAdd(X, 2*X)
assert Trace(q).doit(deep=False).arg == q
+ q = MatMul(X, 2*X)
+ assert Trace(q).doit(deep=False).arg == q
+
+
+@XFAIL
+def test_trace_constant_factor():
+ # Issue 9052: LHS gives Trace(MatMul(A))
+ assert trace(2*A) == 2*Trace(A)
+ X = ImmutableMatrix([[1, 2], [3, 4]])
+ assert trace(MatMul(2, X)) == 10
@XFAIL
| {
"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": 3
},
"num_modified_files": 1
} | 0.7 | {
"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.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
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
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
-e git+https://github.com/sympy/sympy.git@aa175f44f96e3b94c08804645d2388b2a79df13c#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/matrices/expressions/tests/test_trace.py::test_Trace_A_plus_B",
"sympy/matrices/expressions/tests/test_trace.py::test_Trace_MatAdd_doit"
] | [] | [
"sympy/matrices/expressions/tests/test_matmul.py::test_adjoint",
"sympy/matrices/expressions/tests/test_matmul.py::test_transpose",
"sympy/matrices/expressions/tests/test_matmul.py::test_factor_in_front",
"sympy/matrices/expressions/tests/test_matmul.py::test_remove_ids",
"sympy/matrices/expressions/tests/test_matmul.py::test_xxinv",
"sympy/matrices/expressions/tests/test_matmul.py::test_any_zeros",
"sympy/matrices/expressions/tests/test_matmul.py::test_unpack",
"sympy/matrices/expressions/tests/test_matmul.py::test_only_squares",
"sympy/matrices/expressions/tests/test_matmul.py::test_determinant",
"sympy/matrices/expressions/tests/test_matmul.py::test_doit",
"sympy/matrices/expressions/tests/test_matmul.py::test_doit_drills_down",
"sympy/matrices/expressions/tests/test_matmul.py::test_doit_deep_false_still_canonical",
"sympy/matrices/expressions/tests/test_matmul.py::test_matmul_sympify",
"sympy/matrices/expressions/tests/test_matmul.py::test_collapse_MatrixBase",
"sympy/matrices/expressions/tests/test_matmul.py::test_refine",
"sympy/matrices/expressions/tests/test_trace.py::test_Trace",
"sympy/matrices/expressions/tests/test_trace.py::test_Trace_MatPow_doit",
"sympy/matrices/expressions/tests/test_trace.py::test_Trace_MutableMatrix_plus"
] | [] | BSD | 47 |
sympy__sympy-9071 | 85aa425bee35bd485eb4b6b3e6dfb38767997abd | 2015-02-27 21:44:51 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | leosartaj: @smichr
debugger22: Please update your branch with master. | diff --git a/sympy/core/expr.py b/sympy/core/expr.py
index 0de02ff424..c047f157f3 100644
--- a/sympy/core/expr.py
+++ b/sympy/core/expr.py
@@ -2307,6 +2307,9 @@ def is_rational_function(self, *syms):
See also is_algebraic_expr().
"""
+ if self in [S.NaN, S.Infinity, -S.Infinity, S.ComplexInfinity]:
+ return False
+
if syms:
syms = set(map(sympify, syms))
else:
| `nan` is a rational function
In `is_rational_function()`, there's a line which states that if the intersection of the expression's free symbols is an empty set, then the expression is a *constant rational function*. Thus, `nan.is_rational_function()` is `True`, and this behaviour causes bugs like #8414.
I guess that a simple check of `if self is nan` or so just before `return True` should fix that bug. However, there may be some implications that I miss, so I leave it as an issue rather than as a pull request. | sympy/sympy | diff --git a/sympy/core/tests/test_expr.py b/sympy/core/tests/test_expr.py
index 2876515a49..d0fe697665 100644
--- a/sympy/core/tests/test_expr.py
+++ b/sympy/core/tests/test_expr.py
@@ -417,6 +417,11 @@ def test_is_rational_function():
assert (sin(y)/x).is_rational_function(x) is True
assert (sin(y)/x).is_rational_function(x, y) is False
+ assert (S.NaN).is_rational_function() is False
+ assert (S.Infinity).is_rational_function() is False
+ assert (-S.Infinity).is_rational_function() is False
+ assert (S.ComplexInfinity).is_rational_function() is False
+
def test_is_algebraic_expr():
assert sqrt(3).is_algebraic_expr(x) is True
| {
"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.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y python3-dev python3-pip"
],
"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
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
mpmath==1.3.0
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/sympy/sympy.git@85aa425bee35bd485eb4b6b3e6dfb38767997abd#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_expr.py::test_is_rational_function"
] | [] | [
"sympy/core/tests/test_expr.py::test_basic",
"sympy/core/tests/test_expr.py::test_ibasic",
"sympy/core/tests/test_expr.py::test_relational",
"sympy/core/tests/test_expr.py::test_relational_assumptions",
"sympy/core/tests/test_expr.py::test_relational_noncommutative",
"sympy/core/tests/test_expr.py::test_basic_nostr",
"sympy/core/tests/test_expr.py::test_series_expansion_for_uniform_order",
"sympy/core/tests/test_expr.py::test_leadterm",
"sympy/core/tests/test_expr.py::test_as_leading_term",
"sympy/core/tests/test_expr.py::test_leadterm2",
"sympy/core/tests/test_expr.py::test_leadterm3",
"sympy/core/tests/test_expr.py::test_as_leading_term2",
"sympy/core/tests/test_expr.py::test_as_leading_term3",
"sympy/core/tests/test_expr.py::test_as_leading_term4",
"sympy/core/tests/test_expr.py::test_as_leading_term_stub",
"sympy/core/tests/test_expr.py::test_atoms",
"sympy/core/tests/test_expr.py::test_is_polynomial",
"sympy/core/tests/test_expr.py::test_is_algebraic_expr",
"sympy/core/tests/test_expr.py::test_SAGE1",
"sympy/core/tests/test_expr.py::test_SAGE2",
"sympy/core/tests/test_expr.py::test_SAGE3",
"sympy/core/tests/test_expr.py::test_len",
"sympy/core/tests/test_expr.py::test_doit",
"sympy/core/tests/test_expr.py::test_attribute_error",
"sympy/core/tests/test_expr.py::test_args",
"sympy/core/tests/test_expr.py::test_noncommutative_expand_issue_3757",
"sympy/core/tests/test_expr.py::test_as_numer_denom",
"sympy/core/tests/test_expr.py::test_as_independent",
"sympy/core/tests/test_expr.py::test_replace",
"sympy/core/tests/test_expr.py::test_find",
"sympy/core/tests/test_expr.py::test_count",
"sympy/core/tests/test_expr.py::test_has_basics",
"sympy/core/tests/test_expr.py::test_has_multiple",
"sympy/core/tests/test_expr.py::test_has_piecewise",
"sympy/core/tests/test_expr.py::test_has_iterative",
"sympy/core/tests/test_expr.py::test_has_integrals",
"sympy/core/tests/test_expr.py::test_has_tuple",
"sympy/core/tests/test_expr.py::test_has_units",
"sympy/core/tests/test_expr.py::test_has_polys",
"sympy/core/tests/test_expr.py::test_has_physics",
"sympy/core/tests/test_expr.py::test_as_poly_as_expr",
"sympy/core/tests/test_expr.py::test_nonzero",
"sympy/core/tests/test_expr.py::test_is_number",
"sympy/core/tests/test_expr.py::test_as_coeff_add",
"sympy/core/tests/test_expr.py::test_as_coeff_mul",
"sympy/core/tests/test_expr.py::test_as_coeff_exponent",
"sympy/core/tests/test_expr.py::test_extractions",
"sympy/core/tests/test_expr.py::test_coeff",
"sympy/core/tests/test_expr.py::test_coeff2",
"sympy/core/tests/test_expr.py::test_coeff2_0",
"sympy/core/tests/test_expr.py::test_coeff_expand",
"sympy/core/tests/test_expr.py::test_integrate",
"sympy/core/tests/test_expr.py::test_as_base_exp",
"sympy/core/tests/test_expr.py::test_issue_4963",
"sympy/core/tests/test_expr.py::test_action_verbs",
"sympy/core/tests/test_expr.py::test_as_powers_dict",
"sympy/core/tests/test_expr.py::test_as_coefficients_dict",
"sympy/core/tests/test_expr.py::test_args_cnc",
"sympy/core/tests/test_expr.py::test_new_rawargs",
"sympy/core/tests/test_expr.py::test_issue_5226",
"sympy/core/tests/test_expr.py::test_free_symbols",
"sympy/core/tests/test_expr.py::test_issue_5300",
"sympy/core/tests/test_expr.py::test_as_coeff_Mul",
"sympy/core/tests/test_expr.py::test_as_coeff_Add",
"sympy/core/tests/test_expr.py::test_expr_sorting",
"sympy/core/tests/test_expr.py::test_as_ordered_factors",
"sympy/core/tests/test_expr.py::test_as_ordered_terms",
"sympy/core/tests/test_expr.py::test_sort_key_atomic_expr",
"sympy/core/tests/test_expr.py::test_issue_4199",
"sympy/core/tests/test_expr.py::test_eval_interval_zoo",
"sympy/core/tests/test_expr.py::test_primitive",
"sympy/core/tests/test_expr.py::test_issue_5843",
"sympy/core/tests/test_expr.py::test_is_constant",
"sympy/core/tests/test_expr.py::test_equals",
"sympy/core/tests/test_expr.py::test_random",
"sympy/core/tests/test_expr.py::test_round",
"sympy/core/tests/test_expr.py::test_round_exception_nostr",
"sympy/core/tests/test_expr.py::test_extract_branch_factor",
"sympy/core/tests/test_expr.py::test_identity_removal",
"sympy/core/tests/test_expr.py::test_float_0",
"sympy/core/tests/test_expr.py::test_issue_6325",
"sympy/core/tests/test_expr.py::test_issue_7426"
] | [] | BSD | 48 |
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 |
|
sympy__sympy-9078 | 0799c9788b34a1ed9c2292f5e0e48998e518ca84 | 2015-03-01 14:40:34 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | toolforger: Looks good to me. However, I'm not familiar enough with list comprehensions to be 100% sure that lambda expression and list comprehension are always equivalent, so somebody else will have to verify that.
I have made a few proposals for further improvement, but there's always the case of "do not fix more than one thing at a time in a PR, so it remains reviewable"; so maybe it's better to postpone these to a subsequent PR.
jcrist: Looks good, besides my one last comment. Please fix, and squash your commits into one. Will merge after that. | diff --git a/sympy/combinatorics/partitions.py b/sympy/combinatorics/partitions.py
index 5e7147b80e..a98decdda7 100644
--- a/sympy/combinatorics/partitions.py
+++ b/sympy/combinatorics/partitions.py
@@ -58,7 +58,7 @@ def __new__(cls, *partition):
if has_dups(partition):
raise ValueError("Partition contained duplicated elements.")
- obj = FiniteSet.__new__(cls, *list(map(lambda x: FiniteSet(*x), args)))
+ obj = FiniteSet.__new__(cls, *[FiniteSet(*x) for x in args])
obj.members = tuple(partition)
obj.size = len(partition)
return obj
diff --git a/sympy/core/function.py b/sympy/core/function.py
index 56bb4a4959..aa23188d22 100644
--- a/sympy/core/function.py
+++ b/sympy/core/function.py
@@ -1299,7 +1299,7 @@ def _eval_subs(self, old, new):
if match:
variables = self_vars_front + self_vars
return Derivative(new, *variables)
- return Derivative(*map(lambda x: x._subs(old, new), self.args))
+ return Derivative(*(x._subs(old, new) for x in self.args))
def _eval_lseries(self, x, logx):
dx = self.args[1:]
diff --git a/sympy/functions/elementary/complexes.py b/sympy/functions/elementary/complexes.py
index 1a5987b2a2..3b89505812 100644
--- a/sympy/functions/elementary/complexes.py
+++ b/sympy/functions/elementary/complexes.py
@@ -82,8 +82,7 @@ def eval(cls, arg):
included.append(term)
if len(args) != len(included):
- a, b, c = map(lambda xs: Add(*xs),
- [included, reverted, excluded])
+ a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
return cls(a) - im(b) + c
@@ -178,8 +177,7 @@ def eval(cls, arg):
included.append(term)
if len(args) != len(included):
- a, b, c = map(lambda xs: Add(*xs),
- [included, reverted, excluded])
+ a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
return cls(a) + re(b) + c
diff --git a/sympy/galgebra/ga.py b/sympy/galgebra/ga.py
index f597f5a173..ec7733748d 100644
--- a/sympy/galgebra/ga.py
+++ b/sympy/galgebra/ga.py
@@ -285,14 +285,14 @@ def make_vector(self, base): # make a vector (grade 1)
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=1, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[1]))))
+ self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[1])))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=1, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=1, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[1]))))
+ self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[1])))
else:
result = S.Zero
for (coef, base) in zip(base, MV.blades[1]):
@@ -316,14 +316,14 @@ def make_grade(self, base): # if base is 'A,n' then make a grade n multivector
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=n, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[n]))))
+ self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[n])))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=n, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=n, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[n]))))
+ self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[n])))
else:
raise TypeError('Cannot make_grade for base = %s' % base)
self.igrade = n
@@ -335,14 +335,14 @@ def make_grade2(self, base): # grade 2 multivector
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=2, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[2]))))
+ self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[2])))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=2, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=2, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[2]))))
+ self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[2])))
else:
raise TypeError('!!!!Cannot make_grade2 for base = ' + str(base) + '!!!!\n')
self.igrade = 2
@@ -354,14 +354,14 @@ def make_pseudo(self, base): # multivector of grade MV.dim
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=MV.dim, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[MV.dim]))))
+ self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[MV.dim])))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=MV.dim, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=MV.dim, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[MV.dim]))))
+ self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[MV.dim])))
else:
raise TypeError('!!!!Cannot make_pseudo for base = ' + str(base) + '!!!!\n')
self.igrade = MV.dim
@@ -378,14 +378,14 @@ def make_spinor(self, base): # multivector with all even grades
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
+ self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=rank, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
+ self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
else:
raise TypeError('Cannot make_mv for base = %s' % base)
self.igrade = -1
@@ -402,14 +402,14 @@ def make_mv(self, base):
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
+ self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=rank, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
+ self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
else:
raise TypeError('!!!!Cannot make_mv for base = ' + str(base) + '!!!!\n')
self.igrade = -1
diff --git a/sympy/galgebra/stringarrays.py b/sympy/galgebra/stringarrays.py
index 34ebca2984..2e97cfcde5 100644
--- a/sympy/galgebra/stringarrays.py
+++ b/sympy/galgebra/stringarrays.py
@@ -103,6 +103,7 @@ def str_combinations(base, lst, rank=1, mode='_'):
forming the 'indexes' by concatenating combinations of elements from
'lst' taken 'rank' at a time.
"""
- str_lst = list(map(lambda x: base + mode + x, map(lambda x: reduce(operator.add, x),
- combinations(map(lambda x: str(x), lst), rank))))
+ a1 = combinations([str(x) for x in lst], rank)
+ a2 = [reduce(operator.add, x) for x in a1]
+ str_lst = [base + mode + x for x in a2]
return str_lst
diff --git a/sympy/matrices/dense.py b/sympy/matrices/dense.py
index 7289638224..2555ea86a1 100644
--- a/sympy/matrices/dense.py
+++ b/sympy/matrices/dense.py
@@ -804,8 +804,7 @@ def col_op(self, j, f):
col
row_op
"""
- self._mat[j::self.cols] = list(map(lambda t: f(*t),
- list(zip(self._mat[j::self.cols], list(range(self.rows))))))
+ self._mat[j::self.cols] = [f(*t) for t in list(zip(self._mat[j::self.cols], list(range(self.rows))))]
def row_swap(self, i, j):
"""Swap the two given rows of the matrix in-place.
diff --git a/sympy/matrices/matrices.py b/sympy/matrices/matrices.py
index 864b2ab17e..927ea291cd 100644
--- a/sympy/matrices/matrices.py
+++ b/sympy/matrices/matrices.py
@@ -562,7 +562,7 @@ def __add__(self, other):
blst = B.tolist()
ret = [S.Zero]*A.rows
for i in range(A.shape[0]):
- ret[i] = list(map(lambda j, k: j + k, alst[i], blst[i]))
+ ret[i] = [j + k for j, k in zip(alst[i], blst[i])]
rv = classof(A, B)._new(ret)
if 0 in A.shape:
rv = rv.reshape(*A.shape)
diff --git a/sympy/physics/quantum/operatorset.py b/sympy/physics/quantum/operatorset.py
index 0faa70b95c..26e2f5c687 100644
--- a/sympy/physics/quantum/operatorset.py
+++ b/sympy/physics/quantum/operatorset.py
@@ -262,7 +262,7 @@ def _get_ops(state_inst, op_classes, **options):
ret = state_inst._state_to_operators(op_classes, **options)
except NotImplementedError:
if isinstance(op_classes, (set, tuple, frozenset)):
- ret = tuple(map(lambda x: _make_default(x), op_classes))
+ ret = tuple(_make_default(x) for x in op_classes)
else:
ret = _make_default(op_classes)
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index d3ee4523d3..c619b1d4c8 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -87,10 +87,10 @@
'scr': lambda s: r'\mathscr{'+s+r'}',
'frak': lambda s: r'\mathfrak{'+s+r'}',
# Brackets
- 'norm': lambda s: r'\left\|{'+s+r'}\right\|',
+ 'norm': lambda s: r'\left\lVert{'+s+r'}\right\rVert',
'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle',
'abs': lambda s: r'\left|{'+s+r'}\right|',
- 'mag': lambda s: r'\left|{'+s+r'}\right|',
+ 'mag': lambda s: r'\left\lvert{'+s+r'}\right\rvert',
}
greek_letters_set = frozenset(greeks)
@@ -1449,7 +1449,7 @@ def _print_KroneckerDelta(self, expr, exp=None):
def _print_LeviCivita(self, expr, exp=None):
indices = map(self._print, expr.args)
- if all(map(lambda x: x.is_Atom, expr.args)):
+ if all(x.is_Atom for x in expr.args):
tex = r'\varepsilon_{%s}' % " ".join(indices)
else:
tex = r'\varepsilon_{%s}' % ", ".join(indices)
diff --git a/sympy/printing/octave.py b/sympy/printing/octave.py
index 2b25c57492..b7b28f561d 100644
--- a/sympy/printing/octave.py
+++ b/sympy/printing/octave.py
@@ -149,8 +149,8 @@ def _print_Mul(self, expr):
a = a or [S.One]
- a_str = list(map(lambda x: self.parenthesize(x, prec), a))
- b_str = list(map(lambda x: self.parenthesize(x, prec), b))
+ a_str = [self.parenthesize(x, prec) for x in a]
+ b_str = [self.parenthesize(x, prec) for x in b]
# from here it differs from str.py to deal with "*" and ".*"
def multjoin(a, a_str):
diff --git a/sympy/printing/str.py b/sympy/printing/str.py
index 63012e2940..29b4ce5979 100644
--- a/sympy/printing/str.py
+++ b/sympy/printing/str.py
@@ -280,8 +280,8 @@ def _print_Mul(self, expr):
a = a or [S.One]
- a_str = list(map(lambda x: self.parenthesize(x, prec), a))
- b_str = list(map(lambda x: self.parenthesize(x, prec), b))
+ a_str = [self.parenthesize(x, prec) for x in a]
+ b_str = [self.parenthesize(x, prec) for x in b]
if len(b) == 0:
return sign + '*'.join(a_str)
diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index aba2a6ce21..d70309a504 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -584,7 +584,7 @@ def _eval_Eq(self, other):
if len(self.args) != len(other.args):
return false
- return And(*map(lambda x, y: Eq(x, y), self.args, other.args))
+ return And(*(Eq(x, y) for x, y in zip(self.args, other.args)))
def _contains(self, element):
"""
@@ -1698,7 +1698,7 @@ def _eval_Eq(self, other):
if len(self) != len(other):
return false
- return And(*map(lambda x, y: Eq(x, y), self.args, other.args))
+ return And(*(Eq(x, y) for x, y in zip(self.args, other.args)))
def __iter__(self):
return iter(self.args)
diff --git a/sympy/solvers/ode.py b/sympy/solvers/ode.py
index 29cd1edc08..4cc2f5fba4 100644
--- a/sympy/solvers/ode.py
+++ b/sympy/solvers/ode.py
@@ -2490,7 +2490,7 @@ def _recursive_walk(expr):
Ces.append(x)
elif isinstance(expr, C.Integral):
if expr.free_symbols.issubset(Cs) and \
- all(map(lambda x: len(x) == 3, expr.limits)):
+ all(len(x) == 3 for x in expr.limits):
Ces.append(expr)
for i in expr.args:
_recursive_walk(i)
diff --git a/sympy/solvers/pde.py b/sympy/solvers/pde.py
index 7ead7a0d0f..85a4705c56 100644
--- a/sympy/solvers/pde.py
+++ b/sympy/solvers/pde.py
@@ -443,8 +443,7 @@ def checkpdesol(pde, sol, func=None, solve_for_func=True):
# If the given solution is in the form of a list or a set
# then return a list or set of tuples.
if is_sequence(sol, set):
- return type(sol)(map(lambda i: checkpdesol(pde, i,
- solve_for_func=solve_for_func), sol))
+ return type(sol)([checkpdesol(pde, i, solve_for_func=solve_for_func) for i in sol])
# Convert solution into an equation
if not isinstance(sol, Equality):
| Replace map() with a list compression in most cases
```
If you've been programming in Python for long enough, you know about the magic of list comprehensions. They can
make what would otherwise be a short for loop or a map() into a very simple, easy to understand, one line
expression.
Before they were introduced, the best way to do this sort of thing was with the use of map(), and probably a lambda
function. But anything that uses lambda is very difficult to read, and map() even without lambda is harder to read
than a list compression in almost all cases.
So I think we should replace most instances of map in the code with a list comprehension. The exception might be
the use of f, g, h = map(Function, 'fgh') in the docstrings. map(lambda… is the worst in my opinion, and git gr
'map(lambda' reveals around 25 of these.
Of course, performance is also an issue. While we should test the performance of each instance that we actually
change, here are some simple benchmarks:
###
First, cache the function and the list.
###
In [1]: def f(x):
...: return x**2
...:
In [2]: a = range(100)
In [4]: %timeit map(f, a)
10000 loops, best of 3: 128 us per loop
In [5]: %timeit [f(x) for x in a]
10000 loops, best of 3: 162 us per loop
###
So map is slightly faster in this case.
But what if we don't cache the function or the list, but use lambda instead?
###
In [8]: %timeit map(lambda x: x**2, range(100))
10000 loops, best of 3: 145 us per loop
In [9]: %timeit [x**2 for x in range(100)]
10000 loops, best of 3: 64.4 us per loop
###
The use of lambda actually makes map 2x slower than a list comprehension.
It becomes even clearer if we cache only the list.
###
In [10]: %timeit [x**2 for x in a]
10000 loops, best of 3: 58.9 us per loop
In [11]: %timeit map(lambda x: x**2, a)
10000 loops, best of 3: 158 us per loop
In [12]: %timeit map(lambda x: f(x), a)
10000 loops, best of 3: 246 us per loop
###
Which is 3x faster for list comprehensions, or 6x if lambda is used
unnecessarily, which it actually doesn't seem to be anywhere in sympy.
lambda is usually used to call a multi-argument function with map()
###
In [13]: def g(x, y):
....: return x**2*y
....:
In [14]: %timeit map(lambda x: g(x, 10), a)
1000 loops, best of 3: 313 us per loop
In [15]: %timeit [g(x, 10) for x in a]
10000 loops, best of 3: 212 us per loop
###
One last example I ran (x is a Symbol):
###
In [6]: %timeit [x**i for i in range(100)]
1000 loops, best of 3: 2.78 ms per loop
In [7]: %timeit map(lambda i: x**i, range(100))
1000 loops, best of 3: 2.81 ms per loop
I've already done this for ode.py in my WIP ode-coverage branch.
```
Original issue for #4940: http://code.google.com/p/sympy/issues/detail?id=1841
Original author: https://code.google.com/u/[email protected]/
Original owner: https://code.google.com/u/[email protected]/
| sympy/sympy | diff --git a/bin/coverage_doctest.py b/bin/coverage_doctest.py
index 5f3f20f6c0..02e4c77198 100755
--- a/bin/coverage_doctest.py
+++ b/bin/coverage_doctest.py
@@ -229,7 +229,7 @@ def _get_arg_list(name, fobj):
arg_list.append(argspec.keywords)
# Truncate long arguments
- arg_list = map(lambda x: x[:trunc], arg_list)
+ arg_list = [x[:trunc] for x in arg_list]
# Construct the parameter string (enclosed in brackets)
str_param = "%s(%s)" % (name, ', '.join(arg_list))
diff --git a/sympy/matrices/expressions/tests/test_blockmatrix.py b/sympy/matrices/expressions/tests/test_blockmatrix.py
index 75758a0c6c..e21567fa1e 100644
--- a/sympy/matrices/expressions/tests/test_blockmatrix.py
+++ b/sympy/matrices/expressions/tests/test_blockmatrix.py
@@ -97,12 +97,12 @@ def test_BlockMatrix():
def test_BlockMatrix_trace():
- A, B, C, D = map(lambda s: MatrixSymbol(s, 3, 3), 'ABCD')
+ A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
X = BlockMatrix([[A, B], [C, D]])
assert trace(X) == trace(A) + trace(D)
def test_BlockMatrix_Determinant():
- A, B, C, D = map(lambda s: MatrixSymbol(s, 3, 3), 'ABCD')
+ A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
X = BlockMatrix([[A, B], [C, D]])
from sympy import assuming, Q
with assuming(Q.invertible(A)):
diff --git a/sympy/printing/tests/test_dot.py b/sympy/printing/tests/test_dot.py
index 98fc75a48a..a8921ae7e3 100644
--- a/sympy/printing/tests/test_dot.py
+++ b/sympy/printing/tests/test_dot.py
@@ -44,15 +44,15 @@ def test_dotedges():
def test_dotprint():
text = dotprint(x+2, repeat=False)
assert all(e in text for e in dotedges(x+2, repeat=False))
- assert all(n in text for n in map(lambda expr: dotnode(expr, repeat=False), (x, Integer(2), x+2)))
+ assert all(n in text for n in [dotnode(expr, repeat=False) for expr in (x, Integer(2), x+2)])
assert 'digraph' in text
text = dotprint(x+x**2, repeat=False)
assert all(e in text for e in dotedges(x+x**2, repeat=False))
- assert all(n in text for n in map(lambda expr: dotnode(expr, repeat=False), (x, Integer(2), x**2)))
+ assert all(n in text for n in [dotnode(expr, repeat=False) for expr in (x, Integer(2), x**2)])
assert 'digraph' in text
text = dotprint(x+x**2, repeat=True)
assert all(e in text for e in dotedges(x+x**2, repeat=True))
- assert all(n in text for n in map(lambda expr: dotnode(expr, pos=()), [x + x**2]))
+ assert all(n in text for n in [dotnode(expr, pos=()) for expr in [x + x**2]])
text = dotprint(x**x, repeat=True)
assert all(e in text for e in dotedges(x**x, repeat=True))
assert all(n in text for n in [dotnode(x, pos=(0,)), dotnode(x, pos=(1,))])
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index c98cc8d400..b1b031df5a 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -1171,14 +1171,14 @@ def test_modifiers():
assert latex(symbols("xDdDot")) == r"\dddot{x}"
assert latex(symbols("xDDot")) == r"\ddot{x}"
assert latex(symbols("xBold")) == r"\boldsymbol{x}"
- assert latex(symbols("xnOrM")) == r"\left\|{x}\right\|"
+ assert latex(symbols("xnOrM")) == r"\left\lVert{x}\right\rVert"
assert latex(symbols("xAVG")) == r"\left\langle{x}\right\rangle"
assert latex(symbols("xHat")) == r"\hat{x}"
assert latex(symbols("xDot")) == r"\dot{x}"
assert latex(symbols("xBar")) == r"\bar{x}"
assert latex(symbols("xVec")) == r"\vec{x}"
assert latex(symbols("xAbs")) == r"\left|{x}\right|"
- assert latex(symbols("xMag")) == r"\left|{x}\right|"
+ assert latex(symbols("xMag")) == r"\left\lvert{x}\right\rvert"
assert latex(symbols("xPrM")) == r"{x}'"
assert latex(symbols("xBM")) == r"\boldsymbol{x}"
# Test strings that are *only* the names of modifiers
@@ -1205,7 +1205,7 @@ def test_modifiers():
# Check a few combinations
assert latex(symbols("xvecdot")) == r"\dot{\vec{x}}"
assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}"
- assert latex(symbols("xHATNorm")) == r"\left\|{\hat{x}}\right\|"
+ assert latex(symbols("xHATNorm")) == r"\left\lVert{\hat{x}}\right\rVert"
# Check a couple big, ugly combinations
assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}"
assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}"
diff --git a/sympy/simplify/tests/test_hyperexpand.py b/sympy/simplify/tests/test_hyperexpand.py
index 61c71c4cfd..3a2ed35276 100644
--- a/sympy/simplify/tests/test_hyperexpand.py
+++ b/sympy/simplify/tests/test_hyperexpand.py
@@ -214,7 +214,7 @@ def test_plan():
devise_plan(Hyper_Function([2], []), Hyper_Function([S("1/2")], []), z)
# We cannot use pi/(10000 + n) because polys is insanely slow.
- a1, a2, b1 = map(lambda n: randcplx(n), range(3))
+ a1, a2, b1 = (randcplx(n) for n in range(3))
b1 += 2*I
h = hyper([a1, a2], [b1], z)
@@ -247,7 +247,7 @@ def test_plan_derivatives():
def test_reduction_operators():
- a1, a2, b1 = map(lambda n: randcplx(n), range(3))
+ a1, a2, b1 = (randcplx(n) for n in range(3))
h = hyper([a1], [b1], z)
assert ReduceOrder(2, 0) is None
@@ -273,7 +273,7 @@ def test_reduction_operators():
def test_shift_operators():
- a1, a2, b1, b2, b3 = map(lambda n: randcplx(n), range(5))
+ a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5))
h = hyper((a1, a2), (b1, b2, b3), z)
raises(ValueError, lambda: ShiftA(0))
@@ -287,7 +287,7 @@ def test_shift_operators():
def test_ushift_operators():
- a1, a2, b1, b2, b3 = map(lambda n: randcplx(n), range(5))
+ a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5))
h = hyper((a1, a2), (b1, b2, b3), z)
raises(ValueError, lambda: UnShiftA((1,), (), 0, z))
@@ -435,9 +435,9 @@ def test_meijerg():
# carefully set up the parameters.
# NOTE: this used to fail sometimes. I believe it is fixed, but if you
# hit an inexplicable test failure here, please let me know the seed.
- a1, a2 = map(lambda n: randcplx() - 5*I - n*I, range(2))
- b1, b2 = map(lambda n: randcplx() + 5*I + n*I, range(2))
- b3, b4, b5, a3, a4, a5 = map(lambda n: randcplx(), range(6))
+ a1, a2 = (randcplx(n) - 5*I - n*I for n in range(2))
+ b1, b2 = (randcplx(n) + 5*I + n*I for n in range(2))
+ b3, b4, b5, a3, a4, a5 = (randcplx() for n in range(6))
g = meijerg([a1], [a3, a4], [b1], [b3, b4], z)
assert ReduceOrder.meijer_minus(3, 4) is None
@@ -471,8 +471,7 @@ def test_meijerg():
def test_meijerg_shift_operators():
# carefully set up the parameters. XXX this still fails sometimes
- a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 = \
- map(lambda n: randcplx(n), range(10))
+ a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 = (randcplx(n) for n in range(10))
g = meijerg([a1], [a3, a4], [b1], [b3, b4], z)
assert tn(MeijerShiftA(b1).apply(g, op),
@@ -588,7 +587,7 @@ def test_lerchphi():
def test_partial_simp():
# First test that hypergeometric function formulae work.
- a, b, c, d, e = map(lambda _: randcplx(), range(5))
+ a, b, c, d, e = (randcplx() for _ in range(5))
for func in [Hyper_Function([a, b, c], [d, e]),
Hyper_Function([], [a, b, c, d, e])]:
f = build_hypergeometric_formula(func)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"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": 14
} | 0.7 | {
"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.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
mpmath==1.3.0
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/sympy/sympy.git@0799c9788b34a1ed9c2292f5e0e48998e518ca84#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/printing/tests/test_latex.py::test_modifiers"
] | [] | [
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_bc_matmul",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_bc_matadd",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_bc_transpose",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_bc_dist_diag",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_block_plus_ident",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_BlockMatrix",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_BlockMatrix_trace",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_BlockMatrix_Determinant",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_squareBlockMatrix",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_BlockDiagMatrix",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_blockcut",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_reblock_2x2",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_deblock",
"sympy/printing/tests/test_dot.py::test_purestr",
"sympy/printing/tests/test_dot.py::test_styleof",
"sympy/printing/tests/test_dot.py::test_attrprint",
"sympy/printing/tests/test_dot.py::test_dotnode",
"sympy/printing/tests/test_dot.py::test_dotedges",
"sympy/printing/tests/test_dot.py::test_dotprint",
"sympy/printing/tests/test_dot.py::test_dotprint_depth",
"sympy/printing/tests/test_dot.py::test_Matrix_and_non_basics",
"sympy/printing/tests/test_dot.py::test_labelfunc",
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117",
"sympy/simplify/tests/test_hyperexpand.py::test_branch_bug",
"sympy/simplify/tests/test_hyperexpand.py::test_hyperexpand",
"sympy/simplify/tests/test_hyperexpand.py::test_roach",
"sympy/simplify/tests/test_hyperexpand.py::test_polynomial",
"sympy/simplify/tests/test_hyperexpand.py::test_hyperexpand_bases",
"sympy/simplify/tests/test_hyperexpand.py::test_hyperexpand_parametric",
"sympy/simplify/tests/test_hyperexpand.py::test_shifted_sum",
"sympy/simplify/tests/test_hyperexpand.py::test_formulae",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg_formulae",
"sympy/simplify/tests/test_hyperexpand.py::test_plan",
"sympy/simplify/tests/test_hyperexpand.py::test_plan_derivatives",
"sympy/simplify/tests/test_hyperexpand.py::test_reduction_operators",
"sympy/simplify/tests/test_hyperexpand.py::test_shift_operators",
"sympy/simplify/tests/test_hyperexpand.py::test_ushift_operators",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg_expand",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg_lookup",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg_shift_operators",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg_confluence",
"sympy/simplify/tests/test_hyperexpand.py::test_lerchphi",
"sympy/simplify/tests/test_hyperexpand.py::test_partial_simp",
"sympy/simplify/tests/test_hyperexpand.py::test_hyperexpand_special",
"sympy/simplify/tests/test_hyperexpand.py::test_Mod1_behavior",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_misc",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_1",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_2",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_3",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_4",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_5",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_6",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_7",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_8",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_9",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_10",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_11",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_12",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_2F1",
"sympy/simplify/tests/test_hyperexpand.py::test_bug"
] | [] | BSD | 50 |
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 |
|
sympy__sympy-9084 | 0844595e819e5ea6b161162781df14efd9e81b63 | 2015-03-02 15:31:24 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/combinatorics/partitions.py b/sympy/combinatorics/partitions.py
index a98decdda7..5e7147b80e 100644
--- a/sympy/combinatorics/partitions.py
+++ b/sympy/combinatorics/partitions.py
@@ -58,7 +58,7 @@ def __new__(cls, *partition):
if has_dups(partition):
raise ValueError("Partition contained duplicated elements.")
- obj = FiniteSet.__new__(cls, *[FiniteSet(*x) for x in args])
+ obj = FiniteSet.__new__(cls, *list(map(lambda x: FiniteSet(*x), args)))
obj.members = tuple(partition)
obj.size = len(partition)
return obj
diff --git a/sympy/core/function.py b/sympy/core/function.py
index aa23188d22..56bb4a4959 100644
--- a/sympy/core/function.py
+++ b/sympy/core/function.py
@@ -1299,7 +1299,7 @@ def _eval_subs(self, old, new):
if match:
variables = self_vars_front + self_vars
return Derivative(new, *variables)
- return Derivative(*(x._subs(old, new) for x in self.args))
+ return Derivative(*map(lambda x: x._subs(old, new), self.args))
def _eval_lseries(self, x, logx):
dx = self.args[1:]
diff --git a/sympy/functions/elementary/complexes.py b/sympy/functions/elementary/complexes.py
index 3b89505812..1a5987b2a2 100644
--- a/sympy/functions/elementary/complexes.py
+++ b/sympy/functions/elementary/complexes.py
@@ -82,7 +82,8 @@ def eval(cls, arg):
included.append(term)
if len(args) != len(included):
- a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
+ a, b, c = map(lambda xs: Add(*xs),
+ [included, reverted, excluded])
return cls(a) - im(b) + c
@@ -177,7 +178,8 @@ def eval(cls, arg):
included.append(term)
if len(args) != len(included):
- a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
+ a, b, c = map(lambda xs: Add(*xs),
+ [included, reverted, excluded])
return cls(a) + re(b) + c
diff --git a/sympy/galgebra/ga.py b/sympy/galgebra/ga.py
index ec7733748d..f597f5a173 100644
--- a/sympy/galgebra/ga.py
+++ b/sympy/galgebra/ga.py
@@ -285,14 +285,14 @@ def make_vector(self, base): # make a vector (grade 1)
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=1, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[1])))
+ self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[1]))))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=1, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=1, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[1])))
+ self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[1]))))
else:
result = S.Zero
for (coef, base) in zip(base, MV.blades[1]):
@@ -316,14 +316,14 @@ def make_grade(self, base): # if base is 'A,n' then make a grade n multivector
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=n, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[n])))
+ self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[n]))))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=n, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=n, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[n])))
+ self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[n]))))
else:
raise TypeError('Cannot make_grade for base = %s' % base)
self.igrade = n
@@ -335,14 +335,14 @@ def make_grade2(self, base): # grade 2 multivector
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=2, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[2])))
+ self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[2]))))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=2, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=2, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[2])))
+ self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[2]))))
else:
raise TypeError('!!!!Cannot make_grade2 for base = ' + str(base) + '!!!!\n')
self.igrade = 2
@@ -354,14 +354,14 @@ def make_pseudo(self, base): # multivector of grade MV.dim
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=MV.dim, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[MV.dim])))
+ self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[MV.dim]))))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=MV.dim, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=MV.dim, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj = reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[MV.dim])))
+ self.obj = reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[MV.dim]))))
else:
raise TypeError('!!!!Cannot make_pseudo for base = ' + str(base) + '!!!!\n')
self.igrade = MV.dim
@@ -378,14 +378,14 @@ def make_spinor(self, base): # multivector with all even grades
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
+ self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=rank, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
+ self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
else:
raise TypeError('Cannot make_mv for base = %s' % base)
self.igrade = -1
@@ -402,14 +402,14 @@ def make_mv(self, base):
if self.fct:
base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
fct_lst = fct_sym_array(base_lst, MV.coords)
- self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
+ self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
else:
if MV.coords is not None:
base_lst = str_combinations(base, MV.coords, rank=rank, mode='__')
else:
base_lst = str_combinations(base, MV.subscripts, rank=rank, mode='__')
fct_lst = fct_sym_array(base_lst, None)
- self.obj += reduce(operator.add, tuple(x0 * x1 for x0, x1 in zip(fct_lst, MV.blades[rank])))
+ self.obj += reduce(operator.add, tuple(map(lambda x: x[0] * x[1], zip(fct_lst, MV.blades[rank]))))
else:
raise TypeError('!!!!Cannot make_mv for base = ' + str(base) + '!!!!\n')
self.igrade = -1
diff --git a/sympy/galgebra/stringarrays.py b/sympy/galgebra/stringarrays.py
index 2e97cfcde5..34ebca2984 100644
--- a/sympy/galgebra/stringarrays.py
+++ b/sympy/galgebra/stringarrays.py
@@ -103,7 +103,6 @@ def str_combinations(base, lst, rank=1, mode='_'):
forming the 'indexes' by concatenating combinations of elements from
'lst' taken 'rank' at a time.
"""
- a1 = combinations([str(x) for x in lst], rank)
- a2 = [reduce(operator.add, x) for x in a1]
- str_lst = [base + mode + x for x in a2]
+ str_lst = list(map(lambda x: base + mode + x, map(lambda x: reduce(operator.add, x),
+ combinations(map(lambda x: str(x), lst), rank))))
return str_lst
diff --git a/sympy/matrices/dense.py b/sympy/matrices/dense.py
index 2555ea86a1..7289638224 100644
--- a/sympy/matrices/dense.py
+++ b/sympy/matrices/dense.py
@@ -804,7 +804,8 @@ def col_op(self, j, f):
col
row_op
"""
- self._mat[j::self.cols] = [f(*t) for t in list(zip(self._mat[j::self.cols], list(range(self.rows))))]
+ self._mat[j::self.cols] = list(map(lambda t: f(*t),
+ list(zip(self._mat[j::self.cols], list(range(self.rows))))))
def row_swap(self, i, j):
"""Swap the two given rows of the matrix in-place.
diff --git a/sympy/matrices/matrices.py b/sympy/matrices/matrices.py
index 927ea291cd..864b2ab17e 100644
--- a/sympy/matrices/matrices.py
+++ b/sympy/matrices/matrices.py
@@ -562,7 +562,7 @@ def __add__(self, other):
blst = B.tolist()
ret = [S.Zero]*A.rows
for i in range(A.shape[0]):
- ret[i] = [j + k for j, k in zip(alst[i], blst[i])]
+ ret[i] = list(map(lambda j, k: j + k, alst[i], blst[i]))
rv = classof(A, B)._new(ret)
if 0 in A.shape:
rv = rv.reshape(*A.shape)
diff --git a/sympy/physics/quantum/operatorset.py b/sympy/physics/quantum/operatorset.py
index 26e2f5c687..0faa70b95c 100644
--- a/sympy/physics/quantum/operatorset.py
+++ b/sympy/physics/quantum/operatorset.py
@@ -262,7 +262,7 @@ def _get_ops(state_inst, op_classes, **options):
ret = state_inst._state_to_operators(op_classes, **options)
except NotImplementedError:
if isinstance(op_classes, (set, tuple, frozenset)):
- ret = tuple(_make_default(x) for x in op_classes)
+ ret = tuple(map(lambda x: _make_default(x), op_classes))
else:
ret = _make_default(op_classes)
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index 724341f899..07b5dd4363 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -1240,7 +1240,8 @@ def _print_Symbol(self, expr):
if expr in self._settings['symbol_names']:
return self._settings['symbol_names'][expr]
- return self._deal_with_super_sub(expr.name)
+ return self._deal_with_super_sub(expr.name) if \
+ '\\' not in expr.name else expr.name
_print_RandomSymbol = _print_Symbol
_print_MatrixSymbol = _print_Symbol
@@ -1449,7 +1450,7 @@ def _print_KroneckerDelta(self, expr, exp=None):
def _print_LeviCivita(self, expr, exp=None):
indices = map(self._print, expr.args)
- if all(x.is_Atom for x in expr.args):
+ if all(map(lambda x: x.is_Atom, expr.args)):
tex = r'\varepsilon_{%s}' % " ".join(indices)
else:
tex = r'\varepsilon_{%s}' % ", ".join(indices)
diff --git a/sympy/printing/octave.py b/sympy/printing/octave.py
index b7b28f561d..2b25c57492 100644
--- a/sympy/printing/octave.py
+++ b/sympy/printing/octave.py
@@ -149,8 +149,8 @@ def _print_Mul(self, expr):
a = a or [S.One]
- a_str = [self.parenthesize(x, prec) for x in a]
- b_str = [self.parenthesize(x, prec) for x in b]
+ a_str = list(map(lambda x: self.parenthesize(x, prec), a))
+ b_str = list(map(lambda x: self.parenthesize(x, prec), b))
# from here it differs from str.py to deal with "*" and ".*"
def multjoin(a, a_str):
diff --git a/sympy/printing/pretty/pretty_symbology.py b/sympy/printing/pretty/pretty_symbology.py
index 42cf37c982..93e5209cc3 100644
--- a/sympy/printing/pretty/pretty_symbology.py
+++ b/sympy/printing/pretty/pretty_symbology.py
@@ -53,6 +53,15 @@ def pretty_use_unicode(flag=None):
if flag is None:
return _use_unicode
+ # we know that some letters are not supported in Python 2.X so
+ # ignore those warnings. Remove this when 2.X support is dropped.
+ if unicode_warnings:
+ known = ['LATIN SUBSCRIPT SMALL LETTER %s' % i for i in 'HKLMNPST']
+ unicode_warnings = '\n'.join([
+ l for l in unicode_warnings.splitlines() if not any(
+ i in l for i in known)])
+ # ------------ end of 2.X warning filtering
+
if flag and unicode_warnings:
# print warnings (if any) on first unicode usage
warnings.warn(unicode_warnings)
diff --git a/sympy/printing/str.py b/sympy/printing/str.py
index 29b4ce5979..63012e2940 100644
--- a/sympy/printing/str.py
+++ b/sympy/printing/str.py
@@ -280,8 +280,8 @@ def _print_Mul(self, expr):
a = a or [S.One]
- a_str = [self.parenthesize(x, prec) for x in a]
- b_str = [self.parenthesize(x, prec) for x in b]
+ a_str = list(map(lambda x: self.parenthesize(x, prec), a))
+ b_str = list(map(lambda x: self.parenthesize(x, prec), b))
if len(b) == 0:
return sign + '*'.join(a_str)
diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py
index d70309a504..aba2a6ce21 100644
--- a/sympy/sets/sets.py
+++ b/sympy/sets/sets.py
@@ -584,7 +584,7 @@ def _eval_Eq(self, other):
if len(self.args) != len(other.args):
return false
- return And(*(Eq(x, y) for x, y in zip(self.args, other.args)))
+ return And(*map(lambda x, y: Eq(x, y), self.args, other.args))
def _contains(self, element):
"""
@@ -1698,7 +1698,7 @@ def _eval_Eq(self, other):
if len(self) != len(other):
return false
- return And(*(Eq(x, y) for x, y in zip(self.args, other.args)))
+ return And(*map(lambda x, y: Eq(x, y), self.args, other.args))
def __iter__(self):
return iter(self.args)
diff --git a/sympy/solvers/ode.py b/sympy/solvers/ode.py
index 4cc2f5fba4..29cd1edc08 100644
--- a/sympy/solvers/ode.py
+++ b/sympy/solvers/ode.py
@@ -2490,7 +2490,7 @@ def _recursive_walk(expr):
Ces.append(x)
elif isinstance(expr, C.Integral):
if expr.free_symbols.issubset(Cs) and \
- all(len(x) == 3 for x in expr.limits):
+ all(map(lambda x: len(x) == 3, expr.limits)):
Ces.append(expr)
for i in expr.args:
_recursive_walk(i)
diff --git a/sympy/solvers/pde.py b/sympy/solvers/pde.py
index 85a4705c56..7ead7a0d0f 100644
--- a/sympy/solvers/pde.py
+++ b/sympy/solvers/pde.py
@@ -443,7 +443,8 @@ def checkpdesol(pde, sol, func=None, solve_for_func=True):
# If the given solution is in the form of a list or a set
# then return a list or set of tuples.
if is_sequence(sol, set):
- return type(sol)([checkpdesol(pde, i, solve_for_func=solve_for_func) for i in sol])
+ return type(sol)(map(lambda i: checkpdesol(pde, i,
+ solve_for_func=solve_for_func), sol))
# Convert solution into an equation
if not isinstance(sol, Equality):
| incorrect behavior in the latex output
I am trying to define the representation of a symbol as a latex fraction
If denominator and numerator of the fraction do not have subscripts, the representation is correct
In [1]: print sympy.latex(sympy.Symbol(r'\frac{a}{b}'))
\frac{a}{b}
But when you add subscripts the sympy representation breaks down
In [4]: print sympy.latex(sympy.Symbol(r'\frac{a_1}{b_1}'))
\frac{a_{1}{b 1}}
| sympy/sympy | diff --git a/bin/coverage_doctest.py b/bin/coverage_doctest.py
index 02e4c77198..5f3f20f6c0 100755
--- a/bin/coverage_doctest.py
+++ b/bin/coverage_doctest.py
@@ -229,7 +229,7 @@ def _get_arg_list(name, fobj):
arg_list.append(argspec.keywords)
# Truncate long arguments
- arg_list = [x[:trunc] for x in arg_list]
+ arg_list = map(lambda x: x[:trunc], arg_list)
# Construct the parameter string (enclosed in brackets)
str_param = "%s(%s)" % (name, ', '.join(arg_list))
diff --git a/sympy/matrices/expressions/tests/test_blockmatrix.py b/sympy/matrices/expressions/tests/test_blockmatrix.py
index e21567fa1e..75758a0c6c 100644
--- a/sympy/matrices/expressions/tests/test_blockmatrix.py
+++ b/sympy/matrices/expressions/tests/test_blockmatrix.py
@@ -97,12 +97,12 @@ def test_BlockMatrix():
def test_BlockMatrix_trace():
- A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
+ A, B, C, D = map(lambda s: MatrixSymbol(s, 3, 3), 'ABCD')
X = BlockMatrix([[A, B], [C, D]])
assert trace(X) == trace(A) + trace(D)
def test_BlockMatrix_Determinant():
- A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
+ A, B, C, D = map(lambda s: MatrixSymbol(s, 3, 3), 'ABCD')
X = BlockMatrix([[A, B], [C, D]])
from sympy import assuming, Q
with assuming(Q.invertible(A)):
diff --git a/sympy/printing/tests/test_dot.py b/sympy/printing/tests/test_dot.py
index a8921ae7e3..98fc75a48a 100644
--- a/sympy/printing/tests/test_dot.py
+++ b/sympy/printing/tests/test_dot.py
@@ -44,15 +44,15 @@ def test_dotedges():
def test_dotprint():
text = dotprint(x+2, repeat=False)
assert all(e in text for e in dotedges(x+2, repeat=False))
- assert all(n in text for n in [dotnode(expr, repeat=False) for expr in (x, Integer(2), x+2)])
+ assert all(n in text for n in map(lambda expr: dotnode(expr, repeat=False), (x, Integer(2), x+2)))
assert 'digraph' in text
text = dotprint(x+x**2, repeat=False)
assert all(e in text for e in dotedges(x+x**2, repeat=False))
- assert all(n in text for n in [dotnode(expr, repeat=False) for expr in (x, Integer(2), x**2)])
+ assert all(n in text for n in map(lambda expr: dotnode(expr, repeat=False), (x, Integer(2), x**2)))
assert 'digraph' in text
text = dotprint(x+x**2, repeat=True)
assert all(e in text for e in dotedges(x+x**2, repeat=True))
- assert all(n in text for n in [dotnode(expr, pos=()) for expr in [x + x**2]])
+ assert all(n in text for n in map(lambda expr: dotnode(expr, pos=()), [x + x**2]))
text = dotprint(x**x, repeat=True)
assert all(e in text for e in dotedges(x**x, repeat=True))
assert all(n in text for n in [dotnode(x, pos=(0,)), dotnode(x, pos=(1,))])
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index c98cc8d400..3c9c0e5d62 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -1335,3 +1335,7 @@ def test_issue_7117():
assert latex(q) == r"6 + \left(x + 1 = 2 x\right)"
q = Pow(e, 2, evaluate=False)
assert latex(q) == r"\left(x + 1 = 2 x\right)^{2}"
+
+
+def test_issue_2934():
+ assert latex(Symbol(r'\frac{a_1}{b_1}')) == '\\frac{a_1}{b_1}'
diff --git a/sympy/simplify/tests/test_hyperexpand.py b/sympy/simplify/tests/test_hyperexpand.py
index 3a2ed35276..61c71c4cfd 100644
--- a/sympy/simplify/tests/test_hyperexpand.py
+++ b/sympy/simplify/tests/test_hyperexpand.py
@@ -214,7 +214,7 @@ def test_plan():
devise_plan(Hyper_Function([2], []), Hyper_Function([S("1/2")], []), z)
# We cannot use pi/(10000 + n) because polys is insanely slow.
- a1, a2, b1 = (randcplx(n) for n in range(3))
+ a1, a2, b1 = map(lambda n: randcplx(n), range(3))
b1 += 2*I
h = hyper([a1, a2], [b1], z)
@@ -247,7 +247,7 @@ def test_plan_derivatives():
def test_reduction_operators():
- a1, a2, b1 = (randcplx(n) for n in range(3))
+ a1, a2, b1 = map(lambda n: randcplx(n), range(3))
h = hyper([a1], [b1], z)
assert ReduceOrder(2, 0) is None
@@ -273,7 +273,7 @@ def test_reduction_operators():
def test_shift_operators():
- a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5))
+ a1, a2, b1, b2, b3 = map(lambda n: randcplx(n), range(5))
h = hyper((a1, a2), (b1, b2, b3), z)
raises(ValueError, lambda: ShiftA(0))
@@ -287,7 +287,7 @@ def test_shift_operators():
def test_ushift_operators():
- a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5))
+ a1, a2, b1, b2, b3 = map(lambda n: randcplx(n), range(5))
h = hyper((a1, a2), (b1, b2, b3), z)
raises(ValueError, lambda: UnShiftA((1,), (), 0, z))
@@ -435,9 +435,9 @@ def test_meijerg():
# carefully set up the parameters.
# NOTE: this used to fail sometimes. I believe it is fixed, but if you
# hit an inexplicable test failure here, please let me know the seed.
- a1, a2 = (randcplx(n) - 5*I - n*I for n in range(2))
- b1, b2 = (randcplx(n) + 5*I + n*I for n in range(2))
- b3, b4, b5, a3, a4, a5 = (randcplx() for n in range(6))
+ a1, a2 = map(lambda n: randcplx() - 5*I - n*I, range(2))
+ b1, b2 = map(lambda n: randcplx() + 5*I + n*I, range(2))
+ b3, b4, b5, a3, a4, a5 = map(lambda n: randcplx(), range(6))
g = meijerg([a1], [a3, a4], [b1], [b3, b4], z)
assert ReduceOrder.meijer_minus(3, 4) is None
@@ -471,7 +471,8 @@ def test_meijerg():
def test_meijerg_shift_operators():
# carefully set up the parameters. XXX this still fails sometimes
- a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 = (randcplx(n) for n in range(10))
+ a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 = \
+ map(lambda n: randcplx(n), range(10))
g = meijerg([a1], [a3, a4], [b1], [b3, b4], z)
assert tn(MeijerShiftA(b1).apply(g, op),
@@ -587,7 +588,7 @@ def test_lerchphi():
def test_partial_simp():
# First test that hypergeometric function formulae work.
- a, b, c, d, e = (randcplx() for _ in range(5))
+ a, b, c, d, e = map(lambda _: randcplx(), range(5))
for func in [Hyper_Function([a, b, c], [d, e]),
Hyper_Function([], [a, b, c, d, e])]:
f = build_hypergeometric_formula(func)
| {
"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": 15
} | 0.7 | {
"env_vars": null,
"env_yml_path": [],
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "",
"pip_packages": [
"pytest"
],
"pre_install": [],
"python": "3.6",
"reqs_path": [],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
mpmath==1.3.0
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
-e git+https://github.com/sympy/sympy.git@0844595e819e5ea6b161162781df14efd9e81b63#egg=sympy
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: sympy
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
- mpmath==1.3.0
- 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/sympy
| [
"sympy/printing/tests/test_latex.py::test_issue_2934"
] | [] | [
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_bc_matmul",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_bc_matadd",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_bc_transpose",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_bc_dist_diag",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_block_plus_ident",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_BlockMatrix",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_BlockMatrix_trace",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_BlockMatrix_Determinant",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_squareBlockMatrix",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_BlockDiagMatrix",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_blockcut",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_reblock_2x2",
"sympy/matrices/expressions/tests/test_blockmatrix.py::test_deblock",
"sympy/printing/tests/test_dot.py::test_purestr",
"sympy/printing/tests/test_dot.py::test_styleof",
"sympy/printing/tests/test_dot.py::test_attrprint",
"sympy/printing/tests/test_dot.py::test_dotnode",
"sympy/printing/tests/test_dot.py::test_dotedges",
"sympy/printing/tests/test_dot.py::test_dotprint",
"sympy/printing/tests/test_dot.py::test_dotprint_depth",
"sympy/printing/tests/test_dot.py::test_Matrix_and_non_basics",
"sympy/printing/tests/test_dot.py::test_labelfunc",
"sympy/printing/tests/test_latex.py::test_printmethod",
"sympy/printing/tests/test_latex.py::test_latex_basic",
"sympy/printing/tests/test_latex.py::test_latex_builtins",
"sympy/printing/tests/test_latex.py::test_latex_Float",
"sympy/printing/tests/test_latex.py::test_latex_symbols",
"sympy/printing/tests/test_latex.py::test_latex_functions",
"sympy/printing/tests/test_latex.py::test_hyper_printing",
"sympy/printing/tests/test_latex.py::test_latex_bessel",
"sympy/printing/tests/test_latex.py::test_latex_fresnel",
"sympy/printing/tests/test_latex.py::test_latex_brackets",
"sympy/printing/tests/test_latex.py::test_latex_indexed",
"sympy/printing/tests/test_latex.py::test_latex_derivatives",
"sympy/printing/tests/test_latex.py::test_latex_subs",
"sympy/printing/tests/test_latex.py::test_latex_integrals",
"sympy/printing/tests/test_latex.py::test_latex_sets",
"sympy/printing/tests/test_latex.py::test_latex_Range",
"sympy/printing/tests/test_latex.py::test_latex_intervals",
"sympy/printing/tests/test_latex.py::test_latex_emptyset",
"sympy/printing/tests/test_latex.py::test_latex_union",
"sympy/printing/tests/test_latex.py::test_latex_symmetric_difference",
"sympy/printing/tests/test_latex.py::test_latex_Complement",
"sympy/printing/tests/test_latex.py::test_latex_productset",
"sympy/printing/tests/test_latex.py::test_latex_Naturals",
"sympy/printing/tests/test_latex.py::test_latex_ImageSet",
"sympy/printing/tests/test_latex.py::test_latex_Contains",
"sympy/printing/tests/test_latex.py::test_latex_sum",
"sympy/printing/tests/test_latex.py::test_latex_product",
"sympy/printing/tests/test_latex.py::test_latex_limits",
"sympy/printing/tests/test_latex.py::test_issue_3568",
"sympy/printing/tests/test_latex.py::test_latex",
"sympy/printing/tests/test_latex.py::test_latex_dict",
"sympy/printing/tests/test_latex.py::test_latex_list",
"sympy/printing/tests/test_latex.py::test_latex_rational",
"sympy/printing/tests/test_latex.py::test_latex_inverse",
"sympy/printing/tests/test_latex.py::test_latex_DiracDelta",
"sympy/printing/tests/test_latex.py::test_latex_Heaviside",
"sympy/printing/tests/test_latex.py::test_latex_KroneckerDelta",
"sympy/printing/tests/test_latex.py::test_latex_LeviCivita",
"sympy/printing/tests/test_latex.py::test_mode",
"sympy/printing/tests/test_latex.py::test_latex_Piecewise",
"sympy/printing/tests/test_latex.py::test_latex_Matrix",
"sympy/printing/tests/test_latex.py::test_latex_matrix_with_functions",
"sympy/printing/tests/test_latex.py::test_latex_mul_symbol",
"sympy/printing/tests/test_latex.py::test_latex_issue_4381",
"sympy/printing/tests/test_latex.py::test_latex_issue_4576",
"sympy/printing/tests/test_latex.py::test_latex_pow_fraction",
"sympy/printing/tests/test_latex.py::test_noncommutative",
"sympy/printing/tests/test_latex.py::test_latex_order",
"sympy/printing/tests/test_latex.py::test_latex_Lambda",
"sympy/printing/tests/test_latex.py::test_latex_PolyElement",
"sympy/printing/tests/test_latex.py::test_latex_FracElement",
"sympy/printing/tests/test_latex.py::test_latex_Poly",
"sympy/printing/tests/test_latex.py::test_latex_RootOf",
"sympy/printing/tests/test_latex.py::test_latex_RootSum",
"sympy/printing/tests/test_latex.py::test_settings",
"sympy/printing/tests/test_latex.py::test_latex_numbers",
"sympy/printing/tests/test_latex.py::test_lamda",
"sympy/printing/tests/test_latex.py::test_custom_symbol_names",
"sympy/printing/tests/test_latex.py::test_matAdd",
"sympy/printing/tests/test_latex.py::test_matMul",
"sympy/printing/tests/test_latex.py::test_latex_MatrixSlice",
"sympy/printing/tests/test_latex.py::test_latex_RandomDomain",
"sympy/printing/tests/test_latex.py::test_PrettyPoly",
"sympy/printing/tests/test_latex.py::test_integral_transforms",
"sympy/printing/tests/test_latex.py::test_PolynomialRingBase",
"sympy/printing/tests/test_latex.py::test_categories",
"sympy/printing/tests/test_latex.py::test_Modules",
"sympy/printing/tests/test_latex.py::test_QuotientRing",
"sympy/printing/tests/test_latex.py::test_Tr",
"sympy/printing/tests/test_latex.py::test_Adjoint",
"sympy/printing/tests/test_latex.py::test_Hadamard",
"sympy/printing/tests/test_latex.py::test_boolean_args_order",
"sympy/printing/tests/test_latex.py::test_imaginary",
"sympy/printing/tests/test_latex.py::test_builtins_without_args",
"sympy/printing/tests/test_latex.py::test_latex_greek_functions",
"sympy/printing/tests/test_latex.py::test_translate",
"sympy/printing/tests/test_latex.py::test_other_symbols",
"sympy/printing/tests/test_latex.py::test_modifiers",
"sympy/printing/tests/test_latex.py::test_greek_symbols",
"sympy/printing/tests/test_latex.py::test_builtin_no_args",
"sympy/printing/tests/test_latex.py::test_issue_6853",
"sympy/printing/tests/test_latex.py::test_Mul",
"sympy/printing/tests/test_latex.py::test_Pow",
"sympy/printing/tests/test_latex.py::test_issue_7180",
"sympy/printing/tests/test_latex.py::test_issue_8409",
"sympy/printing/tests/test_latex.py::test_issue_8470",
"sympy/printing/tests/test_latex.py::test_issue_7117",
"sympy/simplify/tests/test_hyperexpand.py::test_branch_bug",
"sympy/simplify/tests/test_hyperexpand.py::test_hyperexpand",
"sympy/simplify/tests/test_hyperexpand.py::test_roach",
"sympy/simplify/tests/test_hyperexpand.py::test_polynomial",
"sympy/simplify/tests/test_hyperexpand.py::test_hyperexpand_bases",
"sympy/simplify/tests/test_hyperexpand.py::test_hyperexpand_parametric",
"sympy/simplify/tests/test_hyperexpand.py::test_shifted_sum",
"sympy/simplify/tests/test_hyperexpand.py::test_formulae",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg_formulae",
"sympy/simplify/tests/test_hyperexpand.py::test_plan",
"sympy/simplify/tests/test_hyperexpand.py::test_plan_derivatives",
"sympy/simplify/tests/test_hyperexpand.py::test_reduction_operators",
"sympy/simplify/tests/test_hyperexpand.py::test_shift_operators",
"sympy/simplify/tests/test_hyperexpand.py::test_ushift_operators",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg_expand",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg_lookup",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg_shift_operators",
"sympy/simplify/tests/test_hyperexpand.py::test_meijerg_confluence",
"sympy/simplify/tests/test_hyperexpand.py::test_lerchphi",
"sympy/simplify/tests/test_hyperexpand.py::test_partial_simp",
"sympy/simplify/tests/test_hyperexpand.py::test_hyperexpand_special",
"sympy/simplify/tests/test_hyperexpand.py::test_Mod1_behavior",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_misc",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_1",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_2",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_3",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_4",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_5",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_6",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_7",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_8",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_9",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_10",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_11",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_12",
"sympy/simplify/tests/test_hyperexpand.py::test_prudnikov_2F1",
"sympy/simplify/tests/test_hyperexpand.py::test_bug"
] | [] | BSD | 52 |
|
thisfred__val-9 | a60e8de415d9ed855570fc09ee14a5974532cf07 | 2015-03-03 07:49:35 | a60e8de415d9ed855570fc09ee14a5974532cf07 | coveralls:
[](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 |
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 |
|
sympy__sympy-9105 | 1c3b046c9831553dd18d98bcf5765c325df92eb6 | 2015-03-06 17:43:03 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/functions/elementary/exponential.py b/sympy/functions/elementary/exponential.py
index 5bc5af8089..8b9881d7e3 100644
--- a/sympy/functions/elementary/exponential.py
+++ b/sympy/functions/elementary/exponential.py
@@ -301,7 +301,7 @@ def taylor_term(n, x, *previous_terms):
p = previous_terms[-1]
if p is not None:
return p * x / n
- return x**n/factorial()(n)
+ return x**n/factorial(n)
def as_real_imag(self, deep=True, **hints):
"""
| exp(x).taylor_term(n, x) raises TypeError
When ```exp(x).taylor_term(n, x)``` is called, it raises ```TypeError``` because of a simple typo, instead of calling ```factorial(n)```, ```factorial()(n)``` is called, which is incorrect. | sympy/sympy | diff --git a/sympy/functions/elementary/tests/test_exponential.py b/sympy/functions/elementary/tests/test_exponential.py
index 61991ec99d..279254d9dd 100644
--- a/sympy/functions/elementary/tests/test_exponential.py
+++ b/sympy/functions/elementary/tests/test_exponential.py
@@ -131,6 +131,10 @@ def test_exp_leading_term():
assert exp(1/x).as_leading_term(x) == exp(1/x)
assert exp(2 + x).as_leading_term(x) == exp(2)
+def test_exp_taylor_term():
+ x = symbols('x')
+ assert exp(x).taylor_term(1, x) == x
+ assert exp(x).taylor_term(3, x) == x**3/6
def test_log_values():
assert log(nan) == nan
| {
"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": 0,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"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.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
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
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
-e git+https://github.com/sympy/sympy.git@1c3b046c9831553dd18d98bcf5765c325df92eb6#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/functions/elementary/tests/test_exponential.py::test_exp_taylor_term"
] | [] | [
"sympy/functions/elementary/tests/test_exponential.py::test_exp_values",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_log",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_expand",
"sympy/functions/elementary/tests/test_exponential.py::test_exp__as_base_exp",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_infinity",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_subs",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_conjugate",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_rewrite",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_leading_term",
"sympy/functions/elementary/tests/test_exponential.py::test_log_values",
"sympy/functions/elementary/tests/test_exponential.py::test_log_base",
"sympy/functions/elementary/tests/test_exponential.py::test_log_symbolic",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_assumptions",
"sympy/functions/elementary/tests/test_exponential.py::test_log_assumptions",
"sympy/functions/elementary/tests/test_exponential.py::test_log_hashing",
"sympy/functions/elementary/tests/test_exponential.py::test_log_sign",
"sympy/functions/elementary/tests/test_exponential.py::test_log_expand_complex",
"sympy/functions/elementary/tests/test_exponential.py::test_log_apply_evalf",
"sympy/functions/elementary/tests/test_exponential.py::test_log_expand",
"sympy/functions/elementary/tests/test_exponential.py::test_log_simplify",
"sympy/functions/elementary/tests/test_exponential.py::test_lambertw",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_5673",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_expand_NC",
"sympy/functions/elementary/tests/test_exponential.py::test_as_numer_denom",
"sympy/functions/elementary/tests/test_exponential.py::test_polar",
"sympy/functions/elementary/tests/test_exponential.py::test_log_product",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_8866"
] | [] | BSD | 55 |
|
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 |
|
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 |
|
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 |
|
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.

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 |
|
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 |
|
sympy__sympy-9131 | 10b9aa56e2b41e652767932cf3b043142e2d96e0 | 2015-03-13 10:39:51 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/AUTHORS b/AUTHORS
index 07e0a52f59..47a4f03692 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -387,10 +387,5 @@ harshil goel <[email protected]>
Lokesh Sharma <[email protected]>
Sartaj Singh <[email protected]>
Chris Swierczewski <[email protected]>
-Sumith <[email protected]>
Konstantin Togoi <[email protected]>
Param Singh <[email protected]>
-Philippe Bouafia <[email protected]>
-Lucas Jones <[email protected]>
-Peter Schmidt <[email protected]>
-Jiaxing Liang <[email protected]>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index 1f02eff625..66cdf0e007 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -392,13 +392,8 @@ want to be mentioned here, so see our repository history for a full list).
#. Lokesh Sharma: reorder setup.py file imports to correct NameError
#. Sartaj Singh: use \left \| instead of \lvert for latex Abs
#. Chris Swierczewski: RootOf.evalf watches for root on interval boundary
-#. Sumith: implemented columnspace of a matrix
#. Konstantin Togoi: added truth_table and binary digit utilities to boolalg
#. Param Singh: added missing units from mks system
-#. Philippe Bouafia: Fixed a typo.
-#. Lucas Jones: Add a test in integrals
-#. Peter Schmidt: Removed duplicate tests
-#. Jiaxing Liang: Fix infinite recursion issue in test_f
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
diff --git a/doc/src/modules/integrals/integrals.rst b/doc/src/modules/integrals/integrals.rst
index a5fb8cf471..2eb43ac901 100644
--- a/doc/src/modules/integrals/integrals.rst
+++ b/doc/src/modules/integrals/integrals.rst
@@ -93,6 +93,13 @@ API reference
.. autofunction:: sympy.integrals.integrate
.. autofunction:: sympy.integrals.line_integrate
+.. autofunction:: sympy.integrals.deltaintegrate
+.. autofunction:: sympy.integrals.ratint
+.. autofunction:: sympy.integrals.heurisch
+.. autofunction:: sympy.integrals.heurisch_wrapper
+.. autofunction:: sympy.integrals.trigintegrate
+.. autofunction:: sympy.integrals.manualintegrate
+.. autofunction:: sympy.integrals.manualintegrate.integral_steps
The class `Integral` represents an unevaluated integral and has some methods that help in the integration of an expression.
diff --git a/doc/src/modules/solvers/diophantine.rst b/doc/src/modules/solvers/diophantine.rst
index 102046b987..0129975280 100644
--- a/doc/src/modules/solvers/diophantine.rst
+++ b/doc/src/modules/solvers/diophantine.rst
@@ -164,14 +164,17 @@ solutions. Consider the below cases where `\Delta = 8`.
>>> diophantine(x**2 - 4*x*y + 2*y**2 - 3*x + 7*y - 5)
set()
->>> from sympy import expand
+>>> from sympy import sqrt
>>> n = symbols("n", integer=True)
>>> s = diophantine(x**2 - 2*y**2 - 2*x - 4*y, n)
->>> x_n, y_n = s.pop()
->>> expand(x_n)
--(-2*sqrt(2) + 3)**n/2 + sqrt(2)*(-2*sqrt(2) + 3)**n/2 - sqrt(2)*(2*sqrt(2) + 3)**n/2 - (2*sqrt(2) + 3)**n/2 + 1
->>> expand(y_n)
--sqrt(2)*(-2*sqrt(2) + 3)**n/4 + (-2*sqrt(2) + 3)**n/2 + sqrt(2)*(2*sqrt(2) + 3)**n/4 + (2*sqrt(2) + 3)**n/2 - 1
+>>> x_1, y_1 = s.pop()
+>>> x_2, y_2 = s.pop()
+>>> x_n = -(-2*sqrt(2) + 3)**n/2 + sqrt(2)*(-2*sqrt(2) + 3)**n/2 - sqrt(2)*(2*sqrt(2) + 3)**n/2 - (2*sqrt(2) + 3)**n/2 + 1
+>>> x_1 == x_n or x_2 == x_n
+True
+>>> y_n = -sqrt(2)*(-2*sqrt(2) + 3)**n/4 + (-2*sqrt(2) + 3)**n/2 + sqrt(2)*(2*sqrt(2) + 3)**n/4 + (2*sqrt(2) + 3)**n/2 - 1
+>>> y_1 == y_n or y_2 == y_n
+True
Here `n` is an integer. Although x_n and y_n may not look like
integers, substituting in specific values for n (and simplifying) shows that they
diff --git a/examples/galgebra/physics_check_latex.py b/examples/galgebra/physics_check_latex.py
index 3b69622d9c..e7dda69f59 100755
--- a/examples/galgebra/physics_check_latex.py
+++ b/examples/galgebra/physics_check_latex.py
@@ -28,7 +28,7 @@ def Maxwells_Equations_in_Geometric_Calculus():
print('\\text{Electromagnetic Field Bi-Vector\\;\\;} F = E+IB =', F)
print('%\\text{Four Current Density\\;\\;} J =', J)
gradF = grad*F
- print('#Geometric Derivative of Electromagnetic Field Bi-Vector')
+ print('#Geometric Derivative of Electomagnetic Field Bi-Vector')
gradF.Fmt(3, 'grad*F')
print('#Maxwell Equations')
diff --git a/examples/intermediate/coupled_cluster.py b/examples/intermediate/coupled_cluster.py
index eebda39f4c..5f5ab28b92 100755
--- a/examples/intermediate/coupled_cluster.py
+++ b/examples/intermediate/coupled_cluster.py
@@ -88,7 +88,7 @@ def main():
comm4 = evaluate_deltas(comm4)
comm4 = substitute_dummies(comm4)
- print("construct Hausdorff expansion...")
+ print("construct Hausdoff expansion...")
eq = H + comm1 + comm2/2 + comm3/6 + comm4/24
eq = eq.expand()
eq = evaluate_deltas(eq)
diff --git a/sympy/core/expr.py b/sympy/core/expr.py
index 0de02ff424..14142321ad 100644
--- a/sympy/core/expr.py
+++ b/sympy/core/expr.py
@@ -682,6 +682,10 @@ def equals(self, other, failing_expression=False):
return diff
return None
+ def _eval_is_composite(self):
+ if self.is_integer and self.is_positive and self.is_prime is False:
+ return True
+
def _eval_is_positive(self):
from sympy.polys.numberfields import minimal_polynomial
from sympy.polys.polyerrors import NotAlgebraic
diff --git a/sympy/core/exprtools.py b/sympy/core/exprtools.py
index 654b7f3bf4..7e786424f3 100644
--- a/sympy/core/exprtools.py
+++ b/sympy/core/exprtools.py
@@ -72,7 +72,7 @@ def _monotonic_sign(self):
rv = _monotonic_sign(-self)
return rv if rv is None else -rv
- if not self.is_Add and self.as_numer_denom()[1].is_number:
+ if self.is_Symbol:
s = self
if s.is_prime:
if s.is_odd:
diff --git a/sympy/core/facts.py b/sympy/core/facts.py
index 4cc36ac997..ef4af6b5ad 100644
--- a/sympy/core/facts.py
+++ b/sympy/core/facts.py
@@ -186,7 +186,7 @@ def apply_beta_to_alpha_route(alpha_implications, beta_rules):
ximpls.add(bimpl)
# we introduced new implication - now we have to restore
- # completeness of the whole set.
+ # completness of the whole set.
bimpl_impl = x_impl.get(bimpl)
if bimpl_impl is not None:
ximpls |= bimpl_impl[0]
diff --git a/sympy/functions/elementary/exponential.py b/sympy/functions/elementary/exponential.py
index 01559e77d8..5bc5af8089 100644
--- a/sympy/functions/elementary/exponential.py
+++ b/sympy/functions/elementary/exponential.py
@@ -301,7 +301,7 @@ def taylor_term(n, x, *previous_terms):
p = previous_terms[-1]
if p is not None:
return p * x / n
- return x**n/factorial(n)
+ return x**n/factorial()(n)
def as_real_imag(self, deep=True, **hints):
"""
@@ -687,9 +687,6 @@ def _eval_is_positive(self):
def _eval_is_zero(self):
return (self.args[0] - 1).is_zero
- def _eval_is_nonnegative(self):
- return (self.args[0] - 1).is_nonnegative
-
def _eval_nseries(self, x, n, logx):
# NOTE Please see the comment at the beginning of this file, labelled
# IMPORTANT.
diff --git a/sympy/functions/elementary/trigonometric.py b/sympy/functions/elementary/trigonometric.py
index df0117467b..4ad9068349 100644
--- a/sympy/functions/elementary/trigonometric.py
+++ b/sympy/functions/elementary/trigonometric.py
@@ -1942,9 +1942,6 @@ def _eval_is_rational(self):
def _eval_is_positive(self):
return self.args[0].is_positive
- def _eval_is_nonnegative(self):
- return self.args[0].is_nonnegative
-
@classmethod
def eval(cls, arg):
if arg.is_Number:
diff --git a/sympy/integrals/__init__.py b/sympy/integrals/__init__.py
index 139dd599a3..46c0dcd31a 100644
--- a/sympy/integrals/__init__.py
+++ b/sympy/integrals/__init__.py
@@ -9,7 +9,11 @@
>>> integrate(sin(x),x)
-cos(x)
"""
+from .deltafunctions import deltaintegrate
+from .heurisch import heurisch, heurisch_wrapper
from .integrals import integrate, Integral, line_integrate
+from .manualintegrate import manualintegrate, integral_steps
+from .rationaltools import ratint
from .transforms import (mellin_transform, inverse_mellin_transform,
MellinTransform, InverseMellinTransform,
laplace_transform, inverse_laplace_transform,
@@ -22,3 +26,4 @@
CosineTransform, InverseCosineTransform,
hankel_transform, inverse_hankel_transform,
HankelTransform, InverseHankelTransform)
+from .trigonometry import trigintegrate
diff --git a/sympy/matrices/expressions/matexpr.py b/sympy/matrices/expressions/matexpr.py
index b07b3750ad..01b7420823 100644
--- a/sympy/matrices/expressions/matexpr.py
+++ b/sympy/matrices/expressions/matexpr.py
@@ -322,14 +322,6 @@ class MatrixElement(Expr):
j = property(lambda self: self.args[2])
_diff_wrt = True
- def doit(self, **kwargs):
- deep = kwargs.get('deep', True)
- if deep:
- args = [arg.doit(**kwargs) for arg in self.args]
- else:
- args = self.args
- return args[0][args[1], args[2]]
-
class MatrixSymbol(MatrixExpr):
"""Symbolic representation of a Matrix object
diff --git a/sympy/physics/quantum/qubit.py b/sympy/physics/quantum/qubit.py
index 216f9d556f..58ba60d675 100644
--- a/sympy/physics/quantum/qubit.py
+++ b/sympy/physics/quantum/qubit.py
@@ -481,7 +481,7 @@ def matrix_to_density(mat):
def qubit_to_matrix(qubit, format='sympy'):
- """Converts an Add/Mul of Qubit objects into it's matrix representation
+ """Coverts an Add/Mul of Qubit objects into it's matrix representation
This function is the inverse of ``matrix_to_qubit`` and is a shorthand
for ``represent(qubit)``.
diff --git a/sympy/solvers/diophantine.py b/sympy/solvers/diophantine.py
index e5378624a8..e7e5479381 100644
--- a/sympy/solvers/diophantine.py
+++ b/sympy/solvers/diophantine.py
@@ -715,6 +715,11 @@ def _diop_quadratic(var, coeff, t):
# In this case equation can be transformed into a Pell equation
#n = symbols("n", integer=True)
+ fund_solns = solns_pell
+ solns_pell = set(fund_solns)
+ for X, Y in fund_solns:
+ solns_pell.add((-X, -Y))
+
a = diop_DN(D, 1)
T = a[0][0]
U = a[0][1]
@@ -736,50 +741,33 @@ def _diop_quadratic(var, coeff, t):
l.add((x_n, y_n))
else:
- L = ilcm(S(P[0]).q, ilcm(S(P[1]).q, ilcm(S(P[2]).q, ilcm(S(P[3]).q, ilcm(S(Q[0]).q, S(Q[1]).q)))))
+ L = ilcm(S(P[0]).q, ilcm(S(P[1]).q, ilcm(S(P[2]).q,
+ ilcm(S(P[3]).q, ilcm(S(Q[0]).q, S(Q[1]).q)))))
- k = 0
- done = False
+ k = 1
T_k = T
U_k = U
- while not done:
- k = k + 1
-
- if (T_k - 1) % L == 0 and U_k % L == 0:
- done = True
+ while (T_k - 1) % L != 0 or U_k % L != 0:
T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T
+ k += 1
- for soln in solns_pell:
-
- X = soln[0]
- Y = soln[1]
-
- done = False
+ for X, Y in solns_pell:
for i in range(k):
-
- X_1 = X*T + D*U*Y
- Y_1 = X*U + Y*T
-
- x = (P*Matrix([X_1, Y_1]) + Q)[0]
- y = (P*Matrix([X_1, Y_1]) + Q)[1]
-
- if is_solution_quad(var, coeff, x, y):
- done = True
-
-
- x_n = S( (X_1 + sqrt(D)*Y_1)*(T + sqrt(D)*U)**(t*L) + (X_1 - sqrt(D)*Y_1)*(T - sqrt(D)*U)**(t*L) )/ 2
- y_n = S( (X_1 + sqrt(D)*Y_1)*(T + sqrt(D)*U)**(t*L) - (X_1 - sqrt(D)*Y_1)*(T - sqrt(D)*U)**(t*L) )/ (2*sqrt(D))
-
- x_n = _mexpand(x_n)
- y_n = _mexpand(y_n)
- x_n, y_n = (P*Matrix([x_n, y_n]) + Q)[0], (P*Matrix([x_n, y_n]) + Q)[1]
- l.add((x_n, y_n))
-
- if done:
- break
+ Z = P*Matrix([X, Y]) + Q
+ x, y = Z[0], Z[1]
+
+ if isinstance(x, Integer) and isinstance(y, Integer):
+ Xt = S((X + sqrt(D)*Y)*(T_k + sqrt(D)*U_k)**t +
+ (X - sqrt(D)*Y)*(T_k - sqrt(D)*U_k)**t)/ 2
+ Yt = S((X + sqrt(D)*Y)*(T_k + sqrt(D)*U_k)**t -
+ (X - sqrt(D)*Y)*(T_k - sqrt(D)*U_k)**t)/ (2*sqrt(D))
+ Zt = P*Matrix([Xt, Yt]) + Q
+ l.add((Zt[0], Zt[1]))
+
+ X, Y = X*T + D*U*Y, X*U + Y*T
return l
| diophantine returns a non-integer solution
The following code:
import sympy
from sympy.solvers.diophantine import diophantine
sympy.simplify(diophantine('-48 - 2 * m * (3*m - 1) + n * (3*n - 1)',
param=sympy.Symbol('t')).pop()[1].replace('t', 1))
returns -71816005847/3 on 0.7.6 | sympy/sympy | diff --git a/bin/coverage_doctest.py b/bin/coverage_doctest.py
index dfe02413e7..02e4c77198 100755
--- a/bin/coverage_doctest.py
+++ b/bin/coverage_doctest.py
@@ -396,7 +396,7 @@ def coverage(module_path, verbose=False, no_color=False, sphinx=True):
contained. It then goes through each of the classes/functions to get
the docstring and doctest coverage of the module. """
- # Import the package and find members
+ # Import the package and find membmers
m = None
try:
__import__(module_path)
diff --git a/sympy/core/tests/test_assumptions.py b/sympy/core/tests/test_assumptions.py
index 4e29f4e8ca..3c62a807f0 100644
--- a/sympy/core/tests/test_assumptions.py
+++ b/sympy/core/tests/test_assumptions.py
@@ -1,4 +1,4 @@
-from sympy import I, sqrt, log, exp, sin, asin, factorial
+from sympy import I, sqrt, log, exp, sin, asin
from sympy.core import Symbol, S, Rational, Integer, Dummy, Wild, Pow
from sympy.core.facts import InconsistentAssumptions
from sympy import simplify
@@ -479,7 +479,7 @@ def test_composite():
assert S(17).is_composite is False
assert S(4).is_composite is True
x = Dummy(integer=True, positive=True, prime=False)
- assert x.is_composite is None # x could be 1
+ assert x.is_composite
assert (x + 1).is_composite is None
@@ -900,8 +900,3 @@ def test_issues_8632_8633_8638_8675_8992():
assert ((p + 2)**3 - S.Half).is_positive
n = Dummy(negative=True)
assert (n - 3).is_nonpositive
-
-def test_issue_9115():
- n = Dummy('n', integer=True, nonnegative=True)
- assert (factorial(n) >= 1) == True
- assert (factorial(n) < 1) == False
diff --git a/sympy/functions/elementary/tests/test_exponential.py b/sympy/functions/elementary/tests/test_exponential.py
index a2057365d8..61991ec99d 100644
--- a/sympy/functions/elementary/tests/test_exponential.py
+++ b/sympy/functions/elementary/tests/test_exponential.py
@@ -1,5 +1,5 @@
from sympy import (
- symbols, log, ln, Float, nan, oo, zoo, I, pi, E, exp, Symbol,
+ symbols, log, Float, nan, oo, zoo, I, pi, E, exp, Symbol,
LambertW, sqrt, Rational, expand_log, S, sign, conjugate,
sin, cos, sinh, cosh, tanh, exp_polar, re, Function, simplify)
@@ -131,10 +131,6 @@ def test_exp_leading_term():
assert exp(1/x).as_leading_term(x) == exp(1/x)
assert exp(2 + x).as_leading_term(x) == exp(2)
-def test_exp_taylor_term():
- x = symbols('x')
- assert exp(x).taylor_term(1, x) == x
- assert exp(x).taylor_term(3, x) == x**3/6
def test_log_values():
assert log(nan) == nan
@@ -444,7 +440,6 @@ def test_log_product():
expr = log(Product(-2, (n, 0, 4)))
assert simplify(expr) == expr
-
def test_issue_8866():
x = Symbol('x')
assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10))
@@ -457,10 +452,3 @@ def test_issue_8866():
b2 = log(exp(y), exp(5), evaluate=False)
assert simplify(log(l1, b1)) == simplify(log(l2, b2))
assert expand_log(log(l1, b1)) == expand_log(log(l2, b2))
-
-
-def test_issue_9116():
- n = Symbol('n', positive=True, integer=True)
-
- assert ln(n).is_nonnegative is True
- assert log(n).is_nonnegative is True
diff --git a/sympy/functions/elementary/tests/test_trigonometric.py b/sympy/functions/elementary/tests/test_trigonometric.py
index 5bc62b70d9..f94d1c341f 100644
--- a/sympy/functions/elementary/tests/test_trigonometric.py
+++ b/sympy/functions/elementary/tests/test_trigonometric.py
@@ -1390,8 +1390,3 @@ def test_issue_8653():
assert sin(n).is_irrational is None
assert cos(n).is_irrational is None
assert tan(n).is_irrational is None
-
-
-def test_issue_9157():
- n = Symbol('n', integer=True, positive=True)
- atan(n - 1).is_nonnegative is True
diff --git a/sympy/integrals/tests/test_integrals.py b/sympy/integrals/tests/test_integrals.py
index 3b59ab1713..b34db5b37d 100644
--- a/sympy/integrals/tests/test_integrals.py
+++ b/sympy/integrals/tests/test_integrals.py
@@ -1087,9 +1087,3 @@ def test_issue_8901():
assert integrate(sinh(1.0*x)) == 1.0*cosh(1.0*x)
assert integrate(tanh(1.0*x)) == 1.0*x - 1.0*log(tanh(1.0*x) + 1)
assert integrate(tanh(x)) == x - log(tanh(x) + 1)
-
-
-def test_issue_7130():
- i, L, a, b = symbols('i L a b')
- integrand = (cos(pi*i*x/L)**2 / (a + b*x)).rewrite(exp)
- assert x not in integrate(integrand, (x, 0, L)).free_symbols
diff --git a/sympy/matrices/expressions/tests/test_matrix_exprs.py b/sympy/matrices/expressions/tests/test_matrix_exprs.py
index d1f0dcbb23..77a8f1f9ed 100644
--- a/sympy/matrices/expressions/tests/test_matrix_exprs.py
+++ b/sympy/matrices/expressions/tests/test_matrix_exprs.py
@@ -207,9 +207,3 @@ def test_single_indexing():
def test_MatrixElement_diff():
assert (A[3, 0]*A[0, 0]).diff(A[0, 0]) == A[3, 0]
-
-
-def test_MatrixElement_doit():
- u = MatrixSymbol('u', 2, 1)
- v = ImmutableMatrix([3, 5])
- assert u[0, 0].subs(u, v).doit() == v[0, 0]
diff --git a/sympy/series/tests/test_limits.py b/sympy/series/tests/test_limits.py
index bd160ac9fa..16dd4efeae 100644
--- a/sympy/series/tests/test_limits.py
+++ b/sympy/series/tests/test_limits.py
@@ -37,6 +37,9 @@ def test_basic1():
assert limit(gamma(1/x + 3), x, oo) == 2
assert limit(S.NaN, x, -oo) == S.NaN
assert limit(Order(2)*x, x, S.NaN) == S.NaN
+ assert limit(gamma(1/x + 3), x, oo) == 2
+ assert limit(S.NaN, x, -oo) == S.NaN
+ assert limit(Order(2)*x, x, S.NaN) == S.NaN
assert limit(1/(x - 1), x, 1, dir="+") == oo
assert limit(1/(x - 1), x, 1, dir="-") == -oo
assert limit(1/(5 - x)**3, x, 5, dir="+") == -oo
diff --git a/sympy/series/tests/test_residues.py b/sympy/series/tests/test_residues.py
index 23db6f4fee..676f603677 100644
--- a/sympy/series/tests/test_residues.py
+++ b/sympy/series/tests/test_residues.py
@@ -26,8 +26,9 @@ def test_basic2():
def _test_f():
+ # FIXME: we get infinite recursion here:
f = Function("f")
- assert residue(f(x)/x**5, x, 0) == f(x).diff(x, 4).subs(x, 0)/24
+ assert residue(f(x)/x**5, x, 0) == f.diff(x, 4)/24
def test_functions():
diff --git a/sympy/solvers/tests/test_diophantine.py b/sympy/solvers/tests/test_diophantine.py
index 056124908e..8aea7c93fd 100644
--- a/sympy/solvers/tests/test_diophantine.py
+++ b/sympy/solvers/tests/test_diophantine.py
@@ -118,12 +118,15 @@ def test_quadratic_non_perfect_square():
assert check_solutions(x**2 - x*y - y**2 - 3*y)
assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
+def test_issue_9106():
+ assert check_integrality(-48 - 2*x*(3*x - 1) + y*(3*y - 1))
@slow
def test_quadratic_non_perfect_slow():
assert check_solutions(8*x**2 + 10*x*y - 2*y**2 - 32*x - 13*y - 23)
- assert check_solutions(5*x**2 - 13*x*y + y**2 - 4*x - 4*y - 15)
+ # This leads to very large numbers.
+ # assert check_solutions(5*x**2 - 13*x*y + y**2 - 4*x - 4*y - 15)
assert check_solutions(-3*x**2 - 2*x*y + 7*y**2 - 5*x - 7)
assert check_solutions(-4 - x + 4*x**2 - y - 3*x*y - 4*y**2)
assert check_solutions(1 + 2*x + 2*x**2 + 2*y + x*y - 2*y**2)
@@ -579,3 +582,23 @@ def check_solutions(eq):
break
return okay
+
+def check_integrality(eq):
+ """
+ Check that the solutions returned by diophantine() are integers.
+ This should be seldom needed except for general quadratic
+ equations which are solved with rational transformations.
+ """
+ def _check_values(x):
+ """ Check a number of values. """
+ for i in range(-4, 4):
+ if not isinstance(simplify(x.subs(t, i)), Integer):
+ return False
+ return True
+
+ for soln in diophantine(eq, param=t):
+ for x in soln:
+ if not _check_values(x):
+ return False
+
+ return True
| {
"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": 2,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 15
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"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
mpmath==1.3.0
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/sympy/sympy.git@10b9aa56e2b41e652767932cf3b043142e2d96e0#egg=sympy
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: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_assumptions.py::test_composite",
"sympy/solvers/tests/test_diophantine.py::test_issue_9106"
] | [
"sympy/functions/elementary/tests/test_trigonometric.py::test_sincos_rewrite_sqrt"
] | [
"sympy/core/tests/test_assumptions.py::test_symbol_unset",
"sympy/core/tests/test_assumptions.py::test_zero",
"sympy/core/tests/test_assumptions.py::test_one",
"sympy/core/tests/test_assumptions.py::test_negativeone",
"sympy/core/tests/test_assumptions.py::test_infinity",
"sympy/core/tests/test_assumptions.py::test_neg_infinity",
"sympy/core/tests/test_assumptions.py::test_nan",
"sympy/core/tests/test_assumptions.py::test_pos_rational",
"sympy/core/tests/test_assumptions.py::test_neg_rational",
"sympy/core/tests/test_assumptions.py::test_pi",
"sympy/core/tests/test_assumptions.py::test_E",
"sympy/core/tests/test_assumptions.py::test_I",
"sympy/core/tests/test_assumptions.py::test_symbol_real",
"sympy/core/tests/test_assumptions.py::test_symbol_zero",
"sympy/core/tests/test_assumptions.py::test_symbol_positive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_positive",
"sympy/core/tests/test_assumptions.py::test_symbol_nonpositive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_nonpositive",
"sympy/core/tests/test_assumptions.py::test_symbol_falsepositive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsepositive",
"sympy/core/tests/test_assumptions.py::test_symbol_falsepositive_real",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsepositive_real",
"sympy/core/tests/test_assumptions.py::test_symbol_falsenonnegative",
"sympy/core/tests/test_assumptions.py::test_symbol_falsenonnegative_real",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsenonnegative_real",
"sympy/core/tests/test_assumptions.py::test_prime",
"sympy/core/tests/test_assumptions.py::test_prime_symbol",
"sympy/core/tests/test_assumptions.py::test_symbol_noncommutative",
"sympy/core/tests/test_assumptions.py::test_other_symbol",
"sympy/core/tests/test_assumptions.py::test_issue_3825",
"sympy/core/tests/test_assumptions.py::test_issue_4822",
"sympy/core/tests/test_assumptions.py::test_hash_vs_typeinfo",
"sympy/core/tests/test_assumptions.py::test_hash_vs_typeinfo_2",
"sympy/core/tests/test_assumptions.py::test_hash_vs_eq",
"sympy/core/tests/test_assumptions.py::test_Add_is_pos_neg",
"sympy/core/tests/test_assumptions.py::test_Add_is_imaginary",
"sympy/core/tests/test_assumptions.py::test_Add_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Mul_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Pow_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Mul_is_infinite",
"sympy/core/tests/test_assumptions.py::test_special_is_rational",
"sympy/core/tests/test_assumptions.py::test_sanitize_assumptions",
"sympy/core/tests/test_assumptions.py::test_special_assumptions",
"sympy/core/tests/test_assumptions.py::test_inconsistent",
"sympy/core/tests/test_assumptions.py::test_issue_6631",
"sympy/core/tests/test_assumptions.py::test_issue_2730",
"sympy/core/tests/test_assumptions.py::test_issue_4149",
"sympy/core/tests/test_assumptions.py::test_issue_2920",
"sympy/core/tests/test_assumptions.py::test_issue_7899",
"sympy/core/tests/test_assumptions.py::test_issue_8075",
"sympy/core/tests/test_assumptions.py::test_issue_8642",
"sympy/core/tests/test_assumptions.py::test_issues_8632_8633_8638_8675_8992",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_values",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_log",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_expand",
"sympy/functions/elementary/tests/test_exponential.py::test_exp__as_base_exp",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_infinity",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_subs",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_conjugate",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_rewrite",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_leading_term",
"sympy/functions/elementary/tests/test_exponential.py::test_log_values",
"sympy/functions/elementary/tests/test_exponential.py::test_log_base",
"sympy/functions/elementary/tests/test_exponential.py::test_log_symbolic",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_assumptions",
"sympy/functions/elementary/tests/test_exponential.py::test_log_assumptions",
"sympy/functions/elementary/tests/test_exponential.py::test_log_hashing",
"sympy/functions/elementary/tests/test_exponential.py::test_log_sign",
"sympy/functions/elementary/tests/test_exponential.py::test_log_expand_complex",
"sympy/functions/elementary/tests/test_exponential.py::test_log_apply_evalf",
"sympy/functions/elementary/tests/test_exponential.py::test_log_expand",
"sympy/functions/elementary/tests/test_exponential.py::test_log_simplify",
"sympy/functions/elementary/tests/test_exponential.py::test_lambertw",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_5673",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_expand_NC",
"sympy/functions/elementary/tests/test_exponential.py::test_as_numer_denom",
"sympy/functions/elementary/tests/test_exponential.py::test_polar",
"sympy/functions/elementary/tests/test_exponential.py::test_log_product",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_8866",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sin",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sin_cos",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sin_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sin_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sin_expansion",
"sympy/functions/elementary/tests/test_trigonometric.py::test_trig_symmetry",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cos",
"sympy/functions/elementary/tests/test_trigonometric.py::test_issue_6190",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cos_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cos_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cos_expansion",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tan",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tan_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tan_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tan_subs",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tan_expansion",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cot",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cot_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cot_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cot_subs",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cot_expansion",
"sympy/functions/elementary/tests/test_trigonometric.py::test_asin",
"sympy/functions/elementary/tests/test_trigonometric.py::test_asin_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_asin_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acos",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acos_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acos_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_atan",
"sympy/functions/elementary/tests/test_trigonometric.py::test_atan_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_atan2",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acot",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acot_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_attributes",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sincos_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_evenodd_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_issue_4547",
"sympy/functions/elementary/tests/test_trigonometric.py::test_as_leading_term_issue_5272",
"sympy/functions/elementary/tests/test_trigonometric.py::test_leading_terms",
"sympy/functions/elementary/tests/test_trigonometric.py::test_atan2_expansion",
"sympy/functions/elementary/tests/test_trigonometric.py::test_aseries",
"sympy/functions/elementary/tests/test_trigonometric.py::test_issue_4420",
"sympy/functions/elementary/tests/test_trigonometric.py::test_inverses",
"sympy/functions/elementary/tests/test_trigonometric.py::test_real_imag",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tancot_rewrite_sqrt",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sec",
"sympy/functions/elementary/tests/test_trigonometric.py::test_csc",
"sympy/functions/elementary/tests/test_trigonometric.py::test_asec",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acsc",
"sympy/functions/elementary/tests/test_trigonometric.py::test_issue_8653",
"sympy/integrals/tests/test_integrals.py::test_improper_integral",
"sympy/integrals/tests/test_integrals.py::test_constructor",
"sympy/integrals/tests/test_integrals.py::test_basics",
"sympy/integrals/tests/test_integrals.py::test_basics_multiple",
"sympy/integrals/tests/test_integrals.py::test_conjugate_transpose",
"sympy/integrals/tests/test_integrals.py::test_integration",
"sympy/integrals/tests/test_integrals.py::test_multiple_integration",
"sympy/integrals/tests/test_integrals.py::test_issue_3532",
"sympy/integrals/tests/test_integrals.py::test_issue_3560",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly_defined",
"sympy/integrals/tests/test_integrals.py::test_integrate_omit_var",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly_accurately",
"sympy/integrals/tests/test_integrals.py::test_issue_3635",
"sympy/integrals/tests/test_integrals.py::test_integrate_linearterm_pow",
"sympy/integrals/tests/test_integrals.py::test_issue_3618",
"sympy/integrals/tests/test_integrals.py::test_issue_3623",
"sympy/integrals/tests/test_integrals.py::test_issue_3664",
"sympy/integrals/tests/test_integrals.py::test_issue_3679",
"sympy/integrals/tests/test_integrals.py::test_issue_3686",
"sympy/integrals/tests/test_integrals.py::test_integrate_units",
"sympy/integrals/tests/test_integrals.py::test_transcendental_functions",
"sympy/integrals/tests/test_integrals.py::test_issue_3740",
"sympy/integrals/tests/test_integrals.py::test_issue_3788",
"sympy/integrals/tests/test_integrals.py::test_issue_3952",
"sympy/integrals/tests/test_integrals.py::test_issue_4516",
"sympy/integrals/tests/test_integrals.py::test_issue_7450",
"sympy/integrals/tests/test_integrals.py::test_matrices",
"sympy/integrals/tests/test_integrals.py::test_integrate_functions",
"sympy/integrals/tests/test_integrals.py::test_integrate_derivatives",
"sympy/integrals/tests/test_integrals.py::test_transform",
"sympy/integrals/tests/test_integrals.py::test_issue_4052",
"sympy/integrals/tests/test_integrals.py::test_evalf_integrals",
"sympy/integrals/tests/test_integrals.py::test_evalf_issue_939",
"sympy/integrals/tests/test_integrals.py::test_integrate_DiracDelta",
"sympy/integrals/tests/test_integrals.py::test_integrate_returns_piecewise",
"sympy/integrals/tests/test_integrals.py::test_subs1",
"sympy/integrals/tests/test_integrals.py::test_subs2",
"sympy/integrals/tests/test_integrals.py::test_subs3",
"sympy/integrals/tests/test_integrals.py::test_subs4",
"sympy/integrals/tests/test_integrals.py::test_subs5",
"sympy/integrals/tests/test_integrals.py::test_subs6",
"sympy/integrals/tests/test_integrals.py::test_subs7",
"sympy/integrals/tests/test_integrals.py::test_expand",
"sympy/integrals/tests/test_integrals.py::test_integration_variable",
"sympy/integrals/tests/test_integrals.py::test_expand_integral",
"sympy/integrals/tests/test_integrals.py::test_as_sum_midpoint1",
"sympy/integrals/tests/test_integrals.py::test_as_sum_midpoint2",
"sympy/integrals/tests/test_integrals.py::test_as_sum_left",
"sympy/integrals/tests/test_integrals.py::test_as_sum_right",
"sympy/integrals/tests/test_integrals.py::test_as_sum_raises",
"sympy/integrals/tests/test_integrals.py::test_nested_doit",
"sympy/integrals/tests/test_integrals.py::test_issue_4665",
"sympy/integrals/tests/test_integrals.py::test_integral_reconstruct",
"sympy/integrals/tests/test_integrals.py::test_doit_integrals",
"sympy/integrals/tests/test_integrals.py::test_issue_4884",
"sympy/integrals/tests/test_integrals.py::test_is_number",
"sympy/integrals/tests/test_integrals.py::test_symbols",
"sympy/integrals/tests/test_integrals.py::test_is_zero",
"sympy/integrals/tests/test_integrals.py::test_series",
"sympy/integrals/tests/test_integrals.py::test_issue_4403",
"sympy/integrals/tests/test_integrals.py::test_issue_4403_2",
"sympy/integrals/tests/test_integrals.py::test_issue_4100",
"sympy/integrals/tests/test_integrals.py::test_issue_5167",
"sympy/integrals/tests/test_integrals.py::test_issue_4890",
"sympy/integrals/tests/test_integrals.py::test_issue_4376",
"sympy/integrals/tests/test_integrals.py::test_issue_4517",
"sympy/integrals/tests/test_integrals.py::test_issue_4527",
"sympy/integrals/tests/test_integrals.py::test_issue_4199",
"sympy/integrals/tests/test_integrals.py::test_issue_3940",
"sympy/integrals/tests/test_integrals.py::test_issue_5413",
"sympy/integrals/tests/test_integrals.py::test_issue_4892a",
"sympy/integrals/tests/test_integrals.py::test_issue_4892b",
"sympy/integrals/tests/test_integrals.py::test_issue_5178",
"sympy/integrals/tests/test_integrals.py::test_integrate_series",
"sympy/integrals/tests/test_integrals.py::test_atom_bug",
"sympy/integrals/tests/test_integrals.py::test_limit_bug",
"sympy/integrals/tests/test_integrals.py::test_issue_4703",
"sympy/integrals/tests/test_integrals.py::test_issue_1888",
"sympy/integrals/tests/test_integrals.py::test_issue_3558",
"sympy/integrals/tests/test_integrals.py::test_issue_4422",
"sympy/integrals/tests/test_integrals.py::test_issue_4493",
"sympy/integrals/tests/test_integrals.py::test_issue_4737",
"sympy/integrals/tests/test_integrals.py::test_issue_4992",
"sympy/integrals/tests/test_integrals.py::test_issue_4487",
"sympy/integrals/tests/test_integrals.py::test_issue_4400",
"sympy/integrals/tests/test_integrals.py::test_issue_6253",
"sympy/integrals/tests/test_integrals.py::test_issue_4153",
"sympy/integrals/tests/test_integrals.py::test_issue_4326",
"sympy/integrals/tests/test_integrals.py::test_powers",
"sympy/integrals/tests/test_integrals.py::test_risch_option",
"sympy/integrals/tests/test_integrals.py::test_issue_6828",
"sympy/integrals/tests/test_integrals.py::test_issue_4803",
"sympy/integrals/tests/test_integrals.py::test_issue_4234",
"sympy/integrals/tests/test_integrals.py::test_issue_4492",
"sympy/integrals/tests/test_integrals.py::test_issue_2708",
"sympy/integrals/tests/test_integrals.py::test_issue_8368",
"sympy/integrals/tests/test_integrals.py::test_issue_8901",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_shape",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matexpr",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_subs",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_ZeroMatrix",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_ZeroMatrix_doit",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_Identity",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_Identity_doit",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_addition",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_multiplication",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatPow",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatrixSymbol",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_dense_conversion",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_free_symbols",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_zero_matmul",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matadd_simplify",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matmul_simplify",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_invariants",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_indexing",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_single_indexing",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatrixElement_diff",
"sympy/series/tests/test_limits.py::test_basic1",
"sympy/series/tests/test_limits.py::test_basic2",
"sympy/series/tests/test_limits.py::test_basic3",
"sympy/series/tests/test_limits.py::test_basic4",
"sympy/series/tests/test_limits.py::test_basic5",
"sympy/series/tests/test_limits.py::test_issue_3885",
"sympy/series/tests/test_limits.py::test_Limit",
"sympy/series/tests/test_limits.py::test_floor",
"sympy/series/tests/test_limits.py::test_floor_requires_robust_assumptions",
"sympy/series/tests/test_limits.py::test_ceiling",
"sympy/series/tests/test_limits.py::test_ceiling_requires_robust_assumptions",
"sympy/series/tests/test_limits.py::test_atan",
"sympy/series/tests/test_limits.py::test_abs",
"sympy/series/tests/test_limits.py::test_heuristic",
"sympy/series/tests/test_limits.py::test_issue_3871",
"sympy/series/tests/test_limits.py::test_exponential",
"sympy/series/tests/test_limits.py::test_doit",
"sympy/series/tests/test_limits.py::test_issue_3792",
"sympy/series/tests/test_limits.py::test_issue_4090",
"sympy/series/tests/test_limits.py::test_issue_4547",
"sympy/series/tests/test_limits.py::test_issue_5164",
"sympy/series/tests/test_limits.py::test_issue_5183",
"sympy/series/tests/test_limits.py::test_issue_5184",
"sympy/series/tests/test_limits.py::test_issue_5229",
"sympy/series/tests/test_limits.py::test_issue_4546",
"sympy/series/tests/test_limits.py::test_issue_3934",
"sympy/series/tests/test_limits.py::test_calculate_series",
"sympy/series/tests/test_limits.py::test_issue_5955",
"sympy/series/tests/test_limits.py::test_newissue",
"sympy/series/tests/test_limits.py::test_extended_real_line",
"sympy/series/tests/test_limits.py::test_issue_5436",
"sympy/series/tests/test_limits.py::test_Limit_dir",
"sympy/series/tests/test_limits.py::test_polynomial",
"sympy/series/tests/test_limits.py::test_rational",
"sympy/series/tests/test_limits.py::test_issue_5740",
"sympy/series/tests/test_limits.py::test_issue_6366",
"sympy/series/tests/test_limits.py::test_factorial",
"sympy/series/tests/test_limits.py::test_issue_6560",
"sympy/series/tests/test_limits.py::test_issue_5172",
"sympy/series/tests/test_limits.py::test_issue_7088",
"sympy/series/tests/test_limits.py::test_issue_6364",
"sympy/series/tests/test_limits.py::test_issue_4099",
"sympy/series/tests/test_limits.py::test_issue_4503",
"sympy/series/tests/test_limits.py::test_issue_8730",
"sympy/series/tests/test_residues.py::test_basic1",
"sympy/series/tests/test_residues.py::test_basic2",
"sympy/series/tests/test_residues.py::test_functions",
"sympy/series/tests/test_residues.py::test_expressions",
"sympy/series/tests/test_residues.py::test_NotImplemented",
"sympy/series/tests/test_residues.py::test_bug",
"sympy/series/tests/test_residues.py::test_issue_5654",
"sympy/series/tests/test_residues.py::test_issue_6499",
"sympy/solvers/tests/test_diophantine.py::test_input_format",
"sympy/solvers/tests/test_diophantine.py::test_univariate",
"sympy/solvers/tests/test_diophantine.py::test_linear",
"sympy/solvers/tests/test_diophantine.py::test_quadratic_simple_hyperbolic_case",
"sympy/solvers/tests/test_diophantine.py::test_quadratic_elliptical_case",
"sympy/solvers/tests/test_diophantine.py::test_quadratic_parabolic_case",
"sympy/solvers/tests/test_diophantine.py::test_quadratic_perfect_square",
"sympy/solvers/tests/test_diophantine.py::test_quadratic_non_perfect_square",
"sympy/solvers/tests/test_diophantine.py::test_quadratic_non_perfect_slow",
"sympy/solvers/tests/test_diophantine.py::test_DN",
"sympy/solvers/tests/test_diophantine.py::test_bf_pell",
"sympy/solvers/tests/test_diophantine.py::test_length",
"sympy/solvers/tests/test_diophantine.py::test_transformation_to_pell",
"sympy/solvers/tests/test_diophantine.py::test_find_DN",
"sympy/solvers/tests/test_diophantine.py::test_ldescent",
"sympy/solvers/tests/test_diophantine.py::test_diop_ternary_quadratic_normal",
"sympy/solvers/tests/test_diophantine.py::test_transformation_to_normal",
"sympy/solvers/tests/test_diophantine.py::test_diop_ternary_quadratic",
"sympy/solvers/tests/test_diophantine.py::test_pairwise_prime",
"sympy/solvers/tests/test_diophantine.py::test_square_factor",
"sympy/solvers/tests/test_diophantine.py::test_parametrize_ternary_quadratic",
"sympy/solvers/tests/test_diophantine.py::test_no_square_ternary_quadratic",
"sympy/solvers/tests/test_diophantine.py::test_descent",
"sympy/solvers/tests/test_diophantine.py::test_diophantine",
"sympy/solvers/tests/test_diophantine.py::test_general_pythagorean",
"sympy/solvers/tests/test_diophantine.py::test_diop_general_sum_of_squares",
"sympy/solvers/tests/test_diophantine.py::test_partition",
"sympy/solvers/tests/test_diophantine.py::test_prime_as_sum_of_two_squares",
"sympy/solvers/tests/test_diophantine.py::test_sum_of_three_squares",
"sympy/solvers/tests/test_diophantine.py::test_sum_of_four_squares",
"sympy/solvers/tests/test_diophantine.py::test_power_representation",
"sympy/solvers/tests/test_diophantine.py::test_assumptions"
] | [] | BSD | 61 |
|
sympy__sympy-9139 | e243d0586e669dc9d18db0a705f2bb7883f14634 | 2015-03-14 16:45:03 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/core/exprtools.py b/sympy/core/exprtools.py
index 7e786424f3..654b7f3bf4 100644
--- a/sympy/core/exprtools.py
+++ b/sympy/core/exprtools.py
@@ -72,7 +72,7 @@ def _monotonic_sign(self):
rv = _monotonic_sign(-self)
return rv if rv is None else -rv
- if self.is_Symbol:
+ if not self.is_Add and self.as_numer_denom()[1].is_number:
s = self
if s.is_prime:
if s.is_odd:
| factorial(n) >= 1 is not True for a nonnegative integer n
When `n` is a nonnegative integer, `factorial(n)` is a positive integer, but `factorial(n)>=1` does not simplify to `True`. | sympy/sympy | diff --git a/sympy/core/tests/test_assumptions.py b/sympy/core/tests/test_assumptions.py
index 52b473d90a..4e29f4e8ca 100644
--- a/sympy/core/tests/test_assumptions.py
+++ b/sympy/core/tests/test_assumptions.py
@@ -1,4 +1,4 @@
-from sympy import I, sqrt, log, exp, sin, asin
+from sympy import I, sqrt, log, exp, sin, asin, factorial
from sympy.core import Symbol, S, Rational, Integer, Dummy, Wild, Pow
from sympy.core.facts import InconsistentAssumptions
from sympy import simplify
@@ -900,3 +900,8 @@ def test_issues_8632_8633_8638_8675_8992():
assert ((p + 2)**3 - S.Half).is_positive
n = Dummy(negative=True)
assert (n - 3).is_nonpositive
+
+def test_issue_9115():
+ n = Dummy('n', integer=True, nonnegative=True)
+ assert (factorial(n) >= 1) == True
+ assert (factorial(n) < 1) == False
| {
"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": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"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",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"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
coverage==6.2
execnet==1.9.0
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
mpmath==1.3.0
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
pytest-asyncio==0.16.0
pytest-cov==4.0.0
pytest-mock==3.6.1
pytest-xdist==3.0.2
-e git+https://github.com/sympy/sympy.git@e243d0586e669dc9d18db0a705f2bb7883f14634#egg=sympy
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tomli==1.2.3
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: sympy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- attrs=21.4.0=pyhd3eb1b0_0
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- more-itertools=8.12.0=pyhd3eb1b0_0
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pip=21.2.2=py36h06a4308_0
- pluggy=0.13.1=py36h06a4308_0
- py=1.11.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pytest=6.2.4=py36h06a4308_2
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- toml=0.10.2=pyhd3eb1b0_0
- typing_extensions=4.1.1=pyh06a4308_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- pip:
- coverage==6.2
- execnet==1.9.0
- mpmath==1.3.0
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- tomli==1.2.3
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_assumptions.py::test_issue_9115"
] | [] | [
"sympy/core/tests/test_assumptions.py::test_symbol_unset",
"sympy/core/tests/test_assumptions.py::test_zero",
"sympy/core/tests/test_assumptions.py::test_one",
"sympy/core/tests/test_assumptions.py::test_negativeone",
"sympy/core/tests/test_assumptions.py::test_infinity",
"sympy/core/tests/test_assumptions.py::test_neg_infinity",
"sympy/core/tests/test_assumptions.py::test_nan",
"sympy/core/tests/test_assumptions.py::test_pos_rational",
"sympy/core/tests/test_assumptions.py::test_neg_rational",
"sympy/core/tests/test_assumptions.py::test_pi",
"sympy/core/tests/test_assumptions.py::test_E",
"sympy/core/tests/test_assumptions.py::test_I",
"sympy/core/tests/test_assumptions.py::test_symbol_real",
"sympy/core/tests/test_assumptions.py::test_symbol_zero",
"sympy/core/tests/test_assumptions.py::test_symbol_positive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_positive",
"sympy/core/tests/test_assumptions.py::test_symbol_nonpositive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_nonpositive",
"sympy/core/tests/test_assumptions.py::test_symbol_falsepositive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsepositive",
"sympy/core/tests/test_assumptions.py::test_symbol_falsepositive_real",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsepositive_real",
"sympy/core/tests/test_assumptions.py::test_symbol_falsenonnegative",
"sympy/core/tests/test_assumptions.py::test_symbol_falsenonnegative_real",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsenonnegative_real",
"sympy/core/tests/test_assumptions.py::test_prime",
"sympy/core/tests/test_assumptions.py::test_composite",
"sympy/core/tests/test_assumptions.py::test_prime_symbol",
"sympy/core/tests/test_assumptions.py::test_symbol_noncommutative",
"sympy/core/tests/test_assumptions.py::test_other_symbol",
"sympy/core/tests/test_assumptions.py::test_issue_3825",
"sympy/core/tests/test_assumptions.py::test_issue_4822",
"sympy/core/tests/test_assumptions.py::test_hash_vs_typeinfo",
"sympy/core/tests/test_assumptions.py::test_hash_vs_typeinfo_2",
"sympy/core/tests/test_assumptions.py::test_hash_vs_eq",
"sympy/core/tests/test_assumptions.py::test_Add_is_pos_neg",
"sympy/core/tests/test_assumptions.py::test_Add_is_imaginary",
"sympy/core/tests/test_assumptions.py::test_Add_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Mul_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Pow_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Mul_is_infinite",
"sympy/core/tests/test_assumptions.py::test_special_is_rational",
"sympy/core/tests/test_assumptions.py::test_sanitize_assumptions",
"sympy/core/tests/test_assumptions.py::test_special_assumptions",
"sympy/core/tests/test_assumptions.py::test_inconsistent",
"sympy/core/tests/test_assumptions.py::test_issue_6631",
"sympy/core/tests/test_assumptions.py::test_issue_2730",
"sympy/core/tests/test_assumptions.py::test_issue_4149",
"sympy/core/tests/test_assumptions.py::test_issue_2920",
"sympy/core/tests/test_assumptions.py::test_issue_7899",
"sympy/core/tests/test_assumptions.py::test_issue_8075",
"sympy/core/tests/test_assumptions.py::test_issue_8642",
"sympy/core/tests/test_assumptions.py::test_issues_8632_8633_8638_8675_8992"
] | [] | BSD | 62 |
|
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 |
|
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 |
|
sympy__sympy-9148 | f790d208b0268fdae4018ac11b5f4f28117f03bb | 2015-03-16 08:34:14 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | aktech: > Can you also verify that if
>
>p = Symbol('p', prime=True)
>then
>
>assert ln(p).is_positive == True
>?
Sure.
> In fact, I must say that I don't like comparing with == to constants such as True, False, etc.
Even I don't, but since I saw that in lot of tests, that's why I did that to maintain consistency.
Anyways, I have fixed that.
aktech: There is some problem with Travis:
```
sympy/simplify/tests/test_hyperexpand.py[13] .....
No output has been received in the last 10 minutes, this potentially indicates a stalled build or something wrong with the build itself.
```
This test Passes on local computer:
```
sympy/simplify/tests/test_hyperexpand.py[43] .....fffff...wwwwwwwwwwwww.........
........ [OK]
= tests finished: 25 passed, 13 skipped, 5 expected to fail, in 235.27 seconds =
amit@amit-UDell:~/Desktop/myrepo/sympy$
``` | diff --git a/AUTHORS b/AUTHORS
index f4cfe080ae..47a4f03692 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -387,6 +387,5 @@ harshil goel <[email protected]>
Lokesh Sharma <[email protected]>
Sartaj Singh <[email protected]>
Chris Swierczewski <[email protected]>
-Sumith <[email protected]>
Konstantin Togoi <[email protected]>
Param Singh <[email protected]>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index c40452b128..66cdf0e007 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -392,7 +392,6 @@ want to be mentioned here, so see our repository history for a full list).
#. Lokesh Sharma: reorder setup.py file imports to correct NameError
#. Sartaj Singh: use \left \| instead of \lvert for latex Abs
#. Chris Swierczewski: RootOf.evalf watches for root on interval boundary
-#. Sumith: implemented columnspace of a matrix
#. Konstantin Togoi: added truth_table and binary digit utilities to boolalg
#. Param Singh: added missing units from mks system
diff --git a/sympy/core/expr.py b/sympy/core/expr.py
index 0de02ff424..14142321ad 100644
--- a/sympy/core/expr.py
+++ b/sympy/core/expr.py
@@ -682,6 +682,10 @@ def equals(self, other, failing_expression=False):
return diff
return None
+ def _eval_is_composite(self):
+ if self.is_integer and self.is_positive and self.is_prime is False:
+ return True
+
def _eval_is_positive(self):
from sympy.polys.numberfields import minimal_polynomial
from sympy.polys.polyerrors import NotAlgebraic
diff --git a/sympy/core/exprtools.py b/sympy/core/exprtools.py
index 654b7f3bf4..7e786424f3 100644
--- a/sympy/core/exprtools.py
+++ b/sympy/core/exprtools.py
@@ -72,7 +72,7 @@ def _monotonic_sign(self):
rv = _monotonic_sign(-self)
return rv if rv is None else -rv
- if not self.is_Add and self.as_numer_denom()[1].is_number:
+ if self.is_Symbol:
s = self
if s.is_prime:
if s.is_odd:
diff --git a/sympy/core/facts.py b/sympy/core/facts.py
index 4cc36ac997..ef4af6b5ad 100644
--- a/sympy/core/facts.py
+++ b/sympy/core/facts.py
@@ -186,7 +186,7 @@ def apply_beta_to_alpha_route(alpha_implications, beta_rules):
ximpls.add(bimpl)
# we introduced new implication - now we have to restore
- # completeness of the whole set.
+ # completness of the whole set.
bimpl_impl = x_impl.get(bimpl)
if bimpl_impl is not None:
ximpls |= bimpl_impl[0]
diff --git a/sympy/functions/elementary/exponential.py b/sympy/functions/elementary/exponential.py
index 8b9881d7e3..35b6c8f4cf 100644
--- a/sympy/functions/elementary/exponential.py
+++ b/sympy/functions/elementary/exponential.py
@@ -301,7 +301,7 @@ def taylor_term(n, x, *previous_terms):
p = previous_terms[-1]
if p is not None:
return p * x / n
- return x**n/factorial(n)
+ return x**n/factorial()(n)
def as_real_imag(self, deep=True, **hints):
"""
@@ -687,6 +687,9 @@ def _eval_is_positive(self):
def _eval_is_zero(self):
return (self.args[0] - 1).is_zero
+ def _eval_is_nonnegative(self):
+ return (self.args[0] - 1).is_nonnegative
+
def _eval_nseries(self, x, n, logx):
# NOTE Please see the comment at the beginning of this file, labelled
# IMPORTANT.
diff --git a/sympy/matrices/expressions/matexpr.py b/sympy/matrices/expressions/matexpr.py
index b07b3750ad..01b7420823 100644
--- a/sympy/matrices/expressions/matexpr.py
+++ b/sympy/matrices/expressions/matexpr.py
@@ -322,14 +322,6 @@ class MatrixElement(Expr):
j = property(lambda self: self.args[2])
_diff_wrt = True
- def doit(self, **kwargs):
- deep = kwargs.get('deep', True)
- if deep:
- args = [arg.doit(**kwargs) for arg in self.args]
- else:
- args = self.args
- return args[0][args[1], args[2]]
-
class MatrixSymbol(MatrixExpr):
"""Symbolic representation of a Matrix object
diff --git a/sympy/physics/quantum/qubit.py b/sympy/physics/quantum/qubit.py
index 216f9d556f..58ba60d675 100644
--- a/sympy/physics/quantum/qubit.py
+++ b/sympy/physics/quantum/qubit.py
@@ -481,7 +481,7 @@ def matrix_to_density(mat):
def qubit_to_matrix(qubit, format='sympy'):
- """Converts an Add/Mul of Qubit objects into it's matrix representation
+ """Coverts an Add/Mul of Qubit objects into it's matrix representation
This function is the inverse of ``matrix_to_qubit`` and is a shorthand
for ``represent(qubit)``.
| ln(n) is not known to be nonnegative for positive integer n
If `n` is a positive integer, it is as least 1, hence `ln(n)` is at least 0, hence I'd expect
```python
>>> ln(n).is_nonnegative
```
to return `True` (but it returns `None`). | sympy/sympy | diff --git a/bin/coverage_doctest.py b/bin/coverage_doctest.py
index dfe02413e7..02e4c77198 100755
--- a/bin/coverage_doctest.py
+++ b/bin/coverage_doctest.py
@@ -396,7 +396,7 @@ def coverage(module_path, verbose=False, no_color=False, sphinx=True):
contained. It then goes through each of the classes/functions to get
the docstring and doctest coverage of the module. """
- # Import the package and find members
+ # Import the package and find membmers
m = None
try:
__import__(module_path)
diff --git a/sympy/core/tests/test_assumptions.py b/sympy/core/tests/test_assumptions.py
index 4e29f4e8ca..3c62a807f0 100644
--- a/sympy/core/tests/test_assumptions.py
+++ b/sympy/core/tests/test_assumptions.py
@@ -1,4 +1,4 @@
-from sympy import I, sqrt, log, exp, sin, asin, factorial
+from sympy import I, sqrt, log, exp, sin, asin
from sympy.core import Symbol, S, Rational, Integer, Dummy, Wild, Pow
from sympy.core.facts import InconsistentAssumptions
from sympy import simplify
@@ -479,7 +479,7 @@ def test_composite():
assert S(17).is_composite is False
assert S(4).is_composite is True
x = Dummy(integer=True, positive=True, prime=False)
- assert x.is_composite is None # x could be 1
+ assert x.is_composite
assert (x + 1).is_composite is None
@@ -900,8 +900,3 @@ def test_issues_8632_8633_8638_8675_8992():
assert ((p + 2)**3 - S.Half).is_positive
n = Dummy(negative=True)
assert (n - 3).is_nonpositive
-
-def test_issue_9115():
- n = Dummy('n', integer=True, nonnegative=True)
- assert (factorial(n) >= 1) == True
- assert (factorial(n) < 1) == False
diff --git a/sympy/functions/elementary/tests/test_exponential.py b/sympy/functions/elementary/tests/test_exponential.py
index 279254d9dd..a3e9ccb572 100644
--- a/sympy/functions/elementary/tests/test_exponential.py
+++ b/sympy/functions/elementary/tests/test_exponential.py
@@ -1,5 +1,5 @@
from sympy import (
- symbols, log, Float, nan, oo, zoo, I, pi, E, exp, Symbol,
+ symbols, log, ln, Float, nan, oo, zoo, I, pi, E, exp, Symbol,
LambertW, sqrt, Rational, expand_log, S, sign, conjugate,
sin, cos, sinh, cosh, tanh, exp_polar, re, Function, simplify)
@@ -131,10 +131,6 @@ def test_exp_leading_term():
assert exp(1/x).as_leading_term(x) == exp(1/x)
assert exp(2 + x).as_leading_term(x) == exp(2)
-def test_exp_taylor_term():
- x = symbols('x')
- assert exp(x).taylor_term(1, x) == x
- assert exp(x).taylor_term(3, x) == x**3/6
def test_log_values():
assert log(nan) == nan
@@ -444,6 +440,7 @@ def test_log_product():
expr = log(Product(-2, (n, 0, 4)))
assert simplify(expr) == expr
+
def test_issue_8866():
x = Symbol('x')
assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10))
@@ -456,3 +453,10 @@ def test_issue_8866():
b2 = log(exp(y), exp(5), evaluate=False)
assert simplify(log(l1, b1)) == simplify(log(l2, b2))
assert expand_log(log(l1, b1)) == expand_log(log(l2, b2))
+
+
+def test_issue_9116():
+ n = Symbol('n', positive=True, integer=True)
+
+ assert ln(n).is_nonnegative is True
+ assert log(n).is_nonnegative is True
diff --git a/sympy/matrices/expressions/tests/test_matrix_exprs.py b/sympy/matrices/expressions/tests/test_matrix_exprs.py
index d1f0dcbb23..77a8f1f9ed 100644
--- a/sympy/matrices/expressions/tests/test_matrix_exprs.py
+++ b/sympy/matrices/expressions/tests/test_matrix_exprs.py
@@ -207,9 +207,3 @@ def test_single_indexing():
def test_MatrixElement_diff():
assert (A[3, 0]*A[0, 0]).diff(A[0, 0]) == A[3, 0]
-
-
-def test_MatrixElement_doit():
- u = MatrixSymbol('u', 2, 1)
- v = ImmutableMatrix([3, 5])
- assert u[0, 0].subs(u, v).doit() == v[0, 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": 1,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 8
} | 0.7 | {
"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.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
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
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
-e git+https://github.com/sympy/sympy.git@f790d208b0268fdae4018ac11b5f4f28117f03bb#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_assumptions.py::test_composite",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_9116"
] | [] | [
"sympy/core/tests/test_assumptions.py::test_symbol_unset",
"sympy/core/tests/test_assumptions.py::test_zero",
"sympy/core/tests/test_assumptions.py::test_one",
"sympy/core/tests/test_assumptions.py::test_negativeone",
"sympy/core/tests/test_assumptions.py::test_infinity",
"sympy/core/tests/test_assumptions.py::test_neg_infinity",
"sympy/core/tests/test_assumptions.py::test_nan",
"sympy/core/tests/test_assumptions.py::test_pos_rational",
"sympy/core/tests/test_assumptions.py::test_neg_rational",
"sympy/core/tests/test_assumptions.py::test_pi",
"sympy/core/tests/test_assumptions.py::test_E",
"sympy/core/tests/test_assumptions.py::test_I",
"sympy/core/tests/test_assumptions.py::test_symbol_real",
"sympy/core/tests/test_assumptions.py::test_symbol_zero",
"sympy/core/tests/test_assumptions.py::test_symbol_positive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_positive",
"sympy/core/tests/test_assumptions.py::test_symbol_nonpositive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_nonpositive",
"sympy/core/tests/test_assumptions.py::test_symbol_falsepositive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsepositive",
"sympy/core/tests/test_assumptions.py::test_symbol_falsepositive_real",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsepositive_real",
"sympy/core/tests/test_assumptions.py::test_symbol_falsenonnegative",
"sympy/core/tests/test_assumptions.py::test_symbol_falsenonnegative_real",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsenonnegative_real",
"sympy/core/tests/test_assumptions.py::test_prime",
"sympy/core/tests/test_assumptions.py::test_prime_symbol",
"sympy/core/tests/test_assumptions.py::test_symbol_noncommutative",
"sympy/core/tests/test_assumptions.py::test_other_symbol",
"sympy/core/tests/test_assumptions.py::test_issue_3825",
"sympy/core/tests/test_assumptions.py::test_issue_4822",
"sympy/core/tests/test_assumptions.py::test_hash_vs_typeinfo",
"sympy/core/tests/test_assumptions.py::test_hash_vs_typeinfo_2",
"sympy/core/tests/test_assumptions.py::test_hash_vs_eq",
"sympy/core/tests/test_assumptions.py::test_Add_is_pos_neg",
"sympy/core/tests/test_assumptions.py::test_Add_is_imaginary",
"sympy/core/tests/test_assumptions.py::test_Add_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Mul_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Pow_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Mul_is_infinite",
"sympy/core/tests/test_assumptions.py::test_special_is_rational",
"sympy/core/tests/test_assumptions.py::test_sanitize_assumptions",
"sympy/core/tests/test_assumptions.py::test_special_assumptions",
"sympy/core/tests/test_assumptions.py::test_inconsistent",
"sympy/core/tests/test_assumptions.py::test_issue_6631",
"sympy/core/tests/test_assumptions.py::test_issue_2730",
"sympy/core/tests/test_assumptions.py::test_issue_4149",
"sympy/core/tests/test_assumptions.py::test_issue_2920",
"sympy/core/tests/test_assumptions.py::test_issue_7899",
"sympy/core/tests/test_assumptions.py::test_issue_8075",
"sympy/core/tests/test_assumptions.py::test_issue_8642",
"sympy/core/tests/test_assumptions.py::test_issues_8632_8633_8638_8675_8992",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_values",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_log",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_expand",
"sympy/functions/elementary/tests/test_exponential.py::test_exp__as_base_exp",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_infinity",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_subs",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_conjugate",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_rewrite",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_leading_term",
"sympy/functions/elementary/tests/test_exponential.py::test_log_values",
"sympy/functions/elementary/tests/test_exponential.py::test_log_base",
"sympy/functions/elementary/tests/test_exponential.py::test_log_symbolic",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_assumptions",
"sympy/functions/elementary/tests/test_exponential.py::test_log_assumptions",
"sympy/functions/elementary/tests/test_exponential.py::test_log_hashing",
"sympy/functions/elementary/tests/test_exponential.py::test_log_sign",
"sympy/functions/elementary/tests/test_exponential.py::test_log_expand_complex",
"sympy/functions/elementary/tests/test_exponential.py::test_log_apply_evalf",
"sympy/functions/elementary/tests/test_exponential.py::test_log_expand",
"sympy/functions/elementary/tests/test_exponential.py::test_log_simplify",
"sympy/functions/elementary/tests/test_exponential.py::test_lambertw",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_5673",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_expand_NC",
"sympy/functions/elementary/tests/test_exponential.py::test_as_numer_denom",
"sympy/functions/elementary/tests/test_exponential.py::test_polar",
"sympy/functions/elementary/tests/test_exponential.py::test_log_product",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_8866",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_shape",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matexpr",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_subs",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_ZeroMatrix",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_ZeroMatrix_doit",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_Identity",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_Identity_doit",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_addition",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_multiplication",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatPow",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatrixSymbol",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_dense_conversion",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_free_symbols",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_zero_matmul",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matadd_simplify",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_matmul_simplify",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_invariants",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_indexing",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_single_indexing",
"sympy/matrices/expressions/tests/test_matrix_exprs.py::test_MatrixElement_diff"
] | [] | BSD | 65 |
sympy__sympy-9156 | 10b9aa56e2b41e652767932cf3b043142e2d96e0 | 2015-03-16 14:12:30 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/AUTHORS b/AUTHORS
index 07e0a52f59..f4cfe080ae 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -390,7 +390,3 @@ Chris Swierczewski <[email protected]>
Sumith <[email protected]>
Konstantin Togoi <[email protected]>
Param Singh <[email protected]>
-Philippe Bouafia <[email protected]>
-Lucas Jones <[email protected]>
-Peter Schmidt <[email protected]>
-Jiaxing Liang <[email protected]>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index 1f02eff625..c40452b128 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -395,10 +395,6 @@ want to be mentioned here, so see our repository history for a full list).
#. Sumith: implemented columnspace of a matrix
#. Konstantin Togoi: added truth_table and binary digit utilities to boolalg
#. Param Singh: added missing units from mks system
-#. Philippe Bouafia: Fixed a typo.
-#. Lucas Jones: Add a test in integrals
-#. Peter Schmidt: Removed duplicate tests
-#. Jiaxing Liang: Fix infinite recursion issue in test_f
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
diff --git a/examples/galgebra/physics_check_latex.py b/examples/galgebra/physics_check_latex.py
index 3b69622d9c..e7dda69f59 100755
--- a/examples/galgebra/physics_check_latex.py
+++ b/examples/galgebra/physics_check_latex.py
@@ -28,7 +28,7 @@ def Maxwells_Equations_in_Geometric_Calculus():
print('\\text{Electromagnetic Field Bi-Vector\\;\\;} F = E+IB =', F)
print('%\\text{Four Current Density\\;\\;} J =', J)
gradF = grad*F
- print('#Geometric Derivative of Electromagnetic Field Bi-Vector')
+ print('#Geometric Derivative of Electomagnetic Field Bi-Vector')
gradF.Fmt(3, 'grad*F')
print('#Maxwell Equations')
diff --git a/examples/intermediate/coupled_cluster.py b/examples/intermediate/coupled_cluster.py
index eebda39f4c..5f5ab28b92 100755
--- a/examples/intermediate/coupled_cluster.py
+++ b/examples/intermediate/coupled_cluster.py
@@ -88,7 +88,7 @@ def main():
comm4 = evaluate_deltas(comm4)
comm4 = substitute_dummies(comm4)
- print("construct Hausdorff expansion...")
+ print("construct Hausdoff expansion...")
eq = H + comm1 + comm2/2 + comm3/6 + comm4/24
eq = eq.expand()
eq = evaluate_deltas(eq)
diff --git a/sympy/functions/combinatorial/numbers.py b/sympy/functions/combinatorial/numbers.py
index 6c10e4e1ab..b639372835 100644
--- a/sympy/functions/combinatorial/numbers.py
+++ b/sympy/functions/combinatorial/numbers.py
@@ -96,6 +96,9 @@ def _fibpoly(n, prev):
@classmethod
def eval(cls, n, sym=None):
+ if n is S.Infinity:
+ return S.Infinity
+
if n.is_Integer:
n = int(n)
if n < 0:
@@ -142,6 +145,9 @@ class lucas(Function):
@classmethod
def eval(cls, n):
+ if n is S.Infinity:
+ return S.Infinity
+
if n.is_Integer:
return fibonacci(n + 1) + fibonacci(n - 1)
diff --git a/sympy/functions/elementary/exponential.py b/sympy/functions/elementary/exponential.py
index 01559e77d8..8b9881d7e3 100644
--- a/sympy/functions/elementary/exponential.py
+++ b/sympy/functions/elementary/exponential.py
@@ -687,9 +687,6 @@ def _eval_is_positive(self):
def _eval_is_zero(self):
return (self.args[0] - 1).is_zero
- def _eval_is_nonnegative(self):
- return (self.args[0] - 1).is_nonnegative
-
def _eval_nseries(self, x, n, logx):
# NOTE Please see the comment at the beginning of this file, labelled
# IMPORTANT.
diff --git a/sympy/functions/elementary/trigonometric.py b/sympy/functions/elementary/trigonometric.py
index df0117467b..4ad9068349 100644
--- a/sympy/functions/elementary/trigonometric.py
+++ b/sympy/functions/elementary/trigonometric.py
@@ -1942,9 +1942,6 @@ def _eval_is_rational(self):
def _eval_is_positive(self):
return self.args[0].is_positive
- def _eval_is_nonnegative(self):
- return self.args[0].is_nonnegative
-
@classmethod
def eval(cls, arg):
if arg.is_Number:
| fibonacci(n).limit(n, oo) should be oo rather than fibonacci(oo)
This is consistent with `factorial(n).limit(n, oo)`, `subfactorial(n).limit(n, oo)`, etc. | sympy/sympy | diff --git a/bin/coverage_doctest.py b/bin/coverage_doctest.py
index dfe02413e7..02e4c77198 100755
--- a/bin/coverage_doctest.py
+++ b/bin/coverage_doctest.py
@@ -396,7 +396,7 @@ def coverage(module_path, verbose=False, no_color=False, sphinx=True):
contained. It then goes through each of the classes/functions to get
the docstring and doctest coverage of the module. """
- # Import the package and find members
+ # Import the package and find membmers
m = None
try:
__import__(module_path)
diff --git a/sympy/functions/combinatorial/tests/test_comb_numbers.py b/sympy/functions/combinatorial/tests/test_comb_numbers.py
index 0dd6f62dc1..b201a4ea4a 100644
--- a/sympy/functions/combinatorial/tests/test_comb_numbers.py
+++ b/sympy/functions/combinatorial/tests/test_comb_numbers.py
@@ -60,6 +60,11 @@ def test_fibonacci():
assert fibonacci(3, x) == x**2 + 1
assert fibonacci(4, x) == x**3 + 2*x
+ # issue #8800
+ n = Dummy('n')
+ assert fibonacci(n).limit(n, S.Infinity) == S.Infinity
+ assert lucas(n).limit(n, S.Infinity) == S.Infinity
+
def test_bell():
assert [bell(n) for n in range(8)] == [1, 1, 2, 5, 15, 52, 203, 877]
diff --git a/sympy/functions/elementary/tests/test_exponential.py b/sympy/functions/elementary/tests/test_exponential.py
index a2057365d8..279254d9dd 100644
--- a/sympy/functions/elementary/tests/test_exponential.py
+++ b/sympy/functions/elementary/tests/test_exponential.py
@@ -1,5 +1,5 @@
from sympy import (
- symbols, log, ln, Float, nan, oo, zoo, I, pi, E, exp, Symbol,
+ symbols, log, Float, nan, oo, zoo, I, pi, E, exp, Symbol,
LambertW, sqrt, Rational, expand_log, S, sign, conjugate,
sin, cos, sinh, cosh, tanh, exp_polar, re, Function, simplify)
@@ -444,7 +444,6 @@ def test_log_product():
expr = log(Product(-2, (n, 0, 4)))
assert simplify(expr) == expr
-
def test_issue_8866():
x = Symbol('x')
assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10))
@@ -457,10 +456,3 @@ def test_issue_8866():
b2 = log(exp(y), exp(5), evaluate=False)
assert simplify(log(l1, b1)) == simplify(log(l2, b2))
assert expand_log(log(l1, b1)) == expand_log(log(l2, b2))
-
-
-def test_issue_9116():
- n = Symbol('n', positive=True, integer=True)
-
- assert ln(n).is_nonnegative is True
- assert log(n).is_nonnegative is True
diff --git a/sympy/functions/elementary/tests/test_trigonometric.py b/sympy/functions/elementary/tests/test_trigonometric.py
index 5bc62b70d9..f94d1c341f 100644
--- a/sympy/functions/elementary/tests/test_trigonometric.py
+++ b/sympy/functions/elementary/tests/test_trigonometric.py
@@ -1390,8 +1390,3 @@ def test_issue_8653():
assert sin(n).is_irrational is None
assert cos(n).is_irrational is None
assert tan(n).is_irrational is None
-
-
-def test_issue_9157():
- n = Symbol('n', integer=True, positive=True)
- atan(n - 1).is_nonnegative is True
diff --git a/sympy/integrals/tests/test_integrals.py b/sympy/integrals/tests/test_integrals.py
index 3b59ab1713..b34db5b37d 100644
--- a/sympy/integrals/tests/test_integrals.py
+++ b/sympy/integrals/tests/test_integrals.py
@@ -1087,9 +1087,3 @@ def test_issue_8901():
assert integrate(sinh(1.0*x)) == 1.0*cosh(1.0*x)
assert integrate(tanh(1.0*x)) == 1.0*x - 1.0*log(tanh(1.0*x) + 1)
assert integrate(tanh(x)) == x - log(tanh(x) + 1)
-
-
-def test_issue_7130():
- i, L, a, b = symbols('i L a b')
- integrand = (cos(pi*i*x/L)**2 / (a + b*x)).rewrite(exp)
- assert x not in integrate(integrand, (x, 0, L)).free_symbols
diff --git a/sympy/series/tests/test_limits.py b/sympy/series/tests/test_limits.py
index bd160ac9fa..16dd4efeae 100644
--- a/sympy/series/tests/test_limits.py
+++ b/sympy/series/tests/test_limits.py
@@ -37,6 +37,9 @@ def test_basic1():
assert limit(gamma(1/x + 3), x, oo) == 2
assert limit(S.NaN, x, -oo) == S.NaN
assert limit(Order(2)*x, x, S.NaN) == S.NaN
+ assert limit(gamma(1/x + 3), x, oo) == 2
+ assert limit(S.NaN, x, -oo) == S.NaN
+ assert limit(Order(2)*x, x, S.NaN) == S.NaN
assert limit(1/(x - 1), x, 1, dir="+") == oo
assert limit(1/(x - 1), x, 1, dir="-") == -oo
assert limit(1/(5 - x)**3, x, 5, dir="+") == -oo
diff --git a/sympy/series/tests/test_residues.py b/sympy/series/tests/test_residues.py
index 23db6f4fee..676f603677 100644
--- a/sympy/series/tests/test_residues.py
+++ b/sympy/series/tests/test_residues.py
@@ -26,8 +26,9 @@ def test_basic2():
def _test_f():
+ # FIXME: we get infinite recursion here:
f = Function("f")
- assert residue(f(x)/x**5, x, 0) == f(x).diff(x, 4).subs(x, 0)/24
+ assert residue(f(x)/x**5, x, 0) == f.diff(x, 4)/24
def test_functions():
| {
"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": 7
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": null,
"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
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
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
-e git+https://github.com/sympy/sympy.git@10b9aa56e2b41e652767932cf3b043142e2d96e0#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_fibonacci"
] | [
"sympy/functions/elementary/tests/test_trigonometric.py::test_sincos_rewrite_sqrt",
"sympy/series/tests/test_limits.py::test_basic1",
"sympy/series/tests/test_limits.py::test_floor",
"sympy/series/tests/test_limits.py::test_floor_requires_robust_assumptions",
"sympy/series/tests/test_limits.py::test_ceiling",
"sympy/series/tests/test_limits.py::test_ceiling_requires_robust_assumptions"
] | [
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_bernoulli",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_bell",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_rational",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_evalf",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_rewrite_polygamma",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_rewrite_sum",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_euler",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_catalan",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_genocchi",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_nC_nP_nT",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_issue_8496",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_issue_8601",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_values",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_log",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_expand",
"sympy/functions/elementary/tests/test_exponential.py::test_exp__as_base_exp",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_infinity",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_subs",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_conjugate",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_rewrite",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_leading_term",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_taylor_term",
"sympy/functions/elementary/tests/test_exponential.py::test_log_values",
"sympy/functions/elementary/tests/test_exponential.py::test_log_base",
"sympy/functions/elementary/tests/test_exponential.py::test_log_symbolic",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_assumptions",
"sympy/functions/elementary/tests/test_exponential.py::test_log_assumptions",
"sympy/functions/elementary/tests/test_exponential.py::test_log_hashing",
"sympy/functions/elementary/tests/test_exponential.py::test_log_sign",
"sympy/functions/elementary/tests/test_exponential.py::test_log_expand_complex",
"sympy/functions/elementary/tests/test_exponential.py::test_log_apply_evalf",
"sympy/functions/elementary/tests/test_exponential.py::test_log_expand",
"sympy/functions/elementary/tests/test_exponential.py::test_log_simplify",
"sympy/functions/elementary/tests/test_exponential.py::test_lambertw",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_5673",
"sympy/functions/elementary/tests/test_exponential.py::test_exp_expand_NC",
"sympy/functions/elementary/tests/test_exponential.py::test_as_numer_denom",
"sympy/functions/elementary/tests/test_exponential.py::test_polar",
"sympy/functions/elementary/tests/test_exponential.py::test_log_product",
"sympy/functions/elementary/tests/test_exponential.py::test_issue_8866",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sin",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sin_cos",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sin_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sin_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sin_expansion",
"sympy/functions/elementary/tests/test_trigonometric.py::test_trig_symmetry",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cos",
"sympy/functions/elementary/tests/test_trigonometric.py::test_issue_6190",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cos_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cos_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cos_expansion",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tan",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tan_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tan_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tan_subs",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tan_expansion",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cot",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cot_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cot_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cot_subs",
"sympy/functions/elementary/tests/test_trigonometric.py::test_cot_expansion",
"sympy/functions/elementary/tests/test_trigonometric.py::test_asin",
"sympy/functions/elementary/tests/test_trigonometric.py::test_asin_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_asin_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acos",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acos_series",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acos_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_atan",
"sympy/functions/elementary/tests/test_trigonometric.py::test_atan_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_atan2",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acot",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acot_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_attributes",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sincos_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_evenodd_rewrite",
"sympy/functions/elementary/tests/test_trigonometric.py::test_issue_4547",
"sympy/functions/elementary/tests/test_trigonometric.py::test_as_leading_term_issue_5272",
"sympy/functions/elementary/tests/test_trigonometric.py::test_leading_terms",
"sympy/functions/elementary/tests/test_trigonometric.py::test_atan2_expansion",
"sympy/functions/elementary/tests/test_trigonometric.py::test_aseries",
"sympy/functions/elementary/tests/test_trigonometric.py::test_issue_4420",
"sympy/functions/elementary/tests/test_trigonometric.py::test_inverses",
"sympy/functions/elementary/tests/test_trigonometric.py::test_real_imag",
"sympy/functions/elementary/tests/test_trigonometric.py::test_tancot_rewrite_sqrt",
"sympy/functions/elementary/tests/test_trigonometric.py::test_sec",
"sympy/functions/elementary/tests/test_trigonometric.py::test_csc",
"sympy/functions/elementary/tests/test_trigonometric.py::test_asec",
"sympy/functions/elementary/tests/test_trigonometric.py::test_acsc",
"sympy/functions/elementary/tests/test_trigonometric.py::test_issue_8653",
"sympy/integrals/tests/test_integrals.py::test_improper_integral",
"sympy/integrals/tests/test_integrals.py::test_constructor",
"sympy/integrals/tests/test_integrals.py::test_basics",
"sympy/integrals/tests/test_integrals.py::test_basics_multiple",
"sympy/integrals/tests/test_integrals.py::test_conjugate_transpose",
"sympy/integrals/tests/test_integrals.py::test_integration",
"sympy/integrals/tests/test_integrals.py::test_multiple_integration",
"sympy/integrals/tests/test_integrals.py::test_issue_3532",
"sympy/integrals/tests/test_integrals.py::test_issue_3560",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly_defined",
"sympy/integrals/tests/test_integrals.py::test_integrate_omit_var",
"sympy/integrals/tests/test_integrals.py::test_integrate_poly_accurately",
"sympy/integrals/tests/test_integrals.py::test_issue_3635",
"sympy/integrals/tests/test_integrals.py::test_integrate_linearterm_pow",
"sympy/integrals/tests/test_integrals.py::test_issue_3618",
"sympy/integrals/tests/test_integrals.py::test_issue_3623",
"sympy/integrals/tests/test_integrals.py::test_issue_3664",
"sympy/integrals/tests/test_integrals.py::test_issue_3679",
"sympy/integrals/tests/test_integrals.py::test_issue_3686",
"sympy/integrals/tests/test_integrals.py::test_integrate_units",
"sympy/integrals/tests/test_integrals.py::test_transcendental_functions",
"sympy/integrals/tests/test_integrals.py::test_issue_3740",
"sympy/integrals/tests/test_integrals.py::test_issue_3788",
"sympy/integrals/tests/test_integrals.py::test_issue_3952",
"sympy/integrals/tests/test_integrals.py::test_issue_4516",
"sympy/integrals/tests/test_integrals.py::test_issue_7450",
"sympy/integrals/tests/test_integrals.py::test_matrices",
"sympy/integrals/tests/test_integrals.py::test_integrate_functions",
"sympy/integrals/tests/test_integrals.py::test_integrate_derivatives",
"sympy/integrals/tests/test_integrals.py::test_transform",
"sympy/integrals/tests/test_integrals.py::test_issue_4052",
"sympy/integrals/tests/test_integrals.py::test_evalf_integrals",
"sympy/integrals/tests/test_integrals.py::test_evalf_issue_939",
"sympy/integrals/tests/test_integrals.py::test_integrate_DiracDelta",
"sympy/integrals/tests/test_integrals.py::test_integrate_returns_piecewise",
"sympy/integrals/tests/test_integrals.py::test_subs1",
"sympy/integrals/tests/test_integrals.py::test_subs2",
"sympy/integrals/tests/test_integrals.py::test_subs3",
"sympy/integrals/tests/test_integrals.py::test_subs4",
"sympy/integrals/tests/test_integrals.py::test_subs5",
"sympy/integrals/tests/test_integrals.py::test_subs6",
"sympy/integrals/tests/test_integrals.py::test_subs7",
"sympy/integrals/tests/test_integrals.py::test_expand",
"sympy/integrals/tests/test_integrals.py::test_integration_variable",
"sympy/integrals/tests/test_integrals.py::test_expand_integral",
"sympy/integrals/tests/test_integrals.py::test_as_sum_midpoint1",
"sympy/integrals/tests/test_integrals.py::test_as_sum_midpoint2",
"sympy/integrals/tests/test_integrals.py::test_as_sum_left",
"sympy/integrals/tests/test_integrals.py::test_as_sum_right",
"sympy/integrals/tests/test_integrals.py::test_as_sum_raises",
"sympy/integrals/tests/test_integrals.py::test_nested_doit",
"sympy/integrals/tests/test_integrals.py::test_issue_4665",
"sympy/integrals/tests/test_integrals.py::test_integral_reconstruct",
"sympy/integrals/tests/test_integrals.py::test_doit_integrals",
"sympy/integrals/tests/test_integrals.py::test_issue_4884",
"sympy/integrals/tests/test_integrals.py::test_is_number",
"sympy/integrals/tests/test_integrals.py::test_symbols",
"sympy/integrals/tests/test_integrals.py::test_is_zero",
"sympy/integrals/tests/test_integrals.py::test_series",
"sympy/integrals/tests/test_integrals.py::test_issue_4403",
"sympy/integrals/tests/test_integrals.py::test_issue_4403_2",
"sympy/integrals/tests/test_integrals.py::test_issue_4100",
"sympy/integrals/tests/test_integrals.py::test_issue_5167",
"sympy/integrals/tests/test_integrals.py::test_issue_4890",
"sympy/integrals/tests/test_integrals.py::test_issue_4376",
"sympy/integrals/tests/test_integrals.py::test_issue_4517",
"sympy/integrals/tests/test_integrals.py::test_issue_4527",
"sympy/integrals/tests/test_integrals.py::test_issue_4199",
"sympy/integrals/tests/test_integrals.py::test_issue_3940",
"sympy/integrals/tests/test_integrals.py::test_issue_5413",
"sympy/integrals/tests/test_integrals.py::test_issue_4892a",
"sympy/integrals/tests/test_integrals.py::test_issue_4892b",
"sympy/integrals/tests/test_integrals.py::test_issue_5178",
"sympy/integrals/tests/test_integrals.py::test_integrate_series",
"sympy/integrals/tests/test_integrals.py::test_atom_bug",
"sympy/integrals/tests/test_integrals.py::test_limit_bug",
"sympy/integrals/tests/test_integrals.py::test_issue_4703",
"sympy/integrals/tests/test_integrals.py::test_issue_1888",
"sympy/integrals/tests/test_integrals.py::test_issue_3558",
"sympy/integrals/tests/test_integrals.py::test_issue_4422",
"sympy/integrals/tests/test_integrals.py::test_issue_4493",
"sympy/integrals/tests/test_integrals.py::test_issue_4737",
"sympy/integrals/tests/test_integrals.py::test_issue_4992",
"sympy/integrals/tests/test_integrals.py::test_issue_4487",
"sympy/integrals/tests/test_integrals.py::test_issue_4400",
"sympy/integrals/tests/test_integrals.py::test_issue_6253",
"sympy/integrals/tests/test_integrals.py::test_issue_4153",
"sympy/integrals/tests/test_integrals.py::test_issue_4326",
"sympy/integrals/tests/test_integrals.py::test_powers",
"sympy/integrals/tests/test_integrals.py::test_risch_option",
"sympy/integrals/tests/test_integrals.py::test_issue_6828",
"sympy/integrals/tests/test_integrals.py::test_issue_4803",
"sympy/integrals/tests/test_integrals.py::test_issue_4234",
"sympy/integrals/tests/test_integrals.py::test_issue_4492",
"sympy/integrals/tests/test_integrals.py::test_issue_2708",
"sympy/integrals/tests/test_integrals.py::test_issue_8368",
"sympy/integrals/tests/test_integrals.py::test_issue_8901",
"sympy/series/tests/test_limits.py::test_basic2",
"sympy/series/tests/test_limits.py::test_basic3",
"sympy/series/tests/test_limits.py::test_basic4",
"sympy/series/tests/test_limits.py::test_basic5",
"sympy/series/tests/test_limits.py::test_issue_3885",
"sympy/series/tests/test_limits.py::test_Limit",
"sympy/series/tests/test_limits.py::test_atan",
"sympy/series/tests/test_limits.py::test_abs",
"sympy/series/tests/test_limits.py::test_heuristic",
"sympy/series/tests/test_limits.py::test_issue_3871",
"sympy/series/tests/test_limits.py::test_exponential",
"sympy/series/tests/test_limits.py::test_doit",
"sympy/series/tests/test_limits.py::test_issue_3792",
"sympy/series/tests/test_limits.py::test_issue_4090",
"sympy/series/tests/test_limits.py::test_issue_4547",
"sympy/series/tests/test_limits.py::test_issue_5164",
"sympy/series/tests/test_limits.py::test_issue_5183",
"sympy/series/tests/test_limits.py::test_issue_5184",
"sympy/series/tests/test_limits.py::test_issue_5229",
"sympy/series/tests/test_limits.py::test_issue_4546",
"sympy/series/tests/test_limits.py::test_issue_3934",
"sympy/series/tests/test_limits.py::test_calculate_series",
"sympy/series/tests/test_limits.py::test_issue_5955",
"sympy/series/tests/test_limits.py::test_newissue",
"sympy/series/tests/test_limits.py::test_extended_real_line",
"sympy/series/tests/test_limits.py::test_issue_5436",
"sympy/series/tests/test_limits.py::test_Limit_dir",
"sympy/series/tests/test_limits.py::test_polynomial",
"sympy/series/tests/test_limits.py::test_rational",
"sympy/series/tests/test_limits.py::test_issue_5740",
"sympy/series/tests/test_limits.py::test_issue_6366",
"sympy/series/tests/test_limits.py::test_factorial",
"sympy/series/tests/test_limits.py::test_issue_6560",
"sympy/series/tests/test_limits.py::test_issue_5172",
"sympy/series/tests/test_limits.py::test_issue_7088",
"sympy/series/tests/test_limits.py::test_issue_6364",
"sympy/series/tests/test_limits.py::test_issue_4099",
"sympy/series/tests/test_limits.py::test_issue_4503",
"sympy/series/tests/test_limits.py::test_issue_8730",
"sympy/series/tests/test_residues.py::test_basic1",
"sympy/series/tests/test_residues.py::test_basic2",
"sympy/series/tests/test_residues.py::test_functions",
"sympy/series/tests/test_residues.py::test_expressions",
"sympy/series/tests/test_residues.py::test_NotImplemented",
"sympy/series/tests/test_residues.py::test_bug",
"sympy/series/tests/test_residues.py::test_issue_5654",
"sympy/series/tests/test_residues.py::test_issue_6499"
] | [] | BSD | 66 |
|
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 |
|
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 |
|
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 |
|
sympy__sympy-9179 | 6e714f677b552129ccf8f1e3fc0659cfa247a338 | 2015-03-21 13:52:25 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | debugger22: @cbm755 Please review.
debugger22: Now:
```
mrsud@jarvis:~/workspace/sympy$ time ./bin/test sympy/integrals/tests/test_meijerint.py
============================== test process starts ==============================
executable: /usr/bin/python (2.7.5-final-0) [CPython]
architecture: 64-bit
cache: yes
ground types: python
random seed: 93926777
hash randomization: on (PYTHONHASHSEED=2679446471)
sympy/integrals/tests/test_meijerint.py[21] ..................... [OK]
================= tests finished: 21 passed, in 788.01 seconds ==================
real 13m8.764s
user 12m12.048s
sys 0m2.916s
```
Earlier:
```
mrsud@jarvis:~/workspace/sympy$ time ./bin/test sympy/integrals/tests/test_meijerint.py
============================= test process starts ==============================
executable: /usr/bin/python (2.7.5-final-0) [CPython]
architecture: 64-bit
cache: yes
ground types: python
random seed: 33224468
hash randomization: on (PYTHONHASHSEED=1274036100)
sympy/integrals/tests/test_meijerint.py[21] ..................... [OK]
================= tests finished: 21 passed, in 355.37 seconds =================
real 5m56.866s
user 5m16.792s
sys 0m1.888s
```
This change almost doubled the time taken by meijerint tests. I'm clueless how these couple of ifs caused these.
debugger22: @asmeurer If I'm right then this, at least, shows how badly assumptions affect the performance when they are in core.
cbm755: Sorry @debugger22, I fear this is a bit outside my comfort zone...
Re: Meijerint slow down: IIRC, `is_zero` is cheap but worth double-checking? Perhaps more likely: some code path in there doesn't really expect NaN (see e.g., #7942).
debugger22: > Perhaps more likely: some code path in there doesn't really expect NaN (see e.g., #7942).
This makes more sense.
Clearly, this isn't a good fix. Or maybe a bigger issue is at play here.
debugger22: This one worked.
**In my branch**
```
mrsud@jarvis:~/workspace/sympy$ ./bin/test sympy/integrals/tests/test_meijerint.py
============================== test process starts ===============================
executable: /usr/bin/python (2.7.5-final-0) [CPython]
architecture: 64-bit
cache: yes
ground types: python
random seed: 60322084
hash randomization: on (PYTHONHASHSEED=1973071046)
sympy/integrals/tests/test_meijerint.py[21] ..................... [OK]
================== tests finished: 21 passed, in 112.14 seconds ==================
```
**In master**
```
mrsud@jarvis:~/workspace/sympy$ ./bin/test sympy/integrals/tests/test_meijerint.py
============================== test process starts ===============================
executable: /usr/bin/python (2.7.5-final-0) [CPython]
architecture: 64-bit
cache: yes
ground types: python
random seed: 21661312
hash randomization: on (PYTHONHASHSEED=892971179)
sympy/integrals/tests/test_meijerint.py[21] ..................... [OK]
================== tests finished: 21 passed, in 111.44 seconds ==================
```
@cbm755 I was going to leave it unevaluated but thought to give it another spin.
debugger22: @asmeurer Are you +1 to this?
cbm755: @debugger22: I think this looks good apart except the deleted test mentioned earlier and the tests for the `self.args` stuff...
asmeurer: Looks good to me as well.
debugger22: @shivamvats Do you mind adding those tests here which you missed in https://github.com/sympy/sympy/pull/8401?
shivamvats: @debugger22 I'm sorry for errors in #8401.
Which tests do you want me to add (I can see is_finite mentioned)? I will do it in a day or two as I have tests going on.
debugger22: @shivamvats Cool. Probably, you should add tests for `is_finite` and `is_real` handlers for `csch` and `sech` so that the code that I changed in this PR gets covered by them. | diff --git a/sympy/core/mul.py b/sympy/core/mul.py
index 30a0231525..982d8db475 100644
--- a/sympy/core/mul.py
+++ b/sympy/core/mul.py
@@ -549,7 +549,10 @@ def _handle_for_oo(c_part, coeff_sign):
# 0
elif coeff is S.Zero:
- # we know for sure the result will be 0
+ # we know for sure the result will be 0 except the multiplicand
+ # is infinity
+ if any(c.is_finite == False for c in c_part):
+ return [S.NaN], [], order_symbols
return [coeff], [], order_symbols
# check for straggling Numbers that were produced
| "0/0 = 0" from `0 / Symbol('z', zero=True)`
@skirpichev noted this in https://github.com/sympy/sympy/issues/8751#issuecomment-68861692 in a now-closed bug and I didn't see it filed elsewhere.
````
S(0)/0 # nan, correct
````
But now:
````
z = Symbol('z', zero=True)
0/z # 0, wrong, should be nan
(1/z).is_finite # False, correct (UPDATED, thanks @debugger22)
0*(1/z) # 0, wrong, should be nan
````
Similarly:
````
f = Symbol('f', finite=False)
0*f # 0, this is wrong, should be nan
````
Something should be checking `is_finite`? I started taking a look inside `mul.py` but scary...! | sympy/sympy | diff --git a/sympy/core/tests/test_assumptions.py b/sympy/core/tests/test_assumptions.py
index 4e29f4e8ca..67bbc3c7fa 100644
--- a/sympy/core/tests/test_assumptions.py
+++ b/sympy/core/tests/test_assumptions.py
@@ -901,7 +901,16 @@ def test_issues_8632_8633_8638_8675_8992():
n = Dummy(negative=True)
assert (n - 3).is_nonpositive
+
def test_issue_9115():
n = Dummy('n', integer=True, nonnegative=True)
assert (factorial(n) >= 1) == True
assert (factorial(n) < 1) == False
+
+
+def test_issue_9165():
+ z = Symbol('z', zero=True)
+ f = Symbol('f', finite=False)
+ assert 0/z == S.NaN
+ assert 0*(1/z) == S.NaN
+ assert 0*f == S.NaN
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest"
],
"pre_install": [],
"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
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
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
-e git+https://github.com/sympy/sympy.git@6e714f677b552129ccf8f1e3fc0659cfa247a338#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/core/tests/test_assumptions.py::test_issue_9165"
] | [] | [
"sympy/core/tests/test_assumptions.py::test_symbol_unset",
"sympy/core/tests/test_assumptions.py::test_zero",
"sympy/core/tests/test_assumptions.py::test_one",
"sympy/core/tests/test_assumptions.py::test_negativeone",
"sympy/core/tests/test_assumptions.py::test_infinity",
"sympy/core/tests/test_assumptions.py::test_neg_infinity",
"sympy/core/tests/test_assumptions.py::test_nan",
"sympy/core/tests/test_assumptions.py::test_pos_rational",
"sympy/core/tests/test_assumptions.py::test_neg_rational",
"sympy/core/tests/test_assumptions.py::test_pi",
"sympy/core/tests/test_assumptions.py::test_E",
"sympy/core/tests/test_assumptions.py::test_I",
"sympy/core/tests/test_assumptions.py::test_symbol_real",
"sympy/core/tests/test_assumptions.py::test_symbol_zero",
"sympy/core/tests/test_assumptions.py::test_symbol_positive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_positive",
"sympy/core/tests/test_assumptions.py::test_symbol_nonpositive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_nonpositive",
"sympy/core/tests/test_assumptions.py::test_symbol_falsepositive",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsepositive",
"sympy/core/tests/test_assumptions.py::test_symbol_falsepositive_real",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsepositive_real",
"sympy/core/tests/test_assumptions.py::test_symbol_falsenonnegative",
"sympy/core/tests/test_assumptions.py::test_symbol_falsenonnegative_real",
"sympy/core/tests/test_assumptions.py::test_neg_symbol_falsenonnegative_real",
"sympy/core/tests/test_assumptions.py::test_prime",
"sympy/core/tests/test_assumptions.py::test_composite",
"sympy/core/tests/test_assumptions.py::test_prime_symbol",
"sympy/core/tests/test_assumptions.py::test_symbol_noncommutative",
"sympy/core/tests/test_assumptions.py::test_other_symbol",
"sympy/core/tests/test_assumptions.py::test_issue_3825",
"sympy/core/tests/test_assumptions.py::test_issue_4822",
"sympy/core/tests/test_assumptions.py::test_hash_vs_typeinfo",
"sympy/core/tests/test_assumptions.py::test_hash_vs_typeinfo_2",
"sympy/core/tests/test_assumptions.py::test_hash_vs_eq",
"sympy/core/tests/test_assumptions.py::test_Add_is_pos_neg",
"sympy/core/tests/test_assumptions.py::test_Add_is_imaginary",
"sympy/core/tests/test_assumptions.py::test_Add_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Mul_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Pow_is_algebraic",
"sympy/core/tests/test_assumptions.py::test_Mul_is_infinite",
"sympy/core/tests/test_assumptions.py::test_special_is_rational",
"sympy/core/tests/test_assumptions.py::test_sanitize_assumptions",
"sympy/core/tests/test_assumptions.py::test_special_assumptions",
"sympy/core/tests/test_assumptions.py::test_inconsistent",
"sympy/core/tests/test_assumptions.py::test_issue_6631",
"sympy/core/tests/test_assumptions.py::test_issue_2730",
"sympy/core/tests/test_assumptions.py::test_issue_4149",
"sympy/core/tests/test_assumptions.py::test_issue_2920",
"sympy/core/tests/test_assumptions.py::test_issue_7899",
"sympy/core/tests/test_assumptions.py::test_issue_8075",
"sympy/core/tests/test_assumptions.py::test_issue_8642",
"sympy/core/tests/test_assumptions.py::test_issues_8632_8633_8638_8675_8992",
"sympy/core/tests/test_assumptions.py::test_issue_9115"
] | [] | BSD | 70 |
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 |
|
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 |
|
sympy__sympy-9198 | 9242d31f6d31a1d9c3464264a5a6e61eab8acfb8 | 2015-03-25 00:14:17 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/sympy/functions/combinatorial/numbers.py b/sympy/functions/combinatorial/numbers.py
index b639372835..808886c285 100644
--- a/sympy/functions/combinatorial/numbers.py
+++ b/sympy/functions/combinatorial/numbers.py
@@ -424,6 +424,9 @@ def _bell_incomplete_poly(n, k, symbols):
@classmethod
def eval(cls, n, k_sym=None, symbols=None):
+ if n is S.Infinity:
+ return S.Infinity
+
if n.is_Integer and n.is_nonnegative:
if k_sym is None:
return Integer(cls._bell(int(n)))
| bell(n).limit(n, oo) should be oo rather than bell(oo)
`bell(n).limit(n,oo)` should take the value infinity, but the current output is `bell(oo)`. As the Bell numbers represent the number of partitions of a set, it seems natural that `bell(oo)` should be able to be evaluated rather than be returned unevaluated. This issue is also in line with the recent fixes to the corresponding limit for the Fibonacci numbers and Lucas numbers.
```
from sympy import *
n = symbols('n')
bell(n).limit(n,oo)
Output:
bell(oo)
```
I'm new to Sympy, so I'd appreciate the opportunity to fix this bug myself if that's alright.
| sympy/sympy | diff --git a/sympy/functions/combinatorial/tests/test_comb_numbers.py b/sympy/functions/combinatorial/tests/test_comb_numbers.py
index b201a4ea4a..6fab11a441 100644
--- a/sympy/functions/combinatorial/tests/test_comb_numbers.py
+++ b/sympy/functions/combinatorial/tests/test_comb_numbers.py
@@ -103,6 +103,10 @@ def test_bell():
m = Symbol('m', integer=True)
assert bell(-1).evalf() == bell(m).rewrite(Sum).evalf(subs={m: -1})
+ # issue 9184
+ n = Dummy('n')
+ assert bell(n).limit(n, S.Infinity) == S.Infinity
+
def test_harmonic():
n = Symbol("n")
| {
"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
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"pytest",
"numpy",
"matplotlib"
],
"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
cycler==0.11.0
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
kiwisolver==1.3.1
matplotlib==3.3.4
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
mpmath==1.3.0
numpy==1.19.5
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
Pillow==8.4.0
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
python-dateutil==2.9.0.post0
six==1.17.0
-e git+https://github.com/sympy/sympy.git@9242d31f6d31a1d9c3464264a5a6e61eab8acfb8#egg=sympy
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: sympy
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:
- cycler==0.11.0
- kiwisolver==1.3.1
- matplotlib==3.3.4
- mpmath==1.3.0
- numpy==1.19.5
- pillow==8.4.0
- python-dateutil==2.9.0.post0
- six==1.17.0
prefix: /opt/conda/envs/sympy
| [
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_bell"
] | [] | [
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_bernoulli",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_fibonacci",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_rational",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_evalf",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_rewrite_polygamma",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_harmonic_rewrite_sum",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_euler",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_catalan",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_genocchi",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_nC_nP_nT",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_issue_8496",
"sympy/functions/combinatorial/tests/test_comb_numbers.py::test_issue_8601"
] | [] | BSD | 73 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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__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 |
|
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 |
|
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 |
|
google__yapf-75 | cfb99aba49789019542ec6cb2b3f7215d1f9a04f | 2015-04-07 05:21:11 | 5e7c8aadfe6ed7d892e858b305ef2ca60c65bfcc | coveralls:
[](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:
[](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 |
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 `¶`) 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: '‚',
right-single-quote: '‘',
left-double-quote: '„',
right-double-quote: '“'
```
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">¶</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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
|
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 |
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 |
|
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 @@
-[](https://travis-ci.org/Shopify/shopify_python_api)
-[](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 |
|
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 |
|
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 |
|
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 |
|
sympy__sympy-9306 | 7496dfde89b1baff83b692e99eda56b8c394b15a | 2015-04-16 02:57:10 | 0241b35cae5f2adc04dc37b25f7dc9c5f00bd746 | diff --git a/AUTHORS b/AUTHORS
index 30a642d10e..c7a5d1ab54 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -230,6 +230,7 @@ Niklas Thörne <[email protected]>
Huijun Mai <[email protected]>
Marek Šuppa <[email protected]>
Prasoon Shukla <[email protected]>
+Sergey B Kirpichev <[email protected]>
Stefen Yin <[email protected]>
Thomas Hisch <[email protected]>
Matthew Hoff <[email protected]>
diff --git a/bin/mailmap_update.py b/bin/mailmap_update.py
index 7764192502..7f258c1b5c 100755
--- a/bin/mailmap_update.py
+++ b/bin/mailmap_update.py
@@ -52,7 +52,7 @@
authors = AUTHORS[AUTHORS.find(firstauthor):].strip().split('\n')
# People who don't want to be listed in AUTHORS
-authors_skip = ["Kirill Smelkov <[email protected]>", "Sergey B Kirpichev <[email protected]>"]
+authors_skip = ["Kirill Smelkov <[email protected]>"]
predate_git = 0
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index cf03181293..28b76c667f 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -235,6 +235,7 @@ want to be mentioned here, so see our repository history for a full list).
#. Huijun Mai: Chinese translation of the tutorial
#. Marek Šuppa: Improvements to symbols, tests
#. Prasoon Shukla: Bug fixes
+#. Sergey B Kirpichev: Bug fixes
#. Stefen Yin: Fixes to the mechanics module
#. Thomas Hisch: Improvements to the printing module
#. Matthew Hoff: Addition to quantum module
diff --git a/sympy/abc.py b/sympy/abc.py
index 709ffc4ce5..b751a61d15 100644
--- a/sympy/abc.py
+++ b/sympy/abc.py
@@ -2,36 +2,10 @@
import string
-from .core import Symbol, symbols
+from .core import Symbol
from .core.alphabets import greeks
from .core.compatibility import exec_
-##### Symbol definitions #####
-
-# Implementation note: The easiest way to avoid typos in the symbols()
-# parameter is to copy it from the left-hand side of the assignment.
-
-a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j')
-k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t')
-u, v, w, x, y, z = symbols('u, v, w, x, y, z')
-
-A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J')
-K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T')
-U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z')
-
-alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta')
-epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta')
-iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu')
-nu, xi, omicron, pi = symbols('nu, xi, omicron, pi')
-rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon')
-phi, chi, psi, omega = symbols('phi, chi, psi, omega')
-
-
-##### Clashing-symbols diagnostics #####
-
-# We want to know which names in SymPy collide with those in here.
-# This is mostly for diagnosing SymPy's namespace during SymPy development.
-
_latin = list(string.ascii_letters)
# OSINEQ should not be imported as they clash; gamma, pi and zeta clash, too
_greek = list(greeks) # make a copy, so we can mutate it
@@ -39,6 +13,9 @@
_greek.remove("lambda")
_greek.append("lamda")
+for _s in _latin + _greek:
+ exec_("%s = Symbol('%s')" % (_s, _s))
+
def clashing():
"""Return the clashing-symbols dictionaries.
@@ -85,4 +62,4 @@ def clashing():
_clash1, _clash2, _clash = clashing()
-del _latin, _greek, clashing, Symbol
+del _latin, _greek, _s, clashing, Symbol
diff --git a/sympy/functions/special/tensor_functions.py b/sympy/functions/special/tensor_functions.py
index a4ed440c61..ba3edd114f 100644
--- a/sympy/functions/special/tensor_functions.py
+++ b/sympy/functions/special/tensor_functions.py
@@ -155,16 +155,11 @@ def eval(cls, i, j):
# indirect doctest
"""
- if (i > j) is True:
- return cls(j, i)
-
- diff = Abs(i - j)
- if diff == 0:
+ diff = i - j
+ if diff.is_zero:
return S.One
- elif diff.is_number:
+ elif diff.is_nonzero:
return S.Zero
- elif i != 0 and diff.is_nonzero:
- return cls(0, diff.args[0])
if i.assumptions0.get("below_fermi") and \
j.assumptions0.get("above_fermi"):
| KroneckerDelta(p, 0) raises IndexError
To reproduce
```
>>> p = Symbol('p', prime=True)
>>> KroneckerDelta(p, 0)
IndexError Traceback (most recent call last)
<ipython-input-2-7104d3bd4b37> in <module>()
----> 1 KroneckerDelta(p, 0)
/home/leosartaj/projects/sympy/sympy/core/cache.pyc in wrapper(*args, **kwargs)
89 def wrapper(*args, **kwargs):
90 try:
---> 91 retval = cfunc(*args, **kwargs)
92 except TypeError:
93 retval = func(*args, **kwargs)
/home/leosartaj/projects/sympy/sympy/core/compatibility.pyc in wrapper(*args, **kwds)
878 stats[HITS] += 1
879 return result
--> 880 result = user_function(*args, **kwds)
881 with lock:
882 root, = nonlocal_root
/home/leosartaj/projects/sympy/sympy/core/function.pyc in __new__(cls, *args, **options)
374
375 evaluate = options.get('evaluate', global_evaluate[0])
--> 376 result = super(Function, cls).__new__(cls, *args, **options)
377 if not evaluate or not isinstance(result, cls):
378 return result
/home/leosartaj/projects/sympy/sympy/core/cache.pyc in wrapper(*args, **kwargs)
89 def wrapper(*args, **kwargs):
90 try:
---> 91 retval = cfunc(*args, **kwargs)
92 except TypeError:
93 retval = func(*args, **kwargs)
/home/leosartaj/projects/sympy/sympy/core/compatibility.pyc in wrapper(*args, **kwds)
878 stats[HITS] += 1
879 return result
--> 880 result = user_function(*args, **kwds)
881 with lock:
882 root, = nonlocal_root
/home/leosartaj/projects/sympy/sympy/core/function.pyc in __new__(cls, *args, **options)
198
199 if evaluate:
--> 200 evaluated = cls.eval(*args)
201 if evaluated is not None:
202 return evaluated
/home/leosartaj/projects/sympy/sympy/functions/special/tensor_functions.py in eval(cls, i, j)
165 return S.Zero
166 elif i != 0 and diff.is_nonzero:
--> 167 return cls(0, diff.args[0])
168
169 if i.assumptions0.get("below_fermi") and \
IndexError: tuple index out of range
```
This is because in this case `args` is an empty `Tuple`, hence the `IndexError`. I will send a PR to fix the issue. | sympy/sympy | diff --git a/sympy/functions/special/tests/test_tensor_functions.py b/sympy/functions/special/tests/test_tensor_functions.py
index 888d879721..dcc69c8a02 100644
--- a/sympy/functions/special/tests/test_tensor_functions.py
+++ b/sympy/functions/special/tests/test_tensor_functions.py
@@ -34,13 +34,14 @@ def test_kronecker_delta():
k = Symbol('k', nonzero=True)
assert KroneckerDelta(1, 1) == 1
assert KroneckerDelta(1, 2) == 0
+ assert KroneckerDelta(k, 0) == 0
assert KroneckerDelta(x, x) == 1
assert KroneckerDelta(x**2 - y**2, x**2 - y**2) == 1
assert KroneckerDelta(i, i) == 1
assert KroneckerDelta(i, i + 1) == 0
assert KroneckerDelta(0, 0) == 1
assert KroneckerDelta(0, 1) == 0
- assert KroneckerDelta(i + k, i) == KroneckerDelta(0, k)
+ assert KroneckerDelta(i + k, i) == 0
assert KroneckerDelta(i + k, i + k) == 1
assert KroneckerDelta(i + k, i + 1 + k) == 0
assert KroneckerDelta(i, j).subs(dict(i=1, j=0)) == 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": 1,
"issue_text_score": 0,
"test_score": 1
},
"num_modified_files": 5
} | 0.7 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"mpmath>=0.19",
"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
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mpmath==1.3.0
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
-e git+https://github.com/sympy/sympy.git@7496dfde89b1baff83b692e99eda56b8c394b15a#egg=sympy
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
zipp @ file:///croot/zipp_1672387121353/work
| name: sympy
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:
- mpmath==1.3.0
prefix: /opt/conda/envs/sympy
| [
"sympy/functions/special/tests/test_tensor_functions.py::test_kronecker_delta"
] | [] | [
"sympy/functions/special/tests/test_tensor_functions.py::test_levicivita",
"sympy/functions/special/tests/test_tensor_functions.py::test_kronecker_delta_secondquant"
] | [] | BSD | 99 |
Subsets and Splits