instance_id
stringlengths 10
57
| base_commit
stringlengths 40
40
| created_at
stringdate 2014-04-30 14:58:36
2025-04-30 20:14:11
| environment_setup_commit
stringlengths 40
40
| hints_text
stringlengths 0
273k
| patch
stringlengths 251
7.06M
| problem_statement
stringlengths 11
52.5k
| repo
stringlengths 7
53
| test_patch
stringlengths 231
997k
| meta
dict | version
stringclasses 851
values | install_config
dict | requirements
stringlengths 93
34.2k
⌀ | environment
stringlengths 760
20.5k
⌀ | FAIL_TO_PASS
listlengths 1
9.39k
| FAIL_TO_FAIL
listlengths 0
2.69k
| PASS_TO_PASS
listlengths 0
7.87k
| PASS_TO_FAIL
listlengths 0
192
| license_name
stringclasses 55
values | __index_level_0__
int64 0
21.4k
| before_filepaths
listlengths 1
105
| after_filepaths
listlengths 1
105
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
networkx__networkx-2618 | 3f4fd85765bf2d88188cfd4c84d0707152e6cd1e | 2017-08-16 06:31:13 | 3f4fd85765bf2d88188cfd4c84d0707152e6cd1e | diff --git a/doc/release/migration_guide_from_1.x_to_2.0.rst b/doc/release/migration_guide_from_1.x_to_2.0.rst
index d403fcb15..087605643 100644
--- a/doc/release/migration_guide_from_1.x_to_2.0.rst
+++ b/doc/release/migration_guide_from_1.x_to_2.0.rst
@@ -10,12 +10,37 @@ We have made some major changes to the methods in the Multi/Di/Graph classes.
The methods changed are explained with examples below.
With the release of NetworkX 2.0 we are moving to a view/iterator reporting API.
+We have moved many methods from reporting lists or dicts to iterating over
+the information. Most of the changes in this regard are in the base classes.
Methods that used to return containers now return views (inspired from
[dictionary views](https://docs.python.org/3/library/stdtypes.html#dict-views)
in Python) and methods that returned iterators have been removed.
-For example, ``G.nodes`` (or ``G.nodes()``) now returns a NodeView and
-``G.nodes_iter()`` has been removed. The Graph attributes G.node and G.edge
-have also been removed in favor of using G.nodes[n] and G.edges[u, v].
+The methods which create new graphs have changed in the depth of data copying.
+G.subgraph/edge_subgraph/reverse/to_directed/to_undirected are affected.
+Many now have options for view creation instead of copying data. The depth
+of the dta copying may have also changed.
+
+One View example is ``G.nodes`` (or ``G.nodes()``) which now returns a
+dict-like NodeView while ``G.nodes_iter()`` has been removed. Similarly
+for views with ``G.edges`` and removing ``G.edges_iter``.
+The Graph attributes G.node and G.edge have been removed in favor of using
+G.nodes[n] and G.edges[u, v].
+Finally, the selfloop methods and add_path/star/cycle have been moved from
+graph methods to networkx functions.
+
+We expect that these changes will break some code. We have tried to make
+them break the code in ways that raise exceptions, so it will be obvious
+that code is broken.
+
+There are also a number of improvements to the codebase outside of the base
+graph classes. These are too numerous to catalog here, but a couple obvious
+ones include:
+- centering of nodes in drawing/nx_pylab,
+- iterator vs dict output from a few shortest_path routines
+
+-------
+
+Some demonstrations:
>>> import networkx as nx
>>> G = nx.complete_graph(5)
@@ -40,7 +65,7 @@ If you want a list of nodes you can use the Python list function
G.nodes is set-like allowing set operations. It is also dict-like in that you
can look up node data with G.nodes[n]['weight']. You can still use the calling
interface G.nodes(data='weight') to iterate over node/data pairs. In addition
-to the dict-like views keys/values/items, G.nodes has a data-view
+to the dict-like views keys/values/items, G.nodes has a data-view
G.nodes.data('weight'). The new EdgeView G.edges has similar features for edges.
By adding views NetworkX supports some new features like set operations on
@@ -89,7 +114,7 @@ If ``n`` is a node in ``G``, then ``G.neighbors(n)`` returns an iterator.
>>> list(G.neighbors(2))
[0, 1, 3, 4]
-DiGraphs behave similar to Graphs, but have a few more methods.
+DiGraphViews behave similar to GraphViews, but have a few more methods.
>>> D = nx.DiGraph()
>>> D.add_edges_from([(1, 2), (2, 3), (1, 3), (2, 4)])
@@ -127,7 +152,7 @@ DiGraphs behave similar to Graphs, but have a few more methods.
[1]
The same changes apply to MultiGraphs and MultiDiGraphs.
-
+
-------
The order of arguments to ``set_edge_attributes`` and ``set_node_attributes`` has
@@ -150,10 +175,10 @@ can be refactored as
>>> G = nx.Graph([(1, 2), (1, 3)])
>>> nx.set_node_attributes(G, name='label', values={1: 'one', 2: 'two', 3: 'three'})
>>> nx.set_edge_attributes(G, name='label', values={(1, 2): 'path1', (2, 3): 'path2'})
-
+
-------
-Some methods have been removed from the base graph class and placed into the main
+Some methods have been removed from the base graph class and placed into the main
networkx namespace. These are: G.add_path, G.add_star, G.add_cycle, G.number_of_selfloops,
G.nodes_with_selfloops, and G.selfloop_edges. These are replaced by nx.path_graph(G, ...)
nx.add_star(G, ...), nx.selfloop_edges(G), etc.
diff --git a/doc/release/release_dev.rst b/doc/release/release_dev.rst
index 627cf38d6..a35d9beaf 100644
--- a/doc/release/release_dev.rst
+++ b/doc/release/release_dev.rst
@@ -189,6 +189,9 @@ API Changes
G.node and G.edge are removed. Their functionality are replaced by G.nodes
and G.edges.
+* [`#2620 <https://github.com/networkx/networkx/pull/2620>`_]
+ Removed ``draw_nx``, please use ``draw`` or ``draw_networkx``.
+
Deprecations
------------
diff --git a/networkx/algorithms/centrality/harmonic.py b/networkx/algorithms/centrality/harmonic.py
index c851acaae..571dca4ab 100644
--- a/networkx/algorithms/centrality/harmonic.py
+++ b/networkx/algorithms/centrality/harmonic.py
@@ -65,4 +65,5 @@ def harmonic_centrality(G, nbunch=None, distance=None):
if G.is_directed():
G = G.reverse()
spl = partial(nx.shortest_path_length, G, weight=distance)
- return {u: sum(1 / d if d > 0 else 0 for v, d in spl(source=u)) for u in G.nbunch_iter(nbunch)}
+ return {u: sum(1 / d if d > 0 else 0 for v, d in spl(source=u).items())
+ for u in G.nbunch_iter(nbunch)}
diff --git a/networkx/algorithms/connectivity/stoerwagner.py b/networkx/algorithms/connectivity/stoerwagner.py
index 40b543497..3f55934c2 100644
--- a/networkx/algorithms/connectivity/stoerwagner.py
+++ b/networkx/algorithms/connectivity/stoerwagner.py
@@ -151,7 +151,7 @@ def stoer_wagner(G, weight='weight', heap=BinaryHeap):
G = nx.Graph(islice(contractions, best_phase))
v = contractions[best_phase][1]
G.add_node(v)
- reachable = set(n for n, d in nx.single_source_shortest_path_length(G, v))
+ reachable = set(nx.single_source_shortest_path_length(G, v))
partition = (list(reachable), list(nodes - reachable))
return cut_value, partition
diff --git a/networkx/algorithms/dag.py b/networkx/algorithms/dag.py
index 473e4ce90..437fb9ed9 100644
--- a/networkx/algorithms/dag.py
+++ b/networkx/algorithms/dag.py
@@ -51,7 +51,8 @@ def descendants(G, source):
"""
if not G.has_node(source):
raise nx.NetworkXError("The node %s is not in the graph." % source)
- des = set(n for n, d in nx.shortest_path_length(G, source=source)) - set([source])
+ spl = nx.shortest_path_length(G, source=source)
+ des = set(spl) - set([source])
return des
@@ -71,7 +72,8 @@ def ancestors(G, source):
"""
if not G.has_node(source):
raise nx.NetworkXError("The node %s is not in the graph." % source)
- anc = set(n for n, d in nx.shortest_path_length(G, target=source)) - set([source])
+ spl = nx.shortest_path_length(G, target=source)
+ anc = set(spl) - set([source])
return anc
diff --git a/networkx/algorithms/distance_measures.py b/networkx/algorithms/distance_measures.py
index de0f10d2c..c2d9ec9d3 100644
--- a/networkx/algorithms/distance_measures.py
+++ b/networkx/algorithms/distance_measures.py
@@ -223,7 +223,7 @@ def eccentricity(G, v=None, sp=None):
e = {}
for n in G.nbunch_iter(v):
if sp is None:
- length = dict(networkx.single_source_shortest_path_length(G, n))
+ length = networkx.single_source_shortest_path_length(G, n)
L = len(length)
else:
try:
diff --git a/networkx/algorithms/efficiency.py b/networkx/algorithms/efficiency.py
index 63cf0f2a9..46b2fdcd3 100644
--- a/networkx/algorithms/efficiency.py
+++ b/networkx/algorithms/efficiency.py
@@ -12,6 +12,7 @@ from __future__ import division
from itertools import permutations
import networkx as nx
+from networkx.exception import NetworkXNoPath
from ..utils import not_implemented_for
__all__ = ['efficiency', 'local_efficiency', 'global_efficiency']
@@ -22,7 +23,8 @@ def efficiency(G, u, v):
"""Returns the efficiency of a pair of nodes in a graph.
The *efficiency* of a pair of nodes is the multiplicative inverse of the
- shortest path distance between the nodes [1]_.
+ shortest path distance between the nodes [1]_. Returns 0 if no path
+ between nodes.
Parameters
----------
@@ -53,7 +55,11 @@ def efficiency(G, u, v):
<http://dx.doi.org/10.1103/PhysRevLett.87.198701>
"""
- return 1 / nx.shortest_path_length(G, u, v)
+ try:
+ eff = 1 / nx.shortest_path_length(G, u, v)
+ except NetworkXNoPath:
+ eff = 0
+ return eff
@not_implemented_for('directed')
@@ -93,11 +99,15 @@ def global_efficiency(G):
"""
n = len(G)
denom = n * (n - 1)
+ if denom != 0:
+ g_eff = sum(efficiency(G, u, v) for u, v in permutations(G, 2)) / denom
+ else:
+ g_eff = 0
# TODO This can be made more efficient by computing all pairs shortest
# path lengths in parallel.
#
# TODO This summation can be trivially parallelized.
- return sum(efficiency(G, u, v) for u, v in permutations(G, 2)) / denom
+ return g_eff
@not_implemented_for('directed')
diff --git a/networkx/drawing/nx_pylab.py b/networkx/drawing/nx_pylab.py
index 4a5e5ee4b..79c012c36 100644
--- a/networkx/drawing/nx_pylab.py
+++ b/networkx/drawing/nx_pylab.py
@@ -982,11 +982,6 @@ def draw_shell(G, **kwargs):
draw(G, shell_layout(G, nlist=nlist), **kwargs)
-def draw_nx(G, pos, **kwds):
- """For backward compatibility; use draw or draw_networkx."""
- draw(G, pos, **kwds)
-
-
def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None):
"""Apply an alpha (or list of alphas) to the colors provided.
diff --git a/networkx/release.py b/networkx/release.py
index a76968da9..54af63702 100644
--- a/networkx/release.py
+++ b/networkx/release.py
@@ -101,9 +101,9 @@ vcs_info = %(vcs_info)r
# This is *good*, and the most likely place users will be when
# running setup.py. We do not want to overwrite version.py.
# Grab the version so that setup can use it.
- sys.path.insert(0, basedir)
+ #sys.path.insert(0, basedir)
from version import version
- del sys.path[0]
+ #del sys.path[0]
else:
# This is *bad*. It means the user might have a tarball that
# does not include version.py. Let this error raise so we can
@@ -152,7 +152,7 @@ def get_info(dynamic=True):
# This is where most final releases of NetworkX will be.
# All info should come from version.py. If it does not exist, then
# no vcs information will be provided.
- sys.path.insert(0, basedir)
+ #sys.path.insert(0, basedir)
try:
from version import date, date_info, version, version_info, vcs_info
except ImportError:
@@ -160,7 +160,7 @@ def get_info(dynamic=True):
vcs_info = (None, (None, None))
else:
revision = vcs_info[1][0]
- del sys.path[0]
+ #del sys.path[0]
if import_failed or (dynamic and not dynamic_failed):
# We are here if:
| `networkx.version` shadows any other module named `version` if imported first
Steps to reproduce:
```
$ pip freeze | grep networkx
networkx==1.11
$ touch version.py
$ python -c 'import version; print(version)'
<module 'version' from '/Users/ben/scratch/version.py'>
$ python -c 'import networkx; import version; print(version)'
<module 'version' from '/Users/ben/.virtualenvs/personal/lib/python3.6/site-packages/networkx/version.py'>
```
Reading the code, it looks like the `release` module is adding the networkx package to `sys.path`, importing version and deleting it again? | networkx/networkx | diff --git a/networkx/algorithms/shortest_paths/generic.py b/networkx/algorithms/shortest_paths/generic.py
index b5144e04b..fe8e68526 100644
--- a/networkx/algorithms/shortest_paths/generic.py
+++ b/networkx/algorithms/shortest_paths/generic.py
@@ -113,9 +113,9 @@ def shortest_path(G, source=None, target=None, weight=None):
if target is None:
# Find paths between all pairs.
if weight is None:
- paths = nx.all_pairs_shortest_path(G)
+ paths = dict(nx.all_pairs_shortest_path(G))
else:
- paths = nx.all_pairs_dijkstra_path(G, weight=weight)
+ paths = dict(nx.all_pairs_dijkstra_path(G, weight=weight))
else:
# Find paths from all nodes co-accessible to the target.
with nx.utils.reversed(G):
@@ -174,19 +174,15 @@ def shortest_path_length(G, source=None, target=None, weight=None):
If the source and target are both specified, return the length of
the shortest path from the source to the target.
- If only the source is specified, return a tuple
- (target, shortest path length) iterator, where shortest path lengths
- are the lengths of the shortest path from the source to one of the
- targets.
+ If only the source is specified, return a dict keyed by target
+ to the shortest path length from the source to that target.
- If only the target is specified, return a tuple
- (source, shortest path length) iterator, where shortest path lengths
- are the lengths of the shortest path from one of the sources
- to the target.
+ If only the target is specified, return a dict keyed by source
+ to the shortest path length from that source to the target.
- If neither the source nor target are specified, return a
- (source, dictionary) iterator with dictionary keyed by target and
- shortest path length as the key value.
+ If neither the source nor target are specified, return an iterator
+ over (source, dictionary) where dictionary is keyed by target to
+ shortest path length from source to that target.
Raises
------
@@ -199,13 +195,13 @@ def shortest_path_length(G, source=None, target=None, weight=None):
>>> nx.shortest_path_length(G, source=0, target=4)
4
>>> p = nx.shortest_path_length(G, source=0) # target not specified
- >>> dict(p)[4]
+ >>> p[4]
4
>>> p = nx.shortest_path_length(G, target=4) # source not specified
- >>> dict(p)[0]
+ >>> p[0]
4
- >>> p = nx.shortest_path_length(G) # source,target not specified
- >>> dict(p)[0][4]
+ >>> p = dict(nx.shortest_path_length(G)) # source,target not specified
+ >>> p[0][4]
4
Notes
@@ -239,7 +235,7 @@ def shortest_path_length(G, source=None, target=None, weight=None):
# We need to exhaust the iterator as Graph needs
# to be reversed.
path_length = nx.single_source_shortest_path_length
- paths = list(path_length(G, target))
+ paths = path_length(G, target)
else:
path_length = nx.single_source_dijkstra_path_length
paths = path_length(G, target, weight=weight)
@@ -333,7 +329,7 @@ def average_shortest_path_length(G, weight=None):
ssdpl = nx.single_source_dijkstra_path_length
path_length = lambda v: ssdpl(G, v, weight=weight)
# Sum the distances for each (ordered) pair of source and target node.
- s = sum(l for u in G for v, l in path_length(u))
+ s = sum(l for u in G for l in path_length(u).values())
return s / (n * (n - 1))
diff --git a/networkx/algorithms/shortest_paths/tests/test_generic.py b/networkx/algorithms/shortest_paths/tests/test_generic.py
index 021bfb774..1d992412a 100644
--- a/networkx/algorithms/shortest_paths/tests/test_generic.py
+++ b/networkx/algorithms/shortest_paths/tests/test_generic.py
@@ -96,14 +96,14 @@ class TestGenericPath:
def test_all_pairs_shortest_path(self):
p=nx.shortest_path(self.cycle)
- assert_equal(p[0][3],[0,1,2,3])
- assert_equal(p,nx.all_pairs_shortest_path(self.cycle))
+ assert_equal(p[0][3], [0, 1, 2, 3])
+ assert_equal(p, dict(nx.all_pairs_shortest_path(self.cycle)))
p=nx.shortest_path(self.grid)
validate_grid_path(4, 4, 1, 12, p[1][12])
# now with weights
p=nx.shortest_path(self.cycle,weight='weight')
- assert_equal(p[0][3],[0,1,2,3])
- assert_equal(p,nx.all_pairs_dijkstra_path(self.cycle))
+ assert_equal(p[0][3],[0, 1, 2, 3])
+ assert_equal(p, dict(nx.all_pairs_dijkstra_path(self.cycle)))
p=nx.shortest_path(self.grid,weight='weight')
validate_grid_path(4, 4, 1, 12, p[1][12])
diff --git a/networkx/algorithms/shortest_paths/tests/test_unweighted.py b/networkx/algorithms/shortest_paths/tests/test_unweighted.py
index 570bfe482..0b876c21f 100644
--- a/networkx/algorithms/shortest_paths/tests/test_unweighted.py
+++ b/networkx/algorithms/shortest_paths/tests/test_unweighted.py
@@ -75,9 +75,9 @@ class TestUnweightedPath:
assert_equal(dict(pl(self.directed_cycle, 0)), lengths)
def test_all_pairs_shortest_path(self):
- p=nx.all_pairs_shortest_path(self.cycle)
+ p=dict(nx.all_pairs_shortest_path(self.cycle))
assert_equal(p[0][3],[0,1,2,3])
- p=nx.all_pairs_shortest_path(self.grid)
+ p=dict(nx.all_pairs_shortest_path(self.grid))
validate_grid_path(4, 4, 1, 12, p[1][12])
def test_all_pairs_shortest_path_length(self):
diff --git a/networkx/algorithms/shortest_paths/tests/test_weighted.py b/networkx/algorithms/shortest_paths/tests/test_weighted.py
index 2641521d6..0ba63cc56 100644
--- a/networkx/algorithms/shortest_paths/tests/test_weighted.py
+++ b/networkx/algorithms/shortest_paths/tests/test_weighted.py
@@ -239,6 +239,35 @@ class TestWeightedPath(WeightedTestBase):
assert_equal(distance, 1 / 10)
assert_equal(path, [0, 2])
+ def test_all_pairs_dijkstra_path(self):
+ cycle=nx.cycle_graph(7)
+ p=dict(nx.all_pairs_dijkstra_path(cycle))
+ assert_equal(p[0][3], [0, 1, 2, 3])
+
+ cycle[1][2]['weight'] = 10
+ p=dict(nx.all_pairs_dijkstra_path(cycle))
+ assert_equal(p[0][3], [0, 6, 5, 4, 3])
+
+ def test_all_pairs_dijkstra_path_length(self):
+ cycle=nx.cycle_graph(7)
+ pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
+ assert_equal(pl[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
+
+ cycle[1][2]['weight'] = 10
+ pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
+ assert_equal(pl[0], {0: 0, 1: 1, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1})
+
+ def test_all_pairs_dijkstra(self):
+ cycle=nx.cycle_graph(7)
+ out = dict(nx.all_pairs_dijkstra(cycle))
+ assert_equal(out[0][0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
+ assert_equal(out[0][1][3], [0, 1, 2, 3])
+
+ cycle[1][2]['weight'] = 10
+ out = dict(nx.all_pairs_dijkstra(cycle))
+ assert_equal(out[0][0], {0: 0, 1: 1, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1})
+ assert_equal(out[0][1][3], [0, 6, 5, 4, 3])
+
class TestDijkstraPathLength(object):
"""Unit tests for the :func:`networkx.dijkstra_path_length`
@@ -298,6 +327,13 @@ class TestMultiSourceDijkstra(object):
assert_equal(distances, expected_distances)
assert_equal(paths, expected_paths)
+ def test_simple_paths(self):
+ G = nx.path_graph(4)
+ lengths = nx.multi_source_dijkstra_path_length(G, [0])
+ assert_equal(lengths, {n: n for n in G})
+ paths = nx.multi_source_dijkstra_path(G, [0])
+ assert_equal(paths, {n: list(range(n+1)) for n in G})
+
class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
@@ -305,7 +341,7 @@ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
G = nx.DiGraph()
G.add_node(0)
assert_equal(nx.single_source_bellman_ford_path(G, 0), {0: [0]})
- assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)), {0: 0})
+ assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0})
assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0}, {0: [0]}))
assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: [None]}, {0: 0}))
assert_equal(nx.goldberg_radzik(G, 0), ({0: None}, {0: 0}))
@@ -340,7 +376,7 @@ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
G.add_edge(1, 2, weight=-3)
assert_equal(nx.single_source_bellman_ford_path(G, 0),
{0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4]})
- assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)),
+ assert_equal(nx.single_source_bellman_ford_path_length(G, 0),
{0: 0, 1: 1, 2: -2, 3: -1, 4: 0})
assert_equal(nx.single_source_bellman_ford(G, 0),
({0: 0, 1: 1, 2: -2, 3: -1, 4: 0},
@@ -358,7 +394,7 @@ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
G.add_edge(10, 12)
assert_equal(nx.single_source_bellman_ford_path(G, 0),
{0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]})
- assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)),
+ assert_equal(nx.single_source_bellman_ford_path_length(G, 0),
{0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
assert_equal(nx.single_source_bellman_ford(G, 0),
({0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
@@ -378,7 +414,7 @@ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
('C', 'A', {'load': 2})])
assert_equal(nx.single_source_bellman_ford_path(G, 0, weight='load'),
{0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]})
- assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0, weight='load')),
+ assert_equal(nx.single_source_bellman_ford_path_length(G, 0, weight='load'),
{0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
assert_equal(nx.single_source_bellman_ford(G, 0, weight='load'),
({0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1},
@@ -394,7 +430,7 @@ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
assert_equal(nx.bellman_ford_path(self.MXG, 's', 'v'), ['s', 'x', 'u', 'v'])
assert_equal(nx.bellman_ford_path_length(self.MXG, 's', 'v'), 9)
assert_equal(nx.single_source_bellman_ford_path(self.MXG, 's')['v'], ['s', 'x', 'u', 'v'])
- assert_equal(dict(nx.single_source_bellman_ford_path_length(self.MXG, 's'))['v'], 9)
+ assert_equal(nx.single_source_bellman_ford_path_length(self.MXG, 's')['v'], 9)
D, P = nx.single_source_bellman_ford(self.MXG, 's', target='v')
assert_equal(D, 9)
assert_equal(P, ['s', 'x', 'u', 'v'])
@@ -407,7 +443,7 @@ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
assert_equal(nx.bellman_ford_path(self.MXG4, 0, 2), [0, 1, 2])
assert_equal(nx.bellman_ford_path_length(self.MXG4, 0, 2), 4)
assert_equal(nx.single_source_bellman_ford_path(self.MXG4, 0)[2], [0, 1, 2])
- assert_equal(dict(nx.single_source_bellman_ford_path_length(self.MXG4, 0))[2], 4)
+ assert_equal(nx.single_source_bellman_ford_path_length(self.MXG4, 0)[2], 4)
D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2)
assert_equal(D, 4)
assert_equal(P, [0, 1, 2])
@@ -422,7 +458,7 @@ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
assert_equal(nx.bellman_ford_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v'])
assert_equal(nx.bellman_ford_path_length(self.XG, 's', 'v'), 9)
assert_equal(nx.single_source_bellman_ford_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v'])
- assert_equal(dict(nx.single_source_bellman_ford_path_length(self.XG, 's'))['v'], 9)
+ assert_equal(nx.single_source_bellman_ford_path_length(self.XG, 's')['v'], 9)
D, P = nx.single_source_bellman_ford(self.XG, 's', target='v')
assert_equal(D, 9)
assert_equal(P, ['s', 'x', 'u', 'v'])
@@ -437,7 +473,7 @@ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
G = nx.path_graph(4)
assert_equal(nx.single_source_bellman_ford_path(G, 0),
{0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]})
- assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)),
+ assert_equal(nx.single_source_bellman_ford_path_length(G, 0),
{0: 0, 1: 1, 2: 2, 3: 3})
assert_equal(nx.single_source_bellman_ford(G, 0),
({0: 0, 1: 1, 2: 2, 3: 3}, {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]}))
@@ -447,7 +483,7 @@ class TestBellmanFordAndGoldbergRadzik(WeightedTestBase):
({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3}))
assert_equal(nx.single_source_bellman_ford_path(G, 3),
{0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]})
- assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 3)),
+ assert_equal(nx.single_source_bellman_ford_path_length(G, 3),
{0: 3, 1: 2, 2: 1, 3: 0})
assert_equal(nx.single_source_bellman_ford(G, 3),
({0: 3, 1: 2, 2: 1, 3: 0}, {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]}))
diff --git a/networkx/algorithms/shortest_paths/unweighted.py b/networkx/algorithms/shortest_paths/unweighted.py
index 54410e7ea..0c870c245 100644
--- a/networkx/algorithms/shortest_paths/unweighted.py
+++ b/networkx/algorithms/shortest_paths/unweighted.py
@@ -37,13 +37,13 @@ def single_source_shortest_path_length(G, source, cutoff=None):
Returns
-------
- lengths : iterator
- (target, shortest path length) iterator
+ lengths : dict
+ Dict keyed by node to shortest path length to source.
Examples
--------
>>> G = nx.path_graph(5)
- >>> length = dict(nx.single_source_shortest_path_length(G, 0))
+ >>> length = nx.single_source_shortest_path_length(G, 0)
>>> length[4]
4
>>> for node in length:
@@ -63,7 +63,7 @@ def single_source_shortest_path_length(G, source, cutoff=None):
if cutoff is None:
cutoff = float('inf')
nextlevel = {source: 1}
- return _single_shortest_path_length(G.adj, nextlevel, cutoff)
+ return dict(_single_shortest_path_length(G.adj, nextlevel, cutoff))
def _single_shortest_path_length(adj, firstlevel, cutoff):
@@ -183,7 +183,7 @@ def all_pairs_shortest_path_length(G, cutoff=None):
length = single_source_shortest_path_length
# TODO This can be trivially parallelized.
for n in G:
- yield (n, dict(length(G, n, cutoff=cutoff)))
+ yield (n, length(G, n, cutoff=cutoff))
def bidirectional_shortest_path(G, source, target):
@@ -340,7 +340,7 @@ def single_source_shortest_path(G, source, cutoff=None):
cutoff = float('inf')
nextlevel = {source: 1} # list of nodes to check at next level
paths = {source: [source]} # paths dictionary (paths to key from source)
- return _single_shortest_path(G.adj, nextlevel, paths, cutoff, join)
+ return dict(_single_shortest_path(G.adj, nextlevel, paths, cutoff, join))
def _single_shortest_path(adj, firstlevel, paths, cutoff, join):
@@ -423,7 +423,7 @@ def single_target_shortest_path(G, target, cutoff=None):
cutoff = float('inf')
nextlevel = {target: 1} # list of nodes to check at next level
paths = {target: [target]} # paths dictionary (paths to key from source)
- return _single_shortest_path(adj, nextlevel, paths, cutoff, join)
+ return dict(_single_shortest_path(adj, nextlevel, paths, cutoff, join))
def all_pairs_shortest_path(G, cutoff=None):
@@ -445,7 +445,7 @@ def all_pairs_shortest_path(G, cutoff=None):
Examples
--------
>>> G = nx.path_graph(5)
- >>> path = nx.all_pairs_shortest_path(G)
+ >>> path = dict(nx.all_pairs_shortest_path(G))
>>> print(path[0][4])
[0, 1, 2, 3, 4]
@@ -455,7 +455,8 @@ def all_pairs_shortest_path(G, cutoff=None):
"""
# TODO This can be trivially parallelized.
- return {n: single_source_shortest_path(G, n, cutoff=cutoff) for n in G}
+ for n in G:
+ yield (n, single_source_shortest_path(G, n, cutoff=cutoff))
def predecessor(G, source, target=None, cutoff=None, return_seen=None):
diff --git a/networkx/algorithms/shortest_paths/weighted.py b/networkx/algorithms/shortest_paths/weighted.py
index a597bbdb4..caa5e85c7 100644
--- a/networkx/algorithms/shortest_paths/weighted.py
+++ b/networkx/algorithms/shortest_paths/weighted.py
@@ -31,6 +31,7 @@ __all__ = ['dijkstra_path',
'multi_source_dijkstra',
'multi_source_dijkstra_path',
'multi_source_dijkstra_path_length',
+ 'all_pairs_dijkstra',
'all_pairs_dijkstra_path',
'all_pairs_dijkstra_path_length',
'dijkstra_predecessor_and_distance',
@@ -323,13 +324,13 @@ def single_source_dijkstra_path_length(G, source, cutoff=None,
Returns
-------
- length : iterator
- (target, shortest path length) iterator
+ length : dict
+ Dict keyed by node to shortest path length from source.
Examples
--------
>>> G = nx.path_graph(5)
- >>> length = dict(nx.single_source_dijkstra_path_length(G, 0))
+ >>> length = nx.single_source_dijkstra_path_length(G, 0)
>>> length[4]
4
>>> for node in [0, 1, 2, 3, 4]:
@@ -396,11 +397,12 @@ def single_source_dijkstra(G, source, target=None, cutoff=None,
Returns
-------
- distance, path : pair of dictionaries, or numeric and list
- If target is None, returns a tuple of two dictionaries keyed by node.
- The first dictionary stores distance from one of the source nodes.
- The second stores the path from one of the sources to that node.
- If target is not None, returns a tuple of (distance, path) where
+ distance, path : pair of dictionaries, or numeric and list.
+ If target is None, paths and lengths to all nodes are computed.
+ The return value is a tuple of two dictionaries keyed by target nodes.
+ The first dictionary stores distance to each target node.
+ The second stores the path to each target node.
+ If target is not None, returns a tuple (distance, path), where
distance is the distance from source to target and path is a list
representing the path from source to target.
@@ -559,13 +561,13 @@ def multi_source_dijkstra_path_length(G, sources, cutoff=None,
Returns
-------
- length : iterator
- (target, shortest path length) iterator
+ length : dict
+ Dict keyed by node to shortest path length to nearest source.
Examples
--------
>>> G = nx.path_graph(5)
- >>> length = dict(nx.multi_source_dijkstra_path_length(G, {0, 4}))
+ >>> length = nx.multi_source_dijkstra_path_length(G, {0, 4})
>>> for node in [0, 1, 2, 3, 4]:
... print('{}: {}'.format(node, length[node]))
0: 0
@@ -596,9 +598,7 @@ def multi_source_dijkstra_path_length(G, sources, cutoff=None,
if not sources:
raise ValueError('sources must not be empty')
weight = _weight_function(G, weight)
- dist = _dijkstra_multisource(G, sources, weight, cutoff=cutoff)
- # TODO In Python 3.3+, this should be `yield from dist.items()`.
- return iter(dist.items())
+ return _dijkstra_multisource(G, sources, weight, cutoff=cutoff)
def multi_source_dijkstra(G, sources, target=None, cutoff=None,
@@ -889,6 +889,73 @@ def dijkstra_predecessor_and_distance(G, source, cutoff=None, weight='weight'):
return (pred, _dijkstra(G, source, weight, pred=pred, cutoff=cutoff))
+def all_pairs_dijkstra(G, cutoff=None, weight='weight'):
+ """Find shortest weighted paths and lengths between all nodes.
+
+ Parameters
+ ----------
+ G : NetworkX graph
+
+ cutoff : integer or float, optional
+ Depth to stop the search. Only return paths with length <= cutoff.
+
+ weight : string or function
+ If this is a string, then edge weights will be accessed via the
+ edge attribute with this key (that is, the weight of the edge
+ joining `u` to `v` will be ``G.edge[u][v][weight]``). If no
+ such edge attribute exists, the weight of the edge is assumed to
+ be one.
+
+ If this is a function, the weight of an edge is the value
+ returned by the function. The function must accept exactly three
+ positional arguments: the two endpoints of an edge and the
+ dictionary of edge attributes for that edge. The function must
+ return a number.
+
+ Yields
+ ------
+ (node, (distance, path)) : (node obj, (dict, dict))
+ Each source node has two associated dicts. The first holds distance
+ keyed by target and the second holds paths keyed by target.
+ (See single_source_dijkstra for the source/target node terminology.)
+ If desired you can apply `dict()` to this function to create a dict
+ keyed by source node to the two dicts.
+
+ Examples
+ --------
+ >>> G = nx.path_graph(5)
+ >>> len_path = dict(nx.all_pairs_dijkstra(G))
+ >>> print(len_path[3][0][1])
+ 2
+ >>> for node in [0, 1, 2, 3, 4]:
+ ... print('3 - {}: {}'.format(node, len_path[3][0][node]))
+ 3 - 0: 3
+ 3 - 1: 2
+ 3 - 2: 1
+ 3 - 3: 0
+ 3 - 4: 1
+ >>> len_path[3][1][1]
+ [3, 2, 1]
+ >>> for n, (dist, path) in nx.all_pairs_dijkstra(G):
+ ... print(path[1])
+ [0, 1]
+ [1]
+ [2, 1]
+ [3, 2, 1]
+ [4, 3, 2, 1]
+
+ Notes
+ -----
+ Edge weight attributes must be numerical.
+ Distances are calculated as sums of weighted edges traversed.
+
+ The yielded dicts only have keys for reachable nodes.
+ """
+ for n in G:
+ dist, path = single_source_dijkstra(G, n, cutoff=cutoff, weight=weight)
+ yield (n, (dist, path))
+
+
def all_pairs_dijkstra_path_length(G, cutoff=None, weight='weight'):
"""Compute shortest path lengths between all nodes in a weighted graph.
@@ -943,7 +1010,7 @@ def all_pairs_dijkstra_path_length(G, cutoff=None, weight='weight'):
"""
length = single_source_dijkstra_path_length
for n in G:
- yield (n, dict(length(G, n, cutoff=cutoff, weight=weight)))
+ yield (n, length(G, n, cutoff=cutoff, weight=weight))
def all_pairs_dijkstra_path(G, cutoff=None, weight='weight'):
@@ -976,8 +1043,8 @@ def all_pairs_dijkstra_path(G, cutoff=None, weight='weight'):
Examples
--------
- >>> G=nx.path_graph(5)
- >>> path=nx.all_pairs_dijkstra_path(G)
+ >>> G = nx.path_graph(5)
+ >>> path = dict(nx.all_pairs_dijkstra_path(G))
>>> print(path[0][4])
[0, 1, 2, 3, 4]
@@ -993,7 +1060,8 @@ def all_pairs_dijkstra_path(G, cutoff=None, weight='weight'):
"""
path = single_source_dijkstra_path
# TODO This can be trivially parallelized.
- return {n: path(G, n, cutoff=cutoff, weight=weight) for n in G}
+ for n in G:
+ yield (n, path(G, n, cutoff=cutoff, weight=weight))
def bellman_ford(G, source, weight='weight'):
@@ -1416,8 +1484,7 @@ def single_source_bellman_ford_path_length(G, source,
"""
weight = _weight_function(G, weight)
-
- return iter(_bellman_ford(G, [source], weight, cutoff=cutoff).items())
+ return _bellman_ford(G, [source], weight, cutoff=cutoff)
def single_source_bellman_ford(G, source,
@@ -1566,8 +1633,8 @@ def all_pairs_bellman_ford_path(G, cutoff=None, weight='weight'):
Examples
--------
- >>> G=nx.path_graph(5)
- >>> path=nx.all_pairs_bellman_ford_path(G)
+ >>> G = nx.path_graph(5)
+ >>> path = dict(nx.all_pairs_bellman_ford_path(G))
>>> print(path[0][4])
[0, 1, 2, 3, 4]
@@ -1583,7 +1650,8 @@ def all_pairs_bellman_ford_path(G, cutoff=None, weight='weight'):
"""
path = single_source_bellman_ford_path
# TODO This can be trivially parallelized.
- return {n: path(G, n, cutoff=cutoff, weight=weight) for n in G}
+ for n in G:
+ yield (n, path(G, n, cutoff=cutoff, weight=weight))
def goldberg_radzik(G, source, weight='weight'):
diff --git a/networkx/algorithms/tests/test_efficiency.py b/networkx/algorithms/tests/test_efficiency.py
index 989f8eed5..ba501d1b2 100644
--- a/networkx/algorithms/tests/test_efficiency.py
+++ b/networkx/algorithms/tests/test_efficiency.py
@@ -1,54 +1,68 @@
# test_efficiency.py - unit tests for the efficiency module
#
-# Copyright 2015 NetworkX developers.
+# Copyright 2015-2017 NetworkX developers.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
"""Unit tests for the :mod:`networkx.algorithms.efficiency` module."""
+
from __future__ import division
from unittest import TestCase
-
from nose.tools import assert_equal
-
import networkx as nx
-def test_efficiency():
- G = nx.cycle_graph(4)
- assert_equal(nx.efficiency(G, 0, 1), 1)
- assert_equal(nx.efficiency(G, 0, 2), 1 / 2)
-
+class TestEfficiency:
-def test_global_efficiency():
- G = nx.cycle_graph(4)
- assert_equal(nx.global_efficiency(G), 5 / 6)
+ def __init__(self):
+ # G1 is a disconnected graph
+ self.G1 = nx.Graph()
+ self.G1.add_nodes_from([1, 2, 3])
+ # G2 is a cycle graph
+ self.G2 = nx.cycle_graph(4)
+ # G3 is the triangle graph with one additional edge
+ self.G3 = nx.lollipop_graph(3, 1)
+ def test_efficiency_disconnected_nodes(self):
+ """
+ When nodes are disconnected, efficiency is 0
+ """
+ assert_equal(nx.efficiency(self.G1, 1, 2), 0)
-def test_complete_graph_global_efficiency():
- """Tests that the average global efficiency of the complete graph is
- one.
+ def test_local_efficiency_disconnected_graph(self):
+ """
+ In a disconnected graph the efficiency is 0
+ """
+ assert_equal(nx.local_efficiency(self.G1), 0)
- """
- for n in range(10):
- G = nx.complete_graph(5)
- assert_equal(nx.global_efficiency(G), 1)
+ def test_efficiency(self):
+ assert_equal(nx.efficiency(self.G2, 0, 1), 1)
+ assert_equal(nx.efficiency(self.G2, 0, 2), 1 / 2)
+ def test_global_efficiency(self):
+ assert_equal(nx.global_efficiency(self.G2), 5 / 6)
-class TestLocalEfficiency(TestCase):
- """Unit tests for the local efficiency function."""
+ def test_global_efficiency_complete_graph(self):
+ """
+ Tests that the average global efficiency of the complete graph is one.
+ """
+ for n in range(2, 10):
+ G = nx.complete_graph(n)
+ assert_equal(nx.global_efficiency(G), 1)
- def test_complete_graph(self):
- G = nx.complete_graph(4)
- assert_equal(nx.local_efficiency(G), 1)
+ def test_local_efficiency_complete_graph(self):
+ """
+ Test that the local efficiency for a complete graph should be one.
+ """
+ for n in range(2, 10):
+ G = nx.complete_graph(n)
+ assert_equal(nx.local_efficiency(G), 1)
def test_using_ego_graph(self):
- """Test that the ego graph is used when computing local efficiency.
-
+ """
+ Test that the ego graph is used when computing local efficiency.
For more information, see GitHub issue #2233.
-
"""
- # This is the triangle graph with one additional edge.
- G = nx.lollipop_graph(3, 1)
- assert_equal(nx.local_efficiency(G), 23 / 24)
+ assert_equal(nx.local_efficiency(self.G3), 23 / 24)
diff --git a/networkx/algorithms/tests/test_lowest_common_ancestors.py b/networkx/algorithms/tests/test_lowest_common_ancestors.py
index 5160a4aca..3d984b3bf 100644
--- a/networkx/algorithms/tests/test_lowest_common_ancestors.py
+++ b/networkx/algorithms/tests/test_lowest_common_ancestors.py
@@ -162,7 +162,7 @@ class TestDAGLCA:
self.DG.add_edge(6, 2)
self.DG.add_edge(7, 2)
- self.root_distance = dict(nx.shortest_path_length(self.DG, source=0))
+ self.root_distance = nx.shortest_path_length(self.DG, source=0)
self.gold = {(1, 1): 1,
(1, 2): 1,
@@ -212,7 +212,7 @@ class TestDAGLCA:
else:
roots = [n for n, deg in G.in_degree if deg == 0]
assert(len(roots) == 1)
- root_distance = dict(nx.shortest_path_length(G, source=roots[0]))
+ root_distance = nx.shortest_path_length(G, source=roots[0])
for a, b in ((min(pair), max(pair)) for pair in chain(d1, d2)):
assert_equal(root_distance[get_pair(d1, a, b)],
diff --git a/networkx/algorithms/tests/test_threshold.py b/networkx/algorithms/tests/test_threshold.py
index 8562d8ec2..cc76d7cc0 100644
--- a/networkx/algorithms/tests/test_threshold.py
+++ b/networkx/algorithms/tests/test_threshold.py
@@ -69,7 +69,7 @@ class TestGeneratorThreshold():
for j,pl in enumerate(spl):
n=cs1[j][0]
spld[n]=pl
- assert_equal(spld, dict(nx.single_source_shortest_path_length(G, 3)))
+ assert_equal(spld, nx.single_source_shortest_path_length(G, 3))
def test_weights_thresholds(self):
wseq=[3,4,3,3,5,6,5,4,5,6]
| {
"commit_name": "merge_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": 3
},
"num_modified_files": 9
} | help | {
"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
charset-normalizer==2.0.12
codecov==2.1.13
coverage==6.2
decorator==5.1.1
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
-e git+https://github.com/networkx/networkx.git@3f4fd85765bf2d88188cfd4c84d0707152e6cd1e#egg=networkx
nose==1.3.7
nose-ignore-docstring==0.2
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
requests==2.27.1
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
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
- charset-normalizer==2.0.12
- codecov==2.1.13
- coverage==6.2
- decorator==5.1.1
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- nose==1.3.7
- nose-ignore-docstring==0.2
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- 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/networkx
| [
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_all_pairs_lowest_common_ancestor9",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_lowest_common_ancestor1",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_lowest_common_ancestor2"
]
| [
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_shortest_path",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_shortest_path_length",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_single_source_shortest_path",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_single_source_shortest_path_length",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_all_pairs_shortest_path",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_all_pairs_shortest_path_length",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_bidirectional_shortest_path",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_shortest_path_length",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_single_source_shortest_path",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_single_source_shortest_path_length",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_single_target_shortest_path",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_single_target_shortest_path_length",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_all_pairs_shortest_path",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_all_pairs_shortest_path_length",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor1",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor2",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor3",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor4",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor5",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor6",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor9",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor10",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor11",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_all_pairs_lowest_common_ancestor1",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_all_pairs_lowest_common_ancestor2",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_all_pairs_lowest_common_ancestor3",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_all_pairs_lowest_common_ancestor4",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_all_pairs_lowest_common_ancestor5",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_all_pairs_lowest_common_ancestor6",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_all_pairs_lowest_common_ancestor10"
]
| [
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_shortest_path_target",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_shortest_path_length_target",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_has_path",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_all_shortest_paths",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestGenericPath::test_all_shortest_paths_raise",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestAverageShortestPathLength::test_cycle_graph",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestAverageShortestPathLength::test_path_graph",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestAverageShortestPathLength::test_weighted",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestAverageShortestPathLength::test_disconnected",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestAverageShortestPathLength::test_trivial_graph",
"networkx/algorithms/shortest_paths/tests/test_generic.py::TestAverageShortestPathLength::test_null_graph",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_predecessor_path",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_predecessor_cycle",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_predecessor_cutoff",
"networkx/algorithms/shortest_paths/tests/test_unweighted.py::TestUnweightedPath::test_predecessor_target",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_dijkstra",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_bidirectional_dijkstra",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_bidirectional_dijkstra_no_path",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_dijkstra_predecessor1",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_dijkstra_predecessor2",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_dijkstra_predecessor3",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_single_source_dijkstra_path_length",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_bidirectional_dijkstra_multigraph",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_dijkstra_pred_distance_multigraph",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_negative_edge_cycle",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_weight_function",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_all_pairs_dijkstra_path",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_all_pairs_dijkstra_path_length",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestWeightedPath::test_all_pairs_dijkstra",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestDijkstraPathLength::test_weight_function",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestMultiSourceDijkstra::test_no_sources",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestMultiSourceDijkstra::test_path_no_sources",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestMultiSourceDijkstra::test_path_length_no_sources",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestMultiSourceDijkstra::test_two_sources",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestMultiSourceDijkstra::test_simple_paths",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestBellmanFordAndGoldbergRadzik::test_single_node_graph",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestBellmanFordAndGoldbergRadzik::test_negative_weight_cycle",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestBellmanFordAndGoldbergRadzik::test_not_connected",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestBellmanFordAndGoldbergRadzik::test_multigraph",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestBellmanFordAndGoldbergRadzik::test_others",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestBellmanFordAndGoldbergRadzik::test_path_graph",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestBellmanFordAndGoldbergRadzik::test_4_cycle",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestJohnsonAlgorithm::test_single_node_graph",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestJohnsonAlgorithm::test_negative_cycle",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestJohnsonAlgorithm::test_negative_weights",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestJohnsonAlgorithm::test_unweighted_graph",
"networkx/algorithms/shortest_paths/tests/test_weighted.py::TestJohnsonAlgorithm::test_graphs",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor7",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor8",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor12",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_not_implemented_for",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestTreeLCA::test_tree_all_pairs_lowest_common_ancestor13",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_all_pairs_lowest_common_ancestor7",
"networkx/algorithms/tests/test_lowest_common_ancestors.py::TestDAGLCA::test_all_pairs_lowest_common_ancestor8",
"networkx/algorithms/tests/test_threshold.py::TestGeneratorThreshold::test_threshold_sequence_graph_test",
"networkx/algorithms/tests/test_threshold.py::TestGeneratorThreshold::test_creation_sequences",
"networkx/algorithms/tests/test_threshold.py::TestGeneratorThreshold::test_shortest_path",
"networkx/algorithms/tests/test_threshold.py::TestGeneratorThreshold::test_weights_thresholds",
"networkx/algorithms/tests/test_threshold.py::TestGeneratorThreshold::test_finding_routines",
"networkx/algorithms/tests/test_threshold.py::TestGeneratorThreshold::test_fast_versions_properties_threshold_graphs",
"networkx/algorithms/tests/test_threshold.py::TestGeneratorThreshold::test_tg_creation_routines",
"networkx/algorithms/tests/test_threshold.py::TestGeneratorThreshold::test_create_using"
]
| []
| BSD 3-Clause | 1,593 | [
"networkx/release.py",
"doc/release/migration_guide_from_1.x_to_2.0.rst",
"networkx/algorithms/dag.py",
"networkx/algorithms/centrality/harmonic.py",
"networkx/algorithms/efficiency.py",
"doc/release/release_dev.rst",
"networkx/drawing/nx_pylab.py",
"networkx/algorithms/distance_measures.py",
"networkx/algorithms/connectivity/stoerwagner.py"
]
| [
"networkx/release.py",
"doc/release/migration_guide_from_1.x_to_2.0.rst",
"networkx/algorithms/dag.py",
"networkx/algorithms/centrality/harmonic.py",
"networkx/algorithms/efficiency.py",
"doc/release/release_dev.rst",
"networkx/drawing/nx_pylab.py",
"networkx/algorithms/distance_measures.py",
"networkx/algorithms/connectivity/stoerwagner.py"
]
|
|
poliastro__poliastro-212 | 8cbb3018fb97748a6d66cc4d910657afeb31b7fd | 2017-08-16 16:04:40 | a53526d86e99ce144acab8a8edf9cf3e64b11625 | diff --git a/.travis.yml b/.travis.yml
index fd235711..769e58c4 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -12,6 +12,9 @@ branches:
- 0.5.x
- 0.6.x
+env:
+ - MPLBACKEND="Agg"
+
matrix:
include:
- os: osx
@@ -34,12 +37,17 @@ before_install:
install:
- pip install numpy # Required
- - pip install . # Test installation correctness
+ - pip install pep8 mypy
- pip install sphinx sphinx_rtd_theme nbsphinx ipython # Install documentation dependencies
+ - pip install . # Test installation correctness
+
+before_script:
+ - pep8 setup.py src/ # Check PEP8 compliance
+ - mypy --ignore-missing-imports --check-untyped-defs src/ # Check MyPy diagnostics
script:
- python setup.py test -vv # Test against installed code
- - sphinx-build -vW -b html docs/source _HTMLTest #Test docs build
+ - sphinx-build -vW -b html docs/source _HTMLTest # Test docs build
after_success:
# Uninstall to test coverage against sources
diff --git a/setup.cfg b/setup.cfg
index 0e1fa302..06b96ece 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -6,3 +6,7 @@ norecursedirs =
python_files =
test_*.py
doctest_plus = disabled
+
+[pep8]
+ignore = E731
+max-line-length = 120
diff --git a/setup.py b/setup.py
index 20ff6ca8..a17e69c4 100644
--- a/setup.py
+++ b/setup.py
@@ -40,8 +40,8 @@ setup(
download_url="https://github.com/poliastro/poliastro",
license="MIT",
keywords=[
- "aero", "aerospace", "engineering",
- "astrodynamics", "orbits", "kepler", "orbital mechanics"
+ "aero", "aerospace", "engineering",
+ "astrodynamics", "orbits", "kepler", "orbital mechanics"
],
python_requires=">=3.5",
install_requires=[
@@ -64,24 +64,24 @@ setup(
packages=find_packages('src'),
package_dir={'': 'src'},
entry_points={
- 'console_scripts': [
- 'poliastro = poliastro.cli:main'
- ]
+ 'console_scripts': [
+ 'poliastro = poliastro.cli:main'
+ ]
},
classifiers=[
- "Development Status :: 4 - Beta",
- "Intended Audience :: Education",
- "Intended Audience :: Science/Research",
- "License :: OSI Approved :: MIT License",
- "Operating System :: OS Independent",
- "Programming Language :: Python",
- "Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.5",
- "Programming Language :: Python :: 3.6",
- "Programming Language :: Python :: Implementation :: CPython",
- "Topic :: Scientific/Engineering",
- "Topic :: Scientific/Engineering :: Physics",
- "Topic :: Scientific/Engineering :: Astronomy",
+ "Development Status :: 4 - Beta",
+ "Intended Audience :: Education",
+ "Intended Audience :: Science/Research",
+ "License :: OSI Approved :: MIT License",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.5",
+ "Programming Language :: Python :: 3.6",
+ "Programming Language :: Python :: Implementation :: CPython",
+ "Topic :: Scientific/Engineering",
+ "Topic :: Scientific/Engineering :: Physics",
+ "Topic :: Scientific/Engineering :: Astronomy",
],
long_description=io.open('README.rst', encoding='utf-8').read(),
package_data={"poliastro": ['tests/*.py']},
diff --git a/src/poliastro/cli.py b/src/poliastro/cli.py
index 03b66b96..ce09ab62 100644
--- a/src/poliastro/cli.py
+++ b/src/poliastro/cli.py
@@ -14,21 +14,12 @@ def main():
description="Command line tools for the poliastro Python library.")
parser.add_argument("--version", action='version',
version=poliastro.__version__)
-
- subparsers = parser.add_subparsers(help='Available commands')
-
- download_parser = subparsers.add_parser(
- "download-dastcom5",
- help="Downloads DASTCOM5 database")
- download_parser.add_argument(
- "-p", "--path", help="Download path")
+ parser.add_argument("--download-dastcom5", action="store_true",
+ help="Downloads DASTCOM5 database")
args = parser.parse_args()
- try:
- if args.path:
- download_dastcom5(args.path)
- else:
- download_dastcom5()
- except AttributeError:
- parser.print_help()
+ if args.download_dastcom5:
+ download_dastcom5()
+ else:
+ parser.print_help()
diff --git a/src/poliastro/maneuver.py b/src/poliastro/maneuver.py
index 95bf6436..8340bf50 100644
--- a/src/poliastro/maneuver.py
+++ b/src/poliastro/maneuver.py
@@ -93,7 +93,7 @@ class Maneuver(object):
Rs = r_b / r_i
dv_a = ((np.sqrt(2 * Rs / (1 + Rs)) - 1) * v_i).decompose()
dv_b = (-np.sqrt(2 / Rs) * (np.sqrt(1 / (1 + Rs / R)) -
- np.sqrt(1 / (1 + Rs))) * v_i).decompose()
+ np.sqrt(1 / (1 + Rs))) * v_i).decompose()
dv_c = (-(np.sqrt(2 * Rs / (R + Rs)) - 1) / np.sqrt(R) * v_i).decompose()
t_trans1 = (np.pi * np.sqrt((r_i * (1 + Rs) / 2) ** 3 / k)).decompose()
t_trans2 = (np.pi * np.sqrt((r_i * (R + Rs) / 2) ** 3 / k)).decompose()
diff --git a/src/poliastro/neos/dastcom5.py b/src/poliastro/neos/dastcom5.py
index 701dc367..b50d1bfc 100644
--- a/src/poliastro/neos/dastcom5.py
+++ b/src/poliastro/neos/dastcom5.py
@@ -506,8 +506,8 @@ def download_dastcom5():
def _show_download_progress(transferred, block, totalsize):
- trans_mb = transferred*block/(1024*1024)
- total_mb = totalsize/(1024*1024)
+ trans_mb = transferred * block / (1024 * 1024)
+ total_mb = totalsize / (1024 * 1024)
print('%.2f MB / %.2f MB' % (trans_mb, total_mb), end='\r', flush=True)
@@ -526,13 +526,13 @@ def entire_db():
ast_database = asteroid_db()
com_database = comet_db()
- ast_database = pd.DataFrame(ast_database[list(ast_database.dtype.names[:17])
- + list(ast_database.dtype.names[-4:-3])
- + list(ast_database.dtype.names[-2:])])
+ ast_database = pd.DataFrame(ast_database[list(ast_database.dtype.names[:17]) +
+ list(ast_database.dtype.names[-4:-3]) +
+ list(ast_database.dtype.names[-2:])])
ast_database.rename(columns={'ASTNAM': 'NAME', 'NO': 'NUMBER', 'CALEPO': 'CALEPOCH'}, inplace=True)
- com_database = pd.DataFrame(com_database[list(com_database.dtype.names[:17])
- + list(com_database.dtype.names[-4:-3])
- + list(com_database.dtype.names[-2:])])
+ com_database = pd.DataFrame(com_database[list(com_database.dtype.names[:17]) +
+ list(com_database.dtype.names[-4:-3]) +
+ list(com_database.dtype.names[-2:])])
com_database.rename(columns={'COMNAM': 'NAME', 'NO': 'NUMBER', 'CALEPO': 'CALEPOCH'}, inplace=True)
df = ast_database.append(com_database, ignore_index=True)
df[['NAME', 'DESIG', 'IREF']] = df[['NAME', 'DESIG', 'IREF']].apply(lambda x: x.str.strip().str.decode('utf-8'))
diff --git a/src/poliastro/neos/neows.py b/src/poliastro/neos/neows.py
index 25b2d265..0c551ca9 100644
--- a/src/poliastro/neos/neows.py
+++ b/src/poliastro/neos/neows.py
@@ -37,7 +37,7 @@ def orbit_from_spk_id(spk_id):
NEA orbit.
"""
- payload = {'api_key' : 'DEMO_KEY'}
+ payload = {'api_key': 'DEMO_KEY'}
response = requests.get(NEOWS_URL + spk_id, params=payload)
response.raise_for_status()
@@ -55,7 +55,7 @@ def orbit_from_spk_id(spk_id):
epoch = Time(orbital_data['orbit_determination_date'])
return Orbit.from_classical(attractor, a, ecc, inc,
- raan, argp, nu, epoch)
+ raan, argp, nu, epoch)
def spk_id_from_name(name):
@@ -102,8 +102,8 @@ def spk_id_from_name(name):
bodies += body.string + '\n'
raise ValueError(str(len(object_list)) + ' different bodies found:\n' + bodies)
else:
- raise ValueError('Object could not be found. You can visit: '
- + SBDB_URL + '?sstr=' + name + ' for more information.')
+ raise ValueError('Object could not be found. You can visit: ' +
+ SBDB_URL + '?sstr=' + name + ' for more information.')
def orbit_from_name(name):
diff --git a/src/poliastro/plotting.py b/src/poliastro/plotting.py
index 6e02b4cf..1472b294 100644
--- a/src/poliastro/plotting.py
+++ b/src/poliastro/plotting.py
@@ -2,7 +2,6 @@
""" Plotting utilities.
"""
-
import numpy as np
import matplotlib as mpl
@@ -58,7 +57,6 @@ class OrbitPlotter(object):
_, self.ax = plt.subplots(figsize=(6, 6))
self.num_points = num_points
self._frame = None
- self._states = []
self._attractor_radius = None
def set_frame(self, p_vec, q_vec, w_vec):
@@ -119,8 +117,6 @@ class OrbitPlotter(object):
elif new_radius < self._attractor_radius:
self.set_attractor(orbit)
- self._states.append(orbit)
-
lines = []
nu_vals = self._generate_vals(orbit.state)
diff --git a/src/poliastro/twobody/classical.py b/src/poliastro/twobody/classical.py
index 7e661a76..b01fa9a9 100644
--- a/src/poliastro/twobody/classical.py
+++ b/src/poliastro/twobody/classical.py
@@ -151,8 +151,8 @@ class ClassicalState(BaseState):
self.nu.to(u.rad).value)
return poliastro.twobody.rv.RVState(self.attractor,
- r * u.km,
- v * u.km / u.s)
+ r * u.km,
+ v * u.km / u.s)
def to_classical(self):
"""Converts to classical orbital elements representation.
diff --git a/src/poliastro/twobody/decorators.py b/src/poliastro/twobody/decorators.py
index 87c6a956..0782dd76 100644
--- a/src/poliastro/twobody/decorators.py
+++ b/src/poliastro/twobody/decorators.py
@@ -18,7 +18,7 @@ def state_from_vector(func):
@wraps(func)
def wrapper(t, u_, k, *args, **kwargs):
r, v = u_[:3], u_[3:]
- ss = RVState(Body(k * u.km3s2), r * u.km, v * u.kms)
+ ss = RVState(Body(None, k * u.km3s2, "_Dummy"), r * u.km, v * u.kms)
return func(t, ss, *args, **kwargs)
diff --git a/src/poliastro/twobody/orbit.py b/src/poliastro/twobody/orbit.py
index d76b6dc8..2143823f 100644
--- a/src/poliastro/twobody/orbit.py
+++ b/src/poliastro/twobody/orbit.py
@@ -183,10 +183,10 @@ class Orbit(object):
k = attractor.k.to(u.km ** 3 / u.s ** 2)
ecc = 1.0 * u.one
r, v = poliastro.twobody.classical.coe2rv(
- k.to(u.km ** 3 / u.s ** 2).value,
- p.to(u.km).value, ecc.value, inc.to(u.rad).value,
- raan.to(u.rad).value, argp.to(u.rad).value,
- nu.to(u.rad).value)
+ k.to(u.km ** 3 / u.s ** 2).value,
+ p.to(u.km).value, ecc.value, inc.to(u.rad).value,
+ raan.to(u.rad).value, argp.to(u.rad).value,
+ nu.to(u.rad).value)
ss = cls.from_vectors(attractor, r * u.km, v * u.km / u.s, epoch)
return ss
diff --git a/src/poliastro/twobody/rv.py b/src/poliastro/twobody/rv.py
index bbb83259..c9f3e50e 100644
--- a/src/poliastro/twobody/rv.py
+++ b/src/poliastro/twobody/rv.py
@@ -99,10 +99,11 @@ class RVState(BaseState):
a = p / (1 - ecc**2)
- return poliastro.twobody.classical.ClassicalState(self.attractor,
- a * u.km,
- ecc * u.one,
- inc * u.rad,
- raan * u.rad,
- argp * u.rad,
- nu * u.rad)
+ return poliastro.twobody.classical.ClassicalState(
+ self.attractor,
+ a * u.km,
+ ecc * u.one,
+ inc * u.rad,
+ raan * u.rad,
+ argp * u.rad,
+ nu * u.rad)
| Try to compile with MyPy
"Mypy is an experimental optional static type checker for Python that aims to combine the benefits of dynamic (or "duck") typing and static typing". A new version is out:
http://mypy-lang.blogspot.com.es/2017/05/mypy-0510-released.html
The first question is: does this make any sense? The only way to find out is to try it at least once and decide.
Adding stubs might be needed to improve editor type hints and catch bugs:
https://www.caktusgroup.com/blog/2017/02/22/python-type-annotations/
For external libraries, there's `typeshed` but it includes none of our core dependencies:
https://github.com/python/typeshed
Though this might be a good starting point
https://github.com/machinalis/mypy-data
This is a very, very good article on good practices:
http://blog.zulip.org/2016/10/13/static-types-in-python-oh-mypy/
Ideally this would also be integrated in continuous integration, though I don't know how. | poliastro/poliastro | diff --git a/src/poliastro/neos/tests/test_dastcom5.py b/src/poliastro/neos/tests/test_dastcom5.py
index 0de46e1a..f94a7f52 100644
--- a/src/poliastro/neos/tests/test_dastcom5.py
+++ b/src/poliastro/neos/tests/test_dastcom5.py
@@ -32,7 +32,6 @@ def test_orbit_from_name(mock_record_from_name, mock_orbit_from_record):
mock_record_from_name.assert_called_with(name)
-
@mock.patch('poliastro.neos.dastcom5.orbit_from_record')
@mock.patch('poliastro.neos.dastcom5.record_from_name')
def test_record_from_name(mock_record_from_name, mock_orbit_from_record):
@@ -56,14 +55,15 @@ def test_read_headers(mock_open, mock_np_fromfile):
@mock.patch('poliastro.neos.dastcom5.np.fromfile')
@mock.patch('poliastro.neos.dastcom5.open')
def test_read_record(mock_open, mock_np_fromfile, mock_read_headers):
- mocked_ast_headers = np.array([(3184, -1, b'00740473', b'00496815')],
- dtype=[('IBIAS1', np.int32), ('IBIAS0', np.int32), ('ENDPT2', '|S8'), ('ENDPT1', '|S8')])
- mocked_com_headers = np.array([(99999,)], dtype=[('IBIAS2', '<i4')])
+ mocked_ast_headers = np.array(
+ [(3184, -1, b'00740473', b'00496815')],
+ dtype=[('IBIAS1', np.int32), ('IBIAS0', np.int32), ('ENDPT2', '|S8'), ('ENDPT1', '|S8')])
+ mocked_com_headers = np.array([(99999,)], dtype=[('IBIAS2', '<i4')])
mock_read_headers.return_value = mocked_ast_headers, mocked_com_headers
dastcom5.read_record(740473)
mock_open.assert_called_with(os.path.join(dastcom5.DBS_LOCAL_PATH, 'dast5_le.dat'), 'rb')
- dastcom5.read_record(740473+1)
+ dastcom5.read_record(740473 + 1)
mock_open.assert_called_with(os.path.join(dastcom5.DBS_LOCAL_PATH, 'dcom5_le.dat'), 'rb')
@@ -72,7 +72,7 @@ def test_read_record(mock_open, mock_np_fromfile, mock_read_headers):
@mock.patch('poliastro.neos.dastcom5.os.path.isdir')
@mock.patch('poliastro.neos.dastcom5.urllib.request')
def test_download_dastcom5_raises_error_when_folder_exists(mock_request, mock_isdir, mock_zipfile, mock_makedirs):
- mock_isdir.side_effect = lambda x: x == os.path.join(dastcom5.POLIASTRO_LOCAL_PATH, 'dastcom5')
+ mock_isdir.side_effect = lambda x: x == os.path.join(dastcom5.POLIASTRO_LOCAL_PATH, 'dastcom5')
with pytest.raises(FileExistsError):
dastcom5.download_dastcom5()
mock_isdir.assert_called_once_with(os.path.join(dastcom5.POLIASTRO_LOCAL_PATH, 'dastcom5'))
@@ -93,10 +93,9 @@ def test_download_dastcom5_creates_folder(mock_isdir, mock_zipfile, mock_makedir
@mock.patch('poliastro.neos.dastcom5.os.path.isdir')
@mock.patch('poliastro.neos.dastcom5.urllib.request.urlretrieve')
def test_download_dastcom5_downloads_file(mock_request, mock_isdir, mock_zipfile):
- mock_isdir.side_effect = lambda x: x == dastcom5.POLIASTRO_LOCAL_PATH
+ mock_isdir.side_effect = lambda x: x == dastcom5.POLIASTRO_LOCAL_PATH
mock_zipfile.is_zipfile.return_value = False
dastcom5.download_dastcom5()
mock_request.assert_called_once_with(dastcom5.FTP_DB_URL + 'dastcom5.zip',
os.path.join(dastcom5.POLIASTRO_LOCAL_PATH, 'dastcom5.zip'),
dastcom5._show_download_progress)
-
diff --git a/src/poliastro/neos/tests/test_neos_neows.py b/src/poliastro/neos/tests/test_neos_neows.py
index 5d818d2e..2786f5c6 100644
--- a/src/poliastro/neos/tests/test_neos_neows.py
+++ b/src/poliastro/neos/tests/test_neos_neows.py
@@ -39,7 +39,7 @@ def test_orbit_from_spk_id_raises_when_error(mock_get):
resp = requests.Response()
resp.status_code = 404
- mock_get.return_value = resp
+ mock_get.return_value = resp
with pytest.raises(requests.HTTPError):
ss = neows.orbit_from_spk_id('')
@@ -59,7 +59,7 @@ def test_spk_id_from_name_raises_when_error(mock_get):
def test_spk_id_from_name_parses_body(mock_get, mock_response):
with open('src/poliastro/tests/table.html', 'r') as demo_html:
html = demo_html.read().replace('\n', '')
-
+
mock_response.text = html
mock_get.return_value = mock_response
assert '2000433' == neows.spk_id_from_name('')
diff --git a/src/poliastro/testing.py b/src/poliastro/testing.py
index 224395b2..7697264e 100644
--- a/src/poliastro/testing.py
+++ b/src/poliastro/testing.py
@@ -7,7 +7,7 @@ import pytest
def test():
- '''Initiate poliastro testing
-
- '''
+ """Initiate poliastro testing
+
+ """
pytest.main([os.path.dirname(os.path.abspath(__file__))])
diff --git a/src/poliastro/tests/test_hyper.py b/src/poliastro/tests/test_hyper.py
index e652b3cf..aeaf6196 100644
--- a/src/poliastro/tests/test_hyper.py
+++ b/src/poliastro/tests/test_hyper.py
@@ -9,7 +9,7 @@ from poliastro.hyper import hyp2f1b as hyp2f1
@pytest.mark.parametrize("x", np.linspace(0, 1, num=11))
def test_hyp2f1_battin_scalar(x):
- expected_res = special.hyp2f1(3, 1, 5/2, x)
+ expected_res = special.hyp2f1(3, 1, 5 / 2, x)
res = hyp2f1(x)
assert_allclose(res, expected_res)
diff --git a/src/poliastro/tests/test_plotting.py b/src/poliastro/tests/test_plotting.py
index fbbf308b..3b0fca52 100644
--- a/src/poliastro/tests/test_plotting.py
+++ b/src/poliastro/tests/test_plotting.py
@@ -3,8 +3,6 @@ import pytest
import astropy.units as u
-import matplotlib
-matplotlib.use("Agg") # use Agg backend for these tests
import matplotlib.pyplot as plt
from poliastro.examples import iss
@@ -12,7 +10,7 @@ from poliastro.examples import iss
from poliastro.plotting import OrbitPlotter
-def test_OrbitPlotter_has_axes():
+def test_orbitplotter_has_axes():
ax = "Unused axes"
op = OrbitPlotter(ax)
assert op.ax is ax
diff --git a/src/poliastro/twobody/tests/test_decorators.py b/src/poliastro/twobody/tests/test_decorators.py
new file mode 100644
index 00000000..6a24852f
--- /dev/null
+++ b/src/poliastro/twobody/tests/test_decorators.py
@@ -0,0 +1,31 @@
+import inspect
+
+from astropy import units as u
+
+from poliastro.twobody.decorators import state_from_vector
+
+
+def fun(t, ss):
+ return 1
+
+
+def decorated_fun(t, u_, k):
+ pass
+
+
+def test_decorator_has_correct_signature():
+ expected_signature = inspect.getfullargspec(decorated_fun)
+
+ new_fun = state_from_vector(fun)
+
+ assert inspect.getfullargspec(new_fun).args == expected_signature.args
+
+
+def test_decorated_function_calls_rvstate():
+ _t = 0
+ _u = [1, 0, 0, 0, 1, 0]
+ _k = 1
+
+ new_fun = state_from_vector(fun)
+
+ assert new_fun(_t, _u, _k) == 1
diff --git a/src/poliastro/twobody/tests/test_propagation.py b/src/poliastro/twobody/tests/test_propagation.py
index e44a7ac4..68c64d34 100644
--- a/src/poliastro/twobody/tests/test_propagation.py
+++ b/src/poliastro/twobody/tests/test_propagation.py
@@ -69,9 +69,9 @@ def test_apply_zero_maneuver_returns_equal_state():
dv = [0, 0, 0] * u.km / u.s
orbit_new = ss.apply_maneuver([(dt, dv)])
assert_allclose(orbit_new.r.to(u.km).value,
- ss.r.to(u.km).value)
+ ss.r.to(u.km).value)
assert_allclose(orbit_new.v.to(u.km / u.s).value,
- ss.v.to(u.km / u.s).value)
+ ss.v.to(u.km / u.s).value)
def test_cowell_propagation_callback():
@@ -134,9 +134,8 @@ def test_cowell_propagation_circle_to_circle():
tof.to(u.s).value,
ad=constant_accel)
- ss_final = Orbit.from_vectors(Earth,
- r * u.km,
- v * u.km / u.s)
+ ss_final = Orbit.from_vectors(
+ Earth, r * u.km, v * u.km / u.s)
da_a0 = (ss_final.a - ss.a) / ss.a
dv_v0 = abs(norm(ss_final.v) - norm(ss.v)) / norm(ss.v)
diff --git a/src/poliastro/twobody/tests/test_states.py b/src/poliastro/twobody/tests/test_states.py
index 29e07e93..82a519da 100644
--- a/src/poliastro/twobody/tests/test_states.py
+++ b/src/poliastro/twobody/tests/test_states.py
@@ -63,9 +63,9 @@ def test_perigee_and_apogee():
_a = 1.0 * u.deg # Unused angle
ss = ClassicalState(Earth, a, ecc, _a, _a, _a, _a)
assert_allclose(ss.r_a.to(u.km).value,
- expected_r_a.to(u.km).value)
+ expected_r_a.to(u.km).value)
assert_allclose(ss.r_p.to(u.km).value,
- expected_r_p.to(u.km).value)
+ expected_r_p.to(u.km).value)
def test_convert_from_rv_to_coe():
@@ -138,4 +138,4 @@ def test_pqw_returns_dimensionless():
assert p.unit == u.one
assert q.unit == u.one
- assert w.unit == u.one
\ No newline at end of file
+ assert w.unit == u.one
| {
"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": 2,
"test_score": 2
},
"num_modified_files": 12
} | 0.6 | {
"env_vars": null,
"env_yml_path": [
"environment.yml"
],
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "environment.yml",
"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"
} | alabaster @ file:///home/ktietz/src/ci/alabaster_1611921544520/work
astropy==4.0.2
async-generator @ file:///home/ktietz/src/ci/async_generator_1611927993394/work
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
Babel @ file:///tmp/build/80754af9/babel_1620871417480/work
backcall @ file:///home/ktietz/src/ci/backcall_1611930011877/work
beautifulsoup4 @ file:///tmp/build/80754af9/beautifulsoup4_1631874778482/work
bleach @ file:///opt/conda/conda-bld/bleach_1641577558959/work
brotlipy==0.7.0
certifi==2021.5.30
cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work
charset-normalizer @ file:///tmp/build/80754af9/charset-normalizer_1630003229654/work
colorama @ file:///tmp/build/80754af9/colorama_1607707115595/work
cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work
cycler @ file:///tmp/build/80754af9/cycler_1637851556182/work
decorator @ file:///opt/conda/conda-bld/decorator_1643638310831/work
defusedxml @ file:///tmp/build/80754af9/defusedxml_1615228127516/work
docutils @ file:///tmp/build/80754af9/docutils_1620827982266/work
entrypoints==0.3
idna @ file:///tmp/build/80754af9/idna_1637925883363/work
imagesize @ file:///tmp/build/80754af9/imagesize_1637939814114/work
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig==1.1.1
ipykernel @ file:///tmp/build/80754af9/ipykernel_1596206602906/work/dist/ipykernel-5.3.4-py3-none-any.whl
ipython @ file:///tmp/build/80754af9/ipython_1593447367857/work
ipython-genutils @ file:///tmp/build/80754af9/ipython_genutils_1606773439826/work
jedi @ file:///tmp/build/80754af9/jedi_1606932572482/work
Jinja2 @ file:///opt/conda/conda-bld/jinja2_1647436528585/work
jplephem @ file:///home/conda/feedstock_root/build_artifacts/jplephem_1701439151942/work
jsonschema @ file:///Users/ktietz/demo/mc3/conda-bld/jsonschema_1630511932244/work
jupyter-client @ file:///opt/conda/conda-bld/jupyter_client_1643638337975/work
jupyter-core @ file:///tmp/build/80754af9/jupyter_core_1633420100582/work
jupyterlab-pygments @ file:///tmp/build/80754af9/jupyterlab_pygments_1601490720602/work
kiwisolver @ file:///tmp/build/80754af9/kiwisolver_1612282412546/work
llvmlite==0.36.0
MarkupSafe @ file:///tmp/build/80754af9/markupsafe_1621528150516/work
matplotlib @ file:///tmp/build/80754af9/matplotlib-suite_1613407855456/work
mistune==0.8.4
nbclient @ file:///tmp/build/80754af9/nbclient_1614364831625/work
nbconvert @ file:///tmp/build/80754af9/nbconvert_1601914804165/work
nbformat @ file:///tmp/build/80754af9/nbformat_1617383369282/work
nbsphinx @ file:///home/conda/feedstock_root/build_artifacts/nbsphinx_1741075436613/work
nest-asyncio @ file:///tmp/build/80754af9/nest-asyncio_1613680548246/work
numba @ file:///tmp/build/80754af9/numba_1616771968628/work
numpy @ file:///tmp/build/80754af9/numpy_and_numpy_base_1603483703303/work
olefile @ file:///Users/ktietz/demo/mc3/conda-bld/olefile_1629805411829/work
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pandas==1.1.5
pandocfilters @ file:///opt/conda/conda-bld/pandocfilters_1643405455980/work
parso==0.7.0
pexpect @ file:///tmp/build/80754af9/pexpect_1605563209008/work
pickleshare @ file:///tmp/build/80754af9/pickleshare_1606932040724/work
Pillow @ file:///tmp/build/80754af9/pillow_1625670622947/work
pluggy==1.0.0
-e git+https://github.com/poliastro/poliastro.git@8cbb3018fb97748a6d66cc4d910657afeb31b7fd#egg=poliastro
prompt-toolkit @ file:///tmp/build/80754af9/prompt-toolkit_1633440160888/work
ptyprocess @ file:///tmp/build/80754af9/ptyprocess_1609355006118/work/dist/ptyprocess-0.7.0-py2.py3-none-any.whl
py==1.11.0
pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work
Pygments @ file:///opt/conda/conda-bld/pygments_1644249106324/work
pyOpenSSL @ file:///opt/conda/conda-bld/pyopenssl_1643788558760/work
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pyrsistent @ file:///tmp/build/80754af9/pyrsistent_1600141725711/work
PySocks @ file:///tmp/build/80754af9/pysocks_1605305763431/work
pytest==7.0.1
python-dateutil @ file:///tmp/build/80754af9/python-dateutil_1626374649649/work
pytz==2021.3
pyzmq @ file:///tmp/build/80754af9/pyzmq_1628268400816/work
requests @ file:///opt/conda/conda-bld/requests_1641824580448/work
scipy @ file:///tmp/build/80754af9/scipy_1597686635649/work
six @ file:///tmp/build/80754af9/six_1644875935023/work
snowballstemmer @ file:///tmp/build/80754af9/snowballstemmer_1637937080595/work
soupsieve @ file:///tmp/build/80754af9/soupsieve_1636706018808/work
Sphinx @ file:///opt/conda/conda-bld/sphinx_1643644169832/work
sphinxcontrib-applehelp @ file:///home/ktietz/src/ci/sphinxcontrib-applehelp_1611920841464/work
sphinxcontrib-devhelp @ file:///home/ktietz/src/ci/sphinxcontrib-devhelp_1611920923094/work
sphinxcontrib-htmlhelp @ file:///tmp/build/80754af9/sphinxcontrib-htmlhelp_1623945626792/work
sphinxcontrib-jsmath @ file:///home/ktietz/src/ci/sphinxcontrib-jsmath_1611920942228/work
sphinxcontrib-qthelp @ file:///home/ktietz/src/ci/sphinxcontrib-qthelp_1611921055322/work
sphinxcontrib-serializinghtml @ file:///tmp/build/80754af9/sphinxcontrib-serializinghtml_1624451540180/work
testpath @ file:///tmp/build/80754af9/testpath_1624638946665/work
tomli==1.2.3
tornado @ file:///tmp/build/80754af9/tornado_1606942266872/work
traitlets @ file:///tmp/build/80754af9/traitlets_1632746497744/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
urllib3 @ file:///opt/conda/conda-bld/urllib3_1643638302206/work
wcwidth @ file:///Users/ktietz/demo/mc3/conda-bld/wcwidth_1629357192024/work
webencodings==0.5.1
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: poliastro
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- alabaster=0.7.12=pyhd3eb1b0_0
- astropy=4.0.2=py36h7b6447c_0
- async_generator=1.10=pyhd3eb1b0_0
- attrs=21.4.0=pyhd3eb1b0_0
- babel=2.9.1=pyhd3eb1b0_0
- backcall=0.2.0=pyhd3eb1b0_0
- beautifulsoup4=4.10.0=pyh06a4308_0
- blas=1.0=openblas
- bleach=4.1.0=pyhd3eb1b0_0
- brotlipy=0.7.0=py36h27cfd23_1003
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- cffi=1.14.6=py36h400218f_0
- charset-normalizer=2.0.4=pyhd3eb1b0_0
- colorama=0.4.4=pyhd3eb1b0_0
- cryptography=35.0.0=py36hd23ed53_0
- cycler=0.11.0=pyhd3eb1b0_0
- dbus=1.13.18=hb2f20db_0
- decorator=5.1.1=pyhd3eb1b0_0
- defusedxml=0.7.1=pyhd3eb1b0_0
- docutils=0.17.1=py36h06a4308_1
- entrypoints=0.3=py36_0
- expat=2.6.4=h6a678d5_0
- fontconfig=2.14.1=h52c9d5c_1
- freetype=2.12.1=h4a9f257_0
- giflib=5.2.2=h5eee18b_0
- glib=2.69.1=h4ff587b_1
- gst-plugins-base=1.14.1=h6a678d5_1
- gstreamer=1.14.1=h5eee18b_1
- icu=58.2=he6710b0_3
- idna=3.3=pyhd3eb1b0_0
- imagesize=1.3.0=pyhd3eb1b0_0
- importlib-metadata=4.8.1=py36h06a4308_0
- importlib_metadata=4.8.1=hd3eb1b0_0
- ipykernel=5.3.4=py36h5ca1d4c_0
- ipython=7.16.1=py36h5ca1d4c_0
- ipython_genutils=0.2.0=pyhd3eb1b0_1
- jedi=0.17.2=py36h06a4308_1
- jinja2=3.0.3=pyhd3eb1b0_0
- jpeg=9e=h5eee18b_3
- jplephem=2.21=pyh864a33b_0
- jsonschema=3.2.0=pyhd3eb1b0_2
- jupyter_client=7.1.2=pyhd3eb1b0_0
- jupyter_core=4.8.1=py36h06a4308_0
- jupyterlab_pygments=0.1.2=py_0
- kiwisolver=1.3.1=py36h2531618_0
- lcms2=2.16=hb9589c4_0
- ld_impl_linux-64=2.40=h12ee557_0
- lerc=4.0.0=h6a678d5_0
- libdeflate=1.22=h5eee18b_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=7.5.0=ha8ba4b0_17
- libgfortran4=7.5.0=ha8ba4b0_17
- libgomp=11.2.0=h1234567_1
- libllvm10=10.0.1=hbcb73fb_5
- libopenblas=0.3.18=hf726d26_0
- libpng=1.6.39=h5eee18b_0
- libsodium=1.0.18=h7b6447c_0
- libstdcxx-ng=11.2.0=h1234567_1
- libtiff=4.5.1=hffd6297_1
- libuuid=1.41.5=h5eee18b_0
- libwebp=1.2.4=h11a3e52_1
- libwebp-base=1.2.4=h5eee18b_1
- libxcb=1.15=h7f8727e_0
- libxml2=2.9.14=h74e7548_0
- llvmlite=0.36.0=py36h612dafd_4
- lz4-c=1.9.4=h6a678d5_1
- markupsafe=2.0.1=py36h27cfd23_0
- matplotlib=3.3.4=py36h06a4308_0
- matplotlib-base=3.3.4=py36h62a2d02_0
- mistune=0.8.4=py36h7b6447c_0
- nbclient=0.5.3=pyhd3eb1b0_0
- nbconvert=6.0.7=py36_0
- nbformat=5.1.3=pyhd3eb1b0_0
- nbsphinx=0.9.7=pyhd8ed1ab_0
- ncurses=6.4=h6a678d5_0
- nest-asyncio=1.5.1=pyhd3eb1b0_0
- numba=0.53.1=py36ha9443f7_0
- numpy=1.19.2=py36h6163131_0
- numpy-base=1.19.2=py36h75fe3a5_0
- olefile=0.46=pyhd3eb1b0_0
- openssl=1.1.1w=h7f8727e_0
- packaging=21.3=pyhd3eb1b0_0
- pandas=1.1.5=py36ha9443f7_0
- pandoc=2.12=h06a4308_3
- pandocfilters=1.5.0=pyhd3eb1b0_0
- parso=0.7.0=py_0
- pcre=8.45=h295c915_0
- pexpect=4.8.0=pyhd3eb1b0_3
- pickleshare=0.7.5=pyhd3eb1b0_1003
- pillow=8.3.1=py36h5aabda8_0
- pip=21.2.2=py36h06a4308_0
- prompt-toolkit=3.0.20=pyhd3eb1b0_0
- ptyprocess=0.7.0=pyhd3eb1b0_2
- pycparser=2.21=pyhd3eb1b0_0
- pygments=2.11.2=pyhd3eb1b0_0
- pyopenssl=22.0.0=pyhd3eb1b0_0
- pyparsing=3.0.4=pyhd3eb1b0_0
- pyqt=5.9.2=py36h05f1152_2
- pyrsistent=0.17.3=py36h7b6447c_0
- pysocks=1.7.1=py36h06a4308_0
- python=3.6.13=h12debd9_1
- python-dateutil=2.8.2=pyhd3eb1b0_0
- pytz=2021.3=pyhd3eb1b0_0
- pyzmq=22.2.1=py36h295c915_1
- qt=5.9.7=h5867ecd_1
- readline=8.2=h5eee18b_0
- requests=2.27.1=pyhd3eb1b0_0
- scipy=1.5.2=py36habc2bb6_0
- setuptools=58.0.4=py36h06a4308_0
- sip=4.19.8=py36hf484d3e_0
- six=1.16.0=pyhd3eb1b0_1
- snowballstemmer=2.2.0=pyhd3eb1b0_0
- soupsieve=2.3.1=pyhd3eb1b0_0
- sphinx=4.4.0=pyhd3eb1b0_0
- sphinxcontrib-applehelp=1.0.2=pyhd3eb1b0_0
- sphinxcontrib-devhelp=1.0.2=pyhd3eb1b0_0
- sphinxcontrib-htmlhelp=2.0.0=pyhd3eb1b0_0
- sphinxcontrib-jsmath=1.0.1=pyhd3eb1b0_0
- sphinxcontrib-qthelp=1.0.3=pyhd3eb1b0_0
- sphinxcontrib-serializinghtml=1.1.5=pyhd3eb1b0_0
- sqlite=3.45.3=h5eee18b_0
- tbb=2020.3=hfd86e86_0
- testpath=0.5.0=pyhd3eb1b0_0
- tk=8.6.14=h39e8969_0
- tornado=6.1=py36h27cfd23_0
- traitlets=4.3.3=py36h06a4308_0
- typing_extensions=4.1.1=pyh06a4308_0
- urllib3=1.26.8=pyhd3eb1b0_0
- wcwidth=0.2.5=pyhd3eb1b0_0
- webencodings=0.5.1=py36_1
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zeromq=4.3.5=h6a678d5_0
- zipp=3.6.0=pyhd3eb1b0_0
- zlib=1.2.13=h5eee18b_1
- zstd=1.5.6=hc292b87_0
- pip:
- iniconfig==1.1.1
- pluggy==1.0.0
- py==1.11.0
- pytest==7.0.1
- tomli==1.2.3
prefix: /opt/conda/envs/poliastro
| [
"src/poliastro/twobody/tests/test_decorators.py::test_decorated_function_calls_rvstate"
]
| []
| [
"src/poliastro/neos/tests/test_dastcom5.py::test_asteroid_db_is_called_with_right_path",
"src/poliastro/neos/tests/test_dastcom5.py::test_comet_db_is_called_with_right_path",
"src/poliastro/neos/tests/test_dastcom5.py::test_orbit_from_name",
"src/poliastro/neos/tests/test_dastcom5.py::test_record_from_name",
"src/poliastro/neos/tests/test_dastcom5.py::test_read_headers",
"src/poliastro/neos/tests/test_dastcom5.py::test_read_record",
"src/poliastro/neos/tests/test_dastcom5.py::test_download_dastcom5_raises_error_when_folder_exists",
"src/poliastro/neos/tests/test_dastcom5.py::test_download_dastcom5_creates_folder",
"src/poliastro/neos/tests/test_dastcom5.py::test_download_dastcom5_downloads_file",
"src/poliastro/neos/tests/test_neos_neows.py::test_orbit_from_spk_id_has_proper_values",
"src/poliastro/neos/tests/test_neos_neows.py::test_orbit_from_spk_id_raises_when_error",
"src/poliastro/neos/tests/test_neos_neows.py::test_spk_id_from_name_raises_when_error",
"src/poliastro/neos/tests/test_neos_neows.py::test_spk_id_from_name_parses_body",
"src/poliastro/neos/tests/test_neos_neows.py::test_spk_id_from_name_parses_object_list_and_raises",
"src/poliastro/neos/tests/test_neos_neows.py::test_spk_id_from_name_raises_when_not_found",
"src/poliastro/testing.py::test",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[0.0]",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[0.1]",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[0.2]",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[0.30000000000000004]",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[0.4]",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[0.5]",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[0.6000000000000001]",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[0.7000000000000001]",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[0.8]",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[0.9]",
"src/poliastro/tests/test_hyper.py::test_hyp2f1_battin_scalar[1.0]",
"src/poliastro/tests/test_plotting.py::test_orbitplotter_has_axes",
"src/poliastro/tests/test_plotting.py::test_set_frame_raises_error_if_frame_exists",
"src/poliastro/tests/test_plotting.py::test_axes_labels_and_title",
"src/poliastro/tests/test_plotting.py::test_number_of_lines_for_osculating_orbit",
"src/poliastro/twobody/tests/test_decorators.py::test_decorator_has_correct_signature",
"src/poliastro/twobody/tests/test_propagation.py::test_propagation",
"src/poliastro/twobody/tests/test_propagation.py::test_propagation_hyperbolic",
"src/poliastro/twobody/tests/test_propagation.py::test_propagation_zero_time_returns_same_state",
"src/poliastro/twobody/tests/test_propagation.py::test_apply_zero_maneuver_returns_equal_state",
"src/poliastro/twobody/tests/test_propagation.py::test_cowell_propagation_callback",
"src/poliastro/twobody/tests/test_propagation.py::test_cowell_propagation_with_zero_acceleration_equals_kepler",
"src/poliastro/twobody/tests/test_propagation.py::test_cowell_propagation_circle_to_circle",
"src/poliastro/twobody/tests/test_states.py::test_state_has_attractor_given_in_constructor",
"src/poliastro/twobody/tests/test_states.py::test_state_has_elements_given_in_constructor",
"src/poliastro/twobody/tests/test_states.py::test_state_has_individual_elements",
"src/poliastro/twobody/tests/test_states.py::test_state_has_rv_given_in_constructor",
"src/poliastro/twobody/tests/test_states.py::test_perigee_and_apogee",
"src/poliastro/twobody/tests/test_states.py::test_convert_from_rv_to_coe",
"src/poliastro/twobody/tests/test_states.py::test_convert_from_coe_to_rv",
"src/poliastro/twobody/tests/test_states.py::test_perifocal_points_to_perigee",
"src/poliastro/twobody/tests/test_states.py::test_arglat_within_range",
"src/poliastro/twobody/tests/test_states.py::test_pqw_returns_dimensionless"
]
| []
| MIT License | 1,594 | [
"src/poliastro/plotting.py",
"src/poliastro/cli.py",
"src/poliastro/neos/dastcom5.py",
"src/poliastro/twobody/classical.py",
"src/poliastro/neos/neows.py",
"setup.py",
"src/poliastro/twobody/orbit.py",
"src/poliastro/twobody/rv.py",
".travis.yml",
"setup.cfg",
"src/poliastro/maneuver.py",
"src/poliastro/twobody/decorators.py"
]
| [
"src/poliastro/plotting.py",
"src/poliastro/cli.py",
"src/poliastro/neos/dastcom5.py",
"src/poliastro/twobody/classical.py",
"src/poliastro/neos/neows.py",
"setup.py",
"src/poliastro/twobody/orbit.py",
"src/poliastro/twobody/rv.py",
".travis.yml",
"setup.cfg",
"src/poliastro/maneuver.py",
"src/poliastro/twobody/decorators.py"
]
|
|
jaywink__federation-100 | ebacea83b0d70f8e63ffacdf113f05600acc6451 | 2017-08-17 18:35:12 | bcc779e006bc0af192db08a1ff8ed245c0fbd7c9 | pep8speaks: Hello @jaywink! Thanks for submitting the PR.
- In the file [`federation/tests/entities/diaspora/test_entities.py`](https://github.com/jaywink/federation/blob/296c903b949d95cfdaf3d5c49e79391163621575/federation/tests/entities/diaspora/test_entities.py), following are the PEP8 issues :
> [Line 106:13](https://github.com/jaywink/federation/blob/296c903b949d95cfdaf3d5c49e79391163621575/federation/tests/entities/diaspora/test_entities.py#L106): [E122](https://duckduckgo.com/?q=pep8%20E122) continuation line missing indentation or outdented
> [Line 107:13](https://github.com/jaywink/federation/blob/296c903b949d95cfdaf3d5c49e79391163621575/federation/tests/entities/diaspora/test_entities.py#L107): [E122](https://duckduckgo.com/?q=pep8%20E122) continuation line missing indentation or outdented
> [Line 108:9](https://github.com/jaywink/federation/blob/296c903b949d95cfdaf3d5c49e79391163621575/federation/tests/entities/diaspora/test_entities.py#L108): [E122](https://duckduckgo.com/?q=pep8%20E122) continuation line missing indentation or outdented
- In the file [`federation/tests/entities/diaspora/test_mappers.py`](https://github.com/jaywink/federation/blob/296c903b949d95cfdaf3d5c49e79391163621575/federation/tests/entities/diaspora/test_mappers.py), following are the PEP8 issues :
> [Line 203:30](https://github.com/jaywink/federation/blob/296c903b949d95cfdaf3d5c49e79391163621575/federation/tests/entities/diaspora/test_mappers.py#L203): [E712](https://duckduckgo.com/?q=pep8%20E712) comparison to True should be 'if cond is True:' or 'if cond:'
codecov[bot]: # [Codecov](https://codecov.io/gh/jaywink/federation/pull/100?src=pr&el=h1) Report
> Merging [#100](https://codecov.io/gh/jaywink/federation/pull/100?src=pr&el=desc) into [master](https://codecov.io/gh/jaywink/federation/commit/ebacea83b0d70f8e63ffacdf113f05600acc6451?src=pr&el=desc) will **increase** coverage by `0.15%`.
> The diff coverage is `97.95%`.
[](https://codecov.io/gh/jaywink/federation/pull/100?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #100 +/- ##
==========================================
+ Coverage 91.67% 91.83% +0.15%
==========================================
Files 17 17
Lines 1093 1102 +9
==========================================
+ Hits 1002 1012 +10
+ Misses 91 90 -1
```
| [Impacted Files](https://codecov.io/gh/jaywink/federation/pull/100?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [federation/entities/diaspora/mappers.py](https://codecov.io/gh/jaywink/federation/pull/100?src=pr&el=tree#diff-ZmVkZXJhdGlvbi9lbnRpdGllcy9kaWFzcG9yYS9tYXBwZXJzLnB5) | `99.33% <100%> (ø)` | :arrow_up: |
| [federation/entities/diaspora/entities.py](https://codecov.io/gh/jaywink/federation/pull/100?src=pr&el=tree#diff-ZmVkZXJhdGlvbi9lbnRpdGllcy9kaWFzcG9yYS9lbnRpdGllcy5weQ==) | `97.89% <100%> (+0.11%)` | :arrow_up: |
| [federation/entities/base.py](https://codecov.io/gh/jaywink/federation/pull/100?src=pr&el=tree#diff-ZmVkZXJhdGlvbi9lbnRpdGllcy9iYXNlLnB5) | `96.44% <97.36%> (+0.59%)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/jaywink/federation/pull/100?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/jaywink/federation/pull/100?src=pr&el=footer). Last update [ebacea8...296c903](https://codecov.io/gh/jaywink/federation/pull/100?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
| diff --git a/CHANGELOG.md b/CHANGELOG.md
index 07c5f19..19755b4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,11 @@
## [unreleased]
+### Added
+* Added base entity `Share` which maps to a `DiasporaReshare` for the Diaspora protocol. ([related issue](https://github.com/jaywink/federation/issues/94))
+
+ The `Share` entity supports all the properties that a Diaspora reshare does. Additionally two other properties are supported: `raw_content` and `entity_type`. The former can be used for a "quoted share" case where the sharer adds their own note to the share. The latter can be used to reference the type of object that was shared, to help the receiver, if it is not sharing a `Post` entity. The value must be a base entity class name.
+
### Fixed
* Converting base entity `Profile` to `DiasporaProfile` for outbound sending missed two attributes, `image_urls` and `tag_list`. Those are now included so that the values transfer into the built payload.
diff --git a/docs/protocols.rst b/docs/protocols.rst
index 443cff1..a12f202 100644
--- a/docs/protocols.rst
+++ b/docs/protocols.rst
@@ -24,6 +24,7 @@ The feature set supported by this release is approximately the following:
* Retraction
* StatusMessage
* Contact
+ * Reshare
Implementation unfortunately currently requires knowledge of how Diaspora discovery works as the implementer has to implement all the necessary views correctly (even though this library provides document generators). However, the magic envelope, signature and entity building is all abstracted inside the library.
diff --git a/docs/usage.rst b/docs/usage.rst
index e69a918..5a84ebd 100644
--- a/docs/usage.rst
+++ b/docs/usage.rst
@@ -17,6 +17,7 @@ Entity types are as follows below.
.. autoclass:: federation.entities.base.Reaction
.. autoclass:: federation.entities.base.Relationship
.. autoclass:: federation.entities.base.Retraction
+.. autoclass:: federation.entities.base.Share
Protocol entities
.................
diff --git a/federation/entities/base.py b/federation/entities/base.py
index 989516a..b8f8ba5 100644
--- a/federation/entities/base.py
+++ b/federation/entities/base.py
@@ -5,7 +5,7 @@ from dirty_validators.basic import Email
__all__ = (
- "Post", "Image", "Comment", "Reaction", "Relationship", "Profile", "Retraction", "Follow",
+ "Post", "Image", "Comment", "Reaction", "Relationship", "Profile", "Retraction", "Follow", "Share,"
)
@@ -125,6 +125,24 @@ class TargetGUIDMixin(BaseEntity):
raise ValueError("Target GUID must be at least 16 characters")
+class ParticipationMixin(TargetGUIDMixin):
+ """Reflects a participation to something."""
+ participation = ""
+
+ _participation_valid_values = ["reaction", "subscription", "comment"]
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._required += ["participation"]
+
+ def validate_participation(self):
+ """Ensure participation is of a certain type."""
+ if self.participation not in self._participation_valid_values:
+ raise ValueError("participation should be one of: {valid}".format(
+ valid=", ".join(self._participation_valid_values)
+ ))
+
+
class HandleMixin(BaseEntity):
handle = ""
@@ -178,7 +196,43 @@ class OptionalRawContentMixin(RawContentMixin):
self._required.remove("raw_content")
-class Image(GUIDMixin, HandleMixin, PublicMixin, OptionalRawContentMixin, CreatedAtMixin, BaseEntity):
+class EntityTypeMixin(BaseEntity):
+ """Provides a field for entity type.
+
+ Validates it is one of our entities.
+ """
+ entity_type = ""
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._required += ["entity_type"]
+
+ def validate_entity_type(self):
+ """Ensure type is some entity we know of."""
+ if self.entity_type not in __all__:
+ raise ValueError("Entity type %s not recognized." % self.entity_type)
+
+
+class ProviderDisplayNameMixin(BaseEntity):
+ """Provides a field for provider display name."""
+ provider_display_name = ""
+
+
+class TargetHandleMixin(BaseEntity):
+ """Provides a target handle field."""
+ target_handle = ""
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._required += ["target_handle"]
+
+ def validate_target_handle(self):
+ validator = Email()
+ if not validator.is_valid(self.target_handle):
+ raise ValueError("Target handle is not valid")
+
+
+class Image(GUIDMixin, HandleMixin, PublicMixin, OptionalRawContentMixin, CreatedAtMixin):
"""Reflects a single image, possibly linked to another object."""
remote_path = ""
remote_name = ""
@@ -192,32 +246,13 @@ class Image(GUIDMixin, HandleMixin, PublicMixin, OptionalRawContentMixin, Create
self._required += ["remote_path", "remote_name"]
-class Post(RawContentMixin, GUIDMixin, HandleMixin, PublicMixin, CreatedAtMixin, BaseEntity):
+class Post(RawContentMixin, GUIDMixin, HandleMixin, PublicMixin, CreatedAtMixin, ProviderDisplayNameMixin):
"""Reflects a post, status message, etc, which will be composed from the message or to the message."""
- provider_display_name = ""
location = ""
_allowed_children = (Image,)
-class ParticipationMixin(TargetGUIDMixin):
- """Reflects a participation to something."""
- participation = ""
-
- _participation_valid_values = ["reaction", "subscription", "comment"]
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self._required += ["participation"]
-
- def validate_participation(self):
- """Ensure participation is of a certain type."""
- if self.participation not in self._participation_valid_values:
- raise ValueError("participation should be one of: {valid}".format(
- valid=", ".join(self._participation_valid_values)
- ))
-
-
class Comment(RawContentMixin, GUIDMixin, ParticipationMixin, CreatedAtMixin, HandleMixin):
"""Represents a comment, linked to another object."""
participation = "comment"
@@ -247,21 +282,15 @@ class Reaction(GUIDMixin, ParticipationMixin, CreatedAtMixin, HandleMixin):
))
-class Relationship(CreatedAtMixin, HandleMixin):
+class Relationship(CreatedAtMixin, HandleMixin, TargetHandleMixin):
"""Represents a relationship between two handles."""
- target_handle = ""
relationship = ""
_relationship_valid_values = ["sharing", "following", "ignoring", "blocking"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self._required += ["relationship", "target_handle"]
-
- def validate_target_handle(self):
- validator = Email()
- if not validator.is_valid(self.target_handle):
- raise ValueError("Target handle is not valid")
+ self._required += ["relationship"]
def validate_relationship(self):
"""Ensure relationship is of a certain type."""
@@ -271,19 +300,13 @@ class Relationship(CreatedAtMixin, HandleMixin):
))
-class Follow(CreatedAtMixin, HandleMixin):
+class Follow(CreatedAtMixin, HandleMixin, TargetHandleMixin):
"""Represents a handle following or unfollowing another handle."""
- target_handle = ""
following = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self._required += ["target_handle", "following"]
-
- def validate_target_handle(self):
- validator = Email()
- if not validator.is_valid(self.target_handle):
- raise ValueError("Target handle is not valid")
+ self._required += ["following"]
class Profile(CreatedAtMixin, HandleMixin, OptionalRawContentMixin, PublicMixin, GUIDMixin):
@@ -313,15 +336,19 @@ class Profile(CreatedAtMixin, HandleMixin, OptionalRawContentMixin, PublicMixin,
raise ValueError("Email is not valid")
-class Retraction(CreatedAtMixin, HandleMixin, TargetGUIDMixin):
+class Retraction(CreatedAtMixin, HandleMixin, TargetGUIDMixin, EntityTypeMixin):
"""Represents a retraction of content by author."""
- entity_type = ""
+ pass
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self._required += ["entity_type"]
- def validate_entity_type(self):
- """Ensure type is some entity we know of."""
- if self.entity_type not in __all__:
- raise ValueError("Entity type %s not recognized." % self.entity_type)
+class Share(CreatedAtMixin, HandleMixin, TargetGUIDMixin, GUIDMixin, EntityTypeMixin, OptionalRawContentMixin,
+ PublicMixin, ProviderDisplayNameMixin, TargetHandleMixin):
+ """Represents a share of another entity.
+
+ ``entity_type`` defaults to "Post" but can be any base entity class name. It should be the class name of the
+ entity that was shared.
+
+ The optional ``raw_content`` can be used for a "quoted share" case where the sharer adds their own note to the
+ share.
+ """
+ entity_type = "Post"
diff --git a/federation/entities/diaspora/entities.py b/federation/entities/diaspora/entities.py
index 5e23523..d7392aa 100644
--- a/federation/entities/diaspora/entities.py
+++ b/federation/entities/diaspora/entities.py
@@ -1,6 +1,7 @@
from lxml import etree
-from federation.entities.base import Comment, Post, Reaction, Relationship, Profile, Retraction, BaseEntity, Follow
+from federation.entities.base import (
+ Comment, Post, Reaction, Relationship, Profile, Retraction, BaseEntity, Follow, Share)
from federation.entities.diaspora.utils import format_dt, struct_to_xml, get_base_attributes, add_element_to_doc
from federation.exceptions import SignatureVerificationError
from federation.protocols.diaspora.signatures import verify_relayable_signature, create_relayable_signature
@@ -211,3 +212,22 @@ class DiasporaRetraction(DiasporaEntityMixin, Retraction):
index = values.index(value)
return list(DiasporaRetraction.mapped.keys())[index]
return value
+
+
+class DiasporaReshare(DiasporaEntityMixin, Share):
+ """Diaspora Reshare."""
+ def to_xml(self):
+ element = etree.Element("reshare")
+ struct_to_xml(element, [
+ {"author": self.handle},
+ {"guid": self.guid},
+ {"created_at": format_dt(self.created_at)},
+ {"root_author": self.target_handle},
+ {"root_guid": self.target_guid},
+ {"provider_display_name": self.provider_display_name},
+ {"public": "true" if self.public else "false"},
+ # Some of our own not in Diaspora protocol
+ {"raw_content": self.raw_content},
+ {"entity_type": self.entity_type},
+ ])
+ return element
diff --git a/federation/entities/diaspora/mappers.py b/federation/entities/diaspora/mappers.py
index bb8a174..5acd205 100644
--- a/federation/entities/diaspora/mappers.py
+++ b/federation/entities/diaspora/mappers.py
@@ -3,10 +3,10 @@ from datetime import datetime
from lxml import etree
-from federation.entities.base import Image, Relationship, Post, Reaction, Comment, Profile, Retraction, Follow
+from federation.entities.base import Image, Relationship, Post, Reaction, Comment, Profile, Retraction, Follow, Share
from federation.entities.diaspora.entities import (
DiasporaPost, DiasporaComment, DiasporaLike, DiasporaRequest, DiasporaProfile, DiasporaRetraction,
- DiasporaRelayableMixin, DiasporaContact)
+ DiasporaRelayableMixin, DiasporaContact, DiasporaReshare)
from federation.protocols.diaspora.signatures import get_element_child_info
from federation.utils.diaspora import retrieve_and_parse_profile
@@ -21,11 +21,12 @@ MAPPINGS = {
"profile": DiasporaProfile,
"retraction": DiasporaRetraction,
"contact": DiasporaContact,
+ "reshare": DiasporaReshare,
}
TAGS = [
# Order is important. Any top level tags should be before possibly child tags
- "status_message", "comment", "like", "request", "profile", "retraction", "photo", "contact",
+ "reshare", "status_message", "comment", "like", "request", "profile", "retraction", "photo", "contact",
]
BOOLEAN_KEYS = (
@@ -44,6 +45,7 @@ INTEGER_KEYS = (
"width",
)
+
def xml_children_as_dict(node):
"""Turn the children of node <xml> into a dict, keyed by tag name.
@@ -167,9 +169,9 @@ def transform_attributes(attrs, cls):
transformed["raw_content"] = value
elif key in ["diaspora_handle", "sender_handle", "author"]:
transformed["handle"] = value
- elif key in ["recipient_handle", "recipient"]:
+ elif key in ["recipient_handle", "recipient", "root_author", "root_diaspora_id"]:
transformed["target_handle"] = value
- elif key == "parent_guid":
+ elif key in ["parent_guid", "post_guid", "root_guid"]:
transformed["target_guid"] = value
elif key == "first_name":
transformed["name"] = value
@@ -203,8 +205,6 @@ def transform_attributes(attrs, cls):
transformed["linked_type"] = "Post"
elif key == "author_signature":
transformed["signature"] = value
- elif key == "post_guid":
- transformed["target_guid"] = value
elif key in BOOLEAN_KEYS:
transformed[key] = True if value == "true" else False
elif key in DATETIME_KEYS:
@@ -239,7 +239,7 @@ def get_outbound_entity(entity, private_key):
outbound = None
cls = entity.__class__
if cls in [DiasporaPost, DiasporaRequest, DiasporaComment, DiasporaLike, DiasporaProfile, DiasporaRetraction,
- DiasporaContact]:
+ DiasporaContact, DiasporaReshare]:
# Already fine
outbound = entity
elif cls == Post:
@@ -259,6 +259,8 @@ def get_outbound_entity(entity, private_key):
outbound = DiasporaProfile.from_base(entity)
elif cls == Retraction:
outbound = DiasporaRetraction.from_base(entity)
+ elif cls == Share:
+ outbound = DiasporaReshare.from_base(entity)
if not outbound:
raise ValueError("Don't know how to convert this base entity to Diaspora protocol entities.")
if isinstance(outbound, DiasporaRelayableMixin) and not outbound.signature:
| Add Diaspora Reshare entity support
https://diaspora.github.io/diaspora_federation/entities/reshare.html | jaywink/federation | diff --git a/federation/tests/entities/diaspora/test_entities.py b/federation/tests/entities/diaspora/test_entities.py
index 2f8671d..dea34c1 100644
--- a/federation/tests/entities/diaspora/test_entities.py
+++ b/federation/tests/entities/diaspora/test_entities.py
@@ -6,9 +6,10 @@ from lxml import etree
from federation.entities.base import Profile
from federation.entities.diaspora.entities import (
DiasporaComment, DiasporaPost, DiasporaLike, DiasporaRequest, DiasporaProfile, DiasporaRetraction,
- DiasporaContact)
+ DiasporaContact, DiasporaReshare)
from federation.entities.diaspora.mappers import message_to_objects
from federation.exceptions import SignatureVerificationError
+from federation.tests.factories.entities import ShareFactory
from federation.tests.fixtures.keys import get_dummy_private_key
from federation.tests.fixtures.payloads import DIASPORA_POST_COMMENT
@@ -93,6 +94,21 @@ class TestEntitiesConvertToXML:
b"<following>true</following><sharing>true</sharing></contact>"
assert etree.tostring(result) == converted
+ def test_reshare_to_xml(self):
+ base_entity = ShareFactory()
+ entity = DiasporaReshare.from_base(base_entity)
+ result = entity.to_xml()
+ assert result.tag == "reshare"
+ result.find("created_at").text = "" # timestamp makes testing painful
+ converted = "<reshare><author>%s</author><guid>%s</guid><created_at></created_at><root_author>%s" \
+ "</root_author><root_guid>%s</root_guid><provider_display_name>%s</provider_display_name>" \
+ "<public>%s</public><raw_content>%s</raw_content><entity_type>%s</entity_type></reshare>" % (
+ entity.handle, entity.guid, entity.target_handle, entity.target_guid,
+ entity.provider_display_name, "true" if entity.public else "false", entity.raw_content,
+ entity.entity_type,
+ )
+ assert etree.tostring(result).decode("utf-8") == converted
+
class TestDiasporaProfileFillExtraAttributes:
def test_raises_if_no_handle(self):
diff --git a/federation/tests/entities/diaspora/test_mappers.py b/federation/tests/entities/diaspora/test_mappers.py
index 9313596..1adeac0 100644
--- a/federation/tests/entities/diaspora/test_mappers.py
+++ b/federation/tests/entities/diaspora/test_mappers.py
@@ -6,17 +6,18 @@ import pytest
from federation.entities.base import (
Comment, Post, Reaction, Relationship, Profile, Retraction, Image,
- Follow)
+ Follow, Share)
from federation.entities.diaspora.entities import (
DiasporaPost, DiasporaComment, DiasporaLike, DiasporaRequest,
- DiasporaProfile, DiasporaRetraction, DiasporaContact)
+ DiasporaProfile, DiasporaRetraction, DiasporaContact, DiasporaReshare)
from federation.entities.diaspora.mappers import (
message_to_objects, get_outbound_entity, check_sender_and_entity_handle_match)
from federation.tests.fixtures.payloads import (
DIASPORA_POST_SIMPLE, DIASPORA_POST_COMMENT, DIASPORA_POST_LIKE,
DIASPORA_REQUEST, DIASPORA_PROFILE, DIASPORA_POST_INVALID, DIASPORA_RETRACTION,
DIASPORA_POST_WITH_PHOTOS, DIASPORA_POST_LEGACY_TIMESTAMP, DIASPORA_POST_LEGACY, DIASPORA_CONTACT,
- DIASPORA_LEGACY_REQUEST_RETRACTION, DIASPORA_POST_WITH_PHOTOS_2, DIASPORA_PROFILE_EMPTY_TAGS)
+ DIASPORA_LEGACY_REQUEST_RETRACTION, DIASPORA_POST_WITH_PHOTOS_2, DIASPORA_PROFILE_EMPTY_TAGS, DIASPORA_RESHARE,
+ DIASPORA_RESHARE_WITH_EXTRA_PROPERTIES, DIASPORA_RESHARE_LEGACY)
def mock_fill(attributes):
@@ -189,6 +190,40 @@ class TestDiasporaEntityMappersReceive:
assert entity.target_handle == "[email protected]"
assert entity.following is True
+ def test_message_to_objects_reshare(self):
+ entities = message_to_objects(DIASPORA_RESHARE, "[email protected]")
+ assert len(entities) == 1
+ entity = entities[0]
+ assert isinstance(entity, DiasporaReshare)
+ assert entity.handle == "[email protected]"
+ assert entity.guid == "a0b53e5029f6013487753131731751e9"
+ assert entity.provider_display_name == ""
+ assert entity.target_handle == "[email protected]"
+ assert entity.target_guid == "a0b53bc029f6013487753131731751e9"
+ assert entity.public is True
+ assert entity.entity_type == "Post"
+
+ def test_message_to_objects_reshare_legacy(self):
+ entities = message_to_objects(DIASPORA_RESHARE_LEGACY, "[email protected]")
+ assert len(entities) == 1
+ entity = entities[0]
+ assert isinstance(entity, DiasporaReshare)
+ assert entity.handle == "[email protected]"
+ assert entity.guid == "a0b53e5029f6013487753131731751e9"
+ assert entity.provider_display_name == ""
+ assert entity.target_handle == "[email protected]"
+ assert entity.target_guid == "a0b53bc029f6013487753131731751e9"
+ assert entity.public is True
+ assert entity.entity_type == "Post"
+
+ def test_message_to_objects_reshare_extra_properties(self):
+ entities = message_to_objects(DIASPORA_RESHARE_WITH_EXTRA_PROPERTIES, "[email protected]")
+ assert len(entities) == 1
+ entity = entities[0]
+ assert isinstance(entity, DiasporaReshare)
+ assert entity.raw_content == "Important note here"
+ assert entity.entity_type == "Comment"
+
@patch("federation.entities.diaspora.mappers.logger.error")
def test_invalid_entity_logs_an_error(self, mock_logger):
entities = message_to_objects(DIASPORA_POST_INVALID, "[email protected]")
@@ -242,6 +277,8 @@ class TestGetOutboundEntity:
assert get_outbound_entity(entity, private_key) == entity
entity = DiasporaContact()
assert get_outbound_entity(entity, private_key) == entity
+ entity = DiasporaReshare()
+ assert get_outbound_entity(entity, private_key) == entity
def test_post_is_converted_to_diasporapost(self, private_key):
entity = Post()
@@ -283,6 +320,10 @@ class TestGetOutboundEntity:
entity = Follow()
assert isinstance(get_outbound_entity(entity, private_key), DiasporaContact)
+ def test_share_is_converted_to_diasporareshare(self, private_key):
+ entity = Share()
+ assert isinstance(get_outbound_entity(entity, private_key), DiasporaReshare)
+
def test_signs_relayable_if_no_signature(self, private_key):
entity = DiasporaComment()
outbound = get_outbound_entity(entity, private_key)
diff --git a/federation/tests/entities/test_base.py b/federation/tests/entities/test_base.py
index 5eaa10a..89985e3 100644
--- a/federation/tests/entities/test_base.py
+++ b/federation/tests/entities/test_base.py
@@ -4,11 +4,11 @@ import pytest
from federation.entities.base import (
BaseEntity, Relationship, Profile, RawContentMixin, GUIDMixin, HandleMixin, PublicMixin, Image, Retraction,
- Follow)
-from federation.tests.factories.entities import TaggedPostFactory, PostFactory
+ Follow, TargetHandleMixin)
+from federation.tests.factories.entities import TaggedPostFactory, PostFactory, ShareFactory
-class TestPostEntityTags():
+class TestPostEntityTags:
def test_post_entity_returns_list_of_tags(self):
post = TaggedPostFactory()
assert post.tags == {"tagone", "tagtwo", "tagthree", "upper", "snakecase"}
@@ -18,7 +18,7 @@ class TestPostEntityTags():
assert post.tags == set()
-class TestBaseEntityCallsValidateMethods():
+class TestBaseEntityCallsValidateMethods:
def test_entity_calls_attribute_validate_method(self):
post = PostFactory()
post.validate_location = Mock()
@@ -48,28 +48,41 @@ class TestBaseEntityCallsValidateMethods():
post._validate_children()
-class TestGUIDMixinValidate():
+class TestGUIDMixinValidate:
def test_validate_guid_raises_on_low_length(self):
guid = GUIDMixin(guid="x"*15)
with pytest.raises(ValueError):
guid.validate()
+ guid = GUIDMixin(guid="x" * 16)
+ guid.validate()
-class TestHandleMixinValidate():
+class TestHandleMixinValidate:
def test_validate_handle_raises_on_invalid_format(self):
handle = HandleMixin(handle="foobar")
with pytest.raises(ValueError):
handle.validate()
+ handle = HandleMixin(handle="[email protected]")
+ handle.validate()
-class TestPublicMixinValidate():
+class TestTargetHandleMixinValidate:
+ def test_validate_target_handle_raises_on_invalid_format(self):
+ handle = TargetHandleMixin(target_handle="foobar")
+ with pytest.raises(ValueError):
+ handle.validate()
+ handle = TargetHandleMixin(target_handle="[email protected]")
+ handle.validate()
+
+
+class TestPublicMixinValidate:
def test_validate_public_raises_on_low_length(self):
public = PublicMixin(public="foobar")
with pytest.raises(ValueError):
public.validate()
-class TestEntityRequiredAttributes():
+class TestEntityRequiredAttributes:
def test_entity_checks_for_required_attributes(self):
entity = BaseEntity()
entity._required = ["foobar"]
@@ -85,7 +98,7 @@ class TestEntityRequiredAttributes():
entity.validate()
-class TestRelationshipEntity():
+class TestRelationshipEntity:
def test_instance_creation(self):
entity = Relationship(handle="[email protected]", target_handle="[email protected]", relationship="following")
assert entity
@@ -95,13 +108,8 @@ class TestRelationshipEntity():
entity = Relationship(handle="[email protected]", target_handle="[email protected]", relationship="hating")
entity.validate()
- def test_instance_creation_validates_target_handle_value(self):
- with pytest.raises(ValueError):
- entity = Relationship(handle="[email protected]", target_handle="fefle.com", relationship="following")
- entity.validate()
-
-class TestProfileEntity():
+class TestProfileEntity:
def test_instance_creation(self):
entity = Profile(handle="[email protected]", raw_content="foobar")
assert entity
@@ -117,7 +125,7 @@ class TestProfileEntity():
entity.validate()
-class TestImageEntity():
+class TestImageEntity:
def test_instance_creation(self):
entity = Image(
guid="x"*16, handle="[email protected]", public=False, remote_path="foobar", remote_name="barfoo"
@@ -137,7 +145,7 @@ class TestImageEntity():
entity.validate()
-class TestRetractionEntity():
+class TestRetractionEntity:
def test_instance_creation(self):
entity = Retraction(
handle="[email protected]", target_guid="x"*16, entity_type="Post"
@@ -162,16 +170,15 @@ class TestRetractionEntity():
entity.validate()
-class TestFollowEntity():
+class TestFollowEntity:
def test_instance_creation(self):
entity = Follow(
handle="[email protected]", target_handle="[email protected]", following=True
)
entity.validate()
- def test_required_validates(self):
- entity = Follow(
- handle="[email protected]", following=True
- )
- with pytest.raises(ValueError):
- entity.validate()
+
+class TestShareEntity:
+ def test_instance_creation(self):
+ entity = ShareFactory()
+ entity.validate()
diff --git a/federation/tests/factories/entities.py b/federation/tests/factories/entities.py
index 7e9fdf0..3f4ab26 100644
--- a/federation/tests/factories/entities.py
+++ b/federation/tests/factories/entities.py
@@ -1,9 +1,8 @@
-# -*- coding: utf-8 -*-
from random import shuffle
import factory
from factory import fuzzy
-from federation.entities.base import Post, Profile
+from federation.entities.base import Post, Profile, Share
from federation.entities.diaspora.entities import DiasporaPost
@@ -47,3 +46,15 @@ class ProfileFactory(GUIDMixinFactory, HandleMixinFactory, RawContentMixinFactor
name = fuzzy.FuzzyText(length=30)
public_key = fuzzy.FuzzyText(length=300)
+
+
+class ShareFactory(GUIDMixinFactory, HandleMixinFactory):
+ class Meta:
+ model = Share
+
+ target_guid = factory.Faker("uuid4")
+ entity_type = "Post"
+ raw_content = ""
+ public = factory.Faker("pybool")
+ provider_display_name = ""
+ target_handle = factory.Faker("safe_email")
diff --git a/federation/tests/fixtures/payloads.py b/federation/tests/fixtures/payloads.py
index 973247b..5b5ae85 100644
--- a/federation/tests/fixtures/payloads.py
+++ b/federation/tests/fixtures/payloads.py
@@ -231,3 +231,41 @@ DIASPORA_CONTACT = """
<sharing>true</sharing>
</contact>
"""
+
+DIASPORA_RESHARE = """
+ <reshare>
+ <author>[email protected]</author>
+ <guid>a0b53e5029f6013487753131731751e9</guid>
+ <created_at>2016-07-12T00:36:42Z</created_at>
+ <provider_display_name/>
+ <root_author>[email protected]</root_author>
+ <root_guid>a0b53bc029f6013487753131731751e9</root_guid>
+ <public>true</public>
+ </reshare>
+"""
+
+DIASPORA_RESHARE_LEGACY = """
+ <reshare>
+ <diaspora_handle>[email protected]</diaspora_handle>
+ <guid>a0b53e5029f6013487753131731751e9</guid>
+ <created_at>2016-07-12T00:36:42Z</created_at>
+ <provider_display_name/>
+ <root_diaspora_id>[email protected]</root_diaspora_id>
+ <root_guid>a0b53bc029f6013487753131731751e9</root_guid>
+ <public>true</public>
+ </reshare>
+"""
+
+DIASPORA_RESHARE_WITH_EXTRA_PROPERTIES = """
+ <reshare>
+ <author>[email protected]</author>
+ <guid>a0b53e5029f6013487753131731751e9</guid>
+ <created_at>2016-07-12T00:36:42Z</created_at>
+ <provider_display_name/>
+ <root_author>[email protected]</root_author>
+ <root_guid>a0b53bc029f6013487753131731751e9</root_guid>
+ <public>true</public>
+ <raw_content>Important note here</raw_content>
+ <entity_type>Comment</entity_type>
+ </reshare>
+"""
| {
"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": 3,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 6
} | 0.14 | {
"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-warnings"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"dev-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
arrow==1.2.3
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
codecov==2.1.13
colorama==0.4.5
commonmark==0.9.1
coverage==6.2
cssselect==1.1.0
dirty-validators==0.5.4
docutils==0.18.1
factory-boy==3.2.1
Faker==14.2.1
-e git+https://github.com/jaywink/federation.git@ebacea83b0d70f8e63ffacdf113f05600acc6451#egg=federation
freezegun==1.2.2
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
iniconfig==1.1.1
isodate==0.6.1
Jinja2==3.0.3
jsonschema==3.2.0
livereload==2.6.3
lxml==5.3.1
MarkupSafe==2.0.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycrypto==2.6.1
Pygments==2.14.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
pytest-cov==4.0.0
pytest-warnings==0.3.1
python-dateutil==2.9.0.post0
python-xrd==0.1
pytz==2025.2
recommonmark==0.7.1
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-autobuild==2021.3.14
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
tornado==6.1
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: federation
channels:
- defaults
- https://repo.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
- arrow==1.2.3
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- codecov==2.1.13
- colorama==0.4.5
- commonmark==0.9.1
- coverage==6.2
- cssselect==1.1.0
- dirty-validators==0.5.4
- docutils==0.18.1
- factory-boy==3.2.1
- faker==14.2.1
- freezegun==1.2.2
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- isodate==0.6.1
- jinja2==3.0.3
- jsonschema==3.2.0
- livereload==2.6.3
- lxml==5.3.1
- markupsafe==2.0.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycrypto==2.6.1
- pygments==2.14.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-warnings==0.3.1
- python-dateutil==2.9.0.post0
- python-xrd==0.1
- pytz==2025.2
- recommonmark==0.7.1
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-autobuild==2021.3.14
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- tornado==6.1
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/federation
| [
"federation/tests/entities/diaspora/test_entities.py::TestEntitiesConvertToXML::test_post_to_xml",
"federation/tests/entities/diaspora/test_entities.py::TestEntitiesConvertToXML::test_comment_to_xml",
"federation/tests/entities/diaspora/test_entities.py::TestEntitiesConvertToXML::test_like_to_xml",
"federation/tests/entities/diaspora/test_entities.py::TestEntitiesConvertToXML::test_request_to_xml",
"federation/tests/entities/diaspora/test_entities.py::TestEntitiesConvertToXML::test_profile_to_xml",
"federation/tests/entities/diaspora/test_entities.py::TestEntitiesConvertToXML::test_retraction_to_xml",
"federation/tests/entities/diaspora/test_entities.py::TestEntitiesConvertToXML::test_contact_to_xml",
"federation/tests/entities/diaspora/test_entities.py::TestEntitiesConvertToXML::test_reshare_to_xml",
"federation/tests/entities/diaspora/test_entities.py::TestDiasporaProfileFillExtraAttributes::test_raises_if_no_handle",
"federation/tests/entities/diaspora/test_entities.py::TestDiasporaProfileFillExtraAttributes::test_calls_retrieve_and_parse_profile",
"federation/tests/entities/diaspora/test_entities.py::TestDiasporaRetractionEntityConverters::test_entity_type_from_remote",
"federation/tests/entities/diaspora/test_entities.py::TestDiasporaRetractionEntityConverters::test_entity_type_to_remote",
"federation/tests/entities/diaspora/test_entities.py::TestDiasporaRelayableMixin::test_signing_comment_works",
"federation/tests/entities/diaspora/test_entities.py::TestDiasporaRelayableMixin::test_signing_like_works",
"federation/tests/entities/diaspora/test_entities.py::TestDiasporaRelayableMixin::test_sign_with_parent",
"federation/tests/entities/diaspora/test_entities.py::TestDiasporaRelayableEntityValidate::test_raises_if_no_sender_key",
"federation/tests/entities/diaspora/test_entities.py::TestDiasporaRelayableEntityValidate::test_calls_verify_signature",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_simple_post",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_post_legacy",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_legact_timestamp",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_post_with_photos",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_comment",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_like",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_request",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_profile",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_profile_survives_empty_tag_string",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_retraction",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_retraction_legacy_request",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_contact",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_reshare",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_reshare_legacy",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_message_to_objects_reshare_extra_properties",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_invalid_entity_logs_an_error",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_adds_source_protocol_to_entity",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_source_object",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_element_to_objects_calls_sender_key_fetcher",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_element_to_objects_calls_retrieve_remote_profile",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_element_to_objects_verifies_handles_are_the_same",
"federation/tests/entities/diaspora/test_mappers.py::TestDiasporaEntityMappersReceive::test_element_to_objects_returns_no_entity_if_handles_are_different",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_already_fine_entities_are_returned_as_is",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_post_is_converted_to_diasporapost",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_comment_is_converted_to_diasporacomment",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_reaction_of_like_is_converted_to_diasporalike",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_relationship_of_sharing_or_following_is_converted_to_diasporarequest",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_profile_is_converted_to_diasporaprofile",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_other_reaction_raises",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_other_relation_raises",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_retraction_is_converted_to_diasporaretraction",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_follow_is_converted_to_diasporacontact",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_share_is_converted_to_diasporareshare",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_signs_relayable_if_no_signature",
"federation/tests/entities/diaspora/test_mappers.py::TestGetOutboundEntity::test_returns_entity_if_outbound_doc_on_entity",
"federation/tests/entities/diaspora/test_mappers.py::test_check_sender_and_entity_handle_match",
"federation/tests/entities/test_base.py::TestPostEntityTags::test_post_entity_returns_list_of_tags",
"federation/tests/entities/test_base.py::TestPostEntityTags::test_post_entity_without_raw_content_tags_returns_empty_set",
"federation/tests/entities/test_base.py::TestBaseEntityCallsValidateMethods::test_entity_calls_attribute_validate_method",
"federation/tests/entities/test_base.py::TestBaseEntityCallsValidateMethods::test_entity_calls_main_validate_methods",
"federation/tests/entities/test_base.py::TestBaseEntityCallsValidateMethods::test_validate_children",
"federation/tests/entities/test_base.py::TestGUIDMixinValidate::test_validate_guid_raises_on_low_length",
"federation/tests/entities/test_base.py::TestHandleMixinValidate::test_validate_handle_raises_on_invalid_format",
"federation/tests/entities/test_base.py::TestTargetHandleMixinValidate::test_validate_target_handle_raises_on_invalid_format",
"federation/tests/entities/test_base.py::TestPublicMixinValidate::test_validate_public_raises_on_low_length",
"federation/tests/entities/test_base.py::TestEntityRequiredAttributes::test_entity_checks_for_required_attributes",
"federation/tests/entities/test_base.py::TestEntityRequiredAttributes::test_validate_checks_required_values_are_not_empty",
"federation/tests/entities/test_base.py::TestRelationshipEntity::test_instance_creation",
"federation/tests/entities/test_base.py::TestRelationshipEntity::test_instance_creation_validates_relationship_value",
"federation/tests/entities/test_base.py::TestProfileEntity::test_instance_creation",
"federation/tests/entities/test_base.py::TestProfileEntity::test_instance_creation_validates_email_value",
"federation/tests/entities/test_base.py::TestProfileEntity::test_guid_is_mandatory",
"federation/tests/entities/test_base.py::TestImageEntity::test_instance_creation",
"federation/tests/entities/test_base.py::TestImageEntity::test_required_fields",
"federation/tests/entities/test_base.py::TestRetractionEntity::test_instance_creation",
"federation/tests/entities/test_base.py::TestRetractionEntity::test_required_validates",
"federation/tests/entities/test_base.py::TestFollowEntity::test_instance_creation",
"federation/tests/entities/test_base.py::TestShareEntity::test_instance_creation"
]
| []
| []
| []
| BSD 3-Clause "New" or "Revised" License | 1,595 | [
"federation/entities/diaspora/mappers.py",
"CHANGELOG.md",
"federation/entities/base.py",
"docs/protocols.rst",
"federation/entities/diaspora/entities.py",
"docs/usage.rst"
]
| [
"federation/entities/diaspora/mappers.py",
"CHANGELOG.md",
"federation/entities/base.py",
"docs/protocols.rst",
"federation/entities/diaspora/entities.py",
"docs/usage.rst"
]
|
itamarst__crochet-116 | 2b87285f527cc04cad7ea903477cd03a001e5229 | 2017-08-17 18:44:07 | 2b87285f527cc04cad7ea903477cd03a001e5229 | diff --git a/.gitignore b/.gitignore
index 0aa7ffd..73363d6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,4 +15,5 @@ MANIFEST
# Documentation
docs/_build
-build/
\ No newline at end of file
+build/
+.tox
\ No newline at end of file
diff --git a/crochet/_eventloop.py b/crochet/_eventloop.py
index 93a21dc..00c99d1 100644
--- a/crochet/_eventloop.py
+++ b/crochet/_eventloop.py
@@ -5,7 +5,6 @@ Expose Twisted's event loop to threaded programs.
from __future__ import absolute_import
import select
-import sys
import threading
import weakref
import warnings
@@ -463,15 +462,11 @@ class EventLoop(object):
When the wrapped function is called, an EventualResult is returned.
"""
result = self._run_in_reactor(function)
- # Backwards compatibility; we could have used wrapt's version, but
- # older Crochet code exposed different attribute name:
+ # Backwards compatibility; use __wrapped__ instead.
try:
result.wrapped_function = function
except AttributeError:
- if sys.version_info[0] == 3:
- raise
- # In Python 2 e.g. classmethod has some limitations where you can't
- # set stuff on it.
+ pass
return result
def wait_for_reactor(self, function):
@@ -518,14 +513,12 @@ class EventLoop(object):
raise
result = wrapper(function)
- # Expose underling function for testing purposes:
+ # Expose underling function for testing purposes; this attribute is
+ # deprecated, use __wrapped__ instead:
try:
result.wrapped_function = function
except AttributeError:
- if sys.version_info[0] == 3:
- raise
- # In Python 2 e.g. classmethod has some limitations where you
- # can't set stuff on it.
+ pass
return result
return decorator
diff --git a/docs/api.rst b/docs/api.rst
index 7e99681..15d6700 100644
--- a/docs/api.rst
+++ b/docs/api.rst
@@ -162,14 +162,14 @@ Unit testing
^^^^^^^^^^^^
Both ``@wait_for`` and ``@run_in_reactor`` expose the underlying Twisted
-function via a ``wrapped_function`` attribute. This allows unit testing of the
+function via a ``__wrapped__`` attribute. This allows unit testing of the
Twisted code without having to go through the Crochet layer.
.. literalinclude:: ../examples/testing.py
When run, this gives the following output::
- add() returns EventualResult:
+ add(1, 2) returns EventualResult:
<crochet._eventloop.EventualResult object at 0x2e8b390>
- add.wrapped_function() returns result of underlying function:
+ add.__wrapped__(1, 2) returns result of underlying function:
3
diff --git a/docs/news.rst b/docs/news.rst
index 23365a3..0b664bb 100644
--- a/docs/news.rst
+++ b/docs/news.rst
@@ -1,6 +1,23 @@
What's New
==========
+1.9.0
+^^^^^
+
+New features:
+
+* The underlying callable wrapped ``@run_in_reactor`` and ``@wait_for`` is now available via the more standard ``__wrapped__`` attribute.
+
+Backwards incompatibility (in tests):
+
+* This was actually introduced in 1.8.0: ``wrapped_function`` may not always be available on decorated callables.
+ You should use ``__wrapped__`` instead.
+
+Bug fixes:
+
+* Fixed regression in 1.8.0 where bound method couldn't be wrapped.
+ Thanks to 2mf for the bug report.
+
1.8.0
^^^^^
@@ -23,7 +40,7 @@ Bug fixes:
Bug fixes:
-* If the Python `logging.Handler` throws an exception Crochet no longer goes into a death spiral.
+* If the Python ``logging.Handler`` throws an exception Crochet no longer goes into a death spiral.
Thanks to Michael Schlenker for the bug report.
Removed features:
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..5b1a12b
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,17 @@
+[tox]
+envlist = py27, py35, lint3
+usedevelop = true
+
+[testenv]
+commands =
+ {envpython} setup.py --version
+ pip install .
+ {envpython} -m unittest {posargs:discover -v crochet.tests}
+
+[testenv:lint3]
+deps = flake8
+ pylint
+ yapf
+basepython = python3.5
+commands = flake8 crochet
+ pylint crochet
\ No newline at end of file
| Error using "run_in_reactor" in 1.8.0 that worked well in 1.7.0
use case:
```
@defer.inlineCallbacks
def do_stomething():
yield do_something_else()
crochet.run_in_reactor(do_something)().wait()
```
exception in 1.8.0:
```
def run_in_reactor(self, function):
"""
A decorator that ensures the wrapped function runs in the
reactor thread.
When the wrapped function is called, an EventualResult is returned.
"""
result = self._run_in_reactor(function)
# Backwards compatibility; we could have used wrapt's version, but
# older Crochet code exposed different attribute name:
try:
> result.wrapped_function = function
E AttributeError: 'method' object has no attribute 'wrapped_function'
/usr/local/pyenv/versions/3.6.1/envs/python36/lib/python3.6/site-packages/crochet/_eventloop.py:469: AttributeError
``` | itamarst/crochet | diff --git a/crochet/tests/test_api.py b/crochet/tests/test_api.py
index 3e2220d..b41b20c 100644
--- a/crochet/tests/test_api.py
+++ b/crochet/tests/test_api.py
@@ -728,6 +728,23 @@ class RunInReactorTests(TestCase):
C.func2(1, 2, c=3)
self.assertEqual(calls, [(C, 1, 2, 3), (C, 1, 2, 3)])
+ def test_wrap_method(self):
+ """
+ The object decorated with the wait decorator can be a method object
+ """
+ myreactor = FakeReactor()
+ c = EventLoop(lambda: myreactor, lambda f, g: None)
+ c.no_setup()
+ calls = []
+
+ class C(object):
+ def func(self, a, b, c):
+ calls.append((a, b, c))
+
+ f = c.run_in_reactor(C().func)
+ f(4, 5, c=6)
+ self.assertEqual(calls, [(4, 5, 6)])
+
def make_wrapped_function(self):
"""
Return a function wrapped with run_in_reactor that returns its first
@@ -809,7 +826,8 @@ class RunInReactorTests(TestCase):
def test_wrapped_function(self):
"""
The function wrapped by @run_in_reactor can be accessed via the
- `wrapped_function` attribute.
+ `__wrapped__` attribute and the `wrapped_function` attribute
+ (deprecated, and not always available).
"""
c = EventLoop(lambda: None, lambda f, g: None)
@@ -817,6 +835,7 @@ class RunInReactorTests(TestCase):
pass
wrapper = c.run_in_reactor(func)
+ self.assertIdentical(wrapper.__wrapped__, func)
self.assertIdentical(wrapper.wrapped_function, func)
@@ -881,7 +900,7 @@ class WaitTestsMixin(object):
def test_wrapped_function(self):
"""
The function wrapped by the wait decorator can be accessed via the
- `wrapped_function` attribute.
+ `__wrapped__`, and the deprecated `wrapped_function` attribute.
"""
decorator = self.decorator()
@@ -889,6 +908,7 @@ class WaitTestsMixin(object):
pass
wrapper = decorator(func)
+ self.assertIdentical(wrapper.__wrapped__, func)
self.assertIdentical(wrapper.wrapped_function, func)
def test_reactor_thread_disallowed(self):
diff --git a/examples/testing.py b/examples/testing.py
index cded7dc..7db5696 100644
--- a/examples/testing.py
+++ b/examples/testing.py
@@ -14,7 +14,7 @@ def add(x, y):
if __name__ == '__main__':
- print("add() returns EventualResult:")
+ print("add(1, 2) returns EventualResult:")
print(" ", add(1, 2))
- print("add.wrapped_function() returns result of underlying function:")
- print(" ", add.wrapped_function(1, 2))
+ print("add.__wrapped__(1, 2) is the result of the underlying function:")
+ print(" ", add.__wrapped__(1, 2))
| {
"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": 1,
"test_score": 2
},
"num_modified_files": 4
} | 1.8 | {
"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": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs @ file:///croot/attrs_1668696182826/work
Automat==22.10.0
certifi @ file:///croot/certifi_1671487769961/work/certifi
constantly==15.1.0
-e git+https://github.com/itamarst/crochet.git@2b87285f527cc04cad7ea903477cd03a001e5229#egg=crochet
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
hyperlink==21.0.0
idna==3.10
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1648562407465/work
incremental==22.10.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
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
six==1.17.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
Twisted==23.8.0
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
wrapt==1.16.0
zipp @ file:///croot/zipp_1672387121353/work
zope.interface==6.4.post2
| name: crochet
channels:
- defaults
- https://repo.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:
- automat==22.10.0
- constantly==15.1.0
- hyperlink==21.0.0
- idna==3.10
- incremental==22.10.0
- six==1.17.0
- twisted==23.8.0
- wrapt==1.16.0
- zope-interface==6.4.post2
prefix: /opt/conda/envs/crochet
| [
"crochet/tests/test_api.py::RunInReactorTests::test_wrap_method"
]
| [
"crochet/tests/test_api.py::ResultRegistryTests::test_runs_with_lock",
"crochet/tests/test_api.py::PublicAPITests::test_eventloop_api_reactor"
]
| [
"crochet/tests/test_api.py::ResultRegistryTests::test_stopped_already_have_result",
"crochet/tests/test_api.py::ResultRegistryTests::test_stopped_new_registration",
"crochet/tests/test_api.py::ResultRegistryTests::test_stopped_registered",
"crochet/tests/test_api.py::ResultRegistryTests::test_weakref",
"crochet/tests/test_api.py::EventualResultTests::test_cancel",
"crochet/tests/test_api.py::EventualResultTests::test_connect_deferred",
"crochet/tests/test_api.py::EventualResultTests::test_control_c_is_possible",
"crochet/tests/test_api.py::EventualResultTests::test_error_after_gc_logged",
"crochet/tests/test_api.py::EventualResultTests::test_error_logged_no_wait",
"crochet/tests/test_api.py::EventualResultTests::test_error_logged_wait_timeout",
"crochet/tests/test_api.py::EventualResultTests::test_failure_result",
"crochet/tests/test_api.py::EventualResultTests::test_failure_result_twice",
"crochet/tests/test_api.py::EventualResultTests::test_immediate_cancel",
"crochet/tests/test_api.py::EventualResultTests::test_later_failure_result",
"crochet/tests/test_api.py::EventualResultTests::test_later_success_result",
"crochet/tests/test_api.py::EventualResultTests::test_original_failure",
"crochet/tests/test_api.py::EventualResultTests::test_original_failure_no_result",
"crochet/tests/test_api.py::EventualResultTests::test_original_failure_not_error",
"crochet/tests/test_api.py::EventualResultTests::test_reactor_stop_unblocks_EventualResult",
"crochet/tests/test_api.py::EventualResultTests::test_reactor_stop_unblocks_EventualResult_in_threadpool",
"crochet/tests/test_api.py::EventualResultTests::test_reactor_thread_disallowed",
"crochet/tests/test_api.py::EventualResultTests::test_stash",
"crochet/tests/test_api.py::EventualResultTests::test_success_result",
"crochet/tests/test_api.py::EventualResultTests::test_success_result_twice",
"crochet/tests/test_api.py::EventualResultTests::test_timeout",
"crochet/tests/test_api.py::EventualResultTests::test_timeout_then_result",
"crochet/tests/test_api.py::EventualResultTests::test_timeout_twice",
"crochet/tests/test_api.py::EventualResultTests::test_waiting_during_different_thread_importing",
"crochet/tests/test_api.py::InReactorTests::test_in_reactor_thread",
"crochet/tests/test_api.py::InReactorTests::test_name",
"crochet/tests/test_api.py::InReactorTests::test_run_in_reactor_wrapper",
"crochet/tests/test_api.py::RunInReactorTests::test_classmethod",
"crochet/tests/test_api.py::RunInReactorTests::test_deferred_failure_result",
"crochet/tests/test_api.py::RunInReactorTests::test_deferred_success_result",
"crochet/tests/test_api.py::RunInReactorTests::test_exception_result",
"crochet/tests/test_api.py::RunInReactorTests::test_method",
"crochet/tests/test_api.py::RunInReactorTests::test_name",
"crochet/tests/test_api.py::RunInReactorTests::test_registry",
"crochet/tests/test_api.py::RunInReactorTests::test_regular_result",
"crochet/tests/test_api.py::RunInReactorTests::test_run_in_reactor_thread",
"crochet/tests/test_api.py::RunInReactorTests::test_signature",
"crochet/tests/test_api.py::RunInReactorTests::test_wrapped_function",
"crochet/tests/test_api.py::WaitForReactorTests::test_arguments",
"crochet/tests/test_api.py::WaitForReactorTests::test_classmethod",
"crochet/tests/test_api.py::WaitForReactorTests::test_control_c_is_possible",
"crochet/tests/test_api.py::WaitForReactorTests::test_deferred_failure_result",
"crochet/tests/test_api.py::WaitForReactorTests::test_deferred_success_result",
"crochet/tests/test_api.py::WaitForReactorTests::test_exception_result",
"crochet/tests/test_api.py::WaitForReactorTests::test_name",
"crochet/tests/test_api.py::WaitForReactorTests::test_reactor_stop_unblocks",
"crochet/tests/test_api.py::WaitForReactorTests::test_reactor_thread_disallowed",
"crochet/tests/test_api.py::WaitForReactorTests::test_regular_result",
"crochet/tests/test_api.py::WaitForReactorTests::test_signature",
"crochet/tests/test_api.py::WaitForReactorTests::test_wait_for_reactor_thread",
"crochet/tests/test_api.py::WaitForReactorTests::test_wrapped_function",
"crochet/tests/test_api.py::WaitForTests::test_arguments",
"crochet/tests/test_api.py::WaitForTests::test_classmethod",
"crochet/tests/test_api.py::WaitForTests::test_control_c_is_possible",
"crochet/tests/test_api.py::WaitForTests::test_deferred_failure_result",
"crochet/tests/test_api.py::WaitForTests::test_deferred_success_result",
"crochet/tests/test_api.py::WaitForTests::test_exception_result",
"crochet/tests/test_api.py::WaitForTests::test_name",
"crochet/tests/test_api.py::WaitForTests::test_reactor_stop_unblocks",
"crochet/tests/test_api.py::WaitForTests::test_reactor_thread_disallowed",
"crochet/tests/test_api.py::WaitForTests::test_regular_result",
"crochet/tests/test_api.py::WaitForTests::test_signature",
"crochet/tests/test_api.py::WaitForTests::test_timeoutCancels",
"crochet/tests/test_api.py::WaitForTests::test_timeoutRaises",
"crochet/tests/test_api.py::WaitForTests::test_wait_for_reactor_thread",
"crochet/tests/test_api.py::WaitForTests::test_wrapped_function",
"crochet/tests/test_api.py::PublicAPITests::test_eventloop_api",
"crochet/tests/test_api.py::PublicAPITests::test_no_sideeffects",
"crochet/tests/test_api.py::PublicAPITests::test_reapAllProcesses",
"crochet/tests/test_api.py::PublicAPITests::test_retrieve_result"
]
| []
| MIT License | 1,596 | [
"docs/news.rst",
"crochet/_eventloop.py",
".gitignore",
"tox.ini",
"docs/api.rst"
]
| [
"docs/news.rst",
"crochet/_eventloop.py",
".gitignore",
"tox.ini",
"docs/api.rst"
]
|
|
vertexproject__synapse-404 | 29a6d4587a6f6d177337f6816337c2b7b7a4d97d | 2017-08-18 14:58:00 | 6f5fc661a88b8cc3f4befb2c9c7ddcebf0b89ba0 | codecov[bot]: # [Codecov](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=h1) Report
> Merging [#404](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=desc) into [master](https://codecov.io/gh/vertexproject/synapse/commit/6c0d7366920ea5b5bdc39172f81bc951d0ea976f?src=pr&el=desc) will **decrease** coverage by `0.03%`.
> The diff coverage is `100%`.
[](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #404 +/- ##
==========================================
- Coverage 90.45% 90.41% -0.04%
==========================================
Files 127 127
Lines 14369 14369
==========================================
- Hits 12997 12992 -5
- Misses 1372 1377 +5
```
| [Impacted Files](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [synapse/models/inet.py](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=tree#diff-c3luYXBzZS9tb2RlbHMvaW5ldC5weQ==) | `98.42% <100%> (ø)` | :arrow_up: |
| [synapse/lib/socket.py](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=tree#diff-c3luYXBzZS9saWIvc29ja2V0LnB5) | `83.56% <0%> (-1.14%)` | :arrow_down: |
| [synapse/links/ssl.py](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=tree#diff-c3luYXBzZS9saW5rcy9zc2wucHk=) | `86.71% <0%> (-0.79%)` | :arrow_down: |
| [synapse/daemon.py](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=tree#diff-c3luYXBzZS9kYWVtb24ucHk=) | `83.22% <0%> (-0.21%)` | :arrow_down: |
| [synapse/cores/common.py](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=tree#diff-c3luYXBzZS9jb3Jlcy9jb21tb24ucHk=) | `94.07% <0%> (+0.08%)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=footer). Last update [6c0d736...8f4b785](https://codecov.io/gh/vertexproject/synapse/pull/404?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
| diff --git a/synapse/lib/types.py b/synapse/lib/types.py
index d3691b459..26250328c 100644
--- a/synapse/lib/types.py
+++ b/synapse/lib/types.py
@@ -109,7 +109,8 @@ class GuidType(DataType):
# ( sigh... eventually everything will be a cortex... )
node = self._getTufoByProp(self._guid_alias, valu[1:])
if node is None:
- self._raiseBadValu(valu, mesg='no result for guid resolver')
+ self._raiseBadValu(valu, mesg='no result for guid resolver',
+ alias=self._guid_alias)
iden = node[1].get(node[1].get('tufo:form'))
return iden, {}
diff --git a/synapse/models/inet.py b/synapse/models/inet.py
index 2d949fa32..97d9311f8 100644
--- a/synapse/models/inet.py
+++ b/synapse/models/inet.py
@@ -320,7 +320,6 @@ class CidrType(DataType):
return valu
class InetMod(CoreModule):
-
def initCoreModule(self):
# add an inet:defang cast to swap [.] to .
self.core.addTypeCast('inet:defang', castInetDeFang)
@@ -401,6 +400,47 @@ class InetMod(CoreModule):
def _revModl201708231646(self):
pass # for legacy/backward compat
+ @modelrev('inet', 201709181501)
+ def _revModl201709181501(self):
+ '''
+ Replace inet:whois:rec:ns<int> rows with inet:whos:recns nodes.
+ '''
+ adds = []
+ srcprops = ('inet:whois:rec:ns1', 'inet:whois:rec:ns2', 'inet:whois:rec:ns3', 'inet:whois:rec:ns4')
+ delprops = set()
+
+ tick = s_common.now()
+
+ # We could use the joins API but we would have to still fold rows into tufos for the purpose of migration.
+ nodes = self.core.getTufosByProp('inet:whois:rec')
+
+ for node in nodes:
+ rec = node[1].get('inet:whois:rec')
+ for prop in srcprops:
+ ns = node[1].get(prop)
+ if not ns:
+ continue
+ delprops.add(prop)
+ iden = s_common.guid()
+ pprop = s_common.guid([ns, rec])
+ fqdn = node[1].get('inet:whois:rec:fqdn')
+ asof = node[1].get('inet:whois:rec:asof')
+ rows = [
+ (iden, 'tufo:form', 'inet:whois:recns', tick),
+ (iden, 'inet:whois:recns', pprop, tick),
+ (iden, 'inet:whois:recns:ns', ns, tick),
+ (iden, 'inet:whois:recns:rec', rec, tick),
+ (iden, 'inet:whois:recns:rec:fqdn', fqdn, tick),
+ (iden, 'inet:whois:recns:rec:asof', asof, tick),
+ ]
+ adds.extend(rows)
+
+ if adds:
+ self.core.addRows(adds)
+
+ for prop in delprops:
+ self.core.delRowsByProp(prop)
+
@staticmethod
def getBaseModels():
modl = {
@@ -454,6 +494,8 @@ class InetMod(CoreModule):
('inet:netuser', {'subof': 'sepr', 'sep': '/', 'fields': 'site,inet:fqdn|user,inet:user',
'doc': 'A user account at a given web address', 'ex': 'twitter.com/invisig0th'}),
+ ('inet:web:logon', {'subof': 'guid',
+ 'doc': 'An instance of a user account authenticating to a service.', }),
('inet:netgroup', {'subof': 'sepr', 'sep': '/', 'fields': 'site,inet:fqdn|name,ou:name',
'doc': 'A group within an online community'}),
@@ -478,6 +520,8 @@ class InetMod(CoreModule):
('inet:whois:rec',
{'subof': 'sepr', 'sep': '@', 'fields': 'fqdn,inet:fqdn|asof,time', 'doc': 'A whois record',
'ex': ''}),
+ ('inet:whois:recns', {'subof': 'comp', 'fields': 'ns,inet:fqdn|rec,inet:whois:rec',
+ 'doc': 'A nameserver associated with a given WHOIS record.'}),
('inet:whois:contact', {'subof': 'comp', 'fields': 'rec,inet:whois:rec|type,str:lwr',
'doc': 'A whois contact for a specific record'}),
@@ -525,6 +569,7 @@ class InetMod(CoreModule):
('inet:asn', {'ptype': 'inet:asn', 'doc': 'An Autonomous System'}, (
('name', {'ptype': 'str:lwr', 'defval': '??'}),
+ ('owner', {'ptype': 'ou:org', 'doc': 'Organization which controls an ASN'}),
)),
('inet:asnet4',
@@ -663,6 +708,16 @@ class InetMod(CoreModule):
('seen:max', {'ptype': 'time:max'}),
]),
+ ('inet:web:logon', {'ptype': 'inet:web:logon'}, [
+ ('netuser', {'ptype': 'inet:netuser', 'doc': 'The netuser associated with the logon event.', }),
+ ('netuser:site', {'ptype': 'inet:fqdn', }),
+ ('netuser:user', {'ptype': 'inet:user', }),
+ ('time', {'ptype': 'time', 'doc': 'The time the netuser logged into the service', }),
+ ('ipv4', {'ptype': 'inet:ipv4', 'doc': 'The source IPv4 address of the logon.'}),
+ ('ipv6', {'ptype': 'inet:ipv6', 'doc': 'The source IPv6 address of the logon.'}),
+ ('logout', {'ptype': 'time', 'doc': 'The time the netuser logged out of the service.'})
+ ]),
+
('inet:netgroup', {}, [
('site', {'ptype': 'inet:fqdn', 'ro': 1}),
('name', {'ptype': 'ou:name', 'ro': 1}),
@@ -760,10 +815,13 @@ class InetMod(CoreModule):
('expires', {'ptype': 'time', 'doc': 'The "expires" time from the whois record'}),
('registrar', {'ptype': 'inet:whois:rar', 'defval': '??'}),
('registrant', {'ptype': 'inet:whois:reg', 'defval': '??'}),
- ('ns1', {'ptype': 'inet:fqdn'}),
- ('ns2', {'ptype': 'inet:fqdn'}),
- ('ns3', {'ptype': 'inet:fqdn'}),
- ('ns4', {'ptype': 'inet:fqdn'}),
+ ]),
+
+ ('inet:whois:recns', {}, [
+ ('ns', {'ptype': 'inet:fqdn', 'ro': 1, 'doct': 'Nameserver for a given FQDN'}),
+ ('rec', {'ptype': 'inet:whois:rec', 'ro': 1}),
+ ('rec:fqdn', {'ptype': 'inet:fqdn', 'ro': 1}),
+ ('rec:asof', {'ptype': 'time', 'ro': 1}),
]),
('inet:whois:contact', {}, [
@@ -797,4 +855,4 @@ class InetMod(CoreModule):
),
}
name = 'inet'
- return ((name, modl), )
+ return ((name, modl),)
| need inet:netuser logon nodes to track sources and times | vertexproject/synapse | diff --git a/synapse/tests/test_model_inet.py b/synapse/tests/test_model_inet.py
index 2c07381e3..c8dda056c 100644
--- a/synapse/tests/test_model_inet.py
+++ b/synapse/tests/test_model_inet.py
@@ -70,6 +70,20 @@ class InetModelTest(SynTest):
self.nn(core.getTufoByProp('inet:ipv4', 0x01020304))
self.nn(core.getTufoByProp('inet:ipv4', 0x05060708))
+ o1 = core.formTufoByProp('ou:org', '*', alias='vertex')
+ _, o1pprop = s_tufo.ndef(o1)
+ t1 = core.formTufoByProp('inet:asn', 12345)
+ self.none(t1[1].get('inet:asn:owner'))
+ t1 = core.setTufoProps(t1, owner='$vertex')
+ self.eq(t1[1].get('inet:asn:owner'), o1pprop)
+ # TODO: Uncomment when we have a global alias resolver in place.
+ # self.nn(core.getTufoByProp('ou:alias', 'vertex'))
+ t2 = core.formTufoByProp('inet:asn', 12346, owner='$vertex')
+ self.eq(t2[1].get('inet:asn:owner'), o1pprop)
+ # Lift asn's by owner with guid resolver syntax
+ nodes = core.eval('inet:asn:owner=$vertex')
+ self.eq(len(nodes), 2)
+
def test_model_inet_fqdn(self):
with s_cortex.openurl('ram:///') as core:
t0 = core.formTufoByProp('inet:fqdn', 'com', sfx=1)
@@ -390,6 +404,23 @@ class InetModelTest(SynTest):
self.eq(len(core.eval('inet:whois:rec="woot.com@20501217"')), 1)
self.eq(len(core.eval('inet:whois:contact:rec="woot.com@20501217"')), 1)
+ def test_model_inet_whois_recns(self):
+ with s_cortex.openurl('ram:///') as core:
+ core.setConfOpt('enforce', 1)
+
+ node = core.formTufoByProp('inet:whois:rec', 'woot.com@20501217')
+ form, pprop = s_tufo.ndef(node)
+ node = core.formTufoByProp('inet:whois:recns', ['ns1.woot.com', pprop])
+ self.eq(node[1].get('inet:whois:recns:ns'), 'ns1.woot.com')
+ self.eq(node[1].get('inet:whois:recns:rec'), pprop)
+ self.eq(node[1].get('inet:whois:recns:rec:fqdn'), 'woot.com')
+ self.eq(node[1].get('inet:whois:recns:rec:asof'), 2554848000000)
+ nodes = core.eval('inet:whois:recns:rec:fqdn=woot.com')
+ self.eq(node[0], nodes[0][0])
+ nodes = core.eval('inet:whois:rec:fqdn=woot.com inet:whois:rec->inet:whois:recns:rec')
+ self.eq(len(nodes), 1)
+ self.eq(node[0], nodes[0][0])
+
def test_model_fqdn_punycode(self):
with s_cortex.openurl('ram:///') as core:
@@ -405,6 +436,34 @@ class InetModelTest(SynTest):
self.raises(BadTypeValu, core.getTypeNorm, 'inet:fqdn', '!@#$%')
+ def test_model_inet_weblogon(self):
+
+ with s_cortex.openurl('ram:///') as core:
+ core.setConfOpt('enforce', 1)
+ tick = now()
+
+ t0 = core.formTufoByProp('inet:web:logon', '*',
+ netuser='vertex.link/pennywise',
+ time=tick)
+
+ self.nn(t0)
+
+ self.eq(t0[1].get('inet:web:logon:time'), tick)
+ self.eq(t0[1].get('inet:web:logon:netuser'), 'vertex.link/pennywise')
+ self.eq(t0[1].get('inet:web:logon:netuser:user'), 'pennywise')
+ self.eq(t0[1].get('inet:web:logon:netuser:site'), 'vertex.link')
+
+ # Pivot from a netuser to the netlogon forms via storm
+ self.nn(core.getTufoByProp('inet:netuser', 'vertex.link/pennywise'))
+ nodes = core.eval('inet:netuser=vertex.link/pennywise inet:netuser -> inet:web:logon:netuser')
+ self.eq(len(nodes), 1)
+
+ t0 = core.setTufoProps(t0, ipv4=0x01020304, logout=tick + 1, ipv6='0:0:0:0:0:0:0:1')
+ self.eq(t0[1].get('inet:web:logon:ipv4'), 0x01020304)
+ self.eq(t0[1].get('inet:web:logon:logout'), tick + 1)
+ self.eq(t0[1].get('inet:web:logon:logout') - t0[1].get('inet:web:logon:time'), 1)
+ self.eq(t0[1].get('inet:web:logon:ipv6'), '::1')
+
def test_model_inet_201706121318(self):
iden0 = guid()
@@ -469,3 +528,49 @@ class InetModelTest(SynTest):
t2 = core.getTufoByIden(iden1)
self.eq(t2[1].get('inet:udp4:port'), 443)
self.eq(t2[1].get('inet:udp4:ipv4'), 0x01020304)
+
+ def test_model_inet_201709181501(self):
+ data = {}
+ iden0 = guid()
+ tick = now()
+ rows = [
+ (iden0, 'tufo:form', 'inet:whois:rec', tick),
+ (iden0, 'inet:whois:rec', 'vertex.link@2017/09/18 15:01:00.000', tick), # 1505746860000,
+ (iden0, 'inet:whois:rec:fqdn', 'vertex.link', tick),
+ (iden0, 'inet:whois:rec:asof', 1505746860000, tick),
+ (iden0, 'inet:whois:rec:ns1', 'ns1.vertex.link', tick),
+ (iden0, 'inet:whois:rec:ns2', 'ns2.vertex.link', tick),
+ (iden0, 'inet:whois:rec:ns3', 'ns3.vertex.link', tick),
+ (iden0, 'inet:whois:rec:ns4', 'ns4.vertex.link', tick),
+ ]
+
+ with s_cortex.openstore('ram:///') as stor:
+
+ # force model migration callbacks
+ stor.setModlVers('inet', 0)
+
+ def addrows(mesg):
+ stor.addRows(rows)
+ data['added'] = True
+ stor.on('modl:vers:rev', addrows, name='inet', vers=201709181501)
+
+ with s_cortex.fromstore(stor) as core:
+
+ t_guid, _ = core.getTypeNorm('inet:whois:recns', ['ns1.vertex.link',
+ 'vertex.link@2017/09/18 15:01:00.000'])
+
+ node = core.eval('inet:whois:rec')[0]
+ self.notin('inet:whois:rec:ns1', node[1])
+ self.notin('inet:whois:rec:ns2', node[1])
+ self.notin('inet:whois:rec:ns3', node[1])
+ self.notin('inet:whois:rec:ns4', node[1])
+
+ nodes = core.eval('inet:whois:recns')
+ self.eq(len(nodes), 4)
+
+ nodes = core.eval('inet:whois:recns={}'.format(t_guid))
+ self.eq(len(nodes), 1)
+ node = nodes[0]
+ self.eq(node[1].get('inet:whois:recns:ns'), 'ns1.vertex.link')
+ self.eq(node[1].get('inet:whois:recns:rec:fqdn'), 'vertex.link')
+ self.eq(node[1].get('inet:whois:recns:rec:asof'), 1505746860000)
| {
"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": 1,
"test_score": 2
},
"num_modified_files": 2
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "tornado>=3.2.2 cryptography>=1.7.2 pyOpenSSL>=16.2.0 msgpack-python>=0.4.2 xxhash>=1.0.1 lmdb>=0.92",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y build-essential libffi-dev libssl-dev python3 python3-dev python3-pip python3-setuptools"
],
"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
cffi @ file:///tmp/build/80754af9/cffi_1625814693874/work
cryptography @ file:///tmp/build/80754af9/cryptography_1635366128178/work
importlib-metadata==4.8.3
iniconfig==1.1.1
lmdb==1.6.2
msgpack @ file:///tmp/build/80754af9/msgpack-python_1612287171716/work
msgpack-python==0.5.6
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/work
pyOpenSSL @ file:///opt/conda/conda-bld/pyopenssl_1643788558760/work
pyparsing==3.1.4
pytest==7.0.1
-e git+https://github.com/vertexproject/synapse.git@29a6d4587a6f6d177337f6816337c2b7b7a4d97d#egg=synapse
tomli==1.2.3
tornado @ file:///tmp/build/80754af9/tornado_1606942266872/work
typing_extensions==4.1.1
xxhash==3.2.0
zipp==3.6.0
| name: synapse
channels:
- defaults
- https://repo.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
- cffi=1.14.6=py36h400218f_0
- cryptography=35.0.0=py36hd23ed53_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
- pycparser=2.21=pyhd3eb1b0_0
- pyopenssl=22.0.0=pyhd3eb1b0_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
- tornado=6.1=py36h27cfd23_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
- lmdb==1.6.2
- msgpack-python==0.5.6
- 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
- xxhash==3.2.0
- zipp==3.6.0
prefix: /opt/conda/envs/synapse
| [
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_201709181501",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_asnet4",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_weblogon",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_whois_recns"
]
| []
| [
"synapse/tests/test_model_inet.py::InetModelTest::test_model_fqdn_punycode",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_201706121318",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_201706201837",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_cast_defang",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_cidr4",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_email",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_follows",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_fqdn",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_fqdn_set_sfx",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_fqdn_unicode",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_ipv4",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_ipv4_raise",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_ipv6",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_mac",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_netmemb",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_netmesg",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_netpost",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_passwd",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_srv4_types",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_srv6_types",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_url_fields",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_urlfile",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_inet_whoisemail",
"synapse/tests/test_model_inet.py::InetModelTest::test_model_whois_contact"
]
| []
| Apache License 2.0 | 1,597 | [
"synapse/lib/types.py",
"synapse/models/inet.py"
]
| [
"synapse/lib/types.py",
"synapse/models/inet.py"
]
|
zopefoundation__zope.password-12 | d517a5a165a28336ae51c5e2dabea8a65390e586 | 2017-08-18 16:11:49 | 249f29a3adf8dec36bb4e8e65c7fb9724430f9b0 | diff --git a/CHANGES.rst b/CHANGES.rst
index c44b413..421388f 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -14,6 +14,8 @@
- Fix the ``zpasswd`` console script on Python 3.
+- Update the ``zpasswd`` script to use ``argparse`` instead of ``optparse.``
+
4.2.0 (2016-07-07)
==================
diff --git a/src/zope/password/zpasswd.py b/src/zope/password/zpasswd.py
index 70b6f9c..25d2433 100644
--- a/src/zope/password/zpasswd.py
+++ b/src/zope/password/zpasswd.py
@@ -14,7 +14,7 @@
"""Implementation of the zpasswd script.
"""
from __future__ import print_function
-import optparse
+import argparse
import os
import sys
from xml.sax.saxutils import quoteattr
@@ -156,7 +156,7 @@ class Application(object):
def process(self):
options = self.options
- destination = sys.stdout if not options.destination else open(options.destination, 'w')
+ destination = options.destination
try:
principal = self.get_principal()
@@ -269,20 +269,18 @@ def get_password_managers(config_path=None):
def parse_args(argv):
"""Parse the command line, returning an object representing the input."""
- _path, prog = os.path.split(os.path.realpath(argv[0]))
- p = optparse.OptionParser(prog=prog,
- usage="%prog [options]",
- version=VERSION)
- p.add_option("-c", "--config", dest="config", metavar="FILE",
- help=("path to the site.zcml configuration file"
- " (more accurate but slow password managers registry creation)"))
- p.add_option("-o", "--output", dest="destination", metavar="FILE",
- help=("the file in which the output will be saved"
- " (STDOUT by default)"))
- options, args = p.parse_args(argv[1:])
+ prog = os.path.split(os.path.realpath(argv[0]))[1]
+ p = argparse.ArgumentParser(prog=prog)
+ p.add_argument("-c", "--config", dest="config", metavar="FILE",
+ help=("path to the site.zcml configuration file"
+ " (more accurate but slow password managers registry creation)"))
+ p.add_argument("-o", "--output", dest="destination", metavar="FILE",
+ help=("the file in which the output will be saved"
+ " (STDOUT by default)"),
+ default=sys.stdout,
+ type=argparse.FileType('w'))
+ p.add_argument("--version", action="version", version=VERSION)
+ options = p.parse_args(argv[1:])
options.managers = get_password_managers(options.config)
options.program = prog
- options.version = VERSION
- if args:
- p.error("too many arguments")
return options
| Convert usage of optparse to argparse
optparse is deprecated. | zopefoundation/zope.password | diff --git a/src/zope/password/tests/test_zpasswd.py b/src/zope/password/tests/test_zpasswd.py
index b471a8c..3c33f66 100644
--- a/src/zope/password/tests/test_zpasswd.py
+++ b/src/zope/password/tests/test_zpasswd.py
@@ -17,6 +17,7 @@ import contextlib
import doctest
import os
import sys
+import tempfile
import unittest
import io
@@ -36,13 +37,13 @@ class TestBase(unittest.TestCase):
def setUp(self):
# Create a minimal site.zcml file
- with open('testsite.zcml', 'wb') as file:
- file.write(
+ with tempfile.NamedTemporaryFile(prefix="testsite",
+ suffix=".zcml",
+ delete=False) as f:
+ f.write(
b'<configure xmlns="http://namespaces.zope.org/zope"/>\n')
-
- def tearDown(self):
- # Clean up
- os.unlink('testsite.zcml')
+ self.config = f.name
+ self.addCleanup(os.remove, f.name)
@contextlib.contextmanager
def patched_stdio(self, input_data=None):
@@ -81,32 +82,36 @@ class TestBase(unittest.TestCase):
class ArgumentParsingTestCase(TestBase):
- config = "testsite.zcml"
-
def parse_args(self, args):
argv = ["foo/bar.py"] + args
with self.patched_stdio():
options = zpasswd.parse_args(argv)
+
self.assertEqual(options.program, "bar.py")
- self.assertTrue(options.version)
return options
- def check_stdout_content(self, args):
+ def check_stdout_content(self, args, stderr=False):
with self.assertRaises(SystemExit) as e:
self.parse_args(args)
e = e.exception
self.assertEqual(e.code, 0)
- self.assertTrue(self.stdout.getvalue())
- self.assertFalse(self.stderr.getvalue())
+ full = self.stdout
+ empty = self.stderr
+ if stderr:
+ full = self.stderr
+ empty = self.stdout
+ self.assertTrue(full.getvalue())
+ self.assertFalse(empty.getvalue())
def test_no_arguments(self):
options = self.parse_args([])
self.assertTrue(options.managers)
- self.assertFalse(options.destination)
+ self.assertIs(options.destination, self.stdout)
def test_version_long(self):
- self.check_stdout_content(["--version"])
+ self.check_stdout_content(["--version"],
+ stderr=sys.version_info[0] == 2)
def test_help_long(self):
self.check_stdout_content(["--help"])
@@ -114,13 +119,15 @@ class ArgumentParsingTestCase(TestBase):
def test_help_short(self):
self.check_stdout_content(["-h"])
- def test_destination_short(self):
- options = self.parse_args(["-o", "filename"])
- self.assertEqual(options.destination, "filename")
+ def test_destination_short(self, option="-o"):
+ handle, path = tempfile.mkstemp()
+ os.close(handle)
+ self.addCleanup(os.remove, path)
+ options = self.parse_args([option, path])
+ self.assertEqual(options.destination.name, path)
def test_destination_long(self):
- options = self.parse_args(["--output", "filename"])
- self.assertEqual(options.destination, "filename")
+ self.test_destination_short("--output")
def test_config_short(self):
options = self.parse_args(["-c", self.config])
@@ -134,7 +141,7 @@ class ArgumentParsingTestCase(TestBase):
with self.assertRaises(SystemExit):
self.parse_args(["--config", self.config, "extra stuff"])
- self.assertIn("too many arguments",
+ self.assertIn("unrecognized arguments",
self.stderr.getvalue())
def test_main(self):
@@ -163,11 +170,12 @@ class ControlledInputApplication(zpasswd.Application):
class Options(object):
config = None
- destination = None
- version = "[test-version]"
program = "[test-program]"
managers = password.managers
+ def __init__(self):
+ self.destination = sys.stdout
+
class InputCollectionTestCase(TestBase):
def createOptions(self):
@@ -185,7 +193,6 @@ class InputCollectionTestCase(TestBase):
self.assertEqual(line.strip(), expline)
def test_principal_information(self):
- options = self.createOptions()
apps = []
def factory(options):
app = ControlledInputApplication(
@@ -195,6 +202,7 @@ class InputCollectionTestCase(TestBase):
apps.append(app)
return app
with self.patched_stdio():
+ options = self.createOptions()
zpasswd.run_app_with_options(options, factory)
self.assertFalse(self.stderr.getvalue())
self.assertTrue(apps[0].all_input_consumed())
@@ -214,16 +222,16 @@ class TestDestination(InputCollectionTestCase):
destination = None
def createOptions(self):
- import tempfile
opts = Options()
- handle, destination = tempfile.mkstemp('.test_zpasswd')
- self.addCleanup(lambda: os.remove(destination))
- os.close(handle)
+ destination = tempfile.NamedTemporaryFile(mode='w',
+ suffix=".test_zpasswd",
+ delete=False)
+ self.addCleanup(os.remove, destination.name)
self.destination = opts.destination = destination
return opts
def _get_output(self):
- with open(self.destination) as f:
+ with open(self.destination.name) as f:
return f.read()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 2
} | 4.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"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"
} | bcrypt==4.3.0
coverage==7.8.0
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
zope.component==6.0
zope.configuration==6.0
zope.event==5.0
zope.exceptions==5.2
zope.hookable==7.0
zope.i18nmessageid==7.0
zope.interface==7.2
-e git+https://github.com/zopefoundation/zope.password.git@d517a5a165a28336ae51c5e2dabea8a65390e586#egg=zope.password
zope.schema==7.0.1
zope.testing==5.1
zope.testrunner==7.2
| name: zope.password
channels:
- defaults
- https://repo.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:
- bcrypt==4.3.0
- coverage==7.8.0
- zope-component==6.0
- zope-configuration==6.0
- zope-event==5.0
- zope-exceptions==5.2
- zope-hookable==7.0
- zope-i18nmessageid==7.0
- zope-interface==7.2
- zope-schema==7.0.1
- zope-testing==5.1
- zope-testrunner==7.2
prefix: /opt/conda/envs/zope.password
| [
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_destination_long",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_destination_short",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_no_arguments",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_too_many_arguments",
"src/zope/password/tests/test_zpasswd.py::InputCollectionTestCase::test_principal_information",
"src/zope/password/tests/test_zpasswd.py::TestDestination::test_principal_information"
]
| []
| [
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_config_long",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_config_short",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_help_long",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_help_short",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_main",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_version_long",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_exit",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_passwd_empty",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_passwd_spaces",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_passwd_verify_fail",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_password_manager_bad",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_password_manager_default",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_value",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_keyboard_interrupt",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_read_input",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_read_password",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_read_password_cancel",
"src/zope/password/tests/test_zpasswd.py::test_suite"
]
| []
| Zope Public License 2.1 | 1,598 | [
"src/zope/password/zpasswd.py",
"CHANGES.rst"
]
| [
"src/zope/password/zpasswd.py",
"CHANGES.rst"
]
|
|
zopefoundation__zope.password-13 | f18b5f9371ceb5e7af68c917f2ae9f7de3d91cad | 2017-08-18 18:40:47 | 249f29a3adf8dec36bb4e8e65c7fb9724430f9b0 | jamadden: I'm seeing [a mysterious drop in coverage](https://coveralls.io/builds/12899080/source?filename=src%2Fzope%2Fpassword%2Fzpasswd.py#L262) in `zpasswd.py`. I'm not sure why or how that happened...my best guess is that it's something to do with the cleanup code tearing down the component registry, which would suggest that we were relying on an accidental side-effect before.
I can fix it, but I'd hope that #12 gets merged first, otherwise there will be conflicts. | diff --git a/CHANGES.rst b/CHANGES.rst
index 421388f..1375b4f 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -5,8 +5,13 @@
4.3.0 (unreleased)
==================
-- Added a ``bcrypt``-based password manager (available only if the ``bcrypt``
- library is importable).
+- Added a ``bcrypt``-based password manager (available only if the
+ `bcrypt <https://pypi.python.org/pypi/bcrypt>`_ library is
+ importable). This manager can also check passwords that were encoded
+ with `z3c.bcrypt <https://pypi.python.org/pypi/z3c.bcrypt>`_. If
+ that package is *not* installed, then ``configure.zcml`` will
+ install this manager as a utility with both the ``BCRYPT``
+ (preferred) and ``bcrypt`` names for compatibility with it.
- Add support for Python 3.6.
diff --git a/src/zope/password/configure.zcml b/src/zope/password/configure.zcml
index 035c27f..26e2362 100644
--- a/src/zope/password/configure.zcml
+++ b/src/zope/password/configure.zcml
@@ -3,6 +3,8 @@
xmlns:zcml="http://namespaces.zope.org/zcml"
>
+ <include package="zope.component" file="meta.zcml" />
+
<utility
name="Plain Text"
provides=".interfaces.IMatchingPasswordManager"
@@ -45,6 +47,16 @@
provides=".interfaces.IMatchingPasswordManager"
factory=".password.BCRYPTPasswordManager"
/>
+ <!--
+ Also install it under the same name as z3c.bcrypt does
+ for compatibility with that library.
+ -->
+ <utility
+ zcml:condition="not-installed z3c.bcrypt"
+ name="bcrypt"
+ provides=".interfaces.IMatchingPasswordManager"
+ factory=".password.BCRYPTPasswordManager"
+ />
</configure>
<configure zcml:condition="installed crypt">
diff --git a/src/zope/password/legacy.py b/src/zope/password/legacy.py
index 703d02b..5721755 100644
--- a/src/zope/password/legacy.py
+++ b/src/zope/password/legacy.py
@@ -32,98 +32,97 @@ _encoder = getencoder("utf-8")
PY2 = sys.version_info[0] == 2
-if crypt is not None:
- @implementer(IMatchingPasswordManager)
- class CryptPasswordManager(object):
- """Crypt password manager.
+@implementer(IMatchingPasswordManager)
+class CryptPasswordManager(object):
+ """Crypt password manager.
- Implements a UNIX crypt(3) hashing scheme. Note that crypt is
- considered far inferior to more modern schemes such as SSHA hashing,
- and only uses the first 8 characters of a password.
+ Implements a UNIX crypt(3) hashing scheme. Note that crypt is
+ considered far inferior to more modern schemes such as SSHA hashing,
+ and only uses the first 8 characters of a password.
- >>> from zope.interface.verify import verifyObject
- >>> from zope.password.interfaces import IMatchingPasswordManager
- >>> from zope.password.legacy import CryptPasswordManager
+ >>> from zope.interface.verify import verifyObject
+ >>> from zope.password.interfaces import IMatchingPasswordManager
+ >>> from zope.password.legacy import CryptPasswordManager
- >>> manager = CryptPasswordManager()
- >>> verifyObject(IMatchingPasswordManager, manager)
- True
+ >>> manager = CryptPasswordManager()
+ >>> verifyObject(IMatchingPasswordManager, manager)
+ True
- >>> password = u"right \N{CYRILLIC CAPITAL LETTER A}"
- >>> encoded = manager.encodePassword(password, salt="..")
- >>> encoded
- '{CRYPT}..I1I8wps4Na2'
- >>> manager.match(encoded)
- True
- >>> manager.checkPassword(encoded, password)
- True
+ >>> password = u"right \N{CYRILLIC CAPITAL LETTER A}"
+ >>> encoded = manager.encodePassword(password, salt="..")
+ >>> encoded
+ '{CRYPT}..I1I8wps4Na2'
+ >>> manager.match(encoded)
+ True
+ >>> manager.checkPassword(encoded, password)
+ True
- Note that this object fails to return bytes from the ``encodePassword``
- function on Python 3:
+ Note that this object fails to return bytes from the ``encodePassword``
+ function on Python 3:
- >>> isinstance(encoded, str)
- True
+ >>> isinstance(encoded, str)
+ True
- Unfortunately, crypt only looks at the first 8 characters, so matching
- against an 8 character password plus suffix always matches. Our test
- password (including utf-8 encoding) is exactly 8 characters long, and
- thus affixing 'wrong' to it tests as a correct password:
+ Unfortunately, crypt only looks at the first 8 characters, so matching
+ against an 8 character password plus suffix always matches. Our test
+ password (including utf-8 encoding) is exactly 8 characters long, and
+ thus affixing 'wrong' to it tests as a correct password:
- >>> manager.checkPassword(encoded, password + u"wrong")
- True
+ >>> manager.checkPassword(encoded, password + u"wrong")
+ True
- Using a completely different password is rejected as expected:
+ Using a completely different password is rejected as expected:
- >>> manager.checkPassword(encoded, 'completely wrong')
- False
+ >>> manager.checkPassword(encoded, 'completely wrong')
+ False
- Using the `openssl passwd` command-line utility to encode ``secret``,
- we get ``erz50QD3gv4Dw`` as seeded hash.
+ Using the `openssl passwd` command-line utility to encode ``secret``,
+ we get ``erz50QD3gv4Dw`` as seeded hash.
- Our password manager generates the same value when seeded with the
- same salt, so we can be sure, our output is compatible with
- standard LDAP tools that also use crypt:
+ Our password manager generates the same value when seeded with the
+ same salt, so we can be sure, our output is compatible with
+ standard LDAP tools that also use crypt:
- >>> salt = 'er'
- >>> password = 'secret'
- >>> encoded = manager.encodePassword(password, salt)
- >>> encoded
- '{CRYPT}erz50QD3gv4Dw'
+ >>> salt = 'er'
+ >>> password = 'secret'
+ >>> encoded = manager.encodePassword(password, salt)
+ >>> encoded
+ '{CRYPT}erz50QD3gv4Dw'
- >>> manager.checkPassword(encoded, password)
- True
- >>> manager.checkPassword(encoded, password + u"wrong")
- False
+ >>> manager.checkPassword(encoded, password)
+ True
+ >>> manager.checkPassword(encoded, password + u"wrong")
+ False
- >>> manager.encodePassword(password) != manager.encodePassword(password)
- True
+ >>> manager.encodePassword(password) != manager.encodePassword(password)
+ True
- The manager only claims to implement CRYPT encodings, anything not
- starting with the string {CRYPT} returns False:
+ The manager only claims to implement CRYPT encodings, anything not
+ starting with the string {CRYPT} returns False:
- >>> manager.match('{MD5}someotherhash')
- False
+ >>> manager.match('{MD5}someotherhash')
+ False
- """
+ """
- def encodePassword(self, password, salt=None):
- if salt is None:
- choices = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- "abcdefghijklmnopqrstuvwxyz"
- "0123456789./")
- salt = choice(choices) + choice(choices)
- if PY2:
- # Py3: Python 2 can only handle ASCII for crypt.
- password = _encoder(password)[0]
- return '{CRYPT}%s' % crypt(password, salt)
+ def encodePassword(self, password, salt=None):
+ if salt is None:
+ choices = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "0123456789./")
+ salt = choice(choices) + choice(choices)
+ if PY2:
+ # Py3: Python 2 can only handle ASCII for crypt.
+ password = _encoder(password)[0]
+ return '{CRYPT}%s' % crypt(password, salt)
- def checkPassword(self, encoded_password, password):
- return encoded_password == self.encodePassword(password,
- encoded_password[7:9])
+ def checkPassword(self, encoded_password, password):
+ return encoded_password == self.encodePassword(password,
+ encoded_password[7:9])
- def match(self, encoded_password):
- return encoded_password.startswith('{CRYPT}')
+ def match(self, encoded_password):
+ return encoded_password.startswith('{CRYPT}')
@implementer(IMatchingPasswordManager)
diff --git a/src/zope/password/password.py b/src/zope/password/password.py
index c544927..6fe6b01 100644
--- a/src/zope/password/password.py
+++ b/src/zope/password/password.py
@@ -23,6 +23,8 @@ from codecs import getencoder
from hashlib import md5, sha1
from os import urandom
+import re
+
try:
import bcrypt
except ImportError: # pragma: no cover
@@ -501,6 +503,10 @@ class BCRYPTPasswordManager(PlainTextPasswordManager):
"""
BCRYPT password manager.
+ In addition to the passwords encoded by this class,
+ this class can also recognize passwords encoded by :mod:`z3c.bcrypt`
+ and properly match and check them.
+
.. note:: This uses the :mod:`bcrypt` library in its
implementation, which `only uses the first 72 characters
<https://pypi.python.org/pypi/bcrypt/3.1.3#maximum-password-length>`_
@@ -508,6 +514,10 @@ class BCRYPTPasswordManager(PlainTextPasswordManager):
"""
_prefix = b'{BCRYPT}'
+ # This is the same regex that z3c.bcrypt uses, via way of cryptacular
+ # The $2a$ is a prefix.
+ _z3c_bcrypt_syntax = re.compile(br'\$2a\$[0-9]{2}\$[./A-Za-z0-9]{53}')
+
def _to_bytes(self, password, encoding):
if not isinstance(password, bytes):
@@ -536,7 +546,10 @@ class BCRYPTPasswordManager(PlainTextPasswordManager):
if not self.match(hashed_password):
return False
pw_bytes = self._clean_clear(clear_password)
- pw_hash = hashed_password[len(self._prefix):]
+ pw_hash = hashed_password
+ if hashed_password.startswith(self._prefix):
+ pw_hash = hashed_password[len(self._prefix):]
+
try:
ok = bcrypt.checkpw(pw_bytes, pw_hash)
except ValueError: # pragma: no cover
@@ -569,7 +582,8 @@ class BCRYPTPasswordManager(PlainTextPasswordManager):
:rtype: bool
:returns: True iif the password was hashed with this manager.
"""
- return hashed_password.startswith(self._prefix)
+ return (hashed_password.startswith(self._prefix)
+ or self._z3c_bcrypt_syntax.match(hashed_password) is not None)
# Simple registry
| Support reading the format that z3c.bcrypt produces?
Now that we have a bcrypt password manager (and maybe a KDF manager, see #9) it might be nice if we could read the format for those two managers that z3c.bcrypt produces (they have distinct prefixes, just different from the prefixes our existing bcrypt manager uses). (I'm not 100% sure that the KDF would be compatible, but bcrypt should be.)
That way z3c.bcrypt can eventually be phased out, reducing the amount of dependencies for people that want bcrypt/kdf passwords. (The cryptacular library it uses doesn't seem to be as maintained as the bcrypt library this package uses.) | zopefoundation/zope.password | diff --git a/src/zope/password/testing.py b/src/zope/password/testing.py
index bb97a29..9cdbba9 100644
--- a/src/zope/password/testing.py
+++ b/src/zope/password/testing.py
@@ -15,28 +15,15 @@
"""
__docformat__ = "reStructuredText"
-from zope.component import provideUtility
-from zope.schema.interfaces import IVocabularyFactory
-
-from zope.password.interfaces import IMatchingPasswordManager
-from zope.password.password import PlainTextPasswordManager
-from zope.password.password import MD5PasswordManager
-from zope.password.password import SMD5PasswordManager
-from zope.password.password import SHA1PasswordManager
-from zope.password.password import SSHAPasswordManager
-from zope.password.legacy import MySQLPasswordManager
-from zope.password.vocabulary import PasswordManagerNamesVocabulary
-
-try:
- from zope.password.legacy import CryptPasswordManager
-except ImportError: # pragma: no cover
- CryptPasswordManager = None
-
+import zope.password
+from zope.configuration import xmlconfig
def setUpPasswordManagers():
"""Helper function for setting up password manager utilities for tests
>>> from zope.component import getUtility
+ >>> from zope.password.interfaces import IMatchingPasswordManager
+ >>> from zope.schema.interfaces import IVocabularyFactory
>>> setUpPasswordManagers()
>>> getUtility(IMatchingPasswordManager, 'Plain Text')
@@ -58,8 +45,8 @@ def setUpPasswordManagers():
... CryptPasswordManager = None
... True
... else:
- ... from zope.password.legacy import CryptPasswordManager as cpm
- ... getUtility(IMatchingPasswordManager, 'Crypt') is cpm
+ ... from zope.password.legacy import CryptPasswordManager
+ ... getUtility(IMatchingPasswordManager, 'Crypt') is not None
True
>>> voc = getUtility(IVocabularyFactory, 'Password Manager Names')
@@ -83,16 +70,4 @@ def setUpPasswordManagers():
True
"""
- provideUtility(PlainTextPasswordManager(), IMatchingPasswordManager,
- 'Plain Text')
- provideUtility(SSHAPasswordManager(), IMatchingPasswordManager, 'SSHA')
- provideUtility(MD5PasswordManager(), IMatchingPasswordManager, 'MD5')
- provideUtility(SMD5PasswordManager(), IMatchingPasswordManager, 'SMD5')
- provideUtility(SHA1PasswordManager(), IMatchingPasswordManager, 'SHA1')
- provideUtility(MySQLPasswordManager(), IMatchingPasswordManager, 'MySQL')
-
- if CryptPasswordManager is not None:
- provideUtility(CryptPasswordManager, IMatchingPasswordManager, 'Crypt')
-
- provideUtility(PasswordManagerNamesVocabulary,
- IVocabularyFactory, 'Password Manager Names')
+ xmlconfig.file('configure.zcml', zope.password)
diff --git a/src/zope/password/tests/test_password.py b/src/zope/password/tests/test_password.py
index cf11627..7323b15 100644
--- a/src/zope/password/tests/test_password.py
+++ b/src/zope/password/tests/test_password.py
@@ -20,6 +20,7 @@ import unittest
import bcrypt
+from zope.component.testing import PlacelessSetup
from zope.interface.verify import verifyObject
from zope.password.interfaces import IMatchingPasswordManager
@@ -118,13 +119,58 @@ class TestBCRYPTPasswordManager(unittest.TestCase):
self.assertTrue(pw_mgr.match(b'{BCRYPT}'))
+class TestZ3cBcryptCompatible(unittest.TestCase):
+
+ password = u"right \N{CYRILLIC CAPITAL LETTER A}"
+ z3c_encoded = b'$2a$10$dzfwtSW1sFx5Q.9/8.3dzOyvIBz6xu4Y00kJWZpOrQ1eH4amFtHP6'
+
+
+ def _make_one(self):
+ from zope.password.password import BCRYPTPasswordManager
+ return BCRYPTPasswordManager()
+
+ def test_checkPassword(self):
+ pw_mgr = self._make_one()
+ self.assertTrue(pw_mgr.checkPassword(self.z3c_encoded, self.password))
+ # Mess with the hashed password, should not match
+ encoded = self.z3c_encoded[:-1]
+ self.assertFalse(pw_mgr.checkPassword(encoded, self.password))
+
+ def test_match(self):
+ pw_mgr = self._make_one()
+ self.assertTrue(pw_mgr.match(self.z3c_encoded))
+
+
+class TestConfiguration(PlacelessSetup,
+ unittest.TestCase):
+
+ def setUp(self):
+ from zope.configuration import xmlconfig
+ import zope.password
+ xmlconfig.file('configure.zcml', zope.password)
+
+ def test_crypt_utility_names(self):
+ from zope.password.password import BCRYPTPasswordManager
+ from zope.password.interfaces import IPasswordManager
+ from zope import component
+
+ self.assertIsInstance(component.getUtility(IPasswordManager, 'BCRYPT'),
+ BCRYPTPasswordManager)
+ self.assertIsInstance(component.getUtility(IPasswordManager, 'bcrypt'),
+ BCRYPTPasswordManager)
+
+
+
def test_suite():
+ from zope.component.testing import setUp, tearDown
suite = unittest.TestSuite((
doctest.DocTestSuite('zope.password.password'),
doctest.DocTestSuite('zope.password.legacy'),
doctest.DocTestSuite(
'zope.password.testing',
- optionflags=doctest.ELLIPSIS),
- ))
+ optionflags=doctest.ELLIPSIS,
+ setUp=setUp,
+ tearDown=tearDown),
+ ))
suite.addTests(unittest.defaultTestLoader.loadTestsFromName(__name__))
return suite
diff --git a/src/zope/password/tests/test_zpasswd.py b/src/zope/password/tests/test_zpasswd.py
index 3c33f66..a3d92ab 100644
--- a/src/zope/password/tests/test_zpasswd.py
+++ b/src/zope/password/tests/test_zpasswd.py
@@ -41,7 +41,10 @@ class TestBase(unittest.TestCase):
suffix=".zcml",
delete=False) as f:
f.write(
- b'<configure xmlns="http://namespaces.zope.org/zope"/>\n')
+ b"""<configure xmlns="http://namespaces.zope.org/zope">
+ <include file="configure.zcml" package="zope.password" />
+ </configure>
+ """)
self.config = f.name
self.addCleanup(os.remove, f.name)
| {
"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": 1,
"test_score": 2
},
"num_modified_files": 4
} | 4.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"coverage",
"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
bcrypt==4.0.1
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
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
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
zope.component==5.1.0
zope.configuration==4.4.1
zope.event==4.6
zope.exceptions==4.6
zope.hookable==5.4
zope.i18nmessageid==5.1.1
zope.interface==5.5.2
-e git+https://github.com/zopefoundation/zope.password.git@f18b5f9371ceb5e7af68c917f2ae9f7de3d91cad#egg=zope.password
zope.schema==6.2.1
zope.testing==5.0.1
zope.testrunner==5.6
| name: zope.password
channels:
- defaults
- https://repo.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:
- bcrypt==4.0.1
- coverage==6.2
- six==1.17.0
- zope-component==5.1.0
- zope-configuration==4.4.1
- zope-event==4.6
- zope-exceptions==4.6
- zope-hookable==5.4
- zope-i18nmessageid==5.1.1
- zope-interface==5.5.2
- zope-schema==6.2.1
- zope-testing==5.0.1
- zope-testrunner==5.6
prefix: /opt/conda/envs/zope.password
| [
"src/zope/password/tests/test_password.py::TestZ3cBcryptCompatible::test_checkPassword",
"src/zope/password/tests/test_password.py::TestZ3cBcryptCompatible::test_match",
"src/zope/password/tests/test_password.py::TestConfiguration::test_crypt_utility_names",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_config_long",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_config_short"
]
| []
| [
"src/zope/password/tests/test_password.py::TestBCRYPTPasswordManager::test_checkPassword",
"src/zope/password/tests/test_password.py::TestBCRYPTPasswordManager::test_encodePassword_with_different_salts",
"src/zope/password/tests/test_password.py::TestBCRYPTPasswordManager::test_encodePassword_with_no_salt",
"src/zope/password/tests/test_password.py::TestBCRYPTPasswordManager::test_encodePassword_with_same_salt",
"src/zope/password/tests/test_password.py::TestBCRYPTPasswordManager::test_encodePassword_with_unicode_salts",
"src/zope/password/tests/test_password.py::TestBCRYPTPasswordManager::test_interface_compliance",
"src/zope/password/tests/test_password.py::TestBCRYPTPasswordManager::test_match",
"src/zope/password/tests/test_password.py::test_suite",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_destination_long",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_destination_short",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_help_long",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_help_short",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_main",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_no_arguments",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_too_many_arguments",
"src/zope/password/tests/test_zpasswd.py::ArgumentParsingTestCase::test_version_long",
"src/zope/password/tests/test_zpasswd.py::InputCollectionTestCase::test_principal_information",
"src/zope/password/tests/test_zpasswd.py::TestDestination::test_principal_information",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_exit",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_passwd_empty",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_passwd_spaces",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_passwd_verify_fail",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_password_manager_bad",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_password_manager_default",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_get_value",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_keyboard_interrupt",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_read_input",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_read_password",
"src/zope/password/tests/test_zpasswd.py::TestRunAndApplication::test_read_password_cancel",
"src/zope/password/tests/test_zpasswd.py::test_suite"
]
| []
| Zope Public License 2.1 | 1,600 | [
"src/zope/password/password.py",
"src/zope/password/configure.zcml",
"src/zope/password/legacy.py",
"CHANGES.rst"
]
| [
"src/zope/password/password.py",
"src/zope/password/configure.zcml",
"src/zope/password/legacy.py",
"CHANGES.rst"
]
|
Azure__azure-cli-4265 | 85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b | 2017-08-18 19:52:45 | eb12ac454cbe1ddb59c86cdf2045e1912660e750 | codecov-io: # [Codecov](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=h1) Report
> Merging [#4265](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=desc) into [master](https://codecov.io/gh/Azure/azure-cli/commit/85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b?src=pr&el=desc) will **increase** coverage by `<.01%`.
> The diff coverage is `86.66%`.
[](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #4265 +/- ##
==========================================
+ Coverage 70.08% 70.09% +<.01%
==========================================
Files 475 475
Lines 29636 29639 +3
Branches 4542 4542
==========================================
+ Hits 20771 20774 +3
- Misses 7419 7423 +4
+ Partials 1446 1442 -4
```
| [Impacted Files](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [...cli-vm/azure/cli/command\_modules/vm/\_validators.py](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=tree#diff-c3JjL2NvbW1hbmRfbW9kdWxlcy9henVyZS1jbGktdm0vYXp1cmUvY2xpL2NvbW1hbmRfbW9kdWxlcy92bS9fdmFsaWRhdG9ycy5weQ==) | `78.48% <86.66%> (+0.1%)` | :arrow_up: |
| [...dback/azure/cli/command\_modules/feedback/custom.py](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=tree#diff-c3JjL2NvbW1hbmRfbW9kdWxlcy9henVyZS1jbGktZmVlZGJhY2svYXp1cmUvY2xpL2NvbW1hbmRfbW9kdWxlcy9mZWVkYmFjay9jdXN0b20ucHk=) | `31.25% <0%> (ø)` | :arrow_up: |
| [...nent/azure/cli/command\_modules/component/custom.py](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=tree#diff-c3JjL2NvbW1hbmRfbW9kdWxlcy9henVyZS1jbGktY29tcG9uZW50L2F6dXJlL2NsaS9jb21tYW5kX21vZHVsZXMvY29tcG9uZW50L2N1c3RvbS5weQ==) | `16.26% <0%> (ø)` | :arrow_up: |
| [...li-cloud/azure/cli/command\_modules/cloud/custom.py](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=tree#diff-c3JjL2NvbW1hbmRfbW9kdWxlcy9henVyZS1jbGktY2xvdWQvYXp1cmUvY2xpL2NvbW1hbmRfbW9kdWxlcy9jbG91ZC9jdXN0b20ucHk=) | `13.79% <0%> (ø)` | :arrow_up: |
| [src/azure-cli-core/azure/cli/core/util.py](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=tree#diff-c3JjL2F6dXJlLWNsaS1jb3JlL2F6dXJlL2NsaS9jb3JlL3V0aWwucHk=) | `69.73% <0%> (ø)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=footer). Last update [85c0e4c...5cf8abf](https://codecov.io/gh/Azure/azure-cli/pull/4265?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
| diff --git a/packaged_releases/debian/debian_build.sh b/packaged_releases/debian/debian_build.sh
index cac900add..1d59a1ffd 100644
--- a/packaged_releases/debian/debian_build.sh
+++ b/packaged_releases/debian/debian_build.sh
@@ -55,6 +55,9 @@ $source_dir/python_env/bin/pip3 install wheel
for d in $source_dir/src/azure-cli $source_dir/src/azure-cli-core $source_dir/src/azure-cli-nspkg $source_dir/src/azure-cli-command_modules-nspkg $source_dir/src/command_modules/azure-cli-*/; do cd $d; $source_dir/python_env/bin/python3 setup.py bdist_wheel -d $tmp_pkg_dir; cd -; done;
$source_dir/python_env/bin/pip3 install azure-cli --find-links $tmp_pkg_dir
$source_dir/python_env/bin/pip3 install --force-reinstall --upgrade azure-nspkg azure-mgmt-nspkg
+# WORKAROUND: Newer versions of cryptography do not work on Bash on Windows / WSL - see https://github.com/Azure/azure-cli/issues/4154
+# If you *have* to use a newer version of cryptography in the future, verify that it works on WSL also.
+$source_dir/python_env/bin/pip3 install cryptography==2.0
# Add the debian files
mkdir $source_dir/debian
# Create temp dir for the debian/ directory used for CLI build.
diff --git a/scripts/releaser/HISTORY.rst b/scripts/releaser/HISTORY.rst
index a89636c31..563fff31d 100644
--- a/scripts/releaser/HISTORY.rst
+++ b/scripts/releaser/HISTORY.rst
@@ -3,6 +3,11 @@
Release History
===============
+0.1.3 (2017-08-18)
+++++++++++++++++++
+
+* Fix 'packaged release archive' creation step. We now clone the repo again after pushing tags so we can use the new tags.
+
0.1.2 (2017-08-15)
++++++++++++++++++
diff --git a/scripts/releaser/release.py b/scripts/releaser/release.py
index 4e671b353..c65460c6e 100644
--- a/scripts/releaser/release.py
+++ b/scripts/releaser/release.py
@@ -365,5 +365,8 @@ if __name__ == "__main__":
give_chance_to_cancel('Create GitHub releases and tags')
run_create_github_release(release_commitish_list, release_assets_dir_map)
give_chance_to_cancel('Create Packaged Release archive')
+ # We need to clone the repo again as we've now pushed the git tags and we need them to create the packaged release.
+ # (we could do 'git pull' but this is easier and uses a clean directory just to be safe)
+ cli_repo_dir = set_up_cli_repo_dir()
run_create_packaged_release(cli_repo_dir)
print_status('Done.')
diff --git a/src/command_modules/azure-cli-vm/HISTORY.rst b/src/command_modules/azure-cli-vm/HISTORY.rst
index ad0fe2f37..0f9a6ccf6 100644
--- a/src/command_modules/azure-cli-vm/HISTORY.rst
+++ b/src/command_modules/azure-cli-vm/HISTORY.rst
@@ -4,6 +4,7 @@ Release History
===============
unreleased
+++++++++++++++++++
+* `vm/vmss create`: fix issue where the command would throw an error if unable to extract plan information from an image.
* `vmss create`: fix a crash when create a scaleset with an internal LB
* `vm availability-set create`: Fix issue where --no-wait argument did not work.
diff --git a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py
index f1de4fb21..8e9abcc1d 100644
--- a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py
+++ b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py
@@ -157,32 +157,36 @@ def _parse_image_argument(namespace):
namespace.os_offer = urn_match.group(2)
namespace.os_sku = urn_match.group(3)
namespace.os_version = urn_match.group(4)
- compute_client = _compute_client_factory()
- if namespace.os_version.lower() == 'latest':
- top_one = compute_client.virtual_machine_images.list(namespace.location,
- namespace.os_publisher,
- namespace.os_offer,
- namespace.os_sku,
- top=1,
- orderby='name desc')
- if not top_one:
- raise CLIError("Can't resolve the vesion of '{}'".format(namespace.image))
-
- image_version = top_one[0].name
- else:
- image_version = namespace.os_version
-
- image = compute_client.virtual_machine_images.get(namespace.location,
- namespace.os_publisher,
- namespace.os_offer,
- namespace.os_sku,
- image_version)
-
- # pylint: disable=no-member
- if image.plan:
- namespace.plan_name = image.plan.name
- namespace.plan_product = image.plan.product
- namespace.plan_publisher = image.plan.publisher
+ try:
+ compute_client = _compute_client_factory()
+ if namespace.os_version.lower() == 'latest':
+ top_one = compute_client.virtual_machine_images.list(namespace.location,
+ namespace.os_publisher,
+ namespace.os_offer,
+ namespace.os_sku,
+ top=1,
+ orderby='name desc')
+ if not top_one:
+ raise CLIError("Can't resolve the vesion of '{}'".format(namespace.image))
+
+ image_version = top_one[0].name
+ else:
+ image_version = namespace.os_version
+
+ image = compute_client.virtual_machine_images.get(namespace.location,
+ namespace.os_publisher,
+ namespace.os_offer,
+ namespace.os_sku,
+ image_version)
+
+ # pylint: disable=no-member
+ if image.plan:
+ namespace.plan_name = image.plan.name
+ namespace.plan_product = image.plan.product
+ namespace.plan_publisher = image.plan.publisher
+ except CloudError as ex:
+ logger.warning("Querying the image of '%s' failed for an error '%s'. Configuring plan settings "
+ "will be skipped", namespace.image, ex.message)
return 'urn'
# 4 - check if a fully-qualified ID (assumes it is an image ID)
| vm/vmss create: don't throw when tries to retrieve image to extract the plan information
The context is some images are still being staged and not yet published, hence image API won't go through. Instead of fail (therefore block the create), the suggested change is to warn. I am fine with it, as using market place image with plan is a minority scenario.
The code to wrap inside a try-catch is [here](https://github.com/Azure/azure-cli/blob/master/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py#L160-L185) | Azure/azure-cli | diff --git a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py
index 068c40722..0475ec9e3 100644
--- a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py
+++ b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py
@@ -8,6 +8,7 @@ import tempfile
import unittest
import mock
+from msrestazure.azure_exceptions import CloudError
from azure.cli.core.util import CLIError
from azure.cli.core.commands.validators import DefaultStr
from azure.cli.core.keys import is_valid_ssh_rsa_public_key
@@ -172,6 +173,29 @@ class TestActions(unittest.TestCase):
self.assertEqual('product1', np.plan_product)
self.assertEqual('publisher1', np.plan_publisher)
+ @mock.patch('azure.cli.command_modules.vm._validators._compute_client_factory', autospec=True)
+ @mock.patch('azure.cli.command_modules.vm._validators.logger.warning', autospec=True)
+ def test_parse_staging_image_argument(self, logger_mock, client_factory_mock):
+ compute_client = mock.MagicMock()
+ resp = mock.MagicMock()
+ resp.status_code = 404
+ resp.text = '{"Message": "Not Found"}'
+
+ compute_client.virtual_machine_images.get.side_effect = CloudError(resp, error='image not found')
+ client_factory_mock.return_value = compute_client
+
+ np = mock.MagicMock()
+ np.location = 'some region'
+ np.image = 'publisher1:offer1:sku1:1.0.0'
+
+ # action
+ _parse_image_argument(np)
+
+ # assert
+ logger_mock.assert_called_with("Querying the image of '%s' failed for an error '%s'. "
+ "Configuring plan settings will be skipped", 'publisher1:offer1:sku1:1.0.0',
+ 'image not found')
+
def test_get_next_subnet_addr_suffix(self):
result = _get_next_subnet_addr_suffix('10.0.0.0/16', '10.0.0.0/24', 24)
self.assertEqual(result, '10.0.1.0/24')
| {
"commit_name": "merge_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": 3
},
"num_modified_files": 5
} | 2.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "python scripts/dev_setup.py",
"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 libssl-dev libffi-dev"
],
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | adal==0.4.3
applicationinsights==0.10.0
argcomplete==1.8.0
astroid==2.11.7
attrs==22.2.0
autopep8==2.0.4
azure-batch==3.1.0
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli&subdirectory=src/azure-cli
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_acr&subdirectory=src/command_modules/azure-cli-acr
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_acs&subdirectory=src/command_modules/azure-cli-acs
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_appservice&subdirectory=src/command_modules/azure-cli-appservice
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_batch&subdirectory=src/command_modules/azure-cli-batch
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_billing&subdirectory=src/command_modules/azure-cli-billing
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_cdn&subdirectory=src/command_modules/azure-cli-cdn
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_cloud&subdirectory=src/command_modules/azure-cli-cloud
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_cognitiveservices&subdirectory=src/command_modules/azure-cli-cognitiveservices
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_component&subdirectory=src/command_modules/azure-cli-component
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_configure&subdirectory=src/command_modules/azure-cli-configure
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_consumption&subdirectory=src/command_modules/azure-cli-consumption
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_container&subdirectory=src/command_modules/azure-cli-container
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_core&subdirectory=src/azure-cli-core
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_cosmosdb&subdirectory=src/command_modules/azure-cli-cosmosdb
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_dla&subdirectory=src/command_modules/azure-cli-dla
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_dls&subdirectory=src/command_modules/azure-cli-dls
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_eventgrid&subdirectory=src/command_modules/azure-cli-eventgrid
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_feedback&subdirectory=src/command_modules/azure-cli-feedback
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_find&subdirectory=src/command_modules/azure-cli-find
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_interactive&subdirectory=src/command_modules/azure-cli-interactive
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_iot&subdirectory=src/command_modules/azure-cli-iot
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_keyvault&subdirectory=src/command_modules/azure-cli-keyvault
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_lab&subdirectory=src/command_modules/azure-cli-lab
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_monitor&subdirectory=src/command_modules/azure-cli-monitor
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_network&subdirectory=src/command_modules/azure-cli-network
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_nspkg&subdirectory=src/azure-cli-nspkg
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_profile&subdirectory=src/command_modules/azure-cli-profile
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_rdbms&subdirectory=src/command_modules/azure-cli-rdbms
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_redis&subdirectory=src/command_modules/azure-cli-redis
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_resource&subdirectory=src/command_modules/azure-cli-resource
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_role&subdirectory=src/command_modules/azure-cli-role
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_sf&subdirectory=src/command_modules/azure-cli-sf
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_sql&subdirectory=src/command_modules/azure-cli-sql
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_storage&subdirectory=src/command_modules/azure-cli-storage
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_taskhelp&subdirectory=src/command_modules/azure-cli-taskhelp
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_testsdk&subdirectory=src/azure-cli-testsdk
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_utility_automation&subdirectory=scripts
-e git+https://github.com/Azure/azure-cli.git@85c0e4c8fb21e26a4984cad3b21a5e22a6a8b92b#egg=azure_cli_vm&subdirectory=src/command_modules/azure-cli-vm
azure-common==1.1.28
azure-core==1.24.2
azure-datalake-store==0.0.15
azure-devtools==0.4.3
azure-graphrbac==0.30.0rc6
azure-keyvault==0.3.4
azure-mgmt-authorization==0.30.0rc6
azure-mgmt-batch==4.1.0
azure-mgmt-billing==0.1.0
azure-mgmt-cdn==0.30.2
azure-mgmt-cognitiveservices==1.0.0
azure-mgmt-compute==2.0.0
azure-mgmt-consumption==0.1.0
azure-mgmt-containerinstance==9.2.0
azure-mgmt-containerregistry==0.3.1
azure-mgmt-containerservice==1.0.0
azure-mgmt-core==1.3.2
azure-mgmt-datalake-analytics==0.1.6
azure-mgmt-datalake-nspkg==3.0.1
azure-mgmt-datalake-store==0.1.6
azure-mgmt-devtestlabs==2.0.0
azure-mgmt-dns==1.0.1
azure-mgmt-documentdb==0.1.3
azure-mgmt-iothub==0.2.2
azure-mgmt-keyvault==0.40.0
azure-mgmt-monitor==0.2.1
azure-mgmt-network==1.3.0
azure-mgmt-nspkg==1.0.0
azure-mgmt-rdbms==0.1.0
azure-mgmt-redis==1.0.0
azure-mgmt-resource==1.1.0
azure-mgmt-sql==0.6.0
azure-mgmt-storage==1.2.0
azure-mgmt-trafficmanager==0.30.0
azure-mgmt-web==0.32.0
azure-monitor==0.3.0
azure-multiapi-storage==0.1.2
azure-nspkg==1.0.0
azure-servicefabric==5.6.130
bleach==4.1.0
certifi==2021.5.30
cffi==1.15.1
colorama==0.3.7
ConfigArgParse==1.7
coverage==6.2
cryptography==40.0.2
docutils==0.18.1
flake8==5.0.4
futures==3.1.1
humanfriendly==2.4
idna==3.10
importlib-metadata==4.2.0
iniconfig==1.1.1
isodate==0.7.0
isort==5.10.1
jeepney==0.7.1
jmespath==0.10.0
keyring==23.4.1
lazy-object-proxy==1.7.1
mccabe==0.7.0
mock==5.2.0
msrest==0.7.1
msrestazure==0.4.34
nose==1.3.7
oauthlib==3.2.2
packaging==21.3
paramiko==2.0.2
pbr==6.1.1
pluggy==1.0.0
prompt-toolkit==3.0.36
py==1.11.0
pyasn1==0.5.1
pycodestyle==2.10.0
pycparser==2.21
pydocumentdb==2.3.5
pyflakes==2.5.0
Pygments==2.14.0
PyJWT==2.4.0
pylint==1.7.1
pyOpenSSL==16.2.0
pyparsing==3.1.4
pytest==7.0.1
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==3.11
readme-renderer==34.0
requests==2.9.1
requests-oauthlib==2.0.0
scp==0.15.0
SecretStorage==3.3.3
six==1.10.0
sshtunnel==0.4.0
tabulate==0.7.7
tomli==1.2.3
typed-ast==1.5.5
typing-extensions==4.1.1
urllib3==1.26.20
urllib3-secure-extra==0.1.0
vcrpy==1.10.3
vsts-cd-manager==0.118.0
wcwidth==0.2.13
webencodings==0.5.1
Whoosh==2.7.4
wrapt==1.16.0
xmltodict==0.14.2
zipp==3.6.0
| name: azure-cli
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- 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
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_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:
- adal==0.4.3
- applicationinsights==0.10.0
- argcomplete==1.8.0
- astroid==2.11.7
- attrs==22.2.0
- autopep8==2.0.4
- azure-batch==3.1.0
- azure-common==1.1.28
- azure-core==1.24.2
- azure-datalake-store==0.0.15
- azure-devtools==0.4.3
- azure-graphrbac==0.30.0rc6
- azure-keyvault==0.3.4
- azure-mgmt-authorization==0.30.0rc6
- azure-mgmt-batch==4.1.0
- azure-mgmt-billing==0.1.0
- azure-mgmt-cdn==0.30.2
- azure-mgmt-cognitiveservices==1.0.0
- azure-mgmt-compute==2.0.0
- azure-mgmt-consumption==0.1.0
- azure-mgmt-containerinstance==9.2.0
- azure-mgmt-containerregistry==0.3.1
- azure-mgmt-containerservice==1.0.0
- azure-mgmt-core==1.3.2
- azure-mgmt-datalake-analytics==0.1.6
- azure-mgmt-datalake-nspkg==3.0.1
- azure-mgmt-datalake-store==0.1.6
- azure-mgmt-devtestlabs==2.0.0
- azure-mgmt-dns==1.0.1
- azure-mgmt-documentdb==0.1.3
- azure-mgmt-iothub==0.2.2
- azure-mgmt-keyvault==0.40.0
- azure-mgmt-monitor==0.2.1
- azure-mgmt-network==1.3.0
- azure-mgmt-nspkg==1.0.0
- azure-mgmt-rdbms==0.1.0
- azure-mgmt-redis==1.0.0
- azure-mgmt-resource==1.1.0
- azure-mgmt-sql==0.6.0
- azure-mgmt-storage==1.2.0
- azure-mgmt-trafficmanager==0.30.0
- azure-mgmt-web==0.32.0
- azure-monitor==0.3.0
- azure-multiapi-storage==0.1.2
- azure-nspkg==1.0.0
- azure-servicefabric==5.6.130
- bleach==4.1.0
- cffi==1.15.1
- colorama==0.3.7
- configargparse==1.7
- coverage==6.2
- cryptography==40.0.2
- docutils==0.18.1
- flake8==5.0.4
- futures==3.1.1
- humanfriendly==2.4
- idna==3.10
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- isodate==0.7.0
- isort==5.10.1
- jeepney==0.7.1
- jmespath==0.10.0
- keyring==23.4.1
- lazy-object-proxy==1.7.1
- mccabe==0.7.0
- mock==5.2.0
- msrest==0.7.1
- msrestazure==0.4.34
- nose==1.3.7
- oauthlib==3.2.2
- packaging==21.3
- paramiko==2.0.2
- pbr==6.1.1
- pip==9.0.1
- pluggy==1.0.0
- prompt-toolkit==3.0.36
- py==1.11.0
- pyasn1==0.5.1
- pycodestyle==2.10.0
- pycparser==2.21
- pydocumentdb==2.3.5
- pyflakes==2.5.0
- pygments==2.14.0
- pyjwt==2.4.0
- pylint==1.7.1
- pyopenssl==16.2.0
- pyparsing==3.1.4
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==3.11
- readme-renderer==34.0
- requests==2.9.1
- requests-oauthlib==2.0.0
- scp==0.15.0
- secretstorage==3.3.3
- setuptools==30.4.0
- six==1.10.0
- sshtunnel==0.4.0
- tabulate==0.7.7
- tomli==1.2.3
- typed-ast==1.5.5
- typing-extensions==4.1.1
- urllib3==1.26.20
- urllib3-secure-extra==0.1.0
- vcrpy==1.10.3
- vsts-cd-manager==0.118.0
- wcwidth==0.2.13
- webencodings==0.5.1
- whoosh==2.7.4
- wrapt==1.16.0
- xmltodict==0.14.2
- zipp==3.6.0
prefix: /opt/conda/envs/azure-cli
| [
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_parse_staging_image_argument"
]
| []
| [
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_figure_out_storage_source",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_generate_specfied_ssh_key_files",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_get_next_subnet_addr_suffix",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_parse_image_argument",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_source_storage_account_err_case",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_validate_admin_password_linux",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_validate_admin_password_windows",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_validate_admin_username_linux",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_validate_admin_username_windows",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_validate_msi_on_assign_identity_command",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/tests/test_vm_actions.py::TestActions::test_validate_msi_on_create"
]
| []
| MIT License | 1,601 | [
"src/command_modules/azure-cli-vm/HISTORY.rst",
"scripts/releaser/HISTORY.rst",
"packaged_releases/debian/debian_build.sh",
"scripts/releaser/release.py",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py"
]
| [
"src/command_modules/azure-cli-vm/HISTORY.rst",
"scripts/releaser/HISTORY.rst",
"packaged_releases/debian/debian_build.sh",
"scripts/releaser/release.py",
"src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py"
]
|
Azure__azure-cli-4272 | 966cbaa94a8eba13f89a220fb1fe73bed3e2244b | 2017-08-18 23:54:34 | eb12ac454cbe1ddb59c86cdf2045e1912660e750 | diff --git a/src/command_modules/azure-cli-storage/HISTORY.rst b/src/command_modules/azure-cli-storage/HISTORY.rst
index 3a69e8aa3..51989b349 100644
--- a/src/command_modules/azure-cli-storage/HISTORY.rst
+++ b/src/command_modules/azure-cli-storage/HISTORY.rst
@@ -3,6 +3,12 @@
Release History
===============
+unreleased
+++++++++++
+* Enable service encryption by customer managed key
+* Breaking change: rename --encryption option to --encryption-services for az storage account create and az storage account update command.
+* Fix #4220: az storage account update encryption - syntax mismatch
+
2.0.12 (2017-08-11)
+++++++++++++++++++
* Enable create storage account with system assigned identity
diff --git a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_params.py b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_params.py
index 0e159c576..157a5d77f 100644
--- a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_params.py
+++ b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_params.py
@@ -19,7 +19,7 @@ from azure.cli.core.commands import (register_cli_argument, register_extra_cli_a
from azure.common import AzureMissingResourceHttpError
-from azure.cli.core.profiles import get_sdk, ResourceType
+from azure.cli.core.profiles import get_sdk, ResourceType, supported_api_version
from ._factory import get_storage_data_service_client
from ._validators import \
@@ -30,8 +30,8 @@ from ._validators import \
validate_custom_domain, validate_public_access,
process_blob_upload_batch_parameters, process_blob_download_batch_parameters,
process_file_upload_batch_parameters, process_file_download_batch_parameters,
- get_content_setting_validator, validate_encryption, validate_accept,
- validate_key, storage_account_key_options,
+ get_content_setting_validator, validate_encryption_services, validate_accept,
+ validate_key, storage_account_key_options, validate_encryption_source,
process_file_download_namespace,
process_metric_update_namespace, process_blob_copy_batch_namespace,
get_source_file_or_blob_service_client, process_blob_source_uri,
@@ -112,7 +112,6 @@ class CommandContext(object):
max_api = kwargs.pop('max_api', None)
min_api = kwargs.pop('min_api', None)
if resource_type and (max_api or min_api):
- from azure.cli.core.profiles import supported_api_version
return supported_api_version(resource_type, min_api=min_api, max_api=max_api)
return True
@@ -286,7 +285,6 @@ register_cli_argument('storage', 'if_match', arg_group='Pre-condition')
register_cli_argument('storage', 'if_none_match', arg_group='Pre-condition')
register_cli_argument('storage', 'container_name', container_name_type)
-
for item in ['check-name', 'delete', 'list', 'show', 'show-usage', 'update', 'keys']:
register_cli_argument('storage account {}'.format(item), 'account_name', account_name_type, options_list=('--name', '-n'))
@@ -300,21 +298,35 @@ for item in ['blob', 'file', 'queue', 'table']:
def register_common_storage_account_options(context):
context.reg_arg('https_only', help='Allows https traffic only to storage service.', **three_state_flag())
context.reg_arg('sku', help='The storage account SKU.', **model_choice_list(ResourceType.MGMT_STORAGE, 'SkuName'))
- context.reg_arg('assign_identity', help='Generate and assign a new Storage Account Identity for this storage '
- 'account for use with key management services like Azure KeyVault.',
- action='store_true', resource_type=ResourceType.MGMT_STORAGE, min_api='2017-06-01')
context.reg_arg('access_tier', help='The access tier used for billing StandardBlob accounts. Cannot be set for '
'StandardLRS, StandardGRS, StandardRAGRS, or PremiumLRS account types. It is '
'required for StandardBlob accounts during creation',
**model_choice_list(ResourceType.MGMT_STORAGE, 'AccessTier'))
- encryption_services_model = get_sdk(ResourceType.MGMT_STORAGE, 'models#EncryptionServices')
- if encryption_services_model:
- encryption_choices = list(encryption_services_model._attribute_map.keys()) # pylint: disable=protected-access
- context.reg_arg('encryption', nargs='+', help='Specifies which service(s) to encrypt.',
- validator=validate_encryption,
- resource_type=ResourceType.MGMT_STORAGE, min_api='2016-12-01',
- **enum_choice_list(encryption_choices))
+ # after API 2016-12-01
+ if supported_api_version(resource_type=ResourceType.MGMT_STORAGE, min_api='2016-12-01'):
+ encryption_services_model = get_sdk(ResourceType.MGMT_STORAGE, 'models#EncryptionServices')
+ if encryption_services_model:
+
+ encryption_choices = []
+ for attribute in encryption_services_model._attribute_map.keys(): # pylint: disable=protected-access
+ if not encryption_services_model._validation.get(attribute, {}).get('readonly'): # pylint: disable=protected-access
+ # skip readonly attributes, which are not for input
+ encryption_choices.append(attribute)
+
+ context.reg_arg('encryption_services', nargs='+', help='Specifies which service(s) to encrypt.',
+ validator=validate_encryption_services, **enum_choice_list(encryption_choices))
+
+ # after API 2017-06-01
+ if supported_api_version(resource_type=ResourceType.MGMT_STORAGE, min_api='2017-06-01'):
+ context.reg_arg('assign_identity', action='store_true',
+ help='Generate and assign a new Storage Account Identity for this storage account for use with '
+ 'key management services like Azure KeyVault.')
+
+ # the options of encryption key sources are hardcoded since there isn't a enum represents them in the SDK.
+ context.reg_arg('encryption_key_source', help='The encryption keySource (provider). Default: Microsoft.Storage',
+ validator=validate_encryption_source,
+ **enum_choice_list(['Microsoft.Storage', 'Microsoft.Keyvault']))
with CommandContext('storage account create') as c:
@@ -338,6 +350,15 @@ with CommandContext('storage account update') as c:
**enum_choice_list(['true', 'false']))
c.reg_arg('tags', tags_type, default=None)
+ # after API 2017-06-01
+ if supported_api_version(resource_type=ResourceType.MGMT_STORAGE, min_api='2017-06-01'):
+ c.reg_arg('encryption_key_vault_properties', ignore_type)
+
+ with c.arg_group('Customer managed key') as g:
+ g.reg_extra_arg('encryption_key_name', help='The name of the KeyVault key.')
+ g.reg_extra_arg('encryption_key_vault', help='The Uri of the KeyVault')
+ g.reg_extra_arg('encryption_key_version', help='The version of the KeyVault key')
+
register_cli_argument('storage account keys renew', 'key_name', options_list=('--key',), help='The key to regenerate.', validator=validate_key, **enum_choice_list(list(storage_account_key_options.keys())))
register_cli_argument('storage account keys renew', 'account_name', account_name_type, id_part=None)
diff --git a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_validators.py b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_validators.py
index ffaddd11d..eb8363060 100644
--- a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_validators.py
+++ b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_validators.py
@@ -371,17 +371,43 @@ def validate_custom_domain(namespace):
raise ValueError('usage error: --custom-domain DOMAIN [--use-subdomain]')
-def validate_encryption(namespace):
- ''' Builds up the encryption object for storage account operations based on the
- list of services passed in. '''
- if namespace.encryption:
- Encryption, EncryptionServices, EncryptionService = get_sdk(ResourceType.MGMT_STORAGE,
- 'Encryption',
- 'EncryptionServices',
- 'EncryptionService',
- mod='models')
- services = {service: EncryptionService(True) for service in namespace.encryption}
- namespace.encryption = Encryption(EncryptionServices(**services))
+def validate_encryption_services(namespace):
+ """
+ Builds up the encryption services object for storage account operations based on the list of services passed in.
+ """
+ if namespace.encryption_services:
+ EncryptionServices, EncryptionService = get_sdk(
+ ResourceType.MGMT_STORAGE, 'EncryptionServices', 'EncryptionService', mod='models')
+ services = {service: EncryptionService(True) for service in namespace.encryption_services}
+
+ namespace.encryption_services = EncryptionServices(**services)
+
+
+def validate_encryption_source(namespace):
+ ns = vars(namespace)
+ if namespace.encryption_key_source:
+ allowed_options = ['Microsoft.Storage', 'Microsoft.Keyvault']
+ if namespace.encryption_key_source not in allowed_options:
+ raise ValueError('--encryption-key-source allows to values: {}'.format(', '.join(allowed_options)))
+
+ key_name = ns.pop('encryption_key_name', None)
+ key_version = ns.pop('encryption_key_version', None)
+ key_vault_uri = ns.pop('encryption_key_vault', None)
+
+ if namespace.encryption_key_source == 'Microsoft.Keyvault' and not (key_name and key_version and key_vault_uri):
+ raise ValueError('--encryption-key-name, --encryption-key-vault, and --encryption-key-version are required '
+ 'when --encryption-key-source=Microsoft.Keyvault is specified.')
+
+ if key_name or key_version or key_vault_uri:
+ if namespace.encryption_key_source != 'Microsoft.Keyvault':
+ raise ValueError('--encryption-key-name, --encryption-key-vault, and --encryption-key-version are not '
+ 'applicable when --encryption-key-source=Microsoft.Keyvault is not specified.')
+ KeyVaultProperties = get_sdk(ResourceType.MGMT_STORAGE, 'KeyVaultProperties', mod='models')
+ if not KeyVaultProperties:
+ return
+
+ kv_prop = KeyVaultProperties(key_name, key_version, key_vault_uri)
+ namespace.encryption_key_vault_properties = kv_prop
def validate_entity(namespace):
diff --git a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/custom.py b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/custom.py
index 8ce90a73a..273fabe5c 100644
--- a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/custom.py
+++ b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/custom.py
@@ -40,8 +40,8 @@ def _update_progress(current, total):
# CUSTOM METHODS
def create_storage_account(resource_group_name, account_name, sku, assign_identity=False, location=None, kind=None,
- tags=None, custom_domain=None, encryption=None, access_tier=None, https_only=None):
- StorageAccountCreateParameters, Kind, Sku, CustomDomain, AccessTier, Identity = get_sdk(
+ encryption_services=None, tags=None, custom_domain=None, access_tier=None, https_only=None):
+ StorageAccountCreateParameters, Kind, Sku, CustomDomain, AccessTier, Identity, Encryption = get_sdk(
ResourceType.MGMT_STORAGE,
'StorageAccountCreateParameters',
'Kind',
@@ -49,13 +49,14 @@ def create_storage_account(resource_group_name, account_name, sku, assign_identi
'CustomDomain',
'AccessTier',
'Identity',
+ 'Encryption',
mod='models')
scf = storage_client_factory()
params = StorageAccountCreateParameters(sku=Sku(sku), kind=Kind(kind), location=location, tags=tags)
if custom_domain:
params.custom_domain = CustomDomain(custom_domain, None)
- if encryption:
- params.encryption = encryption
+ if encryption_services:
+ params.encryption = Encryption(services=encryption_services)
if access_tier:
params.access_tier = AccessTier(access_tier)
if assign_identity:
@@ -77,15 +78,17 @@ def create_storage_account_with_account_type(resource_group_name, account_name,
return scf.storage_accounts.create(resource_group_name, account_name, params)
-def update_storage_account(instance, sku=None, tags=None, custom_domain=None, use_subdomain=None, encryption=None,
+def update_storage_account(instance, sku=None, tags=None, custom_domain=None, use_subdomain=None,
+ encryption_services=None, encryption_key_source=None, encryption_key_vault_properties=None,
access_tier=None, https_only=None, assign_identity=False):
- StorageAccountUpdateParameters, Sku, CustomDomain, AccessTier, Identity = get_sdk(
+ StorageAccountUpdateParameters, Sku, CustomDomain, AccessTier, Identity, Encryption = get_sdk(
ResourceType.MGMT_STORAGE,
'StorageAccountUpdateParameters',
'Sku',
'CustomDomain',
'AccessTier',
'Identity',
+ 'Encryption',
mod='models')
domain = instance.custom_domain
if custom_domain is not None:
@@ -93,11 +96,19 @@ def update_storage_account(instance, sku=None, tags=None, custom_domain=None, us
if use_subdomain is not None:
domain.name = use_subdomain == 'true'
+ encryption = instance.encryption or Encryption()
+ if encryption_services:
+ encryption.services = encryption_services
+ if encryption_key_source:
+ encryption.key_source = encryption_key_source
+ if encryption_key_vault_properties:
+ encryption.key_vault_properties = encryption_key_vault_properties
+
params = StorageAccountUpdateParameters(
sku=Sku(sku) if sku is not None else instance.sku,
tags=tags if tags is not None else instance.tags,
custom_domain=domain,
- encryption=encryption if encryption is not None else instance.encryption,
+ encryption=encryption,
access_tier=AccessTier(access_tier) if access_tier is not None else instance.access_tier,
enable_https_traffic_only=https_only if https_only is not None else instance.enable_https_traffic_only
)
| az storage account update encryption - syntax mismatch?
### Description
`az storage account update \
--name ${storageacct} --resource-group ${res_group} \
--encryption queue table blob file`
based on this in usage:
`[--encryption {queue,table,blob,file} [{queue,table,blob,file} ...]]`
results in
`az storage account update: error: __init__() got an unexpected keyword argument 'queue'`
issueing them one at a time appears to work.
---
### Environment summary
**Install Method:** nightly
**CLI Version:** azure-cli (2.0.12+1.dev20170808)
**OS Version:** Ubuntu 16.04 x64
**Shell Type:** bash
| Azure/azure-cli | diff --git a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py
index cfd57ca27..92da19ef3 100644
--- a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py
+++ b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py
@@ -6,14 +6,14 @@
import unittest
from argparse import Namespace
from six import StringIO
-from azure.cli.command_modules.storage._validators import (
- get_permission_validator, get_datetime_type, datetime, ipv4_range_type, resource_type_type, services_type,
- process_blob_source_uri, get_char_options_validator)
+
+from azure.cli.command_modules.storage._validators import (get_permission_validator, get_datetime_type, datetime,
+ ipv4_range_type, resource_type_type, services_type,
+ process_blob_source_uri, get_char_options_validator)
from azure.cli.core.profiles import get_sdk, ResourceType
from azure.cli.testsdk import api_version_constraint
-@api_version_constraint(ResourceType.MGMT_STORAGE, min_api='2016-12-01')
class TestStorageValidators(unittest.TestCase):
def setUp(self):
self.io = StringIO()
@@ -116,5 +116,59 @@ class TestStorageValidators(unittest.TestCase):
self.assertEqual(result, set('ab'))
+@api_version_constraint(resource_type=ResourceType.MGMT_STORAGE, min_api='2016-12-01')
+class TestEncryptionValidators(unittest.TestCase):
+ def test_validate_encryption_services(self):
+ from azure.cli.command_modules.storage._validators import validate_encryption_services
+
+ ns = Namespace(encryption_services=['blob'])
+ validate_encryption_services(ns)
+ self.assertIsNotNone(ns.encryption_services.blob)
+ self.assertTrue(ns.encryption_services.blob.enabled)
+ self.assertIsNone(ns.encryption_services.file)
+
+ ns = Namespace(encryption_services=['file'])
+ validate_encryption_services(ns)
+ self.assertIsNotNone(ns.encryption_services.file)
+ self.assertTrue(ns.encryption_services.file.enabled)
+ self.assertIsNone(ns.encryption_services.blob)
+
+ ns = Namespace(encryption_services=['blob', 'file'])
+ validate_encryption_services(ns)
+ self.assertIsNotNone(ns.encryption_services.blob)
+ self.assertTrue(ns.encryption_services.blob.enabled)
+ self.assertIsNotNone(ns.encryption_services.file)
+ self.assertTrue(ns.encryption_services.file.enabled)
+
+ def test_validate_encryption_source(self):
+ from azure.cli.command_modules.storage._validators import validate_encryption_source
+
+ with self.assertRaises(ValueError):
+ validate_encryption_source(Namespace(encryption_key_source='Notanoption'))
+
+ with self.assertRaises(ValueError):
+ validate_encryption_source(Namespace(encryption_key_source='Microsoft.Keyvault'))
+
+ with self.assertRaises(ValueError):
+ validate_encryption_source(Namespace(encryption_key_source='Microsoft.Storage',
+ encryption_key_name='key_name',
+ encryption_key_version='key_version',
+ encryption_key_vault='https://example.com/key_uri'))
+
+ ns = Namespace(encryption_key_source='Microsoft.Keyvault',
+ encryption_key_name='key_name',
+ encryption_key_version='key_version',
+ encryption_key_vault='https://example.com/key_uri')
+ validate_encryption_source(ns)
+ self.assertFalse(hasattr(ns, 'encryption_key_name'))
+ self.assertFalse(hasattr(ns, 'encryption_key_version'))
+ self.assertFalse(hasattr(ns, 'encryption_key_uri'))
+
+ properties = ns.encryption_key_vault_properties
+ self.assertEqual(properties.key_name, 'key_name')
+ self.assertEqual(properties.key_version, 'key_version')
+ self.assertEqual(properties.key_vault_uri, 'https://example.com/key_uri')
+
+
if __name__ == '__main__':
unittest.main()
| {
"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": 3,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 4
} | 2.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "python scripts/dev_setup.py",
"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 libssl-dev libffi-dev"
],
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | adal==0.4.3
applicationinsights==0.10.0
argcomplete==1.8.0
astroid==2.11.7
attrs==22.2.0
autopep8==2.0.4
azure-batch==3.1.0
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli&subdirectory=src/azure-cli
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_acr&subdirectory=src/command_modules/azure-cli-acr
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_acs&subdirectory=src/command_modules/azure-cli-acs
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_appservice&subdirectory=src/command_modules/azure-cli-appservice
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_batch&subdirectory=src/command_modules/azure-cli-batch
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_billing&subdirectory=src/command_modules/azure-cli-billing
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_cdn&subdirectory=src/command_modules/azure-cli-cdn
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_cloud&subdirectory=src/command_modules/azure-cli-cloud
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_cognitiveservices&subdirectory=src/command_modules/azure-cli-cognitiveservices
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_component&subdirectory=src/command_modules/azure-cli-component
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_configure&subdirectory=src/command_modules/azure-cli-configure
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_consumption&subdirectory=src/command_modules/azure-cli-consumption
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_container&subdirectory=src/command_modules/azure-cli-container
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_core&subdirectory=src/azure-cli-core
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_cosmosdb&subdirectory=src/command_modules/azure-cli-cosmosdb
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_dla&subdirectory=src/command_modules/azure-cli-dla
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_dls&subdirectory=src/command_modules/azure-cli-dls
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_eventgrid&subdirectory=src/command_modules/azure-cli-eventgrid
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_feedback&subdirectory=src/command_modules/azure-cli-feedback
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_find&subdirectory=src/command_modules/azure-cli-find
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_interactive&subdirectory=src/command_modules/azure-cli-interactive
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_iot&subdirectory=src/command_modules/azure-cli-iot
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_keyvault&subdirectory=src/command_modules/azure-cli-keyvault
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_lab&subdirectory=src/command_modules/azure-cli-lab
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_monitor&subdirectory=src/command_modules/azure-cli-monitor
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_network&subdirectory=src/command_modules/azure-cli-network
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_nspkg&subdirectory=src/azure-cli-nspkg
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_profile&subdirectory=src/command_modules/azure-cli-profile
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_rdbms&subdirectory=src/command_modules/azure-cli-rdbms
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_redis&subdirectory=src/command_modules/azure-cli-redis
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_resource&subdirectory=src/command_modules/azure-cli-resource
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_role&subdirectory=src/command_modules/azure-cli-role
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_sf&subdirectory=src/command_modules/azure-cli-sf
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_sql&subdirectory=src/command_modules/azure-cli-sql
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_storage&subdirectory=src/command_modules/azure-cli-storage
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_taskhelp&subdirectory=src/command_modules/azure-cli-taskhelp
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_testsdk&subdirectory=src/azure-cli-testsdk
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_utility_automation&subdirectory=scripts
-e git+https://github.com/Azure/azure-cli.git@966cbaa94a8eba13f89a220fb1fe73bed3e2244b#egg=azure_cli_vm&subdirectory=src/command_modules/azure-cli-vm
azure-common==1.1.28
azure-core==1.24.2
azure-datalake-store==0.0.15
azure-devtools==0.4.3
azure-graphrbac==0.30.0rc6
azure-keyvault==0.3.4
azure-mgmt-authorization==0.30.0rc6
azure-mgmt-batch==4.1.0
azure-mgmt-billing==0.1.0
azure-mgmt-cdn==0.30.2
azure-mgmt-cognitiveservices==1.0.0
azure-mgmt-compute==2.0.0
azure-mgmt-consumption==0.1.0
azure-mgmt-containerinstance==9.2.0
azure-mgmt-containerregistry==0.3.1
azure-mgmt-containerservice==1.0.0
azure-mgmt-core==1.3.2
azure-mgmt-datalake-analytics==0.1.6
azure-mgmt-datalake-nspkg==3.0.1
azure-mgmt-datalake-store==0.1.6
azure-mgmt-devtestlabs==2.0.0
azure-mgmt-dns==1.0.1
azure-mgmt-documentdb==0.1.3
azure-mgmt-iothub==0.2.2
azure-mgmt-keyvault==0.40.0
azure-mgmt-monitor==0.2.1
azure-mgmt-network==1.3.0
azure-mgmt-nspkg==1.0.0
azure-mgmt-rdbms==0.1.0
azure-mgmt-redis==1.0.0
azure-mgmt-resource==1.1.0
azure-mgmt-sql==0.6.0
azure-mgmt-storage==1.2.0
azure-mgmt-trafficmanager==0.30.0
azure-mgmt-web==0.32.0
azure-monitor==0.3.0
azure-multiapi-storage==0.1.2
azure-nspkg==1.0.0
azure-servicefabric==5.6.130
bleach==4.1.0
certifi==2021.5.30
cffi==1.15.1
colorama==0.3.7
ConfigArgParse==1.7
coverage==6.2
cryptography==40.0.2
docutils==0.18.1
flake8==5.0.4
futures==3.1.1
humanfriendly==2.4
idna==3.10
importlib-metadata==4.2.0
iniconfig==1.1.1
isodate==0.7.0
isort==5.10.1
jeepney==0.7.1
jmespath==0.10.0
keyring==23.4.1
lazy-object-proxy==1.7.1
mccabe==0.7.0
mock==5.2.0
msrest==0.7.1
msrestazure==0.4.34
nose==1.3.7
oauthlib==3.2.2
packaging==21.3
paramiko==2.0.2
pbr==6.1.1
pluggy==1.0.0
prompt-toolkit==3.0.36
py==1.11.0
pyasn1==0.5.1
pycodestyle==2.10.0
pycparser==2.21
pydocumentdb==2.3.5
pyflakes==2.5.0
Pygments==2.14.0
PyJWT==2.4.0
pylint==1.7.1
pyOpenSSL==16.2.0
pyparsing==3.1.4
pytest==7.0.1
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==3.11
readme-renderer==34.0
requests==2.9.1
requests-oauthlib==2.0.0
scp==0.15.0
SecretStorage==3.3.3
six==1.10.0
sshtunnel==0.4.0
tabulate==0.7.7
tomli==1.2.3
typed-ast==1.5.5
typing-extensions==4.1.1
urllib3==1.26.20
urllib3-secure-extra==0.1.0
vcrpy==1.10.3
vsts-cd-manager==0.118.0
wcwidth==0.2.13
webencodings==0.5.1
Whoosh==2.7.4
wrapt==1.16.0
xmltodict==0.14.2
zipp==3.6.0
| name: azure-cli
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- 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
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_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:
- adal==0.4.3
- applicationinsights==0.10.0
- argcomplete==1.8.0
- astroid==2.11.7
- attrs==22.2.0
- autopep8==2.0.4
- azure-batch==3.1.0
- azure-common==1.1.28
- azure-core==1.24.2
- azure-datalake-store==0.0.15
- azure-devtools==0.4.3
- azure-graphrbac==0.30.0rc6
- azure-keyvault==0.3.4
- azure-mgmt-authorization==0.30.0rc6
- azure-mgmt-batch==4.1.0
- azure-mgmt-billing==0.1.0
- azure-mgmt-cdn==0.30.2
- azure-mgmt-cognitiveservices==1.0.0
- azure-mgmt-compute==2.0.0
- azure-mgmt-consumption==0.1.0
- azure-mgmt-containerinstance==9.2.0
- azure-mgmt-containerregistry==0.3.1
- azure-mgmt-containerservice==1.0.0
- azure-mgmt-core==1.3.2
- azure-mgmt-datalake-analytics==0.1.6
- azure-mgmt-datalake-nspkg==3.0.1
- azure-mgmt-datalake-store==0.1.6
- azure-mgmt-devtestlabs==2.0.0
- azure-mgmt-dns==1.0.1
- azure-mgmt-documentdb==0.1.3
- azure-mgmt-iothub==0.2.2
- azure-mgmt-keyvault==0.40.0
- azure-mgmt-monitor==0.2.1
- azure-mgmt-network==1.3.0
- azure-mgmt-nspkg==1.0.0
- azure-mgmt-rdbms==0.1.0
- azure-mgmt-redis==1.0.0
- azure-mgmt-resource==1.1.0
- azure-mgmt-sql==0.6.0
- azure-mgmt-storage==1.2.0
- azure-mgmt-trafficmanager==0.30.0
- azure-mgmt-web==0.32.0
- azure-monitor==0.3.0
- azure-multiapi-storage==0.1.2
- azure-nspkg==1.0.0
- azure-servicefabric==5.6.130
- bleach==4.1.0
- cffi==1.15.1
- colorama==0.3.7
- configargparse==1.7
- coverage==6.2
- cryptography==40.0.2
- docutils==0.18.1
- flake8==5.0.4
- futures==3.1.1
- humanfriendly==2.4
- idna==3.10
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- isodate==0.7.0
- isort==5.10.1
- jeepney==0.7.1
- jmespath==0.10.0
- keyring==23.4.1
- lazy-object-proxy==1.7.1
- mccabe==0.7.0
- mock==5.2.0
- msrest==0.7.1
- msrestazure==0.4.34
- nose==1.3.7
- oauthlib==3.2.2
- packaging==21.3
- paramiko==2.0.2
- pbr==6.1.1
- pip==9.0.1
- pluggy==1.0.0
- prompt-toolkit==3.0.36
- py==1.11.0
- pyasn1==0.5.1
- pycodestyle==2.10.0
- pycparser==2.21
- pydocumentdb==2.3.5
- pyflakes==2.5.0
- pygments==2.14.0
- pyjwt==2.4.0
- pylint==1.7.1
- pyopenssl==16.2.0
- pyparsing==3.1.4
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==3.11
- readme-renderer==34.0
- requests==2.9.1
- requests-oauthlib==2.0.0
- scp==0.15.0
- secretstorage==3.3.3
- setuptools==30.4.0
- six==1.10.0
- sshtunnel==0.4.0
- tabulate==0.7.7
- tomli==1.2.3
- typed-ast==1.5.5
- typing-extensions==4.1.1
- urllib3==1.26.20
- urllib3-secure-extra==0.1.0
- vcrpy==1.10.3
- vsts-cd-manager==0.118.0
- wcwidth==0.2.13
- webencodings==0.5.1
- whoosh==2.7.4
- wrapt==1.16.0
- xmltodict==0.14.2
- zipp==3.6.0
prefix: /opt/conda/envs/azure-cli
| [
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py::TestEncryptionValidators::test_validate_encryption_services",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py::TestEncryptionValidators::test_validate_encryption_source"
]
| []
| [
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py::TestStorageValidators::test_datetime_string_type",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py::TestStorageValidators::test_datetime_type",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py::TestStorageValidators::test_ipv4_range_type",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py::TestStorageValidators::test_permission_validator",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py::TestStorageValidators::test_resource_types_type",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py::TestStorageValidators::test_services_type",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py::TestStorageValidators::test_storage_get_char_options_validator",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/tests/test_storage_validators.py::TestStorageValidators::test_storage_process_blob_source_uri_redundent_parameter"
]
| []
| MIT License | 1,602 | [
"src/command_modules/azure-cli-storage/HISTORY.rst",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_params.py",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/custom.py",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_validators.py"
]
| [
"src/command_modules/azure-cli-storage/HISTORY.rst",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_params.py",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/custom.py",
"src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_validators.py"
]
|
|
mjs__imapclient-271 | 82d1a275861b00b70bddf1127e1953d4daa93383 | 2017-08-19 09:44:10 | 2abdac690fa653fa2d0d55b7617be24101597698 | diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index 4452d6f..ebc13dd 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -39,11 +39,11 @@ __all__ = ['IMAPClient', 'DELETED', 'SEEN', 'ANSWERED', 'FLAGGED', 'DRAFT', 'REC
# We also offer the gmail-specific XLIST command...
if 'XLIST' not in imaplib.Commands:
- imaplib.Commands['XLIST'] = imaplib.Commands['LIST']
+ imaplib.Commands['XLIST'] = ('NONAUTH', 'AUTH', 'SELECTED')
# ...and IDLE
if 'IDLE' not in imaplib.Commands:
- imaplib.Commands['IDLE'] = imaplib.Commands['APPEND']
+ imaplib.Commands['IDLE'] = ('NONAUTH', 'AUTH', 'SELECTED')
# ..and STARTTLS
if 'STARTTLS' not in imaplib.Commands:
@@ -60,6 +60,11 @@ if 'ID' not in imaplib.Commands:
if 'UNSELECT' not in imaplib.Commands:
imaplib.Commands['UNSELECT'] = ('AUTH', 'SELECTED')
+# .. and ENABLE.
+if 'ENABLE' not in imaplib.Commands:
+ imaplib.Commands['ENABLE'] = ('AUTH',)
+
+
# System flags
DELETED = br'\Deleted'
SEEN = br'\Seen'
@@ -268,6 +273,35 @@ class IMAPClient(object):
"""
self._imap.shutdown()
+ def enable(self, *capabilities):
+ """Activate one or more server side capability extensions.
+
+ Most capabilities do not need to be enabled. This is only
+ required for extensions which introduce backwards incompatible
+ behaviour. Two capabilities which may require enable are
+ ``CONDSTORE`` and ``UTF8=ACCEPT``.
+
+ A list of the requested extensions that were successfully
+ enabled on the server is returned.
+
+ Once enabled each extension remains active until the IMAP
+ connection is closed.
+
+ See :rfc:`5161` for more details.
+ """
+ if self._imap.state != 'AUTH':
+ raise self.Error("ENABLE command illegal in state %s" % self._imap.state)
+
+ resp = self._raw_command_untagged(
+ b'ENABLE',
+ [to_bytes(c) for c in capabilities],
+ uid=False,
+ response_name='ENABLED',
+ unpack=True)
+ if not resp:
+ return []
+ return resp.split()
+
def id_(self, parameters=None):
"""Issue the ID command, returning a dict of server implementation
fields.
@@ -1117,16 +1151,18 @@ class IMAPClient(object):
self._checkok(command, typ, data)
return data[0], resps
- def _raw_command_untagged(self, command, args, unpack=False):
+ def _raw_command_untagged(self, command, args, response_name=None, unpack=False, uid=True):
# TODO: eventually this should replace _command_and_check (call it _command)
- typ, data = self._raw_command(command, args)
- typ, data = self._imap._untagged_response(typ, data, to_unicode(command))
+ typ, data = self._raw_command(command, args, uid=uid)
+ if response_name is None:
+ response_name = command
+ typ, data = self._imap._untagged_response(typ, data, to_unicode(response_name))
self._checkok(to_unicode(command), typ, data)
if unpack:
return data[0]
return data
- def _raw_command(self, command, args):
+ def _raw_command(self, command, args, uid=True):
"""Run the specific command with the arguments given. 8-bit arguments
are sent as literals. The return value is (typ, data).
@@ -1150,7 +1186,7 @@ class IMAPClient(object):
tag = self._imap._new_tag()
prefix = [to_bytes(tag)]
- if self.use_uid:
+ if uid and self.use_uid:
prefix.append(b'UID')
prefix.append(command)
| Support ENABLE extension
Originally reported by: **Menno Smits (Bitbucket: [mjs0](https://bitbucket.org/mjs0))**
---
https://tools.ietf.org/html/rfc5161
Use this to turn on CONDSTORE in livetests (better than current hack for Dovecot)
---
- Bitbucket: https://bitbucket.org/mjs0/imapclient/issue/139
| mjs/imapclient | diff --git a/imapclient/livetest.py b/imapclient/livetest.py
index 6260568..4192716 100644
--- a/imapclient/livetest.py
+++ b/imapclient/livetest.py
@@ -76,8 +76,11 @@ class _TestBase(unittest.TestCase):
@classmethod
def setUpClass(cls):
- cls.client = create_client_from_config(cls.conf)
- cls.client.use_uid = cls.use_uid
+ client = create_client_from_config(cls.conf)
+ cls.client = client
+ client.use_uid = cls.use_uid
+ if client.has_capability('ENABLE') and client.has_capability('CONDSTORE'):
+ client.enable('CONDSTORE')
cls.base_folder = cls.conf.namespace[0] + '__imapclient'
cls.folder_delimiter = cls.conf.namespace[1]
@@ -642,19 +645,6 @@ def createUidTestClass(conf, use_uid):
if not self.client.has_capability('CONDSTORE'):
return self.skipTest("Server doesn't support CONDSTORE")
- if self.is_gmail():
- return self.skipTest(
- "Gmail doesn't seem to return MODSEQ parts in SEARCH responses")
-
- # A little dance to ensure MODSEQ tracking is turned on.
- # TODO: use ENABLE for this instead
- self.client.select_folder(self.base_folder)
- self.append_msg(SIMPLE_MESSAGE)
- msg_id = self.client.search()[0]
- self.client.fetch(msg_id, ["MODSEQ"])
- self.client.close_folder()
- self.clear_folder(self.base_folder)
-
# Remember the initial MODSEQ
initial_modseq = self.client.select_folder(self.base_folder)[b'HIGHESTMODSEQ']
@@ -833,22 +823,10 @@ def createUidTestClass(conf, use_uid):
def test_fetch_modifiers(self):
# CONDSTORE (RFC 4551) provides a good way to use FETCH
- # modifiers but it isn't commonly available.
+ # modifiers but it isn't always available.
if not self.client.has_capability('CONDSTORE'):
return self.skipTest("Server doesn't support CONDSTORE")
- # A little dance to ensure MODSEQ tracking is turned on.
- self.client.select_folder(self.base_folder)
- self.append_msg(SIMPLE_MESSAGE)
- msg_id = self.client.search()[0]
- self.client.fetch(msg_id, ["MODSEQ"])
- self.client.close_folder()
- self.clear_folder(self.base_folder)
-
- #
- # Actual testing starts here
- #
-
# Get the starting MODSEQ
modseq = self.client.select_folder(self.base_folder)[b'HIGHESTMODSEQ']
diff --git a/imapclient/test/test_enable.py b/imapclient/test/test_enable.py
new file mode 100644
index 0000000..2d1fa10
--- /dev/null
+++ b/imapclient/test/test_enable.py
@@ -0,0 +1,70 @@
+# Copyright (c) 2017, Menno Smits
+# Released subject to the New BSD License
+# Please see http://en.wikipedia.org/wiki/BSD_licenses
+
+from __future__ import unicode_literals
+
+from mock import Mock
+
+from imapclient import IMAPClient
+from .imapclient_test import IMAPClientTest
+
+
+class TestEnable(IMAPClientTest):
+
+ def setUp(self):
+ super(TestEnable, self).setUp()
+ self.command = Mock()
+ self.client._raw_command_untagged = self.command
+ self.client._imap.state = 'AUTH'
+
+ def test_success(self):
+ self.command.return_value = b'CONDSTORE'
+
+ resp = self.client.enable('CONDSTORE')
+
+ self.command.assert_called_once_with(
+ b'ENABLE', [b'CONDSTORE'],
+ uid=False, response_name='ENABLED', unpack=True)
+ self.assertEqual(resp, [b'CONDSTORE'])
+
+ def test_failed1(self):
+ # When server returns an empty ENABLED response
+ self.command.return_value = b''
+
+ resp = self.client.enable('FOO')
+
+ self.command.assert_called_once_with(
+ b'ENABLE', [b'FOO'],
+ uid=False, response_name='ENABLED', unpack=True)
+ self.assertEqual(resp, [])
+
+ def test_failed2(self):
+ # When server returns no ENABLED response
+ self.command.return_value = None
+
+ resp = self.client.enable('FOO')
+
+ self.command.assert_called_once_with(
+ b'ENABLE', [b'FOO'],
+ uid=False, response_name='ENABLED', unpack=True)
+ self.assertEqual(resp, [])
+
+ def test_multiple(self):
+ self.command.return_value = b'FOO BAR'
+
+ resp = self.client.enable('FOO', 'BAR')
+
+ self.command.assert_called_once_with(
+ b'ENABLE', [b'FOO', b'BAR'],
+ uid=False, response_name='ENABLED', unpack=True)
+ self.assertEqual(resp, [b'FOO', b'BAR'])
+
+ def test_wrong_state(self):
+ self.client._imap.state = 'SELECTED'
+
+ self.assertRaises(
+ IMAPClient.Error,
+ self.client.enable,
+ 'FOO',
+ )
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"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": 1
},
"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": [
"mock>=1.3.0",
"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
backports.ssl==0.0.9
certifi==2021.5.30
cffi==1.15.1
cryptography==40.0.2
-e git+https://github.com/mjs/imapclient.git@82d1a275861b00b70bddf1127e1953d4daa93383#egg=IMAPClient
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mock==5.2.0
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
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
pycparser==2.21
pyOpenSSL==23.2.0
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: imapclient
channels:
- defaults
- https://repo.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:
- backports-ssl==0.0.9
- cffi==1.15.1
- cryptography==40.0.2
- mock==5.2.0
- pycparser==2.21
- pyopenssl==23.2.0
- six==1.17.0
prefix: /opt/conda/envs/imapclient
| [
"imapclient/test/test_enable.py::TestEnable::test_failed1",
"imapclient/test/test_enable.py::TestEnable::test_failed2",
"imapclient/test/test_enable.py::TestEnable::test_multiple",
"imapclient/test/test_enable.py::TestEnable::test_success",
"imapclient/test/test_enable.py::TestEnable::test_wrong_state"
]
| []
| []
| []
| BSD License | 1,603 | [
"imapclient/imapclient.py"
]
| [
"imapclient/imapclient.py"
]
|
|
pydicom__pydicom-487 | 4cecd5195fbc10a47f61ff2f70426f300799be1f | 2017-08-20 03:58:19 | bef49851e7c3b70edd43cc40fc84fe905e78d5ba | pep8speaks: Hello @scaramallion! Thanks for submitting the PR.
- In the file [`pydicom/dataset.py`](https://github.com/pydicom/pydicom/blob/201f53ec6ffe632f4875418ee6cd3a2375e88ffa/pydicom/dataset.py), following are the PEP8 issues :
> [Line 339:80](https://github.com/pydicom/pydicom/blob/201f53ec6ffe632f4875418ee6cd3a2375e88ffa/pydicom/dataset.py#L339): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (81 > 79 characters)
> [Line 341:80](https://github.com/pydicom/pydicom/blob/201f53ec6ffe632f4875418ee6cd3a2375e88ffa/pydicom/dataset.py#L341): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (85 > 79 characters)
| diff --git a/README.md b/README.md
index 13667dbc0..457d83603 100644
--- a/README.md
+++ b/README.md
@@ -27,4 +27,4 @@ Documentation
pydicom [documentation](https://pydicom.readthedocs.org/en/stable/) is available on Read The Docs.
-See [Getting Started](https://pydicom.readthedocs.org/en/stable/getting_started.html) for installation and basic information, and the [User Guide](https://pydicom.readthedocs.org/en/stable/pydicom_user_guide.html) for an overview of how to use the pydicom library.
+See [Getting Started](https://pydicom.readthedocs.org/en/stable/getting_started.html) for installation and basic information, and the [User Guide](https://pydicom.readthedocs.org/en/stable/pydicom_user_guide.html) for an overview of how to use the pydicom library. To contribute to pydicom, read our [contribution guide](CONTRIBUTING.md). To contribute an example or extension of pydicom that does not belong with the core software, see our contribution repository, [contrib-pydicom](https://www.github.com/pydicom/contrib-pydicom).
diff --git a/doc/pydicom_user_guide.rst b/doc/pydicom_user_guide.rst
index 6d85c4a62..5f16ce768 100644
--- a/doc/pydicom_user_guide.rst
+++ b/doc/pydicom_user_guide.rst
@@ -9,4 +9,4 @@ Pydicom User Guide
transition_to_pydicom1.rst
base_element.rst
working_with_pixel_data.rst
- viewing_images.rst
+ viewing_images.rst
\ No newline at end of file
diff --git a/doc/viewing_images.rst b/doc/viewing_images.rst
index 3f6f1a66e..5132c4e36 100644
--- a/doc/viewing_images.rst
+++ b/doc/viewing_images.rst
@@ -47,8 +47,8 @@ Using pydicom with Tkinter
--------------------------
The program `pydicom_Tkinter.py
-<https://github.com/pydicom/pydicom/blob/master/pydicom/contrib/pydicom_Tkinter.py>`_
-in the ``contrib`` folder demonstrates how to show an image using the
+<https://github.com/pydicom/contrib-pydicom/blob/master/viewers/pydicom_Tkinter.py>`_
+in the ``contrib-pydicom`` repository demonstrates how to show an image using the
Tkinter graphics system, which comes standard with most python installs.
It creates a Tkinter PhotoImage in a Label widget or a user-supplied widget.
@@ -56,8 +56,8 @@ Using pydicom with Python Imaging Library (PIL)
-----------------------------------------------
The module `pydicom_PIL.py
-<https://github.com/pydicom/pydicom/blob/master/pydicom/contrib/pydicom_PIL.py>`_
-in the ``contrib`` folder
+<https://github.com/pydicom/contrib-pydicom/blob/master/viewers/pydicom_PIL.py>`_
+in the ``contrib-pydicom`` repository
uses PIL's ``Image.show()`` method after creating an Image instance
from the pixel data and some basic information about it (bit depth, LUTs, etc)
@@ -65,6 +65,6 @@ Using pydicom with wxPython
---------------------------
The module `imViewer-Simple.py
-<https://github.com/pydicom/pydicom/blob/master/pydicom/contrib/imViewer_Simple.py>`_
-in the ``contrib`` folder uses wxPython (also PIL, but it notes that it
-may not be strictly necessary) to display an image from a pydicom dataset.
+<https://github.com/pydicom/contrib-pydicom/blob/master/viewers/imViewer_Simple.py>`
+in the ``contrib-pydicom`` repository uses wxPython (also PIL, but it notes that it
+may not be strictly necessary) to display an image from a pydicom dataset.
\ No newline at end of file
diff --git a/pydicom/contrib/__init__.py b/pydicom/contrib/__init__.py
deleted file mode 100644
index c8438e83e..000000000
--- a/pydicom/contrib/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-# __init__.py
-# Mark the folder as a python package
diff --git a/pydicom/contrib/dcm_qt_tree.py b/pydicom/contrib/dcm_qt_tree.py
deleted file mode 100644
index aaa70c98c..000000000
--- a/pydicom/contrib/dcm_qt_tree.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# dcm_qt_tree.py
-"""View DICOM files in a tree using Qt and PySide"""
-# Copyright (c) 2013 Padraig Looney
-# This file is released under the
-# pydicom (https://github.com/pydicom/pydicom)
-# license, see the file LICENSE available at
-# (https://github.com/pydicom/pydicom)
-
-import pydicom
-import sys
-from PySide import QtGui
-import collections
-
-
-class DicomTree(object):
- def __init__(self, filename):
- self.filename = filename
-
- def show_tree(self):
- ds = self.dicom_to_dataset(self.filename)
- dic = self.dataset_to_dic(ds)
- model = self.dic_to_model(dic)
- self.display(model)
-
- def array_to_model(self, array):
- model = QtGui.QStandardItemModel()
- parentItem = model.invisibleRootItem()
- for ntuple in array:
- tag = ntuple[0]
- value = ntuple[1]
- if isinstance(value, dict):
- self.recurse_dic_to_item(value, parentItem)
- else:
- item = QtGui.QStandardItem(tag + str(value))
- parentItem.appendRow(item)
- return parentItem
-
- def dic_to_model(self, dic):
- model = QtGui.QStandardItemModel()
- parentItem = model.invisibleRootItem()
- self.recurse_dic_to_item(dic, parentItem)
- return model
-
- def dataset_to_array(self, dataset):
- array = []
- for data_element in dataset:
- array.append(self.data_element_to_dic(data_element))
- return array
-
- def recurse_dic_to_item(self, dic, parent):
- for k in dic:
- v = dic[k]
- if isinstance(v, dict):
- item = QtGui.QStandardItem(k + ':' + str(v))
- parent.appendRow(self.recurse_dic_to_item(v, item))
- else:
- item = QtGui.QStandardItem(k + ': ' + str(v))
- parent.appendRow(item)
- return parent
-
- def dicom_to_dataset(self, filename):
- dataset = pydicom.read_file(filename, force=True)
- return dataset
-
- def data_element_to_dic(self, data_element):
- dic = collections.OrderedDict()
- if data_element.VR == "SQ":
- items = collections.OrderedDict()
- dic[data_element.name] = items
- i = 0
- for dataset_item in data_element:
- items['item ' + str(i)] = self.dataset_to_dic(dataset_item)
- i += 1
- elif data_element.name != 'Pixel Data':
- dic[data_element.name] = data_element.value
- return dic
-
- def dataset_to_dic(self, dataset):
- dic = collections.OrderedDict()
- for data_element in dataset:
- dic.update(self.data_element_to_dic(data_element))
- return dic
-
- def display(self, model):
- app = QtGui.QApplication.instance()
-
- # create QApplication if it doesnt exist
- if not app:
- app = QtGui.QApplication(sys.argv)
- tree = QtGui.QTreeView()
- tree.setModel(model)
- tree.show()
- app.exec_()
- return tree
-
-
-def main():
- filename = sys.argv[1]
- dicomTree = DicomTree(filename)
- dicomTree.show_tree()
-
-
-if __name__ == "__main__":
- main()
diff --git a/pydicom/contrib/dicom_dao.py b/pydicom/contrib/dicom_dao.py
deleted file mode 100644
index 549e0888d..000000000
--- a/pydicom/contrib/dicom_dao.py
+++ /dev/null
@@ -1,460 +0,0 @@
-#!/usr/bin/python
-""" dicom_dao
-
-Data Access Objects for persisting PyDicom DataSet objects.
-
-Currently we support couchdb through the DicomCouch class.
-
-Limitations:
- - Private tags are discarded
-
-TODO:
- - Unit tests with multiple objects open at a time
- - Unit tests with rtstruct objects
- - Support for mongodb (mongo has more direct support for binary data)
-
-Dependencies:
- - PyDicom
- - python-couchdb
-
-Tested with:
- - PyDicom 0.9.4-1
- - python-couchdb 0.6
- - couchdb 0.10.1
-
-"""
-
-#
-# Copyright (c) 2010 Michael Wallace
-# This file is released under the pydicom license.
-# See the file LICENSE included with the pydicom distribution, also
-# available at https://github.com/pydicom/pydicom
-#
-
-import hashlib
-import os
-import string
-import couchdb
-import pydicom
-
-
-def uid2str(uid):
- """ Convert PyDicom uid to a string """
- return repr(uid).strip("'")
-
-
-# When reading files a VR of 'US or SS' is left as binary,
-# because we don't know how to interpret the values
-# different numbers. We therefore treat it as binary
-# and will continue to until either pydicom works it out
-# for us, or we figure out a test.
-
-BINARY_VR_VALUES = ['OW', 'OB', 'OW/OB', 'US or SS']
-
-
-class DicomCouch(dict):
- """ A Data Access Object for persisting
- PyDicom objects into CouchDB
-
- We follow the same pattern as the python-couchdb
- library for getting and setting documents, for
- example storing pydicom.dataset.Dataset object dcm:
- db = DicomCouch('http://localhost:5984/', 'dbname')
- db[dcm.SeriesInstanceUID] = dcm
-
- The only constraints on the key are that it must be
- json-serializable and unique within the database instance.
- In theory it should be possible to use any DICOM UID.
- Unfortunately I have written this code under the assumption
- that SeriesInstanceUID will always be used.
- This will be fixed.
-
- Retrieving object with key 'foo':
- dcm = db['foo']
-
- Deleting object with key 'foo':
- dcm = db['foo']
- db.delete(dcm)
-
- TODO:
- - It is possible to have couchdb assign a uid
- when adding objects. This
- should be supported.
- """
-
- def __init__(self, server, db):
- """ Create connection to couchdb server/db """
- super(DicomCouch, self).__init__()
- self._meta = {}
- server = couchdb.Server(server)
- try:
- self._db = server[db]
- except couchdb.client.ResourceNotFound:
- self._db = server.create(db)
-
- def __getitem__(self, key):
- """ Retrieve DICOM object with
- specified SeriesInstanceUID """
- doc = self._db[key]
- dcm = json2pydicom(doc)
-
- if dcm.SeriesInstanceUID not in self._meta:
- self._meta[dcm.SeriesInstanceUID] = {}
- self._meta[dcm.SeriesInstanceUID]['hashes'] = {}
-
- if '_attachments' in doc:
- self.__get_attachments(dcm, doc)
- _set_meta_info_dcm(dcm)
- # Keep a copy of the couch doc for use in DELETE operations
- self._meta[dcm.SeriesInstanceUID]['doc'] = doc
- return dcm
-
- def __setitem__(self, key, dcm):
- """ Write the supplied DICOM object to the database """
- try:
- dcm.PixelData = dcm.pixel_array.tostring()
-
- # Silently ignore errors due to pixel_array not existing
- except AttributeError:
- pass
-
- # Silently ignore attempts to modify compressed pixel data
- except NotImplementedError:
- pass
-
- # Silently ignore errors due to PixelData not existing
- except TypeError:
- pass
-
- jsn,
- binary_elements,
- file_meta_binary_elements = pydicom2json(dcm)
-
- _strip_elements(jsn, binary_elements)
- _strip_elements(jsn['file_meta'], file_meta_binary_elements)
- if dcm.SeriesInstanceUID in self._meta:
- self.__set_meta_info_jsn(jsn, dcm)
-
- try: # Actually write to the db
- self._db[key] = jsn
- except TypeError as type_error:
- if str(type_error) == 'string indices must be integers, not str':
- pass
-
- if dcm.SeriesInstanceUID not in self._meta:
- self._meta[dcm.SeriesInstanceUID] = {}
- self._meta[dcm.SeriesInstanceUID]['hashes'] = {}
-
- self.__put_attachments(dcm, binary_elements, jsn)
- # Get a local copy of the document
- # We get this from couch because we get the _id,
- # _rev and _attachments keys which will ensure
- # we don't overwrite the attachments we just uploaded.
- # I don't really like the extra HTTP GET and
- # I think we can generate what we need without doing
- # it. Don't have time to work out how yet.
- self._meta[dcm.SeriesInstanceUID]['doc'] = \
- self._db[dcm.SeriesInstanceUID]
-
- def __str__(self):
- """ Return the string representation of the
- couchdb client """
- return str(self._db)
-
- def __repr__(self):
- """ Return the canonical string representation
- of the couchdb client """
- return repr(self._db)
-
- def __get_attachments(self, dcm, doc):
- """ Set binary tags by retrieving attachments
- from couchdb.
-
- Values are hashed so they are only updated
- if they have changed.
-
- """
- for id in doc['_attachments'].keys():
- tagstack = id.split(':')
- value = self._db.get_attachment(doc['_id'], id)
- _add_element(dcm, tagstack, value)
- value = hashlib.md5(value)
- self._meta[dcm.SeriesInstanceUID]['hashes'][id] = value
-
- def __put_attachments(self, dcm, binary_elements, jsn):
- """ Upload all new and modified attachments """
- func = self.__attachment_update_needed
- elements_to_update = \
- [(tagstack, item)
- for tagstack, item in binary_elements
- if func(dcm,
- _tagstack2id(tagstack + [item.tag]),
- item)
- ] # nopep8
- for tagstack, element in elements_to_update:
- id = _tagstack2id(tagstack + [element.tag])
- self._db.put_attachment(jsn, element.value, id)
- self._meta[dcm.SeriesInstanceUID]['hashes'][id] = \
- hashlib.md5(element.value)
-
- def delete(self, dcm):
- """ Delete from database and remove meta info from the DAO """
- self._db.delete(self._meta[dcm.SeriesInstanceUID]['doc'])
- self._meta.pop(dcm.SeriesInstanceUID)
-
- def __set_meta_info_jsn(self, jsn, dcm):
- """ Set the couch-specific meta data for supplied dict """
- jsn['_rev'] = self._meta[dcm.SeriesInstanceUID]['doc']['_rev']
- if '_attachments' in self._meta[dcm.SeriesInstanceUID]['doc']:
- jsn['_attachments'] = \
- self._meta[dcm.SeriesInstanceUID]['doc']['_attachments']
-
- def __attachment_update_needed(self, dcm, id, binary_element):
- """ Compare hashes for binary element and return true if different """
- try:
- hashes = self._meta[dcm.SeriesInstanceUID]['hashes']
- except KeyError:
- return True # If no hashes dict then attachments do not exist
-
- if id not in hashes or hashes[id].digest() != \
- hashlib.md5(binary_element.value).digest():
- return True
- else:
- return False
-
-
-def _add_element(dcm, tagstack, value):
- """ Add element with tag, vr and value to dcm
- at location tagstack """
- current_node = dcm
- for item in tagstack[:-1]:
- try:
- address = int(item)
- except ValueError:
- address = pydicom.tag.Tag(__str2tag(item))
- current_node = current_node[address]
- tag = __str2tag(tagstack[-1])
- vr = pydicom.datadict.dictionary_VR(tag)
- current_node[tag] = pydicom.dataelem.DataElement(tag, vr, value)
-
-
-def _tagstack2id(tagstack):
- """ Convert a list of tags to a unique
- (within document) attachment id """
- return string.join([str(tag) for tag in tagstack], ':')
-
-
-def _strip_elements(jsn, elements):
- """ Remove supplied elements from the dict object
-
- We use this with a list of binary elements so that
- we don't store empty tags in couchdb when we are
- already storing the binary data as
- attachments.
-
- """
- for tagstack, element in elements:
- if len(tagstack) == 0:
- jsn.pop(element.tag)
- else:
- current_node = jsn
- for tag in tagstack:
- current_node = current_node[tag]
- current_node.pop(element.tag)
-
-
-def _set_meta_info_dcm(dcm):
- """ Set the file metadata DataSet attributes
-
- This is done by PyDicom when we pydicom.read_file(foo)
- but we need to do it ourselves when creating
- a DataSet from scratch, otherwise we cannot use
- foo.pixel_array or pydicom.write_file(foo).
-
- This code is lifted from PyDicom.
-
- """
- TransferSyntax = dcm.file_meta.TransferSyntaxUID
- if TransferSyntax == pydicom.uid.ExplicitVRLittleEndian:
- dcm.is_implicit_vr = False
-
- # This line not in PyDicom
- dcm.is_little_endian = True
-
- elif TransferSyntax == pydicom.uid.ImplicitVRLittleEndian:
- dcm.is_implicit_vr = True
- dcm.is_little_endian = True
-
- elif TransferSyntax == pydicom.uid.ExplicitVRBigEndian:
- dcm.is_implicit_vr = False
- dcm.is_little_endian = False
-
- elif TransferSyntax == pydicom.uid.DeflatedExplicitVRLittleEndian:
-
- # Deleted lines above as it relates
- dcm.is_implicit_vr = False
-
- # to reading compressed file data.
- dcm.is_little_endian = True
-
- else:
- # Any other syntax should be Explicit VR Little Endian,
- # e.g. all Encapsulated (JPEG etc) are ExplVR-LE by
- # Standard PS 3.5-2008 A.4 (p63)
- dcm.is_implicit_vr = False
- dcm.is_little_endian = True
-
-
-def pydicom2json(dcm):
- """ Convert the supplied PyDicom object into a
- json-serializable dict
-
- Binary elements cannot be represented in json
- so we return these as as separate list of the
- tuple (tagstack, element), where:
- - element = pydicom.dataelem.DataElement
- - tagstack = list of tags/sequence IDs that address
- the element
-
- The tagstack variable means we know the absolute
- address of each binary element. We then use this as
- the attachment id in couchdb - when we retrieve
- the attachment we can then insert it at the
- appropriate point in the tree.
-
- """
- dcm.remove_private_tags() # No support for now
- dcm.decode() # Convert to unicode
- binary_elements = []
- tagstack = []
- jsn = dict((key, __jsonify(dcm[key], binary_elements, tagstack))
- for key in dcm.keys())
- file_meta_binary_elements = []
- jsn['file_meta'] = dict((key, __jsonify(dcm.file_meta[key],
- file_meta_binary_elements, tagstack))
- for key in dcm.file_meta.keys())
- return jsn, binary_elements, file_meta_binary_elements
-
-
-def __jsonify(element, binary_elements, tagstack):
- """ Convert key, value to json-serializable types
-
- Recursive, so if value is key/value pairs then
- all children will get converted
-
- """
- value = element.value
- if element.VR in BINARY_VR_VALUES:
- binary_elements.append((tagstack[:], element))
- return ''
- elif type(value) == list:
- new_list = [__typemap(listvalue) for listvalue in value]
- return new_list
- elif type(value) == pydicom.sequence.Sequence:
- tagstack.append(element.tag)
- nested_data = []
- for i in range(0, len(value)):
- tagstack.append(i)
- nested_data.append(
- dict((subkey, __jsonify(value[i][subkey],
- binary_elements, tagstack))
- for subkey in value[i].keys()))
- tagstack.pop()
- tagstack.pop()
- return nested_data
- else:
- return __typemap(value)
-
-
-def __typemap(value):
- """ Map PyDicom types that won't serialize
- to JSON types """
- if type(value) == pydicom.uid.UID:
- return uid2str(value)
- elif isinstance(value, pydicom.tag.BaseTag):
- return int(value)
- else:
- return value
-
-
-def json2pydicom(jsn):
- """ Convert the supplied json dict into
- a PyDicom object """
- dataset = pydicom.dataset.Dataset()
- # Don't try to convert couch specific tags
- dicom_keys = [
- key for key in jsn.keys()
- if key not in ['_rev', '_id', '_attachments', 'file_meta']
- ]
- for key in dicom_keys:
- dataset.add(__dicomify(key, jsn[key]))
- file_meta = pydicom.dataset.Dataset()
- for key in jsn['file_meta']:
- file_meta.add(__dicomify(key, jsn['file_meta'][key]))
- dataset.file_meta = file_meta
- return dataset
-
-
-def __dicomify(key, value):
- """ Convert a json key, value to a PyDicom DataElement """
- tag = __str2tag(key)
-
- # 0 tag implies group length (filreader.py pydicom)
- if tag.element == 0:
- vr = 'UL'
- else:
- vr = pydicom.datadict.dictionary_VR(tag)
-
- if vr == 'OW/OB': # Always write pixel data as bytes
- vr = 'OB' # rather than words
-
- if vr == 'US or SS': # US or SS is up to us as the data is already
- if value < 0: # decoded. We therefore choose US, unless we
- vr = 'SS' # need a signed value.
- else:
- vr = 'US'
-
- if vr == 'SQ': # We have a sequence of datasets, so we recurse
- seq_list = [__make_dataset([__dicomify(subkey, listvalue[subkey])
- for subkey in listvalue.keys()])
- for listvalue in value
- ]
- seq = pydicom.sequence.Sequence(seq_list)
- return pydicom.dataelem.DataElement(tag, vr, seq)
- else:
- return pydicom.dataelem.DataElement(tag, vr, value)
-
-
-def __make_dataset(data_elements):
- """ Create a Dataset from a list of DataElement objects """
- dataset = pydicom.dataset.Dataset()
- for element in data_elements:
- dataset.add(element)
- return dataset
-
-
-def __str2tag(key):
- """ Convert string representation of a tag into a Tag """
- return pydicom.tag.Tag((int(key[1:5], 16), int(key[7:-1], 16)))
-
-
-if __name__ == '__main__':
- TESTDB = 'dicom_test'
- SERVER = 'http://127.0.0.1:5984'
- # Delete test database if it already exists
- couch = couchdb.Server(SERVER)
- try:
- couch.delete(TESTDB)
- except couchdb.client.ResourceNotFound:
- pass # Don't worry if it didn't exist
-
- db = DicomCouch(SERVER, TESTDB)
-
- testfiles_dir = '../testfiles'
- testfiles = os.listdir('../testfiles')
- testfiles = [x for x in testfiles if x.endswith('dcm')]
- testfiles = [os.path.join('../testfiles', x) for x in testfiles]
-
- for dcmfile in testfiles:
- dcm = pydicom.read_file(dcmfile)
- db[dcm.SeriesInstanceUID] = dcm
diff --git a/pydicom/contrib/imViewer_Simple.py b/pydicom/contrib/imViewer_Simple.py
deleted file mode 100644
index ae98aea9c..000000000
--- a/pydicom/contrib/imViewer_Simple.py
+++ /dev/null
@@ -1,347 +0,0 @@
-# ===================================================================
-# imViewer-Simple.py
-#
-# An example program that opens uncompressed DICOM images and
-# converts them via numPy and PIL to be viewed in wxWidgets GUI
-# apps. The conversion is currently:
-#
-# pydicom->NumPy->PIL->wxPython.Image->wxPython.Bitmap
-#
-# Gruesome but it mostly works. Surely there is at least one
-# of these steps that could be eliminated (probably PIL) but
-# haven't tried that yet and I may want some of the PIL manipulation
-# functions.
-#
-# This won't handle RLE, embedded JPEG-Lossy, JPEG-lossless,
-# JPEG2000, old ACR/NEMA files, or anything wierd. Also doesn't
-# handle some RGB images that I tried.
-#
-# Have added Adit Panchal's LUT code. It helps a lot, but needs
-# to be further generalized. Added test for window and/or level
-# as 'list' type - crude, but it worked for a bunch of old MR and
-# CT slices I have.
-#
-# Testing: minimal
-# Tried only on WinXP sp2 using numpy 1.3.0
-# and PIL 1.1.7b1, Python 2.6.4, and wxPython 2.8.10.1
-#
-# Dave Witten: Nov. 11, 2009
-# ===================================================================
-
-import pydicom
-import wx
-from pydicom import compat
-have_PIL = True
-try:
- import PIL.Image
-except ImportError:
- have_PIL = False
-have_numpy = True
-try:
- import numpy as np
-except ImportError:
- have_numpy = False
-
-# ----------------------------------------------------------------
-# Initialize image capabilities.
-# ----------------------------------------------------------------
-
-wx.InitAllImageHandlers()
-
-
-def MsgDlg(window, string, caption='OFAImage', style=wx.YES_NO | wx.CANCEL):
- """Common MessageDialog."""
- dlg = wx.MessageDialog(window, string, caption, style)
- result = dlg.ShowModal()
- dlg.Destroy()
- return result
-
-
-class ImFrame(wx.Frame):
- """Class for main window."""
-
- def __init__(self, parent, title):
- """Create the pydicom image example's main frame window."""
-
- style = wx.DEFAULT_FRAME_STYLE | wx.SUNKEN_BORDER | wx.CLIP_CHILDREN
-
- wx.Frame.__init__(
- self,
- parent,
- id=-1,
- title="",
- pos=wx.DefaultPosition,
- size=wx.Size(w=1024, h=768),
- style=style)
-
- # --------------------------------------------------------
- # Set up the menubar.
- # --------------------------------------------------------
- self.mainmenu = wx.MenuBar()
-
- # Make the 'File' menu.
- menu = wx.Menu()
- item = menu.Append(wx.ID_ANY, '&Open', 'Open file for editing')
- self.Bind(wx.EVT_MENU, self.OnFileOpen, item)
- item = menu.Append(wx.ID_ANY, 'E&xit', 'Exit Program')
- self.Bind(wx.EVT_MENU, self.OnFileExit, item)
- self.mainmenu.Append(menu, '&File')
-
- # Attach the menu bar to the window.
- self.SetMenuBar(self.mainmenu)
-
- # --------------------------------------------------------
- # Set up the main splitter window.
- # --------------------------------------------------------
- self.mainSplitter = wx.SplitterWindow(self, style=wx.NO_3D | wx.SP_3D)
- self.mainSplitter.SetMinimumPaneSize(1)
-
- # -------------------------------------------------------------
- # Create the folderTreeView on the left.
- # -------------------------------------------------------------
- dsstyle = wx.TR_LINES_AT_ROOT | wx.TR_HAS_BUTTONS
- self.dsTreeView = wx.TreeCtrl(self.mainSplitter, style=dsstyle)
-
- # --------------------------------------------------------
- # Create the ImageView on the right pane.
- # --------------------------------------------------------
- imstyle = wx.VSCROLL | wx.HSCROLL | wx.CLIP_CHILDREN
- self.imView = wx.Panel(self.mainSplitter, style=imstyle)
-
- self.imView.Bind(wx.EVT_PAINT, self.OnPaint)
- self.imView.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
-
- self.imView.Bind(wx.EVT_SIZE, self.OnSize)
-
- # --------------------------------------------------------
- # Install the splitter panes.
- # --------------------------------------------------------
- self.mainSplitter.SplitVertically(self.dsTreeView, self.imView)
- self.mainSplitter.SetSashPosition(300, True)
-
- # --------------------------------------------------------
- # Initialize some values
- # --------------------------------------------------------
- self.dcmdsRoot = False
- self.foldersRoot = False
- self.loadCentered = True
- self.bitmap = None
- self.Show(True)
-
- def OnFileExit(self, event):
- """Exits the program."""
- self.Destroy()
- event.Skip()
-
- def OnSize(self, event):
- "Window 'size' event."
- self.Refresh()
-
- def OnEraseBackground(self, event):
- "Window 'erase background' event."
- pass
-
- def populateTree(self, ds):
- """ Populate the tree in the left window with the [desired]
- dataset values"""
- if not self.dcmdsRoot:
- self.dcmdsRoot = self.dsTreeView.AddRoot(text="DICOM Objects")
- else:
- self.dsTreeView.DeleteChildren(self.dcmdsRoot)
- self.recurse_tree(ds, self.dcmdsRoot)
- self.dsTreeView.ExpandAll()
-
- def recurse_tree(self, ds, parent, hide=False):
- """ order the dicom tags """
- for data_element in ds:
- if isinstance(data_element.value, compat.text_type):
- text = compat.text_type(data_element)
- ip = self.dsTreeView.AppendItem(parent, text=text)
- else:
- ip = self.dsTreeView.AppendItem(parent, text=str(data_element))
-
- if data_element.VR == "SQ":
- for i, ds in enumerate(data_element.value):
- item_describe = data_element.name.replace(" Sequence", "")
- item_text = "%s %d" % (item_describe, i + 1)
- rjust = item_text.rjust(128)
- parentNodeID = self.dsTreeView.AppendItem(ip, text=rjust)
- self.recurse_tree(ds, parentNodeID)
-
-# --- Most of what is important happens below this line ---------------------
-
- def OnFileOpen(self, event):
- """Opens a selected file."""
- msg = 'Choose a file to add.'
- dlg = wx.FileDialog(self, msg, '', '', '*.*', wx.OPEN)
- if dlg.ShowModal() == wx.ID_OK:
- fullPath = dlg.GetPath()
- imageFile = dlg.GetFilename()
- # checkDICMHeader()
- self.show_file(imageFile, fullPath)
-
- def OnPaint(self, event):
- "Window 'paint' event."
- dc = wx.PaintDC(self.imView)
- dc = wx.BufferedDC(dc)
-
- # paint a background just so it isn't *so* boring.
- dc.SetBackground(wx.Brush("WHITE"))
- dc.Clear()
- dc.SetBrush(wx.Brush("GREY", wx.CROSSDIAG_HATCH))
- windowsize = self.imView.GetSizeTuple()
- dc.DrawRectangle(0, 0, windowsize[0], windowsize[1])
- bmpX0 = 0
- bmpY0 = 0
- if self.bitmap is not None:
- if self.loadCentered:
- bmpX0 = (windowsize[0] - self.bitmap.Width) / 2
- bmpY0 = (windowsize[1] - self.bitmap.Height) / 2
- dc.DrawBitmap(self.bitmap, bmpX0, bmpY0, False)
-
- # ------------------------------------------------------------
- # ImFrame.ConvertWXToPIL()
- # Expropriated from Andrea Gavana's
- # ShapedButton.py in the wxPython dist
- # ------------------------------------------------------------
- def ConvertWXToPIL(self, bmp):
- """ Convert wx.Image Into PIL Image. """
- width = bmp.GetWidth()
- height = bmp.GetHeight()
- im = wx.EmptyImage(width, height)
- im.fromarray("RGBA", (width, height), bmp.GetData())
- return im
-
- # ------------------------------------------------------------
- # ImFrame.ConvertPILToWX()
- # Expropriated from Andrea Gavana's
- # ShapedButton.py in the wxPython dist
- # ------------------------------------------------------------
- def ConvertPILToWX(self, pil, alpha=True):
- """ Convert PIL Image Into wx.Image. """
- if alpha:
- image = wx.EmptyImage(*pil.size)
- image.SetData(pil.convert("RGB").tostring())
- image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
- else:
- image = wx.EmptyImage(pil.size[0], pil.size[1])
- new_image = pil.convert('RGB')
- data = new_image.tostring()
- image.SetData(data)
- return image
-
- def get_LUT_value(self, data, window, level):
- """Apply the RGB Look-Up Table for the given
- data and window/level value."""
- if not have_numpy:
- raise ImportError("Numpy is not available. "
- "See http://numpy.scipy.org/ "
- "to download and install")
-
- if isinstance(window, list):
- window = window[0]
- if isinstance(level, list):
- level = level[0]
-
- win = window
- lvl = level
-
- e = [
- 0, 255,
- lambda data: ((data - (lvl - 0.5)) / (win - 1) + 0.5) * (255 - 0)
- ]
- return np.piecewise(data, [
- data <= (lvl - 0.5 - (win - 1) / 2),
- data > (lvl - 0.5 + (win - 1) / 2)
- ], e)
-
- # -----------------------------------------------------------
- # ImFrame.loadPIL_LUT(dataset)
- # Display an image using the Python Imaging Library (PIL)
- # -----------------------------------------------------------
- def loadPIL_LUT(self, dataset):
- if not have_PIL:
- raise ImportError("Python Imaging Library is not available."
- " See http://www.pythonware.com/products/pil/"
- " to download and install")
- if 'PixelData' not in dataset:
- raise TypeError("Cannot show image -- "
- "DICOM dataset does not have pixel data")
-
- # can only apply LUT if these values exist
- if ('WindowWidth' not in dataset) or ('WindowCenter' not in dataset):
- bits = dataset.BitsAllocated
- samples = dataset.SamplesPerPixel
- if bits == 8 and samples == 1:
- mode = "L"
- elif bits == 8 and samples == 3:
- mode = "RGB"
- # not sure about this -- PIL source says is
- # 'experimental' and no documentation.
- elif bits == 16:
- # Also, should bytes swap depending
- # on endian of file and system??
- mode = "I;16"
- else:
- msg = "Don't know PIL mode for %d BitsAllocated" % (bits)
- msg += " and %d SamplesPerPixel" % (samples)
- raise TypeError(msg)
- size = (dataset.Columns, dataset.Rows)
-
- # Recommended to specify all details by
- # http://www.pythonware.com/library/pil/handbook/image.htm
- im = PIL.Image.frombuffer(mode, size, dataset.PixelData, "raw",
- mode, 0, 1)
- else:
-
- image = self.get_LUT_value(
- dataset.pixel_array, dataset.WindowWidth, dataset.WindowCenter)
-
- # Convert mode to L since LUT has only 256 values:
- # http://www.pythonware.com/library/pil/handbook/image.htm
- im = PIL.Image.fromarray(image).convert('L')
- return im
-
- def show_file(self, imageFile, fullPath):
- """ Load the DICOM file, make sure it contains at least one
- image, and set it up for display by OnPaint(). ** be
- careful not to pass a unicode string to read_file or it will
- give you 'fp object does not have a defer_size attribute,
- or some such."""
- ds = pydicom.read_file(str(fullPath))
-
- # change strings to unicode
- ds.decode()
- self.populateTree(ds)
- if 'PixelData' in ds:
- self.dImage = self.loadPIL_LUT(ds)
- if self.dImage is not None:
- tmpImage = self.ConvertPILToWX(self.dImage, False)
- self.bitmap = wx.BitmapFromImage(tmpImage)
- self.Refresh()
-
-
-# ------ This is just the initialization of the App ----
-
-# =======================================================
-# The main App Class.
-# =======================================================
-
-
-class App(wx.App):
- """Image Application."""
-
- def OnInit(self):
- """Create the Image Application."""
- ImFrame(None, 'wxImage Example')
- return True
-
-
-# ------------------------------------------------------
-# If this file is running as main or a
-# standalone test, begin execution here.
-# ------------------------------------------------------
-
-if __name__ == '__main__':
- app = App(0)
- app.MainLoop()
diff --git a/pydicom/contrib/pydicom_PIL.py b/pydicom/contrib/pydicom_PIL.py
deleted file mode 100644
index 867cfe4bb..000000000
--- a/pydicom/contrib/pydicom_PIL.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# pydicom_PIL.py
-
-"""View DICOM images using Python image Library (PIL)
-
-Usage:
->>> import pydicom
->>> from pydicom.contrib.pydicom_PIL import show_PIL
->>> ds = pydicom.read_file("filename")
->>> show_PIL(ds)
-
-Requires Numpy:
- http://numpy.scipy.org/
-
-and Python Imaging Library:
- http://www.pythonware.com/products/pil/
-
-"""
-# Copyright (c) 2009 Darcy Mason, Adit Panchal
-# This file is part of pydicom, relased under an MIT license.
-# See the file LICENSE included with this distribution, also
-# available at https://github.com/pydicom/pydicom
-
-# Based on image.py from pydicom version 0.9.3,
-# LUT code added by Adit Panchal
-# Tested on Python 2.5.4 (32-bit) on Mac OS X 10.6
-# using numpy 1.3.0 and PIL 1.1.7b1
-
-have_PIL = True
-try:
- import PIL.Image
-except ImportError:
- have_PIL = False
-
-have_numpy = True
-try:
- import numpy as np
-except ImportError:
- have_numpy = False
-
-
-def get_LUT_value(data, window, level):
- """Apply the RGB Look-Up Table for the given
- data and window/level value."""
- if not have_numpy:
- raise ImportError("Numpy is not available."
- "See http://numpy.scipy.org/"
- "to download and install")
-
- return np.piecewise(data,
- [data <= (level - 0.5 - (window - 1) / 2),
- data > (level - 0.5 + (window - 1) / 2)],
- [0, 255, lambda data: ((data - (level - 0.5)) /
- (window - 1) + 0.5) * (255 - 0)])
-
-
-def get_PIL_image(dataset):
- """Get Image object from Python Imaging Library(PIL)"""
- if not have_PIL:
- raise ImportError("Python Imaging Library is not available. "
- "See http://www.pythonware.com/products/pil/ "
- "to download and install")
-
- if ('PixelData' not in dataset):
- raise TypeError("Cannot show image -- DICOM dataset does not have "
- "pixel data")
- # can only apply LUT if these window info exists
- if ('WindowWidth' not in dataset) or ('WindowCenter' not in dataset):
- bits = dataset.BitsAllocated
- samples = dataset.SamplesPerPixel
- if bits == 8 and samples == 1:
- mode = "L"
- elif bits == 8 and samples == 3:
- mode = "RGB"
- elif bits == 16:
- # not sure about this -- PIL source says is 'experimental'
- # and no documentation. Also, should bytes swap depending
- # on endian of file and system??
- mode = "I;16"
- else:
- raise TypeError("Don't know PIL mode for %d BitsAllocated "
- "and %d SamplesPerPixel" % (bits, samples))
-
- # PIL size = (width, height)
- size = (dataset.Columns, dataset.Rows)
-
- # Recommended to specify all details
- # by http://www.pythonware.com/library/pil/handbook/image.htm
- im = PIL.Image.frombuffer(mode, size, dataset.PixelData,
- "raw", mode, 0, 1)
-
- else:
- image = get_LUT_value(dataset.pixel_array, dataset.WindowWidth,
- dataset.WindowCenter)
- # Convert mode to L since LUT has only 256 values:
- # http://www.pythonware.com/library/pil/handbook/image.htm
- im = PIL.Image.fromarray(image).convert('L')
-
- return im
-
-
-def show_PIL(dataset):
- """Display an image using the Python Imaging Library (PIL)"""
- im = get_PIL_image(dataset)
- im.show()
diff --git a/pydicom/contrib/pydicom_Tkinter.py b/pydicom/contrib/pydicom_Tkinter.py
deleted file mode 100644
index a2232310b..000000000
--- a/pydicom/contrib/pydicom_Tkinter.py
+++ /dev/null
@@ -1,221 +0,0 @@
-# pydicom_Tkinter.py
-#
-# Copyright (c) 2009 Daniel Nanz
-# This file is released under the pydicom
-# (https://github.com/pydicom/pydicom)
-# license, see the file LICENSE available at
-# (https://github.com/pydicom/pydicom)
-#
-# revision history:
-# Dec-08-2009: version 0.1
-#
-# 0.1: tested with pydicom version 0.9.3, Python version 2.6.2 (32-bit)
-# under Windows XP Professional 2002, and Mac OS X 10.5.5,
-# using numpy 1.3.0 and a small random selection of MRI and
-# CT images.
-'''
-View DICOM images from pydicom
-
-requires numpy: http://numpy.scipy.org/
-
-Usage:
-------
->>> import pydicom # pydicom
->>> import pydicom.contrib.pydicom_Tkinter as pydicom_Tkinter # this module
-
->>> df = pydicom.read_file(filename)
->>> pydicom_Tkinter.show_image(df)
-'''
-
-import tempfile
-import os
-
-from pydicom.compat import in_py2
-if in_py2:
- import Tkinter as tkinter
-
-have_numpy = True
-try:
- import numpy as np
-except ImportError:
- # will not work...
- have_numpy = False
-
-
-def get_PGM_bytedata_string(arr):
- '''Given a 2D numpy array as input write
- gray-value image data in the PGM
- format into a byte string and return it.
-
- arr: single-byte unsigned int numpy array
- note: Tkinter's PhotoImage object seems to
- accept only single-byte data
- '''
-
- if arr.dtype != np.uint8:
- raise ValueError
- if len(arr.shape) != 2:
- raise ValueError
-
- # array.shape is (#rows, #cols) tuple; PGM input needs this reversed
- col_row_string = ' '.join(reversed([str(x) for x in arr.shape]))
-
- bytedata_string = '\n'.join(('P5', col_row_string, str(arr.max()),
- arr.tostring()))
- return bytedata_string
-
-
-def get_PGM_from_numpy_arr(arr,
- window_center,
- window_width,
- lut_min=0,
- lut_max=255):
- '''real-valued numpy input -> PGM-image formatted byte string
-
- arr: real-valued numpy array to display as grayscale image
- window_center, window_width: to define max/min values to be mapped to the
- lookup-table range. WC/WW scaling is done
- according to DICOM-3 specifications.
- lut_min, lut_max: min/max values of (PGM-) grayscale table: do not change
- '''
-
- if np.isreal(arr).sum() != arr.size:
- raise ValueError
-
- # currently only support 8-bit colors
- if lut_max != 255:
- raise ValueError
-
- if arr.dtype != np.float64:
- arr = arr.astype(np.float64)
-
- # LUT-specific array scaling
- # width >= 1 (DICOM standard)
- window_width = max(1, window_width)
-
- wc, ww = np.float64(window_center), np.float64(window_width)
- lut_range = np.float64(lut_max) - lut_min
-
- minval = wc - 0.5 - (ww - 1.0) / 2.0
- maxval = wc - 0.5 + (ww - 1.0) / 2.0
-
- min_mask = (minval >= arr)
- to_scale = (arr > minval) & (arr < maxval)
- max_mask = (arr >= maxval)
-
- if min_mask.any():
- arr[min_mask] = lut_min
- if to_scale.any():
- arr[to_scale] = ((arr[to_scale] - (wc - 0.5)) /
- (ww - 1.0) + 0.5) * lut_range + lut_min
- if max_mask.any():
- arr[max_mask] = lut_max
-
- # round to next integer values and convert to unsigned int
- arr = np.rint(arr).astype(np.uint8)
-
- # return PGM byte-data string
- return get_PGM_bytedata_string(arr)
-
-
-def get_tkinter_photoimage_from_pydicom_image(data):
- '''
- Wrap data.pixel_array in a Tkinter PhotoImage instance,
- after conversion into a PGM grayscale image.
-
- This will fail if the "numpy" module is not
- installed in the attempt of creating the data.pixel_array.
-
- data: object returned from pydicom.read_file()
- side effect: may leave a temporary .pgm file on disk
- '''
-
- # get numpy array as representation of image data
- arr = data.pixel_array.astype(np.float64)
-
- # pixel_array seems to be the original, non-rescaled array.
- # If present, window center and width refer to rescaled array
- # -> do rescaling if possible.
- if ('RescaleIntercept' in data) and ('RescaleSlope' in data):
- intercept = data.RescaleIntercept # single value
- slope = data.RescaleSlope
- arr = slope * arr + intercept
-
- # get default window_center and window_width values
- wc = (arr.max() + arr.min()) / 2.0
- ww = arr.max() - arr.min() + 1.0
-
- # overwrite with specific values from data, if available
- if ('WindowCenter' in data) and ('WindowWidth' in data):
- wc = data.WindowCenter
- ww = data.WindowWidth
- try:
- wc = wc[0] # can be multiple values
- except Exception:
- pass
- try:
- ww = ww[0]
- except Exception:
- pass
-
- # scale array to account for center, width and PGM grayscale range,
- # and wrap into PGM formatted ((byte-) string
- pgm = get_PGM_from_numpy_arr(arr, wc, ww)
-
- # create a PhotoImage
- # for as yet unidentified reasons the following fails for certain
- # window center/width values:
- # photo_image = Tkinter.PhotoImage(data=pgm, gamma=1.0)
- # Error with Python 2.6.2 under Windows XP:
- # (self.tk.call(('image', 'create', imgtype, name,) + options)
- # _tkinter.TclError: truncated PPM data
- # OsX: distorted images
- # while all seems perfectly OK for other values of center/width or when
- # the PGM is first written to a temporary file and read again
-
- # write PGM file into temp dir
- (os_id, abs_path) = tempfile.mkstemp(suffix='.pgm')
- with open(abs_path, 'wb') as fd:
- fd.write(pgm)
-
- photo_image = tkinter.PhotoImage(file=abs_path, gamma=1.0)
-
- # close and remove temporary file on disk
- # os.close is needed under windows for os.remove not to fail
- try:
- os.close(os_id)
- os.remove(abs_path)
- except Exception:
- pass # silently leave file on disk in temp-like directory
-
- return photo_image
-
-
-def show_image(data, block=True, master=None):
- '''
- Get minimal Tkinter GUI and display a pydicom data.pixel_array
-
- data: object returned from pydicom.read_file()
- block: if True run Tk mainloop() to show the image
- master: use with block==False and an existing
- Tk widget as parent widget
-
- side effects: may leave a temporary .pgm file on disk
- '''
- frame = tkinter.Frame(master=master, background='#000')
- if 'SeriesDescription' in data and 'InstanceNumber' in data:
- title = ', '.join(('Ser: ' + data.SeriesDescription,
- 'Img: ' + str(data.InstanceNumber)))
- else:
- title = 'pydicom image'
- frame.master.title(title)
- photo_image = get_tkinter_photoimage_from_pydicom_image(data)
- label = tkinter.Label(frame, image=photo_image, background='#000')
-
- # keep a reference to avoid disappearance upon garbage collection
- label.photo_reference = photo_image
- label.grid()
- frame.grid()
-
- if block:
- frame.mainloop()
diff --git a/pydicom/contrib/pydicom_series.py b/pydicom/contrib/pydicom_series.py
deleted file mode 100644
index 23ce8c658..000000000
--- a/pydicom/contrib/pydicom_series.py
+++ /dev/null
@@ -1,686 +0,0 @@
-# dicom_series.py
-"""
-By calling the function read_files with a directory name or list
-of files as an argument, a list of DicomSeries instances can be
-obtained. A DicomSeries object has some attributes that give
-information about the serie (such as shape, sampling, suid) and
-has an info attribute, which is a pydicom.DataSet instance containing
-information about the first dicom file in the serie. The data can
-be obtained using the get_pixel_array() method, which produces a
-3D numpy array if there a multiple files in the serie.
-
-This module can deal with gated data, in which case a DicomSeries
-instance is created for each 3D volume.
-
-"""
-from __future__ import print_function
-#
-# Copyright (c) 2010 Almar Klein
-# This file is released under the pydicom license.
-# See the file LICENSE included with the pydicom distribution, also
-# available at https://github.com/pydicom/pydicom
-#
-
-# I (Almar) performed some test to loading a series of data
-# in two different ways: loading all data, and deferring loading
-# the data. Both ways seem equally fast on my system. I have to
-# note that results can differ quite a lot depending on the system,
-# but still I think this suggests that deferred reading is in
-# general not slower. I think deferred loading of the pixel data
-# can be advantageous because maybe not all data of all series
-# is needed. Also it simply saves memory, because the data is
-# removed from the Dataset instances.
-# In the few result below, cold means reading for the first time,
-# warm means reading 2nd/3d/etc time.
-# - Full loading of data, cold: 9 sec
-# - Full loading of data, warm: 3 sec
-# - Deferred loading of data, cold: 9 sec
-# - Deferred loading of data, warm: 3 sec
-
-import os
-import time
-import gc
-
-import pydicom
-from pydicom.sequence import Sequence
-from pydicom import compat
-
-# Try importing numpy
-try:
- import numpy as np
- have_numpy = True
-except ImportError:
- np = None # NOQA
- have_numpy = False
-
-
-# Helper functions and classes
-class ProgressBar(object):
- """ To print progress to the screen.
- """
-
- def __init__(self, char='-', length=20):
- self.char = char
- self.length = length
- self.progress = 0.0
- self.nbits = 0
- self.what = ''
-
- def Start(self, what=''):
- """ Start(what='')
- Start the progress bar, displaying the given text first.
- Make sure not to print anything untill after calling
- Finish(). Messages can be printed while displaying
- progess by using printMessage().
- """
- self.what = what
- self.progress = 0.0
- self.nbits = 0
- sys.stdout.write(what + " [")
-
- def Stop(self, message=""):
- """ Stop the progress bar where it is now.
- Optionally print a message behind it."""
- delta = int(self.length - self.nbits)
- sys.stdout.write(" " * delta + "] " + message + "\n")
-
- def Finish(self, message=""):
- """ Finish the progress bar, setting it to 100% if it
- was not already. Optionally print a message behind the bar.
- """
- delta = int(self.length - self.nbits)
- sys.stdout.write(self.char * delta + "] " + message + "\n")
-
- def Update(self, newProgress):
- """ Update progress. Progress is given as a number
- between 0 and 1.
- """
- self.progress = newProgress
- required = self.length * (newProgress)
- delta = int(required - self.nbits)
- if delta > 0:
- sys.stdout.write(self.char * delta)
- self.nbits += delta
-
- def PrintMessage(self, message):
- """ Print a message (for example a warning).
- The message is printed behind the progress bar,
- and a new bar is started.
- """
- self.Stop(message)
- self.Start(self.what)
-
-
-def _dummyProgressCallback(progress):
- """ A callback to indicate progress that does nothing. """
- pass
-
-
-_progressBar = ProgressBar()
-
-
-def _progressCallback(progress):
- """ The default callback for displaying progress. """
- if isinstance(progress, compat.string_types):
- _progressBar.Start(progress)
- _progressBar._t0 = time.time()
- elif progress is None:
- dt = time.time() - _progressBar._t0
- _progressBar.Finish('%2.2f seconds' % dt)
- else:
- _progressBar.Update(progress)
-
-
-def _listFiles(files, path):
- """List all files in the directory, recursively. """
-
- for item in os.listdir(path):
- item = os.path.join(path, item)
- if os.path.isdir(item):
- _listFiles(files, item)
- else:
- files.append(item)
-
-
-def _splitSerieIfRequired(serie, series):
- """ _splitSerieIfRequired(serie, series)
- Split the serie in multiple series if this is required.
- The choice is based on examing the image position relative to
- the previous image. If it differs too much, it is assumed
- that there is a new dataset. This can happen for example in
- unspitted gated CT data.
- """
-
- # Sort the original list and get local name
- serie._sort()
- L = serie._datasets
-
- # Init previous slice
- ds1 = L[0]
-
- # Check whether we can do this
- if "ImagePositionPatient" not in ds1:
- return
-
- # Initialize a list of new lists
- L2 = [[ds1]]
-
- # Init slice distance estimate
- distance = 0
-
- for index in range(1, len(L)):
-
- # Get current slice
- ds2 = L[index]
-
- # Get positions
- pos1 = float(ds1.ImagePositionPatient[2])
- pos2 = float(ds2.ImagePositionPatient[2])
-
- # Get distances
- newDist = abs(pos1 - pos2)
- # deltaDist = abs(firstPos-pos2)
-
- # If the distance deviates more than 2x from what we've seen,
- # we can agree it's a new dataset.
- if distance and newDist > 2.1 * distance:
- L2.append([])
- distance = 0
- else:
- # Test missing file
- if distance and newDist > 1.5 * distance:
- print('Warning: missing file after "%s"' % ds1.filename)
- distance = newDist
-
- # Add to last list
- L2[-1].append(ds2)
-
- # Store previous
- ds1 = ds2
-
- # Split if we should
- if len(L2) > 1:
-
- # At what position are we now?
- i = series.index(serie)
-
- # Create new series
- series2insert = []
- for L in L2:
- newSerie = DicomSeries(serie.suid, serie._showProgress)
- newSerie._datasets = Sequence(L)
- series2insert.append(newSerie)
-
- # Insert series and remove self
- for newSerie in reversed(series2insert):
- series.insert(i, newSerie)
- series.remove(serie)
-
-
-pixelDataTag = pydicom.tag.Tag(0x7fe0, 0x0010)
-
-
-def _getPixelDataFromDataset(ds):
- """ Get the pixel data from the given dataset. If the data
- was deferred, make it deferred again, so that memory is
- preserved. Also applies RescaleSlope and RescaleIntercept
- if available. """
-
- # Get original element
- el = dict.__getitem__(ds, pixelDataTag)
-
- # Get data
- data = ds.pixel_array
-
- # Remove data (mark as deferred)
- dict.__setitem__(ds, pixelDataTag, el)
- del ds._pixel_array
-
- # Obtain slope and offset
- slope = 1
- offset = 0
- needFloats = False
- needApplySlopeOffset = False
- if 'RescaleSlope' in ds:
- needApplySlopeOffset = True
- slope = ds.RescaleSlope
- if 'RescaleIntercept' in ds:
- needApplySlopeOffset = True
- offset = ds.RescaleIntercept
- if int(slope) != slope or int(offset) != offset:
- needFloats = True
- if not needFloats:
- slope, offset = int(slope), int(offset)
-
- # Apply slope and offset
- if needApplySlopeOffset:
-
- # Maybe we need to change the datatype?
- if data.dtype in [np.float32, np.float64]:
- pass
- elif needFloats:
- data = data.astype(np.float32)
- else:
- # Determine required range
- minReq, maxReq = data.min(), data.max()
- minReq = min(
- [minReq, minReq * slope + offset, maxReq * slope + offset])
- maxReq = max(
- [maxReq, minReq * slope + offset, maxReq * slope + offset])
-
- # Determine required datatype from that
- dtype = None
- if minReq < 0:
- # Signed integer type
- maxReq = max([-minReq, maxReq])
- if maxReq < 2**7:
- dtype = np.int8
- elif maxReq < 2**15:
- dtype = np.int16
- elif maxReq < 2**31:
- dtype = np.int32
- else:
- dtype = np.float32
- else:
- # Unsigned integer type
- if maxReq < 2**8:
- dtype = np.uint8
- elif maxReq < 2**16:
- dtype = np.uint16
- elif maxReq < 2**32:
- dtype = np.uint32
- else:
- dtype = np.float32
-
- # Change datatype
- if dtype != data.dtype:
- data = data.astype(dtype)
-
- # Apply slope and offset
- data *= slope
- data += offset
-
- # Done
- return data
-
-
-# The public functions and classes
-
-
-def read_files(path, showProgress=False, readPixelData=False, force=False):
- """ read_files(path, showProgress=False, readPixelData=False)
-
- Reads dicom files and returns a list of DicomSeries objects, which
- contain information about the data, and can be used to load the
- image or volume data.
-
- The parameter "path" can also be a list of files or directories.
-
- If the callable "showProgress" is given, it is called with a single
- argument to indicate the progress. The argument is a string when a
- progress is started (indicating what is processed). A float indicates
- progress updates. The paremeter is None when the progress is finished.
- When "showProgress" is True, a default callback is used that writes
- to stdout. By default, no progress is shown.
-
- if readPixelData is True, the pixel data of all series is read. By
- default the loading of pixeldata is deferred until it is requested
- using the DicomSeries.get_pixel_array() method. In general, both
- methods should be equally fast.
- """
-
- # Init list of files
- files = []
-
- # Obtain data from the given path
- if isinstance(path, compat.string_types):
- # Make dir nice
- basedir = os.path.abspath(path)
- # Check whether it exists
- if not os.path.isdir(basedir):
- raise ValueError('The given path is not a valid directory.')
- # Find files recursively
- _listFiles(files, basedir)
-
- elif isinstance(path, (tuple, list)):
- # Iterate over all elements, which can be files or directories
- for p in path:
- if os.path.isdir(p):
- _listFiles(files, os.path.abspath(p))
- elif os.path.isfile(p):
- files.append(p)
- else:
- print("Warning, the path '%s' is not valid." % p)
- else:
- raise ValueError('The path argument must be a string or list.')
-
- # Set default progress callback?
- if showProgress is True:
- showProgress = _progressCallback
- if not hasattr(showProgress, '__call__'):
- showProgress = _dummyProgressCallback
-
- # Set defer size
- deferSize = 16383 # 128**2-1
- if readPixelData:
- deferSize = None
-
- # Gather file data and put in DicomSeries
- series = {}
- count = 0
- showProgress('Loading series information:')
- for filename in files:
-
- # Skip DICOMDIR files
- if filename.count("DICOMDIR"):
- continue
-
- # Try loading dicom ...
- try:
- dcm = pydicom.read_file(filename, deferSize, force=force)
- except pydicom.filereader.InvalidDicomError:
- continue # skip non-dicom file
- except Exception as why:
- if showProgress is _progressCallback:
- _progressBar.PrintMessage(str(why))
- else:
- print('Warning:', why)
- continue
-
- # Get SUID and register the file with an existing or new series object
- try:
- suid = dcm.SeriesInstanceUID
- except AttributeError:
- continue # some other kind of dicom file
- if suid not in series:
- series[suid] = DicomSeries(suid, showProgress)
- series[suid]._append(dcm)
-
- # Show progress (note that we always start with a 0.0)
- showProgress(float(count) / len(files))
- count += 1
-
- # Finish progress
- showProgress(None)
-
- # Make a list and sort, so that the order is deterministic
- series = list(series.values())
- series.sort(key=lambda x: x.suid)
-
- # Split series if necessary
- for serie in reversed([serie for serie in series]):
- _splitSerieIfRequired(serie, series)
-
- # Finish all series
- showProgress('Analysing series')
- series_ = []
- for i in range(len(series)):
- try:
- series[i]._finish()
- series_.append(series[i])
- except Exception:
- pass # Skip serie (probably report-like file without pixels)
- showProgress(float(i + 1) / len(series))
- showProgress(None)
-
- return series_
-
-
-class DicomSeries(object):
- """ DicomSeries
- This class represents a serie of dicom files that belong together.
- If these are multiple files, they represent the slices of a volume
- (like for CT or MRI). The actual volume can be obtained using loadData().
- Information about the data can be obtained using the info attribute.
- """
-
- # To create a DicomSeries object, start by making an instance and
- # append files using the "_append" method. When all files are
- # added, call "_sort" to sort the files, and then "_finish" to evaluate
- # the data, perform some checks, and set the shape and sampling
- # attributes of the instance.
-
- def __init__(self, suid, showProgress):
- # Init dataset list and the callback
- self._datasets = Sequence()
- self._showProgress = showProgress
-
- # Init props
- self._suid = suid
- self._info = None
- self._shape = None
- self._sampling = None
-
- @property
- def suid(self):
- """ The Series Instance UID. """
- return self._suid
-
- @property
- def shape(self):
- """ The shape of the data (nz, ny, nx).
- If None, the serie contains a single dicom file. """
- return self._shape
-
- @property
- def sampling(self):
- """ The sampling (voxel distances) of the data (dz, dy, dx).
- If None, the serie contains a single dicom file. """
- return self._sampling
-
- @property
- def info(self):
- """ A DataSet instance containing the information as present in the
- first dicomfile of this serie. """
- return self._info
-
- @property
- def description(self):
- """ A description of the dicom series. Used fields are
- PatientName, shape of the data, SeriesDescription,
- and ImageComments.
- """
-
- info = self.info
-
- # If no info available, return simple description
- if info is None:
- return "DicomSeries containing %i images" % len(self._datasets)
-
- fields = []
-
- # Give patient name
- if 'PatientName' in info:
- fields.append("" + info.PatientName)
-
- # Also add dimensions
- if self.shape:
- tmp = [str(d) for d in self.shape]
- fields.append('x'.join(tmp))
-
- # Try adding more fields
- if 'SeriesDescription' in info:
- fields.append("'" + info.SeriesDescription + "'")
- if 'ImageComments' in info:
- fields.append("'" + info.ImageComments + "'")
-
- # Combine
- return ' '.join(fields)
-
- def __repr__(self):
- adr = hex(id(self)).upper()
- data_len = len(self._datasets)
- return "<DicomSeries with %i images at %s>" % (data_len, adr)
-
- def get_pixel_array(self):
- """ get_pixel_array()
-
- Get (load) the data that this DicomSeries represents, and return
- it as a numpy array. If this serie contains multiple images, the
- resulting array is 3D, otherwise it's 2D.
-
- If RescaleSlope and RescaleIntercept are present in the dicom info,
- the data is rescaled using these parameters. The data type is chosen
- depending on the range of the (rescaled) data.
-
- """
-
- # Can we do this?
- if not have_numpy:
- msg = "The Numpy package is required to use get_pixel_array.\n"
- raise ImportError(msg)
-
- # It's easy if no file or if just a single file
- if len(self._datasets) == 0:
- raise ValueError('Serie does not contain any files.')
- elif len(self._datasets) == 1:
- ds = self._datasets[0]
- slice = _getPixelDataFromDataset(ds)
- return slice
-
- # Check info
- if self.info is None:
- raise RuntimeError("Cannot return volume if series not finished.")
-
- # Set callback to update progress
- showProgress = self._showProgress
-
- # Init data (using what the dicom packaged produces as a reference)
- ds = self._datasets[0]
- slice = _getPixelDataFromDataset(ds)
- # vol = Aarray(self.shape, self.sampling, fill=0, dtype=slice.dtype)
- vol = np.zeros(self.shape, dtype=slice.dtype)
- vol[0] = slice
-
- # Fill volume
- showProgress('Loading data:')
- ll = self.shape[0]
- for z in range(1, ll):
- ds = self._datasets[z]
- vol[z] = _getPixelDataFromDataset(ds)
- showProgress(float(z) / ll)
-
- # Finish
- showProgress(None)
-
- # Done
- gc.collect()
- return vol
-
- def _append(self, dcm):
- """ _append(dcm)
- Append a dicomfile (as a pydicom.dataset.FileDataset) to the series.
- """
- self._datasets.append(dcm)
-
- def _sort(self):
- """ sort()
- Sort the datasets by instance number.
- """
- self._datasets.sort(key=lambda k: k.InstanceNumber)
-
- def _finish(self):
- """ _finish()
-
- Evaluate the series of dicom files. Together they should make up
- a volumetric dataset. This means the files should meet certain
- conditions. Also some additional information has to be calculated,
- such as the distance between the slices. This method sets the
- attributes for "shape", "sampling" and "info".
-
- This method checks:
- * that there are no missing files
- * that the dimensions of all images match
- * that the pixel spacing of all images match
-
- """
-
- # The datasets list should be sorted by instance number
- L = self._datasets
- if len(L) == 0:
- return
- elif len(L) < 2:
- # Set attributes
- ds = self._datasets[0]
- self._info = self._datasets[0]
- self._shape = [ds.Rows, ds.Columns]
- self._sampling = [
- float(ds.PixelSpacing[0]), float(ds.PixelSpacing[1])
- ]
- return
-
- # Get previous
- ds1 = L[0]
-
- # Init measures to calculate average of
- distance_sum = 0.0
-
- # Init measures to check (these are in 2D)
- dimensions = ds1.Rows, ds1.Columns
-
- # row, column
- sampling = float(ds1.PixelSpacing[0]), float(ds1.PixelSpacing[1])
-
- for index in range(len(L)):
- # The first round ds1 and ds2 will be the same, for the
- # distance calculation this does not matter
-
- # Get current
- ds2 = L[index]
-
- # Get positions
- pos1 = float(ds1.ImagePositionPatient[2])
- pos2 = float(ds2.ImagePositionPatient[2])
-
- # Update distance_sum to calculate distance later
- distance_sum += abs(pos1 - pos2)
-
- # Test measures
- dimensions2 = ds2.Rows, ds2.Columns
- sampling2 = float(ds2.PixelSpacing[0]), float(ds2.PixelSpacing[1])
- if dimensions != dimensions2:
- # We cannot produce a volume if the dimensions match
- raise ValueError('Dimensions of slices does not match.')
- if sampling != sampling2:
- # We can still produce a volume, but we should notify the user
- msg = 'Warning: sampling does not match.'
- if self._showProgress is _progressCallback:
- _progressBar.PrintMessage(msg)
- else:
- print(msg)
- # Store previous
- ds1 = ds2
-
- # Create new dataset by making a deep copy of the first
- info = pydicom.dataset.Dataset()
- firstDs = self._datasets[0]
- for key in firstDs.keys():
- if key != (0x7fe0, 0x0010):
- el = firstDs[key]
- info.add_new(el.tag, el.VR, el.value)
-
- # Finish calculating average distance
- # (Note that there are len(L)-1 distances)
- distance_mean = distance_sum / (len(L) - 1)
-
- # Store information that is specific for the serie
- self._shape = [len(L), ds2.Rows, ds2.Columns]
- self._sampling = [distance_mean, float(ds2.PixelSpacing[0]),
- float(ds2.PixelSpacing[1])]
-
- # Store
- self._info = info
-
-
-if __name__ == '__main__':
- import sys
-
- if len(sys.argv) != 2:
- print("Expected a single argument: a directory with dicom files in it")
- else:
- adir = sys.argv[1]
- t0 = time.time()
- all_series = read_files(adir, None, False)
- print("Summary of each series:")
- for series in all_series:
- print(series.description)
diff --git a/pydicom/dataset.py b/pydicom/dataset.py
index 8c7605a54..664cc62cc 100644
--- a/pydicom/dataset.py
+++ b/pydicom/dataset.py
@@ -335,11 +335,10 @@ class Dataset(dict):
"""
# Force zip object into a list in case of python3. Also backwards
# compatible
- meths = set(
- list(zip(*inspect.getmembers(Dataset, inspect.isroutine)))[0])
- props = set(
- list(zip(*inspect.getmembers(Dataset, inspect.isdatadescriptor)))[
- 0])
+ meths = set(list(zip(
+ *inspect.getmembers(self.__class__, inspect.isroutine)))[0])
+ props = set(list(zip(
+ *inspect.getmembers(self.__class__, inspect.isdatadescriptor)))[0])
dicom_names = set(self.dir())
alldir = sorted(props | meths | dicom_names)
return alldir
diff --git a/pydicom/valuerep.py b/pydicom/valuerep.py
index 655fa821e..f217e3eee 100644
--- a/pydicom/valuerep.py
+++ b/pydicom/valuerep.py
@@ -754,7 +754,7 @@ class PersonNameUnicode(PersonNameBase, compat.text_type):
return new_person
def __deepcopy__(self, memo):
- """Make a correct deep copy of the object.
+ """Make correctly a deep copy of the object.
Needed because of the overwritten __new__.
"""
name = compat.text_type(self).encode('utf8')
| dir(FileDataset) and dir(DicomDir) return only Dataset methods
#### Description
`dir(FileDataset)` and `dir(DicomDir)` don't return their specific methods.
#### Steps/Code to Reproduce
```python
from pydicom import read_file
>>> ds = read_file('DICOMDIR')
>>> type(ds)
<class 'pydicom.dicomdir.DicomDir'>
>>> hasattr(ds, 'parse_records')
True
>>> callable(ds.parse_records)
True
>>> 'parse_records' in dir(ds)
False
```
Occurs because `Dataset.__dir__()` only gets methods/properties from the `Dataset` class. | pydicom/pydicom | diff --git a/pydicom/tests/test_dataset.py b/pydicom/tests/test_dataset.py
index bce2660bf..87b4f19b0 100644
--- a/pydicom/tests/test_dataset.py
+++ b/pydicom/tests/test_dataset.py
@@ -313,6 +313,22 @@ class DatasetTests(unittest.TestCase):
'Johnny',
"set by tag failed")
+ def test_dir_subclass(self):
+ """Dataset.__dir__ returns class specific dir"""
+ class DSP(Dataset):
+ def test_func(self):
+ pass
+
+ ds = DSP()
+ assert hasattr(ds, 'test_func')
+ assert callable(ds.test_func)
+ assert 'test_func' in dir(ds)
+
+ ds = Dataset()
+ assert hasattr(ds, 'group_dataset')
+ assert callable(ds.group_dataset)
+ assert 'group_dataset' in dir(ds)
+
def test_dir(self):
"""Dataset.dir() returns sorted list of named data_elements."""
ds = self.dummy_dataset()
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_removed_files",
"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": 5
} | 0.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": [
"numpy>=1.16.0",
"pytest",
"pytest-cov"
],
"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
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
numpy==1.19.5
packaging==21.3
pluggy==1.0.0
py==1.11.0
-e git+https://github.com/pydicom/pydicom.git@4cecd5195fbc10a47f61ff2f70426f300799be1f#egg=pydicom
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
| name: pydicom
channels:
- defaults
- https://repo.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
- numpy==1.19.5
- 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/pydicom
| [
"pydicom/tests/test_dataset.py::DatasetTests::test_dir_subclass"
]
| [
"pydicom/tests/test_dataset.py::DatasetTests::test_get_item"
]
| [
"pydicom/tests/test_dataset.py::DatasetTests::testAttributeErrorInProperty",
"pydicom/tests/test_dataset.py::DatasetTests::testDeleteDicomAttr",
"pydicom/tests/test_dataset.py::DatasetTests::testDeleteDicomAttrWeDontHave",
"pydicom/tests/test_dataset.py::DatasetTests::testDeleteDicomCommandGroupLength",
"pydicom/tests/test_dataset.py::DatasetTests::testDeleteItemLong",
"pydicom/tests/test_dataset.py::DatasetTests::testDeleteItemTuple",
"pydicom/tests/test_dataset.py::DatasetTests::testDeleteNonExistingItem",
"pydicom/tests/test_dataset.py::DatasetTests::testDeleteOtherAttr",
"pydicom/tests/test_dataset.py::DatasetTests::testEqualityInheritance",
"pydicom/tests/test_dataset.py::DatasetTests::testEqualityNoSequence",
"pydicom/tests/test_dataset.py::DatasetTests::testEqualityNotDataset",
"pydicom/tests/test_dataset.py::DatasetTests::testEqualityPrivate",
"pydicom/tests/test_dataset.py::DatasetTests::testEqualitySequence",
"pydicom/tests/test_dataset.py::DatasetTests::testEqualityUnknown",
"pydicom/tests/test_dataset.py::DatasetTests::testGetDefault1",
"pydicom/tests/test_dataset.py::DatasetTests::testGetDefault2",
"pydicom/tests/test_dataset.py::DatasetTests::testGetDefault3",
"pydicom/tests/test_dataset.py::DatasetTests::testGetDefault4",
"pydicom/tests/test_dataset.py::DatasetTests::testGetExists1",
"pydicom/tests/test_dataset.py::DatasetTests::testGetExists2",
"pydicom/tests/test_dataset.py::DatasetTests::testGetExists3",
"pydicom/tests/test_dataset.py::DatasetTests::testGetExists4",
"pydicom/tests/test_dataset.py::DatasetTests::testGetFromRaw",
"pydicom/tests/test_dataset.py::DatasetTests::testHash",
"pydicom/tests/test_dataset.py::DatasetTests::testMembership",
"pydicom/tests/test_dataset.py::DatasetTests::testSetExistingDataElementByName",
"pydicom/tests/test_dataset.py::DatasetTests::testSetNewDataElementByName",
"pydicom/tests/test_dataset.py::DatasetTests::testSetNonDicom",
"pydicom/tests/test_dataset.py::DatasetTests::testTagExceptionPrint",
"pydicom/tests/test_dataset.py::DatasetTests::testTagExceptionWalk",
"pydicom/tests/test_dataset.py::DatasetTests::testUpdate",
"pydicom/tests/test_dataset.py::DatasetTests::test_NamedMemberUpdated",
"pydicom/tests/test_dataset.py::DatasetTests::test__setitem__",
"pydicom/tests/test_dataset.py::DatasetTests::test_add_repeater_elem_by_keyword",
"pydicom/tests/test_dataset.py::DatasetTests::test_attribute_error_in_property_correct_debug",
"pydicom/tests/test_dataset.py::DatasetTests::test_contains",
"pydicom/tests/test_dataset.py::DatasetTests::test_data_element",
"pydicom/tests/test_dataset.py::DatasetTests::test_delitem_slice",
"pydicom/tests/test_dataset.py::DatasetTests::test_dir",
"pydicom/tests/test_dataset.py::DatasetTests::test_dir_filter",
"pydicom/tests/test_dataset.py::DatasetTests::test_empty_slice",
"pydicom/tests/test_dataset.py::DatasetTests::test_exit_exception",
"pydicom/tests/test_dataset.py::DatasetTests::test_formatted_lines",
"pydicom/tests/test_dataset.py::DatasetTests::test_get_pixel_array_already_have",
"pydicom/tests/test_dataset.py::DatasetTests::test_get_raises",
"pydicom/tests/test_dataset.py::DatasetTests::test_getitem_slice",
"pydicom/tests/test_dataset.py::DatasetTests::test_getitem_slice_raises",
"pydicom/tests/test_dataset.py::DatasetTests::test_group_dataset",
"pydicom/tests/test_dataset.py::DatasetTests::test_inequality",
"pydicom/tests/test_dataset.py::DatasetTests::test_is_uncompressed_transfer_syntax",
"pydicom/tests/test_dataset.py::DatasetTests::test_iterall",
"pydicom/tests/test_dataset.py::DatasetTests::test_matching_tags",
"pydicom/tests/test_dataset.py::DatasetTests::test_property",
"pydicom/tests/test_dataset.py::DatasetTests::test_remove_private_tags",
"pydicom/tests/test_dataset.py::DatasetTests::test_reshape_pixel_array_not_implemented",
"pydicom/tests/test_dataset.py::DatasetTests::test_save_as",
"pydicom/tests/test_dataset.py::DatasetTests::test_set_convert_private_elem_from_raw",
"pydicom/tests/test_dataset.py::DatasetTests::test_setitem_slice_raises",
"pydicom/tests/test_dataset.py::DatasetTests::test_top",
"pydicom/tests/test_dataset.py::DatasetTests::test_trait_names",
"pydicom/tests/test_dataset.py::DatasetTests::test_walk",
"pydicom/tests/test_dataset.py::DatasetTests::test_with",
"pydicom/tests/test_dataset.py::DatasetElementsTests::testSequenceAssignment",
"pydicom/tests/test_dataset.py::FileDatasetTests::test_creation_with_container",
"pydicom/tests/test_dataset.py::FileDatasetTests::test_equality_file_meta"
]
| []
| MIT License | 1,605 | [
"doc/viewing_images.rst",
"pydicom/valuerep.py",
"pydicom/contrib/pydicom_Tkinter.py",
"pydicom/contrib/__init__.py",
"pydicom/contrib/pydicom_PIL.py",
"pydicom/contrib/dicom_dao.py",
"pydicom/contrib/dcm_qt_tree.py",
"pydicom/contrib/imViewer_Simple.py",
"doc/pydicom_user_guide.rst",
"README.md",
"pydicom/contrib/pydicom_series.py",
"pydicom/dataset.py"
]
| [
"doc/viewing_images.rst",
"pydicom/valuerep.py",
"pydicom/contrib/pydicom_Tkinter.py",
"pydicom/contrib/__init__.py",
"pydicom/contrib/pydicom_PIL.py",
"pydicom/contrib/dicom_dao.py",
"pydicom/contrib/dcm_qt_tree.py",
"pydicom/contrib/imViewer_Simple.py",
"doc/pydicom_user_guide.rst",
"README.md",
"pydicom/contrib/pydicom_series.py",
"pydicom/dataset.py"
]
|
python-odin__odinweb-11 | cc4650b45a90fa41346ed53cf970cf0da414a44a | 2017-08-21 14:23:31 | cc4650b45a90fa41346ed53cf970cf0da414a44a | diff --git a/odinweb/containers.py b/odinweb/containers.py
index 43622c4..975da81 100644
--- a/odinweb/containers.py
+++ b/odinweb/containers.py
@@ -274,6 +274,17 @@ class ApiInterfaceBase(ApiContainer):
"""
Handle an *un-handled* exception.
"""
+ # Let middleware attempt to handle exception
+ try:
+ for middleware in self.middleware.handle_500:
+ resource = middleware(request, exception)
+ if resource:
+ return resource
+
+ except Exception as ex: # noqa - This is a top level handler
+ exception = ex
+
+ # Fallback to generic error
logger.exception('Internal Server Error: %s', exception, extra={
'status_code': 500,
'request': request
@@ -343,7 +354,12 @@ class ApiInterfaceBase(ApiContainer):
# error processing, this often provides convenience features
# to aid in the debugging process.
raise
- resource = self.handle_500(request, e)
+
+ resource = None
+ # Fallback to the default handler
+ if resource is None:
+ resource = self.handle_500(request, e)
+
status = resource.status
if isinstance(status, HTTPStatus):
diff --git a/odinweb/data_structures.py b/odinweb/data_structures.py
index cd79032..3ec6db0 100644
--- a/odinweb/data_structures.py
+++ b/odinweb/data_structures.py
@@ -439,6 +439,14 @@ class MiddlewareList(list):
middleware = sort_by_priority(self, reverse=True)
return tuple(m.post_dispatch for m in middleware if hasattr(m, 'post_dispatch'))
+ @lazy_property
+ def handle_500(self):
+ """
+ List of handle-error methods from registered middleware.
+ """
+ middleware = sort_by_priority(self, reverse=True)
+ return tuple(m.handle_500 for m in middleware if hasattr(m, 'handle_500'))
+
@lazy_property
def post_swagger(self):
"""
| Added error hook for middleware
Allow middleware to catch errors.
Returning an explicit `True` indicates that the exception has been handled | python-odin/odinweb | diff --git a/tests/test_containers.py b/tests/test_containers.py
index 475acd4..0be6c61 100644
--- a/tests/test_containers.py
+++ b/tests/test_containers.py
@@ -1,6 +1,7 @@
from __future__ import absolute_import
import pytest
+from odinweb.resources import Error
from odin.exceptions import ValidationError
from odinweb import api
@@ -302,6 +303,37 @@ class TestApiInterfaceBase(object):
with pytest.raises(ValueError):
target.dispatch(operation, MockRequest())
+ def test_dispatch__error_handled_by_middleware(self):
+ class ErrorMiddleware(object):
+ def handle_500(self, request, exception):
+ assert isinstance(exception, ValueError)
+ return Error.from_status(HTTPStatus.SEE_OTHER, 0,
+ "Quick over there...")
+
+ def callback(request):
+ raise ValueError()
+
+ target = containers.ApiInterfaceBase(middleware=[ErrorMiddleware()])
+ operation = Operation(callback)
+
+ actual = target.dispatch(operation, MockRequest())
+ assert actual.status == 303
+
+ def test_dispatch__error_handled_by_middleware_raises_exception(self):
+ class ErrorMiddleware(object):
+ def handle_500(self, request, exception):
+ assert isinstance(exception, ValueError)
+ raise ValueError
+
+ def callback(request):
+ raise ValueError()
+
+ target = containers.ApiInterfaceBase(middleware=[ErrorMiddleware()])
+ operation = Operation(callback)
+
+ actual = target.dispatch(operation, MockRequest())
+ assert actual.status == 500
+
def test_dispatch__encode_error_with_debug_enabled(self):
def callback(request):
raise api.ImmediateHttpResponse(ValueError, HTTPStatus.NOT_MODIFIED, {})
| {
"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": 0
},
"num_modified_files": 2
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"pip install -r requirements-dev.txt"
],
"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
coverage==6.2
importlib-metadata==4.8.3
iniconfig==1.1.1
mock==5.2.0
odin==1.8.1
-e git+https://github.com/python-odin/odinweb.git@cc4650b45a90fa41346ed53cf970cf0da414a44a#egg=odinweb
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytest-mock==3.6.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: odinweb
channels:
- defaults
- https://repo.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
- mock==5.2.0
- odin==1.8.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/odinweb
| [
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__error_handled_by_middleware"
]
| [
"tests/test_containers.py::TestApiContainer::test_extra_option"
]
| [
"tests/test_containers.py::TestResourceApiMeta::test_empty_api",
"tests/test_containers.py::TestResourceApiMeta::test_normal_api",
"tests/test_containers.py::TestResourceApiMeta::test_sub_classed_api",
"tests/test_containers.py::TestResourceApi::test_api_name__default",
"tests/test_containers.py::TestResourceApi::test_api_name__custom",
"tests/test_containers.py::TestResourceApi::test_op_paths",
"tests/test_containers.py::TestApiContainer::test_options[options0-name-None]",
"tests/test_containers.py::TestApiContainer::test_options[options1-name-foo]",
"tests/test_containers.py::TestApiContainer::test_options[options2-path_prefix-value2]",
"tests/test_containers.py::TestApiContainer::test_options[options3-path_prefix-value3]",
"tests/test_containers.py::TestApiContainer::test_options[options4-path_prefix-value4]",
"tests/test_containers.py::TestApiContainer::test_op_paths",
"tests/test_containers.py::TestApiContainer::test_op_paths__no_sub_path",
"tests/test_containers.py::TestApiCollection::test_version_options[options0-1-v1-path_prefix0]",
"tests/test_containers.py::TestApiCollection::test_version_options[options1-2-v2-path_prefix1]",
"tests/test_containers.py::TestApiCollection::test_version_options[options2-3-version-3-path_prefix2]",
"tests/test_containers.py::TestApiCollection::test_register_operation",
"tests/test_containers.py::TestApiInterfaceBase::test_options[options0-api-False-path_prefix0]",
"tests/test_containers.py::TestApiInterfaceBase::test_options[options1-!api-False-path_prefix1]",
"tests/test_containers.py::TestApiInterfaceBase::test_options[options2-api-False-path_prefix2]",
"tests/test_containers.py::TestApiInterfaceBase::test_options[options3-api-True-path_prefix3]",
"tests/test_containers.py::TestApiInterfaceBase::test_init_non_absolute",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__invalid_headers[r0-422-Unprocessable",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__invalid_headers[r1-406-URI",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__invalid_headers[r2-405-Specified",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[error0-HTTPStatus.NOT_MODIFIED]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[error1-400]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[error2-400]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[NotImplementedError-501]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[ValueError-500]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__exceptions[error5-500]",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__with_middleware",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__error_with_debug_enabled",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__error_handled_by_middleware_raises_exception",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__encode_error_with_debug_enabled",
"tests/test_containers.py::TestApiInterfaceBase::test_dispatch__http_response",
"tests/test_containers.py::TestApiInterfaceBase::test_op_paths",
"tests/test_containers.py::TestApiInterfaceBase::test_op_paths__collate_methods"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,606 | [
"odinweb/containers.py",
"odinweb/data_structures.py"
]
| [
"odinweb/containers.py",
"odinweb/data_structures.py"
]
|
|
discos__simulators-61 | a857f00fd7150818b4aa28f267c03a8c90a0dda5 | 2017-08-21 14:26:51 | a857f00fd7150818b4aa28f267c03a8c90a0dda5 | coveralls:
[](https://coveralls.io/builds/12922124)
Coverage increased (+0.1%) to 88.73% when pulling **64b21099e9a5aa15d452ae9e8c907b2741435b02 on fix-issue-60** into **a857f00fd7150818b4aa28f267c03a8c90a0dda5 on master**.
codecov-io: # [Codecov](https://codecov.io/gh/discos/simulators/pull/61?src=pr&el=h1) Report
> Merging [#61](https://codecov.io/gh/discos/simulators/pull/61?src=pr&el=desc) into [master](https://codecov.io/gh/discos/simulators/commit/a857f00fd7150818b4aa28f267c03a8c90a0dda5?src=pr&el=desc) will **increase** coverage by `0.13%`.
> The diff coverage is `100%`.
[](https://codecov.io/gh/discos/simulators/pull/61?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #61 +/- ##
==========================================
+ Coverage 88.59% 88.73% +0.13%
==========================================
Files 7 7
Lines 1245 1260 +15
==========================================
+ Hits 1103 1118 +15
Misses 142 142
```
| [Impacted Files](https://codecov.io/gh/discos/simulators/pull/61?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [tests/test\_utils.py](https://codecov.io/gh/discos/simulators/pull/61?src=pr&el=tree#diff-dGVzdHMvdGVzdF91dGlscy5weQ==) | `100% <100%> (ø)` | :arrow_up: |
| [simulators/utils.py](https://codecov.io/gh/discos/simulators/pull/61?src=pr&el=tree#diff-c2ltdWxhdG9ycy91dGlscy5weQ==) | `93.22% <100%> (+0.62%)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/discos/simulators/pull/61?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/discos/simulators/pull/61?src=pr&el=footer). Last update [a857f00...4b168c3](https://codecov.io/gh/discos/simulators/pull/61?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
coveralls:
[](https://coveralls.io/builds/12933700)
Coverage increased (+0.1%) to 88.73% when pulling **4b168c3aa1c4e8f4ba07ec5131dfdd0649389947 on fix-issue-60** into **a857f00fd7150818b4aa28f267c03a8c90a0dda5 on master**.
coveralls:
[](https://coveralls.io/builds/12936275)
Coverage increased (+0.2%) to 88.766% when pulling **d147cbaad39c5c813f01e7e0aaef1a8bf0f4deba on fix-issue-60** into **a857f00fd7150818b4aa28f267c03a8c90a0dda5 on master**.
| diff --git a/simulators/utils.py b/simulators/utils.py
index f289e78..25e23ff 100644
--- a/simulators/utils.py
+++ b/simulators/utils.py
@@ -46,28 +46,38 @@ def twos_to_int(binary_string):
return val
-def int_to_twos(val):
+def int_to_twos(val, n_bytes=4):
"""Return the two's complement of the given integer as a string of zeroes
- and ones with len = 32.
+ and ones with len = 8*n_bytes.
>>> int_to_twos(5)
'00000000000000000000000000000101'
+ >>> int_to_twos(5, 2)
+ '0000000000000101'
+
>>> int_to_twos(-1625)
'11111111111111111111100110100111'
+ >>> int_to_twos(-1625, 2)
+ '1111100110100111'
+
>>> int_to_twos(4294967295)
Traceback (most recent call last):
...
ValueError: 4294967295 out of range (-2147483648, 2147483647).
"""
- if val < -2147483648 or val > 2147483647:
+ n_bits = 8 * n_bytes
+ min_range = -int(math.pow(2, n_bits - 1))
+ max_range = int(math.pow(2, n_bits - 1)) - 1
+
+ if val < min_range or val > max_range:
raise ValueError(
"%d out of range (%d, %d)."
- % (val, -2147483648, 2147483647)
+ % (val, min_range, max_range)
)
- binary_string = bin(val & int("1" * 32, 2))[2:]
- return ("{0:0>%s}" % 32).format(binary_string)
+ binary_string = bin(val & int("1" * n_bits, 2))[2:]
+ return ("{0:0>%s}" % n_bits).format(binary_string)
def binary_to_bytes(binary_string):
@@ -85,6 +95,20 @@ def binary_to_bytes(binary_string):
return byte_string
+def bytes_to_int(byte_string):
+ """Convert a string of bytes to an integer (like C atoi function).
+
+ >>> bytes_to_int(b'\x10\x05\xFA\xFF')
+ 268827391
+ """
+ binary_string = ''
+
+ for char in byte_string:
+ binary_string += bin(ord(char))[2:].zfill(8)
+
+ return twos_to_int(binary_string)
+
+
def mjd():
"""Return the modified julian date. https://bowie.gsfc.nasa.gov/time/"""
utcnow = datetime.utcnow()
| Add a method to convert a string of bytes into an integer (like C atoi function).
The method should be implemented in utils.py. | discos/simulators | diff --git a/tests/test_utils.py b/tests/test_utils.py
index 8569f6f..7d776a6 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -30,6 +30,10 @@ class TestServer(unittest.TestCase):
utils.int_to_twos(5),
'00000000000000000000000000000101'
)
+ self.assertEqual(
+ utils.int_to_twos(5, 2),
+ '0000000000000101'
+ )
def test_out_of_range_int_to_twos(self):
"""Raise a ValueError in case of out of range integer value"""
@@ -61,5 +65,18 @@ class TestServer(unittest.TestCase):
expected_byte_string = b'\x05\x1A\x28\xD3'
self.assertNotEqual(byte_string, expected_byte_string)
+ def test_bytes_to_int_correct(self):
+ """Convert a string of bytes into an integer (like C atoi function)"""
+ byte_string = b'\x00\x00\xFA\xFF'
+ result = utils.bytes_to_int(byte_string)
+ expected_result = 64255
+ self.assertEqual(result, expected_result)
+
+ def test_bytes_to_int_wrong(self):
+ byte_string = b'\x00\x00\xFA\xFF'
+ result = utils.bytes_to_int(byte_string)
+ expected_result = -1281
+ self.assertNotEqual(result, expected_result)
+
if __name__ == '__main__':
unittest.main()
| {
"commit_name": "merge_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
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"coverage",
"prospector",
"sphinx",
"sphinx_rtd_theme",
"tox",
"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"
} | alabaster==0.7.16
astroid==3.3.9
babel==2.17.0
cachetools==5.5.2
certifi==2025.1.31
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
coverage==7.8.0
dill==0.3.9
-e git+https://github.com/discos/simulators.git@a857f00fd7150818b4aa28f267c03a8c90a0dda5#egg=discos_simulators
distlib==0.3.9
docutils==0.21.2
dodgy==0.2.1
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
filelock==3.18.0
flake8==7.2.0
flake8-polyfill==1.0.2
gitdb==4.0.12
GitPython==3.1.44
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
isort==6.0.1
Jinja2==3.1.6
MarkupSafe==3.0.2
mccabe==0.7.0
packaging @ file:///croot/packaging_1734472117206/work
pep8-naming==0.10.0
platformdirs==4.3.7
pluggy @ file:///croot/pluggy_1733169602837/work
prospector==1.16.1
pycodestyle==2.13.0
pydocstyle==6.3.0
pyflakes==3.3.2
Pygments==2.19.1
pylint==3.3.6
pylint-celery==0.3
pylint-django==2.6.1
pylint-plugin-utils==0.8.2
pyproject-api==1.9.0
pytest @ file:///croot/pytest_1738938843180/work
PyYAML==6.0.2
requests==2.32.3
requirements-detector==1.3.2
semver==3.0.4
setoptconf-tmp==0.3.1
smmap==5.0.2
snowballstemmer==2.2.0
Sphinx==7.4.7
sphinx-rtd-theme==3.0.2
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
toml==0.10.2
tomli==2.2.1
tomlkit==0.13.2
tox==4.25.0
typing_extensions==4.13.0
urllib3==2.3.0
virtualenv==20.29.3
zipp==3.21.0
| name: simulators
channels:
- defaults
- https://repo.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:
- alabaster==0.7.16
- astroid==3.3.9
- babel==2.17.0
- cachetools==5.5.2
- certifi==2025.1.31
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- coverage==7.8.0
- dill==0.3.9
- distlib==0.3.9
- docutils==0.21.2
- dodgy==0.2.1
- filelock==3.18.0
- flake8==7.2.0
- flake8-polyfill==1.0.2
- gitdb==4.0.12
- gitpython==3.1.44
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- isort==6.0.1
- jinja2==3.1.6
- markupsafe==3.0.2
- mccabe==0.7.0
- pep8-naming==0.10.0
- platformdirs==4.3.7
- prospector==1.16.1
- pycodestyle==2.13.0
- pydocstyle==6.3.0
- pyflakes==3.3.2
- pygments==2.19.1
- pylint==3.3.6
- pylint-celery==0.3
- pylint-django==2.6.1
- pylint-plugin-utils==0.8.2
- pyproject-api==1.9.0
- pyyaml==6.0.2
- requests==2.32.3
- requirements-detector==1.3.2
- semver==3.0.4
- setoptconf-tmp==0.3.1
- smmap==5.0.2
- snowballstemmer==2.2.0
- sphinx==7.4.7
- sphinx-rtd-theme==3.0.2
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- toml==0.10.2
- tomli==2.2.1
- tomlkit==0.13.2
- tox==4.25.0
- typing-extensions==4.13.0
- urllib3==2.3.0
- virtualenv==20.29.3
- zipp==3.21.0
prefix: /opt/conda/envs/simulators
| [
"tests/test_utils.py::TestServer::test_int_to_twos"
]
| [
"tests/test_utils.py::TestServer::test_binary_to_bytes_correct",
"tests/test_utils.py::TestServer::test_binary_to_bytes_wrong",
"tests/test_utils.py::TestServer::test_bytes_to_int_correct",
"tests/test_utils.py::TestServer::test_bytes_to_int_wrong",
"tests/test_utils.py::TestServer::test_day_milliseconds"
]
| [
"tests/test_utils.py::TestServer::test_mjd",
"tests/test_utils.py::TestServer::test_out_of_range_int_to_twos",
"tests/test_utils.py::TestServer::test_right_checksum",
"tests/test_utils.py::TestServer::test_right_twos_to_int",
"tests/test_utils.py::TestServer::test_wrong_checksum",
"tests/test_utils.py::TestServer::test_wrong_twos_to_int"
]
| []
| null | 1,607 | [
"simulators/utils.py"
]
| [
"simulators/utils.py"
]
|
zopefoundation__zope.ramcache-5 | c8a5cc3e393783668826355fe26b7b4ec299304d | 2017-08-21 16:23:58 | c8a5cc3e393783668826355fe26b7b4ec299304d | diff --git a/CHANGES.rst b/CHANGES.rst
index c217aeb..5fcdb64 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -13,6 +13,10 @@
- Test PyPy3 on Travis CI.
+- Stop requiring all values to support pickling in order to get
+ statistics. Instead, return ``False`` for the size if such a value
+ is found. Fixes `issue 1 <https://github.com/zopefoundation/zope.ramcache/issues/1>`_.
+
2.1.0 (2014-12-29)
==================
diff --git a/src/zope/ramcache/interfaces/ram.py b/src/zope/ramcache/interfaces/ram.py
index 6e44313..f24ad35 100644
--- a/src/zope/ramcache/interfaces/ram.py
+++ b/src/zope/ramcache/interfaces/ram.py
@@ -34,9 +34,16 @@ class IRAMCache(ICache):
"""Reports on the contents of a cache.
The returned value is a sequence of dictionaries with the
- following keys:
-
- `path`, `hits`, `misses`, `size`, `entries`
+ following (string) keys:
+
+ - ``path``: The object being cached.
+ - ``hits``: How many times this path (for all its keys)
+ has been looked up.
+ - ``misses``: How many misses there have been for this path
+ and all its keys.
+ - ``size``: An integer approximating the RAM usage for this path
+ (only available if all values can be pickled; otherwise ``False``)
+ - ``entries``: How many total keys there are for this path.
"""
def update(maxEntries, maxAge, cleanupInterval):
diff --git a/src/zope/ramcache/ram.py b/src/zope/ramcache/ram.py
index fd07cf5..953fe50 100644
--- a/src/zope/ramcache/ram.py
+++ b/src/zope/ramcache/ram.py
@@ -19,6 +19,9 @@ from contextlib import contextmanager
from time import time
from threading import Lock
+from six import iteritems
+from six import itervalues
+
from persistent import Persistent
from zope.interface import implementer
from zope.location.interfaces import IContained
@@ -254,12 +257,12 @@ class Storage(object):
with self._invalidate_queued_after_writelock():
data = self._data
- for object, dict in tuple(data.items()):
- for key in tuple(dict.keys()):
- if dict[key][1] < punchline:
- del dict[key]
- if not dict:
- del data[object]
+ for path, path_data in tuple(iteritems(data)): # copy, we modify
+ for key, val in tuple(iteritems(path_data)): # likewise
+ if val[1] < punchline:
+ del path_data[key]
+ if not path_data:
+ del data[path]
def cleanup(self):
"""Cleanup the data"""
@@ -270,7 +273,7 @@ class Storage(object):
def removeLeastAccessed(self):
with self._invalidate_queued_after_writelock():
data = self._data
- keys = [(ob, k) for ob, v in data.items() for k in v]
+ keys = [(ob, k) for ob, v in iteritems(data) for k in v]
if len(keys) > self.maxEntries:
def getKey(item):
@@ -292,25 +295,31 @@ class Storage(object):
self._clearAccessCounters()
def _clearAccessCounters(self):
- for dict in self._data.values():
- for val in dict.values():
+ for path_data in itervalues(self._data):
+ for val in itervalues(path_data):
val[2] = 0
- for k in self._misses:
- self._misses[k] = 0
+ self._misses = {}
def getKeys(self, object):
return self._data[object].keys()
def getStatistics(self):
- objects = sorted(self._data.keys())
+ objects = sorted(iteritems(self._data))
result = []
- for ob in objects:
- size = len(dumps(self._data[ob]))
- hits = sum(entry[2] for entry in self._data[ob].values())
- result.append({'path': ob,
+ for path, path_data in objects:
+ try:
+ size = len(dumps(path_data))
+ except Exception:
+ # Some value couldn't be pickled properly.
+ # That's OK, they shouldn't have to be. Return
+ # a distinct value that can be recognized as such,
+ # but that also works in arithmetic.
+ size = False
+ hits = sum(entry[2] for entry in itervalues(path_data))
+ result.append({'path': path,
'hits': hits,
- 'misses': self._misses.get(ob, 0),
+ 'misses': self._misses.get(path, 0),
'size': size,
- 'entries': len(self._data[ob])})
+ 'entries': len(path_data)})
return tuple(result)
| Ram cache statistics crash
I've added a @ram.cache() decorator to a function returning a IITreeSet object.
Basically I need to cache some index search resultset in order to speedup the site.
Unfortunately when checking the ram cache statistcs, it fails with the message:
```python
Traceback (innermost last):
Module ZPublisher.Publish, line 138, in publish
Module ZPublisher.mapply, line 77, in mapply
Module ZPublisher.Publish, line 48, in call_object
Module plone.app.caching.browser.controlpanel, line 57, in call
Module plone.app.caching.browser.controlpanel, line 75, in render
Module Products.Five.browser.pagetemplatefile, line 125, in call
Module Products.Five.browser.pagetemplatefile, line 59, in call
Module zope.pagetemplate.pagetemplate, line 132, in pt_render
Module zope.pagetemplate.pagetemplate, line 240, in call
Module zope.tal.talinterpreter, line 271, in call
Module zope.tal.talinterpreter, line 343, in interpret
Module zope.tal.talinterpreter, line 888, in do_useMacro
Module zope.tal.talinterpreter, line 343, in interpret
Module zope.tal.talinterpreter, line 533, in do_optTag_tal
Module zope.tal.talinterpreter, line 518, in do_optTag
Module zope.tal.talinterpreter, line 513, in no_tag
Module zope.tal.talinterpreter, line 343, in interpret
Module zope.tal.talinterpreter, line 888, in do_useMacro
Module zope.tal.talinterpreter, line 343, in interpret
Module zope.tal.talinterpreter, line 533, in do_optTag_tal
Module zope.tal.talinterpreter, line 518, in do_optTag
Module zope.tal.talinterpreter, line 513, in no_tag
Module zope.tal.talinterpreter, line 343, in interpret
Module zope.tal.talinterpreter, line 946, in do_defineSlot
Module zope.tal.talinterpreter, line 343, in interpret
Module zope.tal.talinterpreter, line 533, in do_optTag_tal
Module zope.tal.talinterpreter, line 518, in do_optTag
Module zope.tal.talinterpreter, line 513, in no_tag
Module zope.tal.talinterpreter, line 343, in interpret
Module zope.tal.talinterpreter, line 954, in do_defineSlot
Module zope.tal.talinterpreter, line 343, in interpret
Module zope.tal.talinterpreter, line 533, in do_optTag_tal
Module zope.tal.talinterpreter, line 518, in do_optTag
Module zope.tal.talinterpreter, line 513, in no_tag
Module zope.tal.talinterpreter, line 343, in interpret
Module zope.tal.talinterpreter, line 946, in do_defineSlot
Module zope.tal.talinterpreter, line 343, in interpret
Module zope.tal.talinterpreter, line 583, in do_setLocal_tal
Module zope.tales.tales, line 696, in evaluate
URL: /home/dev/Plone-Dev/eggs/plone.app.caching-1.1.8-py2.7.egg/plone/app/caching/browser/ramcache.pt
Line 69, Column 16
Expression:
Names: {'args': (), 'container': , 'context': , 'default': , 'here': , 'loop': {}, 'nothing': None, 'options': {}, 'repeat': , 'request': , 'root': , 'template': , 'traverse_subpath': [], 'user': , 'view': , 'views': }
Module zope.tales.expressions, line 217, in call
Module Products.PageTemplates.Expressions, line 155, in _eval
Module Products.PageTemplates.Expressions, line 117, in render
Module zope.ramcache.ram, line 80, in getStatistics
Module zope.ramcache.ram, line 323, in getStatistics
RuntimeError: maximum recursion depth exceeded while calling a Python object
```
| zopefoundation/zope.ramcache | diff --git a/src/zope/ramcache/tests/test_ramcache.py b/src/zope/ramcache/tests/test_ramcache.py
index ce6e9b1..1c6aa99 100644
--- a/src/zope/ramcache/tests/test_ramcache.py
+++ b/src/zope/ramcache/tests/test_ramcache.py
@@ -54,6 +54,23 @@ class TestRAMCache(CleanUp,
r2 = c.getStatistics()
self.assertEqual(r1, r2, "see Storage.getStatistics() tests")
+ def test_getStatistics_non_pickle(self):
+ # https://github.com/zopefoundation/zope.ramcache/issues/1
+ class NoPickle(object):
+ def __getstate__(self):
+ raise RuntimeError()
+
+ c = RAMCache()
+ c.set(NoPickle(), "path")
+ stats = c.getStatistics()
+ self.assertEqual(stats,
+ ({'entries': 1,
+ 'hits': 0,
+ 'misses': 0,
+ 'path': 'path',
+ 'size': False},))
+ self.assertEqual(stats[0]['size'] + 1, 1)
+
def test_update(self):
c = RAMCache()
c.update(1, 2, 3)
@@ -445,7 +462,7 @@ class TestStorage(unittest.TestCase):
object2: {key1: [value, 4, 0],
key2: [value, 5, 0],
key3: [value, 6, 0]}}
- clearMisses = {object: 0, object2: 0}
+ clearMisses = {}
s._clearAccessCounters()
self.assertEqual(s._data, cleared, "access counters not cleared")
| {
"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
} | 2.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"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
cffi==1.15.1
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
persistent==4.9.3
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pycparser==2.21
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
zope.event==4.6
zope.exceptions==4.6
zope.interface==5.5.2
zope.location==4.3
zope.proxy==4.6.1
-e git+https://github.com/zopefoundation/zope.ramcache.git@c8a5cc3e393783668826355fe26b7b4ec299304d#egg=zope.ramcache
zope.schema==6.2.1
zope.testing==5.0.1
zope.testrunner==5.6
| name: zope.ramcache
channels:
- defaults
- https://repo.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:
- cffi==1.15.1
- persistent==4.9.3
- pycparser==2.21
- six==1.17.0
- zope-event==4.6
- zope-exceptions==4.6
- zope-interface==5.5.2
- zope-location==4.3
- zope-proxy==4.6.1
- zope-schema==6.2.1
- zope-testing==5.0.1
- zope-testrunner==5.6
prefix: /opt/conda/envs/zope.ramcache
| [
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_getStatistics_non_pickle",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test__clearAccessCounters"
]
| []
| [
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::testCaching",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::testInvalidateAll",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::testVerifyICache",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_buildKey",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_cache",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_getStatistics",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_getStorage",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_init",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_interface",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_invalidate",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_query",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_set",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_timedCleanup",
"src/zope/ramcache/tests/test_ramcache.py::TestRAMCache::test_update",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_do_invalidate",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_getEntry",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_getEntry_do_cleanup",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_getKeys",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_getStatistics",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_invalidate",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_invalidateAll",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_invalidate_queued",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_invalidate_removes_empty",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_locking",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_removeLeastAccessed",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_removeStale",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_setEntry",
"src/zope/ramcache/tests/test_ramcache.py::TestStorage::test_set_get",
"src/zope/ramcache/tests/test_ramcache.py::TestModule::test_locking"
]
| []
| Zope Public License 2.1 | 1,608 | [
"src/zope/ramcache/interfaces/ram.py",
"src/zope/ramcache/ram.py",
"CHANGES.rst"
]
| [
"src/zope/ramcache/interfaces/ram.py",
"src/zope/ramcache/ram.py",
"CHANGES.rst"
]
|
|
pydicom__pydicom-490 | 1bd33e3ceec19d45844676bdd25367fda4c5319b | 2017-08-21 19:51:21 | bef49851e7c3b70edd43cc40fc84fe905e78d5ba | pep8speaks: Hello @mrbean-bremen! Thanks for updating the PR.
- In the file [`pydicom/filewriter.py`](https://github.com/pydicom/pydicom/blob/dd7516dd80edd1270b7b8fac567b5dfc9aa4e1e1/pydicom/filewriter.py), following are the PEP8 issues :
> [Line 417:80](https://github.com/pydicom/pydicom/blob/dd7516dd80edd1270b7b8fac567b5dfc9aa4e1e1/pydicom/filewriter.py#L417): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (81 > 79 characters)
> [Line 421:80](https://github.com/pydicom/pydicom/blob/dd7516dd80edd1270b7b8fac567b5dfc9aa4e1e1/pydicom/filewriter.py#L421): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (88 > 79 characters)
> [Line 423:80](https://github.com/pydicom/pydicom/blob/dd7516dd80edd1270b7b8fac567b5dfc9aa4e1e1/pydicom/filewriter.py#L423): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (88 > 79 characters)
darcymason: @glemaitre, I'm assuming no further comments and going ahead to merge; please add a comment if needed. | diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py
index 4181cce16..efb596845 100644
--- a/pydicom/filewriter.py
+++ b/pydicom/filewriter.py
@@ -415,6 +415,16 @@ def write_data_element(fp, data_element, encoding=default_encoding):
if (hasattr(data_element, "is_undefined_length")
and data_element.is_undefined_length):
is_undefined_length = True
+ # valid pixel data with undefined length shall contain encapsulated
+ # data, e.g. sequence items - raise ValueError otherwise (see #238)
+ if data_element.tag == 0x7fe00010: # pixel data
+ val = data_element.value
+ if (fp.is_little_endian and not
+ val.startswith(b'\xfe\xff\x00\xe0') or
+ not fp.is_little_endian and
+ not val.startswith(b'\xff\xfe\xe0\x00')):
+ raise ValueError('Pixel Data with undefined length must '
+ 'start with an item tag')
location = fp.tell()
fp.seek(length_location)
if not fp.is_implicit_VR and VR not in extra_length_VRs:
| Malformed PixelData
I am trying to convert color spaces using:
``` python
arr = convert_ybr_to_rgb(ds.pixel_array)
ds.file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian
ds.is_little_endian = True
ds.is_implicit_VR = False
ds.PixelData = arr.tostring()
ds.PlanarConfiguration = 0
ds.PhotometricInterpretation = 'RGB'
```
However `dcmcjpeg` then barfs when it tries to open the saved file with:
```
W: DcmSequenceOfItems: Length of item in sequence PixelData (7fe0,0010) is odd
E: DcmSequenceOfItems: Parse error in sequence (7fe0,0010), found (292a,2a48) instead of sequence delimiter (fffe,e0dd)
F: Sequence Delimitation Item missing: reading file: /var/folders/nk/5v0p39pn4yg7c_3vtydljk000000gn/T/tmpLZfsSL.dcm
```
| pydicom/pydicom | diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py
index 70567f134..4d7814ed0 100644
--- a/pydicom/tests/test_filewriter.py
+++ b/pydicom/tests/test_filewriter.py
@@ -41,7 +41,6 @@ except AttributeError:
except ImportError:
print("unittest2 is required for testing in python2.6")
-
rtplan_name = get_testdata_files("rtplan.dcm")[0]
rtdose_name = get_testdata_files("rtdose.dcm")[0]
ct_name = get_testdata_files("CT_small.dcm")[0]
@@ -263,8 +262,8 @@ class WriteDataElementTests(unittest.TestCase):
# Was issue 74
data_elem = DataElement(0x00280009, "AT", [])
expected = hex2bytes((
- " 28 00 09 00" # (0028,0009) Frame Increment Pointer
- " 00 00 00 00" # length 0
+ " 28 00 09 00" # (0028,0009) Frame Increment Pointer
+ " 00 00 00 00" # length 0
))
write_data_element(self.f1, data_elem)
got = self.f1.getvalue()
@@ -1731,6 +1730,74 @@ class TestWriteFileMetaInfoNonStandard(unittest.TestCase):
self.assertEqual(meta, ref_meta)
+class TestWriteUndefinedLengthPixelData(unittest.TestCase):
+ """Test write_data_element() for pixel data with undefined length."""
+
+ def setUp(self):
+ self.fp = DicomBytesIO()
+
+ def test_little_endian_correct_data(self):
+ """Pixel data starting with an item tag is written."""
+ self.fp.is_little_endian = True
+ self.fp.is_implicit_VR = False
+ pixel_data = DataElement(0x7fe00010, 'OB',
+ b'\xfe\xff\x00\xe0'
+ b'\x00\x01\x02\x03',
+ is_undefined_length=True)
+ write_data_element(self.fp, pixel_data)
+
+ expected = (b'\xe0\x7f\x10\x00' # tag
+ b'OB\x00\x00' # VR
+ b'\xff\xff\xff\xff' # length
+ b'\xfe\xff\x00\xe0\x00\x01\x02\x03' # contents
+ b'\xfe\xff\xdd\xe0\x00\x00\x00\x00') # SQ delimiter
+ self.fp.seek(0)
+ assert self.fp.read() == expected
+
+ def test_big_endian_correct_data(self):
+ """Pixel data starting with an item tag is written."""
+ self.fp.is_little_endian = False
+ self.fp.is_implicit_VR = False
+ pixel_data = DataElement(0x7fe00010, 'OB',
+ b'\xff\xfe\xe0\x00'
+ b'\x00\x01\x02\x03',
+ is_undefined_length=True)
+ write_data_element(self.fp, pixel_data)
+ expected = (b'\x7f\xe0\x00\x10' # tag
+ b'OB\x00\x00' # VR
+ b'\xff\xff\xff\xff' # length
+ b'\xff\xfe\xe0\x00\x00\x01\x02\x03' # contents
+ b'\xff\xfe\xe0\xdd\x00\x00\x00\x00') # SQ delimiter
+ self.fp.seek(0)
+ assert self.fp.read() == expected
+
+ def test_little_endian_incorrect_data(self):
+ """Writing pixel data not starting with an item tag raises."""
+ self.fp.is_little_endian = True
+ self.fp.is_implicit_VR = False
+ pixel_data = DataElement(0x7fe00010, 'OB',
+ b'\xff\xff\x00\xe0'
+ b'\x00\x01\x02\x03'
+ b'\xfe\xff\xdd\xe0',
+ is_undefined_length=True)
+ with pytest.raises(ValueError, match='Pixel Data .* must '
+ 'start with an item tag'):
+ write_data_element(self.fp, pixel_data)
+
+ def test_big_endian_incorrect_data(self):
+ """Writing pixel data not starting with an item tag raises."""
+ self.fp.is_little_endian = False
+ self.fp.is_implicit_VR = False
+ pixel_data = DataElement(0x7fe00010, 'OB',
+ b'\x00\x00\x00\x00'
+ b'\x00\x01\x02\x03'
+ b'\xff\xfe\xe0\xdd',
+ is_undefined_length=True)
+ with pytest.raises(ValueError, match='Pixel Data .+ must '
+ 'start with an item tag'):
+ write_data_element(self.fp, pixel_data)
+
+
if __name__ == "__main__":
# This is called if run alone, but not if loaded through run_tests.py
# If not run from the directory where the sample images are,
| {
"commit_name": "merge_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 .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"numpy>=1.16.0",
"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
numpy==1.19.5
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/pydicom/pydicom.git@1bd33e3ceec19d45844676bdd25367fda4c5319b#egg=pydicom
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: pydicom
channels:
- defaults
- https://repo.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:
- numpy==1.19.5
prefix: /opt/conda/envs/pydicom
| [
"pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data",
"pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data"
]
| []
| [
"pydicom/tests/test_filewriter.py::WriteFileTests::testCT",
"pydicom/tests/test_filewriter.py::WriteFileTests::testJPEG2000",
"pydicom/tests/test_filewriter.py::WriteFileTests::testListItemWriteBack",
"pydicom/tests/test_filewriter.py::WriteFileTests::testMR",
"pydicom/tests/test_filewriter.py::WriteFileTests::testMultiPN",
"pydicom/tests/test_filewriter.py::WriteFileTests::testRTDose",
"pydicom/tests/test_filewriter.py::WriteFileTests::testRTPlan",
"pydicom/tests/test_filewriter.py::WriteFileTests::testUnicode",
"pydicom/tests/test_filewriter.py::WriteFileTests::test_write_double_filemeta",
"pydicom/tests/test_filewriter.py::WriteFileTests::test_write_no_ts",
"pydicom/tests/test_filewriter.py::WriteFileTests::testwrite_short_uid",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_empty_AT",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_DA",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_DT",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OD_explicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OD_implicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OL_explicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OL_implicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_TM",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UC_explicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UC_implicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UR_explicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UR_implicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_multi_DA",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_multi_DT",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_multi_TM",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated",
"pydicom/tests/test_filewriter.py::WriteAmbiguousVRTests::test_write_explicit_vr_big_endian",
"pydicom/tests/test_filewriter.py::WriteAmbiguousVRTests::test_write_explicit_vr_little_endian",
"pydicom/tests/test_filewriter.py::WriteAmbiguousVRTests::test_write_explicit_vr_raises",
"pydicom/tests/test_filewriter.py::ScratchWriteTests::testImpl_LE_deflen_write",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added",
"pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data",
"pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data"
]
| []
| MIT License | 1,609 | [
"pydicom/filewriter.py"
]
| [
"pydicom/filewriter.py"
]
|
Azure__msrest-for-python-43 | 11f19f936f2d2d912782c7280f02f01ed89baf47 | 2017-08-22 03:53:10 | 24deba7a7a9e335314058ec2d0b39a710f61be60 | diff --git a/msrest/serialization.py b/msrest/serialization.py
index 6eb8ec9..063f2e6 100644
--- a/msrest/serialization.py
+++ b/msrest/serialization.py
@@ -918,6 +918,9 @@ class Deserializer(object):
'[]': self.deserialize_iter,
'{}': self.deserialize_dict
}
+ self.deserialize_expected_types = {
+ 'duration': (isodate.Duration, datetime.timedelta)
+ }
self.dependencies = dict(classes) if classes else {}
self.key_extractors = [
rest_key_extractor
@@ -1080,6 +1083,8 @@ class Deserializer(object):
if data_type in self.basic_types.values():
return self.deserialize_basic(data, data_type)
if data_type in self.deserialize_type:
+ if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())):
+ return data
data_val = self.deserialize_type[data_type](data)
return data_val
| Serialization issue if dict syntax and Duration used
```python
msrest.exceptions.SerializationError: Unable to build a model: Unable to deserialize response data. Data: 3 years, 6 months, 4 days, 12:30:05, duration, TypeError: Expecting a string isodate.duration.Duration(4, 45005, 0, years=3, months=6), DeserializationError: Unable to deserialize response data. Data: 3 years, 6 months, 4 days, 12:30:05, duration, TypeError: Expecting a string isodate.duration.Duration(4, 45005, 0, years=3, months=6)
```
Regression introduced in 0.4.12
| Azure/msrest-for-python | diff --git a/tests/test_serialization.py b/tests/test_serialization.py
index f70dcbd..787a086 100644
--- a/tests/test_serialization.py
+++ b/tests/test_serialization.py
@@ -138,7 +138,6 @@ class TestRuntimeSerialized(unittest.TestCase):
class TestObj(Model):
- _validation = {}
_attribute_map = {
'attr_a': {'key':'id', 'type':'str'},
'attr_b': {'key':'AttrB', 'type':'int'},
@@ -147,23 +146,30 @@ class TestRuntimeSerialized(unittest.TestCase):
'attr_e': {'key':'AttrE', 'type': '{float}'},
'attr_f': {'key':'AttrF', 'type': 'duration'},
'attr_g': {'key':'properties.AttrG', 'type':'str'},
- }
-
- def __init__(self):
+ }
- self.attr_a = None
- self.attr_b = None
- self.attr_c = None
- self.attr_d = None
- self.attr_e = None
- self.attr_f = None
- self.attr_g = None
+ def __init__(self,
+ attr_a=None,
+ attr_b=None,
+ attr_c=None,
+ attr_d=None,
+ attr_e=None,
+ attr_f=None,
+ attr_g=None):
+
+ self.attr_a = attr_a
+ self.attr_b = attr_b
+ self.attr_c = attr_c
+ self.attr_d = attr_d
+ self.attr_e = attr_e
+ self.attr_f = attr_f
+ self.attr_g = attr_g
def __str__(self):
return "Test_Object"
def setUp(self):
- self.s = Serializer()
+ self.s = Serializer({'TestObj': self.TestObj})
return super(TestRuntimeSerialized, self).setUp()
def test_serialize_direct_model(self):
@@ -496,6 +502,14 @@ class TestRuntimeSerialized(unittest.TestCase):
message = self.s._serialize(test_obj)
self.assertEquals("P1D", message["AttrF"])
+ test_obj = self.TestObj()
+ test_obj.attr_f = isodate.parse_duration("P3Y6M4DT12H30M5S")
+
+ message = self.s.body({
+ "attr_f": isodate.parse_duration("P3Y6M4DT12H30M5S")},
+ 'TestObj')
+ self.assertEquals("P3Y6M4DT12H30M5S", message["AttrF"])
+
def test_attr_list_simple(self):
"""
Test serializing an object with simple-typed list attributes
@@ -657,8 +671,8 @@ class TestRuntimeSerialized(unittest.TestCase):
g = self.s.body({"test":{"value":"data"}}, 'object')
self.assertEqual(g, {"test":{"value":"data"}})
- h = self.s.serialize_data({"test":self.TestObj()}, 'object')
- self.assertEqual(h, {"test":"Test_Object"})
+ h = self.s.serialize_data({"test":self.TestObj('id')}, 'object')
+ self.assertEqual(h, {"test":{'id': 'id'}})
i = self.s.serialize_data({"test":[1,2,3,4,5]}, 'object')
self.assertEqual(i, {"test":[1,2,3,4,5]})
| {
"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.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt",
"dev_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
exceptiongroup==1.2.2
httpretty==1.1.4
idna==3.10
iniconfig==2.1.0
isodate==0.7.2
-e git+https://github.com/Azure/msrest-for-python.git@11f19f936f2d2d912782c7280f02f01ed89baf47#egg=msrest
oauthlib==3.2.2
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cov==6.0.0
requests==2.32.3
requests-oauthlib==2.0.0
tomli==2.2.1
urllib3==2.3.0
| name: msrest-for-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
- 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
- exceptiongroup==1.2.2
- httpretty==1.1.4
- idna==3.10
- iniconfig==2.1.0
- isodate==0.7.2
- oauthlib==3.2.2
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cov==6.0.0
- requests==2.32.3
- requests-oauthlib==2.0.0
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/msrest-for-python
| [
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_duration"
]
| []
| [
"tests/test_serialization.py::TestModelDeserialization::test_response",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_bool",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_dict_simple",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_enum",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_int",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_list_complex",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_list_simple",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_none",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_sequence",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_str",
"tests/test_serialization.py::TestRuntimeSerialized::test_empty_list",
"tests/test_serialization.py::TestRuntimeSerialized::test_key_type",
"tests/test_serialization.py::TestRuntimeSerialized::test_model_validate",
"tests/test_serialization.py::TestRuntimeSerialized::test_obj_serialize_none",
"tests/test_serialization.py::TestRuntimeSerialized::test_obj_with_malformed_map",
"tests/test_serialization.py::TestRuntimeSerialized::test_obj_with_mismatched_map",
"tests/test_serialization.py::TestRuntimeSerialized::test_obj_without_attr_map",
"tests/test_serialization.py::TestRuntimeSerialized::test_polymorphic_serialization",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_datetime",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_direct_model",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_empty_iter",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_json_obj",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_object",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_primitive_types",
"tests/test_serialization.py::TestRuntimeSerialized::test_validate",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_bool",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_int",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_list_complex",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_list_in_list",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_list_simple",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_none",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_str",
"tests/test_serialization.py::TestRuntimeDeserialized::test_basic_deserialization",
"tests/test_serialization.py::TestRuntimeDeserialized::test_cls_method_deserialization",
"tests/test_serialization.py::TestRuntimeDeserialized::test_deserialize_datetime",
"tests/test_serialization.py::TestRuntimeDeserialized::test_deserialize_object",
"tests/test_serialization.py::TestRuntimeDeserialized::test_deserialize_storage",
"tests/test_serialization.py::TestRuntimeDeserialized::test_non_obj_deserialization",
"tests/test_serialization.py::TestRuntimeDeserialized::test_obj_with_malformed_map",
"tests/test_serialization.py::TestRuntimeDeserialized::test_obj_with_no_attr",
"tests/test_serialization.py::TestRuntimeDeserialized::test_personalize_deserialization",
"tests/test_serialization.py::TestRuntimeDeserialized::test_polymorphic_deserialization",
"tests/test_serialization.py::TestRuntimeDeserialized::test_polymorphic_deserialization_with_escape",
"tests/test_serialization.py::TestRuntimeDeserialized::test_robust_deserialization",
"tests/test_serialization.py::TestModelInstanceEquality::test_model_instance_equality"
]
| []
| MIT License | 1,610 | [
"msrest/serialization.py"
]
| [
"msrest/serialization.py"
]
|
|
mjs__imapclient-277 | f849e44f5cbcaf40433612875b5e84730b1fe358 | 2017-08-22 11:35:54 | 2abdac690fa653fa2d0d55b7617be24101597698 | diff --git a/doc/src/releases.rst b/doc/src/releases.rst
index 17c0f07..3e6c672 100644
--- a/doc/src/releases.rst
+++ b/doc/src/releases.rst
@@ -6,6 +6,7 @@
Changed
-------
+- Connections to servers use SSL/TLS by default (`ssl=True`)
- XXX Use built-in TLS when sensible.
- Logs are now handled by the Python logging module. `debug` and `log_file`
are not used anymore.
diff --git a/imapclient/config.py b/imapclient/config.py
index b6d243a..ebff841 100644
--- a/imapclient/config.py
+++ b/imapclient/config.py
@@ -28,7 +28,7 @@ def get_config_defaults():
return dict(
username=getenv("username", None),
password=getenv("password", None),
- ssl=False,
+ ssl=True,
ssl_check_hostname=True,
ssl_verify_cert=True,
ssl_ca_file=None,
diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index 3776e18..3792a1f 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -85,16 +85,17 @@ class IMAPClient(object):
"""A connection to the IMAP server specified by *host* is made when
this class is instantiated.
- *port* defaults to 143, or 993 if *ssl* is ``True``.
+ *port* defaults to 993, or 143 if *ssl* is ``False``.
If *use_uid* is ``True`` unique message UIDs be used for all calls
that accept message ids (defaults to ``True``).
- If *ssl* is ``True`` an SSL connection will be made (defaults to
- ``False``).
+ If *ssl* is ``True`` (the default) a secure connection will be made.
+ Otherwise an insecure connection over plain text will be
+ established.
If *ssl* is ``True`` the optional *ssl_context* argument can be
- used to provide a ``backports.ssl.SSLContext`` instance used to
+ used to provide an ``ssl.SSLContext`` instance used to
control SSL/TLS connection parameters. If this is not provided a
sensible default context will be used.
@@ -122,7 +123,7 @@ class IMAPClient(object):
AbortError = imaplib.IMAP4.abort
ReadOnlyError = imaplib.IMAP4.readonly
- def __init__(self, host, port=None, use_uid=True, ssl=False, stream=False,
+ def __init__(self, host, port=None, use_uid=True, ssl=True, stream=False,
ssl_context=None, timeout=None):
if stream:
if port is not None:
@@ -132,6 +133,11 @@ class IMAPClient(object):
elif port is None:
port = ssl and 993 or 143
+ if ssl and port == 143:
+ logger.warning("Attempting to establish an encrypted connection "
+ "to a port (143) often used for unencrypted "
+ "connections")
+
self.host = host
self.port = port
self.ssl = ssl
@@ -146,7 +152,8 @@ class IMAPClient(object):
self._cached_capabilities = None
self._imap = self._create_IMAP4()
- logger.debug("Connected to host %s", self.host)
+ logger.debug("Connected to host %s over %s", self.host,
+ "SSL/TLS" if ssl else "plain text")
# Small hack to make imaplib log everything to its own logger
imaplib_logger = IMAPlibLoggerAdapter(
| Make SSL connections the default
In 2017 there is little reasons to connect to a mailbox over plain text.
As this is a breaking change I propose to do it for 2.0.0. | mjs/imapclient | diff --git a/tests/test_init.py b/tests/test_init.py
index 6dbb0b2..f99b238 100644
--- a/tests/test_init.py
+++ b/tests/test_init.py
@@ -25,7 +25,7 @@ class TestInit(unittest.TestCase):
fakeIMAP4 = Mock()
self.imap4.IMAP4WithTimeout.return_value = fakeIMAP4
- imap = IMAPClient('1.2.3.4', timeout=sentinel.timeout)
+ imap = IMAPClient('1.2.3.4', ssl=False, timeout=sentinel.timeout)
self.assertEqual(imap._imap, fakeIMAP4)
self.imap4.IMAP4WithTimeout.assert_called_with(
@@ -42,7 +42,7 @@ class TestInit(unittest.TestCase):
fakeIMAP4_TLS = Mock()
self.tls.IMAP4_TLS.return_value = fakeIMAP4_TLS
- imap = IMAPClient('1.2.3.4', ssl=True, ssl_context=sentinel.context,
+ imap = IMAPClient('1.2.3.4', ssl_context=sentinel.context,
timeout=sentinel.timeout)
self.assertEqual(imap._imap, fakeIMAP4_TLS)
@@ -58,7 +58,7 @@ class TestInit(unittest.TestCase):
def test_stream(self):
self.imaplib.IMAP4_stream.return_value = sentinel.IMAP4_stream
- imap = IMAPClient('command', stream=True)
+ imap = IMAPClient('command', stream=True, ssl=False)
self.assertEqual(imap._imap, sentinel.IMAP4_stream)
self.imaplib.IMAP4_stream.assert_called_with('command')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 3
} | 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": [
"mock>=1.3.0",
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements/base.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/mjs/imapclient.git@f849e44f5cbcaf40433612875b5e84730b1fe358#egg=IMAPClient
importlib-metadata==4.8.3
iniconfig==1.1.1
mock==5.2.0
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: imapclient
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mock==5.2.0
- 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/imapclient
| [
"tests/test_init.py::TestInit::test_SSL"
]
| []
| [
"tests/test_init.py::TestInit::test_plain",
"tests/test_init.py::TestInit::test_ssl_and_stream_is_error",
"tests/test_init.py::TestInit::test_stream",
"tests/test_init.py::TestInit::test_stream_and_port_is_error"
]
| []
| BSD License | 1,611 | [
"doc/src/releases.rst",
"imapclient/imapclient.py",
"imapclient/config.py"
]
| [
"doc/src/releases.rst",
"imapclient/imapclient.py",
"imapclient/config.py"
]
|
|
pydicom__pydicom-492 | 1bd33e3ceec19d45844676bdd25367fda4c5319b | 2017-08-22 16:59:10 | bef49851e7c3b70edd43cc40fc84fe905e78d5ba | glemaitre: Some artifact showing the use of the sphinx :user: and :issue: utilities
https://140-58641730-gh.circle-artifacts.com/0/home/ubuntu/pydicom/doc/_build/html/release-notes.html#documentation
massich: Thats fine with me | diff --git a/doc/index.rst b/doc/index.rst
index 6a687f030..f9ac39d7a 100644
--- a/doc/index.rst
+++ b/doc/index.rst
@@ -29,6 +29,12 @@ pydicom documentation
auto_examples/index
+.. toctree::
+ :maxdepth: 1
+ :hidden:
+ :caption: Additional Information
+
+ release-notes
`Getting started <getting_started.html>`_
-----------------------------------------
@@ -53,3 +59,8 @@ all functions, and all parameters available for the core elements.
A set of examples illustrating the use of the different core elements. It
complements the `User Guide <pydicom_user_guide.html>`_.
+
+`What's new <release-note.html>`_
+------------------------------
+
+Log of the pydicom history.
diff --git a/doc/release-notes.rst b/doc/release-notes.rst
new file mode 100644
index 000000000..117fd5122
--- /dev/null
+++ b/doc/release-notes.rst
@@ -0,0 +1,446 @@
+.. currentmodule:: pydicom
+
+===============
+Release history
+===============
+
+Version 1.0.0 (under development)
+=================================
+
+This is a major release, with major changes, including backwards-incompatible
+changes.
+
+Changelog
+---------
+
+Enhancements
+............
+
+* fully python3 compatible -- one code-base for both python 2 and python 3
+* package name and the import name match -- now use ``import pydicom`` rather
+ than ``import dicom``
+* optional GDCM support for reading files with compressed pixel data
+* optional Pillow, jpeg_ls support for reading some compressed pixel data files
+* cleaned up dicom dictionary code, old non-dicom-keyword code removed
+* dicom dictionary updated to 2017c
+
+Documentation
+.............
+
+* Documentation refactorization with examples. :issue:`472` by :user:`Guillaume
+ Lemaitre <glemaitre>`.
+
+Other changes
+.............
+
+* updated doc strings for common functions
+* UID.py now uid.py to match python style guide
+* added util/fixer.py -- callbacks available to fix dicom non-compliant values
+ before exceptions thrown
+* added PyPy support
+* added util/leanread.py -- very bare-bones reading (for fastest possible speed)
+* added misc/is_dicom function -- return True if a dicom file
+* added context management methods to Dataset
+* added date/time converters :issue:`143`
+* fixed pixel handling for ``PlanarConfiguration=0``
+* updated uid generation to ensure uniqueness
+* added some heuristics to accept files with missing preamble and file_meta
+* added ``from_name()`` method to UID class, to generate UID instance from
+ descriptive name
+* added ability to add custom dicom dictionary items via ``add_dict_entry()``
+ and ``add_dict_entries()``
+* more methods for DataElement -- keyword, is_retired, etc.
+* some support for pickle, cpickle
+* fixes/additions for some character set encodings
+
+Version 0.9.9
+=============
+
+Changelog
+---------
+
+In addition to bug fixes, pydicom 0.9.9 contains updates for all dicom
+dictionaries. New features include DICOMDIR handling, and a utility module
+which produces python/pydicom source code to recreate a dicom file.
+
+Enhancements
+............
+
+* All dicom dictionaries updated (standard dictionary, UID dictionary, and
+ private dictionaries)
+* Dicom commands also added to dictionary
+* Ability to work with DICOMDIR: ``read_dicomdir()`` function and ``DicomDir``
+ class. Example file ``show_dicomdir.py`` file added to examples subdirectory.
+* ``codify.py``: Produce python/pydicom source code from a dicom file.
+* a number of python 3 compatibility enhancements
+* setup.py uses ez_setup only if setuptools not already installed
+* exceptions carry tag info with them, to aid in debugging
+
+Contrib file changes
+....................
+
+* pydicom_series: force parameter added (Nil Goyette)
+* dcm_qt_tree: switch to OrderedDict to preserve ordering of tags (Padraig Looney)
+
+Other Contributors
+..................
+
+Other than Jonathan and myself, other contributors were: Rickard Holmberg,
+Julien Lamy, Yaroslav Halchenko, Mark White, Matthew Brett, Dimitri
+Papadopoulos, videan42 ...(sorry if I've missed anyone).
+
+Version 0.9.8
+=============
+
+Changelog
+---------
+
+pydicom 0.9.8 is mainly a consolidation step before moving to official python 3
+compatibility in pydicom 1.0. It also reverts the change to using Decimal for
+VR of DS (in pydicom 0.9.7), due to performance issues. DS as Decimal is still
+available, but is off by default.
+
+Major changes
+.............
+
+* Requires python 2.6 or later, in preparation for python 3 compatibility
+* experimental python 3 compatibility (unofficial at this point) -- uncomment
+ the two indicated lines in setup.py to use it. Please provide feedback to the
+ issues list.
+* DS values reverted to using float as default (issue 114) due to slow
+ performance using python Decimal. Speed tests show approx factor of 10
+ improvement compared with pydicom 0.9.7 (several revisions up to
+ r78ba350a3eb8)
+* streamlined much code internally taking advantage of modern python
+ constructs: decorators, generators, etc
+
+Bug fixes
+.........
+
+* Fix for duplicate logger from Gunnar Schaefer. Fixes issue 107 (revision
+ 774b7a55db33)
+* Fix rewind behavior in find_bytes (issue 60, revision 6b949a5b925b)
+* Fix error in nested private sequences (issue 113, revision 84af4b240add)
+
+
+Enhancements
+............
+
+* UID generator added (Félix C. Morency) (revisions 0197b5846bb5 and
+ 3678b1be6aca, tests in f1ae573d9de5, 0411bab7c985)
+* new PersonName3 class for python 3: (revision 9b92b336e7d4)
+
+Contrib file changes
+....................
+
+* Fix for pydicom_series for DS decimal (revision e830f30b6781)
+* new dcm_qt_tree.py module - tree display of dicom files using PySide and
+ Qt. Contributed by Padraig Looney.
+
+Special acknowledgement to Jonathan Suever who contributed most of the python 3
+work and many bug fixes.
+
+Version 0.9.7
+=============
+
+Changelog
+---------
+
+pydicom 0.9.7 resolves some remaining bugs before moving to python 3
+compatibility. ** It is the last version which will run with python < 2.6 **
+(it will run with python2.4 to python2.7)
+
+Major changes
+.............
+
+* Added DICOM 2011 keywords. Old "named tags" still work, but will be
+deprecated in future versions. Most names are identical, but some have changed.
+For example:
+* SamplesperPixel becomes SamplesPerPixel (capital 'P' on 'Per')
+* Beams becomes BeamSequence (and similar for all sequences)
+* Decimal and integer strings handled much better (revisions 4ed698a7bfbe and
+ c313d2befb08).
+* New classes for VR of types DS and IS (DS is derived from python Decimal)
+* New MultiValue class, enforcing all values of same type
+* New config.py file with user-definable parameters:
+* allow_DS_float (default False) for controlling whether float values can be
+ used to construct DS or IS strings.
+* enforce_valid_values (default True) for ensuring IS, DS meet DICOM standard
+ limits To change these, use 'import dicom.config, then
+ dicom.config.<parameter>={True|False}' before setting values of data elements
+
+Users are encouraged to switch to the official DICOM keywords, as these are now
+part of the standard, and promote consistency across programming languages and
+libraries.
+
+Bug fixes
+.........
+
+* New way to read file meta information, not using the group length, instead
+ reading until end of group 2 data elements. If group length dose not match,
+ log a warning (revision b6b3658f3b14).
+* Fix bug in copying raw private data elements (issue 98)
+* Force logging level to warning on 'import dicom' (issue 102)
+* Deferred read fixed to work with gzipped files (issue 103)
+* Setting individual items in a DS or IS list now saves to file correctly
+* Japanese and Korean encoding fixes (issue 110)
+
+Other Enhancements
+..................
+
+* New Sequence class which verifies items are Datasets (issue 52)
+* Assignment to SQ data element checks value is a Sequence or can be converted
+ to one (issue 111)
+* dir(ds) now includes methods and properties as well as DICOM named tags. Work
+ only on Python >= 2.6 as previous versions do not call __dir__ method
+ (issue 95)
+* Added much more debugging info and simplified reading of data elements
+ (revision b6b3658f3b14)
+* updated example files to DICOM 2011 keywords; fixed bugs
+
+Many of the bug fixes/enhancements were submitted by users. Many thanks to
+those who contributed.
+
+Version 0.9.6
+=============
+
+Changelog
+---------
+
+pydicom 0.9.6 updates the dictionary to the DICOM 2011 standard, and has a
+number of bug fixes
+
+Major changes
+.............
+
+* updated the dictionary to the DICOM 2011 standard's dictionary.
+
+Bug fixes
+.........
+
+* Fixed bug in Dataset.file_metadata() and deprecated in favor of FileDataset
+ (issue 93)
+* Fixed UID comparisons against non-string values (issue 96)
+* catch exceptions on reading undefined length private data elements (issue 91,
+ issue 97)
+* Fixed bug in raising exception for unknown tag
+
+Other
+.....
+
+* added example file write_new.py to show how to create DICOM files from scratch
+* updated other example files
+* more PEP-8 style changes
+
+Version 0.9.5
+=============
+
+Changelog
+---------
+
+pydicom 0.9.5 is primarily a bug-fix release but includes some contrib files
+also.
+
+Major fixes in this release
+...........................
+
+* fix for incorrect pixel integer types which could lead to numeric errors
+ (issue 79)
+* By default an InvalidDicomError will be raised when trying to read a
+ non-DICOM file (unless read_file keyword arg {{{force}}} is True) (revision
+ fc790f01f5)
+* fix recursion error on private data elements (issue 81, issue 84)
+
+Other fixes in this release
+...........................
+
+* Fix for unicode decode failing with VM > 1 (issue 78)
+* fix for fail of DicomIter on files with Explicit VR Transfer Syntax UID
+ (issue 82)
+* Fix for python 2.5 and 'with' statement (revision 1c32791bf0)
+* Handle 'OB/OW' VR as well as 'OW/OB' (revision e3ee934bbc)
+* Fix dataset.get(tag) so returns same as dataset[tag] (issue 88)
+
+New 'Contrib' files
+...................
+
+* dicom_dao.py by Mike Wallace -- CouchDB storage of DICOM info and binary data
+* pydicom_series.py by Almar Klein -- Reads files and separates into distinct
+ series.
+
+Other
+.....
+
+* switch to Distribute for packaging
+* preliminary work on python 3 compatiblity
+* preliminary work on using sphinx for documentation
+* preliminary work on better writing of files from scratch
+
+Version 0.9.4
+=============
+
+Changelog
+---------
+
+.. note::
+
+ * there is a *backwards incompatible* change made to storage of file_meta
+ info. See item below.
+ * pydicom 0.9.4 requires python 2.4 or higher (pydicom 0.9.3 can run under
+ python 2.3)
+
+Major changes/additions in this version
+.......................................
+
+* file reading code reorganized substantially
+* significant speed increase for reading DICOM files -- approx 3 times faster
+ than 0.9.3
+* partial file reading available -- in particular, new optional argument to
+ read_file(), stop_before_pixels, will stop before getting to the pixel data,
+ not reading those into memory. Saves a little time for small images, but
+ could be quite helpful for very large images when the pixel data is not
+ needed.
+* read_file() now returns a !FileDataset object, instead of a plain
+ Dataset. Most user code will not see much difference (except see next
+ bullet on file meta information) but now the information stored in the
+ object has been made explicit -- e.g. the endian-ness and whether the file
+ syntax was explicit VR or implicit VR.
+* file meta info has been separated from the main dataset. Logically, this
+ makes more sense, as the file meta is not really part of the dataset, but is
+ specific to the method of storage. This is a backwards-incompatible change,
+ but is easily fixed by changing any references to file-meta data elements
+ from {{{dataset.<name>}}} to {{{dataset.file_meta.<name>}}}. The file_meta is
+ a dataset like any other, all the usual methods for viewing, changing data
+ elements work on it also.
+* private dictionaries file now generated from the GDCM library's private
+ dictionary -- code to convert formats contributed by Daniel Nanz.
+* license has returned to an MIT-based license (with the compatible GDCM also
+ noted for the private dictionary component).
+* contributed files with example code for viewing using wxPython or Tkinter
+ (and PIL) -- in dicom.contrib folder. Thanks to Dave Witten, Daniel Nanz and
+ Adit Panchal for these contributions.
+* updates to pydicom's DICOM data dictionary contributed by Adit Panchal:
+ CP805/916; Supp 43 and 117 (and UID dict), Supp 119 and 122
+
+Other changes and bug fixes
+...........................
+
+* Tag is now a factory function; the class is called !BaseTag. This was part of
+ the file reading speed-up process -- a new class !TupleTag was also created,
+ for faster file reading
+* passing a file object to read_file() now works correctly, and also the file
+ closing works as it should (caller needs to close any files passed in)
+ (issue 73)
+* Fix for issue 72 : dataset.get() fails when passed type other than string or
+ Tag. Patch contributed by !NikitaTheSpider
+* Fix for issue 58 : error opening file with unicode. Fix contributed by Pierre
+ Raybaut
+* Fix for issue 42 : catch !AttributeError in property and give proper error
+ message
+* Fix for issue 55 : UI type changed with string operations
+* Tag fixes and enhancements : can create tags with hex string (group,
+ elem). Allow lists as well as tuples (issue 47). Fix arg2=0 bug (issue 64).
+
+Version 0.9.3
+=============
+
+Changelog
+---------
+
+Major changes
+.............
+
+* changed to MIT-style license
+* option to defer reading of large data element values using read_file()'s new
+ defer_size argument (r102, r103)
+* dictionary of private tags added -- descriptive text shown when available
+ (issue36, r97, r110)
+* more conversion to PEP-8 style. Should now use read_file(), save_as(),
+ pixel_array rather than !ReadFile(), !SaveAs(), !PixelArray. Old names kept
+ for now as aliases.
+
+Other Enhancements
+..................
+
+* added DicomFileLike class to simplify and generalize access. Any object that
+ has read, write, seek, tell, and close can now be used. (r105)
+* added dataset.iterall() function to iterate through all items (including
+ inside sequences) (r105)
+* added dataset.formatted_lines() generator to allow custom formatting (r91,
+ r113)
+* made reading tolerant of truncated files -- gives a warning, but returns
+ dataset read to that point (r95)
+
+Bug Fixes
+.........
+
+* fixed issue38, name collision for 'Other Patient Ids' as both data element
+ and sequence name in DICOM standard (r95, r96)
+* fixed issue40, blank VRs in some DICOM dictionary entries caused
+ NotImplementError on reading (r100)
+* fixed issue41, reading VRs of 'US or SS' and similar split on backslash
+ character (r104)
+* fixed bug where TransferSyntaxUID not present when reading file without DICOM
+ header (r109)
+* fixed print recursion bug when printing a UID (r111)
+
+Other
+.....
+
+* many of the example files updated
+* updated anonymize example file to also deal with 'OtherPatientIDs' and
+ 'PatientsBirthDate' (r98)
+
+Version 0.9.2
+=============
+
+Changelog
+---------
+
+Major changes
+.............
+
+* Renamed Attribute class and related modules to !DataElement. Old code will
+ continue to work until pydicom 1.0, but with a !DeprecationWarning (issue22,
+ r72, r73)
+* Added support for character sets through Specific Character Set (0008,0005),
+ using python unicode. Thus foreign languages can display names in Greek,
+ Japanese, Chinese etc characters in environments which support unicode
+ (demonstrated in dicomtree.py example using Tkinter GUI) (r64, r65)
+
+Other Enhancements
+..................
+
+* Added support for auto-completion of dataset elements in ipython; also all
+ environments using python 2.6 (r69, r70)
+* Added __iter__() to Dataset so returns data elements in DICOM order with "for
+ data_elem in dataset:" (r68)
+* Added dicomtree.py example program showing a DICOM file in a GUI window
+ (Tkinter/Tix).
+* Added !PersonName class to parse components of names more easily (r55)
+* Added UID class to handle UID values. Name rather than UID number shown,
+ UID_dictionary used (r51).
+* Code tested under python 2.6
+* Added !DataElement.name property; synonym for !DataElement.description()
+ function
+
+Bug Fixes
+.........
+
+* Fixed issue27, sequence with a single empty item read incorrectly
+* Fixed bug that read_OW did not handle !UndefinedLength (r50)
+* Fixed bugs in example files anonymize.py, !DicomInfo.py, and dicomtree.py
+ (r51)
+* Fixed issue33, VR=UN being split on backslash (r70)
+* Fixed issue18, util directory not installed (r45)
+
+Other
+.....
+
+* Added example file myprint.py -- shows how to custom format DICOM file
+ information (r67)
+* Reorganized test files and added various new tests
+* added preliminary work on encapsulated data (r50)
+* added some simple files to view or work with pixel data (r46)
+* Dataset.!PixelDataArray() Numpy array changed to property Dataset.!PixelArray
+* changed to setuptools for packaging rather than distutils
diff --git a/doc/release-notes.txt b/doc/release-notes.txt
deleted file mode 100644
index 2e272d9cb..000000000
--- a/doc/release-notes.txt
+++ /dev/null
@@ -1,267 +0,0 @@
-#summary Release notes for pydicom package releases
-----
-= Release Notes pydicom 1.0.0 =
-
-This is a major release, with major changes, including backwards-incompatible changes.
-
-== Major changes / enhancements ==
- * fully python3 compatible -- one code-base for both python 2 and python 3
- * package name and the import name match -- now use ``import pydicom`` rather than ``import dicom``
- * optional GDCM support for reading files with compressed pixel data
- * optional Pillow, jpeg_ls support for reading some compressed pixel data files
- * cleaned up dicom dictionary code, old non-dicom-keyword code removed
-
- * dicom dictionary updated to ..............
-
-
-== Other changes ==
- * updated doc strings for common functions
- * UID.py now uid.py to match python style guide
- * added util/fixer.py -- callbacks available to fix dicom non-compliant values before exceptions thrown
- * added PyPy support
- * added util/leanread.py -- very bare-bones reading (for fastest possible speed)
- * added misc/is_dicom function -- return True if a dicom file
- * added context management methods to Dataset
- * added date/time converters (issue 143)
- * fixed pixel handling for PlanarConfiguration=0
- * updated uid generation to ensure uniqueness
- * added some heuristics to accept files with missing preamble and file_meta
- * added from_name() method to UID class, to generate UID instance from descriptive name
- * added ability to add custom dicom dictionary items via add_dict_entry() and add_dict_entries()
- * more methods for DataElement -- keyword, is_retired, etc.
- * some support for pickle, cpickle
- * fixes/additions for some character set encodings
-
-== Contrib file changes ==
-
-
-== Other Contributors ==
-
-
-
-= Release Notes pydicom 0.9.9 =
-
-In addition to bug fixes, pydicom 0.9.9 contains updates for all dicom dictionaries.
-New features include DICOMDIR handling, and a utility module which produces python/pydicom source code to recreate a dicom file.
-
-== Major changes / enhancements ==
- * All dicom dictionaries updated (standard dictionary, UID dictionary, and private dictionaries)
- * Dicom commands also added to dictionary
- * Ability to work with DICOMDIR: read_dicomdir() function and DicomDir class. Example file show_dicomdir.py file added to examples subdirectory.
- * codify.py: Produce python/pydicom source code from a dicom file.
- * a number of python 3 compatibility enhancements
- * setup.py uses ez_setup only if setuptools not already installed
- * exceptions carry tag info with them, to aid in debugging
-
-== Contrib file changes ==
- * pydicom_series: force parameter added (Nil Goyette)
- * dcm_qt_tree: switch to OrderedDict to preserve ordering of tags (Padraig Looney)
-
-== Other Contributors ==
-Other than Jonathan and myself, other contributors were:
-Rickard Holmberg, Julien Lamy, Yaroslav Halchenko, Mark White, Matthew Brett, Dimitri Papadopoulos, videan42 ...(sorry if I've missed anyone).
-
-
-= Release Notes pydicom 0.9.8 =
-
-pydicom 0.9.8 is mainly a consolidation step before moving to official python 3 compatibility in pydicom 1.0.
-It also reverts the change to using Decimal for VR of DS (in pydicom 0.9.7), due to performance issues. DS as Decimal is still available, but is off by default.
-
-== Major changes ==
- * Requires python 2.6 or later, in preparation for python 3 compatibility
- * experimental python 3 compatibility (unofficial at this point) -- uncomment the two indicated lines in setup.py to use it. Please provide feedback to the issues list.
- * DS values reverted to using float as default (issue 114) due to slow performance using python Decimal. Speed tests show approx factor of 10 improvement compared with pydicom 0.9.7 (several revisions up to r78ba350a3eb8)
- * streamlined much code internally taking advantage of modern python constructs: decorators, generators, etc
-
-== Bug fixes ==
- * Fix for duplicate logger from Gunnar Schaefer. Fixes issue 107 (revision 774b7a55db33)
- * Fix rewind behavior in find_bytes (issue 60, revision 6b949a5b925b)
- * Fix error in nested private sequences (issue 113, revision 84af4b240add)
-
-
-== Enhancements ==
- * UID generator added (Félix C. Morency) (revisions 0197b5846bb5 and 3678b1be6aca, tests in f1ae573d9de5, 0411bab7c985)
- * new PersonName3 class for python 3: (revision 9b92b336e7d4)
-
-== Contrib file changes ==
- * Fix for pydicom_series for DS decimal (revision e830f30b6781)
- * new dcm_qt_tree.py module - tree display of dicom files using PySide and Qt. Contributed by Padraig Looney.
-
-Special acknowledgement to Jonathan Suever who contributed most of the python 3 work and many bug fixes.
-
-
-= Release notes for pydicom 0.9.7 =
-
-pydicom 0.9.7 resolves some remaining bugs before moving to python 3 compatibility.
-** It is the last version which will run with python < 2.6 ** (it will run with
-python2.4 to python2.7)
-
-== Major changes ==
- * Added DICOM 2011 keywords. Old "named tags" still work, but
- will be deprecated in future versions. Most names are identical, but some have changed.
- For example:
- * SamplesperPixel becomes SamplesPerPixel (capital 'P' on 'Per')
- * Beams becomes BeamSequence (and similar for all sequences)
- * Decimal and integer strings handled much better (revisions 4ed698a7bfbe and c313d2befb08).
- * New classes for VR of types DS and IS (DS is derived from python Decimal)
- * New MultiValue class, enforcing all values of same type
- * New config.py file with user-definable parameters:
- * allow_DS_float (default False) for controlling whether float values
- can be used to construct DS or IS strings.
- * enforce_valid_values (default True) for ensuring IS, DS meet DICOM standard limits
- To change these, use 'import dicom.config, then dicom.config.<parameter>={True|False}'
- before setting values of data elements
-
-Users are encouraged to switch to the official DICOM keywords, as these are now part of
-the standard, and promote consistency across programming languages and libraries.
-
-== Bug fixes ==
- * New way to read file meta information, not using the group length, instead
- reading until end of group 2 data elements. If group length dose not match,
- log a warning (revision b6b3658f3b14).
- * Fix bug in copying raw private data elements (issue 98)
- * Force logging level to warning on 'import dicom' (issue 102)
- * Deferred read fixed to work with gzipped files (issue 103)
- * Setting individual items in a DS or IS list now saves to file correctly
- * Japanese and Korean encoding fixes (issue 110)
-
-== Other Enhancements ==
- * New Sequence class which verifies items are Datasets (issue 52)
- * Assignment to SQ data element checks value is a Sequence or can be converted to one (issue 111)
- * dir(ds) now includes methods and properties as well as DICOM named tags. Work only on Python >= 2.6 as previous versions do not call __dir__ method (issue 95)
- * Added much more debugging info and simplified reading of data elements (revision b6b3658f3b14)
- * updated example files to DICOM 2011 keywords; fixed bugs
-
-Many of the bug fixes/enhancements were submitted by users. Many thanks to
-those who contributed.
-
-
-= Release notes for pydicom 0.9.6 =
-
-pydicom 0.9.6 updates the dictionary to the DICOM 2011 standard, and has a number of bug fixes
-
-== Major changes ==
- * updated the dictionary to the DICOM 2011 standard's dictionary.
-
-== Bug fixes ==
- * Fixed bug in Dataset.file_metadata() and deprecated in favor of FileDataset (issue 93)
- * Fixed UID comparisons against non-string values (issue 96)
- * catch exceptions on reading undefined length private data elements (issue 91, issue 97)
- * Fixed bug in raising exception for unknown tag
-
-== Other ==
- * added example file write_new.py to show how to create DICOM files from scratch
- * updated other example files
- * more PEP-8 style changes
-
-
-= Release notes for pydicom 0.9.5 =
-
-pydicom 0.9.5 is primarily a bug-fix release but includes some contrib files also.
-
-== Major fixes in this release ==
- * fix for incorrect pixel integer types which could lead to numeric errors (issue 79)
- * By default an InvalidDicomError will be raised when trying to read a non-DICOM
-file (unless read_file keyword arg {{{force}}} is True) (revision fc790f01f5)
- * fix recursion error on private data elements (issue 81, issue 84)
-
-== Other fixes in this release ==
- * Fix for unicode decode failing with VM > 1 (issue 78)
- * fix for fail of DicomIter on files with Explicit VR Transfer Syntax UID (issue 82)
- * Fix for python 2.5 and 'with' statement (revision 1c32791bf0)
- * Handle 'OB/OW' VR as well as 'OW/OB' (revision e3ee934bbc)
- * Fix dataset.get(tag) so returns same as dataset[tag] (issue 88)
-
-== New 'Contrib' files ==
- * dicom_dao.py by Mike Wallace -- CouchDB storage of DICOM info and binary data
- * pydicom_series.py by Almar Klein -- Reads files and separates into distinct series.
-
-== Other ==
- * switch to Distribute for packaging
- * preliminary work on python 3 compatiblity
- * preliminary work on using sphinx for documentation
- * preliminary work on better writing of files from scratch
-
-
-= Release notes for pydicom 0.9.4 =
-
-*NOTE:*
- * there is a *backwards incompatible* change made to storage of file_meta info. See item below.
- * pydicom 0.9.4 requires python 2.4 or higher (pydicom 0.9.3 can run under python 2.3)
-
-== Major changes/additions in this version ==
- * file reading code reorganized substantially
- * significant speed increase for reading DICOM files -- approx 3 times faster than 0.9.3
- * partial file reading available -- in particular, new optional argument to read_file(), stop_before_pixels, will stop before getting to the pixel data, not reading those into memory. Saves a little time for small images, but could be quite helpful for very large images when the pixel data is not needed.
- * read_file() now returns a !FileDataset object, instead of a plain Dataset. Most user code will not see much difference (except see next bullet on file meta information) but now the information stored in the object has been made explicit -- e.g. the endian-ness and whether the file syntax was explicit VR or implicit VR.
- * file meta info has been separated from the main dataset. Logically, this makes more sense, as the file meta is not really part of the dataset, but is specific to the method of storage. This is a backwards-incompatible change, but is easily fixed by changing any references to file-meta data elements from {{{dataset.<name>}}} to {{{dataset.file_meta.<name>}}}. The file_meta is a dataset like any other, all the usual methods for viewing, changing data elements work on it also.
- * private dictionaries file now generated from the GDCM library's private dictionary -- code to convert formats contributed by Daniel Nanz.
- * license has returned to an MIT-based license (with the compatible GDCM also noted for the private dictionary component).
- * contributed files with example code for viewing using wxPython or Tkinter (and PIL) -- in dicom.contrib folder. Thanks to Dave Witten, Daniel Nanz and Adit Panchal for these contributions.
- * updates to pydicom's DICOM data dictionary contributed by Adit Panchal: CP805/916; Supp 43 and 117 (and UID dict), Supp 119 and 122
-
-== Other changes and bug fixes ==
- * Tag is now a factory function; the class is called !BaseTag. This was part of the file reading speed-up process -- a new class !TupleTag was also created, for faster file reading
- * passing a file object to read_file() now works correctly, and also the file closing works as it should (caller needs to close any files passed in) (issue 73)
- * Fix for issue 72 : dataset.get() fails when passed type other than string or Tag. Patch contributed by !NikitaTheSpider
- * Fix for issue 58 : error opening file with unicode. Fix contributed by Pierre Raybaut
- * Fix for issue 42 : catch !AttributeError in property and give proper error message
- * Fix for issue 55 : UI type changed with string operations
- * Tag fixes and enhancements : can create tags with hex string (group, elem). Allow lists as well as tuples (issue 47). Fix arg2=0 bug (issue 64).
-
-
-= Release notes for pydicom 0.9.3 =
-
-== Major changes ==
- * changed to MIT-style license
- * option to defer reading of large data element values using read_file()'s new defer_size argument (r102, r103)
- * dictionary of private tags added -- descriptive text shown when available (issue36, r97, r110)
- * more conversion to PEP-8 style. Should now use read_file(), save_as(), pixel_array rather than !ReadFile(), !SaveAs(), !PixelArray. Old names kept for now as aliases.
-
-== Other Enhancements ==
- * added DicomFileLike class to simplify and generalize access. Any object that has read, write, seek, tell, and close can now be used. (r105)
- * added dataset.iterall() function to iterate through all items (including inside sequences) (r105)
- * added dataset.formatted_lines() generator to allow custom formatting (r91, r113)
- * made reading tolerant of truncated files -- gives a warning, but returns dataset read to that point (r95)
-
-== Bug Fixes ==
- * fixed issue38, name collision for 'Other Patient Ids' as both data element and sequence name in DICOM standard (r95, r96)
- * fixed issue40, blank VRs in some DICOM dictionary entries caused NotImplementError on reading (r100)
- * fixed issue41, reading VRs of 'US or SS' and similar split on backslash character (r104)
- * fixed bug where TransferSyntaxUID not present when reading file without DICOM header (r109)
- * fixed print recursion bug when printing a UID (r111)
-
-== Other ==
- * many of the example files updated
- * updated anonymize example file to also deal with 'OtherPatientIDs' and 'PatientsBirthDate' (r98)
-
-
-= Release notes for pydicom 0.9.2 =
-
-== Major changes ==
- * Renamed Attribute class and related modules to !DataElement. Old code will continue to work until pydicom 1.0, but with a !DeprecationWarning (issue22, r72, r73)
- * Added support for character sets through Specific Character Set (0008,0005), using python unicode. Thus foreign languages can display names in Greek, Japanese, Chinese etc characters in environments which support unicode (demonstrated in dicomtree.py example using Tkinter GUI) (r64, r65)
-
-== Other Enhancements ==
- * Added support for auto-completion of dataset elements in ipython; also all environments using python 2.6 (r69, r70)
- * Added __iter__() to Dataset so returns data elements in DICOM order with "for data_elem in dataset:" (r68)
- * Added dicomtree.py example program showing a DICOM file in a GUI window (Tkinter/Tix).
- * Added !PersonName class to parse components of names more easily (r55)
- * Added UID class to handle UID values. Name rather than UID number shown, UID_dictionary used (r51).
- * Code tested under python 2.6
- * Added !DataElement.name property; synonym for !DataElement.description() function
-
-== Bug Fixes ==
- * Fixed issue27, sequence with a single empty item read incorrectly
- * Fixed bug that read_OW did not handle !UndefinedLength (r50)
- * Fixed bugs in example files anonymize.py, !DicomInfo.py, and dicomtree.py (r51)
- * Fixed issue33, VR=UN being split on backslash (r70)
- * Fixed issue18, util directory not installed (r45)
-
-== Other ==
- * Added example file myprint.py -- shows how to custom format DICOM file information (r67)
- * Reorganized test files and added various new tests
- * added preliminary work on encapsulated data (r50)
- * added some simple files to view or work with pixel data (r46)
- * Dataset.!PixelDataArray() Numpy array changed to property Dataset.!PixelArray
- * changed to setuptools for packaging rather than distutils
diff --git a/pydicom/filewriter.py b/pydicom/filewriter.py
index 4181cce16..efb596845 100644
--- a/pydicom/filewriter.py
+++ b/pydicom/filewriter.py
@@ -415,6 +415,16 @@ def write_data_element(fp, data_element, encoding=default_encoding):
if (hasattr(data_element, "is_undefined_length")
and data_element.is_undefined_length):
is_undefined_length = True
+ # valid pixel data with undefined length shall contain encapsulated
+ # data, e.g. sequence items - raise ValueError otherwise (see #238)
+ if data_element.tag == 0x7fe00010: # pixel data
+ val = data_element.value
+ if (fp.is_little_endian and not
+ val.startswith(b'\xfe\xff\x00\xe0') or
+ not fp.is_little_endian and
+ not val.startswith(b'\xff\xfe\xe0\x00')):
+ raise ValueError('Pixel Data with undefined length must '
+ 'start with an item tag')
location = fp.tell()
fp.seek(length_location)
if not fp.is_implicit_VR and VR not in extra_length_VRs:
| Add what's new (release note) inside the sphinx doc
I think that we should maintain the release note or a what's new to keep track of merging. | pydicom/pydicom | diff --git a/pydicom/tests/test_filewriter.py b/pydicom/tests/test_filewriter.py
index 70567f134..4d7814ed0 100644
--- a/pydicom/tests/test_filewriter.py
+++ b/pydicom/tests/test_filewriter.py
@@ -41,7 +41,6 @@ except AttributeError:
except ImportError:
print("unittest2 is required for testing in python2.6")
-
rtplan_name = get_testdata_files("rtplan.dcm")[0]
rtdose_name = get_testdata_files("rtdose.dcm")[0]
ct_name = get_testdata_files("CT_small.dcm")[0]
@@ -263,8 +262,8 @@ class WriteDataElementTests(unittest.TestCase):
# Was issue 74
data_elem = DataElement(0x00280009, "AT", [])
expected = hex2bytes((
- " 28 00 09 00" # (0028,0009) Frame Increment Pointer
- " 00 00 00 00" # length 0
+ " 28 00 09 00" # (0028,0009) Frame Increment Pointer
+ " 00 00 00 00" # length 0
))
write_data_element(self.f1, data_elem)
got = self.f1.getvalue()
@@ -1731,6 +1730,74 @@ class TestWriteFileMetaInfoNonStandard(unittest.TestCase):
self.assertEqual(meta, ref_meta)
+class TestWriteUndefinedLengthPixelData(unittest.TestCase):
+ """Test write_data_element() for pixel data with undefined length."""
+
+ def setUp(self):
+ self.fp = DicomBytesIO()
+
+ def test_little_endian_correct_data(self):
+ """Pixel data starting with an item tag is written."""
+ self.fp.is_little_endian = True
+ self.fp.is_implicit_VR = False
+ pixel_data = DataElement(0x7fe00010, 'OB',
+ b'\xfe\xff\x00\xe0'
+ b'\x00\x01\x02\x03',
+ is_undefined_length=True)
+ write_data_element(self.fp, pixel_data)
+
+ expected = (b'\xe0\x7f\x10\x00' # tag
+ b'OB\x00\x00' # VR
+ b'\xff\xff\xff\xff' # length
+ b'\xfe\xff\x00\xe0\x00\x01\x02\x03' # contents
+ b'\xfe\xff\xdd\xe0\x00\x00\x00\x00') # SQ delimiter
+ self.fp.seek(0)
+ assert self.fp.read() == expected
+
+ def test_big_endian_correct_data(self):
+ """Pixel data starting with an item tag is written."""
+ self.fp.is_little_endian = False
+ self.fp.is_implicit_VR = False
+ pixel_data = DataElement(0x7fe00010, 'OB',
+ b'\xff\xfe\xe0\x00'
+ b'\x00\x01\x02\x03',
+ is_undefined_length=True)
+ write_data_element(self.fp, pixel_data)
+ expected = (b'\x7f\xe0\x00\x10' # tag
+ b'OB\x00\x00' # VR
+ b'\xff\xff\xff\xff' # length
+ b'\xff\xfe\xe0\x00\x00\x01\x02\x03' # contents
+ b'\xff\xfe\xe0\xdd\x00\x00\x00\x00') # SQ delimiter
+ self.fp.seek(0)
+ assert self.fp.read() == expected
+
+ def test_little_endian_incorrect_data(self):
+ """Writing pixel data not starting with an item tag raises."""
+ self.fp.is_little_endian = True
+ self.fp.is_implicit_VR = False
+ pixel_data = DataElement(0x7fe00010, 'OB',
+ b'\xff\xff\x00\xe0'
+ b'\x00\x01\x02\x03'
+ b'\xfe\xff\xdd\xe0',
+ is_undefined_length=True)
+ with pytest.raises(ValueError, match='Pixel Data .* must '
+ 'start with an item tag'):
+ write_data_element(self.fp, pixel_data)
+
+ def test_big_endian_incorrect_data(self):
+ """Writing pixel data not starting with an item tag raises."""
+ self.fp.is_little_endian = False
+ self.fp.is_implicit_VR = False
+ pixel_data = DataElement(0x7fe00010, 'OB',
+ b'\x00\x00\x00\x00'
+ b'\x00\x01\x02\x03'
+ b'\xff\xfe\xe0\xdd',
+ is_undefined_length=True)
+ with pytest.raises(ValueError, match='Pixel Data .+ must '
+ 'start with an item tag'):
+ write_data_element(self.fp, pixel_data)
+
+
if __name__ == "__main__":
# This is called if run alone, but not if loaded through run_tests.py
# If not run from the directory where the sample images are,
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_removed_files",
"has_many_modified_files",
"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": 2
} | 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": [
"pytest",
"pyflakes",
"pep8",
"autopep8"
],
"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
autopep8==2.0.4
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
pep8==1.7.1
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pycodestyle==2.10.0
-e git+https://github.com/pydicom/pydicom.git@1bd33e3ceec19d45844676bdd25367fda4c5319b#egg=pydicom
pyflakes==3.0.1
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
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: pydicom
channels:
- defaults
- https://repo.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:
- autopep8==2.0.4
- pep8==1.7.1
- pycodestyle==2.10.0
- pyflakes==3.0.1
- tomli==1.2.3
prefix: /opt/conda/envs/pydicom
| [
"pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_incorrect_data",
"pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_incorrect_data"
]
| []
| [
"pydicom/tests/test_filewriter.py::WriteFileTests::testCT",
"pydicom/tests/test_filewriter.py::WriteFileTests::testJPEG2000",
"pydicom/tests/test_filewriter.py::WriteFileTests::testListItemWriteBack",
"pydicom/tests/test_filewriter.py::WriteFileTests::testMR",
"pydicom/tests/test_filewriter.py::WriteFileTests::testMultiPN",
"pydicom/tests/test_filewriter.py::WriteFileTests::testRTDose",
"pydicom/tests/test_filewriter.py::WriteFileTests::testRTPlan",
"pydicom/tests/test_filewriter.py::WriteFileTests::testUnicode",
"pydicom/tests/test_filewriter.py::WriteFileTests::test_write_double_filemeta",
"pydicom/tests/test_filewriter.py::WriteFileTests::test_write_no_ts",
"pydicom/tests/test_filewriter.py::WriteFileTests::testwrite_short_uid",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_empty_AT",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_DA",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_DT",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OD_explicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OD_implicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OL_explicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_OL_implicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_TM",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UC_explicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UC_implicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UR_explicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_UR_implicit_little",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_multi_DA",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_multi_DT",
"pydicom/tests/test_filewriter.py::WriteDataElementTests::test_write_multi_TM",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_lut_descriptor",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_overlay",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_data",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_one",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_pixel_representation_vm_three",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_sequence",
"pydicom/tests/test_filewriter.py::TestCorrectAmbiguousVR::test_waveform_bits_allocated",
"pydicom/tests/test_filewriter.py::WriteAmbiguousVRTests::test_write_explicit_vr_big_endian",
"pydicom/tests/test_filewriter.py::WriteAmbiguousVRTests::test_write_explicit_vr_little_endian",
"pydicom/tests/test_filewriter.py::WriteAmbiguousVRTests::test_write_explicit_vr_raises",
"pydicom/tests/test_filewriter.py::ScratchWriteTests::testImpl_LE_deflen_write",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_default",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_preamble_custom",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_no_preamble",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_none_preamble",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_bad_preamble",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_prefix_none",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_ds_changed",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_added",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_not_added",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_transfer_syntax_raises",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_media_storage_sop_class_uid_added",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_write_no_file_meta",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_raise_no_file_meta",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_add_file_meta",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_standard",
"pydicom/tests/test_filewriter.py::TestWriteToStandard::test_commandset_no_written",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_bad_elements",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_missing_elements",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_group_length_updated",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_version",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_version_name_length",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_implementation_class_uid_length",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoToStandard::test_filelike_position",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_commandset_filemeta_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_ds_unchanged",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_file_meta_unchanged",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_filemeta_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_no_preamble",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_commandset_filemeta_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_custom",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_default",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_preamble_filemeta_dataset",
"pydicom/tests/test_filewriter.py::TestWriteNonStandard::test_read_write_identical",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_bad_elements",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_filelike_position",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_group_length_updated",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_meta_unchanged",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_missing_elements",
"pydicom/tests/test_filewriter.py::TestWriteFileMetaInfoNonStandard::test_transfer_syntax_not_added",
"pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_big_endian_correct_data",
"pydicom/tests/test_filewriter.py::TestWriteUndefinedLengthPixelData::test_little_endian_correct_data"
]
| []
| MIT License | 1,612 | [
"pydicom/filewriter.py",
"doc/index.rst",
"doc/release-notes.txt",
"doc/release-notes.rst"
]
| [
"pydicom/filewriter.py",
"doc/index.rst",
"doc/release-notes.txt",
"doc/release-notes.rst"
]
|
mjs__imapclient-279 | 11700af6595fc3d92eadb54228fe3ddaa3c4b693 | 2017-08-23 13:20:00 | 2abdac690fa653fa2d0d55b7617be24101597698 | diff --git a/doc/src/advanced.rst b/doc/src/advanced.rst
index a151e38..7356328 100644
--- a/doc/src/advanced.rst
+++ b/doc/src/advanced.rst
@@ -3,6 +3,33 @@ Advanced Usage
This document covers some more advanced features and tips for handling
specific usages.
+Cleaning Up Connections
+~~~~~~~~~~~~~~~~~~~~~~~
+
+To communicate with the server, IMAPClient establishes a TCP connection. It is
+important for long-lived processes to always close connections at some
+point to avoid leaking memory and file descriptors. This is usually done with
+the ``logout`` method::
+
+ import imapclient
+
+ c = imapclient.IMAPClient(host="imap.foo.org")
+ c.login("[email protected]", "passwd")
+ c.select_folder("INBOX")
+ c.logout()
+
+However if an error is raised when selecting the folder, the connection may be
+left open.
+
+IMAPClient may be used as a context manager that automatically closes
+connections when they are not needed anymore::
+
+ import imapclient
+
+ with imapclient.IMAPClient(host="imap.foo.org") as c:
+ c.login("[email protected]", "passwd")
+ c.select_folder("INBOX")
+
Watching a mailbox asynchronously using idle
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TODO
diff --git a/doc/src/index.rst b/doc/src/index.rst
index af62a24..3f08ce7 100644
--- a/doc/src/index.rst
+++ b/doc/src/index.rst
@@ -66,6 +66,8 @@ messages in the INBOX folder.
ID #44: "See that fun article about lobsters in Pacific ocean!" received 2017-06-09 09:49:47
ID #46: "Planning for our next vacations" received 2017-05-12 10:29:30
+ >>> server.logout()
+ b'Logging out'
User Guide
----------
diff --git a/doc/src/releases.rst b/doc/src/releases.rst
index 3e6c672..8199b24 100644
--- a/doc/src/releases.rst
+++ b/doc/src/releases.rst
@@ -10,6 +10,8 @@ Changed
- XXX Use built-in TLS when sensible.
- Logs are now handled by the Python logging module. `debug` and `log_file`
are not used anymore.
+- A context manager is introduced to automatically close connections to remote
+ servers.
Other
-----
diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index 3792a1f..cff7b1b 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -117,6 +117,10 @@ class IMAPClient(object):
system time). This attribute can be changed between ``fetch()``
calls if required.
+ Can be used as a context manager to automatically close opened connections:
+ >>> with IMAPClient(host="imap.foo.org") as client:
+ ... client.login("[email protected]", "passwd")
+
"""
Error = imaplib.IMAP4.error
@@ -150,8 +154,11 @@ class IMAPClient(object):
self._timeout = timeout
self._starttls_done = False
self._cached_capabilities = None
+ self._idle_tag = None
self._imap = self._create_IMAP4()
+ self._set_timeout()
+
logger.debug("Connected to host %s over %s", self.host,
"SSL/TLS" if ssl else "plain text")
@@ -162,9 +169,22 @@ class IMAPClient(object):
self._imap.debug = 5
self._imap._mesg = imaplib_logger.debug
- self._idle_tag = None
+ def __enter__(self):
+ return self
- self._set_timeout()
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ """Logout and closes the connection when exiting the context manager.
+
+ All exceptions during logout and connection shutdown are caught because
+ an error here usually means the connection was already closed.
+ """
+ try:
+ self.logout()
+ except Exception:
+ try:
+ self.shutdown()
+ except Exception as e:
+ logger.info("Could not close the connection cleanly: %s", e)
def _create_IMAP4(self):
if self.stream:
| Introduce a context manager for IMAPClient instances
A context manager would prevent accidentally leaking sockets when the user forgets to call `logout()`. | mjs/imapclient | diff --git a/tests/test_imapclient.py b/tests/test_imapclient.py
index c03fce9..9597519 100644
--- a/tests/test_imapclient.py
+++ b/tests/test_imapclient.py
@@ -599,3 +599,32 @@ class TestShutdown(IMAPClientTest):
def test_shutdown(self):
self.client.shutdown()
self.client._imap.shutdown.assert_called_once_with()
+
+
+class TestContextManager(IMAPClientTest):
+
+ def test_context_manager(self):
+ with self.client as client:
+ self.assertIsInstance(client, IMAPClient)
+
+ self.client._imap.logout.assert_called_once_with()
+
+ @patch('imapclient.imapclient.logger')
+ def test_context_manager_fail_closing(self, mock_logger):
+ self.client._imap.logout.side_effect = RuntimeError("Error logout")
+ self.client._imap.shutdown.side_effect = RuntimeError("Error shutdown")
+
+ with self.client as client:
+ self.assertIsInstance(client, IMAPClient)
+
+ self.client._imap.logout.assert_called_once_with()
+ self.client._imap.shutdown.assert_called_once_with()
+ mock_logger.info.assert_called_once_with(
+ 'Could not close the connection cleanly: %s',
+ self.client._imap.shutdown.side_effect
+ )
+
+ def test_exception_inside_context_manager(self):
+ with self.assertRaises(ValueError):
+ with self.client as _:
+ raise ValueError("Error raised inside the context manager")
| {
"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": 2
},
"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": [
"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
-e git+https://github.com/mjs/imapclient.git@11700af6595fc3d92eadb54228fe3ddaa3c4b693#egg=IMAPClient
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
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: imapclient
channels:
- defaults
- https://repo.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:
- six==1.17.0
prefix: /opt/conda/envs/imapclient
| [
"tests/test_imapclient.py::TestContextManager::test_context_manager",
"tests/test_imapclient.py::TestContextManager::test_context_manager_fail_closing",
"tests/test_imapclient.py::TestContextManager::test_exception_inside_context_manager"
]
| [
"tests/test_imapclient.py::TestDebugLogging::test_IMAP_is_patched",
"tests/test_imapclient.py::TestDebugLogging::test_redacted_password"
]
| [
"tests/test_imapclient.py::TestListFolders::test_blanks",
"tests/test_imapclient.py::TestListFolders::test_empty_response",
"tests/test_imapclient.py::TestListFolders::test_folder_encode_off",
"tests/test_imapclient.py::TestListFolders::test_funky_characters",
"tests/test_imapclient.py::TestListFolders::test_list_folders",
"tests/test_imapclient.py::TestListFolders::test_list_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_mixed",
"tests/test_imapclient.py::TestListFolders::test_quoted_specials",
"tests/test_imapclient.py::TestListFolders::test_simple",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name_parsed_as_long",
"tests/test_imapclient.py::TestListFolders::test_utf7_decoding",
"tests/test_imapclient.py::TestListFolders::test_without_quotes",
"tests/test_imapclient.py::TestSelectFolder::test_normal",
"tests/test_imapclient.py::TestSelectFolder::test_unselect",
"tests/test_imapclient.py::TestAppend::test_with_msg_time",
"tests/test_imapclient.py::TestAppend::test_without_msg_time",
"tests/test_imapclient.py::TestAclMethods::test_getacl",
"tests/test_imapclient.py::TestAclMethods::test_setacl",
"tests/test_imapclient.py::TestIdleAndNoop::test_consume_until_tagged_response",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_blocking",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_timeout",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_with_data",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_done",
"tests/test_imapclient.py::TestIdleAndNoop::test_noop",
"tests/test_imapclient.py::TestTimeNormalisation::test_default",
"tests/test_imapclient.py::TestTimeNormalisation::test_pass_through",
"tests/test_imapclient.py::TestNamespace::test_complex",
"tests/test_imapclient.py::TestNamespace::test_folder_decoding",
"tests/test_imapclient.py::TestNamespace::test_other_only",
"tests/test_imapclient.py::TestNamespace::test_simple",
"tests/test_imapclient.py::TestNamespace::test_without_folder_decoding",
"tests/test_imapclient.py::TestCapabilities::test_caching",
"tests/test_imapclient.py::TestCapabilities::test_has_capability",
"tests/test_imapclient.py::TestCapabilities::test_post_auth_request",
"tests/test_imapclient.py::TestCapabilities::test_preauth",
"tests/test_imapclient.py::TestCapabilities::test_server_returned_capability_after_auth",
"tests/test_imapclient.py::TestCapabilities::test_with_starttls",
"tests/test_imapclient.py::TestId::test_id",
"tests/test_imapclient.py::TestId::test_invalid_parameters",
"tests/test_imapclient.py::TestId::test_no_support",
"tests/test_imapclient.py::TestRawCommand::test_complex",
"tests/test_imapclient.py::TestRawCommand::test_embedded_literal",
"tests/test_imapclient.py::TestRawCommand::test_failed_continuation_wait",
"tests/test_imapclient.py::TestRawCommand::test_invalid_input_type",
"tests/test_imapclient.py::TestRawCommand::test_literal_at_end",
"tests/test_imapclient.py::TestRawCommand::test_multiple_literals",
"tests/test_imapclient.py::TestRawCommand::test_not_uid",
"tests/test_imapclient.py::TestRawCommand::test_plain",
"tests/test_imapclient.py::TestShutdown::test_shutdown"
]
| []
| BSD License | 1,613 | [
"doc/src/releases.rst",
"imapclient/imapclient.py",
"doc/src/advanced.rst",
"doc/src/index.rst"
]
| [
"doc/src/releases.rst",
"imapclient/imapclient.py",
"doc/src/advanced.rst",
"doc/src/index.rst"
]
|
|
Azure__msrest-for-python-45 | 07cec915d60e29193935dfca17d5e8a7afd0a3d4 | 2017-08-23 16:10:17 | 24deba7a7a9e335314058ec2d0b39a710f61be60 | diff --git a/msrest/serialization.py b/msrest/serialization.py
index 063f2e6..a3d50cd 100644
--- a/msrest/serialization.py
+++ b/msrest/serialization.py
@@ -1200,6 +1200,12 @@ class Deserializer(object):
:param str data: response string to be deserialized.
:rtype: str or unicode
"""
+ # We might be here because we have an enum modeled as string,
+ # and we try to deserialize a partial dict with enum inside
+ if isinstance(data, Enum):
+ return data
+
+ # Consider this is real string
try:
if isinstance(data, unicode):
return data
| v0.4.12 breaks mixed dict with enum if model-as-string=true
This breaks:
``` python
async_security_rule = self.network_client.security_rules.create_or_update(
self.group_name,
security_group_name,
new_security_rule_name,
{
'access':azure.mgmt.network.models.SecurityRuleAccess.allow,
'description':'New Test security rule',
'destination_address_prefix':'*',
'destination_port_range':'123-3500',
'direction':azure.mgmt.network.models.SecurityRuleDirection.outbound,
'priority':400,
'protocol':azure.mgmt.network.models.SecurityRuleProtocol.tcp,
'source_address_prefix':'*',
'source_port_range':'655',
}
)
``` | Azure/msrest-for-python | diff --git a/tests/test_serialization.py b/tests/test_serialization.py
index 787a086..10fb82f 100644
--- a/tests/test_serialization.py
+++ b/tests/test_serialization.py
@@ -353,10 +353,10 @@ class TestRuntimeSerialized(unittest.TestCase):
class TestEnum(Enum):
val = "Value"
- t = test_obj
+ t = test_obj()
t.abc = TestEnum.val
- serialized = self.s._serialize(test_obj)
+ serialized = self.s._serialize(t)
expected = {
"ABC": "Value"
}
@@ -374,6 +374,31 @@ class TestRuntimeSerialized(unittest.TestCase):
with self.assertRaises(SerializationError):
serializer._serialize(t)
+ serializer = Serializer({
+ 'TestEnumObj': test_obj,
+ 'TestEnum': TestEnum
+ })
+ serialized = serializer.body({
+ 'abc': TestEnum.val
+ }, 'TestEnumObj')
+ expected = {
+ 'ABC': 'Value'
+ }
+ self.assertEqual(expected, serialized)
+
+ # model-as-string=True
+ test_obj._attribute_map = {
+ "abc":{"key":"ABC", "type":"str"}
+ }
+ serialized = serializer.body({
+ 'abc': TestEnum.val
+ }, 'TestEnumObj')
+ expected = {
+ 'ABC': 'Value'
+ }
+ self.assertEqual(expected, serialized)
+
+
def test_attr_none(self):
"""
Test serializing an object with None attributes.
| {
"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.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt",
"dev_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
exceptiongroup==1.2.2
httpretty==1.1.4
idna==3.10
iniconfig==2.1.0
isodate==0.7.2
-e git+https://github.com/Azure/msrest-for-python.git@07cec915d60e29193935dfca17d5e8a7afd0a3d4#egg=msrest
oauthlib==3.2.2
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cov==6.0.0
requests==2.32.3
requests-oauthlib==2.0.0
tomli==2.2.1
urllib3==2.3.0
| name: msrest-for-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
- 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
- exceptiongroup==1.2.2
- httpretty==1.1.4
- idna==3.10
- iniconfig==2.1.0
- isodate==0.7.2
- oauthlib==3.2.2
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cov==6.0.0
- requests==2.32.3
- requests-oauthlib==2.0.0
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/msrest-for-python
| [
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_enum"
]
| []
| [
"tests/test_serialization.py::TestModelDeserialization::test_response",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_bool",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_dict_simple",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_duration",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_int",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_list_complex",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_list_simple",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_none",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_sequence",
"tests/test_serialization.py::TestRuntimeSerialized::test_attr_str",
"tests/test_serialization.py::TestRuntimeSerialized::test_empty_list",
"tests/test_serialization.py::TestRuntimeSerialized::test_key_type",
"tests/test_serialization.py::TestRuntimeSerialized::test_model_validate",
"tests/test_serialization.py::TestRuntimeSerialized::test_obj_serialize_none",
"tests/test_serialization.py::TestRuntimeSerialized::test_obj_with_malformed_map",
"tests/test_serialization.py::TestRuntimeSerialized::test_obj_with_mismatched_map",
"tests/test_serialization.py::TestRuntimeSerialized::test_obj_without_attr_map",
"tests/test_serialization.py::TestRuntimeSerialized::test_polymorphic_serialization",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_datetime",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_direct_model",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_empty_iter",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_json_obj",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_object",
"tests/test_serialization.py::TestRuntimeSerialized::test_serialize_primitive_types",
"tests/test_serialization.py::TestRuntimeSerialized::test_validate",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_bool",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_int",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_list_complex",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_list_in_list",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_list_simple",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_none",
"tests/test_serialization.py::TestRuntimeDeserialized::test_attr_str",
"tests/test_serialization.py::TestRuntimeDeserialized::test_basic_deserialization",
"tests/test_serialization.py::TestRuntimeDeserialized::test_cls_method_deserialization",
"tests/test_serialization.py::TestRuntimeDeserialized::test_deserialize_datetime",
"tests/test_serialization.py::TestRuntimeDeserialized::test_deserialize_object",
"tests/test_serialization.py::TestRuntimeDeserialized::test_deserialize_storage",
"tests/test_serialization.py::TestRuntimeDeserialized::test_non_obj_deserialization",
"tests/test_serialization.py::TestRuntimeDeserialized::test_obj_with_malformed_map",
"tests/test_serialization.py::TestRuntimeDeserialized::test_obj_with_no_attr",
"tests/test_serialization.py::TestRuntimeDeserialized::test_personalize_deserialization",
"tests/test_serialization.py::TestRuntimeDeserialized::test_polymorphic_deserialization",
"tests/test_serialization.py::TestRuntimeDeserialized::test_polymorphic_deserialization_with_escape",
"tests/test_serialization.py::TestRuntimeDeserialized::test_robust_deserialization",
"tests/test_serialization.py::TestModelInstanceEquality::test_model_instance_equality"
]
| []
| MIT License | 1,614 | [
"msrest/serialization.py"
]
| [
"msrest/serialization.py"
]
|
|
pre-commit__pre-commit-592 | 7139a47c1ca968a2699e467279677fa77ad68aae | 2017-08-23 17:24:54 | 7139a47c1ca968a2699e467279677fa77ad68aae | diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py
index c18f2aa..55d2b12 100644
--- a/pre_commit/commands/run.py
+++ b/pre_commit/commands/run.py
@@ -217,7 +217,7 @@ def _has_unstaged_config(runner):
def run(runner, args, environ=os.environ):
- no_stash = args.no_stash or args.all_files or bool(args.files)
+ no_stash = args.all_files or bool(args.files)
# Check if we have unresolved merge conflict files and fail fast.
if _has_unmerged_paths(runner):
@@ -227,20 +227,11 @@ def run(runner, args, environ=os.environ):
logger.error('Specify both --origin and --source.')
return 1
if _has_unstaged_config(runner) and not no_stash:
- if args.allow_unstaged_config:
- logger.warn(
- 'You have an unstaged config file and have specified the '
- '--allow-unstaged-config option.\n'
- 'Note that your config will be stashed before the config is '
- 'parsed unless --no-stash is specified.',
- )
- else:
- logger.error(
- 'Your .pre-commit-config.yaml is unstaged.\n'
- '`git add .pre-commit-config.yaml` to fix this.\n'
- 'Run pre-commit with --allow-unstaged-config to silence this.',
- )
- return 1
+ logger.error(
+ 'Your .pre-commit-config.yaml is unstaged.\n'
+ '`git add .pre-commit-config.yaml` to fix this.\n',
+ )
+ return 1
# Expose origin / source as environment variables for hooks to consume
if args.origin and args.source:
diff --git a/pre_commit/main.py b/pre_commit/main.py
index 3a2fee1..0b00a86 100644
--- a/pre_commit/main.py
+++ b/pre_commit/main.py
@@ -135,10 +135,6 @@ def main(argv=None):
_add_color_option(run_parser)
_add_config_option(run_parser)
run_parser.add_argument('hook', nargs='?', help='A single hook-id to run')
- run_parser.add_argument(
- '--no-stash', default=False, action='store_true',
- help='Use this option to prevent auto stashing of unstaged files.',
- )
run_parser.add_argument(
'--verbose', '-v', action='store_true', default=False,
)
@@ -154,13 +150,6 @@ def main(argv=None):
'--commit-msg-filename',
help='Filename to check when running during `commit-msg`',
)
- run_parser.add_argument(
- '--allow-unstaged-config', default=False, action='store_true',
- help=(
- 'Allow an unstaged config to be present. Note that this will '
- 'be stashed before parsing unless --no-stash is specified.'
- ),
- )
run_parser.add_argument(
'--hook-stage', choices=('commit', 'push', 'commit-msg'),
default='commit',
@@ -173,7 +162,7 @@ def main(argv=None):
run_mutex_group = run_parser.add_mutually_exclusive_group(required=False)
run_mutex_group.add_argument(
'--all-files', '-a', action='store_true', default=False,
- help='Run on all the files in the repo. Implies --no-stash.',
+ help='Run on all the files in the repo.',
)
run_mutex_group.add_argument(
'--files', nargs='*', default=[],
| Deprecate and remove some (useless?) options
I find the following don't really have any good use cases (and don't come up in normal day-to-day) and are undocumented beyond `--help`. **I'm proposing removing these options**:
## `pre-commit run --no-stash`
This disables the auto-stashing of files when running -- though this is already the case for `pre-commit run --all-files` and `pre-commit run --files ...`.
The behaviour of `--no-stash` (without using `--no-stash`) can be achieved via `git diff --name-only | xargs pre-commit run --files`
It was added [along with the avoiding behaviour](https://github.com/pre-commit/pre-commit/pull/80) in the same pull request. I want to say this was my first idea for "fixing" the [original problem](https://github.com/pre-commit/pre-commit/issues/68) and then I forgot to undo it.
## `pre-commit run --allow-unstaged-config`
This (unfortunately) collides with `pre-commit run --all` (prefix match of `pre-commit run --all-files`) so I've wanted to get rid of it anyway.
This allows one to run with an unstaged configuration, which then (in most cases) gets the changes swiped out from under you and causes confusing situations where the hooks that are run aren't what was on disk at the time of running. The warning that's printed when doing this also explains this.
This was [originally my idea](https://github.com/pre-commit/pre-commit/issues/157#issuecomment-99080756) but now I think we can just do without the option at all -- requiring the pre-commit configuration to be staged when running pre-commit. | pre-commit/pre-commit | diff --git a/tests/commands/run_test.py b/tests/commands/run_test.py
index c360fde..924d097 100644
--- a/tests/commands/run_test.py
+++ b/tests/commands/run_test.py
@@ -54,10 +54,8 @@ def _get_opts(
color=False,
verbose=False,
hook=None,
- no_stash=False,
origin='',
source='',
- allow_unstaged_config=False,
hook_stage='commit',
show_diff_on_failure=False,
commit_msg_filename='',
@@ -70,10 +68,8 @@ def _get_opts(
color=color,
verbose=verbose,
hook=hook,
- no_stash=no_stash,
origin=origin,
source=source,
- allow_unstaged_config=allow_unstaged_config,
hook_stage=hook_stage,
show_diff_on_failure=show_diff_on_failure,
commit_msg_filename=commit_msg_filename,
@@ -332,38 +328,6 @@ def test_origin_source_error_msg(
assert warning_msg not in printed
[email protected](
- ('no_stash', 'all_files', 'expect_stash'),
- (
- (True, True, False),
- (True, False, False),
- (False, True, False),
- (False, False, True),
- ),
-)
-def test_no_stash(
- cap_out,
- repo_with_passing_hook,
- no_stash,
- all_files,
- expect_stash,
- mock_out_store_directory,
-):
- stage_a_file()
- # Make unstaged changes
- with open('foo.py', 'w') as foo_file:
- foo_file.write('import os\n')
-
- args = _get_opts(no_stash=no_stash, all_files=all_files)
- ret, printed = _do_run(cap_out, repo_with_passing_hook, args)
- assert ret == 0
- warning_msg = b'[WARNING] Unstaged files detected.'
- if expect_stash:
- assert warning_msg in printed
- else:
- assert warning_msg not in printed
-
-
@pytest.mark.parametrize(('output', 'expected'), (('some', True), ('', False)))
def test_has_unmerged_paths(output, expected):
mock_runner = mock.Mock()
@@ -715,37 +679,19 @@ def modified_config_repo(repo_with_passing_hook):
yield repo_with_passing_hook
-def test_allow_unstaged_config_option(
+def test_error_with_unstaged_config(
cap_out, modified_config_repo, mock_out_store_directory,
):
- args = _get_opts(allow_unstaged_config=True)
- ret, printed = _do_run(cap_out, modified_config_repo, args)
- expected = (
- b'You have an unstaged config file and have specified the '
- b'--allow-unstaged-config option.'
- )
- assert expected in printed
- assert ret == 0
-
-
-def test_no_allow_unstaged_config_option(
- cap_out, modified_config_repo, mock_out_store_directory,
-):
- args = _get_opts(allow_unstaged_config=False)
+ args = _get_opts()
ret, printed = _do_run(cap_out, modified_config_repo, args)
assert b'Your .pre-commit-config.yaml is unstaged.' in printed
assert ret == 1
@pytest.mark.parametrize(
- 'opts',
- (
- {'allow_unstaged_config': False, 'no_stash': True},
- {'all_files': True},
- {'files': [C.CONFIG_FILE]},
- ),
+ 'opts', ({'all_files': True}, {'files': [C.CONFIG_FILE]}),
)
-def test_unstaged_message_suppressed(
+def test_no_unstaged_error_with_all_files_or_files(
cap_out, modified_config_repo, mock_out_store_directory, opts,
):
args = _get_opts(**opts)
diff --git a/tests/git_test.py b/tests/git_test.py
index 4ffccee..0500a42 100644
--- a/tests/git_test.py
+++ b/tests/git_test.py
@@ -137,8 +137,7 @@ def test_get_conflicted_files_in_submodule(in_conflicting_submodule):
def test_get_conflicted_files_unstaged_files(in_merge_conflict):
- # If they for whatever reason did pre-commit run --no-stash during a
- # conflict
+ """This case no longer occurs, but it is a useful test nonetheless"""
resolve_conflict()
# Make unstaged file.
| {
"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": 2
} | 0.16 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aspy.yaml==1.3.0
cached-property==2.0.1
coverage==7.8.0
distlib==0.3.9
exceptiongroup==1.2.2
filelock==3.18.0
flake8==7.2.0
identify==2.6.9
iniconfig==2.1.0
mccabe==0.7.0
mock==5.2.0
nodeenv==1.9.1
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
-e git+https://github.com/pre-commit/pre-commit.git@7139a47c1ca968a2699e467279677fa77ad68aae#egg=pre_commit
pycodestyle==2.13.0
pyflakes==3.3.1
pytest==8.3.5
pytest-env==1.1.5
PyYAML==6.0.2
six==1.17.0
tomli==2.2.1
virtualenv==20.29.3
| name: pre-commit
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- 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:
- aspy-yaml==1.3.0
- cached-property==2.0.1
- coverage==7.8.0
- distlib==0.3.9
- exceptiongroup==1.2.2
- filelock==3.18.0
- flake8==7.2.0
- identify==2.6.9
- iniconfig==2.1.0
- mccabe==0.7.0
- mock==5.2.0
- nodeenv==1.9.1
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pytest==8.3.5
- pytest-env==1.1.5
- pyyaml==6.0.2
- six==1.17.0
- tomli==2.2.1
- virtualenv==20.29.3
prefix: /opt/conda/envs/pre-commit
| [
"tests/commands/run_test.py::test_run_all_hooks_failing",
"tests/commands/run_test.py::test_hook_that_modifies_but_returns_zero",
"tests/commands/run_test.py::test_types_hook_repository",
"tests/commands/run_test.py::test_exclude_types_hook_repository",
"tests/commands/run_test.py::test_show_diff_on_failure",
"tests/commands/run_test.py::test_run[options0-outputs0-0-True]",
"tests/commands/run_test.py::test_run[options1-outputs1-0-True]",
"tests/commands/run_test.py::test_run[options2-outputs2-0-True]",
"tests/commands/run_test.py::test_run[options3-outputs3-1-True]",
"tests/commands/run_test.py::test_run[options4-outputs4-0-True]",
"tests/commands/run_test.py::test_run[options5-outputs5-0-True]",
"tests/commands/run_test.py::test_run[options6-outputs6-0-False]",
"tests/commands/run_test.py::test_run_output_logfile",
"tests/commands/run_test.py::test_always_run",
"tests/commands/run_test.py::test_always_run_alt_config",
"tests/commands/run_test.py::test_origin_source_error_msg[master-master-False]",
"tests/commands/run_test.py::test_origin_source_error_msg[master--True]",
"tests/commands/run_test.py::test_origin_source_error_msg[-master-True]",
"tests/commands/run_test.py::test_merge_conflict",
"tests/commands/run_test.py::test_merge_conflict_modified",
"tests/commands/run_test.py::test_merge_conflict_resolved",
"tests/commands/run_test.py::test_skip_hook",
"tests/commands/run_test.py::test_hook_id_not_in_non_verbose_output",
"tests/commands/run_test.py::test_hook_id_in_verbose_output",
"tests/commands/run_test.py::test_multiple_hooks_same_id",
"tests/commands/run_test.py::test_push_hook",
"tests/commands/run_test.py::test_commit_msg_hook",
"tests/commands/run_test.py::test_local_hook_passes",
"tests/commands/run_test.py::test_local_hook_fails",
"tests/commands/run_test.py::test_error_with_unstaged_config",
"tests/commands/run_test.py::test_no_unstaged_error_with_all_files_or_files[opts0]",
"tests/commands/run_test.py::test_no_unstaged_error_with_all_files_or_files[opts1]",
"tests/commands/run_test.py::test_pass_filenames[True-hook_args0-foo.py]",
"tests/commands/run_test.py::test_pass_filenames[False-hook_args1-]",
"tests/commands/run_test.py::test_pass_filenames[True-hook_args2-some",
"tests/commands/run_test.py::test_pass_filenames[False-hook_args3-some"
]
| [
"tests/commands/run_test.py::test_arbitrary_bytes_hook",
"tests/commands/run_test.py::test_hook_install_failure"
]
| [
"tests/commands/run_test.py::test_has_unmerged_paths[some-True]",
"tests/commands/run_test.py::test_has_unmerged_paths[-False]",
"tests/commands/run_test.py::test_compute_cols[hooks0-True-80]",
"tests/commands/run_test.py::test_compute_cols[hooks1-False-81]",
"tests/commands/run_test.py::test_compute_cols[hooks2-True-85]",
"tests/commands/run_test.py::test_compute_cols[hooks3-False-82]",
"tests/commands/run_test.py::test_get_skips[environ0-expected_output0]",
"tests/commands/run_test.py::test_get_skips[environ1-expected_output1]",
"tests/commands/run_test.py::test_get_skips[environ2-expected_output2]",
"tests/commands/run_test.py::test_get_skips[environ3-expected_output3]",
"tests/commands/run_test.py::test_get_skips[environ4-expected_output4]",
"tests/commands/run_test.py::test_get_skips[environ5-expected_output5]",
"tests/commands/run_test.py::test_get_skips[environ6-expected_output6]",
"tests/commands/run_test.py::test_non_ascii_hook_id",
"tests/commands/run_test.py::test_stdout_write_bug_py26",
"tests/commands/run_test.py::test_get_changed_files",
"tests/commands/run_test.py::test_lots_of_files",
"tests/commands/run_test.py::test_files_running_subdir",
"tests/git_test.py::test_get_root_at_root",
"tests/git_test.py::test_get_root_deeper",
"tests/git_test.py::test_get_root_not_git_dir",
"tests/git_test.py::test_get_staged_files_deleted",
"tests/git_test.py::test_is_not_in_merge_conflict",
"tests/git_test.py::test_is_in_merge_conflict",
"tests/git_test.py::test_cherry_pick_conflict",
"tests/git_test.py::test_get_files_matching_base",
"tests/git_test.py::test_matches_broken_symlink",
"tests/git_test.py::test_get_files_matching_total_match",
"tests/git_test.py::test_does_search_instead_of_match",
"tests/git_test.py::test_does_not_include_deleted_fileS",
"tests/git_test.py::test_exclude_removes_files",
"tests/git_test.py::test_get_conflicted_files",
"tests/git_test.py::test_get_conflicted_files_unstaged_files",
"tests/git_test.py::test_parse_merge_msg_for_conflicts[Merge"
]
| []
| MIT License | 1,615 | [
"pre_commit/main.py",
"pre_commit/commands/run.py"
]
| [
"pre_commit/main.py",
"pre_commit/commands/run.py"
]
|
|
rsheftel__pandas_market_calendars-11 | 72223f2615375c1ec321eb22abdaf9fda5bea1e5 | 2017-08-23 23:58:58 | 72223f2615375c1ec321eb22abdaf9fda5bea1e5 | diff --git a/pandas_market_calendars/calendar_utils.py b/pandas_market_calendars/calendar_utils.py
index 55d1c3d..62f51eb 100644
--- a/pandas_market_calendars/calendar_utils.py
+++ b/pandas_market_calendars/calendar_utils.py
@@ -57,9 +57,9 @@ def merge_schedules(schedules, how='outer'):
:param how: outer or inner
:return: schedule DataFrame
"""
-
- result = schedules.pop(0)
- for schedule in schedules:
+
+ result = schedules[0]
+ for schedule in schedules[1:]:
result = result.merge(schedule, how=how, right_index=True, left_index=True)
if how == 'outer':
result['market_open'] = result.apply(lambda x: min(x.market_open_x, x.market_open_y), axis=1)
@@ -69,24 +69,25 @@ def merge_schedules(schedules, how='outer'):
result['market_close'] = result.apply(lambda x: min(x.market_close_x, x.market_close_y), axis=1)
else:
raise ValueError('how argument must be "inner" or "outer"')
- return result[['market_open', 'market_close']]
+ result = result[['market_open', 'market_close']]
+ return result
def date_range(schedule, frequency, closed='right', force_close=True, **kwargs):
"""
- Given a schedule will return a DatetimeIndex will all of the valid datetime at the frequency given.
+ Given a schedule will return a DatetimeIndex will all of the valid datetime at the frequency given.
The schedule values are assumed to be in UTC.
:param schedule: schedule DataFrame
:param frequency: frequency in standard string
:param closed: same meaning as pandas date_range. 'right' will exclude the first value and should be used when the
results should only include the close for each bar.
- :param force_close: if True then the close of the day will be included even if it does not fall on an even
+ :param force_close: if True then the close of the day will be included even if it does not fall on an even
frequency. If False then the market close for the day may not be included in the results
:param kwargs: arguments that will be passed to the pandas date_time
:return: DatetimeIndex
"""
-
+
kwargs['closed'] = closed
ranges = list()
for row in schedule.itertuples():
| Issues with merge_schedules when list is larger than 2
Firstly thanks for the great project, it's very helpful. I am having issues with `merge_schedules` when the input list is greater than two. The issue seems to be that multiple calls to `pd.merge` happen causing repeated columns, e.g. `market_open_x`, which then fails when the `lambda` function is applied. Here is an illustrative example
```python
import pandas_market_calendars as mcal
start_date = "20170103"
end_date = "20170104"
cme = mcal.get_calendar("CME")
nyse = mcal.get_calendar("NYSE")
ice = mcal.get_calendar("ICE")
s1 = cme.schedule(start_date, end_date)
s2 = nyse.schedule(start_date, end_date)
s3 = ice.schedule(start_date, end_date)
schedules = [s1, s2, s3]
mcal.merge_schedules(schedules, how='inner')
ValueError: ('Can only compare identically-labeled Series objects', 'occurred at index 2017-01-03 00:00:00')
```
As described above, here is an illustration of the internal code causing the
issue
```python
how = "inner"
result = s1
result = result.merge(s2, how=how, right_index=True, left_index=True)
result['market_open'] = result.apply(lambda x: max(x.market_open_x, x.market_open_y), axis=1)
result['market_close'] = result.apply(lambda x: min(x.market_close_x, x.market_close_y), axis=1)
result = result.merge(s3, how=how, right_index=True, left_index=True)
print(result)
```
```
market_open_x market_close_x \
2017-01-03 2017-01-02 23:01:00+00:00 2017-01-03 23:00:00+00:00
2017-01-04 2017-01-03 23:01:00+00:00 2017-01-04 23:00:00+00:00
market_open_y market_close_y \
2017-01-03 2017-01-03 14:30:00+00:00 2017-01-03 21:00:00+00:00
2017-01-04 2017-01-04 14:30:00+00:00 2017-01-04 21:00:00+00:00
market_open_x market_close_x \
2017-01-03 2017-01-03 14:30:00+00:00 2017-01-03 21:00:00+00:00
2017-01-04 2017-01-04 14:30:00+00:00 2017-01-04 21:00:00+00:00
market_open_y market_close_y
2017-01-03 2017-01-03 01:01:00+00:00 2017-01-03 23:00:00+00:00
2017-01-04 2017-01-04 01:01:00+00:00 2017-01-04 23:00:00+00:00
```
In addition, the use of `pop` on the input list has the side effect of changing
the input, I believe this is an unintended side effect? | rsheftel/pandas_market_calendars | diff --git a/tests/test_utils.py b/tests/test_utils.py
index 743f84e..05a4a98 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -200,5 +200,9 @@ def test_merge_schedules():
actual = mcal.merge_schedules([sch1, sch2], how='inner')
assert_frame_equal(actual, expected)
+ # joining more than two calendars works correctly
+ actual = mcal.merge_schedules([sch1, sch1, sch1], how='inner')
+ assert_frame_equal(actual, sch1)
+
with pytest.raises(ValueError):
mcal.merge_schedules([sch1, sch2], how='left')
| {
"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
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist"
],
"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==22.2.0
certifi==2021.5.30
coverage==6.2
execnet==1.9.0
importlib-metadata==4.8.3
iniconfig==1.1.1
numpy==1.19.5
packaging==21.3
pandas==1.1.5
-e git+https://github.com/rsheftel/pandas_market_calendars.git@72223f2615375c1ec321eb22abdaf9fda5bea1e5#egg=pandas_market_calendars
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytest-xdist==3.0.2
python-dateutil==2.9.0.post0
pytz==2025.2
six==1.17.0
tomli==1.2.3
toolz==0.12.0
typing_extensions==4.1.1
zipp==3.6.0
| name: pandas_market_calendars
channels:
- defaults
- https://repo.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
- execnet==1.9.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- numpy==1.19.5
- packaging==21.3
- pandas==1.1.5
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-xdist==3.0.2
- python-dateutil==2.9.0.post0
- pytz==2025.2
- six==1.17.0
- tomli==1.2.3
- toolz==0.12.0
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/pandas_market_calendars
| [
"tests/test_utils.py::test_merge_schedules"
]
| []
| [
"tests/test_utils.py::test_get_calendar",
"tests/test_utils.py::test_date_range_daily",
"tests/test_utils.py::test_date_range_hour",
"tests/test_utils.py::test_date_range_minute"
]
| []
| MIT License | 1,616 | [
"pandas_market_calendars/calendar_utils.py"
]
| [
"pandas_market_calendars/calendar_utils.py"
]
|
|
chimpler__pyhocon-124 | 4dfa3b8b3c2e254964f28127f2d12ce526217869 | 2017-08-24 00:24:49 | 4683937b1d195ce2f53ca78987571e41bfe273e7 | diff --git a/.travis.yml b/.travis.yml
index cffa9ba..368f17e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,12 +1,13 @@
language: python
-python: 2.7
-env:
- - TOX_ENV=py26
- - TOX_ENV=py27
- - TOX_ENV=py33
- - TOX_ENV=py34
-install: pip install tox coveralls
-before_script: tox -e flake8
-script: tox -e ${TOX_ENV}
+python:
+ - 2.6
+ - 2.7
+ - 3.3
+ - 3.4
+ - 3.6
+before_install: pip install --upgrade setuptools
+install: pip install tox tox-travis coveralls
+before_script: if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then tox -e flake8; fi
+script: tox -r
after_success: coveralls
sudo: false
diff --git a/pyhocon/tool.py b/pyhocon/tool.py
index 8620fc2..241fd35 100644
--- a/pyhocon/tool.py
+++ b/pyhocon/tool.py
@@ -3,6 +3,8 @@ import logging
import sys
from pyhocon import ConfigFactory
from pyhocon.config_tree import ConfigTree
+from pyhocon.config_tree import NoneValue
+
try:
basestring
@@ -52,7 +54,7 @@ class HOCONConverter(object):
lines += '\n{indent}]'.format(indent=''.rjust(level * indent, ' '))
elif isinstance(config, basestring):
lines = '"{value}"'.format(value=config.replace('\n', '\\n').replace('"', '\\"'))
- elif config is None:
+ elif config is None or isinstance(config, NoneValue):
lines = 'null'
elif config is True:
lines = 'true'
@@ -103,7 +105,7 @@ class HOCONConverter(object):
lines = '"""{value}"""'.format(value=config) # multilines
else:
lines = '"{value}"'.format(value=config.replace('\n', '\\n').replace('"', '\\"'))
- elif config is None:
+ elif config is None or isinstance(config, NoneValue):
lines = 'null'
elif config is True:
lines = 'true'
@@ -150,6 +152,8 @@ class HOCONConverter(object):
lines = config
else:
lines = '|\n' + '\n'.join([line.rjust(level * indent, ' ') for line in lines])
+ elif config is None or isinstance(config, NoneValue):
+ lines = 'null'
elif config is True:
lines = 'true'
elif config is False:
@@ -185,6 +189,8 @@ class HOCONConverter(object):
lines.append('.'.join(stripped_key_stack) + ' = true')
elif config is False:
lines.append('.'.join(stripped_key_stack) + ' = false')
+ elif config is None or isinstance(config, NoneValue):
+ pass
else:
lines.append('.'.join(stripped_key_stack) + ' = ' + str(config))
return '\n'.join([line for line in lines if len(line) > 0])
diff --git a/tox.ini b/tox.ini
index f9a71ce..5a4f7da 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist = flake8, py26, py27, py33, py34
+envlist = flake8, py26, py27, py33, py34, py36
[testenv]
passenv = TRAVIS TRAVIS_JOB_ID TRAVIS_BRANCH
| HOCONConverter.to_json can't convert `null` value
After convert into JSON with `HOCONConverter.to_json`, the value should be kept `null`, but it is converted to `NonValue`.
```py
In [19]: hocon = "{foo = null}"
In [20]: conf = ConfigFactory.parse_string(hocon)
In [21]: conf
Out[21]: ConfigTree([('foo', <pyhocon.config_tree.NoneValue at 0x1a1074e4fd0>)])
In [22]: HOCONConverter.to_json(conf)
Out[22]: '{\n "foo": <pyhocon.config_tree.NoneValue object at 0x000001A1074E4FD0>\n}'
``` | chimpler/pyhocon | diff --git a/tests/test_tool.py b/tests/test_tool.py
index 937f9e7..9610d77 100644
--- a/tests/test_tool.py
+++ b/tests/test_tool.py
@@ -81,7 +81,7 @@ class TestHOCONConverter(object):
f1: true
f2: false
g: []
- h: None
+ h: null
i:
a.b: 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": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 3
} | 0.3 | {
"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",
"mock"
],
"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
mock==5.2.0
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
-e git+https://github.com/chimpler/pyhocon.git@4dfa3b8b3c2e254964f28127f2d12ce526217869#egg=pyhocon
pyparsing==3.2.3
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| 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
- 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
- pyparsing==3.2.3
prefix: /opt/conda/envs/pyhocon
| [
"tests/test_tool.py::TestHOCONConverter::test_to_json",
"tests/test_tool.py::TestHOCONConverter::test_to_yaml",
"tests/test_tool.py::TestHOCONConverter::test_to_properties",
"tests/test_tool.py::TestHOCONConverter::test_to_hocon",
"tests/test_tool.py::TestHOCONConverter::test_convert_from_file"
]
| []
| [
"tests/test_tool.py::TestHOCONConverter::test_invalid_format"
]
| []
| Apache License 2.0 | 1,617 | [
"pyhocon/tool.py",
".travis.yml",
"tox.ini"
]
| [
"pyhocon/tool.py",
".travis.yml",
"tox.ini"
]
|
|
borgbackup__borg-2959 | e9b892feb5107fc407e2913a8d1b6fa16165efd7 | 2017-08-24 02:19:19 | a714f77c4a0f9539bc21dd3b6b9e2eaaddaa9dfe | diff --git a/docs/changes.rst b/docs/changes.rst
index 9d32ccfd..ec436b7e 100644
--- a/docs/changes.rst
+++ b/docs/changes.rst
@@ -139,12 +139,7 @@ Compatibility notes:
- dropped support and testing for Python 3.4, minimum requirement is 3.5.0.
In case your OS does not provide Python >= 3.5, consider using our binary,
which does not need an external Python interpreter.
-- list: corrected mix-up of "isomtime" and "mtime" formats. Previously,
- "isomtime" was the default but produced a verbose human format,
- while "mtime" produced a ISO-8601-like format.
- The behaviours have been swapped (so "mtime" is human, "isomtime" is ISO-like),
- and the default is now "mtime".
- "isomtime" is now a real ISO-8601 format ("T" between date and time, not a space).
+
Version 1.1.0rc1 (2017-07-24)
-----------------------------
diff --git a/docs/development.rst b/docs/development.rst
index 365025d9..e9868a1b 100644
--- a/docs/development.rst
+++ b/docs/development.rst
@@ -17,7 +17,7 @@ Contributions
Some guidance for contributors:
-- discuss changes on the GitHub issue tracker, on IRC or on the mailing list
+- discuss about changes on github issue tracker, IRC or mailing list
- make your PRs on the ``master`` branch (see `Branching Model`_ for details)
@@ -29,9 +29,9 @@ Some guidance for contributors:
- if you need to fix something after commit/push:
- if there are ongoing reviews: do a fixup commit you can
- squash into the bad commit later.
+ merge into the bad commit later.
- if there are no ongoing reviews or you did not push the
- bad commit yet: amend the commit to include your fix or
+ bad commit yet: edit the commit to include your fix or
merge the fixup commit before pushing.
- have a nice, clear, typo-free commit comment
- if you fixed an issue, refer to it in your commit comment
@@ -39,9 +39,9 @@ Some guidance for contributors:
- if you write new code, please add tests and docs for it
-- run the tests, fix any issues that come up
+- run the tests, fix anything that comes up
-- make a pull request on GitHub
+- make a pull request on github
- wait for review by other developers
@@ -52,15 +52,15 @@ Borg development happens on the ``master`` branch and uses GitHub pull
requests (if you don't have GitHub or don't want to use it you can
send smaller patches via the borgbackup :ref:`mailing_list` to the maintainers).
-Stable releases are maintained on maintenance branches named ``x.y-maint``, eg.
-the maintenance branch of the 1.0.x series is ``1.0-maint``.
+Stable releases are maintained on maintenance branches named x.y-maint, eg.
+the maintenance branch of the 1.0.x series is 1.0-maint.
-Most PRs should be filed against the ``master`` branch. Only if an
+Most PRs should be made against the ``master`` branch. Only if an
issue affects **only** a particular maintenance branch a PR should be
-filed against it directly.
+made against it directly.
While discussing / reviewing a PR it will be decided whether the
-change should be applied to maintenance branches. Each maintenance
+change should be applied to maintenance branch(es). Each maintenance
branch has a corresponding *backport/x.y-maint* label, which will then
be applied.
@@ -113,7 +113,7 @@ troublesome due to merges growing more conflict-heavy and error-prone.
Code and issues
---------------
-Code is stored on GitHub, in the `Borgbackup organization
+Code is stored on Github, in the `Borgbackup organization
<https://github.com/borgbackup/borg/>`_. `Issues
<https://github.com/borgbackup/borg/issues>`_ and `pull requests
<https://github.com/borgbackup/borg/pulls>`_ should be sent there as
@@ -222,7 +222,7 @@ parsers declared in the program and their documentation, which is
embedded in the program (see archiver.py). These are committed to git
for easier use by packagers downstream.
-When a command is added, a command line flag changed, added or removed,
+When a command is added, a commandline flag changed, added or removed,
the usage docs need to be rebuilt as well::
python setup.py build_usage
@@ -327,8 +327,8 @@ Checklist:
git clone borg borg-clean
This makes sure no uncommitted files get into the release archive.
- It will also reveal uncommitted required files.
- Moreover, it makes sure the vagrant machines only get committed files and
+ It also will find if you forgot to commit something that is needed.
+ It also makes sure the vagrant machines only get committed files and
do a fresh start based on that.
- run tox and/or binary builds on all supported platforms via vagrant,
check for test failures
@@ -336,14 +336,14 @@ Checklist:
python setup.py register sdist upload --identity="Thomas Waldmann" --sign
-- close the release milestone on GitHub
+- close release milestone on Github
- announce on:
- Mailing list
- Twitter (follow @ThomasJWaldmann for these tweets)
- IRC channel (change ``/topic``)
-- create a GitHub release, include:
+- create a Github release, include:
* standalone binaries (see above for how to create them)
diff --git a/docs/internals/data-structures.rst b/docs/internals/data-structures.rst
index 045b476b..dd7eaefd 100644
--- a/docs/internals/data-structures.rst
+++ b/docs/internals/data-structures.rst
@@ -96,7 +96,7 @@ files manually.
A segment starts with a magic number (``BORG_SEG`` as an eight byte ASCII string),
followed by a number of log entries. Each log entry consists of:
-* 32-bit size of the entry
+* size of the entry
* CRC32 of the entire entry (for a PUT this includes the data)
* entry tag: PUT, DELETE or COMMIT
* PUT and DELETE follow this with the 32 byte key
@@ -118,9 +118,6 @@ When a repository is opened any ``PUT`` or ``DELETE`` operations not
followed by a ``COMMIT`` tag are discarded since they are part of a
partial/uncommitted transaction.
-The size of individual segments is limited to 4 GiB, since the offset of entries
-within segments is stored in a 32-bit unsigned integer in the repository index.
-
Index, hints and integrity
~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/docs/internals/frontends.rst b/docs/internals/frontends.rst
index cfe9730f..677db738 100644
--- a/docs/internals/frontends.rst
+++ b/docs/internals/frontends.rst
@@ -209,9 +209,8 @@ Standard output
*stdout* is different and more command-dependent than logging. Commands like :ref:`borg_info`, :ref:`borg_create`
and :ref:`borg_list` implement a ``--json`` option which turns their regular output into a single JSON object.
-Dates are formatted according to ISO 8601 in local time. No explicit time zone is specified *at this time*
-(subject to change). The equivalent strftime format string is '%Y-%m-%dT%H:%M:%S.%f',
-e.g. ``2017-08-07T12:27:20.123456``.
+Dates are formatted according to ISO-8601 with the strftime format string '%a, %Y-%m-%d %H:%M:%S',
+e.g. *Sat, 2016-02-25 23:50:06*.
The root object at least contains a *repository* key with an object containing:
@@ -268,7 +267,7 @@ Example *borg info* output::
},
"repository": {
"id": "0cbe6166b46627fd26b97f8831e2ca97584280a46714ef84d2b668daf8271a23",
- "last_modified": "2017-08-07T12:27:20.789123",
+ "last_modified": "Mon, 2017-02-27 21:21:58",
"location": "/home/user/testrepo"
},
"security_dir": "/home/user/.config/borg/security/0cbe6166b46627fd26b97f8831e2ca97584280a46714ef84d2b668daf8271a23",
@@ -329,7 +328,7 @@ Example of a simple archive listing (``borg list --last 1 --json``)::
{
"id": "80cd07219ad725b3c5f665c1dcf119435c4dee1647a560ecac30f8d40221a46a",
"name": "host-system-backup-2017-02-27",
- "start": "2017-08-07T12:27:20.789123"
+ "start": "Mon, 2017-02-27 21:21:52"
}
],
"encryption": {
@@ -337,7 +336,7 @@ Example of a simple archive listing (``borg list --last 1 --json``)::
},
"repository": {
"id": "0cbe6166b46627fd26b97f8831e2ca97584280a46714ef84d2b668daf8271a23",
- "last_modified": "2017-08-07T12:27:20.789123",
+ "last_modified": "Mon, 2017-02-27 21:21:58",
"location": "/home/user/repository"
}
}
@@ -355,14 +354,14 @@ The same archive with more information (``borg info --last 1 --json``)::
],
"comment": "",
"duration": 5.641542,
- "end": "2017-02-27T12:27:20.789123",
+ "end": "Mon, 2017-02-27 21:21:58",
"hostname": "host",
"id": "80cd07219ad725b3c5f665c1dcf119435c4dee1647a560ecac30f8d40221a46a",
"limits": {
"max_archive_size": 0.0001330855110409714
},
"name": "host-system-backup-2017-02-27",
- "start": "2017-02-27T12:27:20.789123",
+ "start": "Mon, 2017-02-27 21:21:52",
"stats": {
"compressed_size": 1880961894,
"deduplicated_size": 2791,
@@ -388,7 +387,7 @@ The same archive with more information (``borg info --last 1 --json``)::
},
"repository": {
"id": "0cbe6166b46627fd26b97f8831e2ca97584280a46714ef84d2b668daf8271a23",
- "last_modified": "2017-08-07T12:27:20.789123",
+ "last_modified": "Mon, 2017-02-27 21:21:58",
"location": "/home/user/repository"
}
}
@@ -406,8 +405,8 @@ Refer to the *borg list* documentation for the available keys and their meaning.
Example (excerpt) of ``borg list --json-lines``::
- {"type": "d", "mode": "drwxr-xr-x", "user": "user", "group": "user", "uid": 1000, "gid": 1000, "path": "linux", "healthy": true, "source": "", "linktarget": "", "flags": null, "mtime": "2017-02-27T12:27:20.023407", "size": 0}
- {"type": "d", "mode": "drwxr-xr-x", "user": "user", "group": "user", "uid": 1000, "gid": 1000, "path": "linux/baz", "healthy": true, "source": "", "linktarget": "", "flags": null, "mtime": "2017-02-27T12:27:20.585407", "size": 0}
+ {"type": "d", "mode": "drwxr-xr-x", "user": "user", "group": "user", "uid": 1000, "gid": 1000, "path": "linux", "healthy": true, "source": "", "linktarget": "", "flags": null, "isomtime": "Sat, 2016-05-07 19:46:01", "size": 0}
+ {"type": "d", "mode": "drwxr-xr-x", "user": "user", "group": "user", "uid": 1000, "gid": 1000, "path": "linux/baz", "healthy": true, "source": "", "linktarget": "", "flags": null, "isomtime": "Sat, 2016-05-07 19:46:01", "size": 0}
.. _msgid:
diff --git a/src/borg/archive.py b/src/borg/archive.py
index 4f25666f..a87219e0 100644
--- a/src/borg/archive.py
+++ b/src/borg/archive.py
@@ -5,13 +5,12 @@
import stat
import sys
import time
-from collections import OrderedDict
from contextlib import contextmanager
from datetime import datetime, timezone, timedelta
from functools import partial
from getpass import getuser
from io import BytesIO
-from itertools import groupby, zip_longest
+from itertools import groupby
from shutil import get_terminal_size
import msgpack
@@ -34,14 +33,14 @@
from .helpers import Error, IntegrityError, set_ec
from .helpers import uid2user, user2uid, gid2group, group2gid
from .helpers import parse_timestamp, to_localtime
-from .helpers import OutputTimestamp, format_timedelta, format_file_size, file_status, FileSize
+from .helpers import format_time, format_timedelta, format_file_size, file_status, FileSize
from .helpers import safe_encode, safe_decode, make_path_safe, remove_surrogates
from .helpers import StableDict
from .helpers import bin_to_hex
from .helpers import safe_ns
from .helpers import ellipsis_truncate, ProgressIndicatorPercent, log_multi
from .patterns import PathPrefixPattern, FnmatchPattern, IECommand
-from .item import Item, ArchiveItem, ItemDiff
+from .item import Item, ArchiveItem
from .platform import acl_get, acl_set, set_flags, get_flags, swidth
from .remote import cache_if_remote
from .repository import Repository, LIST_SCAN_LIMIT
@@ -381,8 +380,8 @@ def info(self):
info = {
'name': self.name,
'id': self.fpr,
- 'start': OutputTimestamp(start),
- 'end': OutputTimestamp(end),
+ 'start': format_time(to_localtime(start)),
+ 'end': format_time(to_localtime(end)),
'duration': (end - start).total_seconds(),
'stats': stats.as_dict(),
'limits': {
@@ -411,8 +410,8 @@ def __str__(self):
Utilization of max. archive size: {csize_max:.0%}
'''.format(
self,
- start=OutputTimestamp(self.start.replace(tzinfo=timezone.utc)),
- end=OutputTimestamp(self.end.replace(tzinfo=timezone.utc)),
+ start=format_time(to_localtime(self.start.replace(tzinfo=timezone.utc))),
+ end=format_time(to_localtime(self.end.replace(tzinfo=timezone.utc))),
csize_max=self.cache.chunks[self.id].csize / MAX_DATA_SIZE)
def __repr__(self):
@@ -446,15 +445,13 @@ def save(self, name=None, comment=None, timestamp=None, additional_metadata=None
self.items_buffer.flush(flush=True)
duration = timedelta(seconds=time.monotonic() - self.start_monotonic)
if timestamp is None:
- self.end = datetime.utcnow()
- self.start = self.end - duration
- start = self.start
- end = self.end
+ end = datetime.utcnow()
+ start = end - duration
else:
- self.end = timestamp
- self.start = timestamp - duration
- end = timestamp
- start = self.start
+ end = timestamp + duration
+ start = timestamp
+ self.start = start
+ self.end = end
metadata = {
'version': 1,
'name': name,
@@ -820,89 +817,6 @@ def _open_rb(path):
# Was this EPERM due to the O_NOATIME flag? Try again without it:
return os.open(path, flags_normal)
- @staticmethod
- def compare_archives_iter(archive1, archive2, matcher=None, can_compare_chunk_ids=False):
- """
- Yields tuples with a path and an ItemDiff instance describing changes/indicating equality.
-
- :param matcher: PatternMatcher class to restrict results to only matching paths.
- :param can_compare_chunk_ids: Whether --chunker-params are the same for both archives.
- """
-
- def hardlink_master_seen(item):
- return 'source' not in item or not hardlinkable(item.mode) or item.source in hardlink_masters
-
- def is_hardlink_master(item):
- return item.get('hardlink_master', True) and 'source' not in item
-
- def update_hardlink_masters(item1, item2):
- if is_hardlink_master(item1) or is_hardlink_master(item2):
- hardlink_masters[item1.path] = (item1, item2)
-
- def has_hardlink_master(item, hardlink_masters):
- return hardlinkable(item.mode) and item.get('source') in hardlink_masters
-
- def compare_items(item1, item2):
- if has_hardlink_master(item1, hardlink_masters):
- item1 = hardlink_masters[item1.source][0]
- if has_hardlink_master(item2, hardlink_masters):
- item2 = hardlink_masters[item2.source][1]
- return ItemDiff(item1, item2,
- archive1.pipeline.fetch_many([c.id for c in item1.get('chunks', [])]),
- archive2.pipeline.fetch_many([c.id for c in item2.get('chunks', [])]),
- can_compare_chunk_ids=can_compare_chunk_ids)
-
- def defer_if_necessary(item1, item2):
- """Adds item tuple to deferred if necessary and returns True, if items were deferred"""
- update_hardlink_masters(item1, item2)
- defer = not hardlink_master_seen(item1) or not hardlink_master_seen(item2)
- if defer:
- deferred.append((item1, item2))
- return defer
-
- orphans_archive1 = OrderedDict()
- orphans_archive2 = OrderedDict()
- deferred = []
- hardlink_masters = {}
-
- for item1, item2 in zip_longest(
- archive1.iter_items(lambda item: matcher.match(item.path)),
- archive2.iter_items(lambda item: matcher.match(item.path)),
- ):
- if item1 and item2 and item1.path == item2.path:
- if not defer_if_necessary(item1, item2):
- yield (item1.path, compare_items(item1, item2))
- continue
- if item1:
- matching_orphan = orphans_archive2.pop(item1.path, None)
- if matching_orphan:
- if not defer_if_necessary(item1, matching_orphan):
- yield (item1.path, compare_items(item1, matching_orphan))
- else:
- orphans_archive1[item1.path] = item1
- if item2:
- matching_orphan = orphans_archive1.pop(item2.path, None)
- if matching_orphan:
- if not defer_if_necessary(matching_orphan, item2):
- yield (matching_orphan.path, compare_items(matching_orphan, item2))
- else:
- orphans_archive2[item2.path] = item2
- # At this point orphans_* contain items that had no matching partner in the other archive
- for added in orphans_archive2.values():
- path = added.path
- deleted_item = Item.create_deleted(path)
- update_hardlink_masters(deleted_item, added)
- yield (path, compare_items(deleted_item, added))
- for deleted in orphans_archive1.values():
- path = deleted.path
- deleted_item = Item.create_deleted(path)
- update_hardlink_masters(deleted, deleted_item)
- yield (path, compare_items(deleted, deleted_item))
- for item1, item2 in deferred:
- assert hardlink_master_seen(item1)
- assert hardlink_master_seen(item2)
- yield (path, compare_items(item1, item2))
-
class MetadataCollector:
def __init__(self, *, noatime, noctime, numeric_owner):
diff --git a/src/borg/archiver.py b/src/borg/archiver.py
index 48b9fde7..80fd7887 100644
--- a/src/borg/archiver.py
+++ b/src/borg/archiver.py
@@ -195,6 +195,33 @@ def print_file_status(self, status, path):
else:
logging.getLogger('borg.output.list').info("%1s %s", status, remove_surrogates(path))
+ @staticmethod
+ def compare_chunk_contents(chunks1, chunks2):
+ """Compare two chunk iterators (like returned by :meth:`.DownloadPipeline.fetch_many`)"""
+ end = object()
+ alen = ai = 0
+ blen = bi = 0
+ while True:
+ if not alen - ai:
+ a = next(chunks1, end)
+ if a is end:
+ return not blen - bi and next(chunks2, end) is end
+ a = memoryview(a)
+ alen = len(a)
+ ai = 0
+ if not blen - bi:
+ b = next(chunks2, end)
+ if b is end:
+ return not alen - ai and next(chunks1, end) is end
+ b = memoryview(b)
+ blen = len(b)
+ bi = 0
+ slicelen = min(alen - ai, blen - bi)
+ if a[ai:ai + slicelen] != b[bi:bi + slicelen]:
+ return False
+ ai += slicelen
+ bi += slicelen
+
@staticmethod
def build_matcher(inclexcl_patterns, include_paths):
matcher = PatternMatcher()
@@ -940,9 +967,195 @@ def item_to_tarinfo(item, original_path):
@with_archive
def do_diff(self, args, repository, manifest, key, archive):
"""Diff contents of two archives"""
+ def fetch_and_compare_chunks(chunk_ids1, chunk_ids2, archive1, archive2):
+ chunks1 = archive1.pipeline.fetch_many(chunk_ids1)
+ chunks2 = archive2.pipeline.fetch_many(chunk_ids2)
+ return self.compare_chunk_contents(chunks1, chunks2)
+
+ def sum_chunk_size(item, consider_ids=None):
+ if item.get('deleted'):
+ size = None
+ else:
+ if consider_ids is not None: # consider only specific chunks
+ size = sum(chunk.size for chunk in item.chunks if chunk.id in consider_ids)
+ else: # consider all chunks
+ size = item.get_size()
+ return size
+
+ def get_owner(item):
+ if args.numeric_owner:
+ return item.uid, item.gid
+ else:
+ return item.user, item.group
+
+ def get_mode(item):
+ if 'mode' in item:
+ return stat.filemode(item.mode)
+ else:
+ return [None]
+
+ def has_hardlink_master(item, hardlink_masters):
+ return hardlinkable(item.mode) and item.get('source') in hardlink_masters
+
+ def compare_link(item1, item2):
+ # These are the simple link cases. For special cases, e.g. if a
+ # regular file is replaced with a link or vice versa, it is
+ # indicated in compare_mode instead.
+ if item1.get('deleted'):
+ return 'added link'
+ elif item2.get('deleted'):
+ return 'removed link'
+ elif 'source' in item1 and 'source' in item2 and item1.source != item2.source:
+ return 'changed link'
+
+ def contents_changed(item1, item2):
+ if can_compare_chunk_ids:
+ return item1.chunks != item2.chunks
+ else:
+ if sum_chunk_size(item1) != sum_chunk_size(item2):
+ return True
+ else:
+ chunk_ids1 = [c.id for c in item1.chunks]
+ chunk_ids2 = [c.id for c in item2.chunks]
+ return not fetch_and_compare_chunks(chunk_ids1, chunk_ids2, archive1, archive2)
+
+ def compare_content(path, item1, item2):
+ if contents_changed(item1, item2):
+ if item1.get('deleted'):
+ return 'added {:>13}'.format(format_file_size(sum_chunk_size(item2)))
+ if item2.get('deleted'):
+ return 'removed {:>11}'.format(format_file_size(sum_chunk_size(item1)))
+ if not can_compare_chunk_ids:
+ return 'modified'
+ chunk_ids1 = {c.id for c in item1.chunks}
+ chunk_ids2 = {c.id for c in item2.chunks}
+ added_ids = chunk_ids2 - chunk_ids1
+ removed_ids = chunk_ids1 - chunk_ids2
+ added = sum_chunk_size(item2, added_ids)
+ removed = sum_chunk_size(item1, removed_ids)
+ return '{:>9} {:>9}'.format(format_file_size(added, precision=1, sign=True),
+ format_file_size(-removed, precision=1, sign=True))
+
+ def compare_directory(item1, item2):
+ if item2.get('deleted') and not item1.get('deleted'):
+ return 'removed directory'
+ elif item1.get('deleted') and not item2.get('deleted'):
+ return 'added directory'
+
+ def compare_owner(item1, item2):
+ user1, group1 = get_owner(item1)
+ user2, group2 = get_owner(item2)
+ if user1 != user2 or group1 != group2:
+ return '[{}:{} -> {}:{}]'.format(user1, group1, user2, group2)
+
+ def compare_mode(item1, item2):
+ if item1.mode != item2.mode:
+ return '[{} -> {}]'.format(get_mode(item1), get_mode(item2))
+
+ def compare_items(output, path, item1, item2, hardlink_masters, deleted=False):
+ """
+ Compare two items with identical paths.
+ :param deleted: Whether one of the items has been deleted
+ """
+ changes = []
+
+ if has_hardlink_master(item1, hardlink_masters):
+ item1 = hardlink_masters[item1.source][0]
+
+ if has_hardlink_master(item2, hardlink_masters):
+ item2 = hardlink_masters[item2.source][1]
+
+ if get_mode(item1)[0] == 'l' or get_mode(item2)[0] == 'l':
+ changes.append(compare_link(item1, item2))
+
+ if 'chunks' in item1 and 'chunks' in item2:
+ changes.append(compare_content(path, item1, item2))
+
+ if get_mode(item1)[0] == 'd' or get_mode(item2)[0] == 'd':
+ changes.append(compare_directory(item1, item2))
- def print_output(diff, path):
- print("{:<19} {}".format(diff, path))
+ if not deleted:
+ changes.append(compare_owner(item1, item2))
+ changes.append(compare_mode(item1, item2))
+
+ changes = [x for x in changes if x]
+ if changes:
+ output_line = (remove_surrogates(path), ' '.join(changes))
+
+ if args.sort:
+ output.append(output_line)
+ else:
+ print_output(output_line)
+
+ def print_output(line):
+ print("{:<19} {}".format(line[1], line[0]))
+
+ def compare_archives(archive1, archive2, matcher):
+ def hardlink_master_seen(item):
+ return 'source' not in item or not hardlinkable(item.mode) or item.source in hardlink_masters
+
+ def is_hardlink_master(item):
+ return item.get('hardlink_master', True) and 'source' not in item
+
+ def update_hardlink_masters(item1, item2):
+ if is_hardlink_master(item1) or is_hardlink_master(item2):
+ hardlink_masters[item1.path] = (item1, item2)
+
+ def compare_or_defer(item1, item2):
+ update_hardlink_masters(item1, item2)
+ if not hardlink_master_seen(item1) or not hardlink_master_seen(item2):
+ deferred.append((item1, item2))
+ else:
+ compare_items(output, item1.path, item1, item2, hardlink_masters)
+
+ orphans_archive1 = collections.OrderedDict()
+ orphans_archive2 = collections.OrderedDict()
+ deferred = []
+ hardlink_masters = {}
+ output = []
+
+ for item1, item2 in zip_longest(
+ archive1.iter_items(lambda item: matcher.match(item.path)),
+ archive2.iter_items(lambda item: matcher.match(item.path)),
+ ):
+ if item1 and item2 and item1.path == item2.path:
+ compare_or_defer(item1, item2)
+ continue
+ if item1:
+ matching_orphan = orphans_archive2.pop(item1.path, None)
+ if matching_orphan:
+ compare_or_defer(item1, matching_orphan)
+ else:
+ orphans_archive1[item1.path] = item1
+ if item2:
+ matching_orphan = orphans_archive1.pop(item2.path, None)
+ if matching_orphan:
+ compare_or_defer(matching_orphan, item2)
+ else:
+ orphans_archive2[item2.path] = item2
+ # At this point orphans_* contain items that had no matching partner in the other archive
+ deleted_item = Item(
+ deleted=True,
+ chunks=[],
+ mode=0,
+ )
+ for added in orphans_archive2.values():
+ path = added.path
+ deleted_item.path = path
+ update_hardlink_masters(deleted_item, added)
+ compare_items(output, path, deleted_item, added, hardlink_masters, deleted=True)
+ for deleted in orphans_archive1.values():
+ path = deleted.path
+ deleted_item.path = path
+ update_hardlink_masters(deleted, deleted_item)
+ compare_items(output, path, deleted, deleted_item, hardlink_masters, deleted=True)
+ for item1, item2 in deferred:
+ assert hardlink_master_seen(item1)
+ assert hardlink_master_seen(item2)
+ compare_items(output, item1.path, item1, item2, hardlink_masters)
+
+ for line in sorted(output):
+ print_output(line)
archive1 = archive
archive2 = Archive(repository, key, manifest, args.archive2,
@@ -957,15 +1170,7 @@ def print_output(diff, path):
matcher = self.build_matcher(args.patterns, args.paths)
- diffs = Archive.compare_archives_iter(archive1, archive2, matcher, can_compare_chunk_ids=can_compare_chunk_ids)
- # Conversion to string and filtering for diff.equal to save memory if sorting
- diffs = ((path, str(diff)) for path, diff in diffs if not diff.equal)
-
- if args.sort:
- diffs = sorted(diffs)
-
- for path, diff in diffs:
- print_output(diff, path)
+ compare_archives(archive1, archive2, matcher)
for pattern in matcher.get_unmatched_include_patterns():
self.print_warning("Include pattern '%s' never matched.", pattern)
@@ -1137,7 +1342,7 @@ def _list_archive(self, args, repository, manifest, key, write):
elif args.short:
format = "{path}{NL}"
else:
- format = "{mode} {user:6} {group:6} {size:8} {mtime} {path}{extra}{NL}"
+ format = "{mode} {user:6} {group:6} {size:8} {isomtime} {path}{extra}{NL}"
def _list_inner(cache):
archive = Archive(repository, key, manifest, args.location.archive, cache=cache,
@@ -2610,9 +2815,6 @@ def define_archive_filters_group(subparser, *, sort_by=True, first_last=True):
and not include any other contents of the containing folder, this can be enabled
through using the ``--keep-exclude-tags`` option.
- Borg respects the nodump flag. Files flagged nodump will be marked as excluded (x)
- in ``--list`` output.
-
Item flags
++++++++++
@@ -2925,7 +3127,7 @@ def define_archive_filters_group(subparser, *, sort_by=True, first_last=True):
help='only print file/directory names, nothing else')
subparser.add_argument('--format', '--list-format', metavar='FORMAT', dest='format',
help='specify format for file listing '
- '(default: "{mode} {user:6} {group:6} {size:8d} {mtime} {path}{extra}{NL}")')
+ '(default: "{mode} {user:6} {group:6} {size:8d} {isomtime} {path}{extra}{NL}")')
subparser.add_argument('--json', action='store_true',
help='Only valid for listing repository contents. Format output as JSON. '
'The form of ``--format`` is ignored, '
diff --git a/src/borg/cache.py b/src/borg/cache.py
index a9e7be27..c1c70332 100644
--- a/src/borg/cache.py
+++ b/src/borg/cache.py
@@ -503,16 +503,10 @@ def _read_files(self):
if not data:
break
u.feed(data)
- try:
- for path_hash, item in u:
- entry = FileCacheEntry(*item)
- # in the end, this takes about 240 Bytes per file
- self.files[path_hash] = msgpack.packb(entry._replace(age=entry.age + 1))
- except (TypeError, ValueError) as exc:
- logger.warning('The files cache seems corrupt, ignoring it. '
- 'Expect lower performance. [%s]' % str(exc))
- self.files = {}
- return
+ for path_hash, item in u:
+ entry = FileCacheEntry(*item)
+ # in the end, this takes about 240 Bytes per file
+ self.files[path_hash] = msgpack.packb(entry._replace(age=entry.age + 1))
def begin_txn(self):
# Initialize transaction snapshot
@@ -982,7 +976,7 @@ def memorize_file(self, path_hash, st, ids):
def add_chunk(self, id, chunk, stats, overwrite=False, wait=True):
assert not overwrite, 'AdHocCache does not permit overwrites — trying to use it for recreate?'
if not self._txn_active:
- self.begin_txn()
+ self._begin_txn()
size = len(chunk)
refcount = self.seen_chunk(id, size)
if refcount:
@@ -996,7 +990,7 @@ def add_chunk(self, id, chunk, stats, overwrite=False, wait=True):
def seen_chunk(self, id, size=None):
if not self._txn_active:
- self.begin_txn()
+ self._begin_txn()
entry = self.chunks.get(id, ChunkIndexEntry(0, None, None))
if entry.refcount and size and not entry.size:
# The LocalCache has existing size information and uses *size* to make an effort at detecting collisions.
@@ -1007,7 +1001,7 @@ def seen_chunk(self, id, size=None):
def chunk_incref(self, id, stats, size=None):
if not self._txn_active:
- self.begin_txn()
+ self._begin_txn()
count, _size, csize = self.chunks.incref(id)
# When _size is 0 and size is not given, then this chunk has not been locally visited yet (seen_chunk with
# size or add_chunk); we can't add references to those (size=0 is invalid) and generally don't try to.
@@ -1018,7 +1012,7 @@ def chunk_incref(self, id, stats, size=None):
def chunk_decref(self, id, stats, wait=True):
if not self._txn_active:
- self.begin_txn()
+ self._begin_txn()
count, size, csize = self.chunks.decref(id)
if count == 0:
del self.chunks[id]
@@ -1037,7 +1031,9 @@ def rollback(self):
self._txn_active = False
del self.chunks
- def begin_txn(self):
+ # Private API
+
+ def _begin_txn(self):
self._txn_active = True
# Explicitly set the initial hash table capacity to avoid performance issues
# due to hash table "resonance".
diff --git a/src/borg/helpers/parseformat.py b/src/borg/helpers/parseformat.py
index 25114c46..c8e65295 100644
--- a/src/borg/helpers/parseformat.py
+++ b/src/borg/helpers/parseformat.py
@@ -18,7 +18,7 @@
from .errors import Error
from .fs import get_keys_dir
-from .time import OutputTimestamp, format_time, to_localtime, safe_timestamp, safe_s
+from .time import format_time, isoformat_time, to_localtime, safe_timestamp, safe_s
from .usergroup import uid2user
from .. import __version__ as borg_version
from .. import __version_tuple__ as borg_version_tuple
@@ -549,11 +549,12 @@ def __init__(self, format, repository, manifest, key, *, json=False):
if self.json:
self.item_data = {}
self.format_item = self.format_item_json
+ self.format_time = self.format_time_json
else:
self.item_data = static_keys
def format_item_json(self, item):
- return json.dumps(self.get_item_data(item), cls=BorgJsonEncoder) + '\n'
+ return json.dumps(self.get_item_data(item)) + '\n'
def get_item_data(self, archive_info):
self.name = archive_info.name
@@ -587,7 +588,12 @@ def get_ts_end(self):
return self.format_time(self.archive.ts_end)
def format_time(self, ts):
- return OutputTimestamp(ts)
+ t = to_localtime(ts)
+ return format_time(t)
+
+ def format_time_json(self, ts):
+ t = to_localtime(ts)
+ return isoformat_time(t)
class ItemFormatter(BaseFormatter):
@@ -663,6 +669,7 @@ def __init__(self, archive, format, *, json_lines=False):
if self.json_lines:
self.item_data = {}
self.format_item = self.format_item_json
+ self.format_time = self.format_time_json
else:
self.item_data = static_keys
self.format = partial_format(format, static_keys)
@@ -674,19 +681,19 @@ def __init__(self, archive, format, *, json_lines=False):
'dcsize': partial(self.sum_unique_chunks_metadata, lambda chunk: chunk.csize),
'num_chunks': self.calculate_num_chunks,
'unique_chunks': partial(self.sum_unique_chunks_metadata, lambda chunk: 1),
- 'isomtime': partial(self.format_iso_time, 'mtime'),
- 'isoctime': partial(self.format_iso_time, 'ctime'),
- 'isoatime': partial(self.format_iso_time, 'atime'),
- 'mtime': partial(self.format_time, 'mtime'),
- 'ctime': partial(self.format_time, 'ctime'),
- 'atime': partial(self.format_time, 'atime'),
+ 'isomtime': partial(self.format_time, 'mtime'),
+ 'isoctime': partial(self.format_time, 'ctime'),
+ 'isoatime': partial(self.format_time, 'atime'),
+ 'mtime': partial(self.time, 'mtime'),
+ 'ctime': partial(self.time, 'ctime'),
+ 'atime': partial(self.time, 'atime'),
}
for hash_function in hashlib.algorithms_guaranteed:
self.add_key(hash_function, partial(self.hash_item, hash_function))
self.used_call_keys = set(self.call_keys) & self.format_keys
def format_item_json(self, item):
- return json.dumps(self.get_item_data(item), cls=BorgJsonEncoder) + '\n'
+ return json.dumps(self.get_item_data(item)) + '\n'
def add_key(self, key, callable_with_item):
self.call_keys[key] = callable_with_item
@@ -761,10 +768,15 @@ def hash_item(self, hash_function, item):
return hash.hexdigest()
def format_time(self, key, item):
- return OutputTimestamp(safe_timestamp(item.get(key) or item.mtime))
+ t = self.time(key, item)
+ return format_time(t)
+
+ def format_time_json(self, key, item):
+ t = self.time(key, item)
+ return isoformat_time(t)
- def format_iso_time(self, key, item):
- return self.format_time(key, item).isoformat()
+ def time(self, key, item):
+ return safe_timestamp(item.get(key) or item.mtime)
def file_status(mode):
@@ -875,8 +887,6 @@ def default(self, o):
return {
'stats': o.stats(),
}
- if callable(getattr(o, 'to_json', None)):
- return o.to_json()
return super().default(o)
@@ -889,7 +899,7 @@ def basic_json_data(manifest, *, cache=None, extra=None):
'mode': key.ARG_NAME,
},
})
- data['repository']['last_modified'] = OutputTimestamp(manifest.last_timestamp.replace(tzinfo=timezone.utc))
+ data['repository']['last_modified'] = isoformat_time(to_localtime(manifest.last_timestamp.replace(tzinfo=timezone.utc)))
if key.NAME.startswith('key file'):
data['encryption']['keyfile'] = key.find_key()
if cache:
diff --git a/src/borg/helpers/time.py b/src/borg/helpers/time.py
index 2d22794a..7203ba2f 100644
--- a/src/borg/helpers/time.py
+++ b/src/borg/helpers/time.py
@@ -86,19 +86,16 @@ def safe_timestamp(item_timestamp_ns):
return datetime.fromtimestamp(t_ns / 1e9)
-def format_time(ts: datetime):
+def format_time(t):
+ """use ISO-8601-like date and time format (human readable, with wkday and blank date/time separator)
"""
- Convert *ts* to a human-friendly format with textual weekday.
- """
- return ts.strftime('%a, %Y-%m-%d %H:%M:%S')
+ return t.strftime('%a, %Y-%m-%d %H:%M:%S')
-def isoformat_time(ts: datetime):
- """
- Format *ts* according to ISO 8601.
+def isoformat_time(t):
+ """use ISO-8601 date and time format (machine readable, no wkday, no microseconds either)
"""
- # note: first make all datetime objects tz aware before adding %z here.
- return ts.strftime('%Y-%m-%dT%H:%M:%S.%f')
+ return t.strftime('%Y-%m-%dT%H:%M:%S') # note: first make all datetime objects tz aware before adding %z here.
def format_timedelta(td):
@@ -116,21 +113,3 @@ def format_timedelta(td):
if td.days:
txt = '%d days %s' % (td.days, txt)
return txt
-
-
-class OutputTimestamp:
- def __init__(self, ts: datetime):
- if ts.tzinfo == timezone.utc:
- ts = to_localtime(ts)
- self.ts = ts
-
- def __format__(self, format_spec):
- return format_time(self.ts)
-
- def __str__(self):
- return '{}'.format(self)
-
- def isoformat(self):
- return isoformat_time(self.ts)
-
- to_json = isoformat
diff --git a/src/borg/item.pyx b/src/borg/item.pyx
index a8a21c04..f8b67ddd 100644
--- a/src/borg/item.pyx
+++ b/src/borg/item.pyx
@@ -5,7 +5,6 @@ from .constants import ITEM_KEYS
from .helpers import safe_encode, safe_decode
from .helpers import bigint_to_int, int_to_bigint
from .helpers import StableDict
-from .helpers import format_file_size
cdef extern from "_item.c":
object _object_to_optr(object obj)
@@ -185,22 +184,19 @@ class Item(PropDict):
part = PropDict._make_property('part', int)
- def get_size(self, hardlink_masters=None, memorize=False, compressed=False, from_chunks=False, consider_ids=None):
+ def get_size(self, hardlink_masters=None, memorize=False, compressed=False, from_chunks=False):
"""
Determine the (uncompressed or compressed) size of this item.
- :param hardlink_masters: If given, the size of hardlink slaves is computed via the hardlink master's chunk list,
- otherwise size will be returned as 0.
- :param memorize: Whether the computed size value will be stored into the item.
- :param compressed: Whether the compressed or uncompressed size will be returned.
- :param from_chunks: If true, size is computed from chunks even if a precomputed value is available.
- :param consider_ids: Returns the size of the given ids only.
+ For hardlink slaves, the size is computed via the hardlink master's
+ chunk list, if available (otherwise size will be returned as 0).
+
+ If memorize is True, the computed size value will be stored into the item.
"""
attr = 'csize' if compressed else 'size'
assert not (compressed and memorize), 'Item does not have a csize field.'
- assert not (consider_ids is not None and memorize), "Can't store size when considering only certain ids"
try:
- if from_chunks or consider_ids is not None:
+ if from_chunks:
raise AttributeError
size = getattr(self, attr)
except AttributeError:
@@ -230,10 +226,7 @@ class Item(PropDict):
chunks, _ = hardlink_masters.get(master, (None, None))
if chunks is None:
return 0
- if consider_ids is not None:
- size = sum(getattr(ChunkListEntry(*chunk), attr) for chunk in chunks if chunk.id in consider_ids)
- else:
- size = sum(getattr(ChunkListEntry(*chunk), attr) for chunk in chunks)
+ size = sum(getattr(ChunkListEntry(*chunk), attr) for chunk in chunks)
# if requested, memorize the precomputed (c)size for items that have an own chunks list:
if memorize and having_chunks:
setattr(self, attr, size)
@@ -258,21 +251,6 @@ class Item(PropDict):
def from_optr(self, optr):
return _optr_to_object(optr)
- @classmethod
- def create_deleted(cls, path):
- return cls(deleted=True, chunks=[], mode=0, path=path)
-
- def is_link(self):
- return self._is_type(stat.S_ISLNK)
-
- def is_dir(self):
- return self._is_type(stat.S_ISDIR)
-
- def _is_type(self, typetest):
- try:
- return typetest(self.mode)
- except AttributeError:
- return False
class EncryptedKey(PropDict):
@@ -380,140 +358,3 @@ class ManifestItem(PropDict):
timestamp = PropDict._make_property('timestamp', str, 'surrogate-escaped str', encode=safe_encode, decode=safe_decode)
config = PropDict._make_property('config', dict)
item_keys = PropDict._make_property('item_keys', tuple)
-
-class ItemDiff:
- """
- Comparison of two items from different archives.
-
- The items may have different paths and still be considered equal (e.g. for renames).
- It does not include extended or time attributes in the comparison.
- """
-
- def __init__(self, item1, item2, chunk_iterator1, chunk_iterator2, numeric_owner=False, can_compare_chunk_ids=False):
- self._item1 = item1
- self._item2 = item2
- self._numeric_owner = numeric_owner
- self._can_compare_chunk_ids = can_compare_chunk_ids
- self.equal = self._equal(chunk_iterator1, chunk_iterator2)
-
- def __repr__(self):
- if self.equal:
- return 'equal'
-
- changes = []
-
- if self._item1.is_link() or self._item2.is_link():
- changes.append(self._link_string())
-
- if 'chunks' in self._item1 and 'chunks' in self._item2:
- changes.append(self._content_string())
-
- if self._item1.is_dir() or self._item2.is_dir():
- changes.append(self._dir_string())
-
- if not (self._item1.get('deleted') or self._item2.get('deleted')):
- changes.append(self._owner_string())
- changes.append(self._mode_string())
-
- return ' '.join((x for x in changes if x))
-
- def _equal(self, chunk_iterator1, chunk_iterator2):
- # if both are deleted, there is nothing at path regardless of what was deleted
- if self._item1.get('deleted') and self._item2.get('deleted'):
- return True
-
- attr_list = ['deleted', 'mode', 'source']
- attr_list += ['uid', 'gid'] if self._numeric_owner else ['user', 'group']
- for attr in attr_list:
- if self._item1.get(attr) != self._item2.get(attr):
- return False
-
- if 'mode' in self._item1: # mode of item1 and item2 is equal
- if (self._item1.is_link() and 'source' in self._item1 and 'source' in self._item2
- and self._item1.source != self._item2.source):
- return False
-
- if 'chunks' in self._item1 and 'chunks' in self._item2:
- return self._content_equal(chunk_iterator1, chunk_iterator2)
-
- return True
-
- def _link_string(self):
- if self._item1.get('deleted'):
- return 'added link'
- if self._item2.get('deleted'):
- return 'removed link'
- if 'source' in self._item1 and 'source' in self._item2 and self._item1.source != self._item2.source:
- return 'changed link'
-
- def _content_string(self):
- if self._item1.get('deleted'):
- return ('added {:>13}'.format(format_file_size(self._item2.get_size())))
- if self._item2.get('deleted'):
- return ('removed {:>11}'.format(format_file_size(self._item1.get_size())))
- if not self._can_compare_chunk_ids:
- return 'modified'
- chunk_ids1 = {c.id for c in self._item1.chunks}
- chunk_ids2 = {c.id for c in self._item2.chunks}
- added_ids = chunk_ids2 - chunk_ids1
- removed_ids = chunk_ids1 - chunk_ids2
- added = self._item2.get_size(consider_ids=added_ids)
- removed = self._item1.get_size(consider_ids=removed_ids)
- return ('{:>9} {:>9}'.format(format_file_size(added, precision=1, sign=True),
- format_file_size(-removed, precision=1, sign=True)))
-
- def _dir_string(self):
- if self._item2.get('deleted') and not self._item1.get('deleted'):
- return 'removed directory'
- if self._item1.get('deleted') and not self._item2.get('deleted'):
- return 'added directory'
-
- def _owner_string(self):
- u_attr, g_attr = ('uid', 'gid') if self._numeric_owner else ('user', 'group')
- u1, g1 = self._item1.get(u_attr), self._item1.get(g_attr)
- u2, g2 = self._item2.get(u_attr), self._item2.get(g_attr)
- if (u1, g1) != (u2, g2):
- return '[{}:{} -> {}:{}]'.format(u1, g1, u2, g2)
-
- def _mode_string(self):
- if 'mode' in self._item1 and 'mode' in self._item2 and self._item1.mode != self._item2.mode:
- return '[{} -> {}]'.format(stat.filemode(self._item1.mode), stat.filemode(self._item2.mode))
-
- def _content_equal(self, chunk_iterator1, chunk_iterator2):
- if self._can_compare_chunk_ids:
- return self._item1.chunks == self._item2.chunks
- if self._item1.get_size() != self._item2.get_size():
- return False
- return ItemDiff._chunk_content_equal(chunk_iterator1, chunk_iterator2)
-
- @staticmethod
- def _chunk_content_equal(chunks1, chunks2):
- """
- Compare chunk content and return True if they are identical.
-
- The chunks must be given as chunk iterators (like returned by :meth:`.DownloadPipeline.fetch_many`).
- """
-
- end = object()
- alen = ai = 0
- blen = bi = 0
- while True:
- if not alen - ai:
- a = next(chunks1, end)
- if a is end:
- return not blen - bi and next(chunks2, end) is end
- a = memoryview(a)
- alen = len(a)
- ai = 0
- if not blen - bi:
- b = next(chunks2, end)
- if b is end:
- return not alen - ai and next(chunks1, end) is end
- b = memoryview(b)
- blen = len(b)
- bi = 0
- slicelen = min(alen - ai, blen - bi)
- if a[ai:ai + slicelen] != b[bi:bi + slicelen]:
- return False
- ai += slicelen
- bi += slicelen
| --timestamp time (vs list time)
The time set with `--timestamp` is the end time, whereas `list` shows the start time, e.g.:
```
$ borg create --timestamp 2017-01-01T00:00:00 ::foo bar
$ borg list
foo Sat, 2016-12-31 23:59:59
$ borg info ::foo
[...]
Time (start): Sat, 2016-12-31 23:59:59
Time (end): Sun, 2017-01-01 00:00:00
Command line: borg create --timestamp 2017-01-01T00:00:00 ::foo bar
[...]
```
Having a start and end time is weird with only a single timestamp given. But if current design should not be changed and the start time is considered the important one, that's what `--timestamp` should set. | borgbackup/borg | diff --git a/src/borg/testsuite/archiver.py b/src/borg/testsuite/archiver.py
index 947612a1..4de155be 100644
--- a/src/borg/testsuite/archiver.py
+++ b/src/borg/testsuite/archiver.py
@@ -47,7 +47,7 @@
from ..helpers import MAX_S
from ..nanorst import RstToTextLazy, rst_to_terminal
from ..patterns import IECommand, PatternMatcher, parse_pattern
-from ..item import Item, ItemDiff
+from ..item import Item
from ..logger import setup_logging
from ..remote import RemoteRepository, PathNotAllowed
from ..repository import Repository
@@ -61,7 +61,7 @@
src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
-ISO_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
+ISO_FORMAT = '%Y-%m-%dT%H:%M:%S'
def exec_cmd(*args, archiver=None, fork=False, exe=None, input=b'', binary_output=False, **kw):
@@ -1326,8 +1326,6 @@ def test_info_json(self):
assert isinstance(archive['duration'], float)
assert len(archive['id']) == 64
assert 'stats' in archive
- assert datetime.strptime(archive['start'], ISO_FORMAT)
- assert datetime.strptime(archive['end'], ISO_FORMAT)
def test_comment(self):
self.create_regular_file('file1', size=1024 * 80)
@@ -1790,7 +1788,7 @@ def test_list_format(self):
output_warn = self.cmd('list', '--list-format', '-', test_archive)
self.assert_in('--list-format" has been deprecated.', output_warn)
output_1 = self.cmd('list', test_archive)
- output_2 = self.cmd('list', '--format', '{mode} {user:6} {group:6} {size:8d} {mtime} {path}{extra}{NEWLINE}', test_archive)
+ output_2 = self.cmd('list', '--format', '{mode} {user:6} {group:6} {size:8d} {isomtime} {path}{extra}{NEWLINE}', test_archive)
output_3 = self.cmd('list', '--format', '{mtime:%s} {path}{NL}', test_archive)
self.assertEqual(output_1, output_2)
self.assertNotEqual(output_1, output_3)
@@ -1864,7 +1862,7 @@ def test_list_json(self):
file1 = items[1]
assert file1['path'] == 'input/file1'
assert file1['size'] == 81920
- assert datetime.strptime(file1['mtime'], ISO_FORMAT) # must not raise
+ assert datetime.strptime(file1['isomtime'], ISO_FORMAT) # must not raise
list_archive = self.cmd('list', '--json-lines', '--format={sha256}', self.repository_location + '::test')
items = [json.loads(s) for s in list_archive.splitlines()]
@@ -3432,12 +3430,12 @@ def test_get_args():
assert args.func == archiver.do_serve
-def test_chunk_content_equal():
+def test_compare_chunk_contents():
def ccc(a, b):
chunks_a = [data for data in a]
chunks_b = [data for data in b]
- compare1 = ItemDiff._chunk_content_equal(iter(chunks_a), iter(chunks_b))
- compare2 = ItemDiff._chunk_content_equal(iter(chunks_b), iter(chunks_a))
+ compare1 = Archiver.compare_chunk_contents(iter(chunks_a), iter(chunks_b))
+ compare2 = Archiver.compare_chunk_contents(iter(chunks_b), iter(chunks_a))
assert compare1 == compare2
return compare1
assert ccc([
| {
"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": 3
},
"num_modified_files": 10
} | 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": [
"apt-get update",
"apt-get install -y gcc pkg-config build-essential libssl-dev libacl1-dev libxxhash-dev liblz4-dev libzstd-dev"
],
"python": "3.9",
"reqs_path": [
"requirements.d/development.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/borgbackup/borg.git@e9b892feb5107fc407e2913a8d1b6fa16165efd7#egg=borgbackup
cachetools==5.5.2
chardet==5.2.0
colorama==0.4.6
coverage==7.8.0
Cython==3.0.12
distlib==0.3.9
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
iniconfig==2.1.0
msgpack-python==0.5.6
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
py-cpuinfo==9.0.0
pyproject-api==1.9.0
pytest==8.3.5
pytest-benchmark==5.1.0
pytest-cov==6.0.0
pytest-xdist==3.6.1
pyzmq==26.3.0
setuptools-scm==8.2.0
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
virtualenv==20.29.3
| name: borg
channels:
- defaults
- https://repo.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
- cython==3.0.12
- distlib==0.3.9
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- iniconfig==2.1.0
- msgpack-python==0.5.6
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- py-cpuinfo==9.0.0
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-benchmark==5.1.0
- pytest-cov==6.0.0
- pytest-xdist==3.6.1
- pyzmq==26.3.0
- setuptools-scm==8.2.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- virtualenv==20.29.3
prefix: /opt/conda/envs/borg
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::test_compare_chunk_contents"
]
| [
"src/borg/testsuite/archiver.py::test_return_codes[python]",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_check_usage",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_corrupted_manifest",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_corrupted_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_file_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_manifest",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable2",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_not_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_path",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_repository",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_chunks",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_files",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_chunks_archive",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_old_version_interfered",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_sort_option"
]
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_put_get_delete_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_attic013_acl_bug",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_empty_repository",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_extra_chunks",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_duplicate_archive",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_item_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_metadata",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data_unencrypted",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_fresh_init_tam_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_doesnt_leak",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::test_get_args",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_basic",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_empty",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_strip_components",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_simple",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-both]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-both]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--no-files-cache-no_files_cache-False-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--no-files-cache-no_files_cache-False-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--no-files-cache-no_files_cache-False-both]",
"src/borg/testsuite/archiver.py::test_parse_storage_quota",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark-parser1]",
"src/borg/testsuite/archiver.py::test_help_formatting[break-lock-parser2]",
"src/borg/testsuite/archiver.py::test_help_formatting[change-passphrase-parser3]",
"src/borg/testsuite/archiver.py::test_help_formatting[check-parser4]",
"src/borg/testsuite/archiver.py::test_help_formatting[create-parser5]",
"src/borg/testsuite/archiver.py::test_help_formatting[debug",
"src/borg/testsuite/archiver.py::test_help_formatting[debug-parser16]",
"src/borg/testsuite/archiver.py::test_help_formatting[delete-parser17]",
"src/borg/testsuite/archiver.py::test_help_formatting[diff-parser18]",
"src/borg/testsuite/archiver.py::test_help_formatting[export-tar-parser19]",
"src/borg/testsuite/archiver.py::test_help_formatting[extract-parser20]",
"src/borg/testsuite/archiver.py::test_help_formatting[help-parser21]",
"src/borg/testsuite/archiver.py::test_help_formatting[info-parser22]",
"src/borg/testsuite/archiver.py::test_help_formatting[init-parser23]",
"src/borg/testsuite/archiver.py::test_help_formatting[key",
"src/borg/testsuite/archiver.py::test_help_formatting[key-parser28]",
"src/borg/testsuite/archiver.py::test_help_formatting[list-parser29]",
"src/borg/testsuite/archiver.py::test_help_formatting[mount-parser30]",
"src/borg/testsuite/archiver.py::test_help_formatting[prune-parser31]",
"src/borg/testsuite/archiver.py::test_help_formatting[recreate-parser32]",
"src/borg/testsuite/archiver.py::test_help_formatting[rename-parser33]",
"src/borg/testsuite/archiver.py::test_help_formatting[serve-parser34]",
"src/borg/testsuite/archiver.py::test_help_formatting[umount-parser35]",
"src/borg/testsuite/archiver.py::test_help_formatting[upgrade-parser36]",
"src/borg/testsuite/archiver.py::test_help_formatting[with-lock-parser37]",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[patterns-\\nFile",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[placeholders-\\nRepository",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[compression-\\nIt"
]
| []
| BSD License | 1,618 | [
"src/borg/archive.py",
"src/borg/helpers/time.py",
"src/borg/helpers/parseformat.py",
"src/borg/item.pyx",
"docs/development.rst",
"docs/internals/frontends.rst",
"docs/changes.rst",
"docs/internals/data-structures.rst",
"src/borg/archiver.py",
"src/borg/cache.py"
]
| [
"src/borg/archive.py",
"src/borg/helpers/time.py",
"src/borg/helpers/parseformat.py",
"src/borg/item.pyx",
"docs/development.rst",
"docs/internals/frontends.rst",
"docs/changes.rst",
"docs/internals/data-structures.rst",
"src/borg/archiver.py",
"src/borg/cache.py"
]
|
|
jupyter__nbgrader-873 | 9822e38532e0c5a31a26316a16d539d51324c424 | 2017-08-24 19:18:13 | 5bc6f37c39c8b10b8f60440b2e6d9487e63ef3f1 | jhamrick: Turns out this fix is not actually correct, though. That's what I get for submitting a PR without running all the tests locally... | diff --git a/nbgrader/api.py b/nbgrader/api.py
index cb9b552b..6c79aabc 100644
--- a/nbgrader/api.py
+++ b/nbgrader/api.py
@@ -2318,7 +2318,8 @@ class Gradebook(object):
A list of dictionaries, one per student
"""
- if len(self.assignments) > 0:
+ total_score, = self.db.query(func.sum(Assignment.max_score)).one()
+ if len(self.assignments) > 0 and total_score > 0:
# subquery the scores
scores = self.db.query(
Student.id,
@@ -2332,7 +2333,7 @@ class Gradebook(object):
students = self.db.query(
Student.id, Student.first_name, Student.last_name,
Student.email, _scores,
- func.sum(GradeCell.max_score)
+ func.sum(Assignment.max_score)
).outerjoin(scores, Student.id == scores.c.id)\
.group_by(
Student.id, Student.first_name, Student.last_name,
| Error generating assignment and managing students
Firstly, I apologize if this is not the proper place to report issues like this. I am exploring nbgrader, and have had some trouble getting it to work.
I have installed nbgrader on a local Jupyterhub installation and have been working through the example notebooks.
I had to create a `~/.jupyter/nbgrader_config.py` file that has the following contents:
```
c = get_config()
c.CourseDirectory.root = '~/Jupyter/ChEn6703_test_nbgrader'
```
(note that I used the full path above, but replaced the prefix with `~` for security reasons)
There are a few strange things going on though:
## Problems with student entries
1. When I go to the `Manage Students` section of nbgrader, it doesn't show any students.
1. When I do `nbgrader db student list --log-level='DEBUG'` I get something which is inconsistent with the empty list in the `Manage Students` dialog.
```
[DbStudentListApp | DEBUG] Searching ['~/Jupyter/ChEn6703_test_nbgrader', '~/.jupyter', '/usr/etc/jupyter', '/usr/local/etc/jupyter', '/etc/jupyter'] for config files
[DbStudentListApp | DEBUG] Looking for jupyter_config in /etc/jupyter
[DbStudentListApp | DEBUG] Looking for jupyter_config in /usr/local/etc/jupyter
[DbStudentListApp | DEBUG] Looking for jupyter_config in /usr/etc/jupyter
[DbStudentListApp | DEBUG] Looking for jupyter_config in ~/.jupyter
[DbStudentListApp | DEBUG] Looking for jupyter_config in ~/Jupyter/ChEn6703_test_nbgrader
[DbStudentListApp | DEBUG] Looking for nbgrader_config in /etc/jupyter
[DbStudentListApp | DEBUG] Looking for nbgrader_config in /usr/local/etc/jupyter
[DbStudentListApp | DEBUG] Looking for nbgrader_config in /usr/etc/jupyter
[DbStudentListApp | DEBUG] Looking for nbgrader_config in ~/.jupyter
[DbStudentListApp | DEBUG] Loaded config file: ~/.jupyter/nbgrader_config.py
[DbStudentListApp | DEBUG] Looking for nbgrader_config in ~/Jupyter/ChEn6703_test_nbgrader
[DbStudentListApp | DEBUG] Loaded config file: ~/Jupyter/ChEn6703_test_nbgrader/nbgrader_conf
ig.py
[DbStudentListApp | DEBUG] Looking for nbgrader_config in ~/Jupyter/ChEn6703_test_nbgrader
[DbStudentListApp | DEBUG] Loaded config file: ~/Jupyter/ChEn6703_test_nbgrader/nbgrader_conf
ig.py
There are 1 students in the database:
1 (Flinstone, Fred) -- None
```
3. If I manually enter a student in the `Manage Students` dialog, the student shows up and then disappears.
## Problems when generating the assignment
When I go to `Manage Assignments` and click on the `Generate` icon for the example `ps1` assignment, I get:
```
[INFO] Copying ~/Jupyter/ChEn6703_test_nbgrader/source/./ps1/jupyter.png -> ~/Jupyter/ChEn6703_test_nbgrader/release/./ps1/jupyter.png
[INFO] Updating/creating assignment 'ps1': {}
[INFO] Converting notebook ~/Jupyter/ChEn6703_test_nbgrader/source/./ps1/problem1.ipynb
[ERROR] There was an error processing assignment: ~/Jupyter/ChEn6703_test_nbgrader/source/./ps1
[ERROR] Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/nbgrader/converters/base.py", line 288, in convert_notebooks
self.convert_single_notebook(notebook_filename)
File "/usr/local/lib/python3.5/dist-packages/nbgrader/converters/base.py", line 244, in convert_single_notebook
output, resources = self.exporter.from_filename(notebook_filename, resources=resources)
File "/usr/local/lib/python3.5/dist-packages/nbconvert/exporters/exporter.py", line 172, in from_filename
return self.from_file(f, resources=resources, **kw)
File "/usr/local/lib/python3.5/dist-packages/nbconvert/exporters/exporter.py", line 190, in from_file
return self.from_notebook_node(nbformat.read(file_stream, as_version=4), resources=resources, **kw)
File "/usr/local/lib/python3.5/dist-packages/nbconvert/exporters/notebook.py", line 31, in from_notebook_node
nb_copy, resources = super(NotebookExporter, self).from_notebook_node(nb, resources, **kw)
File "/usr/local/lib/python3.5/dist-packages/nbconvert/exporters/exporter.py", line 132, in from_notebook_node
nb_copy, resources = self._preprocess(nb_copy, resources)
File "/usr/local/lib/python3.5/dist-packages/nbconvert/exporters/exporter.py", line 309, in _preprocess
nbc, resc = preprocessor(nbc, resc)
File "/usr/local/lib/python3.5/dist-packages/nbconvert/preprocessors/base.py", line 47, in __call__
return self.preprocess(nb,resources)
File "/usr/local/lib/python3.5/dist-packages/nbgrader/preprocessors/headerfooter.py", line 23, in preprocess
with open(self.header, 'r') as fh:
FileNotFoundError: [Errno 2] No such file or directory: 'source/header.ipynb'
[WARNING] Removing failed assignment: ~/Jupyter/ChEn6703_test_nbgrader/release/ps1
[ERROR] There was an error processing assignment 'ps1' for student '.'
[ERROR] Please see the the above traceback for details on the specific errors on the above failures.
Traceback
```
I have tried regenerating the entire class and this issue persists.
If I try the command line approach: `nbgrader assign source/ps1/` I get:
```
[AssignApp | ERROR] No notebooks were matched by ~/Jupyter/ChEn6703_test_nbgrader/source/./s
```
Note the `source/./s` which seems problematic.
Any ideas on this? | jupyter/nbgrader | diff --git a/nbgrader/tests/api/test_gradebook.py b/nbgrader/tests/api/test_gradebook.py
index 361a4def..69c181d1 100644
--- a/nbgrader/tests/api/test_gradebook.py
+++ b/nbgrader/tests/api/test_gradebook.py
@@ -728,6 +728,12 @@ def test_student_dicts(assignment):
assert a == b
+def test_student_dicts_zero_points(gradebook):
+ gradebook.add_assignment("ps1")
+ s = gradebook.add_student("1234")
+ assert gradebook.student_dicts() == [s.to_dict()]
+
+
def test_notebook_submission_dicts(assignment):
assignment.add_student('hacker123')
assignment.add_student('bitdiddle')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_media"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 1
} | 0.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov pytest-rerunfailures coverage selenium invoke sphinx codecov cov-core",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"dev-requirements.txt",
"dev-requirements-windows.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
alembic==1.7.7
anyio==3.6.2
argon2-cffi==21.3.0
argon2-cffi-bindings==21.2.0
async-generator==1.10
attrs==22.2.0
Babel==2.11.0
backcall==0.2.0
bleach==4.1.0
certifi==2021.5.30
cffi==1.15.1
charset-normalizer==2.0.12
codecov==2.1.13
comm==0.1.4
contextvars==2.4
cov-core==1.15.0
coverage==6.2
dataclasses==0.8
decorator==5.1.1
defusedxml==0.7.1
docutils==0.18.1
entrypoints==0.4
greenlet==2.0.2
idna==3.10
imagesize==1.4.1
immutables==0.19
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
invoke==2.2.0
ipykernel==5.5.6
ipython==7.16.3
ipython-genutils==0.2.0
ipywidgets==7.8.5
jedi==0.17.2
Jinja2==3.0.3
json5==0.9.16
jsonschema==3.2.0
jupyter==1.1.1
jupyter-client==7.1.2
jupyter-console==6.4.3
jupyter-core==4.9.2
jupyter-server==1.13.1
jupyterlab==3.2.9
jupyterlab-pygments==0.1.2
jupyterlab-server==2.10.3
jupyterlab_widgets==1.1.11
Mako==1.1.6
MarkupSafe==2.0.1
mistune==0.8.4
nbclassic==0.3.5
nbclient==0.5.9
nbconvert==6.0.7
nbformat==5.1.3
-e git+https://github.com/jupyter/nbgrader.git@9822e38532e0c5a31a26316a16d539d51324c424#egg=nbgrader
nest-asyncio==1.6.0
notebook==6.4.10
packaging==21.3
pandocfilters==1.5.1
parso==0.7.1
pexpect==4.9.0
pickleshare==0.7.5
pluggy==1.0.0
prometheus-client==0.17.1
prompt-toolkit==3.0.36
ptyprocess==0.7.0
py==1.11.0
pycparser==2.21
pyenchant==3.2.2
Pygments==2.14.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
pytest-cov==4.0.0
pytest-rerunfailures==10.3
python-dateutil==2.9.0.post0
pytz==2025.2
pyzmq==25.1.2
requests==2.27.1
selenium==3.141.0
Send2Trash==1.8.3
six==1.17.0
sniffio==1.2.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-rtd-theme==2.0.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
sphinxcontrib-spelling==7.7.0
SQLAlchemy==1.4.54
terminado==0.12.1
testpath==0.6.0
tomli==1.2.3
tornado==6.1
traitlets==4.3.3
typing_extensions==4.1.1
urllib3==1.26.20
wcwidth==0.2.13
webencodings==0.5.1
websocket-client==1.3.1
widgetsnbextension==3.6.10
zipp==3.6.0
| name: nbgrader
channels:
- defaults
- https://repo.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
- alembic==1.7.7
- anyio==3.6.2
- argon2-cffi==21.3.0
- argon2-cffi-bindings==21.2.0
- async-generator==1.10
- attrs==22.2.0
- babel==2.11.0
- backcall==0.2.0
- bleach==4.1.0
- cffi==1.15.1
- charset-normalizer==2.0.12
- codecov==2.1.13
- comm==0.1.4
- contextvars==2.4
- cov-core==1.15.0
- coverage==6.2
- dataclasses==0.8
- decorator==5.1.1
- defusedxml==0.7.1
- docutils==0.18.1
- entrypoints==0.4
- greenlet==2.0.2
- idna==3.10
- imagesize==1.4.1
- immutables==0.19
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- invoke==2.2.0
- ipykernel==5.5.6
- ipython==7.16.3
- ipython-genutils==0.2.0
- ipywidgets==7.8.5
- jedi==0.17.2
- jinja2==3.0.3
- json5==0.9.16
- jsonschema==3.2.0
- jupyter==1.1.1
- jupyter-client==7.1.2
- jupyter-console==6.4.3
- jupyter-core==4.9.2
- jupyter-server==1.13.1
- jupyterlab==3.2.9
- jupyterlab-pygments==0.1.2
- jupyterlab-server==2.10.3
- jupyterlab-widgets==1.1.11
- mako==1.1.6
- markupsafe==2.0.1
- mistune==0.8.4
- nbclassic==0.3.5
- nbclient==0.5.9
- nbconvert==6.0.7
- nbformat==5.1.3
- nest-asyncio==1.6.0
- notebook==6.4.10
- packaging==21.3
- pandocfilters==1.5.1
- parso==0.7.1
- pexpect==4.9.0
- pickleshare==0.7.5
- pluggy==1.0.0
- prometheus-client==0.17.1
- prompt-toolkit==3.0.36
- ptyprocess==0.7.0
- py==1.11.0
- pycparser==2.21
- pyenchant==3.2.2
- pygments==2.14.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-rerunfailures==10.3
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyzmq==25.1.2
- requests==2.27.1
- selenium==3.141.0
- send2trash==1.8.3
- six==1.17.0
- sniffio==1.2.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-rtd-theme==2.0.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- sphinxcontrib-spelling==7.7.0
- sqlalchemy==1.4.54
- terminado==0.12.1
- testpath==0.6.0
- tomli==1.2.3
- tornado==6.1
- traitlets==4.3.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- wcwidth==0.2.13
- webencodings==0.5.1
- websocket-client==1.3.1
- widgetsnbextension==3.6.10
- zipp==3.6.0
prefix: /opt/conda/envs/nbgrader
| [
"nbgrader/tests/api/test_gradebook.py::test_student_dicts_zero_points"
]
| [
"nbgrader/tests/api/test_gradebook.py::test_create_invalid_grade_cell",
"nbgrader/tests/api/test_gradebook.py::test_create_invalid_source_cell",
"nbgrader/tests/api/test_gradebook.py::test_notebook_submission_dicts",
"nbgrader/tests/api/test_gradebook.py::test_submission_dicts"
]
| [
"nbgrader/tests/api/test_gradebook.py::test_init",
"nbgrader/tests/api/test_gradebook.py::test_add_student",
"nbgrader/tests/api/test_gradebook.py::test_add_duplicate_student",
"nbgrader/tests/api/test_gradebook.py::test_find_student",
"nbgrader/tests/api/test_gradebook.py::test_find_nonexistant_student",
"nbgrader/tests/api/test_gradebook.py::test_remove_student",
"nbgrader/tests/api/test_gradebook.py::test_update_or_create_student",
"nbgrader/tests/api/test_gradebook.py::test_add_assignment",
"nbgrader/tests/api/test_gradebook.py::test_add_duplicate_assignment",
"nbgrader/tests/api/test_gradebook.py::test_find_assignment",
"nbgrader/tests/api/test_gradebook.py::test_find_nonexistant_assignment",
"nbgrader/tests/api/test_gradebook.py::test_remove_assignment",
"nbgrader/tests/api/test_gradebook.py::test_update_or_create_assignment",
"nbgrader/tests/api/test_gradebook.py::test_add_notebook",
"nbgrader/tests/api/test_gradebook.py::test_add_duplicate_notebook",
"nbgrader/tests/api/test_gradebook.py::test_find_notebook",
"nbgrader/tests/api/test_gradebook.py::test_find_nonexistant_notebook",
"nbgrader/tests/api/test_gradebook.py::test_update_or_create_notebook",
"nbgrader/tests/api/test_gradebook.py::test_remove_notebook",
"nbgrader/tests/api/test_gradebook.py::test_add_grade_cell",
"nbgrader/tests/api/test_gradebook.py::test_add_grade_cell_with_args",
"nbgrader/tests/api/test_gradebook.py::test_add_duplicate_grade_cell",
"nbgrader/tests/api/test_gradebook.py::test_find_grade_cell",
"nbgrader/tests/api/test_gradebook.py::test_find_nonexistant_grade_cell",
"nbgrader/tests/api/test_gradebook.py::test_update_or_create_grade_cell",
"nbgrader/tests/api/test_gradebook.py::test_add_solution_cell",
"nbgrader/tests/api/test_gradebook.py::test_add_duplicate_solution_cell",
"nbgrader/tests/api/test_gradebook.py::test_find_solution_cell",
"nbgrader/tests/api/test_gradebook.py::test_find_nonexistant_solution_cell",
"nbgrader/tests/api/test_gradebook.py::test_update_or_create_solution_cell",
"nbgrader/tests/api/test_gradebook.py::test_add_source_cell",
"nbgrader/tests/api/test_gradebook.py::test_add_source_cell_with_args",
"nbgrader/tests/api/test_gradebook.py::test_add_duplicate_source_cell",
"nbgrader/tests/api/test_gradebook.py::test_find_source_cell",
"nbgrader/tests/api/test_gradebook.py::test_find_nonexistant_source_cell",
"nbgrader/tests/api/test_gradebook.py::test_update_or_create_source_cell",
"nbgrader/tests/api/test_gradebook.py::test_add_submission",
"nbgrader/tests/api/test_gradebook.py::test_add_duplicate_submission",
"nbgrader/tests/api/test_gradebook.py::test_remove_submission",
"nbgrader/tests/api/test_gradebook.py::test_update_or_create_submission",
"nbgrader/tests/api/test_gradebook.py::test_find_submission_notebook",
"nbgrader/tests/api/test_gradebook.py::test_find_submission_notebook_by_id",
"nbgrader/tests/api/test_gradebook.py::test_remove_submission_notebook",
"nbgrader/tests/api/test_gradebook.py::test_find_grade",
"nbgrader/tests/api/test_gradebook.py::test_find_grade_by_id",
"nbgrader/tests/api/test_gradebook.py::test_find_comment",
"nbgrader/tests/api/test_gradebook.py::test_find_comment_by_id",
"nbgrader/tests/api/test_gradebook.py::test_average_assignment_score",
"nbgrader/tests/api/test_gradebook.py::test_average_notebook_score",
"nbgrader/tests/api/test_gradebook.py::test_student_dicts"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,619 | [
"nbgrader/api.py"
]
| [
"nbgrader/api.py"
]
|
google__mobly-323 | 1493710b2fa167349303bc6710dda042dae0b895 | 2017-08-24 20:07:58 | 7e5e62af4ab4537bf619f0ee403c05f004c5baf0 | dthkao:
Review status: 0 of 2 files reviewed at latest revision, 3 unresolved discussions.
---
*[mobly/base_test.py, line 321 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsW8dICenAvZlCo5EPy:-KsW8dICenAvZlCo5EPz:bc0xqwv) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/mobly/base_test.py#L321)):*
> ```Python
> # will not be modified.
> func(copy.deepcopy(tr_record))
> except (signals.TestAbortAll, signals.TestAbortClass):
> ```
How about having one of these subclass the other or both of them subclassing from something like `signals.TestAbort`. It seems their handling is often very similar.
---
*[mobly/base_test.py, line 349 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsW89wWCGfYzGYozVN4:-KsW89wWCGfYzGYozVN5:b-pgdkr0) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/mobly/base_test.py#L349)):*
> ```Python
> try:
> self._setup_test(test_name)
> except (signals.TestAbortAll, signals.TestAbortClass):
> ```
Why is this needed? Wouldn't they be raised anyway?
---
*[mobly/base_test.py, line 368 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsW8_r_xwSxCOA91u5X:-KsW8_r_xwSxCOA91u5Y:bxthl54) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/mobly/base_test.py#L368)):*
> ```Python
> try:
> self._teardown_test(test_name)
> except signals.TestAbortAll:
> ```
Does this need the same treatment?
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/323)*
<!-- Sent from Reviewable.io -->
k2fong:
Review status: 0 of 2 files reviewed at latest revision, 4 unresolved discussions.
---
*[tests/mobly/base_test_test.py, line 780 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsLbUjtTowbfMVKVkYq:-KsLbUjuEJrAru-PfJfg:bbi2jmz) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/tests/mobly/base_test_test.py#L780)):*
> ```Python
> bt_cls.run(test_names=["test_1", "test_2", "test_3"])
> self.assertEqual(len(bt_cls.results.skipped), 2)
> self.assertEqual(bt_cls.results.summary_str(),
> ```
consider asserting on values from bt_cls.summary_dict() instead or similar len comparison above on the other summary results. plus 'skipped' check is redundant and test will be more susceptible to format changes.
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/323)*
<!-- Sent from Reviewable.io -->
xpconanfan:
Review status: 0 of 2 files reviewed at latest revision, 4 unresolved discussions.
---
*[mobly/base_test.py, line 321 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsW8dICenAvZlCo5EPy:-KsfESx857NKFKpEj7F0:b-896fix) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/mobly/base_test.py#L321)):*
<details><summary><i>Previously, dthkao (David T.H. Kao) wrote…</i></summary><blockquote>
How about having one of these subclass the other or both of them subclassing from something like `signals.TestAbort`. It seems their handling is often very similar.
</blockquote></details>
Done.
---
*[mobly/base_test.py, line 349 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsW89wWCGfYzGYozVN4:-Ksf7OVznst44Y5kUKvg:b-7xle7c) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/mobly/base_test.py#L349)):*
<details><summary><i>Previously, dthkao (David T.H. Kao) wrote…</i></summary><blockquote>
Why is this needed? Wouldn't they be raised anyway?
</blockquote></details>
So they don't fall to the next `except` and get converted to TestError.
---
*[mobly/base_test.py, line 368 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsW8_r_xwSxCOA91u5X:-KsfERkA9Kclo_q7SjRj:b-896fix) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/mobly/base_test.py#L368)):*
<details><summary><i>Previously, dthkao (David T.H. Kao) wrote…</i></summary><blockquote>
Does this need the same treatment?
</blockquote></details>
Done.
---
*[tests/mobly/base_test_test.py, line 780 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsLbUjtTowbfMVKVkYq:-Ksf73Vo1RhZ2v9ji8if:b-1fg0vl) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/tests/mobly/base_test_test.py#L780)):*
<details><summary><i>Previously, k2fong wrote…</i></summary><blockquote>
consider asserting on values from bt_cls.summary_dict() instead or similar len comparison above on the other summary results. plus 'skipped' check is redundant and test will be more susceptible to format changes.
</blockquote></details>
We specifically chose to verify this string as it is user-facing.
Since the string has all the info, we don't need a separate check for the dict.
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/323)*
<!-- Sent from Reviewable.io -->
dthkao:
Review status: 0 of 3 files reviewed at latest revision, 4 unresolved discussions.
---
*[mobly/base_test.py, line 349 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsW89wWCGfYzGYozVN4:-KsgL-Sv8l0YmluAy2mm:bit11dr) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/mobly/base_test.py#L349)):*
<details><summary><i>Previously, xpconanfan (Ang Li) wrote…</i></summary><blockquote>
So they don't fall to the next `except` and get converted to TestError.
</blockquote></details>
The next except only catches TestFailure though?
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/323)*
<!-- Sent from Reviewable.io -->
k2fong:
Review status: 0 of 3 files reviewed at latest revision, 4 unresolved discussions.
---
*[tests/mobly/base_test_test.py, line 780 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsLbUjtTowbfMVKVkYq:-KsioSRefUXtm5KaI4Rf:b-wtk41s) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/tests/mobly/base_test_test.py#L780)):*
<details><summary><i>Previously, xpconanfan (Ang Li) wrote…</i></summary><blockquote>
We specifically chose to verify this string as it is user-facing.
Since the string has all the info, we don't need a separate check for the dict.
</blockquote></details>
If that's the case, it will seem like verification for this summary string should be its own test that properly test out the various values reported from this summary string (if it doesn't exist already). But probably outside the scope of this review.
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/323)*
<!-- Sent from Reviewable.io -->
xpconanfan:
Review status: 0 of 3 files reviewed at latest revision, 4 unresolved discussions.
---
*[mobly/base_test.py, line 349 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsW89wWCGfYzGYozVN4:-KsivUyUSfXVYTMfozsQ:b31vzk8) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/mobly/base_test.py#L349)):*
<details><summary><i>Previously, dthkao (David T.H. Kao) wrote…</i></summary><blockquote>
The next except only catches TestFailure though?
</blockquote></details>
Done.
Oops, somehow I thought it was TestSignal...
---
*[tests/mobly/base_test_test.py, line 780 at r1](https://reviewable.io:443/reviews/google/mobly/323#-KsLbUjtTowbfMVKVkYq:-KsivZ92ZwohGN6R-Jzq:bvadmfs) ([raw file](https://github.com/google/mobly/blob/4fb6d1a9cee058cf24bf5a7c8d76f355862f0388/tests/mobly/base_test_test.py#L780)):*
<details><summary><i>Previously, k2fong wrote…</i></summary><blockquote>
If that's the case, it will seem like verification for this summary string should be its own test that properly test out the various values reported from this summary string (if it doesn't exist already). But probably outside the scope of this review.
</blockquote></details>
No, each test expects a different summaryve string with different info.
It's a lot easier to just verify the final product than each field every time here in `base_test_test`.
We have per-field checks in `record_test`.
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/323)*
<!-- Sent from Reviewable.io -->
| diff --git a/mobly/controllers/android_device.py b/mobly/controllers/android_device.py
index 2be180b..5d7027e 100644
--- a/mobly/controllers/android_device.py
+++ b/mobly/controllers/android_device.py
@@ -725,7 +725,17 @@ class AndroidDevice(object):
' "%s".' % (package, client_name))
client = snippet_client.SnippetClient(
package=package, adb_proxy=self.adb, log=self.log)
- client.start_app_and_connect()
+ try:
+ client.start_app_and_connect()
+ except Exception as e:
+ # If errors happen, make sure we clean up before raising.
+ try:
+ client.stop_app()
+ except:
+ self.log.exception(
+ 'Failed to stop app after failure to launch.')
+ # Raise the error from start app failure.
+ raise e
self._snippet_clients[name] = client
setattr(self, name, client)
diff --git a/mobly/signals.py b/mobly/signals.py
index 85bdc30..e367a8f 100644
--- a/mobly/signals.py
+++ b/mobly/signals.py
@@ -62,13 +62,18 @@ class TestSkip(TestSignal):
"""Raised when a test has been skipped."""
-class TestAbortClass(TestSignal):
+class TestAbortSignal(TestSignal):
+ """Base class for abort signals.
+ """
+
+
+class TestAbortClass(TestAbortSignal):
"""Raised when all subsequent tests within the same test class should
be aborted.
"""
-class TestAbortAll(TestSignal):
+class TestAbortAll(TestAbortSignal):
"""Raised when all subsequent tests should be aborted."""
| `signals.TestAbortClass` does not work in `setup_test` and `on_xxxx` methods
It is valid to abort the class at any stage of a test.
E.g. If we find out in `on_fail` that a test failed due to a fatal error like snippet_client losing socket connection, it is reasonable for the test to abort all subsequent tests in the class instead of continue running and failing more tests when we know they will fail. | google/mobly | diff --git a/mobly/base_test.py b/mobly/base_test.py
index 0c540a5..24290de 100644
--- a/mobly/base_test.py
+++ b/mobly/base_test.py
@@ -318,7 +318,7 @@ class BaseTestClass(object):
# Pass a copy of the record instead of the actual object so that it
# will not be modified.
func(copy.deepcopy(tr_record))
- except signals.TestAbortAll:
+ except signals.TestAbortSignal:
raise
except Exception as e:
logging.exception('Exception happened when executing %s for %s.',
@@ -363,7 +363,7 @@ class BaseTestClass(object):
finally:
try:
self._teardown_test(test_name)
- except signals.TestAbortAll:
+ except signals.TestAbortSignal:
raise
except Exception as e:
logging.exception(e)
@@ -374,7 +374,7 @@ class BaseTestClass(object):
except signals.TestSkip as e:
# Test skipped.
tr_record.test_skip(e)
- except (signals.TestAbortClass, signals.TestAbortAll) as e:
+ except signals.TestAbortSignal as e:
# Abort signals, pass along.
tr_record.test_fail(e)
raise e
@@ -389,17 +389,20 @@ class BaseTestClass(object):
tr_record.test_pass()
finally:
tr_record.update_record()
- if tr_record.result in (records.TestResultEnums.TEST_RESULT_ERROR,
- records.TestResultEnums.TEST_RESULT_FAIL):
- self._exec_procedure_func(self._on_fail, tr_record)
- elif tr_record.result == records.TestResultEnums.TEST_RESULT_PASS:
- self._exec_procedure_func(self._on_pass, tr_record)
- elif tr_record.result == records.TestResultEnums.TEST_RESULT_SKIP:
- self._exec_procedure_func(self._on_skip, tr_record)
- self.results.add_record(tr_record)
- self.summary_writer.dump(tr_record.to_dict(),
- records.TestSummaryEntryType.RECORD)
- self.current_test_name = None
+ try:
+ if tr_record.result in (
+ records.TestResultEnums.TEST_RESULT_ERROR,
+ records.TestResultEnums.TEST_RESULT_FAIL):
+ self._exec_procedure_func(self._on_fail, tr_record)
+ elif tr_record.result == records.TestResultEnums.TEST_RESULT_PASS:
+ self._exec_procedure_func(self._on_pass, tr_record)
+ elif tr_record.result == records.TestResultEnums.TEST_RESULT_SKIP:
+ self._exec_procedure_func(self._on_skip, tr_record)
+ finally:
+ self.results.add_record(tr_record)
+ self.summary_writer.dump(tr_record.to_dict(),
+ records.TestSummaryEntryType.RECORD)
+ self.current_test_name = None
def _assert_function_name_in_stack(self, expected_func_name):
"""Asserts that the current stack contains the given function name."""
@@ -577,7 +580,7 @@ class BaseTestClass(object):
# Setup for the class.
try:
self._setup_class()
- except signals.TestAbortClass as e:
+ except signals.TestAbortSignal as e:
# The test class is intentionally aborted.
# Skip all tests peacefully.
e.details = 'setup_class aborted due to: %s' % e.details
diff --git a/tests/mobly/base_test_test.py b/tests/mobly/base_test_test.py
index d615f3f..29781af 100755
--- a/tests/mobly/base_test_test.py
+++ b/tests/mobly/base_test_test.py
@@ -739,6 +739,48 @@ class BaseTestTest(unittest.TestCase):
("Error 0, Executed 0, Failed 0, Passed 0, "
"Requested 3, Skipped 3"))
+ def test_abort_class_in_setup_test(self):
+ class MockBaseTest(base_test.BaseTestClass):
+ def setup_test(self):
+ asserts.abort_class(MSG_EXPECTED_EXCEPTION)
+
+ def test_1(self):
+ never_call()
+
+ def test_2(self):
+ never_call()
+
+ def test_3(self):
+ never_call()
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.run(test_names=["test_1", "test_2", "test_3"])
+ self.assertEqual(len(bt_cls.results.skipped), 2)
+ self.assertEqual(bt_cls.results.summary_str(),
+ ("Error 0, Executed 1, Failed 1, Passed 0, "
+ "Requested 3, Skipped 2"))
+
+ def test_abort_class_in_on_fail(self):
+ class MockBaseTest(base_test.BaseTestClass):
+ def test_1(self):
+ asserts.fail(MSG_EXPECTED_EXCEPTION)
+
+ def test_2(self):
+ never_call()
+
+ def test_3(self):
+ never_call()
+
+ def on_fail(self, record):
+ asserts.abort_class(MSG_EXPECTED_EXCEPTION)
+
+ bt_cls = MockBaseTest(self.mock_test_cls_configs)
+ bt_cls.run(test_names=["test_1", "test_2", "test_3"])
+ self.assertEqual(len(bt_cls.results.skipped), 2)
+ self.assertEqual(bt_cls.results.summary_str(),
+ ("Error 0, Executed 1, Failed 1, Passed 0, "
+ "Requested 3, Skipped 2"))
+
def test_setup_and_teardown_execution_count(self):
class MockBaseTest(base_test.BaseTestClass):
def test_func(self):
| {
"commit_name": "merge_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": 2
},
"num_modified_files": 2
} | 1.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc adb"
],
"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
future==1.0.0
iniconfig==2.1.0
-e git+https://github.com/google/mobly.git@1493710b2fa167349303bc6710dda042dae0b895#egg=mobly
mock==1.0.1
packaging==24.2
pluggy==1.5.0
portpicker==1.6.0
psutil==7.0.0
pytest==8.3.5
pytz==2025.2
PyYAML==6.0.2
timeout-decorator==0.5.0
tomli==2.2.1
| name: mobly
channels:
- defaults
- https://repo.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
- future==1.0.0
- iniconfig==2.1.0
- mock==1.0.1
- packaging==24.2
- pluggy==1.5.0
- portpicker==1.6.0
- psutil==7.0.0
- pytest==8.3.5
- pytz==2025.2
- pyyaml==6.0.2
- timeout-decorator==0.5.0
- tomli==2.2.1
prefix: /opt/conda/envs/mobly
| [
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_on_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_class_in_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_abort_setup_class",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_wrong_error",
"tests/mobly/base_test_test.py::BaseTestTest::test_both_teardown_and_test_body_raise_exceptions",
"tests/mobly/base_test_test.py::BaseTestTest::test_exception_objects_in_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_explicit_pass_but_teardown_test_raises_an_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_in_procedure_functions_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_failure_to_call_procedure_function_is_recorded",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_call_outside_of_setup_generated_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_both_test_and_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_teardown_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_setup_fails_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_cannot_modify_original_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_pass_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_promote_extra_errors_to_termination_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_test_fail_by_test_signal",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_assert_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_setup_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_raise_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_uncaught_exception"
]
| []
| [
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_fail_with_msg",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_equal_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_fail_with_wrong_regex",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_fail_with_noop",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_raises_regex_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_assert_true",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_cli_test_selection_override_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_current_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_default_execution_of_all_tests",
"tests/mobly/base_test_test.py::BaseTestTest::test_fail",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_dup_test_name",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_generate_tests_selected_run",
"tests/mobly/base_test_test.py::BaseTestTest::test_implicit_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_missing_requested_test_func",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_cannot_modify_original_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_on_fail_executed_if_test_fails",
"tests/mobly/base_test_test.py::BaseTestTest::test_procedure_function_gets_correct_record",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_self_tests_list_fail_by_convention",
"tests/mobly/base_test_test.py::BaseTestTest::test_setup_and_teardown_execution_count",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_if",
"tests/mobly/base_test_test.py::BaseTestTest::test_skip_in_setup_test",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_class_fail_by_exception",
"tests/mobly/base_test_test.py::BaseTestTest::test_teardown_test_executed_if_test_pass",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_basic",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_None",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_optional_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_default_overwrite_by_required_param_list",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_missing",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_optional_with_default",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required",
"tests/mobly/base_test_test.py::BaseTestTest::test_unpack_userparams_required_missing"
]
| []
| Apache License 2.0 | 1,620 | [
"mobly/signals.py",
"mobly/controllers/android_device.py"
]
| [
"mobly/signals.py",
"mobly/controllers/android_device.py"
]
|
borgbackup__borg-2964 | 818e5c8e0199fff8dc15d07fd1d8c65242405f25 | 2017-08-25 01:32:03 | a714f77c4a0f9539bc21dd3b6b9e2eaaddaa9dfe | diff --git a/docs/internals/frontends.rst b/docs/internals/frontends.rst
index c41d427e..677db738 100644
--- a/docs/internals/frontends.rst
+++ b/docs/internals/frontends.rst
@@ -499,6 +499,8 @@ Errors
Insufficient free space to complete transaction (required: {}, available: {}).
Repository.InvalidRepository
{} is not a valid repository. Check repo config.
+ Repository.AtticRepository
+ Attic repository detected. Please run "borg upgrade {}".
Repository.ObjectNotFound
Object with key {} not found in repository {}.
diff --git a/src/borg/remote.py b/src/borg/remote.py
index d131a826..a508e04f 100644
--- a/src/borg/remote.py
+++ b/src/borg/remote.py
@@ -733,6 +733,11 @@ def handle_error(unpacked):
raise IntegrityError('(not available)')
else:
raise IntegrityError(args[0].decode())
+ elif error == 'AtticRepository':
+ if old_server:
+ raise Repository.AtticRepository('(not available)')
+ else:
+ raise Repository.AtticRepository(args[0].decode())
elif error == 'PathNotAllowed':
if old_server:
raise PathNotAllowed('(unknown)')
diff --git a/src/borg/repository.py b/src/borg/repository.py
index a61e4e94..942b862d 100644
--- a/src/borg/repository.py
+++ b/src/borg/repository.py
@@ -30,6 +30,8 @@
MAGIC = b'BORG_SEG'
MAGIC_LEN = len(MAGIC)
+ATTIC_MAGIC = b'ATTICSEG'
+assert len(ATTIC_MAGIC) == MAGIC_LEN
TAG_PUT = 0
TAG_DELETE = 1
TAG_COMMIT = 2
@@ -116,6 +118,9 @@ class AlreadyExists(Error):
class InvalidRepository(Error):
"""{} is not a valid repository. Check repo config."""
+ class AtticRepository(Error):
+ """Attic repository detected. Please run "borg upgrade {}"."""
+
class CheckNeeded(ErrorWithTraceback):
"""Inconsistency detected. Please run "borg check {}"."""
@@ -134,7 +139,7 @@ class StorageQuotaExceeded(Error):
"""The storage quota ({}) has been exceeded ({}). Try deleting some archives."""
def __init__(self, path, create=False, exclusive=False, lock_wait=None, lock=True,
- append_only=False, storage_quota=None):
+ append_only=False, storage_quota=None, check_segment_magic=True):
self.path = os.path.abspath(path)
self._location = Location('file://%s' % self.path)
self.io = None # type: LoggedIO
@@ -154,6 +159,7 @@ def __init__(self, path, create=False, exclusive=False, lock_wait=None, lock=Tru
self.storage_quota = storage_quota
self.storage_quota_use = 0
self.transaction_doomed = None
+ self.check_segment_magic = check_segment_magic
def __del__(self):
if self.lock:
@@ -375,6 +381,12 @@ def open(self, path, exclusive, lock_wait=None, lock=True):
self.storage_quota = self.config.getint('repository', 'storage_quota', fallback=0)
self.id = unhexlify(self.config.get('repository', 'id').strip())
self.io = LoggedIO(self.path, self.max_segment_size, self.segments_per_dir)
+ if self.check_segment_magic:
+ # read a segment and check whether we are dealing with a non-upgraded Attic repository
+ segment = self.io.get_latest_segment()
+ if segment is not None and self.io.get_segment_magic(segment) == ATTIC_MAGIC:
+ self.close()
+ raise self.AtticRepository(path)
def close(self):
if self.lock:
@@ -1250,6 +1262,11 @@ def segment_exists(self, segment):
def segment_size(self, segment):
return os.path.getsize(self.segment_filename(segment))
+ def get_segment_magic(self, segment):
+ fd = self.get_fd(segment)
+ fd.seek(0)
+ return fd.read(MAGIC_LEN)
+
def iter_objects(self, segment, offset=0, include_data=False, read_data=True):
"""
Return object iterator for *segment*.
diff --git a/src/borg/upgrader.py b/src/borg/upgrader.py
index 0b92ce8e..1044f649 100644
--- a/src/borg/upgrader.py
+++ b/src/borg/upgrader.py
@@ -19,6 +19,7 @@
class AtticRepositoryUpgrader(Repository):
def __init__(self, *args, **kw):
kw['lock'] = False # do not create borg lock files (now) in attic repo
+ kw['check_segment_magic'] = False # skip the Attic check when upgrading
super().__init__(*args, **kw)
def upgrade(self, dryrun=True, inplace=False, progress=False):
| Generic error message when trying to use non-upgraded attic repository
Hi,
while playing with borg (as attic user) i accidentally run borg commands on attic*s repository and i get ugly trackback:
```
Traceback (most recent call last):
File "/usr/lib64/python3.4/site-packages/borg/archiver.py", line 1928, in main
exit_code = archiver.run(args)
File "/usr/lib64/python3.4/site-packages/borg/archiver.py", line 1873, in run
return args.func(args)
File "/usr/lib64/python3.4/site-packages/borg/archiver.py", line 81, in wrapper
kwargs['manifest'], kwargs['key'] = Manifest.load(repository)
File "/usr/lib64/python3.4/site-packages/borg/helpers.py", line 113, in load
cdata = repository.get(cls.MANIFEST_ID)
File "/usr/lib64/python3.4/site-packages/borg/repository.py", line 512, in get
self.index = self.open_index(self.get_transaction_id())
File "/usr/lib64/python3.4/site-packages/borg/repository.py", line 152, in get_transaction_id
raise self.CheckNeeded(self.path)
borg.repository.CheckNeeded: /srv/backup/system.borg
```
IMO, this exception have to be catched and only error message needs to be reported, to get more better look ;-)
---
:moneybag: [there is a bounty for this](https://www.bountysource.com/issues/39795380-generic-error-message-when-trying-to-use-non-upgraded-attic-repository) | borgbackup/borg | diff --git a/src/borg/testsuite/archiver.py b/src/borg/testsuite/archiver.py
index a26bc47c..5242d6db 100644
--- a/src/borg/testsuite/archiver.py
+++ b/src/borg/testsuite/archiver.py
@@ -55,6 +55,7 @@
from . import BaseTestCase, changedir, environment_variable, no_selinux
from . import are_symlinks_supported, are_hardlinks_supported, are_fifos_supported, is_utime_fully_supported
from .platform import fakeroot_detected
+from .upgrader import attic_repo
from . import key
@@ -2731,6 +2732,27 @@ def test_extract_hardlinks(self):
assert os.stat('input/dir1/aaaa').st_nlink == 2
assert os.stat('input/dir1/source2').st_nlink == 2
+ def test_detect_attic_repo(self):
+ path = attic_repo(self.repository_path)
+ cmds = [
+ ['create', path + '::test', self.tmpdir],
+ ['extract', path + '::test'],
+ ['check', path],
+ ['rename', path + '::test', 'newname'],
+ ['list', path],
+ ['delete', path],
+ ['prune', path],
+ ['info', path + '::test'],
+ ['mount', path, self.tmpdir],
+ ['key', 'export', path, 'exported'],
+ ['key', 'import', path, 'import'],
+ ['change-passphrase', path],
+ ['break-lock', path],
+ ]
+ for args in cmds:
+ output = self.cmd(*args, fork=True, exit_code=2)
+ assert 'Attic repository detected.' in output
+
@unittest.skipUnless('binary' in BORG_EXES, 'no borg.exe available')
class ArchiverTestCaseBinary(ArchiverTestCase):
diff --git a/src/borg/testsuite/upgrader.py b/src/borg/testsuite/upgrader.py
index 3fd7500c..08c0693b 100644
--- a/src/borg/testsuite/upgrader.py
+++ b/src/borg/testsuite/upgrader.py
@@ -85,8 +85,8 @@ def test_convert_segments(attic_repo, inplace):
:param attic_repo: a populated attic repository (fixture)
"""
repo_path = attic_repo
- # check should fail because of magic number
- assert not repo_valid(repo_path)
+ with pytest.raises(Repository.AtticRepository):
+ repo_valid(repo_path)
repository = AtticRepositoryUpgrader(repo_path, create=False)
with repository:
segments = [filename for i, filename in repository.io.segment_iterator()]
@@ -149,8 +149,8 @@ def test_convert_all(attic_repo, attic_key_file, inplace):
"""
repo_path = attic_repo
- # check should fail because of magic number
- assert not repo_valid(repo_path)
+ with pytest.raises(Repository.AtticRepository):
+ repo_valid(repo_path)
def stat_segment(path):
return os.stat(os.path.join(path, 'data', '0', '0'))
| {
"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": 2,
"test_score": 2
},
"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"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc libssl-dev libacl1-dev liblz4-dev libzstd-dev pkg-config build-essential"
],
"python": "3.9",
"reqs_path": [
"requirements.d/development.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/borgbackup/borg.git@818e5c8e0199fff8dc15d07fd1d8c65242405f25#egg=borgbackup
cachetools==5.5.2
chardet==5.2.0
colorama==0.4.6
coverage==7.8.0
Cython==3.0.12
distlib==0.3.9
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
iniconfig==2.1.0
msgpack-python==0.5.6
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
py-cpuinfo==9.0.0
pyproject-api==1.9.0
pytest==8.3.5
pytest-benchmark==5.1.0
pytest-cov==6.0.0
pytest-xdist==3.6.1
setuptools-scm==8.2.0
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
virtualenv==20.29.3
| name: borg
channels:
- defaults
- https://repo.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
- cython==3.0.12
- distlib==0.3.9
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- iniconfig==2.1.0
- msgpack-python==0.5.6
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- py-cpuinfo==9.0.0
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-benchmark==5.1.0
- pytest-cov==6.0.0
- pytest-xdist==3.6.1
- setuptools-scm==8.2.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- virtualenv==20.29.3
prefix: /opt/conda/envs/borg
| [
"src/borg/testsuite/upgrader.py::test_convert_segments[True]",
"src/borg/testsuite/upgrader.py::test_convert_segments[False]",
"src/borg/testsuite/upgrader.py::test_convert_all[True]",
"src/borg/testsuite/upgrader.py::test_convert_all[False]"
]
| [
"src/borg/testsuite/archiver.py::test_return_codes[python]",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_put_get_delete_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_attic013_acl_bug",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_check_usage",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_corrupted_manifest",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_empty_repository",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_extra_chunks",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_corrupted_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_duplicate_archive",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_item_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_metadata",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_file_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_manifest",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data_unencrypted",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable2",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_fresh_init_tam_required",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_not_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_path",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_doesnt_leak",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_chunks",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_files",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_chunks_archive",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_old_version_interfered",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_sort_option"
]
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::test_get_args",
"src/borg/testsuite/archiver.py::test_compare_chunk_contents",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_basic",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_empty",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_strip_components",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_simple",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-both]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-both]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--no-files-cache-no_files_cache-False-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--no-files-cache-no_files_cache-False-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--no-files-cache-no_files_cache-False-both]",
"src/borg/testsuite/archiver.py::test_parse_storage_quota",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark-parser1]",
"src/borg/testsuite/archiver.py::test_help_formatting[break-lock-parser2]",
"src/borg/testsuite/archiver.py::test_help_formatting[change-passphrase-parser3]",
"src/borg/testsuite/archiver.py::test_help_formatting[check-parser4]",
"src/borg/testsuite/archiver.py::test_help_formatting[create-parser5]",
"src/borg/testsuite/archiver.py::test_help_formatting[debug",
"src/borg/testsuite/archiver.py::test_help_formatting[debug-parser16]",
"src/borg/testsuite/archiver.py::test_help_formatting[delete-parser17]",
"src/borg/testsuite/archiver.py::test_help_formatting[diff-parser18]",
"src/borg/testsuite/archiver.py::test_help_formatting[export-tar-parser19]",
"src/borg/testsuite/archiver.py::test_help_formatting[extract-parser20]",
"src/borg/testsuite/archiver.py::test_help_formatting[help-parser21]",
"src/borg/testsuite/archiver.py::test_help_formatting[info-parser22]",
"src/borg/testsuite/archiver.py::test_help_formatting[init-parser23]",
"src/borg/testsuite/archiver.py::test_help_formatting[key",
"src/borg/testsuite/archiver.py::test_help_formatting[key-parser28]",
"src/borg/testsuite/archiver.py::test_help_formatting[list-parser29]",
"src/borg/testsuite/archiver.py::test_help_formatting[mount-parser30]",
"src/borg/testsuite/archiver.py::test_help_formatting[prune-parser31]",
"src/borg/testsuite/archiver.py::test_help_formatting[recreate-parser32]",
"src/borg/testsuite/archiver.py::test_help_formatting[rename-parser33]",
"src/borg/testsuite/archiver.py::test_help_formatting[serve-parser34]",
"src/borg/testsuite/archiver.py::test_help_formatting[umount-parser35]",
"src/borg/testsuite/archiver.py::test_help_formatting[upgrade-parser36]",
"src/borg/testsuite/archiver.py::test_help_formatting[with-lock-parser37]",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[patterns-\\nFile",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[placeholders-\\nRepository",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[compression-\\nIt",
"src/borg/testsuite/upgrader.py::test_keys",
"src/borg/testsuite/upgrader.py::test_hardlink[True]",
"src/borg/testsuite/upgrader.py::test_hardlink[False]"
]
| []
| BSD License | 1,621 | [
"src/borg/repository.py",
"src/borg/upgrader.py",
"docs/internals/frontends.rst",
"src/borg/remote.py"
]
| [
"src/borg/repository.py",
"src/borg/upgrader.py",
"docs/internals/frontends.rst",
"src/borg/remote.py"
]
|
|
zalando-stups__pierone-cli-61 | 0afce92aedf654855ad35b90623410e6d6c261dd | 2017-08-25 13:13:09 | dc7a7328b557fd16f4ae799c4d166bcb657c6398 | coveralls:
[](https://coveralls.io/builds/12989449)
Coverage decreased (-0.2%) to 84.185% when pulling **bc4f97f25ac83c3272e0bd949d59ef3f7add1168 on luisfarzati:58-fix-credsstore-bug** into **0afce92aedf654855ad35b90623410e6d6c261dd on zalando-stups:master**.
Raffo: @hjacobs The problem looks like it is coming from pierone/api.py line 65 where we read from the local config instead of the temp file.
Raffo: Ok I figured out the problem, pushed a commit with @luisfarzati , should work now!
coveralls:
[](https://coveralls.io/builds/12992022)
Coverage increased (+0.08%) to 84.428% when pulling **2b8aa9d20c68984ea9af219f085e15182c5799d0 on luisfarzati:58-fix-credsstore-bug** into **0afce92aedf654855ad35b90623410e6d6c261dd on zalando-stups:master**.
Raffo: @hjacobs please review.
luisfarzati: ty @Raffo :)
hjacobs: :+1: | diff --git a/pierone/api.py b/pierone/api.py
index 35542be..9b0c76a 100644
--- a/pierone/api.py
+++ b/pierone/api.py
@@ -71,6 +71,9 @@ def docker_login_with_token(url, access_token):
basic_auth = codecs.encode('oauth2:{}'.format(access_token).encode('utf-8'), 'base64').strip().decode('utf-8')
if 'auths' not in dockercfg:
dockercfg['auths'] = {}
+ if 'credsStore' in dockercfg:
+ del dockercfg['credsStore']
+
dockercfg['auths'][url] = {'auth': basic_auth,
'email': '[email protected]'}
with Action('Storing Docker client configuration in {}..'.format(path)):
| no basic auth credentials
Today I had an auth issue. While trying to do `docker push` I was getting the following log:
➜ pierone login
Getting OAuth2 token "pierone".. OK
Storing Docker client configuration in /Users/whoever/.docker/config.json.. OK
➜ docker push myrepo/...
The push refers to a repository [myrepo/...]
a5f591aacc10: Preparing
...
cb11ba605400: Waiting
no basic auth credentials
Recreating `~/config.json` saved me.
There was `"credsStore": "osxkeychain"` setting In the previous version of the `~/config.json` which was causing me troubles.
BTW
mac os 10.12.3
pierone cli 1.1.27
docker 17.06.0-ce, build 02c1d87 | zalando-stups/pierone-cli | diff --git a/tests/test_api.py b/tests/test_api.py
index 62e1f0a..3ee83be 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -21,6 +21,29 @@ def test_docker_login(monkeypatch, tmpdir):
assert {'auth': 'b2F1dGgyOjEyMzc3',
'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org')
+def test_docker_login_with_credsstore(monkeypatch, tmpdir):
+ monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
+ monkeypatch.setattr('pierone.api.get_token', MagicMock(return_value='12377'))
+ path = os.path.expanduser('~/.docker/config.json')
+ os.makedirs(os.path.dirname(path))
+ with open(path, 'w') as fd:
+ json.dump({
+ "auths": {
+ "https://pierone.stups.zalan.do": {
+ "auth": "xxx",
+ "email": "[email protected]"
+ }
+ },
+ "credsStore": "osxkeychain"
+ }, fd)
+ docker_login('https://pierone.example.org', 'services', 'mytok',
+ 'myuser', 'mypass', 'https://token.example.org', use_keyring=False)
+ with open(path) as fd:
+ data = yaml.safe_load(fd)
+ assert {'auth': 'b2F1dGgyOjEyMzc3',
+ 'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org')
+ assert 'credsStore' not in data
+
def test_docker_login_service_token(monkeypatch, tmpdir):
monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
| {
"commit_name": "merge_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
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"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
click==8.1.8
clickclick==20.10.2
coverage==7.8.0
dnspython==2.7.0
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cov==6.0.0
PyYAML==6.0.2
requests==2.32.3
stups-cli-support==1.1.22
-e git+https://github.com/zalando-stups/pierone-cli.git@0afce92aedf654855ad35b90623410e6d6c261dd#egg=stups_pierone
stups-tokens==1.1.19
stups-zign==1.2
tomli==2.2.1
urllib3==2.3.0
| name: pierone-cli
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- 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
- clickclick==20.10.2
- coverage==7.8.0
- dnspython==2.7.0
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cov==6.0.0
- pyyaml==6.0.2
- requests==2.32.3
- stups-cli-support==1.1.22
- stups-tokens==1.1.19
- stups-zign==1.2
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/pierone-cli
| [
"tests/test_api.py::test_docker_login_with_credsstore"
]
| []
| [
"tests/test_api.py::test_docker_login",
"tests/test_api.py::test_docker_login_service_token",
"tests/test_api.py::test_docker_login_with_iid",
"tests/test_api.py::test_keep_dockercfg_entries",
"tests/test_api.py::test_get_latest_tag",
"tests/test_api.py::test_get_latest_tag_IOException",
"tests/test_api.py::test_get_latest_tag_non_json",
"tests/test_api.py::test_image_exists",
"tests/test_api.py::test_image_exists_IOException",
"tests/test_api.py::test_image_exists_but_other_version",
"tests/test_api.py::test_image_not_exists",
"tests/test_api.py::test_get_image_tags",
"tests/test_api.py::test_get_image_tag",
"tests/test_api.py::test_get_image_tag_that_does_not_exist"
]
| []
| Apache License 2.0 | 1,622 | [
"pierone/api.py"
]
| [
"pierone/api.py"
]
|
zopefoundation__zope.tales-8 | b5f635089bee4ef7b14bb97f090f2cf4763cc9da | 2017-08-25 22:06:39 | b5f635089bee4ef7b14bb97f090f2cf4763cc9da | diff --git a/.coveragerc b/.coveragerc
index 5724d01..1e8ed43 100644
--- a/.coveragerc
+++ b/.coveragerc
@@ -1,5 +1,7 @@
[run]
source = zope.tales
+omit =
+ */flycheck_*py
[report]
precision = 2
diff --git a/.travis.yml b/.travis.yml
index b07bcf7..e903051 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -5,12 +5,8 @@ python:
- 3.4
- 3.5
- 3.6
- # Force a newer PyPy on the old 'precise' CI image
- # in order to install 'cryptography' needed for coveralls
- # After September 2017 this should be the default and the version
- # pin can be removed.
- - pypy-5.6.0
- - pypy3.5-5.8.0
+ - pypy
+ - pypy3
install:
- pip install -U pip setuptools
- pip install -U coverage coveralls
diff --git a/CHANGES.rst b/CHANGES.rst
index d9d2dae..684e92f 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -11,6 +11,8 @@
- Drop support for ``python setup.py test``.
+- Reach 100% test coverage and maintain it via tox.ini and Travis CI.
+
4.1.1 (2015-06-06)
==================
diff --git a/src/zope/tales/expressions.py b/src/zope/tales/expressions.py
index 28fb81e..6203cc7 100644
--- a/src/zope/tales/expressions.py
+++ b/src/zope/tales/expressions.py
@@ -90,7 +90,6 @@ class SubPathExpr(object):
compiledpath.append(tuple(currentpath))
first = compiledpath[0]
- base = first[0]
if callable(first):
# check for initial function
@@ -101,6 +100,7 @@ class SubPathExpr(object):
raise engine.getCompilerError()(
'Dynamic name specified in first subpath element')
+ base = first[0]
if base and not _valid_name(base):
raise engine.getCompilerError()(
'Invalid variable name "%s"' % element)
@@ -211,9 +211,7 @@ class PathExpr(object):
# __call__.
if getattr(ob, '__call__', _marker) is not _marker:
return ob()
- if PY2 and isinstance(ob, types.ClassType):
- return ob()
- return ob
+ return ob() if PY2 and isinstance(ob, types.ClassType) else ob
def __call__(self, econtext):
if self._name == 'exists':
@@ -229,8 +227,8 @@ class PathExpr(object):
_interp = re.compile(
- r'\$(%(n)s)|\${(%(n)s(?:/[^}|]*)*(?:\|%(n)s(?:/[^}|]*)*)*)}'
- % {'n': NAME_RE})
+ r'\$(%(n)s)|\${(%(n)s(?:/[^}|]*)*(?:\|%(n)s(?:/[^}|]*)*)*)}'
+ % {'n': NAME_RE})
@implementer(ITALESExpression)
class StringExpr(object):
@@ -318,9 +316,10 @@ class DeferExpr(object):
class LazyWrapper(DeferWrapper):
"""Wrapper for lazy: expression
"""
+ _result = _marker
+
def __init__(self, expr, econtext):
DeferWrapper.__init__(self, expr, econtext)
- self._result = _marker
def __call__(self):
r = self._result
diff --git a/src/zope/tales/tales.py b/src/zope/tales/tales.py
index fd3295e..1256153 100644
--- a/src/zope/tales/tales.py
+++ b/src/zope/tales/tales.py
@@ -21,18 +21,21 @@ import re
from zope.interface import implementer
import six
+from zope.interface import Interface
+class ITALExpressionEngine(Interface):
+ pass
+class ITALExpressionCompiler(Interface):
+ pass
+class ITALExpressionErrorInfo(Interface):
+ pass
+
try:
- from zope.tal.interfaces import ITALExpressionEngine
- from zope.tal.interfaces import ITALExpressionCompiler
- from zope.tal.interfaces import ITALExpressionErrorInfo
+ # Override with real, if present
+ from zope.tal.interfaces import (ITALExpressionEngine,
+ ITALExpressionCompiler,
+ ITALExpressionErrorInfo)
except ImportError:
- from zope.interface import Interface
- class ITALExpressionEngine(Interface):
- pass
- class ITALExpressionCompiler(Interface):
- pass
- class ITALExpressionErrorInfo(Interface):
- pass
+ pass
from zope.tales.interfaces import ITALESIterator
@@ -107,7 +110,7 @@ class Iterator(object):
# but we can't know that without trying to get it. :(
self._last = False
try:
- self._next = six.advance_iterator(i)
+ self._next = next(i)
except StopIteration:
self._done = True
else:
@@ -159,7 +162,7 @@ class Iterator(object):
return False
self._item = v = self._next
try:
- self._next = six.advance_iterator(self._iter)
+ self._next = next(self._iter)
except StopIteration:
self._done = True
self._last = True
@@ -175,6 +178,10 @@ class Iterator(object):
>>> context = Context(ExpressionEngine(), {})
>>> it = Iterator('foo', ("apple", "pear", "orange"), context)
+ >>> it.index()
+ Traceback (most recent call last):
+ ...
+ TypeError: No iteration position
>>> int(bool(it.next()))
1
>>> it.index()
@@ -280,6 +287,10 @@ class Iterator(object):
>>> context = Context(ExpressionEngine(), {})
>>> it = Iterator('foo', ("apple", "pear", "orange"), context)
+ >>> it.letter()
+ Traceback (most recent call last):
+ ...
+ TypeError: No iteration position
>>> it.next()
True
>>> it.letter()
@@ -300,7 +311,8 @@ class Iterator(object):
while 1:
index, off = divmod(index, radix)
s = chr(base + off) + s
- if not index: return s
+ if not index:
+ return s
def Letter(self):
"""Get the iterator position as an upper-case letter
@@ -323,9 +335,9 @@ class Iterator(object):
return self.letter(base=ord('A'))
def Roman(self, rnvalues=(
- (1000,'M'),(900,'CM'),(500,'D'),(400,'CD'),
- (100,'C'),(90,'XC'),(50,'L'),(40,'XL'),
- (10,'X'),(9,'IX'),(5,'V'),(4,'IV'),(1,'I')) ):
+ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
+ (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
+ (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'))):
"""Get the iterator position as an upper-case roman numeral
>>> context = Context(ExpressionEngine(), {})
@@ -431,6 +443,10 @@ class Iterator(object):
>>> context = Context(ExpressionEngine(), {})
>>> it = Iterator('foo', ("apple", "pear", "orange"), context)
+ >>> it.item()
+ Traceback (most recent call last):
+ ...
+ TypeError: No iteration position
>>> it.next()
True
>>> it.item()
@@ -495,13 +511,14 @@ class Iterator(object):
class ErrorInfo(object):
"""Information about an exception passed to an on-error handler."""
+ value = None
+
def __init__(self, err, position=(None, None)):
+ self.type = err
if isinstance(err, Exception):
self.type = err.__class__
self.value = err
- else:
- self.type = err
- self.value = None
+
self.lineno = position[0]
self.offset = position[1]
@@ -691,12 +708,15 @@ class Context(object):
if isinstance(expression, str):
expression = self._engine.compile(expression)
__traceback_supplement__ = (
- TALESTracebackSupplement, self, expression)
+ TALESTracebackSupplement, self, expression)
return expression(self)
evaluateValue = evaluate
def evaluateBoolean(self, expr):
+ # "not not", while frowned upon by linters might be faster
+ # than bool() because it avoids a builtin lookup. Plus it can't be
+ # reassigned.
return not not self.evaluate(expr)
def evaluateText(self, expr):
@@ -708,13 +728,9 @@ class Context(object):
return text
return six.text_type(text)
- def evaluateStructure(self, expr):
- return self.evaluate(expr)
evaluateStructure = evaluate
- def evaluateMacro(self, expr):
- # TODO: Should return None or a macro definition
- return self.evaluate(expr)
+ # TODO: Should return None or a macro definition
evaluateMacro = evaluate
def createErrorInfo(self, err, position):
@@ -749,11 +765,10 @@ class TALESTracebackSupplement(object):
import pprint
data = self.context.contexts.copy()
if 'modules' in data:
- del data['modules'] # the list is really long and boring
+ del data['modules'] # the list is really long and boring
s = pprint.pformat(data)
if not as_html:
return ' - Names:\n %s' % s.replace('\n', '\n ')
- else:
- from cgi import escape
- return '<b>Names:</b><pre>%s</pre>' % (escape(s))
- return None
+
+ from cgi import escape
+ return '<b>Names:</b><pre>%s</pre>' % (escape(s))
diff --git a/tox.ini b/tox.ini
index 47d0c9f..927f900 100644
--- a/tox.ini
+++ b/tox.ini
@@ -11,10 +11,10 @@ deps =
[testenv:coverage]
usedevelop = true
basepython =
- python2.7
+ python3.6
commands =
coverage run -m zope.testrunner --test-path=src []
- coverage report --fail-under=88
+ coverage report --fail-under=100
deps =
{[testenv]deps}
coverage
| Reach 100% coverage | zopefoundation/zope.tales | diff --git a/src/zope/tales/tests/test_expressions.py b/src/zope/tales/tests/test_expressions.py
index b39b1b1..bc820cf 100644
--- a/src/zope/tales/tests/test_expressions.py
+++ b/src/zope/tales/tests/test_expressions.py
@@ -22,11 +22,7 @@ from zope.tales.interfaces import ITALESFunctionNamespace
from zope.tales.tales import Undefined
from zope.interface import implementer
-try:
- unicode
-except NameError:
- # Py3: Make the unicode name available again.
- unicode = str
+text_type = str if str is not bytes else unicode
PY3 = sys.version_info[0] == 3
@@ -35,95 +31,156 @@ class Data(object):
def __init__(self, **kw):
self.__dict__.update(kw)
- def __repr__(self): return self.name
+ def __getattr__(self, name):
+ # Let linters (like pylint) know this is a dynamic class and they shouldn't
+ # emit "Data has no attribute" errors
+ return object.__getattribute__(self, name)
+
+ def __repr__(self):
+ return self.name
__str__ = __repr__
-class ErrorGenerator:
+class ErrorGenerator(object):
def __getitem__(self, name):
from six.moves import builtins
if name == 'Undefined':
e = Undefined
else:
- e = getattr(builtins, name, None)
- if e is None:
- e = SystemError
+ e = getattr(builtins, name, None) or SystemError
raise e('mess')
+class Callable(object):
+
+ def __call__(self):
+ return 42
+
+class OldStyleCallable: # NOT object
+
+ pass
+
class ExpressionTestBase(unittest.TestCase):
def setUp(self):
# Test expression compilation
- from six import u
d = Data(
- name = 'xander',
- y = Data(
- name = 'yikes',
- z = Data(name = 'zope')
- )
- )
+ name='xander',
+ y=Data(
+ name='yikes',
+ z=Data(name='zope')
+ )
+ )
at = Data(
- name = 'yikes',
- _d = d
- )
+ name='yikes',
+ _d=d
+ )
self.context = Data(
- vars = dict(
- x = d,
- y = Data(z = 3),
- b = 'boot',
- B = 2,
- adapterTest = at,
- dynamic = 'z',
- eightBits = u('déjà vu').encode('utf-8'),
- ErrorGenerator = ErrorGenerator(),
- )
+ vars=dict(
+ x=d,
+ y=Data(z=3),
+ b='boot',
+ B=2,
+ adapterTest=at,
+ dynamic='z',
+ eightBits=u'déjà vu'.encode('utf-8'),
+ ErrorGenerator=ErrorGenerator(),
+ callable=Callable(),
+ old_callable_class=OldStyleCallable,
)
+ )
self.engine = Engine
+ self.py3BrokenEightBits = "a b'd\\xc3\\xa9j\\xc3\\xa0 vu'"
-class ExpressionTests(ExpressionTestBase):
+
+ def _compiled_expr(self, expr):
+ return self.engine.compile(expr) if isinstance(expr, str) else expr
+
+ def _check_evals_to(self, expr, result):
+ expr = self._compiled_expr(expr)
+ self.assertEqual(expr(self.context), result)
+ return expr
+
+ def _check_evals_to_instance(self, expr, result_kind):
+ expr = self._compiled_expr(expr)
+ self.assertIsInstance(expr(self.context), result_kind)
+ return expr
+
+ def _check_raises_compiler_error(self, expr_str, regex=None):
+ from zope.tales.tales import CompilerError
+ meth = self.assertRaises if regex is None else self.assertRaisesRegexp
+ args = (regex,) if regex is not None else ()
+ with meth(CompilerError, *args) as exc:
+ self.engine.compile(expr_str)
+ return exc.exception
+
+ def _check_subexpr_raises_compiler_error(self, expr, regexp):
+ from zope.tales.expressions import SubPathExpr
+ from zope.tales.tales import CompilerError
+ with self.assertRaisesRegexp(CompilerError,
+ regexp):
+ SubPathExpr(expr, None, self.engine)
+
+
+class TestParsedExpressions(ExpressionTestBase):
+ # Whitebox tests of expressions that have been compiled by the engine
def testSimple(self):
expr = self.engine.compile('x')
- context=self.context
- self.assertEqual(expr(context), context.vars['x'])
+ self._check_evals_to(expr, self.context.vars['x'])
def testPath(self):
expr = self.engine.compile('x/y')
- context=self.context
- self.assertEqual(expr(context), context.vars['x'].y)
+ self._check_evals_to(expr, self.context.vars['x'].y)
+ self.assertEqual("standard expression ('x/y')", str(expr))
+ self.assertEqual("<PathExpr standard:'x/y'>", repr(expr))
+
+ def test_path_nocall_call(self):
+ self._check_evals_to('callable', 42)
+ self._check_evals_to('nocall:callable', self.context.vars['callable'])
+
+ self._check_evals_to_instance('old_callable_class', OldStyleCallable)
+ self._check_evals_to('nocall:old_callable_class', OldStyleCallable)
+
+ def test_path_exists(self):
+ self._check_evals_to('exists:x', 1)
+ self._check_evals_to('exists:' + 'i' + str(id(self)), 0)
def testLongPath(self):
expr = self.engine.compile('x/y/z')
- context=self.context
- self.assertEqual(expr(context), context.vars['x'].y.z)
+ self._check_evals_to(expr, self.context.vars['x'].y.z)
def testOrPath(self):
expr = self.engine.compile('path:a|b|c/d/e')
- context=self.context
- self.assertEqual(expr(context), 'boot')
+ self._check_evals_to(expr, 'boot')
for e in 'Undefined', 'AttributeError', 'LookupError', 'TypeError':
expr = self.engine.compile('path:ErrorGenerator/%s|b|c/d/e' % e)
- context=self.context
- self.assertEqual(expr(context), 'boot')
+ self._check_evals_to(expr, 'boot')
+
+ def test_path_CONTEXTS(self):
+ self.context.contexts = 42
+ self._check_evals_to('CONTEXTS', 42)
def testDynamic(self):
expr = self.engine.compile('x/y/?dynamic')
- context=self.context
- self.assertEqual(expr(context),context.vars['x'].y.z)
+ self._check_evals_to(expr, self.context.vars['x'].y.z)
def testBadInitalDynamic(self):
from zope.tales.tales import CompilerError
- try:
+ with self.assertRaises(CompilerError) as exc:
self.engine.compile('?x')
- except CompilerError as e:
- self.assertEqual(e.args[0],
- 'Dynamic name specified in first subpath element')
- else:
- self.fail('Engine accepted first subpath element as dynamic')
+ e = exc.exception
+ self.assertEqual(e.args[0],
+ 'Dynamic name specified in first subpath element')
+
+ def test_dynamic_invalid_variable_name(self):
+ from zope.tales.tales import CompilerError
+ with self.assertRaisesRegexp(CompilerError,
+ "Invalid variable name"):
+ self.engine.compile('path:a/?123')
def testOldStyleClassIsCalled(self):
class AnOldStyleClass:
@@ -134,67 +191,67 @@ class ExpressionTests(ExpressionTestBase):
def testString(self):
expr = self.engine.compile('string:Fred')
- context=self.context
+ context = self.context
result = expr(context)
self.assertEqual(result, 'Fred')
- self.assertTrue(isinstance(result, str))
+ self.assertIsInstance(result, str)
+ self.assertEqual("string expression ('Fred')", str(expr))
+ self.assertEqual("<StringExpr 'Fred'>", repr(expr))
def testStringSub(self):
expr = self.engine.compile('string:A$B')
- context=self.context
- self.assertEqual(expr(context), 'A2')
+ self._check_evals_to(expr, 'A2')
def testStringSub_w_python(self):
CompilerError = self.engine.getCompilerError()
self.assertRaises(CompilerError,
self.engine.compile,
- 'string:${python:1}')
+ 'string:${python:1}')
def testStringSubComplex(self):
expr = self.engine.compile('string:a ${x/y} b ${y/z} c')
- context=self.context
- self.assertEqual(expr(context), 'a yikes b 3 c')
+ self._check_evals_to(expr, 'a yikes b 3 c')
def testStringSubComplex_w_miss_and_python(self):
# See https://bugs.launchpad.net/zope.tales/+bug/1002242
CompilerError = self.engine.getCompilerError()
self.assertRaises(CompilerError,
self.engine.compile,
- 'string:${nothig/nothing|python:1}')
+ 'string:${nothig/nothing|python:1}')
def testString8Bits(self):
# Simple eight bit string interpolation should just work.
- from six import u
- if PY3:
- # Py3: We simply do not handle 8-bit strings.
- return
+ # Except on Py3, where we really mess it up.
expr = self.engine.compile('string:a ${eightBits}')
- context=self.context
- self.assertEqual(expr(context), u('a déjà vu').encode('utf8'))
+ expected = 'a ' + self.context.vars['eightBits'] if not PY3 else self.py3BrokenEightBits
+ self._check_evals_to(expr, expected)
def testStringUnicode(self):
# Unicode string expressions should return unicode strings
- from six import u
- expr = self.engine.compile(u('string:Fred'))
- context=self.context
+ expr = self.engine.compile(u'string:Fred')
+ context = self.context
result = expr(context)
- self.assertEqual(result, u('Fred'))
- self.assertTrue(isinstance(result, unicode))
+ self.assertEqual(result, u'Fred')
+ self.assertIsInstance(result, text_type)
def testStringFailureWhenMixed(self):
# Mixed Unicode and 8bit string interpolation fails with a
# UnicodeDecodeError, assuming there is no default encoding
- from six import u
- if PY3:
- # Py3: We simply do not handle 8-bit strings.
- return
- expr = self.engine.compile(u('string:a ${eightBits}'))
- self.assertRaises(UnicodeDecodeError, expr, self.context)
+ expr = self.engine.compile(u'string:a ${eightBits}')
+ with self.assertRaises(UnicodeDecodeError):
+ result = expr(self.context)
+ # If we get here, we're on Python 3, which handles this
+ # poorly.
+ self.assertTrue(PY3)
+ self.assertEqual(result, self.py3BrokenEightBits)
+ self.context.vars['eightBits'].decode('ascii') # raise UnicodeDecodeError
+
+ def test_string_escape_percent(self):
+ self._check_evals_to('string:%', '%')
def testPython(self):
expr = self.engine.compile('python: 2 + 2')
- context=self.context
- self.assertEqual(expr(context), 4)
+ self._check_evals_to(expr, 4)
def testPythonCallableIsntCalled(self):
self.context.vars['acallable'] = lambda: 23
@@ -203,13 +260,11 @@ class ExpressionTests(ExpressionTestBase):
def testPythonNewline(self):
expr = self.engine.compile('python: 2 \n+\n 2\n')
- context=self.context
- self.assertEqual(expr(context), 4)
+ self._check_evals_to(expr, 4)
def testPythonDosNewline(self):
expr = self.engine.compile('python: 2 \r\n+\r\n 2\r\n')
- context=self.context
- self.assertEqual(expr(context), 4)
+ self._check_evals_to(expr, 4)
def testPythonErrorRaisesCompilerError(self):
self.assertRaises(self.engine.getCompilerError(),
@@ -261,15 +316,55 @@ class ExpressionTests(ExpressionTestBase):
def test_defer_expression_returns_wrapper(self):
from zope.tales.expressions import DeferWrapper
+ from zope.tales.expressions import DeferExpr
+ expr = self.engine.compile('defer: B')
+ self.assertIsInstance(expr, DeferExpr)
+ self.assertEqual(str(expr), "<DeferExpr 'B'>")
+ self._check_evals_to_instance(expr, DeferWrapper)
+
+ wrapper = expr(self.context)
+ # It evaluates to what its underlying expression evaluates to
+ self.assertEqual(wrapper(), self.context.vars['B'])
+ # The str() of defer is the same as the str() of evaluating it
+ self.assertEqual(str(wrapper), str(self.context.vars['B']))
+ self.assertEqual(str(wrapper()), str(self.context.vars['B']))
+
+ def test_eval_defer_wrapper(self):
expr = self.engine.compile('defer: b')
- context=self.context
- self.assertTrue(isinstance(expr(context), DeferWrapper))
+ self.context.vars['deferred'] = expr(self.context)
+ self._check_evals_to('deferred', self.context.vars['b'])
def test_lazy_expression_returns_wrapper(self):
from zope.tales.expressions import LazyWrapper
+ from zope.tales.expressions import LazyExpr
expr = self.engine.compile('lazy: b')
- context=self.context
- self.assertTrue(isinstance(expr(context), LazyWrapper))
+ self.assertIsInstance(expr, LazyExpr)
+ self.assertEqual(repr(expr), "lazy:'b'")
+ lazy = expr(self.context)
+ self.assertIsInstance(lazy, LazyWrapper)
+
+ first_result = lazy()
+ second_result = lazy()
+ self.assertIs(first_result, second_result)
+
+ def test_not(self):
+ # self.context is a Data object, not a real
+ # zope.tales.tales.Context object, and as such
+ # it doesn't define the evaluateBoolean function that
+ # not expressions need. Add it locally to avoid disturbing
+ # other tests.
+ def evaluateBoolean(expr):
+ return bool(expr(self.context))
+ self.context.evaluateBoolean = evaluateBoolean
+ self._check_evals_to('not:exists:x', 0)
+ expr = self._check_evals_to('not:exists:v_42', 1)
+ self.assertEqual("<NotExpr 'exists:v_42'>", repr(expr))
+
+ def test_bad_initial_name_subexpr(self):
+ self._check_subexpr_raises_compiler_error(
+ '123',
+ "Invalid variable name"
+ )
class FunctionTests(ExpressionTestBase):
@@ -293,13 +388,14 @@ class FunctionTests(ExpressionTestBase):
def upper(self):
return str(self.context).upper()
- def __getitem__(self,key):
- if key=='jump':
+ def __getitem__(self, key):
+ if key == 'jump':
return self.context._d
raise KeyError(key)
self.TestNameSpace = TestNameSpace
self.engine.registerFunctionNamespace('namespace', self.TestNameSpace)
+ self.engine.registerFunctionNamespace('not_callable_ns', None)
## framework-ish tests
@@ -311,7 +407,7 @@ class FunctionTests(ExpressionTestBase):
self.assertEqual(
self.engine.getFunctionNamespace('namespace'),
self.TestNameSpace
- )
+ )
def testGetFunctionNamespaceBadNamespace(self):
self.assertRaises(KeyError,
@@ -322,20 +418,15 @@ class FunctionTests(ExpressionTestBase):
def testBadNamespace(self):
# namespace doesn't exist
- from zope.tales.tales import CompilerError
- try:
- self.engine.compile('adapterTest/badnamespace:title')
- except CompilerError as e:
- self.assertEqual(e.args[0],'Unknown namespace "badnamespace"')
- else:
- self.fail('Engine accepted unknown namespace')
+ self._check_raises_compiler_error(
+ 'adapterTest/badnamespace:title',
+ 'Unknown namespace "badnamespace"')
def testBadInitialNamespace(self):
# first segment in a path must not have modifier
- from zope.tales.tales import CompilerError
- self.assertRaises(CompilerError,
- self.engine.compile,
- 'namespace:title')
+ self._check_raises_compiler_error(
+ 'namespace:title',
+ 'Unrecognized expression type "namespace"')
# In an ideal world there would be another test here to test
# that a nicer error was raised when you tried to use
@@ -350,25 +441,24 @@ class FunctionTests(ExpressionTestBase):
# should be nested are nestable, then the additional test
# should be added here.
+ def test_bad_initial_namespace_subpath(self):
+ self._check_subexpr_raises_compiler_error(
+ 'namespace:title',
+ "Namespace function specified in first subpath element")
+
def testInvalidNamespaceName(self):
- from zope.tales.tales import CompilerError
- try:
- self.engine.compile('adapterTest/1foo:bar')
- except CompilerError as e:
- self.assertEqual(e.args[0],
- 'Invalid namespace name "1foo"')
- else:
- self.fail('Engine accepted invalid namespace name')
+ self._check_raises_compiler_error(
+ 'adapterTest/1foo:bar',
+ 'Invalid namespace name "1foo"')
def testBadFunction(self):
# namespace is fine, adapter is not defined
- try:
- expr = self.engine.compile('adapterTest/namespace:title')
+ expr = self.engine.compile('adapterTest/namespace:title')
+ with self.assertRaises(KeyError) as exc:
expr(self.context)
- except KeyError as e:
- self.assertEqual(e.args[0],'title')
- else:
- self.fail('Engine accepted unknown function')
+
+ e = exc.exception
+ self.assertEqual(e.args[0], 'title')
## runtime tests
@@ -382,14 +472,36 @@ class FunctionTests(ExpressionTestBase):
def testPathOnFunction(self):
expr = self.engine.compile('adapterTest/namespace:jump/y/z')
- context = self.context
- self.assertEqual(expr(context), context.vars['x'].y.z)
+ self._check_evals_to(expr, self.context.vars['x'].y.z)
+
+ def test_path_through_non_callable_nampspace(self):
+ expr = self.engine.compile('adapterTest/not_callable_ns:nope')
+ with self.assertRaisesRegexp(ValueError,
+ 'None'):
+ expr(self.context)
+
+class TestSimpleModuleImporter(unittest.TestCase):
+
+ def _makeOne(self):
+ from zope.tales.expressions import SimpleModuleImporter
+ return SimpleModuleImporter()
+
+ def test_simple(self):
+ imp = self._makeOne()
+ import os
+ import os.path
+ self.assertIs(os, imp['os'])
+ self.assertIs(os.path, imp['os.path'])
+
+ def test_no_such_toplevel_possible(self):
+ with self.assertRaises(ImportError):
+ self._makeOne()['this cannot exist']
+
-def test_suite():
- return unittest.TestSuite((
- unittest.makeSuite(ExpressionTests),
- unittest.makeSuite(FunctionTests),
- ))
+ def test_no_such_submodule_not_package(self):
+ with self.assertRaises(ImportError):
+ self._makeOne()['zope.tales.tests.test_expressions.submodule']
-if __name__ == '__main__':
- unittest.TextTestRunner().run(test_suite())
+ def test_no_such_submodule_package(self):
+ with self.assertRaises(ImportError):
+ self._makeOne()['zope.tales.tests.submodule']
diff --git a/src/zope/tales/tests/test_pythonexpr.py b/src/zope/tales/tests/test_pythonexpr.py
new file mode 100644
index 0000000..7410c41
--- /dev/null
+++ b/src/zope/tales/tests/test_pythonexpr.py
@@ -0,0 +1,50 @@
+##############################################################################
+#
+# Copyright (c) 2017 Zope Foundation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+
+import unittest
+
+from zope.tales.engine import Engine
+from zope.tales.tales import Context
+
+from zope.tales.pythonexpr import PythonExpr
+from zope.tales.pythonexpr import ExprTypeProxy
+
+class TestPythonExpr(unittest.TestCase):
+
+ def setUp(self):
+ self.context = Context(Engine, {})
+ self.engine = Engine
+
+ def test_repr_str(self):
+ expr = PythonExpr(None, 'a', None)
+ self.assertEqual('Python expression "(a)"', str(expr))
+ self.assertEqual('<PythonExpr (a)>', repr(expr))
+
+ def test_bind_not_dict(self):
+ expr = PythonExpr(None, 'test_bind_not_dict', None)
+ names = expr._bind_used_names(self.context, type(self))
+
+ # It found it in type(self).__dict__, so it only added
+ # __builtins__ to the names
+ self.assertEqual(names,
+ {'__builtins__': type(self).__dict__})
+
+ def test_bind_as_expression(self):
+ expr = PythonExpr(None, 'string("abc")', None)
+ names = expr._bind_used_names(self.context, {})
+
+ string = names['string']
+ self.assertIsInstance(string, ExprTypeProxy)
+
+ self.assertEqual(expr(self.context), "abc")
diff --git a/src/zope/tales/tests/test_tales.py b/src/zope/tales/tests/test_tales.py
index 0bbf4ff..356413c 100644
--- a/src/zope/tales/tests/test_tales.py
+++ b/src/zope/tales/tests/test_tales.py
@@ -13,17 +13,17 @@
##############################################################################
"""TALES Tests
"""
+from doctest import DocTestSuite
import unittest
import re
import six
from zope.tales import tales
from zope.tales.tests.simpleexpr import SimpleExpr
-from doctest import DocTestSuite
from zope.testing import renormalizing
-class TALESTests(unittest.TestCase):
+class TestIterator(unittest.TestCase):
def testIterator0(self):
# Test sample Iterator class
@@ -51,6 +51,8 @@ class TALESTests(unittest.TestCase):
self.assertTrue(not next(it), "Multi-element iterator")
context._complete_()
+class TALESTests(unittest.TestCase):
+
def testRegisterType(self):
# Test expression type registration
e = tales.ExpressionEngine()
@@ -110,6 +112,17 @@ class TALESTests(unittest.TestCase):
self.assertTrue(isinstance(se, six.text_type))
self.assertEqual(se, "('simple', 'x')")
+ def test_context_createErrorInfo(self):
+ ei = self.getContext().createErrorInfo(self, (0, 0))
+ self.assertEqual(ei.type, self)
+ self.assertEqual(ei.value, None)
+
+ e = Exception()
+ ei = self.getContext().createErrorInfo(e, (0, 0))
+ self.assertEqual(ei.type, Exception)
+ self.assertEqual(ei.value, e)
+
+
def testVariables(self):
# Test variables
ctxt = self.getContext()
@@ -137,6 +150,145 @@ class TALESTests(unittest.TestCase):
ctxt.endScope()
+class TestExpressionEngine(unittest.TestCase):
+
+ def setUp(self):
+ self.engine = tales.ExpressionEngine()
+
+ def test_register_invalid_name(self):
+ with self.assertRaisesRegexp(tales.RegistrationError,
+ "Invalid base name"):
+ self.engine.registerBaseName('123', None)
+
+ def test_register_duplicate_name(self):
+ self.engine.registerBaseName('abc', 123)
+ with self.assertRaisesRegexp(tales.RegistrationError,
+ "Multiple registrations"):
+ self.engine.registerBaseName('abc', None)
+
+ self.assertEqual({'abc': 123}, self.engine.getBaseNames())
+
+ def test_getContext(self):
+ contexts = {}
+ ctx = self.engine.getContext(contexts)
+ self.assertIs(ctx.contexts, contexts)
+
+ ctx = self.engine.getContext(b=2, c=3)
+ self.assertEqual(ctx.contexts['b'], 2)
+ self.assertEqual(ctx.contexts['c'], 3)
+
+ contexts = {'a': 1, 'c': 1}
+ ctx = self.engine.getContext(contexts, b=2, c=3)
+ self.assertEqual(ctx.contexts['a'], 1)
+ self.assertEqual(ctx.contexts['b'], 2)
+ self.assertEqual(ctx.contexts['c'], 1)
+
+class TestContext(unittest.TestCase):
+
+ def setUp(self):
+ from zope.tales.engine import Engine
+ self.engine = Engine
+ self.context = tales.Context(self.engine, {})
+
+ def test_setRepeat_false(self):
+ self.context.vars['it'] = ()
+ self.context.beginScope()
+ self.context.setRepeat('name', 'it')
+ self.assertNotIn('name', self.context.repeat_vars)
+
+ def test_endScope_with_repeat_active(self):
+ self.context.vars['it'] = [1, 2, 3]
+ self.context.vars['it2'] = [1, 2, 3]
+ self.context.beginScope()
+ self.context.setRepeat('name', 'it')
+ # shadow it
+ self.context.setRepeat('name', 'it2')
+ self.assertIn('name', self.context.repeat_vars)
+ self.context.endScope()
+ self.assertNotIn('name', self.context.repeat_vars)
+
+ def test_getValue_simple(self):
+ self.context.vars['it'] = 1
+ self.assertEqual(self.context.getValue('it'), 1)
+ self.assertEqual(self.context.getValue('missing', default=self), self)
+
+ def test_getValue_nested(self):
+ self.context.vars['it'] = 1
+ self.context.beginScope()
+ self.context.vars['it'] = 2
+ self.assertEqual(self.context.getValue('it'), 1)
+
+ def test_evaluate_boolean(self):
+ # Make sure it always returns a regular bool, no matter
+ # what the class returns
+ class WithCustomBool(object):
+
+ def __init__(self, value):
+ self.value = value
+
+ def __bool__(self):
+ return self.value
+
+ __nonzero__ = __bool__
+
+ # On Python 2, you can return only bool or int from __nonzero__
+ # Python 3 requires just a bool from __bool__. This is true whether
+ # you pass it to the bool builtin on the not operator
+ # On both 2 and 3, you cannot subclass bool()
+ bool_value = 1 if str is bytes else True
+ self.context.vars['it'] = WithCustomBool(bool_value)
+ self.assertEqual(bool_value, self.context.evaluate('it').__bool__())
+ self.assertIs(True, self.context.evaluateBoolean('it'))
+
+ def test_evaluateText_none(self):
+ self.context.vars['it'] = None
+ self.assertIsNone(self.context.evaluateText('it'))
+
+ def test_evaluateText_text(self):
+ self.context.vars['it'] = u'text'
+ self.assertEqual(u'text', self.context.evaluateText("it"))
+
+ def test_traceback_supplement(self):
+ import sys
+ def raises(self):
+ raise Exception()
+
+ self.context.contexts['modules'] = 1
+ self.context.setSourceFile("source")
+ self.context.setPosition((0, 1))
+
+ try:
+ self.context.evaluate(raises)
+ except Exception:
+ tb = sys.exc_info()[2]
+
+ try:
+ supp = tb.tb_next.tb_frame.f_locals['__traceback_supplement__']
+ finally:
+ del tb
+
+ supp = supp[0](supp[1], supp[2])
+ self.assertIs(supp.context, self.context)
+ self.assertEqual(supp.source_url, self.context.source_file)
+ self.assertEqual(supp.line, 0)
+ self.assertEqual(supp.column, 1)
+ self.assertEqual(supp.expression, repr(raises))
+
+ info = supp.getInfo()
+ # We stripped this info
+ self.assertNotIn('modules', info)
+ self.assertIn(' - Names', info)
+
+ html_info = supp.getInfo(as_html=True)
+ self.assertIn('<b>Names', html_info)
+
+ # And we didn't change the data in the context
+ self.assertIn('modules', self.context.contexts)
+
+ def test_translate(self):
+ import six
+ self.assertIsInstance(self.context.translate(b'abc'), six.text_type)
+
class Harness(object):
def __init__(self, testcase):
@@ -148,7 +300,7 @@ class Harness(object):
def _complete_(self):
self._testcase.assertEqual(len(self._callstack), 0,
- "Harness methods called")
+ "Harness methods called")
def __getattr__(self, name):
return HarnessMethod(self, name)
@@ -167,28 +319,26 @@ class HarnessMethod(object):
self._testcase.assertTrue(
len(cs),
'Unexpected harness method call "%s".' % name
- )
+ )
self._testcase.assertEqual(
- cs[0][0], name,
+ cs[0][0], name,
'Harness method name "%s" called, "%s" expected.' %
(name, cs[0][0])
- )
-
+ )
+
name, aargs, akwargs = self._callstack.pop(0)
self._testcase.assertEqual(aargs, args, "Harness method arguments")
self._testcase.assertEqual(akwargs, kwargs,
- "Harness method keyword args")
+ "Harness method keyword args")
def test_suite():
- checker = renormalizing.RENormalizing([
- (re.compile(r"object of type 'MyIter' has no len\(\)"),
- r"len() of unsized object"),
- ])
- suite = unittest.makeSuite(TALESTests)
- suite.addTest(DocTestSuite("zope.tales.tales",checker=checker))
+ checker = renormalizing.RENormalizing(
+ [(re.compile(r"object of type 'MyIter' has no len\(\)"),
+ r"len() of unsized object"),
+ ]
+ )
+ suite = unittest.defaultTestLoader.loadTestsFromName(__name__)
+ suite.addTest(DocTestSuite("zope.tales.tales",
+ checker=checker))
return suite
-
-
-if __name__ == '__main__':
- unittest.TextTestRunner().run(test_suite())
| {
"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": 3,
"test_score": 2
},
"num_modified_files": 6
} | 4.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"zope.testrunner",
"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
six==1.17.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
zope.exceptions==4.6
zope.interface==5.5.2
-e git+https://github.com/zopefoundation/zope.tales.git@b5f635089bee4ef7b14bb97f090f2cf4763cc9da#egg=zope.tales
zope.testing==5.0.1
zope.testrunner==5.6
| name: zope.tales
channels:
- defaults
- https://repo.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:
- six==1.17.0
- zope-exceptions==4.6
- zope-interface==5.5.2
- zope-testing==5.0.1
- zope-testrunner==5.6
prefix: /opt/conda/envs/zope.tales
| [
"src/zope/tales/tests/test_expressions.py::FunctionTests::test_bad_initial_namespace_subpath"
]
| []
| [
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testBadInitalDynamic",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testDynamic",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testEmptyPathSegmentRaisesCompilerError",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testHybridPathExpressions",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testLongPath",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testOldStyleClassIsCalled",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testOrPath",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testPath",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testPython",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testPythonCallableIsntCalled",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testPythonDosNewline",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testPythonErrorRaisesCompilerError",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testPythonNewline",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testSimple",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testString",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testString8Bits",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testStringFailureWhenMixed",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testStringSub",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testStringSubComplex",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testStringSubComplex_w_miss_and_python",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testStringSub_w_python",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::testStringUnicode",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::test_bad_initial_name_subexpr",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::test_defer_expression_returns_wrapper",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::test_dynamic_invalid_variable_name",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::test_eval_defer_wrapper",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::test_lazy_expression_returns_wrapper",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::test_not",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::test_path_CONTEXTS",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::test_path_exists",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::test_path_nocall_call",
"src/zope/tales/tests/test_expressions.py::TestParsedExpressions::test_string_escape_percent",
"src/zope/tales/tests/test_expressions.py::FunctionTests::testBadFunction",
"src/zope/tales/tests/test_expressions.py::FunctionTests::testBadInitialNamespace",
"src/zope/tales/tests/test_expressions.py::FunctionTests::testBadNamespace",
"src/zope/tales/tests/test_expressions.py::FunctionTests::testFunctionOnFunction",
"src/zope/tales/tests/test_expressions.py::FunctionTests::testGetFunctionNamespace",
"src/zope/tales/tests/test_expressions.py::FunctionTests::testGetFunctionNamespaceBadNamespace",
"src/zope/tales/tests/test_expressions.py::FunctionTests::testInvalidNamespaceName",
"src/zope/tales/tests/test_expressions.py::FunctionTests::testNormalFunction",
"src/zope/tales/tests/test_expressions.py::FunctionTests::testPathOnFunction",
"src/zope/tales/tests/test_expressions.py::FunctionTests::testSetEngine",
"src/zope/tales/tests/test_expressions.py::FunctionTests::test_path_through_non_callable_nampspace",
"src/zope/tales/tests/test_expressions.py::TestSimpleModuleImporter::test_no_such_submodule_not_package",
"src/zope/tales/tests/test_expressions.py::TestSimpleModuleImporter::test_no_such_submodule_package",
"src/zope/tales/tests/test_expressions.py::TestSimpleModuleImporter::test_no_such_toplevel_possible",
"src/zope/tales/tests/test_expressions.py::TestSimpleModuleImporter::test_simple",
"src/zope/tales/tests/test_pythonexpr.py::TestPythonExpr::test_bind_as_expression",
"src/zope/tales/tests/test_pythonexpr.py::TestPythonExpr::test_bind_not_dict",
"src/zope/tales/tests/test_pythonexpr.py::TestPythonExpr::test_repr_str",
"src/zope/tales/tests/test_tales.py::TestIterator::testIterator0",
"src/zope/tales/tests/test_tales.py::TestIterator::testIterator1",
"src/zope/tales/tests/test_tales.py::TestIterator::testIterator2",
"src/zope/tales/tests/test_tales.py::TALESTests::testCompile",
"src/zope/tales/tests/test_tales.py::TALESTests::testContext_evaluate",
"src/zope/tales/tests/test_tales.py::TALESTests::testContext_evaluateText",
"src/zope/tales/tests/test_tales.py::TALESTests::testGetContext",
"src/zope/tales/tests/test_tales.py::TALESTests::testRegisterType",
"src/zope/tales/tests/test_tales.py::TALESTests::testRegisterTypeNameConstraints",
"src/zope/tales/tests/test_tales.py::TALESTests::testRegisterTypeUnique",
"src/zope/tales/tests/test_tales.py::TALESTests::testVariables",
"src/zope/tales/tests/test_tales.py::TALESTests::test_context_createErrorInfo",
"src/zope/tales/tests/test_tales.py::TestExpressionEngine::test_getContext",
"src/zope/tales/tests/test_tales.py::TestExpressionEngine::test_register_duplicate_name",
"src/zope/tales/tests/test_tales.py::TestExpressionEngine::test_register_invalid_name",
"src/zope/tales/tests/test_tales.py::TestContext::test_endScope_with_repeat_active",
"src/zope/tales/tests/test_tales.py::TestContext::test_evaluateText_none",
"src/zope/tales/tests/test_tales.py::TestContext::test_evaluateText_text",
"src/zope/tales/tests/test_tales.py::TestContext::test_evaluate_boolean",
"src/zope/tales/tests/test_tales.py::TestContext::test_getValue_nested",
"src/zope/tales/tests/test_tales.py::TestContext::test_getValue_simple",
"src/zope/tales/tests/test_tales.py::TestContext::test_setRepeat_false",
"src/zope/tales/tests/test_tales.py::TestContext::test_traceback_supplement",
"src/zope/tales/tests/test_tales.py::TestContext::test_translate",
"src/zope/tales/tests/test_tales.py::test_suite"
]
| []
| Zope Public License 2.1 | 1,623 | [
"src/zope/tales/tales.py",
".travis.yml",
"tox.ini",
".coveragerc",
"CHANGES.rst",
"src/zope/tales/expressions.py"
]
| [
"src/zope/tales/tales.py",
".travis.yml",
"tox.ini",
".coveragerc",
"CHANGES.rst",
"src/zope/tales/expressions.py"
]
|
|
OpenMined__PySyft-188 | a81fde47c4593a787f9bb61dd655af58497bef4a | 2017-08-26 08:14:00 | a81fde47c4593a787f9bb61dd655af58497bef4a | diff --git a/syft/tensor.py b/syft/tensor.py
index f9eff20a64..ee9cf8715d 100644
--- a/syft/tensor.py
+++ b/syft/tensor.py
@@ -518,3 +518,41 @@ class TensorBase(object):
if self.encrypted:
return NotImplemented
self.data = 1 / np.array(self.data)
+
+ def log(self):
+ """performs elementwise logarithm operation
+ and returns a new Tensor"""
+ if self.encrypted:
+ return NotImplemented
+ out = np.log(self.data)
+ return TensorBase(out)
+
+ def log_(self):
+ """performs elementwise logarithm operation inplace"""
+ if self.encrypted:
+ return NotImplemented
+ self.data = np.log(self.data)
+ return self
+
+ def log1p(self):
+ """performs elementwise log(1+x) operation
+ and returns new tensor"""
+ if self.encrypted:
+ return NotImplemented
+ out = np.log1p(self.data)
+ return TensorBase(out)
+
+ def log1p_(self):
+ """performs elementwise log(1+x) operation inplace"""
+ if self.encrypted:
+ return NotImplemented
+ self.data = np.log1p(self.data)
+ return self
+
+ def log_normal_(self, mean=0, stdev=1.0):
+ """Fills give tensor with samples from a lognormal distribution
+ with given mean and stdev"""
+ if self.encrypted:
+ return NotImplemented
+ self.data = np.random.lognormal(mean, stdev, self.shape())
+ return self
| Implement Default log Functionality for Base Tensor Type
**User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, log(), log1p(), and log_normal() should return a new tensor and log_(), log1p_(), and log_normal_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation.
**Acceptance Criteria:**
- If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error.
- a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors.
- inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. | OpenMined/PySyft | diff --git a/tests/test_tensor.py b/tests/test_tensor.py
index 1ae53eb8ce..d73c443827 100644
--- a/tests/test_tensor.py
+++ b/tests/test_tensor.py
@@ -2,6 +2,7 @@ from syft import TensorBase
import syft
import unittest
import numpy as np
+import math
# Here's our "unit tests".
@@ -374,3 +375,21 @@ class reciprocalTests(unittest.TestCase):
t1 = TensorBase(np.array([2, 3, 4]))
t1.reciprocal_()
self.assertTrue(np.allclose(t1.data, [0.5, 0.33333333, 0.25]))
+
+
+class logTests(unittest.TestCase):
+ def testLog(self):
+ t1 = TensorBase(np.array([math.exp(1), math.exp(2), math.exp(3)]))
+ self.assertTrue(np.array_equal((t1.log()).data, [1., 2., 3.]))
+
+ def testLog_(self):
+ t1 = TensorBase(np.array([math.exp(1), math.exp(2), math.exp(3)]))
+ self.assertTrue(np.array_equal((t1.log_()).data, [1., 2., 3.]))
+
+ def testLog1p(self):
+ t1 = TensorBase(np.array([1, 2, 3]))
+ self.assertTrue(np.allclose((t1.log1p()).data, [0.69314718, 1.09861229, 1.38629436]))
+
+ def testLog1p_(self):
+ t1 = TensorBase(np.array([1, 2, 3]))
+ self.assertTrue(np.allclose((t1.log1p_()).data, [0.69314718, 1.09861229, 1.38629436]))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 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": null,
"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"
} | args==0.1.0
clint==0.5.1
exceptiongroup==1.2.2
flake8==7.2.0
iniconfig==2.1.0
line_profiler==4.2.0
mccabe==0.7.0
numpy==1.26.4
packaging==24.2
phe==1.5.0
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.1
pyRserve==1.0.4
pytest==8.3.5
pytest-flake8==1.3.0
-e git+https://github.com/OpenMined/PySyft.git@a81fde47c4593a787f9bb61dd655af58497bef4a#egg=syft
tomli==2.2.1
| name: PySyft
channels:
- defaults
- https://repo.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:
- args==0.1.0
- clint==0.5.1
- exceptiongroup==1.2.2
- flake8==7.2.0
- iniconfig==2.1.0
- line-profiler==4.2.0
- mccabe==0.7.0
- numpy==1.26.4
- packaging==24.2
- phe==1.5.0
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pyrserve==1.0.4
- pytest==8.3.5
- pytest-flake8==1.3.0
- tomli==2.2.1
prefix: /opt/conda/envs/PySyft
| [
"tests/test_tensor.py::logTests::testLog",
"tests/test_tensor.py::logTests::testLog1p",
"tests/test_tensor.py::logTests::testLog1p_",
"tests/test_tensor.py::logTests::testLog_"
]
| []
| [
"tests/test_tensor.py::DimTests::testDimOne",
"tests/test_tensor.py::AddTests::testInplace",
"tests/test_tensor.py::AddTests::testScalar",
"tests/test_tensor.py::AddTests::testSimple",
"tests/test_tensor.py::CeilTests::testCeil_",
"tests/test_tensor.py::FloorTests::testFloor_",
"tests/test_tensor.py::SubTests::testInplace",
"tests/test_tensor.py::SubTests::testScalar",
"tests/test_tensor.py::SubTests::testSimple",
"tests/test_tensor.py::MultTests::testInplace",
"tests/test_tensor.py::MultTests::testScalar",
"tests/test_tensor.py::MultTests::testSimple",
"tests/test_tensor.py::DivTests::testInplace",
"tests/test_tensor.py::DivTests::testScalar",
"tests/test_tensor.py::DivTests::testSimple",
"tests/test_tensor.py::AbsTests::testabs",
"tests/test_tensor.py::AbsTests::testabs_",
"tests/test_tensor.py::ShapeTests::testShape",
"tests/test_tensor.py::SqrtTests::testSqrt",
"tests/test_tensor.py::SqrtTests::testSqrt_",
"tests/test_tensor.py::SumTests::testDimIsNotNoneInt",
"tests/test_tensor.py::SumTests::testDimNoneInt",
"tests/test_tensor.py::EqualTests::testEqOp",
"tests/test_tensor.py::EqualTests::testEqual",
"tests/test_tensor.py::EqualTests::testIneqOp",
"tests/test_tensor.py::EqualTests::testNotEqual",
"tests/test_tensor.py::IndexTests::testIndexing",
"tests/test_tensor.py::sigmoidTests::testSigmoid",
"tests/test_tensor.py::addmm::testaddmm1d",
"tests/test_tensor.py::addmm::testaddmm2d",
"tests/test_tensor.py::addmm::testaddmm_1d",
"tests/test_tensor.py::addmm::testaddmm_2d",
"tests/test_tensor.py::addcmulTests::testaddcmul1d",
"tests/test_tensor.py::addcmulTests::testaddcmul2d",
"tests/test_tensor.py::addcmulTests::testaddcmul_1d",
"tests/test_tensor.py::addcmulTests::testaddcmul_2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_2d",
"tests/test_tensor.py::addmvTests::testaddmv",
"tests/test_tensor.py::addmvTests::testaddmv_",
"tests/test_tensor.py::addbmmTests::testaddbmm",
"tests/test_tensor.py::addbmmTests::testaddbmm_",
"tests/test_tensor.py::baddbmmTests::testbaddbmm",
"tests/test_tensor.py::baddbmmTests::testbaddbmm_",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze_",
"tests/test_tensor.py::expTests::testexp",
"tests/test_tensor.py::expTests::testexp_",
"tests/test_tensor.py::fracTests::testfrac",
"tests/test_tensor.py::fracTests::testfrac_",
"tests/test_tensor.py::rsqrtTests::testrsqrt",
"tests/test_tensor.py::rsqrtTests::testrsqrt_",
"tests/test_tensor.py::numpyTests::testnumpy",
"tests/test_tensor.py::reciprocalTests::testreciprocal",
"tests/test_tensor.py::reciprocalTests::testrsqrt_"
]
| []
| Apache License 2.0 | 1,625 | [
"syft/tensor.py"
]
| [
"syft/tensor.py"
]
|
|
mozilla__bleach-302 | d77c4b7bf1a967f462d47beb8caa5e803133dfe4 | 2017-08-27 18:24:01 | 3e274abf4bb5a77720abe6687af5cfbf42de9062 | diff --git a/.gitignore b/.gitignore
index f5adb54..26bbdf8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,4 @@ build
docs/_build/
.cache/
.eggs/
+.*env*/
diff --git a/bleach/linkifier.py b/bleach/linkifier.py
index 471ce93..c8d3340 100644
--- a/bleach/linkifier.py
+++ b/bleach/linkifier.py
@@ -349,7 +349,17 @@ class LinkifyFilter(Filter):
def handle_links(self, src_iter):
"""Handle links in character tokens"""
+ in_a = False # happens, if parse_email=True and if a mail was found
for token in src_iter:
+ if in_a:
+ if token['type'] == 'EndTag' and token['name'] == 'a':
+ in_a = False
+ yield token
+ continue
+ elif token['type'] == 'StartTag' and token['name'] == 'a':
+ in_a = True
+ yield token
+ continue
if token['type'] == 'Characters':
text = token['data']
new_tokens = []
diff --git a/setup.py b/setup.py
old mode 100644
new mode 100755
index 1df9765..7e5c6ca
--- a/setup.py
+++ b/setup.py
@@ -1,3 +1,5 @@
+#!/usr/bin/env python
+
import re
import sys
| Linkify creates http link in mailto link when host contains a hyphen
Linkify creates http links **in** mailto links if the mail host name contains a hyphen `-` (and `parse_email=True`). The http link starts with the hyphen, even if host names mustn't start with hyphens at all (https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames).
```py
>>> linkify('[email protected]', parse_email=True)
'<a href="mailto:[email protected]">foo@exa<a href="http://-mple.com" rel="nofollow">-mple.com</a></a>'
```
This is what the link looks like: <a href="mailto:[email protected]">foo@exa<a href="http://-mple.com" rel="nofollow">-mple.com</a></a> :smile: | mozilla/bleach | diff --git a/tests/test_links.py b/tests/test_links.py
index b967151..3d44665 100644
--- a/tests/test_links.py
+++ b/tests/test_links.py
@@ -588,6 +588,14 @@ def test_hang():
)
+def test_hyphen_in_mail():
+ """Test hyphens `-` in mails. Issue #300."""
+ assert (
+ linkify('[email protected]', parse_email=True) ==
+ '<a href="mailto:[email protected]">[email protected]</a>'
+ )
+
+
def test_url_re_arg():
"""Verifies that a specified url_re is used"""
fred_re = re.compile(r"""(fred\.com)""")
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 3
} | 2.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest_v2",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": null,
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest -v"
} | alabaster==0.7.13
args==0.1.0
Babel==2.11.0
-e git+https://github.com/mozilla/bleach.git@d77c4b7bf1a967f462d47beb8caa5e803133dfe4#egg=bleach
certifi==2021.5.30
charset-normalizer==2.0.12
clint==0.5.1
distlib==0.3.9
docutils==0.18.1
filelock==3.4.1
flake8==3.3.0
html5lib==1.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
Jinja2==3.0.3
MarkupSafe==2.0.1
mccabe==0.6.1
pkginfo==1.10.0
platformdirs==2.4.0
pluggy==0.4.0
py==1.11.0
pycodestyle==2.3.1
pyflakes==1.5.0
Pygments==2.14.0
pytest==3.0.6
pytest-wholenodeid==0.2
pytz==2025.2
requests==2.27.1
requests-toolbelt==1.0.0
six==1.17.0
snowballstemmer==2.2.0
Sphinx==1.5.2
tox==2.4.1
twine==1.8.1
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.17.1
webencodings==0.5.1
zipp==3.6.0
| name: bleach
channels:
- defaults
- https://repo.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
- args==0.1.0
- babel==2.11.0
- charset-normalizer==2.0.12
- clint==0.5.1
- distlib==0.3.9
- docutils==0.18.1
- filelock==3.4.1
- flake8==3.3.0
- html5lib==1.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- jinja2==3.0.3
- markupsafe==2.0.1
- mccabe==0.6.1
- pkginfo==1.10.0
- platformdirs==2.4.0
- pluggy==0.4.0
- py==1.11.0
- pycodestyle==2.3.1
- pyflakes==1.5.0
- pygments==2.14.0
- pytest==3.0.6
- pytest-wholenodeid==0.2
- pytz==2025.2
- requests==2.27.1
- requests-toolbelt==1.0.0
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==1.5.2
- tox==2.4.1
- twine==1.8.1
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.17.1
- webencodings==0.5.1
- zipp==3.6.0
prefix: /opt/conda/envs/bleach
| [
"tests/test_links.py::test_hyphen_in_mail"
]
| []
| [
"tests/test_links.py::test_empty",
"tests/test_links.py::test_simple_link",
"tests/test_links.py::test_trailing_slash",
"tests/test_links.py::test_mangle_link",
"tests/test_links.py::test_mangle_text",
"tests/test_links.py::test_email_link[\"\\\\\\n\"@opa.ru-True-\"\\\\\\n\"@opa.ru]",
"tests/test_links.py::test_set_attrs",
"tests/test_links.py::test_only_proto_links",
"tests/test_links.py::test_stop_email",
"tests/test_links.py::test_tlds[example.yyy-example.yyy]",
"tests/test_links.py::test_tlds[brie-brie]",
"tests/test_links.py::test_escaping",
"tests/test_links.py::test_nofollow_off",
"tests/test_links.py::test_link_in_html",
"tests/test_links.py::test_links_https",
"tests/test_links.py::test_add_rel_nofollow",
"tests/test_links.py::test_url_with_path",
"tests/test_links.py::test_link_ftp",
"tests/test_links.py::test_link_query",
"tests/test_links.py::test_link_fragment",
"tests/test_links.py::test_link_entities",
"tests/test_links.py::test_escaped_html",
"tests/test_links.py::test_link_http_complete",
"tests/test_links.py::test_non_url",
"tests/test_links.py::test_javascript_url",
"tests/test_links.py::test_unsafe_url",
"tests/test_links.py::test_skip_tags",
"tests/test_links.py::test_libgl",
"tests/test_links.py::test_end_of_sentence[example.com-.]",
"tests/test_links.py::test_end_of_sentence[example.com-...]",
"tests/test_links.py::test_end_of_sentence[ex.com/foo-.]",
"tests/test_links.py::test_end_of_sentence[ex.com/foo-....]",
"tests/test_links.py::test_end_of_clause",
"tests/test_links.py::test_wrapping_parentheses[(example.com)-expected_data0]",
"tests/test_links.py::test_wrapping_parentheses[(example.com/)-expected_data1]",
"tests/test_links.py::test_wrapping_parentheses[(example.com/foo)-expected_data2]",
"tests/test_links.py::test_wrapping_parentheses[(((example.com/))))-expected_data3]",
"tests/test_links.py::test_wrapping_parentheses[example.com/))-expected_data4]",
"tests/test_links.py::test_wrapping_parentheses[http://en.wikipedia.org/wiki/Test_(assessment)-expected_data7]",
"tests/test_links.py::test_wrapping_parentheses[(http://en.wikipedia.org/wiki/Test_(assessment))-expected_data8]",
"tests/test_links.py::test_wrapping_parentheses[((http://en.wikipedia.org/wiki/Test_(assessment))-expected_data9]",
"tests/test_links.py::test_wrapping_parentheses[(http://en.wikipedia.org/wiki/Test_(assessment)))-expected_data10]",
"tests/test_links.py::test_wrapping_parentheses[(http://en.wikipedia.org/wiki/)Test_(assessment-expected_data11]",
"tests/test_links.py::test_parentheses_with_removing",
"tests/test_links.py::test_ports[http://foo.com:8000-expected_data0]",
"tests/test_links.py::test_ports[http://foo.com:8000/-expected_data1]",
"tests/test_links.py::test_ports[http://bar.com:xkcd-expected_data2]",
"tests/test_links.py::test_ports[http://foo.com:81/bar-expected_data3]",
"tests/test_links.py::test_ports[http://foo.com:-expected_data4]",
"tests/test_links.py::test_ports[http://foo.com:\\u0663\\u0669/-expected_data5]",
"tests/test_links.py::test_ports[http://foo.com:\\U0001d7e0\\U0001d7d8/-expected_data6]",
"tests/test_links.py::test_ignore_bad_protocols",
"tests/test_links.py::test_link_emails_and_urls",
"tests/test_links.py::test_links_case_insensitive",
"tests/test_links.py::test_elements_inside_links",
"tests/test_links.py::test_drop_link_tags",
"tests/test_links.py::test_naughty_unescaping[<br>-<br>]",
"tests/test_links.py::test_hang",
"tests/test_links.py::test_url_re_arg",
"tests/test_links.py::test_email_re_arg",
"tests/test_links.py::test_linkify_idempotent",
"tests/test_links.py::TestLinkify::test_no_href_links",
"tests/test_links.py::TestLinkify::test_rel_already_there",
"tests/test_links.py::TestLinkify::test_only_text_is_linkified"
]
| []
| Apache License 2.0 | 1,627 | [
"bleach/linkifier.py",
".gitignore",
"setup.py"
]
| [
"bleach/linkifier.py",
".gitignore",
"setup.py"
]
|
|
HewlettPackard__python-hpOneView-310 | 294a2d9f6510d39865b9bc638a2f08459a7374e2 | 2017-08-28 13:13:37 | 294a2d9f6510d39865b9bc638a2f08459a7374e2 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1c4a8175..04f9040a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,8 +1,11 @@
-# v4.1.0 (Unreleased)
+# v4.1.0
#### New Resources:
- Appliance node information
+#### Bug fixes & Enhancements
+- [#309](https://github.com/HewlettPackard/python-hpOneView/issues/309) HPOneViewException not raised when connection with paused VM fails
+
# v4.0.0
#### Notes
Major release which extends support of the SDK to OneView Rest API version 500 (OneView v3.10).
diff --git a/hpOneView/connection.py b/hpOneView/connection.py
index 4d32ad3a..bba6b8d0 100644
--- a/hpOneView/connection.py
+++ b/hpOneView/connection.py
@@ -14,6 +14,7 @@ from __future__ import unicode_literals
from builtins import open
from builtins import str
from future import standard_library
+from future.utils import raise_from
standard_library.install_aliases()
@@ -479,8 +480,11 @@ class connection(object):
# Login/Logout to/from appliance
###########################################################################
def login(self, cred, verbose=False):
- if self._validateVersion is False:
- self.validateVersion()
+ try:
+ if self._validateVersion is False:
+ self.validateVersion()
+ except Exception as e:
+ raise_from(HPOneViewException('Failure during login attempt.'), e)
self._cred = cred
try:
diff --git a/setup.py b/setup.py
index ff2ac945..3fe21c28 100644
--- a/setup.py
+++ b/setup.py
@@ -26,10 +26,10 @@ from setuptools import find_packages
from setuptools import setup
setup(name='hpOneView',
- version='4.0.0',
+ version='4.1.0',
description='HPE OneView Python Library',
url='https://github.com/HewlettPackard/python-hpOneView',
- download_url="https://github.com/HewlettPackard/python-hpOneView/tarball/v4.0.0",
+ download_url="https://github.com/HewlettPackard/python-hpOneView/tarball/v4.1.0",
author='Hewlett Packard Enterprise Development LP',
author_email='[email protected]',
license='MIT',
| HPOneViewException not raised when connection with paused VM fails
Hi guys,
When I try to create the OneView client but my VM is paused, an **OSError** exception is raised instead of a HPOneViewException. The HPOneViewException should not cover this type of exception in this scenario? For treat this exception is only possible if I catch an **OSError**, but is seems odd for me since this also could be used as a HPOneViewException maybe.
**Code example:**
```python
#VM paused
config = {
"ip": "x.x.x.x",
"credentials": {
"userName": "user_name",
"password": "pass"
}
}
oneview_client = OneViewClient(config)
```
**Result:**
```shell
Traceback (most recent call last):
File "one_view.py", line 89, in <module>
one_view = OneView(config)
File "one_view.py", line 12, in __init__
self.oneview_client = OneViewClient(config)
File "/usr/local/lib/python3.5/dist-packages/hpOneView/oneview_client.py", line 118, in __init__
self.__connection.login(config["credentials"])
File "/usr/local/lib/python3.5/dist-packages/hpOneView/connection.py", line 483, in login
self.validateVersion()
File "/usr/local/lib/python3.5/dist-packages/hpOneView/connection.py", line 79, in validateVersion
version = self.get(uri['version'])
File "/usr/local/lib/python3.5/dist-packages/hpOneView/connection.py", line 324, in get
resp, body = self.do_http('GET', uri, '')
File "/usr/local/lib/python3.5/dist-packages/hpOneView/connection.py", line 126, in do_http
conn.request(method, path, body, http_headers)
File "/usr/lib/python3.5/http/client.py", line 1106, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python3.5/http/client.py", line 1151, in _send_request
self.endheaders(body)
File "/usr/lib/python3.5/http/client.py", line 1102, in endheaders
self._send_output(message_body)
File "/usr/lib/python3.5/http/client.py", line 934, in _send_output
self.send(msg)
File "/usr/lib/python3.5/http/client.py", line 877, in send
self.connect()
File "/usr/lib/python3.5/http/client.py", line 1252, in connect
super().connect()
File "/usr/lib/python3.5/http/client.py", line 849, in connect
(self.host,self.port), self.timeout, self.source_address)
File "/usr/lib/python3.5/socket.py", line 711, in create_connection
raise err
File "/usr/lib/python3.5/socket.py", line 702, in create_connection
sock.connect(sa)
OSError: [Errno 113] No route to host
```
| HewlettPackard/python-hpOneView | diff --git a/tests/unit/test_connection.py b/tests/unit/test_connection.py
index 9206ed11..4a5a9cdc 100644
--- a/tests/unit/test_connection.py
+++ b/tests/unit/test_connection.py
@@ -869,6 +869,13 @@ class ConnectionTest(unittest.TestCase):
self.assertEqual(self.connection.get_session_id(), '123')
self.assertEqual(self.connection.get_session(), True)
+ @patch.object(connection, 'get')
+ def test_login_catches_exceptions_as_hpOneView(self, mock_get):
+ mock_get.side_effect = [Exception('test')]
+
+ with self.assertRaises(HPOneViewException):
+ self.connection.login({})
+
@patch.object(connection, 'get')
@patch.object(connection, 'post')
def test_login_with_exception_in_post(self, mock_post, mock_get):
| {
"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": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 3
} | 4.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",
"mock"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup==1.2.2
future==1.0.0
-e git+https://github.com/HewlettPackard/python-hpOneView.git@294a2d9f6510d39865b9bc638a2f08459a7374e2#egg=hpOneView
iniconfig==2.1.0
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
tomli==2.2.1
| name: python-hpOneView
channels:
- defaults
- https://repo.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
- future==1.0.0
- iniconfig==2.1.0
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/python-hpOneView
| [
"tests/unit/test_connection.py::ConnectionTest::test_login_catches_exceptions_as_hpOneView"
]
| []
| [
"tests/unit/test_connection.py::ConnectionTest::test_default_headers",
"tests/unit/test_connection.py::ConnectionTest::test_default_headers_when_etag_validation_is_disabled",
"tests/unit/test_connection.py::ConnectionTest::test_default_headers_when_etag_validation_is_disabled_and_enabled",
"tests/unit/test_connection.py::ConnectionTest::test_default_headers_when_etag_validation_is_enabled",
"tests/unit/test_connection.py::ConnectionTest::test_default_headers_when_etag_validation_is_enabled_and_disabled",
"tests/unit/test_connection.py::ConnectionTest::test_delete_should_do_rest_calls_when_status_accepted",
"tests/unit/test_connection.py::ConnectionTest::test_delete_should_do_rest_calls_when_status_ok",
"tests/unit/test_connection.py::ConnectionTest::test_delete_should_raise_exception_when_status_internal_error",
"tests/unit/test_connection.py::ConnectionTest::test_delete_should_raise_exception_when_status_not_found",
"tests/unit/test_connection.py::ConnectionTest::test_delete_should_return_body_when_status_ok",
"tests/unit/test_connection.py::ConnectionTest::test_delete_should_return_tuple_when_status_accepted",
"tests/unit/test_connection.py::ConnectionTest::test_delete_should_send_merged_headers_when_headers_provided",
"tests/unit/test_connection.py::ConnectionTest::test_do_http_with_bad_status_line",
"tests/unit/test_connection.py::ConnectionTest::test_do_http_with_invalid_json_return",
"tests/unit/test_connection.py::ConnectionTest::test_do_http_with_invalid_unicode",
"tests/unit/test_connection.py::ConnectionTest::test_do_rest_call_with_304_status",
"tests/unit/test_connection.py::ConnectionTest::test_do_rest_call_with_304_status_and_invalid_json",
"tests/unit/test_connection.py::ConnectionTest::test_download_to_stream_when_error_status_with_decode_error",
"tests/unit/test_connection.py::ConnectionTest::test_download_to_stream_when_error_status_with_empty_body",
"tests/unit/test_connection.py::ConnectionTest::test_download_to_stream_when_error_status_with_response_body",
"tests/unit/test_connection.py::ConnectionTest::test_download_to_stream_when_status_ok",
"tests/unit/test_connection.py::ConnectionTest::test_encode_multipart_formdata",
"tests/unit/test_connection.py::ConnectionTest::test_get_connection_ssl_trust_all",
"tests/unit/test_connection.py::ConnectionTest::test_get_connection_ssl_trust_all_with_proxy",
"tests/unit/test_connection.py::ConnectionTest::test_get_connection_trusted_ssl_bundle",
"tests/unit/test_connection.py::ConnectionTest::test_get_connection_trusted_ssl_bundle_with_proxy",
"tests/unit/test_connection.py::ConnectionTest::test_headers_with_api_version_300",
"tests/unit/test_connection.py::ConnectionTest::test_login",
"tests/unit/test_connection.py::ConnectionTest::test_login_with_exception_in_post",
"tests/unit/test_connection.py::ConnectionTest::test_patch_should_do_rest_call_when_status_ok",
"tests/unit/test_connection.py::ConnectionTest::test_patch_should_do_rest_calls_when_status_accepted",
"tests/unit/test_connection.py::ConnectionTest::test_patch_should_raise_exception_when_status_internal_error",
"tests/unit/test_connection.py::ConnectionTest::test_patch_should_raise_exception_when_status_not_found",
"tests/unit/test_connection.py::ConnectionTest::test_patch_should_return_body_when_status_ok",
"tests/unit/test_connection.py::ConnectionTest::test_patch_should_return_tuple_when_status_accepted",
"tests/unit/test_connection.py::ConnectionTest::test_patch_should_send_merged_headers_when_headers_provided",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_should_handle_json_load_exception",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_should_put_headers",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_should_put_request",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_should_raise_exception_when_response_status_400",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_should_read_file_in_chunks_of_1mb",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_should_remove_temp_encoded_file",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_should_return_response_and_body_when_response_status_200",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_should_send_file_in_chuncks_of_1mb",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_with_response_handling_when_status_200_and_body_is_not_task",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_with_response_handling_when_status_200_and_body_is_task",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_with_response_handling_when_status_202_with_task",
"tests/unit/test_connection.py::ConnectionTest::test_post_multipart_with_response_handling_when_status_202_without_task",
"tests/unit/test_connection.py::ConnectionTest::test_post_should_do_rest_call_when_status_ok",
"tests/unit/test_connection.py::ConnectionTest::test_post_should_do_rest_calls_when_status_accepted",
"tests/unit/test_connection.py::ConnectionTest::test_post_should_raise_exception_when_status_internal_error",
"tests/unit/test_connection.py::ConnectionTest::test_post_should_raise_exception_when_status_not_found",
"tests/unit/test_connection.py::ConnectionTest::test_post_should_return_body_when_status_ok",
"tests/unit/test_connection.py::ConnectionTest::test_post_should_return_tuple_when_status_accepted",
"tests/unit/test_connection.py::ConnectionTest::test_post_should_send_merged_headers_when_headers_provided",
"tests/unit/test_connection.py::ConnectionTest::test_post_when_status_is_202_and_response_is_not_a_task",
"tests/unit/test_connection.py::ConnectionTest::test_post_when_status_is_202_and_task_contains_taskState",
"tests/unit/test_connection.py::ConnectionTest::test_put_should_do_rest_call_when_status_ok",
"tests/unit/test_connection.py::ConnectionTest::test_put_should_do_rest_calls_when_status_accepted",
"tests/unit/test_connection.py::ConnectionTest::test_put_should_raise_exception_when_status_internal_error",
"tests/unit/test_connection.py::ConnectionTest::test_put_should_raise_exception_when_status_not_found",
"tests/unit/test_connection.py::ConnectionTest::test_put_should_return_body_when_status_ok",
"tests/unit/test_connection.py::ConnectionTest::test_put_should_return_tuple_when_status_accepted",
"tests/unit/test_connection.py::ConnectionTest::test_put_should_send_merged_headers_when_headers_provided",
"tests/unit/test_connection.py::ConnectionTest::test_task_in_response_body_without_202_status",
"tests/unit/test_connection.py::ConnectionTest::test_validate_version_exceeding_current",
"tests/unit/test_connection.py::ConnectionTest::test_validate_version_exceeding_minimum"
]
| []
| MIT License | 1,628 | [
"setup.py",
"hpOneView/connection.py",
"CHANGELOG.md"
]
| [
"setup.py",
"hpOneView/connection.py",
"CHANGELOG.md"
]
|
|
peterbe__hashin-50 | ac3f43043a3de7e9b87c731d2aeccf7713c1d465 | 2017-08-28 13:47:42 | ac3f43043a3de7e9b87c731d2aeccf7713c1d465 | diff --git a/hashin.py b/hashin.py
index 6856bcb..f2b3c1e 100755
--- a/hashin.py
+++ b/hashin.py
@@ -430,13 +430,17 @@ def main():
args = parser.parse_args()
- return run(
- args.packages,
- args.requirements_file,
- args.algorithm,
- args.python_version,
- verbose=args.verbose,
- )
+ try:
+ return run(
+ args.packages,
+ args.requirements_file,
+ args.algorithm,
+ args.python_version,
+ verbose=args.verbose,
+ )
+ except PackageError as exception:
+ print(str(exception), file=sys.stderr)
+ return 1
if __name__ == '__main__':
| Python version typos generate messy exception
Currently, if I specify the python version improperly, or there is no package for that version, I get an exception thrown:
```
$ hashin -p python2.8 -v -r requirements.txt pyasn1==0.2.3
https://pypi.python.org/pypi/pyasn1/json
Traceback (most recent call last):
File "/Users/hwine/.pyenv/versions/tools3/bin/hashin", line 11, in <module>
sys.exit(main())
File "/Users/hwine/.pyenv/versions/3.6.1/envs/tools3/lib/python3.6/site-packages/hashin.py", line 432, in main
verbose=args.verbose,
File "/Users/hwine/.pyenv/versions/3.6.1/envs/tools3/lib/python3.6/site-packages/hashin.py", line 104, in run
run_single_package(spec, *args, **kwargs)
File "/Users/hwine/.pyenv/versions/3.6.1/envs/tools3/lib/python3.6/site-packages/hashin.py", line 127, in run_single_package
algorithm=algorithm
File "/Users/hwine/.pyenv/versions/3.6.1/envs/tools3/lib/python3.6/site-packages/hashin.py", line 399, in get_package_hashes
python_versions
hashin.PackageError: No releases could be found for 0.2.3 matching Python versions ['python2.8']
```
The last line is great! The traceback doesn't help much in this case. | peterbe/hashin | diff --git a/tests/test_cli.py b/tests/test_cli.py
index af232ad..10e6206 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -142,6 +142,18 @@ class Tests(TestCase):
'sha256'
)
+ @mock.patch('hashin.parser')
+ @mock.patch('hashin.sys')
+ @mock.patch('hashin.run')
+ def test_main_packageerrors_stderr(self, mock_run, mock_sys, mock_parser):
+ # Doesn't matter so much what, just make sure it breaks
+ mock_run.side_effect = hashin.PackageError('Some message here')
+
+ error = hashin.main()
+ self.assertEqual(error, 1)
+ mock_sys.stderr.write.assert_any_call('Some message here')
+ mock_sys.stderr.write.assert_any_call('\n')
+
def test_amend_requirements_content_new(self):
requirements = """
# empty so far
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"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": "pytest",
"pip_packages": [
"nose",
"mock",
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
-e git+https://github.com/peterbe/hashin.git@ac3f43043a3de7e9b87c731d2aeccf7713c1d465#egg=hashin
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
mock==5.2.0
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
| name: hashin
channels:
- defaults
- https://repo.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
- nose==1.3.7
prefix: /opt/conda/envs/hashin
| [
"tests/test_cli.py::Tests::test_main_packageerrors_stderr"
]
| [
"tests/test_cli.py::Tests::test_as_library",
"tests/test_cli.py::Tests::test_run",
"tests/test_cli.py::Tests::test_run_case_insensitive",
"tests/test_cli.py::Tests::test_run_contained_names"
]
| [
"tests/test_cli.py::Tests::test_amend_requirements_content_new",
"tests/test_cli.py::Tests::test_amend_requirements_content_new_similar_name",
"tests/test_cli.py::Tests::test_amend_requirements_content_replacement",
"tests/test_cli.py::Tests::test_amend_requirements_content_replacement_2",
"tests/test_cli.py::Tests::test_amend_requirements_content_replacement_amonst_others",
"tests/test_cli.py::Tests::test_amend_requirements_content_replacement_amonst_others_2",
"tests/test_cli.py::Tests::test_amend_requirements_content_replacement_single_to_multi",
"tests/test_cli.py::Tests::test_expand_python_version",
"tests/test_cli.py::Tests::test_filter_releases",
"tests/test_cli.py::Tests::test_get_hashes_error",
"tests/test_cli.py::Tests::test_get_latest_version_non_pre_release",
"tests/test_cli.py::Tests::test_get_latest_version_non_pre_release_leading_zeros",
"tests/test_cli.py::Tests::test_get_latest_version_simple",
"tests/test_cli.py::Tests::test_non_200_ok_download",
"tests/test_cli.py::Tests::test_release_url_metadata_python"
]
| []
| MIT License | 1,629 | [
"hashin.py"
]
| [
"hashin.py"
]
|
|
Netuitive__netuitive-statsd-14 | 0b8c90d3a351de7f0b6d6ec5915af31263702590 | 2017-08-28 14:34:19 | 0b8c90d3a351de7f0b6d6ec5915af31263702590 | diff --git a/libs/config.py b/libs/config.py
index c43a9a0..5d68cb9 100644
--- a/libs/config.py
+++ b/libs/config.py
@@ -6,30 +6,18 @@ import socket
import os
import configobj
import sys
+import subprocess
logger = logging.getLogger(__name__)
def config(args=None):
- # try to find the hostname
- hostname = socket.getfqdn().split('.')[0]
-
- if hostname == 'localhost':
- hostname = socket.gethostname().split('.')[0]
-
- if hostname == 'localhost':
- hostname = os.uname()[1].split('.')[0]
-
- if hostname == 'localhost':
- logger.error('could not determine hostname')
-
# default config
ret = {
'enabled': True,
'url': 'https://api.app.netuitive.com/ingest',
'api_key': None,
- 'hostname': hostname,
'interval': 60,
'element_type': 'SERVER',
'prefix': 'statsd',
@@ -67,6 +55,7 @@ def config(args=None):
# assemble the config from config file
+ ret['hostname'] = get_hostname(cfg)
ret['configfile'] = configfile
ret['url'] = cfg['handlers']['NetuitiveHandler']['url']
ret['api_key'] = cfg['handlers'][
@@ -162,3 +151,98 @@ def config(args=None):
except Exception as e:
logger.error(e, exc_info=True)
raise(e)
+
+
+def get_hostname(fullconfig, method=None):
+ """
+ Returns a hostname as configured by the user
+ """
+ config = fullconfig.get('collectors').get('default')
+ method = method or config.get('hostname_method', 'smart')
+
+ # case insensitive method
+ method = method.lower()
+
+ if 'hostname' in config and method != 'shell':
+ return config['hostname']
+
+ if method == 'shell':
+ if 'hostname' not in config:
+ raise Exception(
+ "hostname must be set to a shell command for"
+ " hostname_method=shell")
+ else:
+ proc = subprocess.Popen(config['hostname'],
+ shell=True,
+ stdout=subprocess.PIPE)
+ hostname = proc.communicate()[0].strip()
+ if proc.returncode != 0:
+ raise subprocess.CalledProcessError(proc.returncode,
+ config['hostname'])
+ return hostname
+
+ if method == 'smart':
+ hostname = get_hostname(config, 'fqdn_short')
+ if hostname != 'localhost':
+ return hostname
+ hostname = get_hostname(config, 'hostname_short')
+ return hostname
+
+ if method == 'fqdn_short':
+ hostname = socket.getfqdn().split('.')[0]
+ if hostname == '':
+ raise Exception('Hostname is empty?!')
+ return hostname
+
+ if method == 'fqdn':
+ hostname = socket.getfqdn().replace('.', '_')
+ if hostname == '':
+ raise Exception('Hostname is empty?!')
+ return hostname
+
+ if method == 'fqdn_rev':
+ hostname = socket.getfqdn().split('.')
+ hostname.reverse()
+ hostname = '.'.join(hostname)
+ if hostname == '':
+ raise Exception('Hostname is empty?!')
+ return hostname
+
+ if method == 'uname_short':
+ hostname = os.uname()[1].split('.')[0]
+ if hostname == '':
+ raise Exception('Hostname is empty?!')
+ return hostname
+
+ if method == 'uname_rev':
+ hostname = os.uname()[1].split('.')
+ hostname.reverse()
+ hostname = '.'.join(hostname)
+ if hostname == '':
+ raise Exception('Hostname is empty?!')
+ return hostname
+
+ if method == 'hostname':
+ hostname = socket.gethostname()
+ if hostname == '':
+ raise Exception('Hostname is empty?!')
+ return hostname
+
+ if method == 'hostname_short':
+ hostname = socket.gethostname().split('.')[0]
+ if hostname == '':
+ raise Exception('Hostname is empty?!')
+ return hostname
+
+ if method == 'hostname_rev':
+ hostname = socket.gethostname().split('.')
+ hostname.reverse()
+ hostname = '.'.join(hostname)
+ if hostname == '':
+ raise Exception('Hostname is empty?!')
+ return hostname
+
+ if method == 'none':
+ return None
+
+ raise NotImplementedError(config['hostname_method'])
diff --git a/netuitive-statsd.conf.example b/netuitive-statsd.conf.example
index b231aae..eb08f33 100644
--- a/netuitive-statsd.conf.example
+++ b/netuitive-statsd.conf.example
@@ -28,6 +28,26 @@ enabled = True
[[default]]
hostname = statsd-test-host
+# If you prefer to just use a different way of calculating the hostname
+# Uncomment and set this to one of these values:
+
+# smart = Default. Tries fqdn_short. If that's localhost, uses hostname_short
+
+# fqdn_short = Default. Similar to hostname -s
+# fqdn = hostname output
+# fqdn_rev = hostname in reverse (com.example.www)
+
+# uname_short = Similar to uname -n, but only the first part
+# uname_rev = uname -r in reverse (com.example.www)
+
+# hostname_short = `hostname -s`
+# hostname = `hostname`
+# hostname_rev = `hostname` in reverse (com.example.www)
+
+# shell = Run the string set in hostname as a shell command and use its
+# output(with spaces trimmed off from both ends) as the hostname.
+
+# hostname_method = smart
[logger_root]
| Support More Flexible Hostname Methods
Ideally this will match the Metricly Diamond project:
https://github.com/Netuitive/netuitive-diamond/blob/f48a0bc7de6038164e0919e2d3d0fd524c83e1d9/conf/diamond.conf.example#L146-L169 | Netuitive/netuitive-statsd | diff --git a/tests/test_config.py b/tests/test_config.py
index 197d8cb..9a5512c 100755
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -32,7 +32,6 @@ class Test_Config(unittest.TestCase):
'forward': False,
'forward_ip': None,
'forward_port': None,
- 'hostname': socket.getfqdn().split('.')[0],
'interval': 60,
'listen_ip': '127.0.0.1',
'listen_port': 8125,
| {
"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": 3,
"test_score": 3
},
"num_modified_files": 2
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"mock",
"flake8",
"coverage",
"coveralls"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
charset-normalizer==2.0.12
configobj==5.0.8
coverage==6.2
coveralls==3.3.1
docopt==0.6.2
docutils==0.18.1
flake8==5.0.4
idna==3.10
importlib-metadata==4.2.0
iniconfig==1.1.1
mccabe==0.7.0
mock==5.2.0
netuitive==0.3.4
-e git+https://github.com/Netuitive/netuitive-statsd.git@0b8c90d3a351de7f0b6d6ec5915af31263702590#egg=netuitive_statsd
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
requests==2.27.1
setproctitle==1.2.3
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: netuitive-statsd
channels:
- defaults
- https://repo.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
- configobj==5.0.8
- coverage==6.2
- coveralls==3.3.1
- docopt==0.6.2
- docutils==0.18.1
- flake8==5.0.4
- idna==3.10
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- mccabe==0.7.0
- mock==5.2.0
- netuitive==0.3.4
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pytest==7.0.1
- requests==2.27.1
- setproctitle==1.2.3
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/netuitive-statsd
| [
"tests/test_config.py::Test_Config::test_defaults"
]
| []
| [
"tests/test_config.py::Test_Config::test_args_and_configfile",
"tests/test_config.py::Test_Config::test_args_only",
"tests/test_config.py::Test_Config::test_missing_configfile"
]
| []
| Apache License 2.0 | 1,630 | [
"libs/config.py",
"netuitive-statsd.conf.example"
]
| [
"libs/config.py",
"netuitive-statsd.conf.example"
]
|
|
hylang__hy-1403 | 3db13ec71f2c79a1b91f3e0a7169d85658a410a1 | 2017-08-28 16:33:28 | 5c720c0110908e3f47dba2e4cc1c820d16f359a1 | diff --git a/NEWS b/NEWS
index 468d884a..3e23f668 100644
--- a/NEWS
+++ b/NEWS
@@ -34,6 +34,7 @@ Changes from 0.13.0
* Fixed a crash when `macroexpand`ing a macro with a named import
* Fixed a crash when `with` suppresses an exception. `with` now returns
`None` in this case.
+ * Fixed a crash when --repl-output-fn raises an exception
* `assoc` now evaluates its arguments only once each
* `break` and `continue` now raise an error when given arguments
instead of silently ignoring them
diff --git a/hy/cmdline.py b/hy/cmdline.py
index a9d966c0..fb585392 100644
--- a/hy/cmdline.py
+++ b/hy/cmdline.py
@@ -115,7 +115,12 @@ class HyREPL(code.InteractiveConsole):
# the user as `_`.
self.locals['_'] = value
# Print the value.
- print(self.output_fn(value))
+ try:
+ output = self.output_fn(value)
+ except Exception:
+ self.showtraceback()
+ return False
+ print(output)
return False
| Exception in __repr__ crashes repl
```Python
=> (defclass BadRepr[] (defn __repr__ [self] (/ 0)))
class BadRepr:
def __repr__(self):
return (1 / 0)
None
=> (BadRepr)
BadRepr()
Traceback (most recent call last):
File "C:\Users\ME\workspace\hy36-gilch\Scripts\hy-script.py", line 11, in <module>
load_entry_point('hy', 'console_scripts', 'hy')()
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 341, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 336, in cmdline_handler
return run_repl(spy=options.spy, output_fn=options.repl_output_fn)
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 231, in run_repl
os=platform.system()
File "C:\Users\ME\AppData\Local\Programs\Python\Python36\lib\code.py", line 233, in interact
more = self.push(line)
File "C:\Users\ME\AppData\Local\Programs\Python\Python36\lib\code.py", line 259, in push
more = self.runsource(source, self.filename)
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 118, in runsource
print(self.output_fn(value))
File "<eval_body>", line 1, in __repr__
ZeroDivisionError: division by zero
(hy36-gilch) C:\Users\ME\Documents\GitHub\hy>
```
It should just report the exception like Python does, not quit the repl. | hylang/hy | diff --git a/tests/test_bin.py b/tests/test_bin.py
index 6df4d437..670b77a2 100644
--- a/tests/test_bin.py
+++ b/tests/test_bin.py
@@ -132,6 +132,16 @@ def test_bin_hy_stdin_except_do():
assert "zzz" in output
+def test_bin_hy_stdin_bad_repr():
+ # https://github.com/hylang/hy/issues/1389
+ output, err = run_cmd("hy", """
+ (defclass BadRepr [] (defn __repr__ [self] (/ 0)))
+ (BadRepr)
+ (+ "A" "Z")""")
+ assert "ZeroDivisionError" in err
+ assert "AZ" in output
+
+
def test_bin_hy_stdin_hy_repr():
output, _ = run_cmd("hy", '(+ [1] [2])')
assert "[1, 2]" in output.replace('L', '')
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 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"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
appdirs==1.4.4
args==0.1.0
astor==0.8.1
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
clint==0.5.1
coverage==6.2
distlib==0.3.9
docutils==0.17.1
filelock==3.4.1
flake8==5.0.4
-e git+https://github.com/hylang/hy.git@3db13ec71f2c79a1b91f3e0a7169d85658a410a1#egg=hy
idna==3.10
imagesize==1.4.1
importlib-metadata==4.2.0
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mccabe==0.7.0
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
rply==0.7.8
six==1.17.0
snowballstemmer==2.2.0
Sphinx==4.3.2
sphinx-rtd-theme==1.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.16.2
zipp==3.6.0
| name: hy
channels:
- defaults
- https://repo.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
- appdirs==1.4.4
- args==0.1.0
- astor==0.8.1
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- clint==0.5.1
- coverage==6.2
- distlib==0.3.9
- docutils==0.17.1
- filelock==3.4.1
- flake8==5.0.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.2.0
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mccabe==0.7.0
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- rply==0.7.8
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==4.3.2
- sphinx-rtd-theme==1.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.16.2
- zipp==3.6.0
prefix: /opt/conda/envs/hy
| [
"tests/test_bin.py::test_bin_hy_stdin_bad_repr"
]
| [
"tests/test_bin.py::test_bin_hy_stdin",
"tests/test_bin.py::test_bin_hy_icmd_and_spy"
]
| [
"tests/test_bin.py::test_bin_hy",
"tests/test_bin.py::test_bin_hy_stdin_multiline",
"tests/test_bin.py::test_bin_hy_stdin_comments",
"tests/test_bin.py::test_bin_hy_stdin_assignment",
"tests/test_bin.py::test_bin_hy_stdin_as_arrow",
"tests/test_bin.py::test_bin_hy_stdin_error_underline_alignment",
"tests/test_bin.py::test_bin_hy_stdin_except_do",
"tests/test_bin.py::test_bin_hy_stdin_hy_repr",
"tests/test_bin.py::test_bin_hy_cmd",
"tests/test_bin.py::test_bin_hy_icmd",
"tests/test_bin.py::test_bin_hy_icmd_file",
"tests/test_bin.py::test_bin_hy_missing_file",
"tests/test_bin.py::test_bin_hy_file_with_args",
"tests/test_bin.py::test_bin_hyc",
"tests/test_bin.py::test_bin_hyc_missing_file",
"tests/test_bin.py::test_hy2py",
"tests/test_bin.py::test_bin_hy_builtins",
"tests/test_bin.py::test_bin_hy_main",
"tests/test_bin.py::test_bin_hy_main_args",
"tests/test_bin.py::test_bin_hy_main_exitvalue",
"tests/test_bin.py::test_bin_hy_no_main",
"tests/test_bin.py::test_bin_hy_byte_compile[hy",
"tests/test_bin.py::test_bin_hy_module_main",
"tests/test_bin.py::test_bin_hy_module_main_args",
"tests/test_bin.py::test_bin_hy_module_main_exitvalue",
"tests/test_bin.py::test_bin_hy_module_no_main"
]
| []
| MIT License | 1,631 | [
"hy/cmdline.py",
"NEWS"
]
| [
"hy/cmdline.py",
"NEWS"
]
|
|
smarkets__marge-bot-48 | 2ce32f55eede12f76b7a760fbdf3ee2cd15a7bb6 | 2017-08-28 17:51:03 | 48d0576a978af8b71f4971926e345d7d1425a8c0 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6627c28..9002695 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,5 @@
+ * 0.3.2: Fix support for branches with "/" in their names #50.
+ * 0.3.1: Fix start-up error when running as non-admin user #49.
* 0.3.0:
- Display better messages when GitLab refuses to merge #32, #33.
- Handle auto-squash being selected #14.
diff --git a/README.md b/README.md
index 02f2f47..751b94a 100644
--- a/README.md
+++ b/README.md
@@ -139,9 +139,10 @@ ktmpl ./deploy.yml \
commits in the merge request as described in the next section.
-## Adding Reviewed-by: and Tested: messages to commits
+## Adding Reviewed-by:, Tested: and Part-of: to commit messages
+
Marge-bot supports automated addition of the following
-two [standardized git commit headers](https://www.kernel.org/doc/html/v4.11/process/submitting-patches.html#using-reported-by-tested-by-reviewed-by-suggested-by-and-fixes):
+two [standardized git commit trailers](https://www.kernel.org/doc/html/v4.11/process/submitting-patches.html#using-reported-by-tested-by-reviewed-by-suggested-by-and-fixes):
`Reviewed-by` and `Tested-by`. For the latter it uses `Marge Bot
<$MERGE_REQUEST_URL>` as a slight abuse of the convention (here `Marge Bot` is
the name of the `marge-bot` user in GitLab).
@@ -155,20 +156,27 @@ target branch into your PR branch:
Reviewed-by: A. Reviewer <[email protected]>
```
-All existing `Reviewed-by:` tags on commits in the branch will be stripped. This
+All existing `Reviewed-by:` trailers on commits in the branch will be stripped. This
feature requires marge to run with admin privileges due to a peculiarity of the
GitLab API: only admin users can obtain email addresses of other users, even
ones explicitly declared as public (strangely this limitation is particular to
email, Skype handles etc. are visible to everyone).
-If you pass `--add-tested` the final commit in a PR will be tagged with
-`Tested-by: marge-bot <$MERGE_REQUEST_URL>`. This can be very useful for two
-reasons:
+If you pass `--add-tested` the final commit message in a PR will be tagged with
+`Tested-by: marge-bot <$MERGE_REQUEST_URL>` trailer. This can be very useful for
+two reasons:
1. Seeing where stuff "came from" in a rebase-based workflow
2. Knowing that a commit has been tested, which is e.g. important for bisection
so you can easily and automatically `git bisect --skip` untested commits.
+Additionally, by using `--add-part-of`, all commit messages will be tagged with
+a `Part-of: <$MERGE_REQUEST_URL>` trailer to the merge request on which they
+were merged. This is useful, for example, to go from a commit shown in `git
+blame` to the merge request on which it was introduced or to easily revert a all
+commits introduced by a single Merge Request when using a fast-forward/rebase
+based merge workflow.
+
## Impersonating approvers
If you want a full audit trail, you will configure Gitlab
[require approvals](https://docs.gitlab.com/ee/user/project/merge_requests/merge_request_approvals.html#approvals-required)
diff --git a/deploy.yml b/deploy.yml
index 7f295c3..852e8de 100644
--- a/deploy.yml
+++ b/deploy.yml
@@ -36,7 +36,11 @@ objects:
- name: app
image: "$(APP_IMAGE)"
imagePullPolicy: Always
- args: ["--gitlab-url=$(MARGE_GITLAB_URL)", "--impersonate-approvers", "--add-tested"]
+ args: ["--gitlab-url=$(MARGE_GITLAB_URL)",
+ "--impersonate-approvers",
+ "--add-tested",
+ "--add-reviewed-by",
+ "--add-part-of"]
env:
- name: MARGE_AUTH_TOKEN
valueFrom:
diff --git a/marge/app.py b/marge/app.py
index eda524f..847cffe 100644
--- a/marge/app.py
+++ b/marge/app.py
@@ -68,14 +68,19 @@ def _parse_args(args):
help='Time(s) during which no merging is to take place, e.g. "Friday 1pm - Monday 9am".',
)
arg(
- '--add-reviewers',
+ '--add-tested',
action='store_true',
- help='add Reviewed-by: $approver for each approver of PR to each commit in PR'
+ help='add Tested: marge-bot <$PR_URL> for the final commit on branch after it passed CI',
)
arg(
- '--add-tested',
+ '--add-part-of',
action='store_true',
- help='add Tested: marge-bot <$PR_URL> for the final commit on branch after it passed CI',
+ help='add Part-of: <$PR_URL> to each commit in PR (except top commit when --add-tested is used)',
+ )
+ arg(
+ '--add-reviewers',
+ action='store_true',
+ help='add Reviewed-by: $approver for each approver of PR to each commit in PR',
)
arg(
'--impersonate-approvers',
@@ -140,6 +145,7 @@ def main(args=sys.argv[1:]):
project_regexp=options.project_regexp,
merge_opts=bot.MergeJobOptions.default(
add_tested=options.add_tested,
+ add_part_of=options.add_part_of,
add_reviewers=options.add_reviewers,
reapprove=options.impersonate_approvers,
embargo=options.embargo,
diff --git a/marge/bot.py b/marge/bot.py
index ad92db5..2d9cd43 100644
--- a/marge/bot.py
+++ b/marge/bot.py
@@ -21,7 +21,7 @@ class Bot(object):
opts = config.merge_opts
if not user.is_admin:
- assert not opts.impersonate_approvers, (
+ assert not opts.reapprove, (
"{0.username} is not an admin, can't impersonate!".format(user)
)
assert not opts.add_reviewers, (
diff --git a/marge/commit.py b/marge/commit.py
index b6df891..91a4316 100644
--- a/marge/commit.py
+++ b/marge/commit.py
@@ -1,5 +1,7 @@
import re
+from requests.utils import quote
+
from . import gitlab
@@ -23,7 +25,7 @@ class Commit(gitlab.Resource):
info = api.call(GET(
'/projects/{project_id}/repository/branches/{branch}'.format(
project_id=project_id,
- branch=branch,
+ branch=quote(branch, safe=''),
),
))['commit']
return cls(api, info)
diff --git a/marge/job.py b/marge/job.py
index b2078d8..5287bc4 100644
--- a/marge/job.py
+++ b/marge/job.py
@@ -10,7 +10,7 @@ from .project import Project
from .user import User
class MergeJob(object):
- def __init__(self, api, user, project, merge_request, repo, options):
+ def __init__(self, *, api, user, project, merge_request, repo, options):
self._api = api
self._user = user
self._project = project
@@ -100,6 +100,10 @@ class MergeJob(object):
_get_reviewer_names_and_emails(approvals=approvals, api=api) if self.opts.add_reviewers
else None
)
+ part_of = (
+ '<{0.web_url}>'.format(merge_request) if self.opts.add_part_of
+ else None
+ )
source_repo_url = None if source_project is self._project else source_project.ssh_url_to_repo
# NB. this will be a no-op if there is nothing to rebase/rewrite
target_sha, _rebased_sha, actual_sha = push_rebased_and_rewritten_version(
@@ -109,6 +113,7 @@ class MergeJob(object):
source_repo_url=source_repo_url,
reviewers=reviewers,
tested_by=tested_by,
+ part_of=part_of,
)
log.info('Commit id to merge %r (into: %r)', actual_sha, target_sha)
time.sleep(5)
@@ -142,7 +147,7 @@ class MergeJob(object):
if new_target_sha != target_sha:
log.info('Someone was naughty and by-passed marge')
merge_request.comment(
- "My job would be easier if people didn't jump the queue and pushed directly... *sigh*"
+ "My job would be easier if people didn't jump the queue and push directly... *sigh*"
)
continue
# otherwise the source branch has been pushed to or something
@@ -247,12 +252,14 @@ class MergeJob(object):
return self.opts.embargo.covers(now)
def push_rebased_and_rewritten_version(
+ *,
repo,
source_branch,
target_branch,
source_repo_url=None,
reviewers=None,
tested_by=None,
+ part_of=None,
):
"""Rebase `target_branch` into `source_branch`, optionally add trailers and push.
@@ -273,6 +280,8 @@ def push_rebased_and_rewritten_version(
tested_by
A list like ``["User Name <[email protected]>", ...]`` or `None`. ``None`` means
existing Tested-by lines will be left alone, otherwise they will be replaced.
+ part_of
+ A string with likely a link to the merge request this commit is part-of, or ``None``.
Returns
-------
@@ -302,7 +311,14 @@ def push_rebased_and_rewritten_version(
trailer_name='Tested-by',
trailer_values=tested_by,
branch=source_branch,
- start_commit=source_branch+'^'
+ start_commit=source_branch + '^'
+ )
+ if part_of is not None:
+ rewritten_sha = repo.tag_with_trailer(
+ trailer_name='Part-of',
+ trailer_values=[part_of],
+ branch=source_branch,
+ start_commit='origin/' + target_branch,
)
branch_rewritten = True
repo.push_force(source_branch, source_repo_url)
@@ -336,7 +352,12 @@ def _get_reviewer_names_and_emails(approvals, api):
_job_options = [
- 'add_tested', 'add_reviewers', 'reapprove', 'embargo', 'max_ci_waiting_time',
+ 'add_tested',
+ 'add_part_of',
+ 'add_reviewers',
+ 'reapprove',
+ 'embargo',
+ 'max_ci_waiting_time',
]
class MergeJobOptions(namedtuple('MergeJobOptions', _job_options)):
@@ -344,18 +365,19 @@ class MergeJobOptions(namedtuple('MergeJobOptions', _job_options)):
@property
def requests_commit_tagging(self):
- return self.add_tested or self.add_reviewers
+ return self.add_tested or self.add_part_of or self.add_reviewers
@classmethod
def default(
- cls,
- add_tested=False, add_reviewers=False, reapprove=False,
+ cls, *,
+ add_tested=False, add_part_of=False, add_reviewers=False, reapprove=False,
embargo=None, max_ci_waiting_time=None,
):
embargo = embargo or IntervalUnion.empty()
max_ci_waiting_time = max_ci_waiting_time or timedelta(minutes=15)
return cls(
add_tested=add_tested,
+ add_part_of=add_part_of,
add_reviewers=add_reviewers,
reapprove=reapprove,
embargo=embargo,
diff --git a/pinnedNixpkgs.nix b/pinnedNixpkgs.nix
index e8fe663..5ce5fce 100644
--- a/pinnedNixpkgs.nix
+++ b/pinnedNixpkgs.nix
@@ -1,1 +1,9 @@
-import (fetchTarball "https://github.com/NixOS/nixpkgs/archive/90afb0c10fe6f437fca498298747b2bcb6a77d39.tar.gz") { }
+let
+ fetchFromGitHub = (import <nixpkgs> {}).fetchFromGitHub;
+ pkgs = import (fetchFromGitHub {
+ owner = "NixOS";
+ repo = "nixpkgs";
+ rev = "90afb0c10fe6f437fca498298747b2bcb6a77d39";
+ sha256 = "0mvzdw5aygi1vjnvm0bc8bp7iwb9rypiqg749m6a6km84m7srm0w";
+ }) {};
+in pkgs
diff --git a/version b/version
index 0d91a54..d15723f 100644
--- a/version
+++ b/version
@@ -1,1 +1,1 @@
-0.3.0
+0.3.2
| Add reference to original merge request in commit message
Marge could put a link to original merge request in the commit message, presumably for every commit in a MR. | smarkets/marge-bot | diff --git a/tests/test_commit.py b/tests/test_commit.py
index 60de697..789d0f9 100644
--- a/tests/test_commit.py
+++ b/tests/test_commit.py
@@ -48,6 +48,11 @@ class TestProject(object):
Commit.last_on_branch(project_id=1234, branch='foobar-branch', api=self.api)
self.api.call.assert_called_once_with(GET('/projects/1234/repository/branches/foobar-branch'))
+ def test_last_on_branch_encoding(self):
+ self.api.call.side_effect = lambda *_, **__: {'commit': INFO}
+ Commit.last_on_branch(project_id=1234, branch='foo/bar', api=self.api)
+ self.api.call.assert_called_once_with(GET('/projects/1234/repository/branches/foo%2Fbar'))
+
def test_properties(self):
commit = Commit(api=self.api, info=INFO)
assert commit.id == "6104942438c14ec7bd21c6cd5bd995272b3faff6"
diff --git a/tests/test_job.py b/tests/test_job.py
index 984c9c4..fa16c39 100644
--- a/tests/test_job.py
+++ b/tests/test_job.py
@@ -121,7 +121,7 @@ class MockLab(object):
)
api.expected_note(
self.merge_request_info,
- "My job would be easier if people didn't jump the queue and pushed directly... *sigh*",
+ "My job would be easier if people didn't jump the queue and push directly... *sigh*",
from_state=['pushed_but_master_moved', 'merge_rejected'],
)
api.expected_note(
@@ -244,7 +244,7 @@ class TestRebaseAndAccept(object):
job.execute()
assert api.state == 'merged'
- assert api.notes == ["My job would be easier if people didn't jump the queue and pushed directly... *sigh*"]
+ assert api.notes == ["My job would be easier if people didn't jump the queue and push directly... *sigh*"]
def test_handles_races_for_merging(self, time_sleep):
api, mocklab = self.api, self.mocklab
@@ -397,6 +397,7 @@ class TestMergeJobOptions(object):
def test_default(self):
assert MergeJobOptions.default() == MergeJobOptions(
add_tested=False,
+ add_part_of=False,
add_reviewers=False,
reapprove=False,
embargo=marge.interval.IntervalUnion.empty(),
| {
"commit_name": "merge_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": 2
},
"num_modified_files": 9
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | astroid==2.11.7
attrs==22.2.0
backports.zoneinfo==0.2.1
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
dateparser==1.1.3
dill==0.3.4
humanize==3.14.0
idna==3.10
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
isort==5.10.1
lazy-object-proxy==1.7.1
-e git+https://github.com/smarkets/marge-bot.git@2ce32f55eede12f76b7a760fbdf3ee2cd15a7bb6#egg=marge
maya==0.6.1
mccabe==0.7.0
packaging==21.3
pendulum==2.1.2
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
pylint==2.13.9
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
python-dateutil==2.9.0.post0
pytz==2025.2
pytz-deprecation-shim==0.1.0.post0
pytzdata==2020.1
regex==2022.3.2
requests==2.27.1
six==1.17.0
snaptime==0.2.4
tomli==1.2.3
typed-ast==1.5.5
typing_extensions==4.1.1
tzdata==2025.2
tzlocal==4.2
urllib3==1.26.20
wrapt==1.16.0
zipp==3.6.0
| name: marge-bot
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- astroid==2.11.7
- attrs==22.2.0
- backports-zoneinfo==0.2.1
- charset-normalizer==2.0.12
- coverage==6.2
- dateparser==1.1.3
- dill==0.3.4
- humanize==3.14.0
- idna==3.10
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- isort==5.10.1
- lazy-object-proxy==1.7.1
- maya==0.6.1
- mccabe==0.7.0
- packaging==21.3
- pendulum==2.1.2
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pylint==2.13.9
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pytz-deprecation-shim==0.1.0.post0
- pytzdata==2020.1
- regex==2022.3.2
- requests==2.27.1
- six==1.17.0
- snaptime==0.2.4
- tomli==1.2.3
- typed-ast==1.5.5
- typing-extensions==4.1.1
- tzdata==2025.2
- tzlocal==4.2
- urllib3==1.26.20
- wrapt==1.16.0
- zipp==3.6.0
prefix: /opt/conda/envs/marge-bot
| [
"tests/test_commit.py::TestProject::test_last_on_branch_encoding",
"tests/test_job.py::TestRebaseAndAccept::test_succeeds_second_time_if_master_moved",
"tests/test_job.py::TestMergeJobOptions::test_default"
]
| []
| [
"tests/test_commit.py::TestProject::test_fetch_by_id",
"tests/test_commit.py::TestProject::test_last_on_branch",
"tests/test_commit.py::TestProject::test_properties",
"tests/test_job.py::TestRebaseAndAccept::test_succeeds_first_time",
"tests/test_job.py::TestRebaseAndAccept::test_fails_on_not_acceptable_if_master_did_not_move",
"tests/test_job.py::TestRebaseAndAccept::test_handles_races_for_merging",
"tests/test_job.py::TestRebaseAndAccept::test_handles_request_becoming_wip_after_push",
"tests/test_job.py::TestRebaseAndAccept::test_guesses_git_hook_error_on_merge_refusal",
"tests/test_job.py::TestRebaseAndAccept::test_tells_explicitly_that_gitlab_refused_to_merge",
"tests/test_job.py::TestRebaseAndAccept::test_wont_merge_wip_stuff",
"tests/test_job.py::TestRebaseAndAccept::test_wont_merge_branches_with_autosquash_if_rewriting",
"tests/test_job.py::TestMergeJobOptions::test_default_ci_time"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,632 | [
"version",
"deploy.yml",
"pinnedNixpkgs.nix",
"marge/commit.py",
"CHANGELOG.md",
"marge/job.py",
"marge/bot.py",
"README.md",
"marge/app.py"
]
| [
"version",
"deploy.yml",
"pinnedNixpkgs.nix",
"marge/commit.py",
"CHANGELOG.md",
"marge/job.py",
"marge/bot.py",
"README.md",
"marge/app.py"
]
|
|
ASPP__pelita-412 | 002ae9e325b1608a324d02749205cd70b4f6da2b | 2017-08-29 08:38:58 | e3fc4b8a42f874925aa619a06d2a16d5b189ba24 | diff --git a/pelita/player/__init__.py b/pelita/player/__init__.py
index cf429bca..bedaae24 100644
--- a/pelita/player/__init__.py
+++ b/pelita/player/__init__.py
@@ -1,7 +1,7 @@
from .base import AbstractTeam, SimpleTeam, AbstractPlayer
-from .base import (StoppingPlayer, TestPlayer, SpeakingPlayer,
+from .base import (StoppingPlayer, SteppingPlayer, SpeakingPlayer,
RoundBasedPlayer, MoveExceptionPlayer, InitialExceptionPlayer,
DebuggablePlayer)
diff --git a/pelita/player/base.py b/pelita/player/base.py
index f07bba65..0e578f2f 100644
--- a/pelita/player/base.py
+++ b/pelita/player/base.py
@@ -516,7 +516,7 @@ class SpeakingPlayer(AbstractPlayer):
self.say("Going %r." % (move,))
return move
-class TestPlayer(AbstractPlayer):
+class SteppingPlayer(AbstractPlayer):
""" A Player with predetermined set of moves.
Parameters
| pytest warns about our TestPlayer
WC1 /tmp/group1/test/test_drunk_player.py cannot collect test class 'TestPlayer' because it has a __init__ constructor
Maybe rename it? | ASPP/pelita | diff --git a/test/test_game_master.py b/test/test_game_master.py
index 2b164441..e943d70b 100644
--- a/test/test_game_master.py
+++ b/test/test_game_master.py
@@ -5,7 +5,7 @@ import collections
from pelita.datamodel import CTFUniverse
from pelita.game_master import GameMaster, ManhattanNoiser, PlayerTimeout
-from pelita.player import AbstractPlayer, SimpleTeam, StoppingPlayer, TestPlayer
+from pelita.player import AbstractPlayer, SimpleTeam, StoppingPlayer, SteppingPlayer
from pelita.viewer import AbstractViewer
@@ -18,8 +18,8 @@ class TestGameMaster:
# . # . .#3#
################## """)
- team_1 = SimpleTeam("team1", TestPlayer([]), TestPlayer([]))
- team_2 = SimpleTeam("team2", TestPlayer([]), TestPlayer([]))
+ team_1 = SimpleTeam("team1", SteppingPlayer([]), SteppingPlayer([]))
+ team_2 = SimpleTeam("team2", SteppingPlayer([]), SteppingPlayer([]))
game_master = GameMaster(test_layout, [team_1, team_2], 4, 200)
assert game_master.game_state["team_name"][0] == ""
@@ -48,8 +48,8 @@ class TestGameMaster:
# . # . .#3#
################## """)
- team_1 = SimpleTeam('team1', TestPlayer([]), TestPlayer([]))
- team_2 = SimpleTeam('team2', TestPlayer([]), TestPlayer([]))
+ team_1 = SimpleTeam('team1', SteppingPlayer([]), SteppingPlayer([]))
+ team_2 = SimpleTeam('team2', SteppingPlayer([]), SteppingPlayer([]))
game_master = GameMaster(test_layout, [team_1, team_2], 4, 200)
game_master.set_initial()
@@ -64,7 +64,7 @@ class TestGameMaster:
#2##### #####1#
# . # . .#3#
################## """)
- team_1 = SimpleTeam(TestPlayer([]), TestPlayer([]))
+ team_1 = SimpleTeam(SteppingPlayer([]), SteppingPlayer([]))
with pytest.raises(ValueError):
GameMaster(test_layout_4, [team_1], 4, 200)
@@ -76,9 +76,9 @@ class TestGameMaster:
# . # . .#3#
################## """)
- team_1 = SimpleTeam(TestPlayer([]), TestPlayer([]))
- team_2 = SimpleTeam(TestPlayer([]), TestPlayer([]))
- team_3 = SimpleTeam(TestPlayer([]), TestPlayer([]))
+ team_1 = SimpleTeam(SteppingPlayer([]), SteppingPlayer([]))
+ team_2 = SimpleTeam(SteppingPlayer([]), SteppingPlayer([]))
+ team_3 = SimpleTeam(SteppingPlayer([]), SteppingPlayer([]))
with pytest.raises(ValueError):
GameMaster(test_layout_4, [team_1, team_2, team_3], 4, 200)
@@ -259,7 +259,7 @@ class TestGame:
return universe
- teams = [SimpleTeam(TestPlayer('>-v>>>')), SimpleTeam(TestPlayer('<<-<<<'))]
+ teams = [SimpleTeam(SteppingPlayer('>-v>>>')), SimpleTeam(SteppingPlayer('<<-<<<'))]
gm = GameMaster(test_start, teams, number_bots, 200)
gm.set_initial()
@@ -317,7 +317,7 @@ class TestGame:
assert create_TestUniverse(test_sixth_round,
black_score=gm.universe.KILLPOINTS, white_score=gm.universe.KILLPOINTS) == gm.universe
- teams = [SimpleTeam(TestPlayer('>-v>>>')), SimpleTeam(TestPlayer('<<-<<<'))]
+ teams = [SimpleTeam(SteppingPlayer('>-v>>>')), SimpleTeam(SteppingPlayer('<<-<<<'))]
# now play the full game
gm = GameMaster(test_start, teams, number_bots, 200)
gm.play()
@@ -380,7 +380,7 @@ class TestGame:
#0 . #
#.. 1#
###### """)
- teams = [SimpleTeam(FailingPlayer()), SimpleTeam(TestPlayer("^"))]
+ teams = [SimpleTeam(FailingPlayer()), SimpleTeam(SteppingPlayer("^"))]
gm = GameMaster(test_layout, teams, 2, 1)
@@ -409,8 +409,8 @@ class TestGame:
number_bots = 2
teams = [
- SimpleTeam(TestPlayer([(0,0)])),
- SimpleTeam(TestPlayer([(0,0)]))
+ SimpleTeam(SteppingPlayer([(0,0)])),
+ SimpleTeam(SteppingPlayer([(0,0)]))
]
gm = GameMaster(test_start, teams, number_bots, 200)
@@ -439,7 +439,7 @@ class TestGame:
NUM_ROUNDS = 2
# bot 1 moves east twice to eat the single food
teams = [
- SimpleTeam(TestPlayer('>>')),
+ SimpleTeam(SteppingPlayer('>>')),
SimpleTeam(StoppingPlayer())
]
gm = GameMaster(test_start, teams, 2, game_time=NUM_ROUNDS)
@@ -473,7 +473,7 @@ class TestGame:
teams = [
SimpleTeam(StoppingPlayer()),
- SimpleTeam(TestPlayer('<<')) # bot 1 moves west twice to eat the single food
+ SimpleTeam(SteppingPlayer('<<')) # bot 1 moves west twice to eat the single food
]
gm = GameMaster(test_start, teams, 2, game_time=NUM_ROUNDS)
@@ -533,7 +533,7 @@ class TestGame:
)
teams = [
SimpleTeam(StoppingPlayer()),
- SimpleTeam(TestPlayer('<<<'))
+ SimpleTeam(SteppingPlayer('<<<'))
]
# bot 1 eats all the food and the game stops
gm = GameMaster(test_start, teams, 2, 100)
@@ -566,7 +566,7 @@ class TestGame:
)
teams = [
SimpleTeam(StoppingPlayer()),
- SimpleTeam(TestPlayer('<<<'))
+ SimpleTeam(SteppingPlayer('<<<'))
]
# bot 1 eats all the food and the game stops
gm = GameMaster(test_start, teams, 2, 100)
@@ -710,8 +710,8 @@ class TestGame:
teams = [
- SimpleTeam(TestPlayer('>>>>')),
- SimpleTeam(TestPlayer('<<<<'))
+ SimpleTeam(SteppingPlayer('>>>>')),
+ SimpleTeam(SteppingPlayer('<<<<'))
]
gm = GameMaster(test_start, teams, number_bots, 4)
@@ -806,8 +806,8 @@ class TestGame:
# the game lasts two rounds, enough time for bot 1 to eat food
NUM_ROUNDS = 5
teams = [
- SimpleTeam(TestPlayer('>--->')),
- SimpleTeam(TestPlayer('<<<<<')) # bot 1 moves west twice to eat the single food
+ SimpleTeam(SteppingPlayer('>--->')),
+ SimpleTeam(SteppingPlayer('<<<<<')) # bot 1 moves west twice to eat the single food
]
gm = GameMaster(test_start, teams, 2, game_time=NUM_ROUNDS)
diff --git a/test/test_player_base.py b/test/test_player_base.py
index 96998f8d..75fdadae 100644
--- a/test/test_player_base.py
+++ b/test/test_player_base.py
@@ -8,7 +8,7 @@ from pelita import datamodel
from pelita.datamodel import CTFUniverse, east, stop, west
from pelita.game_master import GameMaster
from pelita.player import (AbstractPlayer, SimpleTeam,
- RandomPlayer, StoppingPlayer, TestPlayer,
+ RandomPlayer, StoppingPlayer, SteppingPlayer,
RoundBasedPlayer, SpeakingPlayer)
@@ -29,7 +29,7 @@ class TestAbstractPlayer:
################## """)
player_0 = StoppingPlayer()
- player_1 = TestPlayer('^<')
+ player_1 = SteppingPlayer('^<')
player_2 = StoppingPlayer()
player_3 = StoppingPlayer()
teams = [
@@ -277,8 +277,8 @@ class TestAbstractPlayer:
assert set(sim_uni.enemy_food(p1._index)) == {(4, 3), (4, 2)}
-class TestTestPlayer:
- def test_test_players(self):
+class TestSteppingPlayer:
+ def test_stepping_players(self):
test_layout = (
""" ############
#0 . . 1#
@@ -287,8 +287,8 @@ class TestTestPlayer:
movements_0 = [east, east]
movements_1 = [west, west]
teams = [
- SimpleTeam(TestPlayer(movements_0), TestPlayer(movements_0)),
- SimpleTeam(TestPlayer(movements_1), TestPlayer(movements_1))
+ SimpleTeam(SteppingPlayer(movements_0), SteppingPlayer(movements_0)),
+ SimpleTeam(SteppingPlayer(movements_1), SteppingPlayer(movements_1))
]
gm = GameMaster(test_layout, teams, 4, 2)
@@ -311,8 +311,8 @@ class TestTestPlayer:
############ """)
num_rounds = 5
teams = [
- SimpleTeam(TestPlayer('>v<^-)')),
- SimpleTeam(TestPlayer('<^>v-)'))
+ SimpleTeam(SteppingPlayer('>v<^-)')),
+ SimpleTeam(SteppingPlayer('<^>v-)'))
]
gm = GameMaster(test_layout, teams, 2, num_rounds)
player0_expected_positions = [(1,1), (2,1), (2,2), (1,2), (1,1)]
@@ -334,8 +334,8 @@ class TestTestPlayer:
movements_0 = [east, east]
movements_1 = [west, west]
teams = [
- SimpleTeam(TestPlayer(movements_0), TestPlayer(movements_0)),
- SimpleTeam(TestPlayer(movements_1), TestPlayer(movements_1))
+ SimpleTeam(SteppingPlayer(movements_0), SteppingPlayer(movements_0)),
+ SimpleTeam(SteppingPlayer(movements_1), SteppingPlayer(movements_1))
]
gm = GameMaster(test_layout, teams, 4, 3)
@@ -512,19 +512,19 @@ class TestSimpleTeam:
assert team0.team_name == "my team"
assert len(team0._players) == 0
- team1 = SimpleTeam("my team", TestPlayer([]))
+ team1 = SimpleTeam("my team", SteppingPlayer([]))
assert team1.team_name == "my team"
assert len(team1._players) == 1
- team2 = SimpleTeam("my other team", TestPlayer([]), TestPlayer([]))
+ team2 = SimpleTeam("my other team", SteppingPlayer([]), SteppingPlayer([]))
assert team2.team_name == "my other team"
assert len(team2._players) == 2
- team3 = SimpleTeam(TestPlayer([]))
+ team3 = SimpleTeam(SteppingPlayer([]))
assert team3.team_name == ""
assert len(team3._players) == 1
- team4 = SimpleTeam(TestPlayer([]), TestPlayer([]))
+ team4 = SimpleTeam(SteppingPlayer([]), SteppingPlayer([]))
assert team4.team_name == ""
assert len(team4._players) == 2
@@ -535,7 +535,7 @@ class TestSimpleTeam:
###### """
)
dummy_universe = CTFUniverse.create(layout, 4)
- team1 = SimpleTeam(TestPlayer('^'))
+ team1 = SimpleTeam(SteppingPlayer('^'))
with pytest.raises(ValueError):
team1.set_initial(0, dummy_universe, {})
diff --git a/test/test_simplesetup.py b/test/test_simplesetup.py
index 1a1cb830..fafe8c43 100644
--- a/test/test_simplesetup.py
+++ b/test/test_simplesetup.py
@@ -5,7 +5,7 @@ import uuid
import zmq
import pelita
-from pelita.player import AbstractPlayer, SimpleTeam, TestPlayer
+from pelita.player import AbstractPlayer, SimpleTeam, SteppingPlayer
from pelita.simplesetup import SimpleClient, SimpleServer, bind_socket, extract_port_range
from pelita.player import RandomPlayer
@@ -61,8 +61,8 @@ class TestSimpleSetup:
client1_address = server.bind_addresses[0].replace("*", "localhost")
client2_address = server.bind_addresses[1].replace("*", "localhost")
- client1 = SimpleClient(SimpleTeam("team1", TestPlayer("^>>v<")), address=client1_address)
- client2 = SimpleClient(SimpleTeam("team2", TestPlayer("^<<v>")), address=client2_address)
+ client1 = SimpleClient(SimpleTeam("team1", SteppingPlayer("^>>v<")), address=client1_address)
+ client2 = SimpleClient(SimpleTeam("team2", SteppingPlayer("^<<v>")), address=client2_address)
client1.autoplay_process()
client2.autoplay_process()
@@ -92,7 +92,7 @@ class TestSimpleSetup:
def _get_move(self, universe, game_state):
pass
- client1 = SimpleClient(SimpleTeam("team1", TestPlayer("^>>v<")), address=client1_address)
+ client1 = SimpleClient(SimpleTeam("team1", SteppingPlayer("^>>v<")), address=client1_address)
client2 = SimpleClient(SimpleTeam("team2", FailingPlayer()), address=client2_address)
client1.autoplay_process()
| {
"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": 0,
"issue_text_score": 2,
"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",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements/base.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
importlib-metadata==4.8.3
iniconfig==1.1.1
numpy==1.19.5
packaging==21.3
-e git+https://github.com/ASPP/pelita.git@002ae9e325b1608a324d02749205cd70b4f6da2b#egg=pelita
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
PyYAML==6.0.1
pyzmq==25.1.2
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: pelita
channels:
- defaults
- https://repo.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
- numpy==1.19.5
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pyyaml==6.0.1
- pyzmq==25.1.2
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/pelita
| [
"test/test_game_master.py::TestGameMaster::test_team_names",
"test/test_game_master.py::TestGameMaster::test_team_names_in_simpleteam",
"test/test_game_master.py::TestGameMaster::test_too_few_registered_teams",
"test/test_game_master.py::TestGameMaster::test_too_many_registered_teams",
"test/test_game_master.py::TestUniverseNoiser::test_uniform_noise_manhattan",
"test/test_game_master.py::TestUniverseNoiser::test_uniform_noise_4_bots_manhattan",
"test/test_game_master.py::TestUniverseNoiser::test_uniform_noise_4_bots_no_noise_manhattan",
"test/test_game_master.py::TestUniverseNoiser::test_noise_manhattan_failure",
"test/test_game_master.py::TestAbstracts::test_AbstractViewer",
"test/test_game_master.py::TestAbstracts::test_BrokenViewer",
"test/test_game_master.py::TestGame::test_game",
"test/test_game_master.py::TestGame::test_malicous_player",
"test/test_game_master.py::TestGame::test_failing_player",
"test/test_game_master.py::TestGame::test_viewer_may_change_gm",
"test/test_game_master.py::TestGame::test_win_on_timeout_team_0",
"test/test_game_master.py::TestGame::test_win_on_timeout_team_1",
"test/test_game_master.py::TestGame::test_draw_on_timeout",
"test/test_game_master.py::TestGame::test_win_on_eating_all",
"test/test_game_master.py::TestGame::test_lose_on_eating_all",
"test/test_game_master.py::TestGame::test_lose_5_timeouts",
"test/test_game_master.py::TestGame::test_must_not_move_after_last_timeout",
"test/test_game_master.py::TestGame::test_play_step",
"test/test_game_master.py::TestGame::test_kill_count",
"test/test_player_base.py::TestAbstractPlayer::test_convenience",
"test/test_player_base.py::TestAbstractPlayer::test_time_spent",
"test/test_player_base.py::TestAbstractPlayer::test_rnd",
"test/test_player_base.py::TestAbstractPlayer::test_simulate_move",
"test/test_player_base.py::TestSteppingPlayer::test_stepping_players",
"test/test_player_base.py::TestSteppingPlayer::test_shorthand",
"test/test_player_base.py::TestSteppingPlayer::test_too_many_moves",
"test/test_player_base.py::TestRoundBasedPlayer::test_round_based_players",
"test/test_player_base.py::TestRandomPlayerSeeds::test_demo_players",
"test/test_player_base.py::TestRandomPlayerSeeds::test_random_seeds",
"test/test_player_base.py::TestSpeakingPlayer::test_demo_players",
"test/test_player_base.py::TestSimpleTeam::test_player_api_methods",
"test/test_player_base.py::TestSimpleTeam::test_init",
"test/test_player_base.py::TestSimpleTeam::test_too_few_players",
"test/test_player_base.py::TestAbstracts::test_AbstractPlayer",
"test/test_player_base.py::TestAbstracts::test_BrokenPlayer",
"test/test_simplesetup.py::TestSimpleSetup::test_bind_socket",
"test/test_simplesetup.py::TestSimpleSetup::test_simple_game",
"test/test_simplesetup.py::TestSimpleSetup::test_simple_remote_game",
"test/test_simplesetup.py::TestSimpleSetup::test_simple_failing_bots",
"test/test_simplesetup.py::TestSimpleSetup::test_failing_bots_do_not_crash_server_in_set_initial",
"test/test_simplesetup.py::TestSimpleSetup::test_failing_bots_do_not_crash_server",
"test/test_simplesetup.py::TestSimpleSetup::test_extract_port_range"
]
| []
| []
| []
| BSD License | 1,633 | [
"pelita/player/__init__.py",
"pelita/player/base.py"
]
| [
"pelita/player/__init__.py",
"pelita/player/base.py"
]
|
|
globocom__m3u8-105 | e58a2411b7df376adb922cf56bc411d55e371e77 | 2017-08-29 12:05:15 | 5cbf61314f8cb1a2fcee860a49f770eca16b29f9 | diff --git a/m3u8/model.py b/m3u8/model.py
index 0b13349..5ca29d5 100644
--- a/m3u8/model.py
+++ b/m3u8/model.py
@@ -176,7 +176,7 @@ class M3U8(object):
uri=ifr_pl['uri'],
iframe_stream_info=ifr_pl['iframe_stream_info'])
)
- self.segment_map_uri = self.data.get('segment_map_uri')
+ self.segment_map = self.data.get('segment_map')
def __unicode__(self):
return self.dumps()
diff --git a/m3u8/parser.py b/m3u8/parser.py
index 5aa117e..f28fd07 100644
--- a/m3u8/parser.py
+++ b/m3u8/parser.py
@@ -137,7 +137,9 @@ def parse(content, strict=False):
data['is_endlist'] = True
elif line.startswith(protocol.ext_x_map):
- data['segment_map_uri'] = _parse_segment_map_uri(line)
+ quoted_parser = remove_quotes_parser('uri')
+ segment_map_info = _parse_attribute_list(protocol.ext_x_map, line, quoted_parser)
+ data['segment_map'] = segment_map_info
# Comments and whitespace
elif line.startswith('#'):
@@ -310,14 +312,6 @@ def _parse_cueout_start(line, state, prevline):
state['current_cue_out_duration'] = _cueout_state[1]
-def _parse_segment_map_uri(line):
- """
- :param line: '#EXT-X-MAP:URI="fileSequence0.mp4"'
- :rtype: str
- """
- return remove_quotes(line.replace(protocol.ext_x_map+':', '').split('=', 1)[1])
-
-
def string_to_lines(string):
return string.strip().replace('\r\n', '\n').split('\n')
| Error parsing line #EXT-X-MAP:URI="main.mp4",BYTERANGE="812@0"
Apple 'Advanced stream (HEVC/H.264)' reference has #EXT-X-MAP:URI="main.mp4",BYTERANGE="812@0" attribute. This attribute parses as segment_map_uri with incorrect value 'main.mp4",BYTERANGE="812@0'. But should be parsed as separate 'uri' and 'byterange'.
Link to m3u8:
https://tungsten.aaplimg.com/VOD/bipbop_adv_example_hevc/tp10/iframe_index.m3u8
Link to examples:
https://developer.apple.com/streaming/examples/ | globocom/m3u8 | diff --git a/tests/playlists.py b/tests/playlists.py
index 8bb85be..8f06a0b 100755
--- a/tests/playlists.py
+++ b/tests/playlists.py
@@ -607,6 +607,15 @@ MAP_URI_PLAYLIST = '''#EXTM3U
#EXT-X-MAP:URI="fileSequence0.mp4"
'''
+MAP_URI_PLAYLIST_WITH_BYTERANGE = '''#EXTM3U
+#EXT-X-TARGETDURATION:2
+#EXT-X-VERSION:7
+#EXT-X-MEDIA-SEQUENCE:1
+#EXT-X-PLAYLIST-TYPE:VOD
+#EXT-X-INDEPENDENT-SEGMENTS
+#EXT-X-MAP:URI="main.mp4",BYTERANGE="812@0"
+'''
+
RELATIVE_PLAYLIST_FILENAME = abspath(join(dirname(__file__), 'playlists/relative-playlist.m3u8'))
RELATIVE_PLAYLIST_URI = TEST_HOST + '/path/to/relative-playlist.m3u8'
diff --git a/tests/test_model.py b/tests/test_model.py
index f4e985a..502144c 100755
--- a/tests/test_model.py
+++ b/tests/test_model.py
@@ -692,11 +692,16 @@ def test_m3u8_should_propagate_base_uri_to_key():
def test_segment_map_uri_attribute():
obj = m3u8.M3U8(playlists.MAP_URI_PLAYLIST)
- assert obj.segment_map_uri == "fileSequence0.mp4"
+ assert obj.segment_map['uri'] == "fileSequence0.mp4"
+def test_segment_map_uri_attribute_with_byterange():
+ obj = m3u8.M3U8(playlists.MAP_URI_PLAYLIST_WITH_BYTERANGE)
+ assert obj.segment_map['uri'] == "main.mp4"
+
# custom asserts
+
def assert_file_content(filename, expected):
with open(filename) as fileobj:
content = fileobj.read().strip()
diff --git a/tests/test_parser.py b/tests/test_parser.py
index 7a77ecb..47676f9 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -255,4 +255,9 @@ def test_commaless_extinf_strict():
def test_should_parse_segment_map_uri():
data = m3u8.parse(playlists.MAP_URI_PLAYLIST)
- assert data['segment_map_uri'] == "fileSequence0.mp4"
+ assert data['segment_map']['uri'] == "fileSequence0.mp4"
+
+
+def test_should_parse_segment_map_uri_with_byterange():
+ data = m3u8.parse(playlists.MAP_URI_PLAYLIST_WITH_BYTERANGE)
+ assert data['segment_map']['uri'] == "main.mp4"
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_media",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 2
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"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"
} | arrow==1.3.0
bottle==0.13.2
certifi==2025.1.31
charset-normalizer==3.4.1
coverage==7.8.0
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
iso8601==2.1.0
-e git+https://github.com/globocom/m3u8.git@e58a2411b7df376adb922cf56bc411d55e371e77#egg=m3u8
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cov==6.0.0
python-coveralls==2.9.3
python-dateutil==2.9.0.post0
PyYAML==6.0.2
requests==2.32.3
six==1.17.0
tomli==2.2.1
types-python-dateutil==2.9.0.20241206
urllib3==2.3.0
| name: m3u8
channels:
- defaults
- https://repo.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:
- arrow==1.3.0
- bottle==0.13.2
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==7.8.0
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- iso8601==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cov==6.0.0
- python-coveralls==2.9.3
- python-dateutil==2.9.0.post0
- pyyaml==6.0.2
- requests==2.32.3
- six==1.17.0
- tomli==2.2.1
- types-python-dateutil==2.9.0.20241206
- urllib3==2.3.0
prefix: /opt/conda/envs/m3u8
| [
"tests/test_model.py::test_segment_map_uri_attribute",
"tests/test_model.py::test_segment_map_uri_attribute_with_byterange",
"tests/test_parser.py::test_should_parse_segment_map_uri",
"tests/test_parser.py::test_should_parse_segment_map_uri_with_byterange"
]
| []
| [
"tests/test_model.py::test_target_duration_attribute",
"tests/test_model.py::test_media_sequence_attribute",
"tests/test_model.py::test_program_date_time_attribute",
"tests/test_model.py::test_program_date_time_attribute_for_each_segment",
"tests/test_model.py::test_program_date_time_attribute_with_discontinuity",
"tests/test_model.py::test_segment_discontinuity_attribute",
"tests/test_model.py::test_segment_cue_out_attribute",
"tests/test_model.py::test_segment_elemental_scte35_attribute",
"tests/test_model.py::test_segment_envivio_scte35_attribute",
"tests/test_model.py::test_keys_on_clear_playlist",
"tests/test_model.py::test_keys_on_simple_encrypted_playlist",
"tests/test_model.py::test_key_attribute",
"tests/test_model.py::test_key_attribute_on_none",
"tests/test_model.py::test_key_attribute_without_initialization_vector",
"tests/test_model.py::test_segments_attribute",
"tests/test_model.py::test_segments_attribute_without_title",
"tests/test_model.py::test_segments_attribute_without_duration",
"tests/test_model.py::test_segments_attribute_with_byterange",
"tests/test_model.py::test_segment_attribute_with_multiple_keys",
"tests/test_model.py::test_is_variant_attribute",
"tests/test_model.py::test_is_endlist_attribute",
"tests/test_model.py::test_is_i_frames_only_attribute",
"tests/test_model.py::test_playlists_attribute",
"tests/test_model.py::test_playlists_attribute_without_program_id",
"tests/test_model.py::test_playlists_attribute_with_resolution",
"tests/test_model.py::test_iframe_playlists_attribute",
"tests/test_model.py::test_version_attribute",
"tests/test_model.py::test_allow_cache_attribute",
"tests/test_model.py::test_files_attribute_should_list_all_files_including_segments_and_key",
"tests/test_model.py::test_vod_playlist_type_should_be_imported_as_a_simple_attribute",
"tests/test_model.py::test_event_playlist_type_should_be_imported_as_a_simple_attribute",
"tests/test_model.py::test_independent_segments_should_be_true",
"tests/test_model.py::test_independent_segments_should_be_false",
"tests/test_model.py::test_no_playlist_type_leaves_attribute_empty",
"tests/test_model.py::test_dump_playlists_with_resolution",
"tests/test_model.py::test_dump_should_build_file_with_same_content",
"tests/test_model.py::test_dump_should_create_sub_directories",
"tests/test_model.py::test_dump_should_work_for_variant_streams",
"tests/test_model.py::test_dump_should_work_for_variant_playlists_with_iframe_playlists",
"tests/test_model.py::test_dump_should_work_for_iframe_playlists",
"tests/test_model.py::test_dump_should_include_program_date_time",
"tests/test_model.py::test_dump_should_work_for_playlists_using_byteranges",
"tests/test_model.py::test_should_dump_with_endlist_tag",
"tests/test_model.py::test_should_dump_without_endlist_tag",
"tests/test_model.py::test_should_dump_multiple_keys",
"tests/test_model.py::test_should_dump_unencrypted_encrypted_keys_together",
"tests/test_model.py::test_should_dump_complex_unencrypted_encrypted_keys",
"tests/test_model.py::test_should_dump_complex_unencrypted_encrypted_keys_no_uri_attr",
"tests/test_model.py::test_length_segments_by_key",
"tests/test_model.py::test_list_segments_by_key",
"tests/test_model.py::test_replace_segment_key",
"tests/test_model.py::test_should_dump_program_datetime_and_discontinuity",
"tests/test_model.py::test_should_normalize_segments_and_key_urls_if_base_path_passed_to_constructor",
"tests/test_model.py::test_should_normalize_variant_streams_urls_if_base_path_passed_to_constructor",
"tests/test_model.py::test_should_normalize_segments_and_key_urls_if_base_path_attribute_updated",
"tests/test_model.py::test_playlist_type_dumped_to_appropriate_m3u8_field",
"tests/test_model.py::test_empty_playlist_type_is_gracefully_ignored",
"tests/test_model.py::test_none_playlist_type_is_gracefully_ignored",
"tests/test_model.py::test_0_media_sequence_added_to_file",
"tests/test_model.py::test_none_media_sequence_gracefully_ignored",
"tests/test_model.py::test_should_correctly_update_base_path_if_its_blank",
"tests/test_model.py::test_m3u8_should_propagate_base_uri_to_segments",
"tests/test_model.py::test_m3u8_should_propagate_base_uri_to_key",
"tests/test_parser.py::test_should_parse_simple_playlist_from_string",
"tests/test_parser.py::test_should_parse_non_integer_duration_from_playlist_string",
"tests/test_parser.py::test_should_parse_simple_playlist_from_string_with_different_linebreaks",
"tests/test_parser.py::test_should_parse_sliding_window_playlist_from_string",
"tests/test_parser.py::test_should_parse_playlist_with_encripted_segments_from_string",
"tests/test_parser.py::test_should_load_playlist_with_iv_from_string",
"tests/test_parser.py::test_should_add_key_attribute_to_segment_from_playlist",
"tests/test_parser.py::test_should_add_non_key_for_multiple_keys_unencrypted_and_encrypted",
"tests/test_parser.py::test_should_handle_key_method_none_and_no_uri_attr",
"tests/test_parser.py::test_should_parse_title_from_playlist",
"tests/test_parser.py::test_should_parse_variant_playlist",
"tests/test_parser.py::test_should_parse_variant_playlist_with_average_bandwidth",
"tests/test_parser.py::test_should_parse_variant_playlist_with_bandwidth_as_float",
"tests/test_parser.py::test_should_parse_variant_playlist_with_iframe_playlists",
"tests/test_parser.py::test_should_parse_variant_playlist_with_alt_iframe_playlists_layout",
"tests/test_parser.py::test_should_parse_iframe_playlist",
"tests/test_parser.py::test_should_parse_playlist_using_byteranges",
"tests/test_parser.py::test_should_parse_endlist_playlist",
"tests/test_parser.py::test_should_parse_ALLOW_CACHE",
"tests/test_parser.py::test_should_parse_VERSION",
"tests/test_parser.py::test_should_parse_program_date_time_from_playlist",
"tests/test_parser.py::test_should_parse_scte35_from_playlist",
"tests/test_parser.py::test_should_parse_envivio_cue_playlist",
"tests/test_parser.py::test_parse_simple_playlist_messy",
"tests/test_parser.py::test_parse_simple_playlist_messy_strict",
"tests/test_parser.py::test_commaless_extinf",
"tests/test_parser.py::test_commaless_extinf_strict"
]
| []
| MIT License | 1,634 | [
"m3u8/model.py",
"m3u8/parser.py"
]
| [
"m3u8/model.py",
"m3u8/parser.py"
]
|
|
zopefoundation__zope.sendmail-12 | 6e377f7e9a849bf4b39c416ddc9f7ce010a0785d | 2017-08-29 16:31:06 | 97b322df35daa029c76ae501ca43fe7bfc5acf1d | diff --git a/CHANGES.rst b/CHANGES.rst
index 3d3de1a..685b9d4 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -23,6 +23,11 @@
- Reach 100% test coverage and maintain it via tox.ini and Travis CI.
+- Replaced deprecated dependency on ``optparse`` with equivalent
+ ``argparse``. The help messages have changed and errors are
+ generally more clear. Specifying a ``--config`` path that doesn't
+ exist is now an error instead of being silently ignored.
+
4.0.1 (2014-12-29)
==================
diff --git a/src/zope/sendmail/queue.py b/src/zope/sendmail/queue.py
index ec667d6..7296999 100644
--- a/src/zope/sendmail/queue.py
+++ b/src/zope/sendmail/queue.py
@@ -19,7 +19,7 @@ __docformat__ = 'restructuredtext'
import atexit
import logging
-import optparse
+import argparse
import os
import smtplib
import stat
@@ -363,39 +363,56 @@ class ConsoleApp(object):
"queue_path",
]
- parser = optparse.OptionParser(usage='%prog [OPTIONS] path/to/maildir')
- parser.add_option('--daemon', action='store_true',
- help="Run in daemon mode, periodically checking queue "
- "and sending messages. Default is to send all "
- "messages in queue once and exit.")
- parser.add_option('--interval', metavar='<#secs>', type='float', default=3,
- help="How often to check queue when in daemon mode. "
- "Default is %default seconds.")
- parser.add_option('--hostname', default='localhost',
- help="Name of smtp host to use for delivery. Default is "
- "%default.")
- parser.add_option('--port', type='int', default=25,
- help="Which port on smtp server to deliver mail to. "
- "Default is %default.")
- parser.add_option('--username',
- help="Username to use to log in to smtp server. Default "
- "is none.")
- parser.add_option('--password',
- help="Password to use to log in to smtp server. Must be "
- "specified if username is specified.")
- parser.add_option('--force-tls', action='store_true',
- help="Do not connect if TLS is not available. Not "
- "enabled by default.")
- parser.add_option('--no-tls', action='store_true',
- help="Do not use TLS even if is available. Not enabled "
- "by default.")
- parser.add_option('--config', metavar='<inifile>',
- help="Get configuration from specified ini file; it must "
- "contain a section [%s] that can contain the "
- "following keys: %s. If you specify the queue path "
- "in the ini file, you don't need to specify it on "
- "the command line." % (INI_SECTION,
- ', '.join(INI_NAMES)))
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--daemon', action='store_true',
+ help=("Run in daemon mode, periodically checking queue "
+ "and sending messages. Default is to send all "
+ "messages in queue once and exit."))
+ parser.add_argument('--interval', metavar='<#secs>', type=float, default=3,
+ help=("How often to check queue when in daemon mode. "
+ "Default is %(default)s seconds."))
+ smtp_group = parser.add_argument_group("SMTP Server",
+ "Connection information for the SMTP server")
+ smtp_group.add_argument('--hostname', default='localhost',
+ help=("Name of SMTP host to use for delivery. Default is "
+ "%(default)s."))
+ smtp_group.add_argument('--port', type=int, default=25,
+ help=("Which port on SMTP server to deliver mail to. "
+ "Default is %(default)s."))
+
+ auth_group = parser.add_argument_group("Authentication",
+ ("Authentication information for the SMTP server. "
+ "If one is provided, they must both be. One or both "
+ "can be provided in the --config file."))
+ auth_group.add_argument('--username',
+ help=("Username to use to log in to SMTP server. Default "
+ "is none."))
+ auth_group.add_argument('--password',
+ help=("Password to use to log in to SMTP server. Must be "
+ "specified if username is specified."))
+ del auth_group
+ tls_group = smtp_group.add_mutually_exclusive_group()
+ tls_group.add_argument('--force-tls', action='store_true',
+ help=("Do not connect if TLS is not available. Not "
+ "enabled by default."))
+ tls_group.add_argument('--no-tls', action='store_true',
+ help=("Do not use TLS even if is available. Not enabled "
+ "by default."))
+ del tls_group
+ del smtp_group
+ parser.add_argument('--config', metavar='<inifile>',
+ type=argparse.FileType(),
+ help=("Get configuration from specified ini file; it must "
+ "contain a section [%s] that can contain the "
+ "following keys: %s. If you specify the queue path "
+ "in the ini file, you don't need to specify it on "
+ "the command line. With the exception of the queue path, "
+ "options specified in the ini file override options on the "
+ "command line." % (INI_SECTION, ', '.join(INI_NAMES))))
+ parser.add_argument("maildir", default=None, nargs="?",
+ help=("The path to the mail queue directory."
+ "If not given, it must be found in the --config file."
+ "If given, this overrides a value in the --config file"))
daemon = False
interval = 3
@@ -425,7 +442,7 @@ class ConsoleApp(object):
queue.run(forever=self.daemon)
def _process_args(self, args):
- opts, args = self.parser.parse_args(args)
+ opts = self.parser.parse_args(args)
self.daemon = opts.daemon
self.interval = opts.interval
self.hostname = opts.hostname
@@ -434,19 +451,18 @@ class ConsoleApp(object):
self.password = opts.password
self.force_tls = opts.force_tls
self.no_tls = opts.no_tls
+
if opts.config:
- self._load_config(opts.config)
- if len(args) > 1:
- self.parser.error('too many arguments')
- elif args:
- self.queue_path = args[0]
+ fname = opts.config.name
+ opts.config.close()
+ self._load_config(fname)
+ self.queue_path = opts.maildir or self.queue_path
+
if not self.queue_path:
self.parser.error('please specify the queue path')
if (self.username or self.password) and \
not (self.username and self.password):
self.parser.error('Must use username and password together.')
- if self.force_tls and self.no_tls:
- self.parser.error('--force-tls and --no-tls are mutually exclusive.')
def _load_config(self, path):
section = self.INI_SECTION
| Port to argparse
We're still using the deprecated optparse. This will be easier after #7 | zopefoundation/zope.sendmail | diff --git a/src/zope/sendmail/tests/test_queue.py b/src/zope/sendmail/tests/test_queue.py
index ca00337..9baac58 100644
--- a/src/zope/sendmail/tests/test_queue.py
+++ b/src/zope/sendmail/tests/test_queue.py
@@ -376,17 +376,26 @@ class TestConsoleApp(unittest.TestCase):
self.delivery = QueuedMailDelivery(self.queue_dir)
self.maildir = Maildir(self.queue_dir, True)
self.mailer = MailerStub()
- self.real_stderr = sys.stderr
- self.stderr = io.StringIO() if bytes is not str else io.BytesIO()
+ io_type = io.StringIO if bytes is not str else io.BytesIO
+ self.stderr = io_type()
+ self.stdout = io_type()
def tearDown(self):
- sys.stderr = self.real_stderr
shutil.rmtree(self.dir)
+ def _make_one(self, cmdline):
+ cmdline = cmdline.split() if isinstance(cmdline, str) else cmdline
+ with patched(sys, 'stdout', self.stdout), \
+ patched(sys, 'stderr', self.stderr):
+ return ConsoleApp(cmdline, verbose=False)
+
+ def _get_output(self):
+ return self.stderr.getvalue() + self.stdout.getvalue()
+
def test_args_processing(self):
# simplest case that works
cmdline = "zope-sendmail %s" % self.dir
- app = ConsoleApp(cmdline.split(), verbose=False)
+ app = self._make_one(cmdline)
self.assertEqual("zope-sendmail", app.script_name)
self.assertEqual(self.dir, app.queue_path)
self.assertFalse(app.daemon)
@@ -401,15 +410,18 @@ class TestConsoleApp(unittest.TestCase):
def test_args_processing_no_queue_path(self):
# simplest case that doesn't work: no queue path specified
cmdline = "zope-sendmail"
- sys.stderr = self.stderr
- self.assertRaises(SystemExit, ConsoleApp, cmdline.split(), verbose=False)
+
+ with self.assertRaises(SystemExit):
+ self._make_one(cmdline)
+
+ self.assertIn('please specify the queue path', self._get_output())
def test_args_processing_almost_all_options(self):
# use (almost) all of the options
cmdline = "zope-sendmail --daemon --interval 7 --hostname foo --port 75 " \
"--username chris --password rossi --force-tls " \
"%s" % self.dir
- app = ConsoleApp(cmdline.split(), verbose=False)
+ app = self._make_one(cmdline)
self.assertEqual("zope-sendmail", app.script_name)
self.assertEqual(self.dir, app.queue_path)
self.assertTrue(app.daemon)
@@ -424,21 +436,28 @@ class TestConsoleApp(unittest.TestCase):
# Add an extra argument
cmdline += ' another-one'
with self.assertRaises(SystemExit):
- ConsoleApp(cmdline.split(), verbose=False)
+ self._make_one(cmdline)
- # self.assertIn('too many arguments', self.stderr.getvalue())
+ self.assertIn('unrecognized argument', self._get_output())
def test_args_processing_username_without_password(self):
# test username without password
cmdline = "zope-sendmail --username chris %s" % self.dir
- sys.stderr = self.stderr
- self.assertRaises(SystemExit, ConsoleApp, cmdline.split(), verbose=False)
+
+ with self.assertRaises(SystemExit):
+ self._make_one(cmdline)
+
+ self.assertIn('Must use username and password together', self._get_output())
+
def test_args_processing_force_tls_and_no_tls(self):
# test force_tls and no_tls
cmdline = "zope-sendmail --force-tls --no-tls %s" % self.dir
- sys.stderr = self.stderr
- self.assertRaises(SystemExit, ConsoleApp, cmdline.split(), verbose=False)
+
+ with self.assertRaises(SystemExit):
+ self._make_one(cmdline)
+
+ self.assertIn('--no-tls: not allowed with argument', self._get_output())
def test_ini_parse(self):
ini_path = os.path.join(self.dir, "zope-sendmail.ini")
@@ -473,6 +492,14 @@ class TestConsoleApp(unittest.TestCase):
self.assertFalse(app.force_tls)
self.assertFalse(app.no_tls)
+ def test_ini_not_exist(self):
+ cmdline = ['sendmail', '--config', 'this path cannot be opened']
+ with self.assertRaises(SystemExit) as exc:
+ self._make_one(cmdline)
+
+ self.assertIn('No such file or directory', self._get_output())
+ self.assertEqual(exc.exception.code, 2)
+
def test_run(self):
cmdline = ['sendmail', self.dir]
@@ -481,5 +508,14 @@ class TestConsoleApp(unittest.TestCase):
patched(ConsoleApp, 'MailerKind', MailerStub):
queue.run(cmdline)
+ def test_help(self):
+ cmdline = ['prog', '--help']
+
+ with self.assertRaises(SystemExit) as exc:
+ self._make_one(cmdline)
+
+ self.assertIn('usage', self._get_output())
+ self.assertEqual(exc.exception.code, 0)
+
def test_suite():
return unittest.defaultTestLoader.loadTestsFromName(__name__)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"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": 2
},
"num_modified_files": 2
} | 4.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"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
certifi==2021.5.30
importlib-metadata==4.8.3
iniconfig==1.1.1
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
transaction==3.1.0
typing_extensions==4.1.1
zipp==3.6.0
zope.component==5.1.0
zope.configuration==4.4.1
zope.event==4.6
zope.exceptions==4.6
zope.hookable==5.4
zope.i18nmessageid==5.1.1
zope.interface==5.5.2
zope.location==4.3
zope.proxy==4.6.1
zope.schema==6.2.1
zope.security==5.8
-e git+https://github.com/zopefoundation/zope.sendmail.git@6e377f7e9a849bf4b39c416ddc9f7ce010a0785d#egg=zope.sendmail
zope.testing==5.0.1
zope.testrunner==5.6
| name: zope.sendmail
channels:
- defaults
- https://repo.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
- six==1.17.0
- tomli==1.2.3
- transaction==3.1.0
- typing-extensions==4.1.1
- zipp==3.6.0
- zope-component==5.1.0
- zope-configuration==4.4.1
- zope-event==4.6
- zope-exceptions==4.6
- zope-hookable==5.4
- zope-i18nmessageid==5.1.1
- zope-interface==5.5.2
- zope-location==4.3
- zope-proxy==4.6.1
- zope-schema==6.2.1
- zope-security==5.8
- zope-testing==5.0.1
- zope-testrunner==5.6
prefix: /opt/conda/envs/zope.sendmail
| [
"src/zope/sendmail/tests/test_queue.py::TestConsoleApp::test_args_processing_almost_all_options",
"src/zope/sendmail/tests/test_queue.py::TestConsoleApp::test_args_processing_force_tls_and_no_tls",
"src/zope/sendmail/tests/test_queue.py::TestConsoleApp::test_help",
"src/zope/sendmail/tests/test_queue.py::TestConsoleApp::test_ini_not_exist"
]
| []
| [
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_deliveration",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_error_logging",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_makeMaildir_creates",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_parseMessage",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_parseMessage_error",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_run_forever",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_smtp_recipients_refused",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_smtp_response_error_permanent",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_smtp_response_error_transient",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_stop_while_running",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_threadName",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_tmpfile_cannot_stat",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_tmpfile_exists",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_tmpfile_too_old",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_tmpfile_too_old_unlink_fails_dne",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_tmpfile_too_old_unlink_fails_generic",
"src/zope/sendmail/tests/test_queue.py::TestQueueProcessorThread::test_utime_fails_dne",
"src/zope/sendmail/tests/test_queue.py::TestConsoleApp::test_args_processing",
"src/zope/sendmail/tests/test_queue.py::TestConsoleApp::test_args_processing_no_queue_path",
"src/zope/sendmail/tests/test_queue.py::TestConsoleApp::test_args_processing_username_without_password",
"src/zope/sendmail/tests/test_queue.py::TestConsoleApp::test_ini_parse",
"src/zope/sendmail/tests/test_queue.py::TestConsoleApp::test_run",
"src/zope/sendmail/tests/test_queue.py::test_suite"
]
| []
| Zope Public License 2.1 | 1,635 | [
"CHANGES.rst",
"src/zope/sendmail/queue.py"
]
| [
"CHANGES.rst",
"src/zope/sendmail/queue.py"
]
|
|
zopefoundation__zope.security-28 | 4e08d85f4ad2d9fb1f1acbe1fad004c81b6d33c0 | 2017-08-30 14:06:26 | c192803b8e92255aea5c45349fdbd478b173224f | diff --git a/.travis.yml b/.travis.yml
index 92655c1..c5b8cc2 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -17,7 +17,8 @@ env:
- TOXENV=docs
install:
- pip install -U pip
- - pip install -U setuptools tox
+ - pip install -U setuptools
+ - pip install -U tox
script:
- tox
notifications:
diff --git a/CHANGES.rst b/CHANGES.rst
index 13ea38e..1533b06 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,7 +4,14 @@ Changes
4.1.2 (unreleased)
------------------
-- TBD
+- Fix `issue 27 <https://github.com/zopefoundation/zope.security/issues/27>`_:
+ iteration of ``zope.interface.providedBy()`` is now allowed by
+ default on all versions of Python. Previously it only worked on
+ Python 2. Note that ``providedBy`` returns unproxied objects for backwards
+ compatibility.
+
+- Fix ``__length_hint__`` of proxied iterator objects. Previously it
+ was ignored.
4.1.1 (2017-05-17)
------------------
diff --git a/appveyor.yml b/appveyor.yml
index 51053ff..567e1a5 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -20,10 +20,12 @@ install:
# We need to install the C extensions that BTrees setup-requires
# separately because we've seen problems with the BTrees build cleanup step trying
# to delete a .pyd that was still open.
- - pip install persistent
- - pip install BTrees
- - pip install zope.testrunner
- - pip install .[test]
+ - python -m pip install -U pip
+ - pip install -U setuptools
+ - pip install -U persistent
+ - pip install -U BTrees
+ - pip install -U zope.testrunner
+ - pip install -U .[test]
build: false
diff --git a/src/zope/security/_proxy.c b/src/zope/security/_proxy.c
index 27edbb3..5108065 100644
--- a/src/zope/security/_proxy.c
+++ b/src/zope/security/_proxy.c
@@ -177,8 +177,8 @@ check(SecurityProxy *self, PyObject *meth, PyObject *name)
return self->proxy_checker->ob_type->tp_as_mapping->
mp_ass_subscript(self->proxy_checker, self->proxy.proxy_object, name);
- r = PyObject_CallMethodObjArgs(self->proxy_checker, meth,
- self->proxy.proxy_object, name,
+ r = PyObject_CallMethodObjArgs(self->proxy_checker, meth,
+ self->proxy.proxy_object, name,
NULL);
if (r == NULL)
return -1;
@@ -227,26 +227,26 @@ check2(PyObject *self, PyObject *other,
{
PyObject *result = NULL;
- if (Proxy_Check(self))
+ if (Proxy_Check(self))
{
if (check((SecurityProxy*)self, str_check, opname) >= 0)
{
- result = operation(((SecurityProxy*)self)->proxy.proxy_object,
+ result = operation(((SecurityProxy*)self)->proxy.proxy_object,
other);
PROXY_RESULT(((SecurityProxy*)self), result);
}
}
- else if (Proxy_Check(other))
+ else if (Proxy_Check(other))
{
if (check((SecurityProxy*)other, str_check, ropname) >= 0)
{
- result = operation(self,
+ result = operation(self,
((SecurityProxy*)other)->proxy.proxy_object);
-
+
PROXY_RESULT(((SecurityProxy*)other), result);
}
}
- else
+ else
{
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
@@ -261,10 +261,10 @@ check2i(SecurityProxy *self, PyObject *other,
{
PyObject *result = NULL;
- if (check(self, str_check, opname) >= 0)
+ if (check(self, str_check, opname) >= 0)
{
result = operation(self->proxy.proxy_object, other);
- if (result == self->proxy.proxy_object)
+ if (result == self->proxy.proxy_object)
{
/* If the operation was really carried out inplace,
don't create a new proxy, but use the old one. */
@@ -272,7 +272,7 @@ check2i(SecurityProxy *self, PyObject *other,
Py_INCREF((PyObject *)self);
result = (PyObject *)self;
}
- else
+ else
PROXY_RESULT(self, result);
}
return result;
@@ -372,7 +372,7 @@ proxy_iter(SecurityProxy *self)
{
PyObject *result = NULL;
- if (check(self, str_check, str___iter__) >= 0)
+ if (check(self, str_check, str___iter__) >= 0)
{
result = PyObject_GetIter(self->proxy.proxy_object);
PROXY_RESULT(self, result);
@@ -385,7 +385,7 @@ proxy_iternext(SecurityProxy *self)
{
PyObject *result = NULL;
- if (check(self, str_check_getattr, str_next) >= 0)
+ if (check(self, str_check_getattr, str_next) >= 0)
{
result = PyIter_Next(self->proxy.proxy_object);
PROXY_RESULT(self, result);
@@ -398,7 +398,7 @@ proxy_getattro(SecurityProxy *self, PyObject *name)
{
PyObject *result = NULL;
- if (check(self, str_check_getattr, name) >= 0)
+ if (check(self, str_check_getattr, name) >= 0)
{
result = PyObject_GetAttr(self->proxy.proxy_object, name);
PROXY_RESULT(self, result);
@@ -449,7 +449,7 @@ default_repr(PyObject *object)
Py_DECREF(klass);
Py_XDECREF(name);
Py_XDECREF(module);
-
+
return result;
}
@@ -458,11 +458,11 @@ proxy_str(SecurityProxy *self)
{
PyObject *result = NULL;
- if (check(self, str_check, str___str__) >= 0)
+ if (check(self, str_check, str___str__) >= 0)
{
result = PyObject_Str(self->proxy.proxy_object);
}
- else
+ else
{
PyErr_Clear();
result = default_repr(self->proxy.proxy_object);
@@ -504,7 +504,7 @@ proxy_call(SecurityProxy *self, PyObject *args, PyObject *kwds)
{
PyObject *result = NULL;
- if (check(self, str_check, str___call__) >= 0)
+ if (check(self, str_check, str___call__) >= 0)
{
result = PyObject_Call(self->proxy.proxy_object, args, kwds);
PROXY_RESULT(self, result);
@@ -558,7 +558,7 @@ proxy_pow(PyObject *self, PyObject *other, PyObject *modulus)
{
PyObject *result = NULL;
- if (Proxy_Check(self))
+ if (Proxy_Check(self))
{
if (check((SecurityProxy*)self, str_check, str___pow__) >= 0)
{
@@ -567,21 +567,21 @@ proxy_pow(PyObject *self, PyObject *other, PyObject *modulus)
PROXY_RESULT(((SecurityProxy*)self), result);
}
}
- else if (Proxy_Check(other))
+ else if (Proxy_Check(other))
{
if (check((SecurityProxy*)other, str_check, str___rpow__) >= 0)
- {
- result = PyNumber_Power(self,
- ((SecurityProxy*)other)->proxy.proxy_object,
+ {
+ result = PyNumber_Power(self,
+ ((SecurityProxy*)other)->proxy.proxy_object,
modulus);
PROXY_RESULT(((SecurityProxy*)other), result);
}
}
- else if (modulus != NULL && Proxy_Check(modulus))
+ else if (modulus != NULL && Proxy_Check(modulus))
{
if (check((SecurityProxy*)modulus, str_check, str___3pow__) >= 0)
- {
- result = PyNumber_Power(self, other,
+ {
+ result = PyNumber_Power(self, other,
((SecurityProxy*)modulus)->proxy.proxy_object);
PROXY_RESULT(((SecurityProxy*)modulus), result);
}
@@ -608,7 +608,7 @@ proxy_coerce(PyObject **p_self, PyObject **p_other)
assert(Proxy_Check(self));
- if (check((SecurityProxy*)self, str_check, str___coerce__) >= 0)
+ if (check((SecurityProxy*)self, str_check, str___coerce__) >= 0)
{
PyObject *left = ((SecurityProxy*)self)->proxy.proxy_object;
PyObject *right = other;
@@ -697,6 +697,21 @@ proxy_length(SecurityProxy *self)
return -1;
}
+static PyObject *
+proxy_length_hint(SecurityProxy *self)
+{
+ PyObject *result = NULL;
+ result = PyObject_CallMethod(self->proxy.proxy_object, "__length_hint__", NULL);
+ if (result == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
+ PyErr_Clear();
+ result = Py_NotImplemented;
+ Py_INCREF(result);
+ }
+ }
+ return result;
+}
+
/* sq_item and sq_ass_item may be called by PySequece_{Get,Set}Item(). */
static PyObject *proxy_getitem(SecurityProxy *, PyObject *);
static int proxy_setitem(SecurityProxy *, PyObject *, PyObject *);
@@ -765,7 +780,7 @@ proxy_getitem(SecurityProxy *self, PyObject *key)
{
PyObject *result = NULL;
- if (check(self, str_check, str___getitem__) >= 0)
+ if (check(self, str_check, str___getitem__) >= 0)
{
result = PyObject_GetItem(self->proxy.proxy_object, key);
PROXY_RESULT(self, result);
@@ -884,6 +899,13 @@ disallowed. The proxy method should return a proxy for the object\n\
if one is needed, otherwise the object itself.\n\
";
+static PyMethodDef proxy_methods[] = {
+ {"__length_hint__", (PyCFunction)proxy_length_hint, METH_NOARGS,
+ "Guess the length of the object"},
+ {NULL, NULL} /* sentinel */
+};
+
+
static PyTypeObject SecurityProxyType = {
PyVarObject_HEAD_INIT(NULL, 0)
"zope.security._proxy._Proxy",
@@ -925,7 +947,7 @@ static PyTypeObject SecurityProxyType = {
0, /* tp_weaklistoffset */
(getiterfunc)proxy_iter, /* tp_iter */
(iternextfunc)proxy_iternext, /* tp_iternext */
- 0, /* tp_methods */
+ proxy_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
@@ -963,7 +985,7 @@ module_getObject(PyObject *self, PyObject *arg)
result = arg;
else
result = ((SecurityProxy*)arg)->proxy.proxy_object;
-
+
Py_INCREF(result);
return result;
}
@@ -974,7 +996,7 @@ module___doc__[] = "Security proxy implementation.";
static PyMethodDef
module_functions[] = {
{"getChecker", module_getChecker, METH_O, "get checker from proxy"},
- {"getObject", module_getObject, METH_O,
+ {"getObject", module_getObject, METH_O,
"Get the proxied object\n\nReturn the original object if not proxied."},
{NULL}
};
@@ -1069,19 +1091,19 @@ if((str_op_##S = INTERN("__" #S "__")) == NULL) return MOD_ERROR_VAL
INIT_STRING(__setitem__);
INIT_STRING(__setslice__);
INIT_STRING(__str__);
-
+
__class__str = FROM_STRING("__class__");
if (! __class__str)
return MOD_ERROR_VAL;
-
+
__name__str = FROM_STRING("__name__");
if (! __name__str)
return MOD_ERROR_VAL;
-
+
__module__str = FROM_STRING("__module__");
if (! __module__str) return MOD_ERROR_VAL;
-
+
SecurityProxyType.tp_alloc = PyType_GenericAlloc;
SecurityProxyType.tp_free = PyObject_GC_Del;
SecurityProxyType.tp_base = &ProxyType;
diff --git a/src/zope/security/checker.py b/src/zope/security/checker.py
index 344428c..f870a13 100644
--- a/src/zope/security/checker.py
+++ b/src/zope/security/checker.py
@@ -604,7 +604,8 @@ _typeChecker = NamesChecker(
'__implemented__'])
_namedChecker = NamesChecker(['__name__'])
-_iteratorChecker = NamesChecker(['next', '__next__', '__iter__', '__len__'])
+_iteratorChecker = NamesChecker(['next', '__next__', '__iter__', '__len__',
+ '__length_hint__',])
_setChecker = NamesChecker(['__iter__', '__len__', '__str__', '__contains__',
'copy', 'difference', 'intersection', 'issubset',
@@ -823,6 +824,42 @@ else:
del _fixup_dictlike
+def _fixup_zope_interface():
+ # Make sure the provided and implementedBy objects
+ # can be iterated.
+ # Note that we DO NOT use the _iteratorChecker, but instead
+ # we use NoProxy to be sure that the results (of iteration or not) are not
+ # proxied. On Python 2, these objects are builtin and don't go through the
+ # checking process at all, much like BTrees, so NoProxy is necessary for
+ # compatibility. On Python 3, prior to this, iteration was simply not allowed.
+ from zope.interface import providedBy
+ from zope.interface import alsoProvides
+
+ class I1(Interface):
+ pass
+
+ class I2(Interface):
+ pass
+
+ @implementer(I1)
+ class O(object):
+ pass
+
+ o = O()
+
+
+ # This will be athe zope.interface.implementedBy from the class
+ # a zope.interface.declarations.Implements
+ _default_checkers[type(providedBy(o))] = NoProxy
+
+ alsoProvides(o, I2)
+ # This will be the zope.interface.Provides from the instance
+ _default_checkers[type(providedBy(o))] = NoProxy
+
+_fixup_zope_interface()
+del _fixup_zope_interface
+
+
def _clear():
_checkers.clear()
_checkers.update(_default_checkers)
diff --git a/src/zope/security/proxy.py b/src/zope/security/proxy.py
index d7f12e2..77a82d4 100644
--- a/src/zope/security/proxy.py
+++ b/src/zope/security/proxy.py
@@ -199,6 +199,11 @@ class ProxyPy(PyProxyBase):
return bool(wrapped)
__bool__ = __nonzero__
+ def __length_hint__(self):
+ # no check
+ wrapped = super(PyProxyBase, self).__getattribute__('_wrapped')
+ return wrapped.__length_hint__()
+
def __coerce__(self, other):
# For some reason _check_name does not work for coerce()
wrapped = super(PyProxyBase, self).__getattribute__('_wrapped')
| Proxied zope.interface.Provides and implementedBy can't be put in a list in Python 3 but can in Py2
This is similar to #23 and #20, except with `__len__`, not `__iter__`. And it only happens in Python 3.
When you write `list(thing)` in CPython 3, CPython will look for the `__len__` slot in the C struct for the object's type. If that's filled in, and calling it raises any exception besides a `TypeError`, that exception is propageted. This is implemented in `Objects/abstract.c:PyObject_LengthHint`. This is defined in [PEP 424](https://www.python.org/dev/peps/pep-0424/) and implemented in Python 3.4.
In Python 2.7 and earlier, there is a private CPython function `_PyObject_LengthHint` that ignores both `TypeError` and `AttributeError` when it tries to get the `__len__`. zope.security's `ForbiddenAttribute` exception derives from `AttributeError` and so is ignored for this purpose.
Here's sample code:
```python
from zope.security.proxy import Proxy
from zope.security.checker import Checker
from zope.security.checker import CheckerPublic
from zope.interface import providedBy
from zope.interface import alsoProvides
from zope.interface import implementer
from zope.interface import Interface
class I1(Interface):
pass
class I2(Interface):
pass
@implementer(I1)
class O(object):
pass
o = O()
# alsoProvides(o, I2)
checker = Checker({})
proxy = Proxy(o, checker)
list(providedBy(proxy))
```
Under Python 3.4+ this raises (PURE_PYTHON used for a slightly more clear stack trace; the same thing happens with all the C extensions in place):
```
PURE_PYTHON=1 python /tmp/test.py
Traceback (most recent call last):
File "/tmp/test.py", line 22, in <module>
list(providedBy(proxy))
File "//lib/python3.5/site-packages/zope/security/proxy.py", line 28, in _wrapper
checker.check(wrapped, name)
File "//lib/python3.5/site-packages/zope/security/checker.py", line 229, in check
raise ForbiddenAttribute(name, object)
zope.security.interfaces.ForbiddenAttribute: ('__len__', <implementedBy __main__.O>)
```
If you uncomment the `alsoProvides` line, you get a similar but different exception:
```
Traceback (most recent call last):
File "/tmp/test.py", line 27, in <module>
list(providedBy(proxy))
File "//lib/python3.5/site-packages/zope/security/proxy.py", line 28, in _wrapper
checker.check(wrapped, name)
File "//lib/python3.5/site-packages/zope/security/checker.py", line 229, in check
raise ForbiddenAttribute(name, object)
zope.security.interfaces.ForbiddenAttribute: ('__len__', <zope.interface.Provides object at 0x1060f2048>)
```
**Under Python 2.7, these both run just fine.**
How should we address this discrepancy (assuming we should)?
* Should we keep playing whack-a-mole and add those two types of objects to the set for which `_iteratorChecker` is used by default?
* Or should we alter the `Checker` implementation to ignore requests for `__len__`, as it already does for `__iter__`?
* Or maybe these two types of objects (the attributes) shouldn't be wrapped in proxies at all? (I don't think we trivially have that capability.)
* Other options?
If we do anything, we should probably also adapt the same solution for the other half of PEP424 and do the same thing for the `__length_hint__` method.
I ran into this considering a potential efficiency change in `zope.app.apidoc`. | zopefoundation/zope.security | diff --git a/src/zope/security/tests/test_checker.py b/src/zope/security/tests/test_checker.py
index 03a8883..b82799f 100644
--- a/src/zope/security/tests/test_checker.py
+++ b/src/zope/security/tests/test_checker.py
@@ -434,6 +434,125 @@ class CheckerTestsBase(object):
# iteration of regular dict is allowed by default
self._check_iteration_of_dict_like(dict())
+ def test_iteration_of_interface_implementedBy(self):
+ # Iteration of implementedBy is allowed by default
+ # See https://github.com/zopefoundation/zope.security/issues/27
+ from zope.security.proxy import Proxy
+ from zope.security.checker import Checker
+
+ from zope.interface import providedBy
+ from zope.interface import implementer
+ from zope.interface import Interface
+
+ class I1(Interface):
+ pass
+
+ @implementer(I1)
+ class O(object):
+ pass
+
+ o = O()
+
+ checker = Checker({})
+
+ proxy = Proxy(o, checker)
+
+ # Since the object itself doesn't have any interfaces,
+ # the providedBy will return the implementedBy of the class
+ l = list(providedBy(proxy))
+
+ self.assertEqual(l, [I1])
+
+ def test_iteration_of_interface_providesBy(self):
+ # Iteration of zope.interface.Provides is allowed by default
+ # See https://github.com/zopefoundation/zope.security/issues/27
+ from zope.security.proxy import Proxy
+ from zope.security.checker import Checker
+
+ from zope.interface import providedBy
+ from zope.interface import alsoProvides
+ from zope.interface import implementer
+ from zope.interface import Interface
+
+ class I1(Interface):
+ pass
+
+ class I2(Interface):
+ pass
+
+ @implementer(I1)
+ class O(object):
+ pass
+
+ o = O()
+ alsoProvides(o, I2)
+
+ checker = Checker({})
+
+ proxy = Proxy(o, checker)
+
+ # Since the object has its own interfaces, provided
+ # by will return a zope.interface.Provides object
+ l = list(providedBy(proxy))
+
+ self.assertEqual(l, [I2, I1])
+
+ def test_iteration_with_length_hint(self):
+ # PEP 424 implemented officially in Python 3.4 and
+ # unofficially before in cPython and PyPy that allows for a
+ # __length_hint__ method to be defined on iterators. It should
+ # be allowed by default. See
+ # https://github.com/zopefoundation/zope.security/issues/27
+ from zope.security.proxy import Proxy
+ from zope.security.checker import _iteratorChecker
+ from zope.security.checker import Checker
+
+ class Iter(object):
+ __Security_checker__ = _iteratorChecker
+
+ items = (0, 1, 2)
+ index = 0
+ hint = len(items)
+ hint_called = False
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ try:
+ return self.items[self.index]
+ except IndexError:
+ raise StopIteration()
+ finally:
+ self.index += 1
+
+ next = __next__
+
+ def __length_hint__(self):
+ self.hint_called = True
+ return self.hint
+
+ # The hint is called on raw objects
+ i = Iter()
+ list(i)
+ self.assertTrue(i.hint_called, "__length_hint__ should be called")
+
+ # The hint is called when we proxy the root object
+ i = Iter()
+ proxy = Proxy(i, _iteratorChecker)
+ l = list(proxy)
+ self.assertEqual(l, [0, 1, 2])
+ self.assertTrue(i.hint_called, "__length_hint__ should be called")
+
+ # The hint is called when we proxy its iterator
+ i = Iter()
+ it = iter(i)
+ proxy = Proxy(it, _iteratorChecker)
+ l = list(proxy)
+ self.assertEqual(l, [0, 1, 2])
+ self.assertTrue(i.hint_called, "__length_hint__ should be called")
+
+
class CheckerPyTests(unittest.TestCase, CheckerTestsBase):
def _getTargetClass(self):
| {
"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": 1,
"issue_text_score": 2,
"test_score": 1
},
"num_modified_files": 6
} | 4.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",
"coverage"
],
"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
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
zope.component==5.1.0
zope.event==4.6
zope.hookable==5.4
zope.i18nmessageid==5.1.1
zope.interface==5.5.2
zope.location==4.3
zope.proxy==4.6.1
zope.schema==6.2.1
-e git+https://github.com/zopefoundation/zope.security.git@4e08d85f4ad2d9fb1f1acbe1fad004c81b6d33c0#egg=zope.security
| name: zope.security
channels:
- defaults
- https://repo.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
- 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
- zope-component==5.1.0
- zope-event==4.6
- zope-hookable==5.4
- zope-i18nmessageid==5.1.1
- zope-interface==5.5.2
- zope-location==4.3
- zope-proxy==4.6.1
- zope-schema==6.2.1
prefix: /opt/conda/envs/zope.security
| [
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_iteration_of_interface_implementedBy",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_iteration_of_interface_providesBy",
"src/zope/security/tests/test_checker.py::CheckerTests::test_iteration_of_interface_implementedBy",
"src/zope/security/tests/test_checker.py::CheckerTests::test_iteration_of_interface_providesBy"
]
| [
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_iteration_with_length_hint",
"src/zope/security/tests/test_checker.py::CheckerTests::test_iteration_with_length_hint",
"src/zope/security/tests/test_checker.py::Test_defineChecker::test_w_duplicate",
"src/zope/security/tests/test_checker.py::Test::testMultiChecker"
]
| [
"src/zope/security/tests/test_checker.py::Test_ProxyFactory::test_no_checker_no_dunder_no_select",
"src/zope/security/tests/test_checker.py::Test_ProxyFactory::test_no_checker_no_dunder_w_select",
"src/zope/security/tests/test_checker.py::Test_ProxyFactory::test_no_checker_w_dunder",
"src/zope/security/tests/test_checker.py::Test_ProxyFactory::test_w_already_proxied_different_checker",
"src/zope/security/tests/test_checker.py::Test_ProxyFactory::test_w_already_proxied_no_checker",
"src/zope/security/tests/test_checker.py::Test_ProxyFactory::test_w_already_proxied_same_checker",
"src/zope/security/tests/test_checker.py::Test_ProxyFactory::test_w_explicit_checker",
"src/zope/security/tests/test_checker.py::Test_canWrite::test_ok",
"src/zope/security/tests/test_checker.py::Test_canWrite::test_w_setattr_forbidden_getattr_allowed",
"src/zope/security/tests/test_checker.py::Test_canWrite::test_w_setattr_forbidden_getattr_forbidden",
"src/zope/security/tests/test_checker.py::Test_canWrite::test_w_setattr_forbidden_getattr_unauth",
"src/zope/security/tests/test_checker.py::Test_canWrite::test_w_setattr_unauth",
"src/zope/security/tests/test_checker.py::Test_canAccess::test_ok",
"src/zope/security/tests/test_checker.py::Test_canAccess::test_w_getattr_unauth",
"src/zope/security/tests/test_checker.py::Test_canAccess::test_w_setattr_forbidden_getattr_allowed",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_check_available_by_default",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_check_miss",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_check_non_public_w_interaction_allows",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_check_non_public_w_interaction_denies",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_check_public",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_check_setattr_miss",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_check_setattr_miss_none_set",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_check_setattr_public",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_check_setattr_w_interaction_allows",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_check_setattr_w_interaction_denies",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_class_conforms_to_IChecker",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_ctor_w_non_dict_get_permissions",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_ctor_w_non_dict_set_permissions",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_instance_conforms_to_IChecker",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_iteration_of_dict_items_keys_values",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_iteration_of_odict_items_keys_values",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_permission_id_hit",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_permission_id_miss",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_proxy_already_proxied",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_proxy_no_checker_no_dunder_w_select",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_proxy_no_checker_w_dunder",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_proxy_no_dunder_no_select",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_setattr_permission_id_hit",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_setattr_permission_id_miss",
"src/zope/security/tests/test_checker.py::CheckerPyTests::test_setattr_permission_id_miss_none_set",
"src/zope/security/tests/test_checker.py::CheckerTests::test_check_available_by_default",
"src/zope/security/tests/test_checker.py::CheckerTests::test_check_miss",
"src/zope/security/tests/test_checker.py::CheckerTests::test_check_non_public_w_interaction_allows",
"src/zope/security/tests/test_checker.py::CheckerTests::test_check_non_public_w_interaction_denies",
"src/zope/security/tests/test_checker.py::CheckerTests::test_check_public",
"src/zope/security/tests/test_checker.py::CheckerTests::test_check_setattr_miss",
"src/zope/security/tests/test_checker.py::CheckerTests::test_check_setattr_miss_none_set",
"src/zope/security/tests/test_checker.py::CheckerTests::test_check_setattr_public",
"src/zope/security/tests/test_checker.py::CheckerTests::test_check_setattr_w_interaction_allows",
"src/zope/security/tests/test_checker.py::CheckerTests::test_check_setattr_w_interaction_denies",
"src/zope/security/tests/test_checker.py::CheckerTests::test_class_conforms_to_IChecker",
"src/zope/security/tests/test_checker.py::CheckerTests::test_ctor_w_non_dict_get_permissions",
"src/zope/security/tests/test_checker.py::CheckerTests::test_ctor_w_non_dict_set_permissions",
"src/zope/security/tests/test_checker.py::CheckerTests::test_instance_conforms_to_IChecker",
"src/zope/security/tests/test_checker.py::CheckerTests::test_iteration_of_dict_items_keys_values",
"src/zope/security/tests/test_checker.py::CheckerTests::test_iteration_of_odict_items_keys_values",
"src/zope/security/tests/test_checker.py::CheckerTests::test_permission_id_hit",
"src/zope/security/tests/test_checker.py::CheckerTests::test_permission_id_miss",
"src/zope/security/tests/test_checker.py::CheckerTests::test_proxy_already_proxied",
"src/zope/security/tests/test_checker.py::CheckerTests::test_proxy_no_checker_no_dunder_w_select",
"src/zope/security/tests/test_checker.py::CheckerTests::test_proxy_no_checker_w_dunder",
"src/zope/security/tests/test_checker.py::CheckerTests::test_proxy_no_dunder_no_select",
"src/zope/security/tests/test_checker.py::CheckerTests::test_setattr_permission_id_hit",
"src/zope/security/tests/test_checker.py::CheckerTests::test_setattr_permission_id_miss",
"src/zope/security/tests/test_checker.py::CheckerTests::test_setattr_permission_id_miss_none_set",
"src/zope/security/tests/test_checker.py::TracebackSupplementTests::test_getInfo_builtin_types",
"src/zope/security/tests/test_checker.py::TracebackSupplementTests::test_getInfo_newstyle_instance",
"src/zope/security/tests/test_checker.py::GlobalTests::test___reduce__",
"src/zope/security/tests/test_checker.py::GlobalTests::test___repr__",
"src/zope/security/tests/test_checker.py::GlobalTests::test_ctor_name_and_module",
"src/zope/security/tests/test_checker.py::Test_NamesChecker::test_empty_names_no_kw",
"src/zope/security/tests/test_checker.py::Test_NamesChecker::test_w_names_no_kw",
"src/zope/security/tests/test_checker.py::Test_NamesChecker::test_w_names_no_kw_explicit_permission",
"src/zope/security/tests/test_checker.py::Test_NamesChecker::test_w_names_w_kw_no_clash",
"src/zope/security/tests/test_checker.py::Test_NamesChecker::test_w_names_w_kw_w_clash",
"src/zope/security/tests/test_checker.py::Test_InterfaceChecker::test_derived_iface",
"src/zope/security/tests/test_checker.py::Test_InterfaceChecker::test_simple_iface_w_explicit_permission",
"src/zope/security/tests/test_checker.py::Test_InterfaceChecker::test_simple_iface_w_kw",
"src/zope/security/tests/test_checker.py::Test_InterfaceChecker::test_simple_iface_wo_kw",
"src/zope/security/tests/test_checker.py::Test_InterfaceChecker::test_w_clash",
"src/zope/security/tests/test_checker.py::Test_MultiChecker::test_empty",
"src/zope/security/tests/test_checker.py::Test_MultiChecker::test_w_spec_as_iface",
"src/zope/security/tests/test_checker.py::Test_MultiChecker::test_w_spec_as_mapping",
"src/zope/security/tests/test_checker.py::Test_MultiChecker::test_w_spec_as_names",
"src/zope/security/tests/test_checker.py::Test_MultiChecker::test_w_spec_as_names_and_iface",
"src/zope/security/tests/test_checker.py::Test_MultiChecker::test_w_spec_as_names_and_iface_clash",
"src/zope/security/tests/test_checker.py::Test_MultiChecker::test_w_spec_as_names_and_mapping_clash",
"src/zope/security/tests/test_checker.py::Test_selectCheckerPy::test_w_basic_types_NoProxy",
"src/zope/security/tests/test_checker.py::Test_selectCheckerPy::test_w_checker_inst",
"src/zope/security/tests/test_checker.py::Test_selectCheckerPy::test_w_factory_factory",
"src/zope/security/tests/test_checker.py::Test_selectCheckerPy::test_w_factory_returning_NoProxy",
"src/zope/security/tests/test_checker.py::Test_selectCheckerPy::test_w_factory_returning_None",
"src/zope/security/tests/test_checker.py::Test_selectCheckerPy::test_w_factory_returning_checker",
"src/zope/security/tests/test_checker.py::Test_selectChecker::test_w_basic_types_NoProxy",
"src/zope/security/tests/test_checker.py::Test_selectChecker::test_w_checker_inst",
"src/zope/security/tests/test_checker.py::Test_selectChecker::test_w_factory_factory",
"src/zope/security/tests/test_checker.py::Test_selectChecker::test_w_factory_returning_NoProxy",
"src/zope/security/tests/test_checker.py::Test_selectChecker::test_w_factory_returning_None",
"src/zope/security/tests/test_checker.py::Test_selectChecker::test_w_factory_returning_checker",
"src/zope/security/tests/test_checker.py::Test_getCheckerForInstancesOf::test_hit",
"src/zope/security/tests/test_checker.py::Test_getCheckerForInstancesOf::test_miss",
"src/zope/security/tests/test_checker.py::Test_defineChecker::test_w_module",
"src/zope/security/tests/test_checker.py::Test_defineChecker::test_w_newstyle_class",
"src/zope/security/tests/test_checker.py::Test_defineChecker::test_w_wrong_type",
"src/zope/security/tests/test_checker.py::Test_undefineChecker::test_hit",
"src/zope/security/tests/test_checker.py::Test_undefineChecker::test_miss",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_lhs_forbidden_rhs_forbidden",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_lhs_forbidden_rhs_ok",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_lhs_forbidden_rhs_unauth",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_lhs_ok_rhs_not_called",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_lhs_unauth_rhs_forbidden",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_lhs_unauth_rhs_ok",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_lhs_unauth_rhs_unauth",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_setattr_lhs_forbidden_rhs_forbidden",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_setattr_lhs_forbidden_rhs_ok",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_setattr_lhs_forbidden_rhs_unauth",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_setattr_lhs_ok_rhs_not_called",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_setattr_lhs_unauth_rhs_forbidden",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_setattr_lhs_unauth_rhs_ok",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_check_setattr_lhs_unauth_rhs_unauth",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_class_conforms_to_IChecker",
"src/zope/security/tests/test_checker.py::CombinedCheckerTests::test_instance_conforms_to_IChecker",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_forbidden_attribute",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_getattr_forbidden_attribute",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_getattr_ok_normal_verbosity",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_getattr_ok_raised_verbosity_available_by_default",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_getattr_ok_raised_verbosity_normal_name",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_getattr_unauthorized",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_ok_normal_verbosity",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_ok_raised_verbosity_available_by_default",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_ok_raised_verbosity_normal_name",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_setattr_forbidden_attribute",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_setattr_ok_normal_verbosity",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_setattr_ok_raised_verbosity_normal_name",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_setattr_unauthorized",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_setitem_unauthorized",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_unauthorized",
"src/zope/security/tests/test_checker.py::CheckerLoggingMixinTests::test_check_unauthorized_raised_verbosity",
"src/zope/security/tests/test_checker.py::Test__instanceChecker::test_hit",
"src/zope/security/tests/test_checker.py::Test__instanceChecker::test_miss",
"src/zope/security/tests/test_checker.py::Test_moduleChecker::test_hit",
"src/zope/security/tests/test_checker.py::Test_moduleChecker::test_miss",
"src/zope/security/tests/test_checker.py::BasicTypesTests::test___delitem__",
"src/zope/security/tests/test_checker.py::BasicTypesTests::test___setitem__",
"src/zope/security/tests/test_checker.py::BasicTypesTests::test_clear",
"src/zope/security/tests/test_checker.py::BasicTypesTests::test_update",
"src/zope/security/tests/test_checker.py::Test::testAlwaysAvailable",
"src/zope/security/tests/test_checker.py::Test::testLayeredProxies",
"src/zope/security/tests/test_checker.py::Test::test_ProxyFactory",
"src/zope/security/tests/test_checker.py::Test::test_ProxyFactory_using_proxy",
"src/zope/security/tests/test_checker.py::Test::test_canWrite_canAccess",
"src/zope/security/tests/test_checker.py::Test::test_defineChecker_error",
"src/zope/security/tests/test_checker.py::Test::test_defineChecker_module",
"src/zope/security/tests/test_checker.py::Test::test_defineChecker_newstyle_class",
"src/zope/security/tests/test_checker.py::Test::test_define_and_undefineChecker",
"src/zope/security/tests/test_checker.py::Test::test_iteration",
"src/zope/security/tests/test_checker.py::TestCheckerPublic::test_that_CheckerPublic_identity_works_even_when_proxied",
"src/zope/security/tests/test_checker.py::TestCheckerPublic::test_that_pickling_CheckerPublic_retains_identity",
"src/zope/security/tests/test_checker.py::TestCombinedChecker::test_checking",
"src/zope/security/tests/test_checker.py::TestCombinedChecker::test_interface",
"src/zope/security/tests/test_checker.py::TestBasicTypes::test",
"src/zope/security/tests/test_checker.py::test_suite"
]
| []
| Zope Public License 2.1 | 1,636 | [
"src/zope/security/checker.py",
"src/zope/security/proxy.py",
".travis.yml",
"CHANGES.rst",
"appveyor.yml",
"src/zope/security/_proxy.c"
]
| [
"src/zope/security/checker.py",
"src/zope/security/proxy.py",
".travis.yml",
"CHANGES.rst",
"appveyor.yml",
"src/zope/security/_proxy.c"
]
|
|
jupyterhub__oauthenticator-116 | ac730b276184640227c2ca999bfccfe7472fca85 | 2017-08-30 14:14:45 | bd4567ceacca1dcc8122be2f96db320c4342fd02 | diff --git a/oauthenticator/gitlab.py b/oauthenticator/gitlab.py
index 860aa92..5afddb8 100644
--- a/oauthenticator/gitlab.py
+++ b/oauthenticator/gitlab.py
@@ -107,7 +107,7 @@ class GitLabOAuthenticator(OAuthenticator):
username = resp_json["username"]
user_id = resp_json["id"]
- is_admin = resp_json["is_admin"]
+ is_admin = resp_json.get("is_admin", False)
# Check if user is a member of any whitelisted organizations.
# This check is performed here, as it requires `access_token`.
| GitLab auth fails for non admin users
Recent changes in GitLab's API have removed the "is_admin" property from most API calls: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/10846
Now it is only shown when the request comes from an admin user:
https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/12211
This causes an error 500 for non-admin users, when "is_admin" is not found in the response. | jupyterhub/oauthenticator | diff --git a/oauthenticator/tests/test_gitlab.py b/oauthenticator/tests/test_gitlab.py
index 86d2b45..5163a49 100644
--- a/oauthenticator/tests/test_gitlab.py
+++ b/oauthenticator/tests/test_gitlab.py
@@ -16,11 +16,15 @@ from .mocks import setup_oauth_mock
def user_model(username, id=1, is_admin=False):
"""Return a user model"""
- return {
+ user = {
'username': username,
'id': id,
- 'is_admin': is_admin
}
+ if is_admin:
+ # Some versions of the API do not return the is_admin property
+ # for non-admin users (See #115).
+ user['is_admin'] = True
+ return user
@fixture
def gitlab_client(client):
@@ -58,12 +62,10 @@ def test_group_whitelist(gitlab_client):
'burns': ['blue', 'yellow'],
})
- def user_model(username, is_admin=False):
- return {
- 'username': username,
- 'id': list(user_groups.keys()).index(username) + 1,
- 'is_admin': is_admin
- }
+ def group_user_model(username, is_admin=False):
+ return user_model(username,
+ list(user_groups.keys()).index(username) + 1,
+ is_admin)
member_regex = re.compile(r'/api/v3/groups/(.*)/members/(.*)')
@@ -116,30 +118,30 @@ def test_group_whitelist(gitlab_client):
authenticator.gitlab_group_whitelist = ['blue']
- handler = client.handler_for_user(user_model('caboose'))
+ handler = client.handler_for_user(group_user_model('caboose'))
name = yield authenticator.authenticate(handler)
assert name == 'caboose'
- handler = client.handler_for_user(user_model('burns', is_admin=True))
+ handler = client.handler_for_user(group_user_model('burns', is_admin=True))
name = yield authenticator.authenticate(handler)
assert name == 'burns'
- handler = client.handler_for_user(user_model('grif'))
+ handler = client.handler_for_user(group_user_model('grif'))
name = yield authenticator.authenticate(handler)
assert name is None
- handler = client.handler_for_user(user_model('simmons', is_admin=True))
+ handler = client.handler_for_user(group_user_model('simmons', is_admin=True))
name = yield authenticator.authenticate(handler)
assert name is None
# reverse it, just to be safe
authenticator.gitlab_group_whitelist = ['red']
- handler = client.handler_for_user(user_model('caboose'))
+ handler = client.handler_for_user(group_user_model('caboose'))
name = yield authenticator.authenticate(handler)
assert name is None
- handler = client.handler_for_user(user_model('grif'))
+ handler = client.handler_for_user(group_user_model('grif'))
name = yield authenticator.authenticate(handler)
assert name == 'grif'
| {
"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": 2
},
"num_modified_files": 1
} | 0.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-tornado",
"requests-mock",
"flake8",
"pyjwt",
"codecov"
],
"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"
} | alembic==1.15.2
annotated-types==0.7.0
arrow==1.3.0
async-generator==1.10
attrs==25.3.0
certifi==2025.1.31
certipy==0.2.2
cffi==1.17.1
charset-normalizer==3.4.1
codecov==2.1.13
coverage==7.8.0
cryptography==44.0.2
exceptiongroup==1.2.2
flake8==7.2.0
fqdn==1.5.1
greenlet==3.1.1
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
isoduration==20.11.0
Jinja2==3.1.6
jsonpointer==3.0.0
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
jupyter-events==0.12.0
jupyterhub==5.2.1
Mako==1.3.9
MarkupSafe==3.0.2
mccabe==0.7.0
-e git+https://github.com/jupyterhub/oauthenticator.git@ac730b276184640227c2ca999bfccfe7472fca85#egg=oauthenticator
oauthlib==3.2.2
packaging==24.2
pamela==1.2.0
pluggy==1.5.0
prometheus_client==0.21.1
pycodestyle==2.13.0
pycparser==2.22
pydantic==2.11.1
pydantic_core==2.33.0
pyflakes==3.3.2
PyJWT==2.10.1
pytest==8.3.5
pytest-cov==6.0.0
pytest-tornado==0.8.1
python-dateutil==2.9.0.post0
python-json-logger==3.3.0
PyYAML==6.0.2
referencing==0.36.2
requests==2.32.3
requests-mock==1.12.1
rfc3339-validator==0.1.4
rfc3986-validator==0.1.1
rpds-py==0.24.0
six==1.17.0
SQLAlchemy==2.0.40
tomli==2.2.1
tornado==6.4.2
traitlets==5.14.3
types-python-dateutil==2.9.0.20241206
typing-inspection==0.4.0
typing_extensions==4.13.0
uri-template==1.3.0
urllib3==2.3.0
webcolors==24.11.1
zipp==3.21.0
| name: oauthenticator
channels:
- defaults
- https://repo.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:
- alembic==1.15.2
- annotated-types==0.7.0
- arrow==1.3.0
- async-generator==1.10
- attrs==25.3.0
- certifi==2025.1.31
- certipy==0.2.2
- cffi==1.17.1
- charset-normalizer==3.4.1
- codecov==2.1.13
- coverage==7.8.0
- cryptography==44.0.2
- exceptiongroup==1.2.2
- flake8==7.2.0
- fqdn==1.5.1
- greenlet==3.1.1
- idna==3.10
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- isoduration==20.11.0
- jinja2==3.1.6
- jsonpointer==3.0.0
- jsonschema==4.23.0
- jsonschema-specifications==2024.10.1
- jupyter-events==0.12.0
- jupyterhub==5.2.1
- mako==1.3.9
- markupsafe==3.0.2
- mccabe==0.7.0
- oauthlib==3.2.2
- packaging==24.2
- pamela==1.2.0
- pluggy==1.5.0
- prometheus-client==0.21.1
- pycodestyle==2.13.0
- pycparser==2.22
- pydantic==2.11.1
- pydantic-core==2.33.0
- pyflakes==3.3.2
- pyjwt==2.10.1
- pytest==8.3.5
- pytest-cov==6.0.0
- pytest-tornado==0.8.1
- python-dateutil==2.9.0.post0
- python-json-logger==3.3.0
- pyyaml==6.0.2
- referencing==0.36.2
- requests==2.32.3
- requests-mock==1.12.1
- rfc3339-validator==0.1.4
- rfc3986-validator==0.1.1
- rpds-py==0.24.0
- six==1.17.0
- sqlalchemy==2.0.40
- tomli==2.2.1
- tornado==6.4.2
- traitlets==5.14.3
- types-python-dateutil==2.9.0.20241206
- typing-extensions==4.13.0
- typing-inspection==0.4.0
- uri-template==1.3.0
- urllib3==2.3.0
- webcolors==24.11.1
- zipp==3.21.0
prefix: /opt/conda/envs/oauthenticator
| [
"oauthenticator/tests/test_gitlab.py::test_gitlab",
"oauthenticator/tests/test_gitlab.py::test_group_whitelist"
]
| []
| []
| []
| BSD 3-Clause "New" or "Revised" License | 1,637 | [
"oauthenticator/gitlab.py"
]
| [
"oauthenticator/gitlab.py"
]
|
|
mapbox__mapbox-sdk-py-208 | 2a5971f9b4f90ae23bb52ff5f273ce7061b23461 | 2017-08-30 22:44:06 | d29f0c4bf475f3a126b61e89bcd1336fec5a7675 | sgillies: 👋 @amishas157 @perrygeo can you review this for me? | diff --git a/.travis.yml b/.travis.yml
index b8e7592..ff98592 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -6,7 +6,7 @@ python:
- '3.4'
- '3.5'
- '3.6'
- - pypy
+ - pypy-5.3.1
cache:
directories:
- $HOME/.pip-cache/
diff --git a/CHANGES b/CHANGES
index ee8f2dd..9a18eff 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,8 @@
+Next (YYYY-MM-DD)
+-----------------
+- Add api_name and api_version class attributes (#207).
+
+
0.14.0 (2017-07-10)
-------------------
- Permit images of size 1 and 1280 (#196)
diff --git a/README.rst b/README.rst
index d5e4771..fc69108 100644
--- a/README.rst
+++ b/README.rst
@@ -15,56 +15,57 @@ The Mapbox Python SDK is a low-level client API, not a Resource API such as the
Services
========
-- **Analytics** `examples <./docs/analytics.md>`__, `website <https://www.mapbox.com/api-documentation/#analytics>`__
+- **Analytics V1** `examples <./docs/analytics.md>`__, `website <https://www.mapbox.com/api-documentation/#analytics>`__
- API usage for services by resource.
- available for premium and enterprise plans.
-- **Directions** `examples <./docs/directions.md#directions>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#directions>`__
+- **Directions V4** `examples <./docs/directions.md#directions>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#directions>`__
- Profiles for driving, walking, and cycling
- GeoJSON & Polyline formatting
- Instructions as text or HTML
-- **Distance** `examples <./docs/distance.md#distance>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#directions-matrix>`__
+- **Distance V1** `examples <./docs/distance.md#distance>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#directions-matrix>`__
- Travel-time tables between up to 100 points
- Profiles for driving, walking and cycling
-- **Geocoding** `examples <./docs/geocoding.md#geocoding>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#geocoding>`__
+- **Geocoding V5** `examples <./docs/geocoding.md#geocoding>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#geocoding>`__
- Forward (place names ⇢ longitude, latitude)
- Reverse (longitude, latitude ⇢ place names)
-- **Map Matching** `examples <./docs/mapmatching.md#map-matching>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#map-matching>`__
+- **Map Matching V4** `examples <./docs/mapmatching.md#map-matching>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#map-matching>`__
- Snap GPS traces to OpenStreetMap data
-- **Static Maps** `examples <./docs/static.md#static-maps>`__, `website <https://www.mapbox.com/api-documentation/pages/static_classic.html>`__
+- **Static Maps V4** `examples <./docs/static.md#static-maps>`__, `website <https://www.mapbox.com/api-documentation/pages/static_classic.html>`__
- Generate standalone images from existing Mapbox *mapids* (tilesets)
- Render with GeoJSON overlays
-- **Static Styles** `examples <./docs/static.md#static-maps>`__, `website <https://www.mapbox.com/api-documentation/#static>`__
+- **Static Styles V1** `examples <./docs/static.md#static-maps>`__, `website <https://www.mapbox.com/api-documentation/#static>`__
- Generate standalone images from existing Mapbox *styles*
- Render with GeoJSON overlays
- Adjust pitch and bearing, decimal zoom levels
-- **Surface** `examples <./docs/surface.md#surface>`__, `website <https://www.mapbox.com/developers/api/surface/>`__
+- **Surface V4** `examples <./docs/surface.md#surface>`__, `website <https://www.mapbox.com/developers/api/surface/>`__
- Interpolates values along lines. Useful for elevation traces.
-- **Uploads** `examples <./docs/uploads.md#uploads>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#uploads>`__
+- **Uploads V1** `examples <./docs/uploads.md#uploads>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#uploads>`__
- Upload data to be processed and hosted by Mapbox.
-- **Datasets** `examples <./docs/datasets.md#datasets>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#datasets>`__
+- **Datasets V1** `examples <./docs/datasets.md#datasets>`__, `website <https://www.mapbox.com/api-documentation/?language=Python#datasets>`__
- Manage editable collections of GeoJSON features
- Persistent storage for custom geographic data
-Other services coming soon.
+Please note that there may be some lag between the release of new Mapbox web
+services and releases of this package.
Installation
============
diff --git a/mapbox/services/analytics.py b/mapbox/services/analytics.py
index dafb3c5..5428b70 100644
--- a/mapbox/services/analytics.py
+++ b/mapbox/services/analytics.py
@@ -5,15 +5,14 @@ from uritemplate import URITemplate
from mapbox.services.base import Service
from mapbox import errors
+
class Analytics(Service):
- """Access to Analytics API"""
+ """Access to Analytics API V1"""
+ api_name = 'analytics'
+ api_version = 'v1'
valid_resource_types = ['tokens', 'styles', 'accounts', 'tilesets']
- @property
- def baseuri(self):
- return 'https://{0}/analytics/v1'.format(self.host)
-
def _validate_resource_type(self, resource_type):
if resource_type not in self.valid_resource_types:
raise errors.InvalidResourceTypeError(
diff --git a/mapbox/services/base.py b/mapbox/services/base.py
index 9bae0a4..c8cae87 100644
--- a/mapbox/services/base.py
+++ b/mapbox/services/base.py
@@ -42,6 +42,8 @@ class Service(object):
"""Service base class."""
default_host = 'api.mapbox.com'
+ api_name = 'hors service'
+ api_version = 'v0'
def __init__(self, access_token=None, host=None, cache=None):
"""Constructs a Service object.
@@ -55,6 +57,11 @@ class Service(object):
if cache:
self.session = CacheControl(self.session, cache=cache)
+ @property
+ def baseuri(self):
+ return 'https://{0}/{1}/{2}'.format(
+ self.host, self.api_name, self.api_version)
+
@property
def username(self):
"""Get username from access token.
diff --git a/mapbox/services/datasets.py b/mapbox/services/datasets.py
index 921897b..064f27e 100644
--- a/mapbox/services/datasets.py
+++ b/mapbox/services/datasets.py
@@ -8,11 +8,10 @@ from mapbox.services.base import Service
class Datasets(Service):
- """Access to the Datasets API."""
+ """Access to the Datasets API V1"""
- @property
- def baseuri(self):
- return 'https://{0}/datasets/v1'.format(self.host)
+ api_name = 'datasets'
+ api_version = 'v1'
def _attribs(self, name=None, description=None):
"""Form an attributes dictionary from keyword args."""
diff --git a/mapbox/services/directions.py b/mapbox/services/directions.py
index d6f6af3..a782c33 100644
--- a/mapbox/services/directions.py
+++ b/mapbox/services/directions.py
@@ -6,7 +6,10 @@ from mapbox import errors
class Directions(Service):
- """Access to the Directions API."""
+ """Access to the Directions API V4"""
+
+ api_name = 'directions'
+ api_version = 'v4'
valid_profiles = ['mapbox.driving',
'mapbox.cycling',
@@ -16,7 +19,8 @@ class Directions(Service):
@property
def baseuri(self):
- return 'https://{0}/v4/directions'.format(self.host)
+ return 'https://{0}/{2}/{1}'.format(
+ self.host, self.api_name, self.api_version)
def _validate_profile(self, profile):
if profile not in self.valid_profiles:
diff --git a/mapbox/services/distance.py b/mapbox/services/distance.py
index be27a34..9362532 100644
--- a/mapbox/services/distance.py
+++ b/mapbox/services/distance.py
@@ -6,13 +6,17 @@ from mapbox.services.base import Service
class Distance(Service):
- """Access to the Distance API."""
+ """Access to the Distance API V1"""
+
+ api_name = 'distances'
+ api_version = 'v1'
valid_profiles = ['driving', 'cycling', 'walking']
@property
def baseuri(self):
- return 'https://{0}/distances/v1/mapbox'.format(self.host)
+ return 'https://{0}/{1}/{2}/mapbox'.format(
+ self.host, self.api_name, self.api_version)
def _validate_profile(self, profile):
if profile not in self.valid_profiles:
diff --git a/mapbox/services/geocoding.py b/mapbox/services/geocoding.py
index e22b91e..bad7dd3 100644
--- a/mapbox/services/geocoding.py
+++ b/mapbox/services/geocoding.py
@@ -7,14 +7,12 @@ from mapbox.services.base import Service
class Geocoder(Service):
- """Access to the Geocoding API."""
+ """Access to the Geocoding API V5"""
+ api_name = 'geocoding'
+ api_version = 'v5'
precision = {'reverse': 5, 'proximity': 3}
- @property
- def baseuri(self):
- return 'https://{0}/geocoding/v5'.format(self.host)
-
def __init__(self, name='mapbox.places', access_token=None, cache=None,
host=None):
"""Constructs a Geocoding Service object.
diff --git a/mapbox/services/mapmatching.py b/mapbox/services/mapmatching.py
index cec6acc..66f6c8f 100644
--- a/mapbox/services/mapmatching.py
+++ b/mapbox/services/mapmatching.py
@@ -7,14 +7,12 @@ from mapbox.services.base import Service
class MapMatcher(Service):
- """Access to the Map Matching API."""
+ """Access to the Map Matching API V4"""
+ api_name = 'matching'
+ api_version = 'v4'
valid_profiles = ['mapbox.driving', 'mapbox.cycling', 'mapbox.walking']
- @property
- def baseuri(self):
- return 'https://{0}/matching/v4'.format(self.host)
-
def _validate_profile(self, profile):
if profile not in self.valid_profiles:
raise errors.InvalidProfileError(
diff --git a/mapbox/services/static.py b/mapbox/services/static.py
index a532ac4..4aadee7 100644
--- a/mapbox/services/static.py
+++ b/mapbox/services/static.py
@@ -8,11 +8,14 @@ from mapbox.utils import normalize_geojson_featurecollection
class Static(Service):
- """Access to the Static Map API."""
+ """Access to the Static Map API V4"""
+
+ api_name = None
+ api_version = 'v4'
@property
def baseuri(self):
- return 'https://{0}/v4'.format(self.host)
+ return 'https://{0}/{1}'.format(self.host, self.api_version)
def _validate_lat(self, val):
if val < -85.0511 or val > 85.0511:
diff --git a/mapbox/services/static_style.py b/mapbox/services/static_style.py
index b0cef3a..750f0fa 100644
--- a/mapbox/services/static_style.py
+++ b/mapbox/services/static_style.py
@@ -50,11 +50,10 @@ def validate_bearing(val):
class StaticStyle(Service):
- """Access to the Static Map API."""
+ """Access to the Static Map API V1"""
- @property
- def baseuri(self):
- return 'https://{0}/styles/v1'.format(self.host)
+ api_name = 'styles'
+ api_version = 'v1'
def tile(self, username, style_id, z, x, y, tile_size=512, retina=False):
"/styles/v1/{username}/{style_id}/tiles/{tileSize}/{z}/{x}/{y}{@2x}"
diff --git a/mapbox/services/surface.py b/mapbox/services/surface.py
index 8c69073..2dd3dcc 100644
--- a/mapbox/services/surface.py
+++ b/mapbox/services/surface.py
@@ -5,11 +5,15 @@ from mapbox.services.base import Service
class Surface(Service):
- """Access to the Surface API."""
+ """Access to the Surface API V4"""
+
+ api_name = 'surface'
+ api_version = 'v4'
@property
def baseuri(self):
- return 'https://{0}/v4/surface'.format(self.host)
+ return 'https://{0}/{2}/{1}'.format(
+ self.host, self.api_name, self.api_version)
def surface(self,
features,
diff --git a/mapbox/services/uploads.py b/mapbox/services/uploads.py
index 8c4a34d..94dcd75 100644
--- a/mapbox/services/uploads.py
+++ b/mapbox/services/uploads.py
@@ -10,7 +10,7 @@ from mapbox.services.base import Service
class Uploader(Service):
- """Access to the Upload API.
+ """Access to the Upload API V1
Example usage:
@@ -29,9 +29,8 @@ class Uploader(Service):
assert job not in u.list().json()
"""
- @property
- def baseuri(self):
- return 'https://{0}/uploads/v1'.format(self.host)
+ api_name = 'uploads'
+ api_version = 'v1'
def _get_credentials(self):
"""Gets temporary S3 credentials to stage user-uploaded files
diff --git a/tox.ini b/tox.ini
index bdce644..bceb578 100644
--- a/tox.ini
+++ b/tox.ini
@@ -7,4 +7,4 @@ deps =
pytest-cov
responses
commands =
- py.test --cov {envsitepackagesdir}/mapbox --cov-report term-missing
+ py.test --cov mapbox --cov-report term-missing
| Add api_name and api_version Service class attributes
These can be used in constructing the the base URI and in debugging. | mapbox/mapbox-sdk-py | diff --git a/tests/test_analytics.py b/tests/test_analytics.py
index 0940e41..1ddd84e 100644
--- a/tests/test_analytics.py
+++ b/tests/test_analytics.py
@@ -5,25 +5,37 @@ import responses
import mapbox
from mapbox import errors
+
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = mapbox.Analytics()
+ assert serv.api_name == 'analytics'
+ assert serv.api_version == 'v1'
+
+
def test_resource_type_invalid():
"""'random' is not a valid resource type."""
with pytest.raises(errors.InvalidResourceTypeError):
mapbox.Analytics(access_token='pk.test')._validate_resource_type('random')
+
@pytest.mark.parametrize('resource_type', ['tokens', 'styles', 'accounts', 'tilesets'])
def test_profile_valid(resource_type):
"""Resource types are valid."""
assert resource_type == mapbox.Analytics(
access_token='pk.test')._validate_resource_type(resource_type)
+
@pytest.mark.parametrize(
- 'start, end',[('2016-03-22T00:00:00.000Z', None),
- ('2016-03-22T00:00:00.000Z', '2016-03-20T00:00:00.000Z'),
- ('2016-03-22T00:00:00.000Z', '2017-04-20T00:00:00.000Z')])
+ 'start, end', [
+ ('2016-03-22T00:00:00.000Z', None),
+ ('2016-03-22T00:00:00.000Z', '2016-03-20T00:00:00.000Z'),
+ ('2016-03-22T00:00:00.000Z', '2017-04-20T00:00:00.000Z')])
def test_period_invalid(start, end):
with pytest.raises(errors.InvalidPeriodError):
mapbox.Analytics(access_token='pk.test')._validate_period(start, end)
+
@pytest.mark.parametrize(
'start, end', [('2016-03-22T00:00:00.000Z', '2016-03-24T00:00:00.000Z'),
(None, None)])
@@ -31,16 +43,19 @@ def test_period_valid(start, end):
period = start, end
assert period == mapbox.Analytics(access_token='pk.test')._validate_period(start, end)
+
def test_username_invalid():
"""Username is requird."""
with pytest.raises(errors.InvalidUsernameError):
mapbox.Analytics(access_token='pk.test')._validate_username(None)
+
def test_username_valid():
"""Providing valid username"""
user = 'abc'
assert user == mapbox.Analytics(access_token='pk.test')._validate_username(user)
+
def test_id_invalid():
"""id is required when resource type is other than accounts"""
resource_type = 'tokens'
@@ -48,13 +63,14 @@ def test_id_invalid():
with pytest.raises(errors.InvalidId):
mapbox.Analytics(access_token='pk.test')._validate_id(resource_type, id)
+
@pytest.mark.parametrize(
- 'resource_type, id', [('accounts', None),
- ('tokens', 'abc')])
+ 'resource_type, id', [('accounts', None), ('tokens', 'abc')])
def test_id_valid(resource_type, id):
"""id is not required when resource type is accounts"""
assert id == mapbox.Analytics(access_token='pk.test')._validate_id(resource_type, id)
+
@responses.activate
def test_analytics():
responses.add(
diff --git a/tests/test_base.py b/tests/test_base.py
index 2025043..da442ad 100644
--- a/tests/test_base.py
+++ b/tests/test_base.py
@@ -10,6 +10,14 @@ from mapbox.errors import TokenError
from mapbox.services import base
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = base.Service()
+ assert serv.api_name == 'hors service'
+ assert serv.api_version == 'v0'
+ assert serv.baseuri == 'https://api.mapbox.com/hors service/v0'
+
+
def test_service_session():
"""Get a session using a token"""
session = base.Session('pk.test')
diff --git a/tests/test_datasets.py b/tests/test_datasets.py
index b35f517..53a4e0c 100644
--- a/tests/test_datasets.py
+++ b/tests/test_datasets.py
@@ -11,6 +11,13 @@ access_token = 'pk.{0}.test'.format(
base64.b64encode(b'{"u":"testuser"}').decode('utf-8'))
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = Datasets()
+ assert serv.api_name == 'datasets'
+ assert serv.api_version == 'v1'
+
+
def test_datasets_service_properties():
"""Get expected username and baseuri."""
datasets = Datasets(access_token=access_token)
@@ -240,7 +247,7 @@ def test_update_feature():
callback=request_callback)
response = Datasets(access_token=access_token).update_feature(
- 'test', '1', {'type': 'Feature'})
+ 'test', '1', {'type': 'Feature'})
assert response.status_code == 200
diff --git a/tests/test_directions.py b/tests/test_directions.py
index f4160b1..2628d26 100644
--- a/tests/test_directions.py
+++ b/tests/test_directions.py
@@ -21,6 +21,13 @@ points = [{
36.92217534275667]}}]
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = mapbox.Directions()
+ assert serv.api_name == 'directions'
+ assert serv.api_version == 'v4'
+
+
@responses.activate
@pytest.mark.parametrize("cache", [None, DictCache()])
def test_directions(cache):
@@ -41,7 +48,6 @@ def test_directions(cache):
@responses.activate
-
def test_directions_geojson():
with open('tests/moors.json') as fh:
body = fh.read()
diff --git a/tests/test_distances.py b/tests/test_distances.py
index 7abacd7..4c4be8b 100644
--- a/tests/test_distances.py
+++ b/tests/test_distances.py
@@ -29,6 +29,13 @@ points = [{
36.922175]}}]
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = mapbox.Distance()
+ assert serv.api_name == 'distances'
+ assert serv.api_version == 'v1'
+
+
def test_profile_invalid():
"""'jetpack' is not a valid profile."""
with pytest.raises(ValueError):
@@ -74,21 +81,3 @@ def test_distances_matrix():
# 3x3 list
assert len(matrix) == 3
assert len(matrix[0]) == 3
-
-
[email protected]
-def test_distances_matrix():
-
- responses.add(
- responses.POST,
- 'https://api.mapbox.com/distances/v1/mapbox/driving?access_token=pk.test',
- match_querystring=True,
- body='{"durations":[[0,4977,5951],[4963,0,9349],[5881,9317,0]]}',
- status=200,
- content_type='application/json')
-
- res = mapbox.Distance(access_token='pk.test').distances(points)
- matrix = res.json()['durations']
- # 3x3 list
- assert len(matrix) == 3
- assert len(matrix[0]) == 3
diff --git a/tests/test_geocoder.py b/tests/test_geocoder.py
index 46efa78..7f17b54 100644
--- a/tests/test_geocoder.py
+++ b/tests/test_geocoder.py
@@ -8,6 +8,13 @@ import pytest
import mapbox
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = mapbox.Geocoder()
+ assert serv.api_name == 'geocoding'
+ assert serv.api_version == 'v5'
+
+
def test_geocoder_default_name():
"""Default name is set"""
geocoder = mapbox.Geocoder()
@@ -121,7 +128,7 @@ def test_validate_country_codes_err():
def test_validate_country():
assert mapbox.Geocoder()._validate_country_codes(
- ('us', 'br')) == {'country': 'us,br'}
+ ('us', 'br')) == {'country': 'us,br'}
def test_validate_place_types_err():
@@ -229,7 +236,7 @@ def test_geocoder_forward_bbox():
response = mapbox.Geocoder(
access_token='pk.test').forward(
- 'washington', bbox=(-78.3284,38.6039,-78.0428,38.7841))
+ 'washington', bbox=(-78.3284, 38.6039, -78.0428, 38.7841))
assert response.status_code == 200
assert response.json()['query'] == ["washington"]
diff --git a/tests/test_mapmatching.py b/tests/test_mapmatching.py
index 0791a88..53743bd 100644
--- a/tests/test_mapmatching.py
+++ b/tests/test_mapmatching.py
@@ -24,6 +24,13 @@ def line_feature():
[13.420631289482117, 52.50294888790448]]}}
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = mapbox.MapMatcher()
+ assert serv.api_name == 'matching'
+ assert serv.api_version == 'v4'
+
+
@responses.activate
def test_matching(line_feature):
diff --git a/tests/test_staticmaps.py b/tests/test_staticmaps.py
index cb325bf..6f1c62d 100644
--- a/tests/test_staticmaps.py
+++ b/tests/test_staticmaps.py
@@ -18,6 +18,13 @@ import responses
import mapbox
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = mapbox.Static()
+ assert serv.api_name is None
+ assert serv.api_version == 'v4'
+
+
@pytest.fixture
def points():
points = [
diff --git a/tests/test_staticstyle.py b/tests/test_staticstyle.py
index 6cf9941..33ca666 100644
--- a/tests/test_staticstyle.py
+++ b/tests/test_staticstyle.py
@@ -33,6 +33,13 @@ def points():
coordinates=[-61.6, 12.0]))]
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = mapbox.StaticStyle()
+ assert serv.api_name == 'styles'
+ assert serv.api_version == 'v1'
+
+
@responses.activate
def test_staticmap_lonlatzpitchbearing():
diff --git a/tests/test_surface.py b/tests/test_surface.py
index 562f9c7..c85b656 100644
--- a/tests/test_surface.py
+++ b/tests/test_surface.py
@@ -20,6 +20,13 @@ points = [{
"coordinates": [-112.083965, 36.053845]}}]
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = mapbox.Surface()
+ assert serv.api_name == 'surface'
+ assert serv.api_version == 'v4'
+
+
@responses.activate
def test_surface():
body = """{"results":[{"id":0,"latlng":{"lat":36.05322,"lng":-112.084004},"ele":2186.361304424316},{"id":1,"latlng":{"lat":36.053573,"lng":-112.083914},"ele":2187.6233827411997},{"id":2,"latlng":{"lat":36.053845,"lng":-112.083965},"ele":2163.921475128245}],"attribution":"<a href='https://www.mapbox.com/about/maps/' target='_blank'>&copy; Mapbox</a>"}"""
diff --git a/tests/test_upload.py b/tests/test_upload.py
index 1afcfc3..9b2ec99 100644
--- a/tests/test_upload.py
+++ b/tests/test_upload.py
@@ -25,6 +25,13 @@ upload_response_body = """
"name": null}}""".format(username=username)
+def test_class_attrs():
+ """Get expected class attr values"""
+ serv = mapbox.Uploader()
+ assert serv.api_name == 'uploads'
+ assert serv.api_version == 'v1'
+
+
@responses.activate
def test_get_credentials():
query_body = """
| {
"commit_name": "merge_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": 3,
"test_score": 0
},
"num_modified_files": 15
} | 0.14 | {
"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"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | attrs==22.2.0
boto3==1.23.10
botocore==1.26.10
CacheControl==0.12.14
certifi==2021.5.30
charset-normalizer==2.0.12
click==8.0.4
click-plugins==1.1.1
cligj==0.7.2
coverage==6.2
coveralls==3.3.1
distlib==0.3.9
docopt==0.6.2
filelock==3.4.1
idna==3.10
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
iso3166==2.1.1
jmespath==0.10.0
-e git+https://github.com/mapbox/mapbox-sdk-py.git@2a5971f9b4f90ae23bb52ff5f273ce7061b23461#egg=mapbox
msgpack==1.0.5
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
polyline==1.4.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
python-dateutil==2.9.0.post0
requests==2.27.1
responses==0.17.0
s3transfer==0.5.2
six==1.17.0
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
uritemplate==4.1.1
urllib3==1.26.20
virtualenv==20.17.1
zipp==3.6.0
| name: mapbox-sdk-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==22.2.0
- boto3==1.23.10
- botocore==1.26.10
- cachecontrol==0.12.14
- charset-normalizer==2.0.12
- click==8.0.4
- click-plugins==1.1.1
- cligj==0.7.2
- coverage==6.2
- coveralls==3.3.1
- distlib==0.3.9
- docopt==0.6.2
- filelock==3.4.1
- idna==3.10
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- iso3166==2.1.1
- jmespath==0.10.0
- msgpack==1.0.5
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- polyline==1.4.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- python-dateutil==2.9.0.post0
- requests==2.27.1
- responses==0.17.0
- s3transfer==0.5.2
- six==1.17.0
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- uritemplate==4.1.1
- urllib3==1.26.20
- virtualenv==20.17.1
- zipp==3.6.0
prefix: /opt/conda/envs/mapbox-sdk-py
| [
"tests/test_analytics.py::test_class_attrs",
"tests/test_base.py::test_class_attrs",
"tests/test_datasets.py::test_class_attrs",
"tests/test_directions.py::test_class_attrs",
"tests/test_distances.py::test_class_attrs",
"tests/test_geocoder.py::test_class_attrs",
"tests/test_mapmatching.py::test_class_attrs",
"tests/test_staticmaps.py::test_class_attrs",
"tests/test_staticstyle.py::test_class_attrs",
"tests/test_surface.py::test_class_attrs",
"tests/test_upload.py::test_class_attrs"
]
| []
| [
"tests/test_analytics.py::test_resource_type_invalid",
"tests/test_analytics.py::test_profile_valid[tokens]",
"tests/test_analytics.py::test_profile_valid[styles]",
"tests/test_analytics.py::test_profile_valid[accounts]",
"tests/test_analytics.py::test_profile_valid[tilesets]",
"tests/test_analytics.py::test_period_invalid[2016-03-22T00:00:00.000Z-None]",
"tests/test_analytics.py::test_period_invalid[2016-03-22T00:00:00.000Z-2016-03-20T00:00:00.000Z]",
"tests/test_analytics.py::test_period_invalid[2016-03-22T00:00:00.000Z-2017-04-20T00:00:00.000Z]",
"tests/test_analytics.py::test_period_valid[2016-03-22T00:00:00.000Z-2016-03-24T00:00:00.000Z]",
"tests/test_analytics.py::test_period_valid[None-None]",
"tests/test_analytics.py::test_username_invalid",
"tests/test_analytics.py::test_username_valid",
"tests/test_analytics.py::test_id_invalid",
"tests/test_analytics.py::test_id_valid[accounts-None]",
"tests/test_analytics.py::test_id_valid[tokens-abc]",
"tests/test_analytics.py::test_analytics",
"tests/test_base.py::test_service_session",
"tests/test_base.py::test_service_session_env",
"tests/test_base.py::test_service_session_os_environ",
"tests/test_base.py::test_service_session_os_environ_caps",
"tests/test_base.py::test_service_session_os_environ_precedence",
"tests/test_base.py::test_user_agent",
"tests/test_base.py::test_custom_messages",
"tests/test_base.py::test_username",
"tests/test_base.py::test_default_host",
"tests/test_base.py::test_configured_host",
"tests/test_base.py::test_username_failures",
"tests/test_datasets.py::test_datasets_service_properties",
"tests/test_datasets.py::test_datasets_list",
"tests/test_datasets.py::test_datasets_create",
"tests/test_datasets.py::test_dataset_read",
"tests/test_datasets.py::test_dataset_update",
"tests/test_datasets.py::test_delete_dataset",
"tests/test_datasets.py::test_dataset_list_features",
"tests/test_datasets.py::test_dataset_list_features_reverse",
"tests/test_datasets.py::test_dataset_list_features_pagination",
"tests/test_datasets.py::test_read_feature",
"tests/test_datasets.py::test_update_feature",
"tests/test_datasets.py::test_delete_feature",
"tests/test_directions.py::test_directions[None]",
"tests/test_directions.py::test_directions[cache1]",
"tests/test_directions.py::test_directions_geojson",
"tests/test_directions.py::test_invalid_profile",
"tests/test_directions.py::test_direction_params",
"tests/test_directions.py::test_invalid_geom_encoding",
"tests/test_directions.py::test_invalid_instruction_format",
"tests/test_distances.py::test_profile_invalid",
"tests/test_distances.py::test_profile_valid[driving]",
"tests/test_distances.py::test_profile_valid[cycling]",
"tests/test_distances.py::test_profile_valid[walking]",
"tests/test_distances.py::test_distance",
"tests/test_distances.py::test_distances_matrix",
"tests/test_geocoder.py::test_geocoder_default_name",
"tests/test_geocoder.py::test_geocoder_name",
"tests/test_geocoder.py::test_geocoder_forward",
"tests/test_geocoder.py::test_geocoder_forward_geojson",
"tests/test_geocoder.py::test_geocoder_reverse",
"tests/test_geocoder.py::test_geocoder_reverse_geojson",
"tests/test_geocoder.py::test_geocoder_place_types",
"tests/test_geocoder.py::test_validate_country_codes_err",
"tests/test_geocoder.py::test_validate_country",
"tests/test_geocoder.py::test_validate_place_types_err",
"tests/test_geocoder.py::test_validate_place_types",
"tests/test_geocoder.py::test_geocoder_forward_types",
"tests/test_geocoder.py::test_geocoder_reverse_types",
"tests/test_geocoder.py::test_geocoder_forward_proximity",
"tests/test_geocoder.py::test_geocoder_proximity_rounding",
"tests/test_geocoder.py::test_geocoder_forward_bbox",
"tests/test_geocoder.py::test_geocoder_forward_limit",
"tests/test_geocoder.py::test_geocoder_reverse_limit",
"tests/test_geocoder.py::test_geocoder_reverse_limit_requires_onetype",
"tests/test_geocoder.py::test_geocoder_reverse_rounding",
"tests/test_geocoder.py::test_geocoder_unicode",
"tests/test_geocoder.py::test_geocoder_forward_country",
"tests/test_geocoder.py::test_geocoder_language",
"tests/test_mapmatching.py::test_matching",
"tests/test_mapmatching.py::test_matching_precision",
"tests/test_mapmatching.py::test_invalid_feature",
"tests/test_mapmatching.py::test_invalid_profile",
"tests/test_staticmaps.py::test_staticmap_lonlatz_only",
"tests/test_staticmaps.py::test_staticmap_lonlatz_features",
"tests/test_staticmaps.py::test_staticmap_auto_features",
"tests/test_staticmaps.py::test_staticmap_auto_nofeatures",
"tests/test_staticmaps.py::test_staticmap_featurestoolarge",
"tests/test_staticmaps.py::test_staticmap_imagesize",
"tests/test_staticmaps.py::test_latlon",
"tests/test_staticmaps.py::test_lon_invalid",
"tests/test_staticmaps.py::test_staticmap_retina",
"tests/test_staticstyle.py::test_staticmap_lonlatzpitchbearing",
"tests/test_staticstyle.py::test_staticmap_lonlatz_features",
"tests/test_staticstyle.py::test_staticmap_auto_features",
"tests/test_staticstyle.py::test_staticmap_auto_nofeatures",
"tests/test_staticstyle.py::test_staticmap_featurestoolarge",
"tests/test_staticstyle.py::test_staticmap_validate_bearing",
"tests/test_staticstyle.py::test_staticmap_validate_pitch",
"tests/test_staticstyle.py::test_staticmap_imagesize",
"tests/test_staticstyle.py::test_latlon",
"tests/test_staticstyle.py::test_lon_invalid",
"tests/test_staticstyle.py::test_staticmap_options",
"tests/test_staticstyle.py::test_staticmap_tile",
"tests/test_staticstyle.py::test_bad_tilesize",
"tests/test_staticstyle.py::test_staticmap_tile_retina",
"tests/test_staticstyle.py::test_staticmap_wmts",
"tests/test_staticstyle.py::test_staticmap_retina",
"tests/test_staticstyle.py::test_staticmap_twox_deprecated",
"tests/test_staticstyle.py::test_staticmap_twox_deprecated_error",
"tests/test_surface.py::test_surface",
"tests/test_surface.py::test_surface_geojson",
"tests/test_surface.py::test_surface_params",
"tests/test_upload.py::test_get_credentials",
"tests/test_upload.py::test_create",
"tests/test_upload.py::test_create_name",
"tests/test_upload.py::test_list",
"tests/test_upload.py::test_status",
"tests/test_upload.py::test_delete",
"tests/test_upload.py::test_stage",
"tests/test_upload.py::test_stage_filename",
"tests/test_upload.py::test_big_stage",
"tests/test_upload.py::test_upload",
"tests/test_upload.py::test_upload_error",
"tests/test_upload.py::test_upload_patch",
"tests/test_upload.py::test_upload_tileset_validation",
"tests/test_upload.py::test_upload_tileset_validation_username",
"tests/test_upload.py::test_create_tileset_validation"
]
| []
| MIT License | 1,638 | [
"README.rst",
"mapbox/services/base.py",
"mapbox/services/distance.py",
"mapbox/services/static_style.py",
"mapbox/services/directions.py",
"mapbox/services/surface.py",
"mapbox/services/analytics.py",
"mapbox/services/geocoding.py",
"CHANGES",
".travis.yml",
"mapbox/services/datasets.py",
"mapbox/services/mapmatching.py",
"mapbox/services/static.py",
"tox.ini",
"mapbox/services/uploads.py"
]
| [
"README.rst",
"mapbox/services/base.py",
"mapbox/services/distance.py",
"mapbox/services/static_style.py",
"mapbox/services/directions.py",
"mapbox/services/surface.py",
"mapbox/services/analytics.py",
"mapbox/services/geocoding.py",
"CHANGES",
".travis.yml",
"mapbox/services/datasets.py",
"mapbox/services/mapmatching.py",
"mapbox/services/static.py",
"tox.ini",
"mapbox/services/uploads.py"
]
|
ucfopen__canvasapi-65 | 9fd5a6a5dfcbbaae52b9d42752ffee163852b1f9 | 2017-08-31 15:15:45 | f2faa1835e104aae764a1fc7638c284d2888639f | diff --git a/canvasapi/requester.py b/canvasapi/requester.py
index 2388493..0c09669 100644
--- a/canvasapi/requester.py
+++ b/canvasapi/requester.py
@@ -1,4 +1,5 @@
from __future__ import absolute_import, division, print_function, unicode_literals
+from datetime import datetime
import requests
@@ -58,6 +59,20 @@ class Requester(object):
auth_header = {'Authorization': 'Bearer %s' % (self.access_token)}
headers.update(auth_header)
+ # Convert kwargs into list of 2-tuples and combine with _kwargs.
+ _kwargs = [] if _kwargs is None else _kwargs
+ for kw, arg, in kwargs.items():
+ _kwargs.append((kw, arg))
+
+ # Do any final argument processing before sending to request method.
+ for i, kwarg in enumerate(_kwargs):
+ kw, arg = kwarg
+
+ # Convert any datetime objects into ISO 8601 formatted strings.
+ if isinstance(arg, datetime):
+ _kwargs[i] = (kw, arg.isoformat())
+
+ # Determine the appropriate request method.
if method == 'GET':
req_method = self._get_request
elif method == 'POST':
@@ -67,13 +82,10 @@ class Requester(object):
elif method == 'PUT':
req_method = self._put_request
- # Convert kwargs into list of 2-tuples and combine with _kwargs.
- _kwargs = [] if _kwargs is None else _kwargs
- for kw, arg, in kwargs.items():
- _kwargs.append((kw, arg))
-
+ # Call the request method
response = req_method(full_url, headers, _kwargs)
+ # Raise for status codes
if response.status_code == 400:
raise BadRequest(response.json())
elif response.status_code == 401:
| Canvas.list_calendar_events should accept datetime instances
The `Canvas.list_calendar_events` method feeds its parameters down to a `GET /api/v1/calendar_events` request. [That request](https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.index) accepts `start_date` and `end_date` parameters, which “should be formatted as: yyyy-mm-dd or ISO 8601 YYYY-MM-DDTHH:MM:SSZ.” When using these parameters from Python, it would be convenient to provide values as Python `datetime` instances. For example, to list events between a course’ start and end dates:
```python
from datetime import datetime, timedelta
soon = datetime.today() + timedelta(weeks=2)
events = canvas.list_calendar_events(end_date=soon)
```
This seems like an obvious way to make the call, but iterating over the result fails using version 0.6.0 of `canvasapi`:
```
canvasapi.exceptions.BadRequest: {'end_date': 'Invalid date or invalid datetime for end_date'}'}
```
The call works if I convert the date into a suitably-formatted (ISO 8601) string:
```python
from datetime import datetime, timedelta
soon = datetime.today() + timedelta(weeks=2)
soon_iso = soon.isoformat()
events = canvas.list_calendar_events(end_date=soon_iso)
```
It would be very convenient if `Canvas.list_calendar_events` could accept parameters in the standard `datetime` a Python programmer would naturally expect to use, and would handle the ISO 8601 conversion internally.
Of course, dates and times appear in many other places in the Canvas API. I am reporting this against `Canvas.list_calendar_events` because that is where it is affecting me right now. But perhaps the best fix would be at a lower level within `canvasapi` so that *every* `datetime` instance is converted using `.isoformat` whenever given as the value of any request parameter. Is there a single, centralized place where that could be done? | ucfopen/canvasapi | diff --git a/tests/test_requester.py b/tests/test_requester.py
index 0fabb9f..d65f2d4 100644
--- a/tests/test_requester.py
+++ b/tests/test_requester.py
@@ -1,7 +1,10 @@
from __future__ import absolute_import, division, print_function, unicode_literals
+from datetime import datetime
import unittest
+import requests
import requests_mock
+from six.moves.urllib.parse import quote
from canvasapi import Canvas
from canvasapi.exceptions import (
@@ -26,12 +29,42 @@ class TestRequester(unittest.TestCase):
response = self.requester.request('GET', 'fake_get_request')
self.assertEqual(response.status_code, 200)
+ def test_request_get_datetime(self, m):
+ date = datetime.today()
+
+ def custom_matcher(request):
+ match_query = 'date={}'.format(quote(date.isoformat()).lower())
+ if request.query == match_query:
+ resp = requests.Response()
+ resp.status_code = 200
+ return resp
+
+ m.add_matcher(custom_matcher)
+
+ response = self.requester.request('GET', 'test', date=date)
+ self.assertEqual(response.status_code, 200)
+
def test_request_post(self, m):
register_uris({'requests': ['post']}, m)
response = self.requester.request('POST', 'fake_post_request')
self.assertEqual(response.status_code, 200)
+ def test_request_post_datetime(self, m):
+ date = datetime.today()
+
+ def custom_matcher(request):
+ match_text = 'date={}'.format(quote(date.isoformat()))
+ if request.text == match_text:
+ resp = requests.Response()
+ resp.status_code = 200
+ return resp
+
+ m.add_matcher(custom_matcher)
+
+ response = self.requester.request('POST', 'test', date=date)
+ self.assertEqual(response.status_code, 200)
+
def test_request_delete(self, m):
register_uris({'requests': ['delete']}, m)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 1
} | 0.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"coverage",
"flake8",
"pyflakes",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt",
"dev_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
-e git+https://github.com/ucfopen/canvasapi.git@9fd5a6a5dfcbbaae52b9d42752ffee163852b1f9#egg=canvasapi
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
docutils==0.18.1
flake8==5.0.4
idna==3.10
imagesize==1.4.1
importlib-metadata==4.2.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mccabe==0.7.0
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
requests-mock==1.12.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-rtd-theme==2.0.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: canvasapi
channels:
- defaults
- https://repo.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
- coverage==6.2
- docutils==0.18.1
- flake8==5.0.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mccabe==0.7.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- requests-mock==1.12.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-rtd-theme==2.0.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/canvasapi
| [
"tests/test_requester.py::TestRequester::test_request_get_datetime",
"tests/test_requester.py::TestRequester::test_request_post_datetime"
]
| []
| [
"tests/test_requester.py::TestRequester::test_request_400",
"tests/test_requester.py::TestRequester::test_request_401_InvalidAccessToken",
"tests/test_requester.py::TestRequester::test_request_401_Unauthorized",
"tests/test_requester.py::TestRequester::test_request_404",
"tests/test_requester.py::TestRequester::test_request_500",
"tests/test_requester.py::TestRequester::test_request_delete",
"tests/test_requester.py::TestRequester::test_request_get",
"tests/test_requester.py::TestRequester::test_request_post",
"tests/test_requester.py::TestRequester::test_request_put"
]
| []
| MIT License | 1,639 | [
"canvasapi/requester.py"
]
| [
"canvasapi/requester.py"
]
|
|
ros-infrastructure__catkin_pkg-191 | 6cc8d7998803ea8d2e70c5243a6b0dad9c8589dc | 2017-09-01 00:06:34 | 6cc8d7998803ea8d2e70c5243a6b0dad9c8589dc | scpeters: CI is green now, but I haven't tested it locally. I'm guessing that it won't ever produce `<depend>` tags in the output since I didn't adapt the [merge logic for run_depends](https://github.com/ros-infrastructure/catkin_pkg/blob/master/src/catkin_pkg/package.py#L108-L113) to the `depends` tag.
scpeters: I just squashed some of the embarrassing commits. It should be ready for review.
dirk-thomas: > CI is green now, but I haven't tested it locally.
> It should be ready for review.
Please go ahead and test the changes locally before requesting a review.
scpeters: Here's what it generates for the [beginner_tutorials package.xml](http://wiki.ros.org/ROS/Tutorials/catkin/CreatingPackage#Creating_a_catkin_Package) when I run it locally:
~~~
<?xml version="1.0"?>
<package format="2">
<name>beginner_tutorials</name>
<version>0.0.0</version>
<description>The beginner_tutorials package</description>
<!-- One maintainer tag required, multiple allowed, one person per tag -->
<!-- Example: -->
<!-- <maintainer email="[email protected]">Jane Doe</maintainer> -->
<maintainer email="[email protected]">scpeters</maintainer>
<!-- One license tag required, multiple allowed, one license per tag -->
<!-- Commonly used license strings: -->
<!-- BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
<license>TODO</license>
<!-- Url tags are optional, but multiple are allowed, one per tag -->
<!-- Optional attribute type can be: website, bugtracker, or repository -->
<!-- Example: -->
<!-- <url type="website">http://wiki.ros.org/beginner_tutorials</url> -->
<!-- Author tags are optional, multiple are allowed, one per tag -->
<!-- Authors do not have to be maintainers, but could be -->
<!-- Example: -->
<!-- <author email="[email protected]">Jane Doe</author> -->
<!-- The *depend tags are used to specify dependencies -->
<!-- Dependencies can be catkin packages or system dependencies -->
<!-- Examples: -->
<!-- Use build_depend for packages you need at compile time: -->
<!-- <build_depend>message_generation</build_depend> -->
<!-- Use build_export_depend for packages you need in order to build against this package: -->
<!-- <build_export_depend>message_generation</build_export_depend> -->
<!-- Use buildtool_depend for build tool packages: -->
<!-- <buildtool_depend>catkin</buildtool_depend> -->
<!-- Use doc_depend for packages you need only for building documentation: -->
<!-- <doc_depend>gtest</doc_depend> -->
<!-- Use exec_depend for packages you need at runtime: -->
<!-- <exec_depend>message_runtime</exec_depend> -->
<!-- Use test_depend for packages you need only for testing: -->
<!-- <test_depend>gtest</test_depend> -->
<!-- Use depend as a shortcut for packages that are both build and runtime dependencies -->
<!-- <depend>roscpp</depend> -->
<!-- Note that this is equivalent to the following: -->
<!-- <build_depend>roscpp</build_depend> -->
<!-- <build_export_depend>roscpp</build_export_depend> -->
<!-- <exec_depend>roscpp</exec_depend> -->
<buildtool_depend>catkin</buildtool_depend>
<build_depend>roscpp</build_depend>
<build_depend>rospy</build_depend>
<build_depend>std_msgs</build_depend>
<build_export_depend>roscpp</build_export_depend>
<build_export_depend>rospy</build_export_depend>
<build_export_depend>std_msgs</build_export_depend>
<exec_depend>roscpp</exec_depend>
<exec_depend>rospy</exec_depend>
<exec_depend>std_msgs</exec_depend>
<!-- The export tag contains other, unspecified, tags -->
<export>
<!-- Other tools can request additional information be placed here -->
</export>
</package>
~~~
It would be nicer if it grouped them into the `<depend>` tag.
scpeters: @dirk-thomas I have tested it locally.
dirk-thomas: > I have tested it locally.
That is great.
Currently I have to focus on ROS 2 related task so it might take a bit until I will have the time to review this. Sorry. | diff --git a/src/catkin_pkg/package_templates.py b/src/catkin_pkg/package_templates.py
index f5b405d..5dc0dde 100644
--- a/src/catkin_pkg/package_templates.py
+++ b/src/catkin_pkg/package_templates.py
@@ -92,8 +92,9 @@ class PackageTemplate(Package):
catkin_deps = list(catkin_deps or [])
catkin_deps.sort()
pkg_catkin_deps = []
+ depends = []
build_depends = []
- run_depends = []
+ exec_depends = []
buildtool_depends = [Dependency('catkin')]
for dep in catkin_deps:
if dep.lower() == 'catkin':
@@ -111,12 +112,11 @@ class PackageTemplate(Package):
if dep.lower() == 'message_runtime':
if not 'message_generation' in catkin_deps:
sys.stderr.write('WARNING: Packages with messages or services should depend on both message_generation and message_runtime\n')
- run_depends.append(Dependency('message_runtime'))
+ exec_depends.append(Dependency('message_runtime'))
continue
pkg_catkin_deps.append(Dependency(dep))
for dep in pkg_catkin_deps:
- build_depends.append(dep)
- run_depends.append(dep)
+ depends.append(dep)
if boost_comps:
if not system_deps:
system_deps = ['boost']
@@ -124,15 +124,17 @@ class PackageTemplate(Package):
system_deps.append('boost')
for dep in system_deps or []:
if not dep.lower().startswith('python-'):
- build_depends.append(Dependency(dep))
- run_depends.append(Dependency(dep))
+ depends.append(Dependency(dep))
+ else:
+ exec_depends.append(Dependency(dep))
package_temp = PackageTemplate(
name=package_name,
version=version or '0.0.0',
description=description or 'The %s package' % package_name,
buildtool_depends=buildtool_depends,
build_depends=build_depends,
- run_depends=run_depends,
+ depends=depends,
+ exec_depends=exec_depends,
catkin_deps=catkin_deps,
system_deps=system_deps,
boost_comps=boost_comps,
@@ -390,14 +392,15 @@ def create_package_xml(package_template, rosdistro, meta=False):
dependencies = []
dep_map = {
'build_depend': package_template.build_depends,
+ 'build_export_depend': package_template.build_export_depends,
'buildtool_depend': package_template.buildtool_depends,
- 'run_depend': package_template.run_depends,
+ 'exec_depend': package_template.exec_depends,
'test_depend': package_template.test_depends,
'conflict': package_template.conflicts,
'replace': package_template.replaces
}
- for dep_type in ['buildtool_depend', 'build_depend', 'run_depend',
- 'test_depend', 'conflict', 'replace']:
+ for dep_type in ['buildtool_depend', 'build_depend', 'build_export_depend',
+ 'exec_depend', 'test_depend', 'conflict', 'replace']:
for dep in sorted(dep_map[dep_type], key=lambda x: x.name):
if 'depend' in dep_type:
dep_tag = _create_depend_tag(
diff --git a/src/catkin_pkg/templates/CMakeLists.txt.in b/src/catkin_pkg/templates/CMakeLists.txt.in
index be37947..1e67b7c 100644
--- a/src/catkin_pkg/templates/CMakeLists.txt.in
+++ b/src/catkin_pkg/templates/CMakeLists.txt.in
@@ -94,7 +94,7 @@ find_package(catkin REQUIRED@components)
###################################
## The catkin_package macro generates cmake config files for your package
## Declare things to be passed to dependent projects
-## INCLUDE_DIRS: uncomment this if you package contains header files
+## INCLUDE_DIRS: uncomment this if your package contains header files
## LIBRARIES: libraries you create in this project that dependent projects also need
## CATKIN_DEPENDS: catkin_packages dependent projects also need
## DEPENDS: system dependencies of this project that dependent projects also need
diff --git a/src/catkin_pkg/templates/package.xml.in b/src/catkin_pkg/templates/package.xml.in
index bdf167a..5c7e0ba 100644
--- a/src/catkin_pkg/templates/package.xml.in
+++ b/src/catkin_pkg/templates/package.xml.in
@@ -1,5 +1,5 @@
<?xml version="1.0"?>
-<package>
+<package format="2">
<name>@name</name>
<version@version_abi>@version</version>
<description>@description</description>
@@ -26,17 +26,26 @@
<!-- <author email="jane.doe@@example.com">Jane Doe</author> -->
@authors
- <!-- The *_depend tags are used to specify dependencies -->
+ <!-- The *depend tags are used to specify dependencies -->
<!-- Dependencies can be catkin packages or system dependencies -->
<!-- Examples: -->
+ <!-- Use depend as a shortcut for packages that are both build and exec dependencies -->
+ <!-- <depend>roscpp</depend> -->
+ <!-- Note that this is equivalent to the following: -->
+ <!-- <build_depend>roscpp</build_depend> -->
+ <!-- <exec_depend>roscpp</exec_depend> -->
<!-- Use build_depend for packages you need at compile time: -->
<!-- <build_depend>message_generation</build_depend> -->
+ <!-- Use build_export_depend for packages you need in order to build against this package: -->
+ <!-- <build_export_depend>message_generation</build_export_depend> -->
<!-- Use buildtool_depend for build tool packages: -->
<!-- <buildtool_depend>catkin</buildtool_depend> -->
- <!-- Use run_depend for packages you need at runtime: -->
- <!-- <run_depend>message_runtime</run_depend> -->
+ <!-- Use exec_depend for packages you need at runtime: -->
+ <!-- <exec_depend>message_runtime</exec_depend> -->
<!-- Use test_depend for packages you need only for testing: -->
<!-- <test_depend>gtest</test_depend> -->
+ <!-- Use doc_depend for packages you need only for building documentation: -->
+ <!-- <doc_depend>doxygen</doc_depend> -->
@dependencies
<!-- The export tag contains other, unspecified, tags -->
| catkin_create_pkg: start using package.xml format 2 | ros-infrastructure/catkin_pkg | diff --git a/test/test_templates.py b/test/test_templates.py
index ef5f913..ed2a5b6 100644
--- a/test/test_templates.py
+++ b/test/test_templates.py
@@ -156,7 +156,7 @@ class TemplateTest(unittest.TestCase):
def test_parse_generated(self):
maint = self.get_maintainer()
pack = PackageTemplate(name='bar',
- package_format=1,
+ package_format=2,
version='0.0.0',
version_abi='pabi',
urls=[Url('foo')],
@@ -207,7 +207,7 @@ class TemplateTest(unittest.TestCase):
# test with multiple attributes filled
maint = self.get_maintainer()
pack = PackageTemplate(name='bar',
- package_format=1,
+ package_format=2,
version='0.0.0',
version_abi='pabi',
description='pdesc',
| {
"commit_name": "merge_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": 1,
"test_score": 1
},
"num_modified_files": 3
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-mock",
"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"
} | -e git+https://github.com/ros-infrastructure/catkin_pkg.git@6cc8d7998803ea8d2e70c5243a6b0dad9c8589dc#egg=catkin_pkg
docutils==0.21.2
exceptiongroup==1.2.2
iniconfig==2.1.0
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-mock==3.14.0
python-dateutil==2.9.0.post0
six==1.17.0
tomli==2.2.1
| name: catkin_pkg
channels:
- defaults
- https://repo.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
- docutils==0.21.2
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-mock==3.14.0
- python-dateutil==2.9.0.post0
- six==1.17.0
- tomli==2.2.1
prefix: /opt/conda/envs/catkin_pkg
| [
"test/test_templates.py::TemplateTest::test_parse_generated",
"test/test_templates.py::TemplateTest::test_parse_generated_multi"
]
| []
| [
"test/test_templates.py::TemplateTest::test_create_cmakelists",
"test/test_templates.py::TemplateTest::test_create_include_macro",
"test/test_templates.py::TemplateTest::test_create_package",
"test/test_templates.py::TemplateTest::test_create_package_template",
"test/test_templates.py::TemplateTest::test_create_package_xml",
"test/test_templates.py::TemplateTest::test_create_targetlib_args",
"test/test_templates.py::TemplateTest::test_safe_write_files"
]
| []
| BSD License | 1,640 | [
"src/catkin_pkg/package_templates.py",
"src/catkin_pkg/templates/package.xml.in",
"src/catkin_pkg/templates/CMakeLists.txt.in"
]
| [
"src/catkin_pkg/package_templates.py",
"src/catkin_pkg/templates/package.xml.in",
"src/catkin_pkg/templates/CMakeLists.txt.in"
]
|
aio-libs__yarl-106 | 6a091a171b0419dfa5ed67049d432d50d3301ce8 | 2017-09-01 11:48:08 | 6a091a171b0419dfa5ed67049d432d50d3301ce8 | codecov[bot]: # [Codecov](https://codecov.io/gh/aio-libs/yarl/pull/106?src=pr&el=h1) Report
> Merging [#106](https://codecov.io/gh/aio-libs/yarl/pull/106?src=pr&el=desc) into [master](https://codecov.io/gh/aio-libs/yarl/commit/6a091a171b0419dfa5ed67049d432d50d3301ce8?src=pr&el=desc) will **increase** coverage by `<.01%`.
> The diff coverage is `100%`.
[](https://codecov.io/gh/aio-libs/yarl/pull/106?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #106 +/- ##
==========================================
+ Coverage 99.63% 99.63% +<.01%
==========================================
Files 2 2
Lines 544 546 +2
Branches 139 140 +1
==========================================
+ Hits 542 544 +2
Partials 2 2
```
| [Impacted Files](https://codecov.io/gh/aio-libs/yarl/pull/106?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [yarl/\_\_init\_\_.py](https://codecov.io/gh/aio-libs/yarl/pull/106?src=pr&el=tree#diff-eWFybC9fX2luaXRfXy5weQ==) | `100% <100%> (ø)` | :arrow_up: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/aio-libs/yarl/pull/106?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/aio-libs/yarl/pull/106?src=pr&el=footer). Last update [6a091a1...1baf675](https://codecov.io/gh/aio-libs/yarl/pull/106?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
| diff --git a/CHANGES.rst b/CHANGES.rst
index 5b9a667..49b78a2 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -10,6 +10,8 @@ CHANGES
* Unsafe encoding for QS fixed. Encode `;` char in value param (#104)
+* Process passwords without user names (#95)
+
0.12.0 (2017-06-26)
-------------------
diff --git a/yarl/__init__.py b/yarl/__init__.py
index 41a3089..e1151c0 100644
--- a/yarl/__init__.py
+++ b/yarl/__init__.py
@@ -176,8 +176,11 @@ class URL:
netloc += ':{}'.format(val.port)
if val.username:
user = _quote(val.username)
- if val.password:
- user += ':' + _quote(val.password)
+ else:
+ user = ''
+ if val.password:
+ user += ':' + _quote(val.password)
+ if user:
netloc = user + '@' + netloc
path = _quote(val[2], safe='+@:', protected='/+', strict=strict)
@@ -380,7 +383,10 @@ class URL:
"""
# not .username
- return self._val.username
+ ret = self._val.username
+ if not ret:
+ return None
+ return ret
@cached_property
def user(self):
@@ -590,7 +596,7 @@ class URL:
ret = ret + ':' + str(port)
if password:
if not user:
- raise ValueError("Non-empty password requires non-empty user")
+ user = ''
user = user + ':' + password
if user:
ret = user + '@' + ret
| Passwords without users
Currently, yarl refuses to set an password if a user isn't set. That's a bit unfortunate because that’s exactly what you need if you’re building redis URLs: https://redis-py.readthedocs.io/en/latest/#redis.StrictRedis.from_url | aio-libs/yarl | diff --git a/tests/test_url.py b/tests/test_url.py
index b5d365e..d2582ff 100644
--- a/tests/test_url.py
+++ b/tests/test_url.py
@@ -77,6 +77,11 @@ def test_raw_user_non_ascii():
assert '%D0%B2%D0%B0%D1%81%D1%8F' == url.raw_user
+def test_no_user():
+ url = URL('http://example.com')
+ assert url.user is None
+
+
def test_user_non_ascii():
url = URL('http://вася@example.com')
assert 'вася' == url.user
@@ -97,6 +102,11 @@ def test_password_non_ascii():
assert 'пароль' == url.password
+def test_password_without_user():
+ url = URL('http://:[email protected]')
+ assert 'password' == url.password
+
+
def test_raw_host():
url = URL('http://example.com')
assert "example.com" == url.raw_host
diff --git a/tests/test_url_update_netloc.py b/tests/test_url_update_netloc.py
index 9790dd4..46bdab0 100644
--- a/tests/test_url_update_netloc.py
+++ b/tests/test_url_update_netloc.py
@@ -90,8 +90,10 @@ def test_with_password_invalid_type():
def test_with_password_and_empty_user():
url = URL('http://example.com')
- with pytest.raises(ValueError):
- assert str(url.with_password('pass'))
+ url2 = url.with_password('pass')
+ assert url2.password == 'pass'
+ assert url2.user is None
+ assert str(url2) == 'http://:[email protected]'
def test_from_str_with_host_ipv4():
| {
"commit_name": "merge_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": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 0.12 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov pytest-xdist",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements/dev.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
iniconfig==2.1.0
multidict==6.2.0
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cov==6.0.0
pytest-xdist==3.6.1
tomli==2.2.1
typing_extensions==4.13.0
-e git+https://github.com/aio-libs/yarl.git@6a091a171b0419dfa5ed67049d432d50d3301ce8#egg=yarl
| name: yarl
channels:
- defaults
- https://repo.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
- multidict==6.2.0
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cov==6.0.0
- pytest-xdist==3.6.1
- tomli==2.2.1
- typing-extensions==4.13.0
prefix: /opt/conda/envs/yarl
| [
"tests/test_url.py::test_password_without_user",
"tests/test_url_update_netloc.py::test_with_password_and_empty_user"
]
| []
| [
"tests/test_url.py::test_absolute_url_without_host",
"tests/test_url.py::test_url_is_not_str",
"tests/test_url.py::test_str",
"tests/test_url.py::test_repr",
"tests/test_url.py::test_origin",
"tests/test_url.py::test_origin_not_absolute_url",
"tests/test_url.py::test_origin_no_scheme",
"tests/test_url.py::test_drop_dots",
"tests/test_url.py::test_abs_cmp",
"tests/test_url.py::test_abs_hash",
"tests/test_url.py::test_scheme",
"tests/test_url.py::test_raw_user",
"tests/test_url.py::test_raw_user_non_ascii",
"tests/test_url.py::test_no_user",
"tests/test_url.py::test_user_non_ascii",
"tests/test_url.py::test_raw_password",
"tests/test_url.py::test_raw_password_non_ascii",
"tests/test_url.py::test_password_non_ascii",
"tests/test_url.py::test_raw_host",
"tests/test_url.py::test_raw_host_non_ascii",
"tests/test_url.py::test_host_non_ascii",
"tests/test_url.py::test_raw_host_when_port_is_specified",
"tests/test_url.py::test_raw_host_from_str_with_ipv4",
"tests/test_url.py::test_raw_host_from_str_with_ipv6",
"tests/test_url.py::test_explicit_port",
"tests/test_url.py::test_implicit_port",
"tests/test_url.py::test_port_for_relative_url",
"tests/test_url.py::test_port_for_unknown_scheme",
"tests/test_url.py::test_raw_path_string_empty",
"tests/test_url.py::test_raw_path",
"tests/test_url.py::test_raw_path_non_ascii",
"tests/test_url.py::test_path_non_ascii",
"tests/test_url.py::test_path_with_spaces",
"tests/test_url.py::test_raw_path_for_empty_url",
"tests/test_url.py::test_raw_path_for_colon_and_at",
"tests/test_url.py::test_raw_query_string",
"tests/test_url.py::test_raw_query_string_non_ascii",
"tests/test_url.py::test_query_string_non_ascii",
"tests/test_url.py::test_path_qs",
"tests/test_url.py::test_query_string_spaces",
"tests/test_url.py::test_raw_fragment_empty",
"tests/test_url.py::test_raw_fragment",
"tests/test_url.py::test_raw_fragment_non_ascii",
"tests/test_url.py::test_raw_fragment_safe",
"tests/test_url.py::test_fragment_non_ascii",
"tests/test_url.py::test_raw_parts_empty",
"tests/test_url.py::test_raw_parts",
"tests/test_url.py::test_raw_parts_without_path",
"tests/test_url.py::test_raw_path_parts_with_2F_in_path",
"tests/test_url.py::test_raw_path_parts_with_2f_in_path",
"tests/test_url.py::test_raw_parts_for_relative_path",
"tests/test_url.py::test_raw_parts_for_relative_path_starting_from_slash",
"tests/test_url.py::test_raw_parts_for_relative_double_path",
"tests/test_url.py::test_parts_for_empty_url",
"tests/test_url.py::test_raw_parts_non_ascii",
"tests/test_url.py::test_parts_non_ascii",
"tests/test_url.py::test_name_for_empty_url",
"tests/test_url.py::test_raw_name",
"tests/test_url.py::test_raw_name_root",
"tests/test_url.py::test_raw_name_root2",
"tests/test_url.py::test_raw_name_root3",
"tests/test_url.py::test_relative_raw_name",
"tests/test_url.py::test_relative_raw_name_starting_from_slash",
"tests/test_url.py::test_relative_raw_name_slash",
"tests/test_url.py::test_name_non_ascii",
"tests/test_url.py::test_plus_in_path",
"tests/test_url.py::test_parent_raw_path",
"tests/test_url.py::test_parent_raw_parts",
"tests/test_url.py::test_double_parent_raw_path",
"tests/test_url.py::test_empty_parent_raw_path",
"tests/test_url.py::test_empty_parent_raw_path2",
"tests/test_url.py::test_clear_fragment_on_getting_parent",
"tests/test_url.py::test_clear_fragment_on_getting_parent_toplevel",
"tests/test_url.py::test_clear_query_on_getting_parent",
"tests/test_url.py::test_clear_query_on_getting_parent_toplevel",
"tests/test_url.py::test_div_root",
"tests/test_url.py::test_div_root_with_slash",
"tests/test_url.py::test_div",
"tests/test_url.py::test_div_with_slash",
"tests/test_url.py::test_div_path_starting_from_slash_is_forbidden",
"tests/test_url.py::test_div_cleanup_query_and_fragment",
"tests/test_url.py::test_div_for_empty_url",
"tests/test_url.py::test_div_for_relative_url",
"tests/test_url.py::test_div_for_relative_url_started_with_slash",
"tests/test_url.py::test_div_non_ascii",
"tests/test_url.py::test_div_with_colon_and_at",
"tests/test_url.py::test_div_with_dots",
"tests/test_url.py::test_with_path",
"tests/test_url.py::test_with_path_encoded",
"tests/test_url.py::test_with_path_dots",
"tests/test_url.py::test_with_path_relative",
"tests/test_url.py::test_with_path_query",
"tests/test_url.py::test_with_path_fragment",
"tests/test_url.py::test_with_path_empty",
"tests/test_url.py::test_with_path_leading_slash",
"tests/test_url.py::test_with_fragment",
"tests/test_url.py::test_with_fragment_safe",
"tests/test_url.py::test_with_fragment_non_ascii",
"tests/test_url.py::test_with_fragment_None",
"tests/test_url.py::test_with_fragment_bad_type",
"tests/test_url.py::test_with_name",
"tests/test_url.py::test_with_name_for_naked_path",
"tests/test_url.py::test_with_name_for_relative_path",
"tests/test_url.py::test_with_name_for_relative_path2",
"tests/test_url.py::test_with_name_for_relative_path_starting_from_slash",
"tests/test_url.py::test_with_name_for_relative_path_starting_from_slash2",
"tests/test_url.py::test_with_name_empty",
"tests/test_url.py::test_with_name_non_ascii",
"tests/test_url.py::test_with_name_with_slash",
"tests/test_url.py::test_with_name_non_str",
"tests/test_url.py::test_with_name_within_colon_and_at",
"tests/test_url.py::test_with_name_dot",
"tests/test_url.py::test_with_name_double_dot",
"tests/test_url.py::test_is_absolute_for_relative_url",
"tests/test_url.py::test_is_absolute_for_absolute_url",
"tests/test_url.py::test_is_non_absolute_for_empty_url",
"tests/test_url.py::test_is_non_absolute_for_empty_url2",
"tests/test_url.py::test_is_absolute_path_starting_from_double_slash",
"tests/test_url.py::test_is_default_port_for_relative_url",
"tests/test_url.py::test_is_default_port_for_absolute_url_without_port",
"tests/test_url.py::test_is_default_port_for_absolute_url_with_default_port",
"tests/test_url.py::test_is_default_port_for_absolute_url_with_nondefault_port",
"tests/test_url.py::test_is_default_port_for_unknown_scheme",
"tests/test_url.py::test_no_scheme",
"tests/test_url.py::test_no_scheme2",
"tests/test_url.py::test_from_non_allowed",
"tests/test_url.py::test_from_idna",
"tests/test_url.py::test_to_idna",
"tests/test_url.py::test_from_ascii_login",
"tests/test_url.py::test_from_non_ascii_login",
"tests/test_url.py::test_from_ascii_login_and_password",
"tests/test_url.py::test_from_non_ascii_login_and_password",
"tests/test_url.py::test_from_ascii_path",
"tests/test_url.py::test_from_ascii_path_lower_case",
"tests/test_url.py::test_from_non_ascii_path",
"tests/test_url.py::test_from_ascii_query_parts",
"tests/test_url.py::test_from_non_ascii_query_parts",
"tests/test_url.py::test_from_non_ascii_query_parts2",
"tests/test_url.py::test_from_ascii_fragment",
"tests/test_url.py::test_from_bytes_with_non_ascii_fragment",
"tests/test_url.py::test_to_str",
"tests/test_url.py::test_to_str_long",
"tests/test_url.py::test_decoding_with_2F_in_path",
"tests/test_url.py::test_decoding_with_26_and_3D_in_query",
"tests/test_url.py::test_fragment_only_url",
"tests/test_url.py::test_url_from_url",
"tests/test_url.py::test_lowercase_scheme",
"tests/test_url.py::test_str_for_empty_url",
"tests/test_url.py::test_parent_for_empty_url",
"tests/test_url.py::test_empty_value_for_query",
"tests/test_url.py::test_decode_pct_in_path",
"tests/test_url.py::test_decode_pct_in_path_lower_case",
"tests/test_url.py::test_join",
"tests/test_url.py::test_join_absolute",
"tests/test_url.py::test_join_non_url",
"tests/test_url.py::test_join_from_rfc_3986_normal[g:h-g:h]",
"tests/test_url.py::test_join_from_rfc_3986_normal[g-http://a/b/c/g]",
"tests/test_url.py::test_join_from_rfc_3986_normal[./g-http://a/b/c/g]",
"tests/test_url.py::test_join_from_rfc_3986_normal[g/-http://a/b/c/g/]",
"tests/test_url.py::test_join_from_rfc_3986_normal[/g-http://a/g]",
"tests/test_url.py::test_join_from_rfc_3986_normal[//g-http://g]",
"tests/test_url.py::test_join_from_rfc_3986_normal[?y-http://a/b/c/d;p?y]",
"tests/test_url.py::test_join_from_rfc_3986_normal[g?y-http://a/b/c/g?y]",
"tests/test_url.py::test_join_from_rfc_3986_normal[#s-http://a/b/c/d;p?q#s]",
"tests/test_url.py::test_join_from_rfc_3986_normal[g#s-http://a/b/c/g#s]",
"tests/test_url.py::test_join_from_rfc_3986_normal[g?y#s-http://a/b/c/g?y#s]",
"tests/test_url.py::test_join_from_rfc_3986_normal[;x-http://a/b/c/;x]",
"tests/test_url.py::test_join_from_rfc_3986_normal[g;x-http://a/b/c/g;x]",
"tests/test_url.py::test_join_from_rfc_3986_normal[g;x?y#s-http://a/b/c/g;x?y#s]",
"tests/test_url.py::test_join_from_rfc_3986_normal[-http://a/b/c/d;p?q]",
"tests/test_url.py::test_join_from_rfc_3986_normal[.-http://a/b/c/]",
"tests/test_url.py::test_join_from_rfc_3986_normal[./-http://a/b/c/]",
"tests/test_url.py::test_join_from_rfc_3986_normal[..-http://a/b/]",
"tests/test_url.py::test_join_from_rfc_3986_normal[../-http://a/b/]",
"tests/test_url.py::test_join_from_rfc_3986_normal[../g-http://a/b/g]",
"tests/test_url.py::test_join_from_rfc_3986_normal[../..-http://a/]",
"tests/test_url.py::test_join_from_rfc_3986_normal[../../-http://a/]",
"tests/test_url.py::test_join_from_rfc_3986_normal[../../g-http://a/g]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[../../../g-http://a/g]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[../../../../g-http://a/g]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[/./g-http://a/g]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[/../g-http://a/g]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[g.-http://a/b/c/g.]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[.g-http://a/b/c/.g]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[g..-http://a/b/c/g..]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[..g-http://a/b/c/..g]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[./../g-http://a/b/g]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[./g/.-http://a/b/c/g/]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[g/./h-http://a/b/c/g/h]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[g/../h-http://a/b/c/h]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[g;x=1/./y-http://a/b/c/g;x=1/y]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[g;x=1/../y-http://a/b/c/y]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[g?y/./x-http://a/b/c/g?y/./x]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[g?y/../x-http://a/b/c/g?y/../x]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[g#s/./x-http://a/b/c/g#s/./x]",
"tests/test_url.py::test_join_from_rfc_3986_abnormal[g#s/../x-http://a/b/c/g#s/../x]",
"tests/test_url.py::test_split_result_non_decoded",
"tests/test_url.py::test_human_repr",
"tests/test_url.py::test_human_repr_defaults",
"tests/test_url.py::test_human_repr_default_port",
"tests/test_url.py::test_relative",
"tests/test_url.py::test_relative_is_relative",
"tests/test_url.py::test_relative_abs_parts_are_removed",
"tests/test_url.py::test_relative_fails_on_rel_url",
"tests/test_url.py::test_slash_and_question_in_query",
"tests/test_url.py::test_slash_and_question_in_fragment",
"tests/test_url.py::test_requoting",
"tests/test_url_update_netloc.py::test_with_scheme",
"tests/test_url_update_netloc.py::test_with_scheme_uppercased",
"tests/test_url_update_netloc.py::test_with_scheme_for_relative_url",
"tests/test_url_update_netloc.py::test_with_scheme_invalid_type",
"tests/test_url_update_netloc.py::test_with_user",
"tests/test_url_update_netloc.py::test_with_user_non_ascii",
"tests/test_url_update_netloc.py::test_with_user_for_relative_url",
"tests/test_url_update_netloc.py::test_with_user_invalid_type",
"tests/test_url_update_netloc.py::test_with_user_None",
"tests/test_url_update_netloc.py::test_with_user_None_when_password_present",
"tests/test_url_update_netloc.py::test_with_password",
"tests/test_url_update_netloc.py::test_with_password_non_ascii",
"tests/test_url_update_netloc.py::test_with_password_for_relative_url",
"tests/test_url_update_netloc.py::test_with_password_None",
"tests/test_url_update_netloc.py::test_with_password_invalid_type",
"tests/test_url_update_netloc.py::test_from_str_with_host_ipv4",
"tests/test_url_update_netloc.py::test_from_str_with_host_ipv6",
"tests/test_url_update_netloc.py::test_with_host",
"tests/test_url_update_netloc.py::test_with_host_empty",
"tests/test_url_update_netloc.py::test_with_host_non_ascii",
"tests/test_url_update_netloc.py::test_with_host_for_relative_url",
"tests/test_url_update_netloc.py::test_with_host_invalid_type",
"tests/test_url_update_netloc.py::test_with_port",
"tests/test_url_update_netloc.py::test_with_port_keeps_query_and_fragment",
"tests/test_url_update_netloc.py::test_with_port_for_relative_url",
"tests/test_url_update_netloc.py::test_with_port_invalid_type"
]
| []
| Apache License 2.0 | 1,641 | [
"yarl/__init__.py",
"CHANGES.rst"
]
| [
"yarl/__init__.py",
"CHANGES.rst"
]
|
jupyter__nbgrader-888 | 6a5a895fb1de74af4de84f55288421833a655976 | 2017-09-01 12:04:34 | 5bc6f37c39c8b10b8f60440b2e6d9487e63ef3f1 | diff --git a/nbgrader/preprocessors/overwritekernelspec.py b/nbgrader/preprocessors/overwritekernelspec.py
index cff743e3..f8995051 100644
--- a/nbgrader/preprocessors/overwritekernelspec.py
+++ b/nbgrader/preprocessors/overwritekernelspec.py
@@ -14,9 +14,17 @@ class OverwriteKernelspec(NbGraderPreprocessor):
db_url = resources['nbgrader']['db_url']
with Gradebook(db_url) as gb:
- kernelspec = gb.find_notebook(notebook_id, assignment_id).kernelspec
+ kernelspec = json.loads(
+ gb.find_notebook(notebook_id, assignment_id).kernelspec)
+ self.log.debug("Source notebook kernelspec: {}".format(kernelspec))
+ self.log.debug(
+ "Submitted notebook kernelspec: {}"
+ "".format(nb.metadata.get('kernelspec', None))
+ )
if kernelspec:
self.log.debug(
- "Overwriting notebook kernelspec with: {}".format(kernelspec))
- nb.metadata['kernelspec'] = json.loads(kernelspec)
+ "Overwriting submitted notebook kernelspec: {}"
+ "".format(kernelspec)
+ )
+ nb.metadata['kernelspec'] = kernelspec
return nb, resources
| Tests failing due to kernelspec validation on autograding
See #880 and https://travis-ci.org/jupyter/nbgrader/builds/270643170 | jupyter/nbgrader | diff --git a/nbgrader/tests/apps/test_nbgrader_autograde.py b/nbgrader/tests/apps/test_nbgrader_autograde.py
index 8d8576a9..eba18c8d 100644
--- a/nbgrader/tests/apps/test_nbgrader_autograde.py
+++ b/nbgrader/tests/apps/test_nbgrader_autograde.py
@@ -658,21 +658,49 @@ class TestNbGraderAutograde(BaseTestApp):
assert not os.path.isfile(join(course_dir, "autograded", "foo", "ps1", "p1.ipynb"))
assert not os.path.isfile(join(course_dir, "autograded", "foo", "ps1", "p2.ipynb"))
- def test_handle_failure_missing_kernelspec(self, course_dir):
+ def test_missing_source_kernelspec(self, course_dir):
with open("nbgrader_config.py", "a") as fh:
fh.write("""c.CourseDirectory.db_assignments = [dict(name='ps1', duedate='2015-02-02 14:58:23.948203 PST')]\n""")
fh.write("""c.CourseDirectory.db_students = [dict(id="foo"), dict(id="bar")]\n""")
fh.write("""c.ClearSolutions.code_stub = {'python': '## Answer', 'blah': '## Answer'}""")
- self._empty_notebook(join(course_dir, "source", "ps1", "p1.ipynb"), kernel="blah")
+ self._empty_notebook(join(course_dir, "source", "ps1", "p1.ipynb"))
run_nbgrader(["assign", "ps1"])
- self._empty_notebook(join(course_dir, "submitted", "foo", "ps1", "p1.ipynb"), kernel="blah")
- self._empty_notebook(join(course_dir, "submitted", "bar", "ps1", "p1.ipynb"), kernel="python")
+ self._empty_notebook(join(course_dir, "submitted", "foo", "ps1", "p1.ipynb"), kernel="python")
+ run_nbgrader(["autograde", "ps1"])
+ assert os.path.exists(join(course_dir, "autograded", "foo", "ps1"))
+ assert os.path.isfile(join(course_dir, "autograded", "foo", "ps1", "p1.ipynb"))
+
+ self._empty_notebook(join(course_dir, "submitted", "bar", "ps1", "p1.ipynb"), kernel="blarg")
run_nbgrader(["autograde", "ps1"], retcode=1)
+ assert not os.path.exists(join(course_dir, "autograded", "bar", "ps1"))
+
+ def test_incorrect_source_kernelspec(self, course_dir):
+ with open("nbgrader_config.py", "a") as fh:
+ fh.write("""c.CourseDirectory.db_assignments = [dict(name='ps1', duedate='2015-02-02 14:58:23.948203 PST')]\n""")
+ fh.write("""c.CourseDirectory.db_students = [dict(id="foo"), dict(id="bar")]\n""")
+ fh.write("""c.ClearSolutions.code_stub = {'python': '## Answer', 'blah': '## Answer'}""")
+
+ self._empty_notebook(join(course_dir, "source", "ps1", "p1.ipynb"), kernel="blah")
+ run_nbgrader(["assign", "ps1"])
+ self._empty_notebook(join(course_dir, "submitted", "foo", "ps1", "p1.ipynb"), kernel="python")
+ run_nbgrader(["autograde", "ps1"], retcode=1)
assert not os.path.exists(join(course_dir, "autograded", "foo", "ps1"))
- assert not os.path.exists(join(course_dir, "autograded", "bar", "ps1"))
+
+ def test_incorrect_submitted_kernelspec(self, db, course_dir):
+ with open("nbgrader_config.py", "a") as fh:
+ fh.write("""c.CourseDirectory.db_assignments = [dict(name='ps1', duedate='2015-02-02 14:58:23.948203 PST')]\n""")
+ fh.write("""c.CourseDirectory.db_students = [dict(id="foo"), dict(id="bar")]""")
+
+ self._empty_notebook(join(course_dir, "source", "ps1", "p1.ipynb"), kernel="python")
+ run_nbgrader(["assign", "ps1"])
+
+ self._empty_notebook(join(course_dir, "submitted", "foo", "ps1", "p1.ipynb"), kernel="blah")
+ run_nbgrader(["autograde", "ps1"])
+ assert os.path.exists(join(course_dir, "autograded", "foo", "ps1"))
+ assert os.path.isfile(join(course_dir, "autograded", "foo", "ps1", "p1.ipynb"))
def test_no_execute(self, course_dir):
with open("nbgrader_config.py", "a") as fh:
@@ -771,23 +799,6 @@ class TestNbGraderAutograde(BaseTestApp):
assert not os.path.isfile(join(course_dir, "autograded", "foo", "ps1", "p1.ipynb"))
- def test_overwrite_kernelspec(self, db, course_dir):
- with open("nbgrader_config.py", "a") as fh:
- fh.write("""c.CourseDirectory.db_assignments = [dict(name='ps1', duedate='2015-02-02 14:58:23.948203 PST')]\n""")
- fh.write("""c.CourseDirectory.db_students = [dict(id="foo"), dict(id="bar")]""")
-
- self._empty_notebook(join(course_dir, "source", "ps1", "p1.ipynb"))
- run_nbgrader(["assign", "ps1"])
-
- self._empty_notebook(join(course_dir, "submitted", "foo", "ps1", "p1.ipynb"))
- self._empty_notebook(join(course_dir, "submitted", "bar", "ps1", "p1.ipynb"), kernel="blah")
- run_nbgrader(["autograde", "ps1"])
-
- assert os.path.exists(join(course_dir, "autograded", "foo", "ps1"))
- assert os.path.isfile(join(course_dir, "autograded", "foo", "ps1", "p1.ipynb"))
- assert os.path.exists(join(course_dir, "autograded", "bar", "ps1"))
- assert os.path.isfile(join(course_dir, "autograded", "bar", "ps1", "p1.ipynb"))
-
def test_missing_files(self, db, course_dir):
with open("nbgrader_config.py", "a") as fh:
fh.write("""c.CourseDirectory.db_assignments = [dict(name='ps1', duedate='2015-02-02 14:58:23.948203 PST')]\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": 1,
"issue_text_score": 3,
"test_score": 2
},
"num_modified_files": 1
} | 0.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pyenchant",
"sphinxcontrib-spelling",
"sphinx_rtd_theme",
"nbval",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.5",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
alembic==1.7.7
anyio==3.6.2
argon2-cffi==21.3.0
argon2-cffi-bindings==21.2.0
async-generator==1.10
attrs==22.2.0
Babel==2.11.0
backcall==0.2.0
bleach==4.1.0
certifi==2021.5.30
cffi==1.15.1
charset-normalizer==2.0.12
comm==0.1.4
contextvars==2.4
coverage==6.2
dataclasses==0.8
decorator==5.1.1
defusedxml==0.7.1
docutils==0.18.1
entrypoints==0.4
greenlet==2.0.2
idna==3.10
imagesize==1.4.1
immutables==0.19
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
ipykernel==5.5.6
ipython==7.16.3
ipython-genutils==0.2.0
ipywidgets==7.8.5
jedi==0.17.2
Jinja2==3.0.3
json5==0.9.16
jsonschema==3.2.0
jupyter==1.1.1
jupyter-client==7.1.2
jupyter-console==6.4.3
jupyter-core==4.9.2
jupyter-server==1.13.1
jupyterlab==3.2.9
jupyterlab-pygments==0.1.2
jupyterlab-server==2.10.3
jupyterlab_widgets==1.1.11
Mako==1.1.6
MarkupSafe==2.0.1
mistune==0.8.4
nbclassic==0.3.5
nbclient==0.5.9
nbconvert==6.0.7
nbformat==5.1.3
-e git+https://github.com/jupyter/nbgrader.git@6a5a895fb1de74af4de84f55288421833a655976#egg=nbgrader
nbval==0.10.0
nest-asyncio==1.6.0
notebook==6.4.10
packaging==21.3
pandocfilters==1.5.1
parso==0.7.1
pexpect==4.9.0
pickleshare==0.7.5
pluggy==1.0.0
prometheus-client==0.17.1
prompt-toolkit==3.0.36
ptyprocess==0.7.0
py==1.11.0
pycparser==2.21
pyenchant==3.2.2
Pygments==2.14.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
python-dateutil==2.9.0.post0
pytz==2025.2
pyzmq==25.1.2
requests==2.27.1
Send2Trash==1.8.3
six==1.17.0
sniffio==1.2.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-rtd-theme==2.0.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
sphinxcontrib-spelling==7.7.0
SQLAlchemy==1.4.54
terminado==0.12.1
testpath==0.6.0
tomli==1.2.3
tornado==6.1
traitlets==4.3.3
typing_extensions==4.1.1
urllib3==1.26.20
wcwidth==0.2.13
webencodings==0.5.1
websocket-client==1.3.1
widgetsnbextension==3.6.10
zipp==3.6.0
| name: nbgrader
channels:
- defaults
- https://repo.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
- alembic==1.7.7
- anyio==3.6.2
- argon2-cffi==21.3.0
- argon2-cffi-bindings==21.2.0
- async-generator==1.10
- attrs==22.2.0
- babel==2.11.0
- backcall==0.2.0
- bleach==4.1.0
- cffi==1.15.1
- charset-normalizer==2.0.12
- comm==0.1.4
- contextvars==2.4
- coverage==6.2
- dataclasses==0.8
- decorator==5.1.1
- defusedxml==0.7.1
- docutils==0.18.1
- entrypoints==0.4
- greenlet==2.0.2
- idna==3.10
- imagesize==1.4.1
- immutables==0.19
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- ipykernel==5.5.6
- ipython==7.16.3
- ipython-genutils==0.2.0
- ipywidgets==7.8.5
- jedi==0.17.2
- jinja2==3.0.3
- json5==0.9.16
- jsonschema==3.2.0
- jupyter==1.1.1
- jupyter-client==7.1.2
- jupyter-console==6.4.3
- jupyter-core==4.9.2
- jupyter-server==1.13.1
- jupyterlab==3.2.9
- jupyterlab-pygments==0.1.2
- jupyterlab-server==2.10.3
- jupyterlab-widgets==1.1.11
- mako==1.1.6
- markupsafe==2.0.1
- mistune==0.8.4
- nbclassic==0.3.5
- nbclient==0.5.9
- nbconvert==6.0.7
- nbformat==5.1.3
- nbval==0.10.0
- nest-asyncio==1.6.0
- notebook==6.4.10
- packaging==21.3
- pandocfilters==1.5.1
- parso==0.7.1
- pexpect==4.9.0
- pickleshare==0.7.5
- pluggy==1.0.0
- prometheus-client==0.17.1
- prompt-toolkit==3.0.36
- ptyprocess==0.7.0
- py==1.11.0
- pycparser==2.21
- pyenchant==3.2.2
- pygments==2.14.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyzmq==25.1.2
- requests==2.27.1
- send2trash==1.8.3
- six==1.17.0
- sniffio==1.2.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-rtd-theme==2.0.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- sphinxcontrib-spelling==7.7.0
- sqlalchemy==1.4.54
- terminado==0.12.1
- testpath==0.6.0
- tomli==1.2.3
- tornado==6.1
- traitlets==4.3.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- wcwidth==0.2.13
- webencodings==0.5.1
- websocket-client==1.3.1
- widgetsnbextension==3.6.10
- zipp==3.6.0
prefix: /opt/conda/envs/nbgrader
| [
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_permissions",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_custom_permissions",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_handle_failure",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_handle_failure_single_notebook",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_missing_source_kernelspec",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_missing_files"
]
| [
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_force_single_notebook",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_update_newer_single_notebook"
]
| [
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_help",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_missing_student",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_missing_assignment",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_grade",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_grade_timestamp",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_grade_empty_timestamp",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_late_submission_penalty_none",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_late_submission_penalty_zero",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_late_submission_penalty_plugin",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_force",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_filter_notebook",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_grade_overwrite_files",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_side_effects",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_skip_extra_notebooks",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_update_newer",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_hidden_tests_single_notebook",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_incorrect_source_kernelspec",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_incorrect_submitted_kernelspec",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_no_execute",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_infinite_loop",
"nbgrader/tests/apps/test_nbgrader_autograde.py::TestNbGraderAutograde::test_grade_missing_notebook"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,642 | [
"nbgrader/preprocessors/overwritekernelspec.py"
]
| [
"nbgrader/preprocessors/overwritekernelspec.py"
]
|
|
mpdavis__python-jose-63 | b54c12aa54b76d34942f537418399d689d828099 | 2017-09-01 14:12:56 | b54c12aa54b76d34942f537418399d689d828099 | diff --git a/.travis.yml b/.travis.yml
index 5f5a814..92102f6 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,4 +1,7 @@
sudo: false
+# Travis infra requires pinning dist:precise, at least as of 2017-09-01
+# detail: https://blog.travis-ci.com/2017-06-21-trusty-updates-2017-Q2-launch
+dist: precise
language: python
python:
- "2.6"
diff --git a/jose/jwk.py b/jose/jwk.py
index 03a318d..0ae8b05 100644
--- a/jose/jwk.py
+++ b/jose/jwk.py
@@ -105,6 +105,7 @@ class HMACKey(Key):
invalid_strings = [
b'-----BEGIN PUBLIC KEY-----',
+ b'-----BEGIN RSA PUBLIC KEY-----',
b'-----BEGIN CERTIFICATE-----',
b'ssh-rsa'
]
| CVE-2017-11424 Applies to python-jose as well!
[CVE-2017-11424](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-11424) details a key confusion attack against pyjwt.
As I understand it, we just need to add another magic string to [this check](https://github.com/mpdavis/python-jose/blob/b54c12aa54b76d34942f537418399d689d828099/jose/jwk.py#L106-L115)
Not being a crypto expert, I'll open a pull request with the fix described in the CVE, but would appreciate someone else taking a look at the CVE before merging. | mpdavis/python-jose | diff --git a/tests/algorithms/test_HMAC.py b/tests/algorithms/test_HMAC.py
index 30e2714..e84c2c0 100644
--- a/tests/algorithms/test_HMAC.py
+++ b/tests/algorithms/test_HMAC.py
@@ -17,6 +17,10 @@ class TestHMACAlgorithm:
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
+ key = "-----BEGIN RSA PUBLIC KEY-----"
+ with pytest.raises(JOSEError):
+ HMACKey(key, ALGORITHMS.HS256)
+
key = "-----BEGIN CERTIFICATE-----"
with pytest.raises(JOSEError):
HMACKey(key, ALGORITHMS.HS256)
| {
"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": 3,
"test_score": 0
},
"num_modified_files": 2
} | 1.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",
"pytest-cov",
"pytest-runner"
],
"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
coverage==6.2
ecdsa==0.19.1
future==0.18.3
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycrypto==2.6.1
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytest-runner==5.3.2
-e git+https://github.com/mpdavis/python-jose.git@b54c12aa54b76d34942f537418399d689d828099#egg=python_jose
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: python-jose
channels:
- defaults
- https://repo.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
- ecdsa==0.19.1
- future==0.18.3
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycrypto==2.6.1
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-runner==5.3.2
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/python-jose
| [
"tests/algorithms/test_HMAC.py::TestHMACAlgorithm::test_RSA_key"
]
| []
| [
"tests/algorithms/test_HMAC.py::TestHMACAlgorithm::test_non_string_key",
"tests/algorithms/test_HMAC.py::TestHMACAlgorithm::test_to_dict"
]
| []
| MIT License | 1,643 | [
".travis.yml",
"jose/jwk.py"
]
| [
".travis.yml",
"jose/jwk.py"
]
|
|
EdinburghGenomics__EGCG-Core-60 | dff158066e922124e05d2d93cca14b2ee4ad6bfc | 2017-09-01 14:24:56 | 5be3adbce57f2efd3afc6d15f59bb288ce0c1b50 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 58a261b..6db3fe5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,10 +1,10 @@
Changelog for EGCG-Core
===========================
-0.8 (unreleased)
+0.7.3 (unreleased)
----------------
-- Nothing changed yet.
+- Add new option to rest_communication.post_entry to submit payload without json
0.7.2 (2017-08-03)
diff --git a/egcg_core/rest_communication.py b/egcg_core/rest_communication.py
index 949e97c..bc78e7d 100644
--- a/egcg_core/rest_communication.py
+++ b/egcg_core/rest_communication.py
@@ -165,9 +165,12 @@ class Communicator(AppLogger):
else:
self.warning('No document found in endpoint %s for %s', endpoint, query_args)
- def post_entry(self, endpoint, payload):
+ def post_entry(self, endpoint, payload, use_data=False):
files, payload = self._detect_files_in_json(payload)
- return self._req('POST', self.api_url(endpoint), json=payload, files=files)
+ if use_data:
+ return self._req('POST', self.api_url(endpoint), data=payload, files=files)
+ else:
+ return self._req('POST', self.api_url(endpoint), json=payload, files=files)
def put_entry(self, endpoint, element_id, payload):
files, payload = self._detect_files_in_json(payload)
diff --git a/requirements.txt b/requirements.txt
index b55e6f8..b0f950e 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,6 +1,7 @@
pytest>=2.7.2
+requests==2.14.2
PyYAML>=3.11
pyclarity_lims>=0.4
jinja2==2.8
-asana==0.6.2
+asana==0.6.5
cached_property
| rest_communication: post data as form instead of json
`post_entry` should have an option to specify a post where the data is stored in the form instead of the query string.
| EdinburghGenomics/EGCG-Core | diff --git a/tests/test_rest_communication.py b/tests/test_rest_communication.py
index 3f920be..fcc907f 100644
--- a/tests/test_rest_communication.py
+++ b/tests/test_rest_communication.py
@@ -180,6 +180,24 @@ class TestRestCommunication(TestEGCG):
files={'f': (file_path, b'test content', 'text/plain')}
)
+ self.comm.post_entry(test_endpoint, payload=test_flat_request_content, use_data=True)
+ mocked_response.assert_called_with(
+ 'POST',
+ rest_url(test_endpoint),
+ auth=auth,
+ data=test_flat_request_content,
+ files=None
+ )
+
+ self.comm.post_entry(test_endpoint, payload=test_request_content_plus_files, use_data=True)
+ mocked_response.assert_called_with(
+ 'POST',
+ rest_url(test_endpoint),
+ auth=auth,
+ data=test_flat_request_content,
+ files={'f': (file_path, b'test content', 'text/plain')}
+ )
+
@patched_response
def test_put_entry(self, mocked_response):
self.comm.put_entry(test_endpoint, 'an_element_id', payload=test_nested_request_content)
| {
"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": 0,
"issue_text_score": 2,
"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": [
"pytest",
"pytest-cov",
"python-coveralls"
],
"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"
} | asana==0.6.2
attrs==22.2.0
cached-property==1.5.2
certifi==2021.5.30
coverage==6.2
-e git+https://github.com/EdinburghGenomics/EGCG-Core.git@dff158066e922124e05d2d93cca14b2ee4ad6bfc#egg=EGCG_Core
importlib-metadata==4.8.3
iniconfig==1.1.1
Jinja2==2.8
MarkupSafe==2.0.1
oauthlib==3.2.2
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyclarity-lims==0.4.8
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
python-coveralls==2.9.3
PyYAML==6.0.1
requests==2.9.2
requests-oauthlib==0.6.2
six==1.10.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: EGCG-Core
channels:
- defaults
- https://repo.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:
- asana==0.6.2
- attrs==22.2.0
- cached-property==1.5.2
- coverage==6.2
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jinja2==2.8
- markupsafe==2.0.1
- oauthlib==3.2.2
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyclarity-lims==0.4.8
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- python-coveralls==2.9.3
- pyyaml==6.0.1
- requests==2.9.2
- requests-oauthlib==0.6.2
- six==1.10.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/EGCG-Core
| [
"tests/test_rest_communication.py::TestRestCommunication::test_post_entry"
]
| [
"tests/test_rest_communication.py::test_default"
]
| [
"tests/test_rest_communication.py::TestRestCommunication::test_api_url",
"tests/test_rest_communication.py::TestRestCommunication::test_auth_token_and_if_match",
"tests/test_rest_communication.py::TestRestCommunication::test_detect_files_in_json",
"tests/test_rest_communication.py::TestRestCommunication::test_get_content",
"tests/test_rest_communication.py::TestRestCommunication::test_get_document",
"tests/test_rest_communication.py::TestRestCommunication::test_get_documents",
"tests/test_rest_communication.py::TestRestCommunication::test_get_documents_depaginate",
"tests/test_rest_communication.py::TestRestCommunication::test_parse_query_string",
"tests/test_rest_communication.py::TestRestCommunication::test_patch_entry",
"tests/test_rest_communication.py::TestRestCommunication::test_post_or_patch",
"tests/test_rest_communication.py::TestRestCommunication::test_put_entry",
"tests/test_rest_communication.py::TestRestCommunication::test_req",
"tests/test_rest_communication.py::TestRestCommunication::test_token_auth"
]
| []
| MIT License | 1,644 | [
"requirements.txt",
"egcg_core/rest_communication.py",
"CHANGELOG.md"
]
| [
"requirements.txt",
"egcg_core/rest_communication.py",
"CHANGELOG.md"
]
|
|
dask__dask-2647 | d32e8b7b91e130037701daffabf663d8f1bae5de | 2017-09-01 15:47:53 | c560965c8fc0da7cbc0920d43b7011d2721307d3 | fujiisoup: Thanks for the review.
Done. | diff --git a/dask/array/slicing.py b/dask/array/slicing.py
index 269ffbc49..42e65cc45 100644
--- a/dask/array/slicing.py
+++ b/dask/array/slicing.py
@@ -62,7 +62,7 @@ def sanitize_index(ind):
# If a 1-element tuple, unwrap the element
nonzero = nonzero[0]
return np.asanyarray(nonzero)
- elif np.issubdtype(index_array.dtype, int):
+ elif np.issubdtype(index_array.dtype, np.integer):
return index_array
elif np.issubdtype(index_array.dtype, float):
int_index = index_array.astype(np.intp)
| Indexing dask.array by an unsigned-integer np.ndarray
Indexing dask.array by an unsigned-integer np.ndarray raises TypeError.
Is it an intended behavior?
```python
In [1]: import numpy as np
...: import dask.array as da
...:
...: array = da.from_array(np.arange(6), chunks=3)
...: array[np.array([0])] # indexing works with integer array
...:
Out[1]: dask.array<getitem, shape=(1,), dtype=int64, chunksize=(1,)>
In [2]: array[np.array([0], dtype=np.uint64)] # not with uint array
...:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-6161ebf9f837> in <module>()
----> 1 array[np.array([0], dtype=np.uint64)] # not with uint array
~/anaconda3/envs/xarray/lib/python3.5/site-packages/dask/array/core.py in __getitem__(self, index)
1197 return self
1198
-> 1199 dsk, chunks = slice_array(out, self.name, self.chunks, index)
1200
1201 dsk2 = sharedict.merge(self.dask, (out, dsk))
~/anaconda3/envs/xarray/lib/python3.5/site-packages/dask/array/slicing.py in slice_array(out_name, in_name, blockdims, index)
140 """
141 index = replace_ellipsis(len(blockdims), index)
--> 142 index = tuple(map(sanitize_index, index))
143
144 blockdims = tuple(map(tuple, blockdims))
~/anaconda3/envs/xarray/lib/python3.5/site-packages/dask/array/slicing.py in sanitize_index(ind)
76 first_err)
77 else:
---> 78 raise TypeError("Invalid index type", type(ind), ind)
79
80
TypeError: ('Invalid index type', <class 'numpy.ndarray'>, array([0], dtype=uint64))
```
python 3.5
dask 0.15.2
originally raised in an [xarray issue](https://github.com/pydata/xarray/issues/1405). | dask/dask | diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py
index d6af863f3..f6f04ee7a 100644
--- a/dask/array/tests/test_array_core.py
+++ b/dask/array/tests/test_array_core.py
@@ -1611,6 +1611,14 @@ def test_slice_with_floats():
d[[1, 1.5]]
+def test_slice_with_uint():
+ x = np.arange(10)
+ dx = da.from_array(x, chunks=5)
+ inds = np.array([0, 3, 6], dtype='u8')
+ assert_eq(dx[inds], x[inds])
+ assert_eq(dx[inds.astype('u4')], x[inds.astype('u4')])
+
+
def test_vindex_basic():
x = np.arange(56).reshape((7, 8))
d = da.from_array(x, chunks=(3, 4))
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.15 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[complete]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-xdist",
"pytest-cov",
"pytest-mock",
"pytest-asyncio",
"numpy>=1.16.0",
"pandas>=1.0.0"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aiobotocore==2.1.2
aiohttp==3.8.6
aioitertools==0.11.0
aiosignal==1.2.0
async-timeout==4.0.2
asynctest==0.13.0
attrs==22.2.0
botocore==1.23.24
certifi==2021.5.30
charset-normalizer==3.0.1
click==8.0.4
cloudpickle==2.2.1
coverage==6.2
-e git+https://github.com/dask/dask.git@d32e8b7b91e130037701daffabf663d8f1bae5de#egg=dask
distributed==1.19.3
execnet==1.9.0
frozenlist==1.2.0
fsspec==2022.1.0
HeapDict==1.0.1
idna==3.10
idna-ssl==1.1.0
importlib-metadata==4.8.3
iniconfig==1.1.1
jmespath==0.10.0
locket==1.0.0
msgpack-python==0.5.6
multidict==5.2.0
numpy==1.19.5
packaging==21.3
pandas==1.1.5
partd==1.2.0
pluggy==1.0.0
psutil==7.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
python-dateutil==2.9.0.post0
pytz==2025.2
s3fs==2022.1.0
six==1.17.0
sortedcontainers==2.4.0
tblib==1.7.0
tomli==1.2.3
toolz==0.12.0
tornado==6.1
typing_extensions==4.1.1
urllib3==1.26.20
wrapt==1.16.0
yarl==1.7.2
zict==2.1.0
zipp==3.6.0
| name: dask
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- 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:
- aiobotocore==2.1.2
- aiohttp==3.8.6
- aioitertools==0.11.0
- aiosignal==1.2.0
- async-timeout==4.0.2
- asynctest==0.13.0
- attrs==22.2.0
- botocore==1.23.24
- charset-normalizer==3.0.1
- click==8.0.4
- cloudpickle==2.2.1
- coverage==6.2
- distributed==1.19.3
- execnet==1.9.0
- frozenlist==1.2.0
- fsspec==2022.1.0
- heapdict==1.0.1
- idna==3.10
- idna-ssl==1.1.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jmespath==0.10.0
- locket==1.0.0
- msgpack-python==0.5.6
- multidict==5.2.0
- numpy==1.19.5
- packaging==21.3
- pandas==1.1.5
- partd==1.2.0
- pluggy==1.0.0
- psutil==7.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
- python-dateutil==2.9.0.post0
- pytz==2025.2
- s3fs==2022.1.0
- six==1.17.0
- sortedcontainers==2.4.0
- tblib==1.7.0
- tomli==1.2.3
- toolz==0.12.0
- tornado==6.1
- typing-extensions==4.1.1
- urllib3==1.26.20
- wrapt==1.16.0
- yarl==1.7.2
- zict==2.1.0
- zipp==3.6.0
prefix: /opt/conda/envs/dask
| [
"dask/array/tests/test_array_core.py::test_slice_with_uint"
]
| [
"dask/array/tests/test_array_core.py::test_concatenate_unknown_axes",
"dask/array/tests/test_array_core.py::test_field_access",
"dask/array/tests/test_array_core.py::test_field_access_with_shape",
"dask/array/tests/test_array_core.py::test_matmul",
"dask/array/tests/test_array_core.py::test_to_dask_dataframe"
]
| [
"dask/array/tests/test_array_core.py::test_getem",
"dask/array/tests/test_array_core.py::test_top",
"dask/array/tests/test_array_core.py::test_top_supports_broadcasting_rules",
"dask/array/tests/test_array_core.py::test_concatenate3_on_scalars",
"dask/array/tests/test_array_core.py::test_chunked_dot_product",
"dask/array/tests/test_array_core.py::test_chunked_transpose_plus_one",
"dask/array/tests/test_array_core.py::test_broadcast_dimensions_works_with_singleton_dimensions",
"dask/array/tests/test_array_core.py::test_broadcast_dimensions",
"dask/array/tests/test_array_core.py::test_Array",
"dask/array/tests/test_array_core.py::test_uneven_chunks",
"dask/array/tests/test_array_core.py::test_numblocks_suppoorts_singleton_block_dims",
"dask/array/tests/test_array_core.py::test_keys",
"dask/array/tests/test_array_core.py::test_Array_computation",
"dask/array/tests/test_array_core.py::test_stack",
"dask/array/tests/test_array_core.py::test_short_stack",
"dask/array/tests/test_array_core.py::test_stack_scalars",
"dask/array/tests/test_array_core.py::test_stack_promote_type",
"dask/array/tests/test_array_core.py::test_stack_rechunk",
"dask/array/tests/test_array_core.py::test_concatenate",
"dask/array/tests/test_array_core.py::test_concatenate_rechunk",
"dask/array/tests/test_array_core.py::test_concatenate_fixlen_strings",
"dask/array/tests/test_array_core.py::test_binops",
"dask/array/tests/test_array_core.py::test_broadcast_shapes",
"dask/array/tests/test_array_core.py::test_elemwise_on_scalars",
"dask/array/tests/test_array_core.py::test_partial_by_order",
"dask/array/tests/test_array_core.py::test_elemwise_with_ndarrays",
"dask/array/tests/test_array_core.py::test_elemwise_differently_chunked",
"dask/array/tests/test_array_core.py::test_elemwise_dtype",
"dask/array/tests/test_array_core.py::test_operators",
"dask/array/tests/test_array_core.py::test_operator_dtype_promotion",
"dask/array/tests/test_array_core.py::test_T",
"dask/array/tests/test_array_core.py::test_norm",
"dask/array/tests/test_array_core.py::test_broadcast_to",
"dask/array/tests/test_array_core.py::test_broadcast_to_array",
"dask/array/tests/test_array_core.py::test_broadcast_to_scalar",
"dask/array/tests/test_array_core.py::test_reshape[original_shape0-new_shape0-chunks0]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape1-new_shape1-5]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape2-new_shape2-5]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape3-new_shape3-12]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape4-new_shape4-12]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape5-new_shape5-chunks5]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape6-new_shape6-4]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape7-new_shape7-4]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape8-new_shape8-4]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape9-new_shape9-2]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape10-new_shape10-2]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape11-new_shape11-2]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape12-new_shape12-2]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape13-new_shape13-2]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape14-new_shape14-2]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape15-new_shape15-2]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape16-new_shape16-chunks16]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape17-new_shape17-3]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape18-new_shape18-4]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape19-new_shape19-chunks19]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape20-new_shape20-1]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape21-new_shape21-1]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape22-new_shape22-24]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape23-new_shape23-6]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape24-new_shape24-6]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape25-new_shape25-6]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape26-new_shape26-chunks26]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape27-new_shape27-chunks27]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape28-new_shape28-chunks28]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape29-new_shape29-chunks29]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape30-new_shape30-chunks30]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape31-new_shape31-chunks31]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape32-new_shape32-chunks32]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape33-new_shape33-chunks33]",
"dask/array/tests/test_array_core.py::test_reshape[original_shape34-new_shape34-chunks34]",
"dask/array/tests/test_array_core.py::test_reshape_exceptions",
"dask/array/tests/test_array_core.py::test_reshape_splat",
"dask/array/tests/test_array_core.py::test_reshape_fails_for_dask_only",
"dask/array/tests/test_array_core.py::test_reshape_unknown_dimensions",
"dask/array/tests/test_array_core.py::test_full",
"dask/array/tests/test_array_core.py::test_map_blocks",
"dask/array/tests/test_array_core.py::test_map_blocks2",
"dask/array/tests/test_array_core.py::test_map_blocks_with_constants",
"dask/array/tests/test_array_core.py::test_map_blocks_with_kwargs",
"dask/array/tests/test_array_core.py::test_map_blocks_with_chunks",
"dask/array/tests/test_array_core.py::test_map_blocks_dtype_inference",
"dask/array/tests/test_array_core.py::test_from_function_requires_block_args",
"dask/array/tests/test_array_core.py::test_repr",
"dask/array/tests/test_array_core.py::test_slicing_with_ellipsis",
"dask/array/tests/test_array_core.py::test_slicing_with_ndarray",
"dask/array/tests/test_array_core.py::test_dtype",
"dask/array/tests/test_array_core.py::test_blockdims_from_blockshape",
"dask/array/tests/test_array_core.py::test_coerce",
"dask/array/tests/test_array_core.py::test_store_delayed_target",
"dask/array/tests/test_array_core.py::test_store",
"dask/array/tests/test_array_core.py::test_store_regions",
"dask/array/tests/test_array_core.py::test_store_compute_false",
"dask/array/tests/test_array_core.py::test_store_locks",
"dask/array/tests/test_array_core.py::test_np_array_with_zero_dimensions",
"dask/array/tests/test_array_core.py::test_dtype_complex",
"dask/array/tests/test_array_core.py::test_astype",
"dask/array/tests/test_array_core.py::test_arithmetic",
"dask/array/tests/test_array_core.py::test_elemwise_consistent_names",
"dask/array/tests/test_array_core.py::test_optimize",
"dask/array/tests/test_array_core.py::test_slicing_with_non_ndarrays",
"dask/array/tests/test_array_core.py::test_getter",
"dask/array/tests/test_array_core.py::test_size",
"dask/array/tests/test_array_core.py::test_nbytes",
"dask/array/tests/test_array_core.py::test_itemsize",
"dask/array/tests/test_array_core.py::test_Array_normalizes_dtype",
"dask/array/tests/test_array_core.py::test_from_array_with_lock",
"dask/array/tests/test_array_core.py::test_from_array_no_asarray",
"dask/array/tests/test_array_core.py::test_from_array_getitem",
"dask/array/tests/test_array_core.py::test_asarray",
"dask/array/tests/test_array_core.py::test_asanyarray",
"dask/array/tests/test_array_core.py::test_from_func",
"dask/array/tests/test_array_core.py::test_concatenate3_2",
"dask/array/tests/test_array_core.py::test_map_blocks3",
"dask/array/tests/test_array_core.py::test_from_array_with_missing_chunks",
"dask/array/tests/test_array_core.py::test_normalize_chunks",
"dask/array/tests/test_array_core.py::test_raise_on_no_chunks",
"dask/array/tests/test_array_core.py::test_chunks_is_immutable",
"dask/array/tests/test_array_core.py::test_raise_on_bad_kwargs",
"dask/array/tests/test_array_core.py::test_long_slice",
"dask/array/tests/test_array_core.py::test_ellipsis_slicing",
"dask/array/tests/test_array_core.py::test_point_slicing",
"dask/array/tests/test_array_core.py::test_point_slicing_with_full_slice",
"dask/array/tests/test_array_core.py::test_slice_with_floats",
"dask/array/tests/test_array_core.py::test_vindex_basic",
"dask/array/tests/test_array_core.py::test_vindex_nd",
"dask/array/tests/test_array_core.py::test_vindex_errors",
"dask/array/tests/test_array_core.py::test_vindex_merge",
"dask/array/tests/test_array_core.py::test_empty_array",
"dask/array/tests/test_array_core.py::test_memmap",
"dask/array/tests/test_array_core.py::test_to_npy_stack",
"dask/array/tests/test_array_core.py::test_view",
"dask/array/tests/test_array_core.py::test_view_fortran",
"dask/array/tests/test_array_core.py::test_map_blocks_with_changed_dimension",
"dask/array/tests/test_array_core.py::test_broadcast_chunks",
"dask/array/tests/test_array_core.py::test_chunks_error",
"dask/array/tests/test_array_core.py::test_array_compute_forward_kwargs",
"dask/array/tests/test_array_core.py::test_dont_fuse_outputs",
"dask/array/tests/test_array_core.py::test_dont_dealias_outputs",
"dask/array/tests/test_array_core.py::test_timedelta_op",
"dask/array/tests/test_array_core.py::test_to_delayed",
"dask/array/tests/test_array_core.py::test_to_delayed_optimizes",
"dask/array/tests/test_array_core.py::test_cumulative",
"dask/array/tests/test_array_core.py::test_atop_names",
"dask/array/tests/test_array_core.py::test_atop_new_axes",
"dask/array/tests/test_array_core.py::test_atop_kwargs",
"dask/array/tests/test_array_core.py::test_atop_chunks",
"dask/array/tests/test_array_core.py::test_from_delayed",
"dask/array/tests/test_array_core.py::test_A_property",
"dask/array/tests/test_array_core.py::test_copy_mutate",
"dask/array/tests/test_array_core.py::test_npartitions",
"dask/array/tests/test_array_core.py::test_astype_gh1151",
"dask/array/tests/test_array_core.py::test_elemwise_name",
"dask/array/tests/test_array_core.py::test_map_blocks_name",
"dask/array/tests/test_array_core.py::test_from_array_names",
"dask/array/tests/test_array_core.py::test_array_picklable",
"dask/array/tests/test_array_core.py::test_from_array_raises_on_bad_chunks",
"dask/array/tests/test_array_core.py::test_concatenate_axes",
"dask/array/tests/test_array_core.py::test_atop_concatenate",
"dask/array/tests/test_array_core.py::test_common_blockdim",
"dask/array/tests/test_array_core.py::test_uneven_chunks_that_fit_neatly",
"dask/array/tests/test_array_core.py::test_elemwise_uneven_chunks",
"dask/array/tests/test_array_core.py::test_uneven_chunks_atop",
"dask/array/tests/test_array_core.py::test_warn_bad_rechunking",
"dask/array/tests/test_array_core.py::test_optimize_fuse_keys",
"dask/array/tests/test_array_core.py::test_concatenate_stack_dont_warn",
"dask/array/tests/test_array_core.py::test_map_blocks_delayed",
"dask/array/tests/test_array_core.py::test_no_chunks",
"dask/array/tests/test_array_core.py::test_no_chunks_2d",
"dask/array/tests/test_array_core.py::test_no_chunks_yes_chunks",
"dask/array/tests/test_array_core.py::test_raise_informative_errors_no_chunks",
"dask/array/tests/test_array_core.py::test_no_chunks_slicing_2d",
"dask/array/tests/test_array_core.py::test_index_array_with_array_1d",
"dask/array/tests/test_array_core.py::test_index_array_with_array_2d",
"dask/array/tests/test_array_core.py::test_setitem_1d",
"dask/array/tests/test_array_core.py::test_setitem_2d",
"dask/array/tests/test_array_core.py::test_setitem_errs",
"dask/array/tests/test_array_core.py::test_zero_slice_dtypes",
"dask/array/tests/test_array_core.py::test_zero_sized_array_rechunk",
"dask/array/tests/test_array_core.py::test_atop_zero_shape",
"dask/array/tests/test_array_core.py::test_atop_zero_shape_new_axes",
"dask/array/tests/test_array_core.py::test_broadcast_against_zero_shape",
"dask/array/tests/test_array_core.py::test_fast_from_array",
"dask/array/tests/test_array_core.py::test_random_from_array",
"dask/array/tests/test_array_core.py::test_concatenate_errs",
"dask/array/tests/test_array_core.py::test_stack_errs",
"dask/array/tests/test_array_core.py::test_atop_with_numpy_arrays",
"dask/array/tests/test_array_core.py::test_elemwise_with_lists[other0-100]",
"dask/array/tests/test_array_core.py::test_elemwise_with_lists[other0-6]",
"dask/array/tests/test_array_core.py::test_elemwise_with_lists[other1-100]",
"dask/array/tests/test_array_core.py::test_elemwise_with_lists[other1-6]",
"dask/array/tests/test_array_core.py::test_elemwise_with_lists[other2-100]",
"dask/array/tests/test_array_core.py::test_elemwise_with_lists[other2-6]",
"dask/array/tests/test_array_core.py::test_constructor_plugin",
"dask/array/tests/test_array_core.py::test_no_warnings_on_metadata",
"dask/array/tests/test_array_core.py::test_delayed_array_key_hygeine"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,645 | [
"dask/array/slicing.py"
]
| [
"dask/array/slicing.py"
]
|
google__mobly-328 | 51c912d1a8ffd5ace4a9a744a46498515cf5c145 | 2017-09-01 21:02:53 | 7e5e62af4ab4537bf619f0ee403c05f004c5baf0 | dthkao:
Review status: 0 of 1 files reviewed at latest revision, 1 unresolved discussion.
---
*[mobly/controllers/android_device.py, line 839 at r1](https://reviewable.io:443/reviews/google/mobly/328#-KszMvOnUpIQ_wuRiftL:-KszMvOnUpIQ_wuRiftM:b-dddf90) ([raw file](https://github.com/google/mobly/blob/41979c89e8b741071f4d90fe81cc0f8724c9dec1/mobly/controllers/android_device.py#L839)):*
> ```Python
> except AttributeError:
> extra_params = ''
> cmd = '"%s" -s %s logcat -v threadtime %s >> %s' % (
> ```
Can we quote the file path in the literal rather than edit the string?
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/328)*
<!-- Sent from Reviewable.io -->
xpconanfan:
Review status: 0 of 1 files reviewed at latest revision, 1 unresolved discussion.
---
*[mobly/controllers/android_device.py, line 839 at r1](https://reviewable.io:443/reviews/google/mobly/328#-KszMvOnUpIQ_wuRiftL:-KszOwCoUGOHTmyHnR4c:b-896fix) ([raw file](https://github.com/google/mobly/blob/41979c89e8b741071f4d90fe81cc0f8724c9dec1/mobly/controllers/android_device.py#L839)):*
<details><summary><i>Previously, dthkao (David T.H. Kao) wrote…</i></summary><blockquote>
Can we quote the file path in the literal rather than edit the string?
</blockquote></details>
Done.
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/328)*
<!-- Sent from Reviewable.io -->
dthkao:
Review status: 0 of 1 files reviewed at latest revision, 2 unresolved discussions.
---
*[mobly/controllers/android_device.py, line 832 at r2](https://reviewable.io:443/reviews/google/mobly/328#-KszPom4LWZUJNxFsMzj:-KszPom4LWZUJNxFsMzk:bqebhii) ([raw file](https://github.com/google/mobly/blob/fb26406eb9181bf644ace98857e9f54bd2f53c5f/mobly/controllers/android_device.py#L832)):*
> ```Python
> self.adb.shell('logpersist.stop --clear')
> self.adb.shell('logpersist.start')
> f_name = 'adblog,%s,%s.txt' % ('model a c', self.serial)
> ```
why this change?
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/328)*
<!-- Sent from Reviewable.io -->
xpconanfan:
Review status: 0 of 2 files reviewed at latest revision, 2 unresolved discussions.
---
*[mobly/controllers/android_device.py, line 832 at r2](https://reviewable.io:443/reviews/google/mobly/328#-KszPom4LWZUJNxFsMzj:-KszR96tRrUELpuNC-IO:b-896fix) ([raw file](https://github.com/google/mobly/blob/fb26406eb9181bf644ace98857e9f54bd2f53c5f/mobly/controllers/android_device.py#L832)):*
<details><summary><i>Previously, dthkao (David T.H. Kao) wrote…</i></summary><blockquote>
why this change?
</blockquote></details>
Done.
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/328)*
<!-- Sent from Reviewable.io -->
dthkao: <img class="emoji" title=":lgtm:" alt=":lgtm:" align="absmiddle" src="https://reviewable.io/lgtm.png" height="20" width="61"/>
---
Review status: 0 of 2 files reviewed at latest revision, 2 unresolved discussions.
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/328#-:-KtGF4JfiLwz8PYZvweh:bnfp4nl)*
<!-- Sent from Reviewable.io -->
k2fong:
Review status: 0 of 2 files reviewed at latest revision, 2 unresolved discussions.
---
*[mobly/controllers/android_device.py, line 839 at r1](https://reviewable.io:443/reviews/google/mobly/328#-KszMvOnUpIQ_wuRiftL:-KtHnpJS_gLK3fm0aWke:b-4nkc0v) ([raw file](https://github.com/google/mobly/blob/41979c89e8b741071f4d90fe81cc0f8724c9dec1/mobly/controllers/android_device.py#L839)):*
<details><summary><i>Previously, xpconanfan (Ang Li) wrote…</i></summary><blockquote>
Done.
</blockquote></details>
why not have the quote inside the string literal? seems like that'll follow how adb is done.
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/328)*
<!-- Sent from Reviewable.io -->
xpconanfan:
Review status: 0 of 2 files reviewed at latest revision, 2 unresolved discussions.
---
*[mobly/controllers/android_device.py, line 839 at r1](https://reviewable.io:443/reviews/google/mobly/328#-KszMvOnUpIQ_wuRiftL:-KtHrazK6XDU2xpFjRls:b-896fix) ([raw file](https://github.com/google/mobly/blob/41979c89e8b741071f4d90fe81cc0f8724c9dec1/mobly/controllers/android_device.py#L839)):*
<details><summary><i>Previously, k2fong wrote…</i></summary><blockquote>
why not have the quote inside the string literal? seems like that'll follow how adb is done.
</blockquote></details>
Done.
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/328)*
<!-- Sent from Reviewable.io -->
k2fong: <img class="emoji" title=":lgtm:" alt=":lgtm:" align="absmiddle" src="https://reviewable.io/lgtm.png" height="20" width="61"/>
---
Review status: 0 of 2 files reviewed at latest revision, 2 unresolved discussions.
---
*Comments from [Reviewable](https://reviewable.io:443/reviews/google/mobly/328#-:-KtHvHPp4h2cIKq9J2C1:bnfp4nl)*
<!-- Sent from Reviewable.io -->
| diff --git a/mobly/controllers/android_device.py b/mobly/controllers/android_device.py
index 5d7027e..e52e5fd 100644
--- a/mobly/controllers/android_device.py
+++ b/mobly/controllers/android_device.py
@@ -836,10 +836,8 @@ class AndroidDevice(object):
extra_params = self.adb_logcat_param
except AttributeError:
extra_params = ''
- cmd = '"%s" -s %s logcat -v threadtime %s >> %s' % (adb.ADB,
- self.serial,
- extra_params,
- logcat_file_path)
+ cmd = '"%s" -s %s logcat -v threadtime %s >> "%s"' % (
+ adb.ADB, self.serial, extra_params, logcat_file_path)
process = utils.start_standing_subprocess(cmd, shell=True)
self._adb_logcat_process = process
self.adb_logcat_file_path = logcat_file_path
| `AndroidDevice` adb logcat file name gets truncated
If device model name includes space, the output file name of adb logcat is incorrect.
For example, for model "aqua power hd-4g", we expect `adblog,aqua power hd-4g,usb:3-5.2.3.txt`, but we actually get `adblog,aqua`. | google/mobly | diff --git a/tests/mobly/controllers/android_device_test.py b/tests/mobly/controllers/android_device_test.py
index 1849496..59c5529 100755
--- a/tests/mobly/controllers/android_device_test.py
+++ b/tests/mobly/controllers/android_device_test.py
@@ -326,7 +326,7 @@ class AndroidDeviceTest(unittest.TestCase):
creat_dir_mock.assert_called_with(os.path.dirname(expected_log_path))
adb_cmd = '"adb" -s %s logcat -v threadtime >> %s'
start_proc_mock.assert_called_with(
- adb_cmd % (ad.serial, expected_log_path), shell=True)
+ adb_cmd % (ad.serial, '"%s"' % expected_log_path), shell=True)
self.assertEqual(ad.adb_logcat_file_path, expected_log_path)
expected_msg = (
'Logcat thread is already running, cannot start another'
@@ -373,7 +373,7 @@ class AndroidDeviceTest(unittest.TestCase):
creat_dir_mock.assert_called_with(os.path.dirname(expected_log_path))
adb_cmd = '"adb" -s %s logcat -v threadtime -b radio >> %s'
start_proc_mock.assert_called_with(
- adb_cmd % (ad.serial, expected_log_path), shell=True)
+ adb_cmd % (ad.serial, '"%s"' % expected_log_path), shell=True)
self.assertEqual(ad.adb_logcat_file_path, expected_log_path)
@mock.patch(
| {
"commit_name": "merge_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
} | 1.6 | {
"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": [
"apt-get update",
"apt-get install -y gcc",
"apt-get install -y adb"
],
"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
future==1.0.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
-e git+https://github.com/google/mobly.git@51c912d1a8ffd5ace4a9a744a46498515cf5c145#egg=mobly
mock==1.0.1
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
portpicker==1.6.0
psutil==7.0.0
pytest @ file:///croot/pytest_1738938843180/work
pytz==2025.2
PyYAML==6.0.2
timeout-decorator==0.5.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: mobly
channels:
- defaults
- https://repo.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:
- future==1.0.0
- mock==1.0.1
- portpicker==1.6.0
- psutil==7.0.0
- pytz==2025.2
- pyyaml==6.0.2
- timeout-decorator==0.5.0
prefix: /opt/conda/envs/mobly
| [
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_logcat_with_user_param"
]
| []
| [
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_build_info",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_cat_adb_log",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_debug_tag",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_instantiation",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_attribute_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_package",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_load_snippet_dup_snippet_name",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_snippet_cleanup",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fail",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_AndroidDevice_take_bug_report_fallback",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_dict_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_empty_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_no_valid_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_not_list_config",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_pickup_all",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_string_list",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_create_with_usb_id",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_no_match",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_success_with_serial_and_extra_field",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_get_device_too_many_matches",
"tests/mobly/controllers/android_device_test.py::AndroidDeviceTest::test_start_services_on_ads"
]
| []
| Apache License 2.0 | 1,646 | [
"mobly/controllers/android_device.py"
]
| [
"mobly/controllers/android_device.py"
]
|
alvinwan__TexSoup-8 | 17bcf8e20d19d9f70ef10a5b4cfab1cc6ea9e592 | 2017-09-03 06:04:14 | 17bcf8e20d19d9f70ef10a5b4cfab1cc6ea9e592 | diff --git a/TexSoup/__init__.py b/TexSoup/__init__.py
index c34f8b7..ec90adb 100644
--- a/TexSoup/__init__.py
+++ b/TexSoup/__init__.py
@@ -8,8 +8,6 @@ Main file, containing most commonly used elements of TexSoup
@site: alvinwan.com
"""
-import itertools
-import _io
from TexSoup.tex import *
diff --git a/TexSoup/data.py b/TexSoup/data.py
index 93926d5..6ccb199 100644
--- a/TexSoup/data.py
+++ b/TexSoup/data.py
@@ -212,7 +212,7 @@ class TexExpr(object):
"""Further breaks down all tokens for a particular expression into
words and other expressions."""
for content in self.contents:
- if isinstance(str, content):
+ if isinstance(content, str):
for word in content.split():
yield word
yield content
@@ -229,10 +229,10 @@ class TexEnv(TexExpr):
environment arguments, whether optional or required, and (3) the
environment's contents.
- >>> t = TexEnv('tabular', ['0 & 0 & * \\\\', '1 & 1 & * \\\\'],
+ >>> t = TexEnv('tabular', ['\n0 & 0 & * \\\\\n1 & 1 & * \\\\\n'],
... [RArg('c | c c')])
>>> t
- TexEnv('tabular', ['0 & 0 & * \\\\', '1 & 1 & * \\\\'], [RArg('c | c c')])
+ TexEnv('tabular', ['\n0 & 0 & * \\\\\n1 & 1 & * \\\\\n'], [RArg('c | c c')])
>>> print(t)
\begin{tabular}{c | c c}
0 & 0 & * \\
@@ -270,7 +270,7 @@ class TexEnv(TexExpr):
if self.nobegin:
return '%s%s%s' % (
self.name, contents, self.name)
- return '\\begin{%s}%s\n%s\n\\end{%s}' % (
+ return '\\begin{%s}%s%s\\end{%s}' % (
self.name, self.args, contents, self.name)
def __repr__(self):
diff --git a/TexSoup/reader.py b/TexSoup/reader.py
index 2e9842f..5772cea 100644
--- a/TexSoup/reader.py
+++ b/TexSoup/reader.py
@@ -4,8 +4,7 @@ import TexSoup.data as data
import functools
import itertools
-__all__ = ['read_line', 'read_lines', 'tokenize_line', 'tokenize_lines',
- 'read_tex']
+__all__ = ['tokenize', 'read_tex']
COMMAND_TOKENS = {'\\'}
MATH_TOKENS = {'$'}
@@ -14,46 +13,20 @@ ARG_END_TOKENS = {arg.delims()[1] for arg in data.args}
ARG_TOKENS = ARG_START_TOKENS | ARG_END_TOKENS
ALL_TOKENS = COMMAND_TOKENS | ARG_TOKENS | MATH_TOKENS
SKIP_ENVS = ('verbatim', 'equation', 'lstlisting')
+PUNCTUATION_COMMANDS = ('right', 'left')
-#######################
-# Convenience Methods #
-#######################
-
-
-def read_line(line):
- r"""Read first expression from a single line
-
- >>> read_line(r'\textbf{Do play \textit{nice}.}')
- TexCmd('textbf', [RArg('Do play ', TexCmd('textit', [RArg('nice')]), '.')])
- >>> print(read_line(r'\newcommand{solution}[1]{{\color{blue} #1}}'))
- \newcommand{solution}[1]{{\color{blue} #1}}
- """
- return read_tex(Buffer(tokenize_line(line)))
-
-
-def read_lines(*lines):
- r"""Read first expression from multiple lines
-
- >>> print(read_lines(r'\begin{tabular}{c c}', '0 & 1 \\\\',
- ... '\end{tabular}'))
- \begin{tabular}{c c}
- 0 & 1 \\
- \end{tabular}
- """
- return read_tex(Buffer(itertools.chain(*tokenize_lines(lines))))
-
#############
# Tokenizer #
#############
@to_buffer
-def next_token(line):
+def next_token(text):
r"""Returns the next possible token, advancing the iterator to the next
position to start processing from.
- :param (str, iterator, Buffer) line: LaTeX to process
+ :param (str, iterator, Buffer) text: LaTeX to process
:return str: the token
>>> b = Buffer(r'\textbf{Do play\textit{nice}.} $$\min_w \|w\|_2^2$$')
@@ -71,38 +44,30 @@ def next_token(line):
'$$\\min_w \\|w\\|_2^2$$'
>>> next_token(b)
"""
- while line.hasNext():
+ while text.hasNext():
for name, f in tokenizers:
- token = f(line)
+ token = f(text)
if token is not None:
return token
@to_buffer
-def tokenize_line(line):
- r"""Generator for LaTeX tokens on a single line, ignoring comments.
+def tokenize(text):
+ r"""Generator for LaTeX tokens on text, ignoring comments.
- :param (str, iterator, Buffer) line: LaTeX to process
+ :param (str, iterator, Buffer) text: LaTeX to process
- >>> print(*tokenize_line(r'\textbf{Do play \textit{nice}.}'))
+ >>> print(*tokenize(r'\textbf{Do play \textit{nice}.}'))
\ textbf { Do play \ textit { nice } . }
- >>> print(*tokenize_line(r'\begin{tabular} 0 & 1 \\ 2 & 0 \end{tabular}'))
+ >>> print(*tokenize(r'\begin{tabular} 0 & 1 \\ 2 & 0 \end{tabular}'))
\ begin { tabular } 0 & 1 \\ 2 & 0 \ end { tabular }
- >>> print(*tokenize_line(r'$$\min_x \|Xw-y\|_2^2$$'))
+ >>> print(*tokenize(r'$$\min_x \|Xw-y\|_2^2$$'))
$$\min_x \|Xw-y\|_2^2$$
"""
- token = next_token(line)
+ token = next_token(text)
while token is not None:
yield token
- token = next_token(line)
-
-
-def tokenize_lines(lines):
- """Generator for LaTeX tokens across multiple lines, ignoring comments.
-
- :param list lines: list of strings or iterator over strings
- """
- return map(tokenize_line, lines)
+ token = next_token(text)
##########
@@ -123,52 +88,67 @@ def token(name):
return wrap
+@token('punctuation_command')
+def tokenize_punctuation_command(text):
+ """Process command that augments or modifies punctuation.
+
+ This is important to the tokenization of a string, as opening or closing
+ punctuation is not supposed to match.
+
+ :param Buffer text: iterator over text, with current position
+ """
+ if text.peek() == '\\':
+ for string in PUNCTUATION_COMMANDS:
+ if text.peek((1, len(string) + 1)) == string:
+ return text.forward(len(string) + 3)
+
+
@token('command')
-def tokenize_command(line):
+def tokenize_command(text):
"""Process command, but ignore line breaks. (double backslash)
- :param Buffer line: iterator over line, with current position
+ :param Buffer text: iterator over line, with current position
"""
- if line.peek() == '\\' and line.peek(1) not in ALL_TOKENS:
- return next(line)
+ if text.peek() == '\\' and text.peek(1) not in ALL_TOKENS:
+ return next(text)
@token('argument')
-def tokenize_argument(line):
+def tokenize_argument(text):
"""Process both optional and required arguments.
- :param Buffer line: iterator over line, with current position
+ :param Buffer text: iterator over line, with current position
"""
for delim in ARG_TOKENS:
- if line.startswith(delim):
- return line.forward(len(delim))
+ if text.startswith(delim):
+ return text.forward(len(delim))
@token('math')
-def tokenize_math(line):
+def tokenize_math(text):
r"""Prevents math from being tokenized.
- :param Buffer line: iterator over line, with current position
+ :param Buffer text: iterator over line, with current position
>>> b = Buffer('$$\min_x$$ \command')
>>> tokenize_math(b)
'$$\\min_x$$'
"""
result = ''
- if line.startswith('$'):
- starter = '$$' if line.startswith('$$') else '$'
- result += line.forward(len(starter))
- while line.hasNext() and line.peek((0, len(starter))) != starter:
- result += next(line)
- if not line.startswith(starter):
+ if text.startswith('$'):
+ starter = '$$' if text.startswith('$$') else '$'
+ result += text.forward(len(starter))
+ while text.hasNext() and text.peek((0, len(starter))) != starter:
+ result += next(text)
+ if not text.startswith(starter):
raise EOFError('Expecting %s. Instead got %s' % (
- starter, line.peek((0, 5))))
- result += line.forward(len(starter))
+ starter, text.peek((0, 5))))
+ result += text.forward(len(starter))
return result
@token('string')
-def tokenize_string(line, delimiters=ALL_TOKENS):
+def tokenize_string(text, delimiters=ALL_TOKENS):
r"""Process a string of text
:param Buffer line: iterator over line, with current position
@@ -184,15 +164,15 @@ def tokenize_string(line, delimiters=ALL_TOKENS):
0 & 1 \\
"""
result = ''
- for c in line:
- if c == '\\' and line.peek() in delimiters:
- c += next(line)
+ for c in text:
+ if c == '\\' and text.peek() in delimiters:
+ c += next(text)
elif c in delimiters: # assumes all tokens are single characters
- line.backward(1)
+ text.backward(1)
return result
result += c
- if line.peek((0, 2)) == '\\\\':
- result += line.forward(2)
+ if text.peek((0, 2)) == '\\\\':
+ result += text.forward(2)
return result
@@ -213,15 +193,16 @@ def read_tex(src):
if c == '\\':
if src.peek().startswith('item '):
mode, expr = 'command', TexCmd('item', (),
- ' '.join(next(src).split(' ')[1:]))
+ ' '.join(next(src).split(' ')[1:]).strip())
elif src.peek() == 'begin':
mode, expr = next(src), TexEnv(Arg.parse(src.forward(3)).value)
else:
- mode, candidate = 'command', next(src)
- if ' ' in candidate:
- tokens = candidate.split(' ')
- expr = TexCmd(tokens[0], (), ' '.join(tokens[1:]))
- else:
+ mode, candidate, expr = 'command', next(src), None
+ for i, c in enumerate(candidate):
+ if c.isspace():
+ expr = TexCmd(candidate[:i], (), candidate[i+1:])
+ break
+ if not expr:
expr = TexCmd(candidate)
while src.peek() in ARG_START_TOKENS:
expr.args.append(read_tex(src))
@@ -230,6 +211,8 @@ def read_tex(src):
if src.startswith('$'):
expr.add_contents(read_tex(src))
return expr
+ if c.startswith('\\'):
+ return TexCmd(c[1:])
if c in ARG_START_TOKENS:
return read_arg(src, c)
return c
diff --git a/TexSoup/tex.py b/TexSoup/tex.py
index 555e7b7..a384906 100644
--- a/TexSoup/tex.py
+++ b/TexSoup/tex.py
@@ -11,8 +11,10 @@ def read(tex):
:return TexEnv: the global environment
"""
if isinstance(tex, str):
- tex = tex.strip().splitlines()
- buf, children = Buffer(itertools.chain(*tokenize_lines(tex))), []
+ tex = tex.strip()
+ else:
+ tex = itertools.chain(*tex)
+ buf, children = Buffer(tokenize(tex)), []
while buf.hasNext():
content = read_tex(buf)
if content is not None:
diff --git a/TexSoup/utils.py b/TexSoup/utils.py
index 6f2af40..acbd865 100644
--- a/TexSoup/utils.py
+++ b/TexSoup/utils.py
@@ -15,12 +15,22 @@ import functools
# Decorators #
##############
+
def to_buffer(f, i=0):
"""
Decorator converting all strings and iterators/iterables into
Buffers.
:param int i: index of iterator argument. Used only if not a kwarg.
+
+ >>> f = to_buffer(lambda x: x[:])
+ >>> f('asdf')
+ 'asdf'
+ >>> g = to_buffer(lambda x: x)
+ >>> g('').hasNext()
+ False
+ >>> next(g('asdf'))
+ 'a'
"""
@functools.wraps(f)
def wrap(*args, **kwargs):
@@ -39,6 +49,7 @@ def to_buffer(f, i=0):
# Generalized Utilities #
#########################
+
class Buffer:
"""Converts string or iterable into a navigable iterator of strings
| edge cases
- [x] \ can denote escape (special characters: { , : ; ) or be used after e.g.\
- [ ] \right. \right[ \right( \right|
again, noted by/thanks to @chewisinho for bringing up
| alvinwan/TexSoup | diff --git a/tests/test_parser.py b/tests/test_parser.py
index 7d99360..de08b65 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -95,7 +95,7 @@ def test_command_name_parse():
with_linebreak_not_arg = TexSoup(r"""\Question
(10 points)""")
assert with_linebreak_not_arg.Question is not None
- assert with_linebreak_not_arg.Question.extra == ''
+ assert with_linebreak_not_arg.Question.extra == '(10 points)'
with_space_with_arg = TexSoup(r"""\section {hula}""")
assert with_space_with_arg.section.string == 'hula'
@@ -141,14 +141,16 @@ def test_ignore_environment():
\min_x \|Ax - b\|_2^2 + \lambda \|x\|_2^2
\end{verbatim}
$$\min_x \|Ax - b\|_2^2 + \lambda \|x\|_1^2$$
+ $$[0,1)$$
""")
verbatim = list(list(soup.children)[1].contents)[0]
- assert len(list(soup.contents)) == 3, 'Special environments not recognized.'
+ assert len(list(soup.contents)) == 4, 'Special environments not recognized.'
assert str(list(soup.children)[0]) == \
- '\\begin{equation}\n\min_x \|Ax - b\|_2^2\n\\end{equation}'
- assert verbatim.startswith(' '), 'Whitespace not preserved.'
+ '\\begin{equation}\min_x \|Ax - b\|_2^2\\end{equation}'
+ assert verbatim.startswith('\n '), 'Whitespace not preserved.'
assert str(list(soup.children)[2]) == \
'$$\min_x \|Ax - b\|_2^2 + \lambda \|x\|_1^2$$'
+ assert str(list(soup.children)[3]) == '$$[0,1)$$'
def test_inline_math():
@@ -169,11 +171,58 @@ def test_escaped_characters():
"""
soup = TexSoup("""
\begin{itemize}
- \item Ice cream costs \$4-\$5 around here.
+ \item Ice cream costs \$4-\$5 around here. \}\]\{\[
\end{itemize}""")
+ assert str(soup.item) == r'\item Ice cream costs \$4-\$5 around here. ' \
+ r'\}\]\{\['
assert '\\$4-\\$5' in str(soup), 'Escaped characters not properly rendered.'
+##############
+# FORMATTING #
+##############
+
+
+def test_basic_whitespace():
+ """Tests that basic text maintains whitespace."""
+ soup = TexSoup("""
+ Here is some text
+ with a line break
+ and awko taco spacing
+ """)
+ assert len(str(soup).split('\n')) == 3, 'Line breaks not persisted.'
+
+
+def test_whitespace_in_command():
+ """Tests that whitespace in commands are maintained."""
+ soup = TexSoup(r"""
+ \begin{article}
+ \title {This title contains a space}
+ \section {This title contains
+ line break}
+ \end{article}
+ """)
+ assert ' ' in soup.article.title.string
+ assert '\n' in soup.article.section.string
+
+
+def test_math_environment_whitespace():
+ """Tests that math environments are untouched."""
+ soup = TexSoup("""$$\lambda
+ \Sigma$$ But don't mind me \$3.00""")
+ children, contents = list(soup.children), list(soup.contents)
+ assert '\n' in str(children[0]), 'Whitesapce not preserved in math env.'
+ assert len(children) == 1 and children[0].name == '$$', 'Math env wrong'
+ assert '\$' in contents[1], 'Dollar sign not escaped!'
+
+
+def test_punctuation_command_structure():
+ """Tests that commands for punctuation work."""
+ soup = TexSoup(r"""\right. \right[ \right( \right|""")
+ assert len(list(soup.contents)) == 4
+ assert len(list(soup.children)) == 4
+
+
##########
# ERRORS #
##########
@@ -186,6 +235,7 @@ def test_unclosed_environments():
def test_unclosed_math_environments():
+ """Tests that unclosed math environment results in error."""
with pytest.raises(EOFError):
TexSoup(r"""$$\min_x \|Xw-y\|_2^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": 2,
"issue_text_score": 3,
"test_score": 3
},
"num_modified_files": 5
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest",
"coverage",
"coveralls"
],
"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"
} | certifi==2025.1.31
charset-normalizer==3.4.1
coverage==3.7.1
coveralls==1.1
docopt==0.6.2
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
idna==3.10
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
requests==2.32.3
-e git+https://github.com/alvinwan/TexSoup.git@17bcf8e20d19d9f70ef10a5b4cfab1cc6ea9e592#egg=TexSoup
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
urllib3==2.3.0
| name: TexSoup
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- exceptiongroup=1.2.0=py39h06a4308_0
- iniconfig=1.1.1=pyhd3eb1b0_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- packaging=24.2=py39h06a4308_0
- pip=25.0=py39h06a4308_0
- pluggy=1.5.0=py39h06a4308_0
- pytest=8.3.4=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tomli=2.0.1=py39h06a4308_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- certifi==2025.1.31
- charset-normalizer==3.4.1
- coverage==3.7.1
- coveralls==1.1
- docopt==0.6.2
- idna==3.10
- requests==2.32.3
- urllib3==2.3.0
prefix: /opt/conda/envs/TexSoup
| [
"TexSoup/reader.py::TexSoup.reader.tokenize",
"TexSoup/utils.py::TexSoup.utils.to_buffer",
"tests/test_parser.py::test_command_name_parse",
"tests/test_parser.py::test_ignore_environment",
"tests/test_parser.py::test_whitespace_in_command",
"tests/test_parser.py::test_math_environment_whitespace",
"tests/test_parser.py::test_punctuation_command_structure"
]
| []
| [
"TexSoup/__init__.py::TexSoup.TexSoup",
"TexSoup/data.py::TexSoup.data.TexArgs",
"TexSoup/data.py::TexSoup.data.TexArgs.__repr__",
"TexSoup/data.py::TexSoup.data.TexArgs.__str__",
"TexSoup/data.py::TexSoup.data.TexCmd",
"TexSoup/data.py::TexSoup.data.TexEnv",
"TexSoup/data.py::TexSoup.data.TexNode.__match__",
"TexSoup/reader.py::TexSoup.reader.next_token",
"TexSoup/reader.py::TexSoup.reader.tokenize_math",
"TexSoup/reader.py::TexSoup.reader.tokenize_string",
"TexSoup/utils.py::TexSoup.utils.Buffer",
"TexSoup/utils.py::TexSoup.utils.Buffer.__getitem__",
"TexSoup/utils.py::TexSoup.utils.Buffer.backward",
"TexSoup/utils.py::TexSoup.utils.Buffer.forward",
"tests/test_parser.py::test_commands_only",
"tests/test_parser.py::test_commands_envs_only",
"tests/test_parser.py::test_commands_envs_text",
"tests/test_parser.py::test_text_preserved",
"tests/test_parser.py::test_commands_without_arguments",
"tests/test_parser.py::test_unlabeled_environment",
"tests/test_parser.py::test_inline_math",
"tests/test_parser.py::test_escaped_characters",
"tests/test_parser.py::test_basic_whitespace",
"tests/test_parser.py::test_unclosed_environments",
"tests/test_parser.py::test_unclosed_math_environments",
"tests/test_parser.py::test_arg_parse"
]
| []
| BSD 2-Clause "Simplified" License | 1,647 | [
"TexSoup/reader.py",
"TexSoup/utils.py",
"TexSoup/__init__.py",
"TexSoup/tex.py",
"TexSoup/data.py"
]
| [
"TexSoup/reader.py",
"TexSoup/utils.py",
"TexSoup/__init__.py",
"TexSoup/tex.py",
"TexSoup/data.py"
]
|
|
tox-dev__tox-599 | aee874c0b48698bb8d4e2afba18713a8aeb32011 | 2017-09-03 14:27:12 | f1a933b59c2682f40054c0cabe8c1f42a3635168 | diff --git a/CHANGELOG b/CHANGELOG
index 6afb70b4..3b95f4c3 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,7 +1,7 @@
Not released yet
----------------
-- #p598: fix problems with implementation of #515.
+- #p599: fix problems with implementation of #515.
Substitutions from other sections were not made anymore if they were not in `envlist`.
Thanks to Clark Boylan (@cboylan) for helping to get this fixed (#p597).
diff --git a/tox/__init__.py b/tox/__init__.py
index 73d095eb..98f1246a 100644
--- a/tox/__init__.py
+++ b/tox/__init__.py
@@ -14,12 +14,18 @@ class exception:
def __str__(self):
return "%s: %s" % (self.__class__.__name__, self.args[0])
+ class MissingSubstitution(Exception):
+ FLAG = 'TOX_MISSING_SUBSTITUTION'
+ """placeholder for debugging configurations"""
+ def __init__(self, name):
+ self.name = name
+
class ConfigError(Error):
""" error in tox configuration. """
class UnsupportedInterpreter(Error):
- "signals an unsupported Interpreter"
+ """signals an unsupported Interpreter"""
class InterpreterNotFound(Error):
- "signals that an interpreter could not be found"
+ """signals that an interpreter could not be found"""
class InvocationError(Error):
""" an error while invoking a script. """
class MissingFile(Error):
@@ -35,4 +41,5 @@ class exception:
self.message = message
super(exception.MinVersionError, self).__init__(message)
+
from tox.session import main as cmdline # noqa
diff --git a/tox/config.py b/tox/config.py
index 9f0024c0..d5a6baf8 100755
--- a/tox/config.py
+++ b/tox/config.py
@@ -609,6 +609,13 @@ class TestenvConfig:
#: set of factors
self.factors = factors
self._reader = reader
+ self.missing_subs = []
+ """Holds substitutions that could not be resolved.
+
+ Pre 2.8.1 missing substitutions crashed with a ConfigError although this would not be a
+ problem if the env is not part of the current testrun. So we need to remember this and
+ check later when the testenv is actually run and crash only then.
+ """
def get_envbindir(self):
""" path to directory where scripts/binaries reside. """
@@ -791,9 +798,7 @@ class parseini:
section = testenvprefix + name
factors = set(name.split('-'))
if section in self._cfg or factors <= known_factors:
- config.envconfigs[name] = \
- self.make_envconfig(name, section, reader._subs, config,
- replace=name in config.envlist)
+ config.envconfigs[name] = self.make_envconfig(name, section, reader._subs, config)
all_develop = all(name in config.envconfigs
and config.envconfigs[name].usedevelop
@@ -813,33 +818,31 @@ class parseini:
factors = set(name.split('-'))
reader = SectionReader(section, self._cfg, fallbacksections=["testenv"],
factors=factors)
- vc = TestenvConfig(config=config, envname=name, factors=factors, reader=reader)
- reader.addsubstitutions(**subs)
- reader.addsubstitutions(envname=name)
- reader.addsubstitutions(envbindir=vc.get_envbindir,
- envsitepackagesdir=vc.get_envsitepackagesdir,
- envpython=vc.get_envpython)
-
+ tc = TestenvConfig(name, config, factors, reader)
+ reader.addsubstitutions(
+ envname=name, envbindir=tc.get_envbindir, envsitepackagesdir=tc.get_envsitepackagesdir,
+ envpython=tc.get_envpython, **subs)
for env_attr in config._testenv_attr:
atype = env_attr.type
- if atype in ("bool", "path", "string", "dict", "dict_setenv", "argv", "argvlist"):
- meth = getattr(reader, "get" + atype)
- res = meth(env_attr.name, env_attr.default, replace=replace)
- elif atype == "space-separated-list":
- res = reader.getlist(env_attr.name, sep=" ")
- elif atype == "line-list":
- res = reader.getlist(env_attr.name, sep="\n")
- else:
- raise ValueError("unknown type %r" % (atype,))
-
- if env_attr.postprocess:
- res = env_attr.postprocess(testenv_config=vc, value=res)
- setattr(vc, env_attr.name, res)
-
+ try:
+ if atype in ("bool", "path", "string", "dict", "dict_setenv", "argv", "argvlist"):
+ meth = getattr(reader, "get" + atype)
+ res = meth(env_attr.name, env_attr.default, replace=replace)
+ elif atype == "space-separated-list":
+ res = reader.getlist(env_attr.name, sep=" ")
+ elif atype == "line-list":
+ res = reader.getlist(env_attr.name, sep="\n")
+ else:
+ raise ValueError("unknown type %r" % (atype,))
+ if env_attr.postprocess:
+ res = env_attr.postprocess(testenv_config=tc, value=res)
+ except tox.exception.MissingSubstitution as e:
+ tc.missing_subs.append(e.name)
+ res = e.FLAG
+ setattr(tc, env_attr.name, res)
if atype in ("path", "string"):
reader.addsubstitutions(**{env_attr.name: res})
-
- return vc
+ return tc
def _getenvdata(self, reader):
envstr = self.config.option.env \
@@ -961,8 +964,7 @@ class SectionReader:
def getdict_setenv(self, name, default=None, sep="\n", replace=True):
value = self.getstring(name, None, replace=replace, crossonly=True)
- definitions = self._getdict(value, default=default, sep=sep,
- replace=replace)
+ definitions = self._getdict(value, default=default, sep=sep, replace=replace)
self._setenv = SetenvDict(definitions, reader=self)
return self._setenv
@@ -1042,9 +1044,15 @@ class SectionReader:
section_name = section_name if section_name else self.section_name
self._subststack.append((section_name, name))
try:
- return Replacer(self, crossonly=crossonly).do_replace(value)
- finally:
+ replaced = Replacer(self, crossonly=crossonly).do_replace(value)
assert self._subststack.pop() == (section_name, name)
+ except tox.exception.MissingSubstitution:
+ if not section_name.startswith(testenvprefix):
+ raise tox.exception.ConfigError(
+ "substitution env:%r: unknown or recursive definition in "
+ "section %r." % (value, section_name))
+ raise
+ return replaced
class Replacer:
@@ -1112,20 +1120,14 @@ class Replacer:
def _replace_env(self, match):
envkey = match.group('substitution_value')
if not envkey:
- raise tox.exception.ConfigError(
- 'env: requires an environment variable name')
-
+ raise tox.exception.ConfigError('env: requires an environment variable name')
default = match.group('default_value')
-
envvalue = self.reader.get_environ_value(envkey)
- if envvalue is None:
- if default is None:
- raise tox.exception.ConfigError(
- "substitution env:%r: unknown environment variable %r "
- " or recursive definition." %
- (envkey, envkey))
+ if envvalue is not None:
+ return envvalue
+ if default is not None:
return default
- return envvalue
+ raise tox.exception.MissingSubstitution(envkey)
def _substitute_from_other_section(self, key):
if key.startswith("[") and "]" in key:
diff --git a/tox/session.py b/tox/session.py
index 269a7705..60baaeee 100644
--- a/tox/session.py
+++ b/tox/session.py
@@ -440,6 +440,12 @@ class Session:
path.ensure(dir=1)
def setupenv(self, venv):
+ if venv.envconfig.missing_subs:
+ venv.status = (
+ "unresolvable substitution(s): %s. "
+ "Environment variables are missing or defined recursively." %
+ (','.join(["'%s'" % m for m in venv.envconfig.missing_subs])))
+ return
if not venv.matching_platform():
venv.status = "platform mismatch"
return # we simply omit non-matching platforms
| 2.8.0: {[testenv]setenv} substitution broken
While installing tempest as part of devstack install, below commnd blows up with an error -
`tox -r --notest -efull`
Error -
```
2017-09-01 18:22:20.661 | ++ lib/tempest:install_tempest:612 : pushd /opt/stack/new/tempest
2017-09-01 18:22:20.661 | ~/tempest ~/devstack
2017-09-01 18:22:20.662 | ++ lib/tempest:install_tempest:613 : tox -r --notest -efull
2017-09-01 18:22:21.720 | Traceback (most recent call last):
2017-09-01 18:22:21.720 | File "/usr/local/bin/tox", line 11, in <module>
2017-09-01 18:22:21.720 | sys.exit(cmdline())
2017-09-01 18:22:21.720 | File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 38, in main
2017-09-01 18:22:21.720 | config = prepare(args)
2017-09-01 18:22:21.720 | File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 26, in prepare
2017-09-01 18:22:21.720 | config = parseconfig(args)
2017-09-01 18:22:21.720 | File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 242, in parseconfig
2017-09-01 18:22:21.720 | parseini(config, inipath)
2017-09-01 18:22:21.720 | File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 796, in __init__
2017-09-01 18:22:21.721 | replace=name in config.envlist)
2017-09-01 18:22:21.721 | File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 827, in make_envconfig
2017-09-01 18:22:21.721 | res = meth(env_attr.name, env_attr.default, replace=replace)
2017-09-01 18:22:21.721 | File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 964, in getdict_setenv
2017-09-01 18:22:21.721 | definitions = self._getdict(value, default=default, sep=sep)
2017-09-01 18:22:21.721 | File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 975, in _getdict
2017-09-01 18:22:21.721 | name, rest = line.split('=', 1)
2017-09-01 18:22:21.721 | ValueError: need more than 1 value to unpack
2017-09-01 18:22:21.733 | + lib/tempest:install_tempest:1 : exit_trap
```
Logs link - http://logs.openstack.netapp.com/ci-logs/logs/65/499765/5/upstream-check/cinder-cDOT-FCP/3566c47/logs/devstacklog.txt.gz
| tox-dev/tox | diff --git a/tests/test_config.py b/tests/test_config.py
index 6fa64571..2533c962 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -444,18 +444,20 @@ class TestIniParser:
x = reader.getdict("key3", {1: 2})
assert x == {1: 2}
- def test_getstring_environment_substitution(self, monkeypatch, newconfig):
- monkeypatch.setenv("KEY1", "hello")
- config = newconfig("""
- [section]
- key1={env:KEY1}
- key2={env:KEY2}
- """)
- reader = SectionReader("section", config._cfg)
- x = reader.getstring("key1")
- assert x == "hello"
+ def test_normal_env_sub_works(self, monkeypatch, newconfig):
+ monkeypatch.setenv("VAR", "hello")
+ config = newconfig("[section]\nkey={env:VAR}")
+ assert SectionReader("section", config._cfg).getstring("key") == "hello"
+
+ def test_missing_env_sub_raises_config_error_in_non_testenv(self, newconfig):
+ config = newconfig("[section]\nkey={env:VAR}")
with pytest.raises(tox.exception.ConfigError):
- reader.getstring("key2")
+ SectionReader("section", config._cfg).getstring("key")
+
+ def test_missing_env_sub_populates_missing_subs(self, newconfig):
+ config = newconfig("[testenv:foo]\ncommands={env:VAR}")
+ print(SectionReader("section", config._cfg).getstring("commands"))
+ assert config.envconfigs['foo'].missing_subs == ['VAR']
def test_getstring_environment_substitution_with_default(self, monkeypatch, newconfig):
monkeypatch.setenv("KEY1", "hello")
diff --git a/tests/test_z_cmdline.py b/tests/test_z_cmdline.py
index 49e7641f..97e0712b 100644
--- a/tests/test_z_cmdline.py
+++ b/tests/test_z_cmdline.py
@@ -871,3 +871,10 @@ def test_envtmpdir(initproj, cmd):
result = cmd.run("tox")
assert not result.ret
+
+
+def test_missing_env_fails(initproj, cmd):
+ initproj("foo", filedefs={'tox.ini': "[testenv:foo]\ncommands={env:VAR}"})
+ result = cmd.run("tox")
+ assert result.ret == 1
+ result.stdout.fnmatch_lines(["*foo: unresolvable substitution(s): 'VAR'*"])
| {
"commit_name": "merge_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": 3,
"test_score": 0
},
"num_modified_files": 4
} | 2.8 | {
"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",
"pytest-timeout"
],
"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
distlib==0.3.9
filelock==3.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
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
platformdirs==2.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
pytest-timeout==2.1.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
-e git+https://github.com/tox-dev/tox.git@aee874c0b48698bb8d4e2afba18713a8aeb32011#egg=tox
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
virtualenv==20.17.1
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work
| name: tox
channels:
- defaults
- https://repo.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=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:
- distlib==0.3.9
- filelock==3.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- platformdirs==2.4.0
- pytest-timeout==2.1.0
- virtualenv==20.17.1
prefix: /opt/conda/envs/tox
| [
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_regression_issue595",
"tests/test_config.py::TestIniParser::test_missing_env_sub_populates_missing_subs",
"tests/test_z_cmdline.py::test_missing_env_fails"
]
| [
"test_hello.py::test_fail",
"tests/test_config.py::TestVenvConfig::test_force_dep_with_url",
"tests/test_config.py::TestIniParser::test_getbool",
"tests/test_z_cmdline.py::test_report_protocol",
"tests/test_z_cmdline.py::test__resolve_pkg"
]
| [
"tests/test_config.py::TestVenvConfig::test_config_parsing_minimal",
"tests/test_config.py::TestVenvConfig::test_config_parsing_multienv",
"tests/test_config.py::TestVenvConfig::test_envdir_set_manually",
"tests/test_config.py::TestVenvConfig::test_envdir_set_manually_with_substitutions",
"tests/test_config.py::TestVenvConfig::test_force_dep_version",
"tests/test_config.py::TestVenvConfig::test_is_same_dep",
"tests/test_config.py::TestConfigPlatform::test_config_parse_platform",
"tests/test_config.py::TestConfigPlatform::test_config_parse_platform_rex",
"tests/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[win]",
"tests/test_config.py::TestConfigPlatform::test_config_parse_platform_with_factors[lin]",
"tests/test_config.py::TestConfigPackage::test_defaults",
"tests/test_config.py::TestConfigPackage::test_defaults_distshare",
"tests/test_config.py::TestConfigPackage::test_defaults_changed_dir",
"tests/test_config.py::TestConfigPackage::test_project_paths",
"tests/test_config.py::TestParseconfig::test_search_parents",
"tests/test_config.py::TestParseconfig::test_explicit_config_path",
"tests/test_config.py::test_get_homedir",
"tests/test_config.py::TestGetcontextname::test_blank",
"tests/test_config.py::TestGetcontextname::test_jenkins",
"tests/test_config.py::TestGetcontextname::test_hudson_legacy",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section_multiline",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_substitution_from_other_section_posargs",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_section_and_posargs_substitution",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution",
"tests/test_config.py::TestIniParserAgainstCommandsKey::test_command_env_substitution_global",
"tests/test_config.py::TestIniParser::test_getstring_single",
"tests/test_config.py::TestIniParser::test_missing_substitution",
"tests/test_config.py::TestIniParser::test_getstring_fallback_sections",
"tests/test_config.py::TestIniParser::test_getstring_substitution",
"tests/test_config.py::TestIniParser::test_getlist",
"tests/test_config.py::TestIniParser::test_getdict",
"tests/test_config.py::TestIniParser::test_normal_env_sub_works",
"tests/test_config.py::TestIniParser::test_missing_env_sub_raises_config_error_in_non_testenv",
"tests/test_config.py::TestIniParser::test_getstring_environment_substitution_with_default",
"tests/test_config.py::TestIniParser::test_value_matches_section_substituion",
"tests/test_config.py::TestIniParser::test_value_doesn_match_section_substitution",
"tests/test_config.py::TestIniParser::test_getstring_other_section_substitution",
"tests/test_config.py::TestIniParser::test_argvlist",
"tests/test_config.py::TestIniParser::test_argvlist_windows_escaping",
"tests/test_config.py::TestIniParser::test_argvlist_multiline",
"tests/test_config.py::TestIniParser::test_argvlist_quoting_in_command",
"tests/test_config.py::TestIniParser::test_argvlist_comment_after_command",
"tests/test_config.py::TestIniParser::test_argvlist_command_contains_hash",
"tests/test_config.py::TestIniParser::test_argvlist_positional_substitution",
"tests/test_config.py::TestIniParser::test_argvlist_quoted_posargs",
"tests/test_config.py::TestIniParser::test_argvlist_posargs_with_quotes",
"tests/test_config.py::TestIniParser::test_positional_arguments_are_only_replaced_when_standing_alone",
"tests/test_config.py::TestIniParser::test_posargs_are_added_escaped_issue310",
"tests/test_config.py::TestIniParser::test_substitution_with_multiple_words",
"tests/test_config.py::TestIniParser::test_getargv",
"tests/test_config.py::TestIniParser::test_getpath",
"tests/test_config.py::TestIniParserPrefix::test_basic_section_access",
"tests/test_config.py::TestIniParserPrefix::test_fallback_sections",
"tests/test_config.py::TestIniParserPrefix::test_value_matches_prefixed_section_substituion",
"tests/test_config.py::TestIniParserPrefix::test_value_doesn_match_prefixed_section_substitution",
"tests/test_config.py::TestIniParserPrefix::test_other_section_substitution",
"tests/test_config.py::TestConfigTestEnv::test_commentchars_issue33",
"tests/test_config.py::TestConfigTestEnv::test_defaults",
"tests/test_config.py::TestConfigTestEnv::test_sitepackages_switch",
"tests/test_config.py::TestConfigTestEnv::test_installpkg_tops_develop",
"tests/test_config.py::TestConfigTestEnv::test_specific_command_overrides",
"tests/test_config.py::TestConfigTestEnv::test_whitelist_externals",
"tests/test_config.py::TestConfigTestEnv::test_changedir",
"tests/test_config.py::TestConfigTestEnv::test_ignore_errors",
"tests/test_config.py::TestConfigTestEnv::test_envbindir",
"tests/test_config.py::TestConfigTestEnv::test_envbindir_jython[jython]",
"tests/test_config.py::TestConfigTestEnv::test_envbindir_jython[pypy]",
"tests/test_config.py::TestConfigTestEnv::test_envbindir_jython[pypy3]",
"tests/test_config.py::TestConfigTestEnv::test_passenv_as_multiline_list[win32]",
"tests/test_config.py::TestConfigTestEnv::test_passenv_as_multiline_list[linux2]",
"tests/test_config.py::TestConfigTestEnv::test_passenv_as_space_separated_list[win32]",
"tests/test_config.py::TestConfigTestEnv::test_passenv_as_space_separated_list[linux2]",
"tests/test_config.py::TestConfigTestEnv::test_passenv_with_factor",
"tests/test_config.py::TestConfigTestEnv::test_passenv_from_global_env",
"tests/test_config.py::TestConfigTestEnv::test_passenv_glob_from_global_env",
"tests/test_config.py::TestConfigTestEnv::test_changedir_override",
"tests/test_config.py::TestConfigTestEnv::test_install_command_setting",
"tests/test_config.py::TestConfigTestEnv::test_install_command_must_contain_packages",
"tests/test_config.py::TestConfigTestEnv::test_install_command_substitutions",
"tests/test_config.py::TestConfigTestEnv::test_pip_pre",
"tests/test_config.py::TestConfigTestEnv::test_pip_pre_cmdline_override",
"tests/test_config.py::TestConfigTestEnv::test_simple",
"tests/test_config.py::TestConfigTestEnv::test_substitution_error",
"tests/test_config.py::TestConfigTestEnv::test_substitution_defaults",
"tests/test_config.py::TestConfigTestEnv::test_substitution_notfound_issue246",
"tests/test_config.py::TestConfigTestEnv::test_substitution_notfound_issue515",
"tests/test_config.py::TestConfigTestEnv::test_substitution_nested_env_defaults",
"tests/test_config.py::TestConfigTestEnv::test_substitution_positional",
"tests/test_config.py::TestConfigTestEnv::test_substitution_noargs_issue240",
"tests/test_config.py::TestConfigTestEnv::test_substitution_double",
"tests/test_config.py::TestConfigTestEnv::test_posargs_backslashed_or_quoted",
"tests/test_config.py::TestConfigTestEnv::test_rewrite_posargs",
"tests/test_config.py::TestConfigTestEnv::test_rewrite_simple_posargs",
"tests/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_testenv[envlist0-deps0]",
"tests/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_testenv[envlist1-deps1]",
"tests/test_config.py::TestConfigTestEnv::test_take_dependencies_from_other_section",
"tests/test_config.py::TestConfigTestEnv::test_multilevel_substitution",
"tests/test_config.py::TestConfigTestEnv::test_recursive_substitution_cycle_fails",
"tests/test_config.py::TestConfigTestEnv::test_single_value_from_other_secton",
"tests/test_config.py::TestConfigTestEnv::test_factors",
"tests/test_config.py::TestConfigTestEnv::test_factor_ops",
"tests/test_config.py::TestConfigTestEnv::test_default_factors",
"tests/test_config.py::TestConfigTestEnv::test_factors_in_boolean",
"tests/test_config.py::TestConfigTestEnv::test_factors_in_setenv",
"tests/test_config.py::TestConfigTestEnv::test_factor_use_not_checked",
"tests/test_config.py::TestConfigTestEnv::test_factors_groups_touch",
"tests/test_config.py::TestConfigTestEnv::test_period_in_factor",
"tests/test_config.py::TestConfigTestEnv::test_ignore_outcome",
"tests/test_config.py::TestGlobalOptions::test_notest",
"tests/test_config.py::TestGlobalOptions::test_verbosity",
"tests/test_config.py::TestGlobalOptions::test_substitution_jenkins_default",
"tests/test_config.py::TestGlobalOptions::test_substitution_jenkins_context",
"tests/test_config.py::TestGlobalOptions::test_sdist_specification",
"tests/test_config.py::TestGlobalOptions::test_env_selection",
"tests/test_config.py::TestGlobalOptions::test_py_venv",
"tests/test_config.py::TestGlobalOptions::test_default_environments",
"tests/test_config.py::TestGlobalOptions::test_envlist_expansion",
"tests/test_config.py::TestGlobalOptions::test_envlist_cross_product",
"tests/test_config.py::TestGlobalOptions::test_envlist_multiline",
"tests/test_config.py::TestGlobalOptions::test_minversion",
"tests/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_true",
"tests/test_config.py::TestGlobalOptions::test_skip_missing_interpreters_false",
"tests/test_config.py::TestGlobalOptions::test_defaultenv_commandline",
"tests/test_config.py::TestGlobalOptions::test_defaultenv_partial_override",
"tests/test_config.py::TestHashseedOption::test_default",
"tests/test_config.py::TestHashseedOption::test_passing_integer",
"tests/test_config.py::TestHashseedOption::test_passing_string",
"tests/test_config.py::TestHashseedOption::test_passing_empty_string",
"tests/test_config.py::TestHashseedOption::test_passing_no_argument",
"tests/test_config.py::TestHashseedOption::test_setenv",
"tests/test_config.py::TestHashseedOption::test_noset",
"tests/test_config.py::TestHashseedOption::test_noset_with_setenv",
"tests/test_config.py::TestHashseedOption::test_one_random_hashseed",
"tests/test_config.py::TestHashseedOption::test_setenv_in_one_testenv",
"tests/test_config.py::TestSetenv::test_getdict_lazy",
"tests/test_config.py::TestSetenv::test_getdict_lazy_update",
"tests/test_config.py::TestSetenv::test_setenv_uses_os_environ",
"tests/test_config.py::TestSetenv::test_setenv_default_os_environ",
"tests/test_config.py::TestSetenv::test_setenv_uses_other_setenv",
"tests/test_config.py::TestSetenv::test_setenv_recursive_direct",
"tests/test_config.py::TestSetenv::test_setenv_overrides",
"tests/test_config.py::TestSetenv::test_setenv_with_envdir_and_basepython",
"tests/test_config.py::TestSetenv::test_setenv_ordering_1",
"tests/test_config.py::TestSetenv::test_setenv_cross_section_subst_issue294",
"tests/test_config.py::TestSetenv::test_setenv_cross_section_subst_twice",
"tests/test_config.py::TestSetenv::test_setenv_cross_section_mixed",
"tests/test_config.py::TestIndexServer::test_indexserver",
"tests/test_config.py::TestIndexServer::test_parse_indexserver",
"tests/test_config.py::TestIndexServer::test_multiple_homedir_relative_local_indexservers",
"tests/test_config.py::TestConfigConstSubstitutions::test_replace_pathsep_unix[:]",
"tests/test_config.py::TestConfigConstSubstitutions::test_replace_pathsep_unix[;]",
"tests/test_config.py::TestConfigConstSubstitutions::test_pathsep_regex",
"tests/test_config.py::TestParseEnv::test_parse_recreate",
"tests/test_config.py::TestCmdInvocation::test_help",
"tests/test_config.py::TestCmdInvocation::test_version",
"tests/test_config.py::TestCmdInvocation::test_listenvs",
"tests/test_config.py::TestCmdInvocation::test_listenvs_verbose_description",
"tests/test_config.py::TestCmdInvocation::test_listenvs_all",
"tests/test_config.py::TestCmdInvocation::test_listenvs_all_verbose_description",
"tests/test_config.py::TestCmdInvocation::test_listenvs_all_verbose_description_no_additional_environments",
"tests/test_config.py::TestCmdInvocation::test_config_specific_ini",
"tests/test_config.py::TestCmdInvocation::test_no_tox_ini",
"tests/test_config.py::TestCmdInvocation::test_override_workdir",
"tests/test_config.py::TestCmdInvocation::test_showconfig_with_force_dep_version",
"tests/test_config.py::test_env_spec[-e",
"tests/test_config.py::TestCommandParser::test_command_parser_for_word",
"tests/test_config.py::TestCommandParser::test_command_parser_for_posargs",
"tests/test_config.py::TestCommandParser::test_command_parser_for_multiple_words",
"tests/test_config.py::TestCommandParser::test_command_parser_for_substitution_with_spaces",
"tests/test_config.py::TestCommandParser::test_command_parser_with_complex_word_set",
"tests/test_config.py::TestCommandParser::test_command_with_runs_of_whitespace",
"tests/test_config.py::TestCommandParser::test_command_with_split_line_in_subst_arguments",
"tests/test_config.py::TestCommandParser::test_command_parsing_for_issue_10",
"tests/test_z_cmdline.py::test__resolve_pkg_doubledash",
"tests/test_z_cmdline.py::TestSession::test_make_sdist",
"tests/test_z_cmdline.py::TestSession::test_make_sdist_distshare",
"tests/test_z_cmdline.py::TestSession::test_log_pcall",
"tests/test_z_cmdline.py::TestSession::test_summary_status",
"tests/test_z_cmdline.py::TestSession::test_getvenv",
"tests/test_z_cmdline.py::test_minversion",
"tests/test_z_cmdline.py::test_notoxini_help_still_works",
"tests/test_z_cmdline.py::test_notoxini_help_ini_still_works",
"tests/test_z_cmdline.py::test_envdir_equals_toxini_errors_out",
"tests/test_z_cmdline.py::test_run_custom_install_command_error",
"tests/test_z_cmdline.py::test_unknown_interpreter_and_env",
"tests/test_z_cmdline.py::test_unknown_interpreter",
"tests/test_z_cmdline.py::test_skip_platform_mismatch",
"tests/test_z_cmdline.py::test_skip_unknown_interpreter",
"tests/test_z_cmdline.py::test_unknown_dep",
"tests/test_z_cmdline.py::test_venv_special_chars_issue252",
"tests/test_z_cmdline.py::test_unknown_environment",
"tests/test_z_cmdline.py::test_skip_sdist",
"tests/test_z_cmdline.py::test_minimal_setup_py_empty",
"tests/test_z_cmdline.py::test_minimal_setup_py_comment_only",
"tests/test_z_cmdline.py::test_minimal_setup_py_non_functional",
"tests/test_z_cmdline.py::test_sdist_fails",
"tests/test_z_cmdline.py::test_package_install_fails",
"tests/test_z_cmdline.py::TestToxRun::test_toxuone_env",
"tests/test_z_cmdline.py::TestToxRun::test_different_config_cwd",
"tests/test_z_cmdline.py::TestToxRun::test_json",
"tests/test_z_cmdline.py::test_develop",
"tests/test_z_cmdline.py::test_usedevelop",
"tests/test_z_cmdline.py::test_usedevelop_mixed",
"tests/test_z_cmdline.py::test_test_usedevelop[.]",
"tests/test_z_cmdline.py::test_test_usedevelop[src]",
"tests/test_z_cmdline.py::test_alwayscopy",
"tests/test_z_cmdline.py::test_alwayscopy_default",
"tests/test_z_cmdline.py::test_test_piphelp",
"tests/test_z_cmdline.py::test_notest",
"tests/test_z_cmdline.py::test_PYC",
"tests/test_z_cmdline.py::test_env_VIRTUALENV_PYTHON",
"tests/test_z_cmdline.py::test_sdistonly",
"tests/test_z_cmdline.py::test_separate_sdist_no_sdistfile",
"tests/test_z_cmdline.py::test_separate_sdist",
"tests/test_z_cmdline.py::test_sdist_latest",
"tests/test_z_cmdline.py::test_installpkg",
"tests/test_z_cmdline.py::test_envsitepackagesdir",
"tests/test_z_cmdline.py::test_envsitepackagesdir_skip_missing_issue280",
"tests/test_z_cmdline.py::test_verbosity[]",
"tests/test_z_cmdline.py::test_verbosity[-v]",
"tests/test_z_cmdline.py::test_verbosity[-vv]",
"tests/test_z_cmdline.py::test_envtmpdir"
]
| []
| MIT License | 1,648 | [
"tox/__init__.py",
"tox/config.py",
"tox/session.py",
"CHANGELOG"
]
| [
"tox/__init__.py",
"tox/config.py",
"tox/session.py",
"CHANGELOG"
]
|
|
jboss-dockerfiles__dogen-196 | 611898a32fca936d5a45368f049c1e3f74ea3c2f | 2017-09-04 10:31:40 | 611898a32fca936d5a45368f049c1e3f74ea3c2f | diff --git a/dogen/generator.py b/dogen/generator.py
index 1106f49..3a13051 100644
--- a/dogen/generator.py
+++ b/dogen/generator.py
@@ -232,13 +232,24 @@ class Generator(object):
if not self.cfg.get('labels'):
self.cfg['labels'] = []
+ labels = {}
+
+ for label in self.cfg.get('labels'):
+ labels[label['name']] = label['value']
+
# https://github.com/jboss-dockerfiles/dogen/issues/129
# https://github.com/jboss-dockerfiles/dogen/issues/137
for label in ['maintainer', 'description']:
value = self.cfg.get(label)
- if value:
+ if value and not label in labels:
self.cfg['labels'].append({'name': label, 'value': value})
+ labels[label] = value
+
+ # https://github.com/jboss-dockerfiles/dogen/issues/195
+ if 'summary' not in labels:
+ if 'description' in labels:
+ self.cfg['labels'].append({'name': 'summary', 'value': labels.get('description')})
if self.template:
template_file = self.template
| Set summary label to value provided in description key
If the `summary` label is not defined, its value should be set to value of the `description` key. If it's not provided, summary label should not be set. | jboss-dockerfiles/dogen | diff --git a/tests/test_dockerfile.py b/tests/test_dockerfile.py
index 3ab2885..9f34741 100644
--- a/tests/test_dockerfile.py
+++ b/tests/test_dockerfile.py
@@ -170,7 +170,7 @@ class TestDockerfile(unittest.TestCase):
generator.configure()
generator.render_from_template()
- self.assertEqual(generator.cfg['labels'], [{'name': 'description', 'value': 'This is a nice image'}])
+ self.assertEqual(generator.cfg['labels'], [{'name': 'description', 'value': 'This is a nice image'}, {'name': 'summary', 'value': 'This is a nice image'}])
with open(os.path.join(self.target, "Dockerfile"), "r") as f:
dockerfile = f.read()
| {
"commit_name": "merge_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": 2
},
"num_modified_files": 1
} | 2.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",
"pytest-cov",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | certifi==2025.1.31
charset-normalizer==3.4.1
colorlog==6.9.0
coverage==7.8.0
docopt==0.6.2
-e git+https://github.com/jboss-dockerfiles/dogen.git@611898a32fca936d5a45368f049c1e3f74ea3c2f#egg=dogen
exceptiongroup==1.2.2
idna==3.10
iniconfig==2.1.0
Jinja2==3.1.6
MarkupSafe==3.0.2
mock==5.2.0
packaging==24.2
pluggy==1.5.0
pykwalify==1.8.0
pytest==8.3.5
pytest-cov==6.0.0
python-dateutil==2.9.0.post0
PyYAML==6.0.2
requests==2.32.3
ruamel.yaml==0.18.10
ruamel.yaml.clib==0.2.12
six==1.17.0
tomli==2.2.1
urllib3==2.3.0
| name: dogen
channels:
- defaults
- https://repo.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
- colorlog==6.9.0
- coverage==7.8.0
- docopt==0.6.2
- exceptiongroup==1.2.2
- idna==3.10
- iniconfig==2.1.0
- jinja2==3.1.6
- markupsafe==3.0.2
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- pykwalify==1.8.0
- pytest==8.3.5
- pytest-cov==6.0.0
- python-dateutil==2.9.0.post0
- pyyaml==6.0.2
- requests==2.32.3
- ruamel-yaml==0.18.10
- ruamel-yaml-clib==0.2.12
- six==1.17.0
- tomli==2.2.1
- urllib3==2.3.0
prefix: /opt/conda/envs/dogen
| [
"tests/test_dockerfile.py::TestDockerfile::test_generating_description_label"
]
| []
| [
"tests/test_dockerfile.py::TestDockerfile::test_debug_port",
"tests/test_dockerfile.py::TestDockerfile::test_default_cmd_user",
"tests/test_dockerfile.py::TestDockerfile::test_generating_env_variables",
"tests/test_dockerfile.py::TestDockerfile::test_generating_maintainer_label",
"tests/test_dockerfile.py::TestDockerfile::test_set_cmd",
"tests/test_dockerfile.py::TestDockerfile::test_set_cmd_user",
"tests/test_dockerfile.py::TestDockerfile::test_set_entrypoint",
"tests/test_dockerfile.py::TestDockerfile::test_volumes"
]
| []
| MIT License | 1,649 | [
"dogen/generator.py"
]
| [
"dogen/generator.py"
]
|
|
pre-commit__pre-commit-602 | ef8347cf2dedfd818f7a170f8461131fb75223dc | 2017-09-04 21:51:16 | 3e507bf8bdb601bcf2e15bbe7cab76a970bbf1ec | asottile: Cool, I have some plans to do some larger changes and get to "v1.0.0", I think I'll wait to merge this until I'm ready to do that -- maybe a few days. | diff --git a/.travis.yml b/.travis.yml
index e84d8cc..8f91d70 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -28,4 +28,4 @@ after_success: coveralls
cache:
directories:
- $HOME/.cache/pip
- - $HOME/.pre-commit
+ - $HOME/.cache/pre-commit
diff --git a/appveyor.yml b/appveyor.yml
index 013e142..ddb9af3 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -23,4 +23,4 @@ test_script: tox
cache:
- '%LOCALAPPDATA%\pip\cache'
- - '%USERPROFILE%\.pre-commit'
+ - '%USERPROFILE%\.cache\pre-commit'
diff --git a/pre_commit/commands/clean.py b/pre_commit/commands/clean.py
index 8cea6fc..75d0acc 100644
--- a/pre_commit/commands/clean.py
+++ b/pre_commit/commands/clean.py
@@ -8,7 +8,9 @@ from pre_commit.util import rmtree
def clean(runner):
- if os.path.exists(runner.store.directory):
- rmtree(runner.store.directory)
- output.write_line('Cleaned {}.'.format(runner.store.directory))
+ legacy_path = os.path.expanduser('~/.pre-commit')
+ for directory in (runner.store.directory, legacy_path):
+ if os.path.exists(directory):
+ rmtree(directory)
+ output.write_line('Cleaned {}.'.format(directory))
return 0
diff --git a/pre_commit/error_handler.py b/pre_commit/error_handler.py
index b248f93..76662e9 100644
--- a/pre_commit/error_handler.py
+++ b/pre_commit/error_handler.py
@@ -28,10 +28,11 @@ def _log_and_exit(msg, exc, formatted):
_to_bytes(exc), b'\n',
))
output.write(error_msg)
- output.write_line('Check the log at ~/.pre-commit/pre-commit.log')
store = Store()
store.require_created()
- with open(os.path.join(store.directory, 'pre-commit.log'), 'wb') as log:
+ log_path = os.path.join(store.directory, 'pre-commit.log')
+ output.write_line('Check the log at {}'.format(log_path))
+ with open(log_path, 'wb') as log:
output.write(error_msg, stream=log)
output.write_line(formatted, stream=log)
raise SystemExit(1)
diff --git a/pre_commit/store.py b/pre_commit/store.py
index 263b315..3262bda 100644
--- a/pre_commit/store.py
+++ b/pre_commit/store.py
@@ -29,9 +29,9 @@ def _get_default_directory():
`Store.get_default_directory` can be mocked in tests and
`_get_default_directory` can be tested.
"""
- return os.environ.get(
- 'PRE_COMMIT_HOME',
- os.path.join(os.path.expanduser('~'), '.pre-commit'),
+ return os.environ.get('PRE_COMMIT_HOME') or os.path.join(
+ os.environ.get('XDG_CACHE_HOME') or os.path.expanduser('~/.cache'),
+ 'pre-commit',
)
| pre-commit should meet the XDG Base Directory Specification
XDG Base Directory Specification is quite common now. Just `ls ~/.cache ~/.config ~/.local` to realize it.
I think `~/.pre-commit` should be moved to `$XDG_CACHE_HOME` or `$HOME/.cache`
https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html | pre-commit/pre-commit | diff --git a/tests/commands/clean_test.py b/tests/commands/clean_test.py
index bdbdc99..fddd444 100644
--- a/tests/commands/clean_test.py
+++ b/tests/commands/clean_test.py
@@ -2,18 +2,35 @@ from __future__ import unicode_literals
import os.path
+import mock
+import pytest
+
from pre_commit.commands.clean import clean
from pre_commit.util import rmtree
-def test_clean(runner_with_mocked_store):
[email protected](autouse=True)
+def fake_old_dir(tempdir_factory):
+ fake_old_dir = tempdir_factory.get()
+
+ def _expanduser(path, *args, **kwargs):
+ assert path == '~/.pre-commit'
+ return fake_old_dir
+
+ with mock.patch.object(os.path, 'expanduser', side_effect=_expanduser):
+ yield fake_old_dir
+
+
+def test_clean(runner_with_mocked_store, fake_old_dir):
+ assert os.path.exists(fake_old_dir)
assert os.path.exists(runner_with_mocked_store.store.directory)
clean(runner_with_mocked_store)
+ assert not os.path.exists(fake_old_dir)
assert not os.path.exists(runner_with_mocked_store.store.directory)
def test_clean_empty(runner_with_mocked_store):
- """Make sure clean succeeds when we the directory doesn't exist."""
+ """Make sure clean succeeds when the directory doesn't exist."""
rmtree(runner_with_mocked_store.store.directory)
assert not os.path.exists(runner_with_mocked_store.store.directory)
clean(runner_with_mocked_store)
diff --git a/tests/error_handler_test.py b/tests/error_handler_test.py
index bdc54b6..d6eaf50 100644
--- a/tests/error_handler_test.py
+++ b/tests/error_handler_test.py
@@ -81,12 +81,12 @@ def test_log_and_exit(cap_out, mock_out_store_directory):
)
printed = cap_out.get()
+ log_file = os.path.join(mock_out_store_directory, 'pre-commit.log')
assert printed == (
'msg: FatalError: hai\n'
- 'Check the log at ~/.pre-commit/pre-commit.log\n'
+ 'Check the log at {}\n'.format(log_file)
)
- log_file = os.path.join(mock_out_store_directory, 'pre-commit.log')
assert os.path.exists(log_file)
contents = io.open(log_file).read()
assert contents == (
@@ -102,6 +102,7 @@ def test_error_handler_non_ascii_exception(mock_out_store_directory):
def test_error_handler_no_tty(tempdir_factory):
+ pre_commit_home = tempdir_factory.get()
output = cmd_output_mocked_pre_commit_home(
sys.executable, '-c',
'from __future__ import unicode_literals\n'
@@ -110,8 +111,10 @@ def test_error_handler_no_tty(tempdir_factory):
' raise ValueError("\\u2603")\n',
retcode=1,
tempdir_factory=tempdir_factory,
+ pre_commit_home=pre_commit_home,
)
+ log_file = os.path.join(pre_commit_home, 'pre-commit.log')
assert output[1].replace('\r', '') == (
'An unexpected error has occurred: ValueError: ☃\n'
- 'Check the log at ~/.pre-commit/pre-commit.log\n'
+ 'Check the log at {}\n'.format(log_file)
)
diff --git a/tests/main_test.py b/tests/main_test.py
index 4348b8c..29c9ea2 100644
--- a/tests/main_test.py
+++ b/tests/main_test.py
@@ -2,6 +2,7 @@ from __future__ import absolute_import
from __future__ import unicode_literals
import argparse
+import os.path
import mock
import pytest
@@ -121,10 +122,11 @@ def test_expected_fatal_error_no_git_repo(
with cwd(tempdir_factory.get()):
with pytest.raises(SystemExit):
main.main([])
+ log_file = os.path.join(mock_out_store_directory, 'pre-commit.log')
assert cap_out.get() == (
'An error has occurred: FatalError: git failed. '
'Is it installed, and are you in a Git repository directory?\n'
- 'Check the log at ~/.pre-commit/pre-commit.log\n'
+ 'Check the log at {}\n'.format(log_file)
)
diff --git a/tests/store_test.py b/tests/store_test.py
index 106a464..718f24d 100644
--- a/tests/store_test.py
+++ b/tests/store_test.py
@@ -29,7 +29,15 @@ def test_our_session_fixture_works():
def test_get_default_directory_defaults_to_home():
# Not we use the module level one which is not mocked
ret = _get_default_directory()
- assert ret == os.path.join(os.path.expanduser('~'), '.pre-commit')
+ assert ret == os.path.join(os.path.expanduser('~/.cache'), 'pre-commit')
+
+
+def test_adheres_to_xdg_specification():
+ with mock.patch.dict(
+ os.environ, {'XDG_CACHE_HOME': '/tmp/fakehome'},
+ ):
+ ret = _get_default_directory()
+ assert ret == os.path.join('/tmp/fakehome', 'pre-commit')
def test_uses_environment_variable_when_present():
| {
"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": 0
},
"num_modified_files": 5
} | 0.18 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aspy.yaml==1.3.0
cached-property==2.0.1
coverage==7.8.0
distlib==0.3.9
exceptiongroup==1.2.2
filelock==3.18.0
flake8==7.2.0
identify==2.6.9
iniconfig==2.1.0
mccabe==0.7.0
mock==5.2.0
nodeenv==1.9.1
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
-e git+https://github.com/pre-commit/pre-commit.git@ef8347cf2dedfd818f7a170f8461131fb75223dc#egg=pre_commit
pycodestyle==2.13.0
pyflakes==3.3.1
pytest==8.3.5
pytest-env==1.1.5
PyYAML==6.0.2
six==1.17.0
tomli==2.2.1
virtualenv==20.29.3
| name: pre-commit
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- 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:
- aspy-yaml==1.3.0
- cached-property==2.0.1
- coverage==7.8.0
- distlib==0.3.9
- exceptiongroup==1.2.2
- filelock==3.18.0
- flake8==7.2.0
- identify==2.6.9
- iniconfig==2.1.0
- mccabe==0.7.0
- mock==5.2.0
- nodeenv==1.9.1
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pytest==8.3.5
- pytest-env==1.1.5
- pyyaml==6.0.2
- six==1.17.0
- tomli==2.2.1
- virtualenv==20.29.3
prefix: /opt/conda/envs/pre-commit
| [
"tests/commands/clean_test.py::test_clean",
"tests/error_handler_test.py::test_log_and_exit",
"tests/error_handler_test.py::test_error_handler_no_tty",
"tests/main_test.py::test_expected_fatal_error_no_git_repo",
"tests/store_test.py::test_get_default_directory_defaults_to_home",
"tests/store_test.py::test_adheres_to_xdg_specification"
]
| []
| [
"tests/commands/clean_test.py::test_clean_empty",
"tests/error_handler_test.py::test_error_handler_no_exception",
"tests/error_handler_test.py::test_error_handler_fatal_error",
"tests/error_handler_test.py::test_error_handler_uncaught_error",
"tests/error_handler_test.py::test_error_handler_non_ascii_exception",
"tests/main_test.py::test_overall_help",
"tests/main_test.py::test_help_command",
"tests/main_test.py::test_help_other_command",
"tests/main_test.py::test_install_command[autoupdate]",
"tests/main_test.py::test_install_command[clean]",
"tests/main_test.py::test_install_command[install]",
"tests/main_test.py::test_install_command[install-hooks]",
"tests/main_test.py::test_install_command[run]",
"tests/main_test.py::test_install_command[sample-config]",
"tests/main_test.py::test_install_command[uninstall]",
"tests/main_test.py::test_help_cmd_in_empty_directory",
"tests/main_test.py::test_warning_on_tags_only",
"tests/store_test.py::test_our_session_fixture_works",
"tests/store_test.py::test_uses_environment_variable_when_present",
"tests/store_test.py::test_store_require_created",
"tests/store_test.py::test_store_require_created_does_not_create_twice",
"tests/store_test.py::test_does_not_recreate_if_directory_already_exists",
"tests/store_test.py::test_clone",
"tests/store_test.py::test_clone_cleans_up_on_checkout_failure",
"tests/store_test.py::test_clone_when_repo_already_exists",
"tests/store_test.py::test_require_created_when_directory_exists_but_not_db"
]
| []
| MIT License | 1,650 | [
"pre_commit/error_handler.py",
".travis.yml",
"pre_commit/commands/clean.py",
"appveyor.yml",
"pre_commit/store.py"
]
| [
"pre_commit/error_handler.py",
".travis.yml",
"pre_commit/commands/clean.py",
"appveyor.yml",
"pre_commit/store.py"
]
|
palantir__python-language-server-124 | aa8e1b2c12759470c18910c61f55ab4c6b80d344 | 2017-09-04 22:54:53 | e59167faa05a84bce7fd569a0ee477803a27a6e3 | diff --git a/pyls/language_server.py b/pyls/language_server.py
index cfd187b..ce11da6 100644
--- a/pyls/language_server.py
+++ b/pyls/language_server.py
@@ -37,7 +37,7 @@ def start_tcp_lang_server(bind_addr, port, handler_class):
log.info("Serving %s on (%s, %s)", handler_class.__name__, bind_addr, port)
server.serve_forever()
except KeyboardInterrupt:
- server.shutdown()
+ server.exit()
finally:
log.info("Shutting down")
server.server_close()
@@ -113,7 +113,7 @@ class LanguageServer(MethodJSONRPCServer):
self.shutdown()
def m_exit(self, **_kwargs):
- self.shutdown()
+ self.exit()
_RE_FIRST_CAP = re.compile('(.)([A-Z][a-z]+)')
diff --git a/pyls/plugins/pycodestyle_lint.py b/pyls/plugins/pycodestyle_lint.py
index a0ee0c7..668096d 100644
--- a/pyls/plugins/pycodestyle_lint.py
+++ b/pyls/plugins/pycodestyle_lint.py
@@ -64,12 +64,6 @@ class PyCodeStyleDiagnosticReport(pycodestyle.BaseReport):
'range': range,
'message': text,
'code': code,
- 'severity': _get_severity(code)
+ # Are style errors really ever errors?
+ 'severity': lsp.DiagnosticSeverity.Warning
})
-
-
-def _get_severity(code):
- if code[0] == 'E':
- return lsp.DiagnosticSeverity.Error
- elif code[0] == 'W':
- return lsp.DiagnosticSeverity.Warning
diff --git a/pyls/server.py b/pyls/server.py
index 9e3fcac..83f8002 100644
--- a/pyls/server.py
+++ b/pyls/server.py
@@ -14,23 +14,36 @@ class JSONRPCServer(object):
def __init__(self, rfile, wfile):
self.rfile = rfile
self.wfile = wfile
+ self._shutdown = False
- def shutdown(self):
- # TODO: we should handle this much better
+ def exit(self):
+ # Exit causes a complete exit of the server
self.rfile.close()
self.wfile.close()
+ def shutdown(self):
+ # Shutdown signals the server to stop, but not exit
+ self._shutdown = True
+ log.debug("Server shut down, awaiting exit notification")
+
def handle(self):
# VSCode wants us to keep the connection open, so let's handle messages in a loop
while True:
try:
data = self._read_message()
log.debug("Got message: %s", data)
+
+ if self._shutdown:
+ # Handle only the exit notification when we're shut down
+ jsonrpc.JSONRPCResponseManager.handle(data, {'exit': self.exit})
+ break
+
response = jsonrpc.JSONRPCResponseManager.handle(data, self)
+
if response is not None:
self._write_message(response.data)
except Exception:
- log.exception("Language server shutting down for uncaught exception")
+ log.exception("Language server exiting due to uncaught exception")
break
def call(self, method, params=None):
| Severity of linting erros
I currently really dislike the displayed errors of the linters.
If I use `pycodestyle` and `Pyflakes` I would prefer that `pycodestyle`s errors like `line too long`, `missing whitespace` could be *downgraded* to warnings or info. Obviously `Pyflakes` messages are more severe, but I still would like `pycodestyles` as an information.
I hope it can be understood what I mean. Is there a way to configure `pyls` this way? | palantir/python-language-server | diff --git a/test/test_language_server.py b/test/test_language_server.py
index 408fccc..e1641df 100644
--- a/test/test_language_server.py
+++ b/test/test_language_server.py
@@ -37,10 +37,10 @@ def client_server():
yield client, server
- try:
- client.call('shutdown')
- except:
- pass
+ client.call('shutdown')
+ response = _get_response(client)
+ assert response['result'] is None
+ client.notify('exit')
def test_initialize(client_server):
@@ -56,13 +56,6 @@ def test_initialize(client_server):
assert 'capabilities' in response['result']
-def test_file_closed(client_server):
- client, server = client_server
- client.rfile.close()
- with pytest.raises(Exception):
- _get_response(client)
-
-
def test_missing_message(client_server):
client, server = client_server
| {
"commit_name": "merge_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": 3
} | 0.5 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[test]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"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"
} | cachetools==5.5.2
chardet==5.2.0
colorama==0.4.6
configparser==7.2.0
coverage==7.8.0
distlib==0.3.9
exceptiongroup==1.2.2
filelock==3.18.0
future==1.0.0
iniconfig==2.1.0
jedi==0.19.2
json-rpc==1.15.0
packaging==24.2
parso==0.8.4
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
pytest-cov==6.0.0
-e git+https://github.com/palantir/python-language-server.git@aa8e1b2c12759470c18910c61f55ab4c6b80d344#egg=python_language_server
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
versioneer==0.29
virtualenv==20.29.3
yapf==0.43.0
| name: python-language-server
channels:
- defaults
- https://repo.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
- configparser==7.2.0
- coverage==7.8.0
- distlib==0.3.9
- exceptiongroup==1.2.2
- filelock==3.18.0
- future==1.0.0
- iniconfig==2.1.0
- jedi==0.19.2
- json-rpc==1.15.0
- packaging==24.2
- parso==0.8.4
- 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
- pytest-cov==6.0.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- versioneer==0.29
- virtualenv==20.29.3
- yapf==0.43.0
prefix: /opt/conda/envs/python-language-server
| [
"test/test_language_server.py::test_initialize",
"test/test_language_server.py::test_missing_message",
"test/test_language_server.py::test_linting"
]
| []
| []
| []
| MIT License | 1,651 | [
"pyls/language_server.py",
"pyls/server.py",
"pyls/plugins/pycodestyle_lint.py"
]
| [
"pyls/language_server.py",
"pyls/server.py",
"pyls/plugins/pycodestyle_lint.py"
]
|
|
borgbackup__borg-2998 | 2eab60ff49a4ad8f86c7dd562d8dd38eae66d70b | 2017-09-05 04:15:14 | a439fa3e720c8bb2a82496768ffcce282fb7f7b7 | diff --git a/src/borg/archive.py b/src/borg/archive.py
index 0f4c2d0f..3cb0b7cf 100644
--- a/src/borg/archive.py
+++ b/src/borg/archive.py
@@ -461,8 +461,8 @@ def save(self, name=None, comment=None, timestamp=None, additional_metadata=None
'cmdline': sys.argv,
'hostname': socket.gethostname(),
'username': getuser(),
- 'time': start.isoformat(),
- 'time_end': end.isoformat(),
+ 'time': start.strftime(ISO_FORMAT),
+ 'time_end': end.strftime(ISO_FORMAT),
'chunker_params': self.chunker_params,
}
metadata.update(additional_metadata or {})
diff --git a/src/borg/archiver.py b/src/borg/archiver.py
index 3b468db1..48b9fde7 100644
--- a/src/borg/archiver.py
+++ b/src/borg/archiver.py
@@ -1467,11 +1467,6 @@ def do_with_lock(self, args, repository):
# the encryption key (and can operate just with encrypted data).
data = repository.get(Manifest.MANIFEST_ID)
repository.put(Manifest.MANIFEST_ID, data)
- # usually, a 0 byte (open for writing) segment file would be visible in the filesystem here.
- # we write and close this file, to rather have a valid segment file on disk, before invoking the subprocess.
- # we can only do this for local repositories (with .io), though:
- if hasattr(repository, 'io'):
- repository.io.close_segment()
try:
# we exit with the return code we get from the subprocess
return subprocess.call([args.command] + args.args)
diff --git a/src/borg/constants.py b/src/borg/constants.py
index 6c13a9c9..36d6ee45 100644
--- a/src/borg/constants.py
+++ b/src/borg/constants.py
@@ -66,6 +66,12 @@
EXIT_WARNING = 1 # reached normal end of operation, but there were issues
EXIT_ERROR = 2 # terminated abruptly, did not reach end of operation
+# never use datetime.isoformat(), it is evil. always use one of these:
+# datetime.strftime(ISO_FORMAT) # output always includes .microseconds
+# datetime.strftime(ISO_FORMAT_NO_USECS) # output never includes microseconds
+ISO_FORMAT_NO_USECS = '%Y-%m-%dT%H:%M:%S'
+ISO_FORMAT = ISO_FORMAT_NO_USECS + '.%f'
+
DASHES = '-' * 78
PBKDF2_ITERATIONS = 100000
diff --git a/src/borg/helpers/manifest.py b/src/borg/helpers/manifest.py
index e92672f4..eb88c038 100644
--- a/src/borg/helpers/manifest.py
+++ b/src/borg/helpers/manifest.py
@@ -64,7 +64,7 @@ def __setitem__(self, name, info):
id, ts = info
assert isinstance(id, bytes)
if isinstance(ts, datetime):
- ts = ts.replace(tzinfo=None).isoformat()
+ ts = ts.replace(tzinfo=None).strftime(ISO_FORMAT)
assert isinstance(ts, str)
ts = ts.encode()
self._archives[name] = {b'id': id, b'time': ts}
@@ -166,7 +166,7 @@ def id_str(self):
@property
def last_timestamp(self):
- return datetime.strptime(self.timestamp, "%Y-%m-%dT%H:%M:%S.%f")
+ return parse_timestamp(self.timestamp, tzinfo=None)
@classmethod
def load(cls, repository, operations, key=None, force_tam_not_required=False):
@@ -236,11 +236,11 @@ def write(self):
self.config[b'tam_required'] = True
# self.timestamp needs to be strictly monotonically increasing. Clocks often are not set correctly
if self.timestamp is None:
- self.timestamp = datetime.utcnow().isoformat()
+ self.timestamp = datetime.utcnow().strftime(ISO_FORMAT)
else:
prev_ts = self.last_timestamp
- incremented = (prev_ts + timedelta(microseconds=1)).isoformat()
- self.timestamp = max(incremented, datetime.utcnow().isoformat())
+ incremented = (prev_ts + timedelta(microseconds=1)).strftime(ISO_FORMAT)
+ self.timestamp = max(incremented, datetime.utcnow().strftime(ISO_FORMAT))
# include checks for limits as enforced by limited unpacker (used by load())
assert len(self.archives) <= MAX_ARCHIVES
assert all(len(name) <= 255 for name in self.archives)
diff --git a/src/borg/helpers/parseformat.py b/src/borg/helpers/parseformat.py
index 25114c46..f926bbe9 100644
--- a/src/borg/helpers/parseformat.py
+++ b/src/borg/helpers/parseformat.py
@@ -137,7 +137,7 @@ def __init__(self, dt):
def __format__(self, format_spec):
if format_spec == '':
- format_spec = '%Y-%m-%dT%H:%M:%S'
+ format_spec = ISO_FORMAT_NO_USECS
return self.dt.__format__(format_spec)
diff --git a/src/borg/helpers/time.py b/src/borg/helpers/time.py
index 2d22794a..c5a5ddd8 100644
--- a/src/borg/helpers/time.py
+++ b/src/borg/helpers/time.py
@@ -2,18 +2,21 @@
import time
from datetime import datetime, timezone
+from ..constants import ISO_FORMAT, ISO_FORMAT_NO_USECS
+
def to_localtime(ts):
"""Convert datetime object from UTC to local time zone"""
return datetime(*time.localtime((ts - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds())[:6])
-def parse_timestamp(timestamp):
+def parse_timestamp(timestamp, tzinfo=timezone.utc):
"""Parse a ISO 8601 timestamp string"""
- if '.' in timestamp: # microseconds might not be present
- return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f').replace(tzinfo=timezone.utc)
- else:
- return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc)
+ fmt = ISO_FORMAT if '.' in timestamp else ISO_FORMAT_NO_USECS
+ dt = datetime.strptime(timestamp, fmt)
+ if tzinfo is not None:
+ dt = dt.replace(tzinfo=tzinfo)
+ return dt
def timestamp(s):
@@ -98,7 +101,7 @@ def isoformat_time(ts: datetime):
Format *ts* according to ISO 8601.
"""
# note: first make all datetime objects tz aware before adding %z here.
- return ts.strftime('%Y-%m-%dT%H:%M:%S.%f')
+ return ts.strftime(ISO_FORMAT)
def format_timedelta(td):
diff --git a/src/borg/repository.py b/src/borg/repository.py
index dada3c14..86b4ae9b 100644
--- a/src/borg/repository.py
+++ b/src/borg/repository.py
@@ -540,7 +540,8 @@ def rename_tmp(file):
# Log transaction in append-only mode
if self.append_only:
with open(os.path.join(self.path, 'transactions'), 'a') as log:
- print('transaction %d, UTC time %s' % (transaction_id, datetime.utcnow().isoformat()), file=log)
+ print('transaction %d, UTC time %s' % (
+ transaction_id, datetime.utcnow().strftime(ISO_FORMAT)), file=log)
# Write hints file
hints_name = 'hints.%d' % transaction_id
@@ -1176,8 +1177,6 @@ def cleanup(self, transaction_id):
count = 0
for segment, filename in self.segment_iterator(reverse=True):
if segment > transaction_id:
- if segment in self.fds:
- del self.fds[segment]
truncate_and_unlink(filename)
count += 1
else:
@@ -1234,12 +1233,6 @@ def get_write_fd(self, no_new=False, raise_full=False):
self._write_fd = SyncFile(self.segment_filename(self.segment), binary=True)
self._write_fd.write(MAGIC)
self.offset = MAGIC_LEN
- if self.segment in self.fds:
- # we may have a cached fd for a segment file we already deleted and
- # we are writing now a new segment file to same file name. get rid of
- # of the cached fd that still refers to the old file, so it will later
- # get repopulated (on demand) with a fd that refers to the new file.
- del self.fds[self.segment]
return self._write_fd
def get_fd(self, segment):
| timestamp microseconds parsing issue
Spurious failure seen in a unrelated 1.1-maint PR on py 3.4:
```
.tox/py34/lib/python3.4/site-packages/borg/archiver.py:1232: in _delete_archives
manifest.write()
.tox/py34/lib/python3.4/site-packages/borg/helpers.py:393: in write
prev_ts = self.last_timestamp
.tox/py34/lib/python3.4/site-packages/borg/helpers.py:321: in last_timestamp
return datetime.strptime(self.timestamp, "%Y-%m-%dT%H:%M:%S.%f")
E ValueError: time data '2017-09-02T16:16:34' does not match format '%Y-%m-%dT%H:%M:%S.%f'
```
Suspicion: crappy standard formatting behaviour of stdlib to only add `.uuu` for the microsecs if microsecs != 0, which then causes complications when trying to parse that. | borgbackup/borg | diff --git a/src/borg/testsuite/archiver.py b/src/borg/testsuite/archiver.py
index 1bf3ed73..6af6008f 100644
--- a/src/borg/testsuite/archiver.py
+++ b/src/borg/testsuite/archiver.py
@@ -61,8 +61,6 @@
src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
-ISO_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
-
def exec_cmd(*args, archiver=None, fork=False, exe=None, input=b'', binary_output=False, **kw):
if fork:
@@ -3037,7 +3035,7 @@ def spoof_manifest(self, repository):
'version': 1,
'archives': {},
'config': {},
- 'timestamp': (datetime.utcnow() + timedelta(days=1)).isoformat(),
+ 'timestamp': (datetime.utcnow() + timedelta(days=1)).strftime(ISO_FORMAT),
})))
repository.commit()
@@ -3049,7 +3047,7 @@ def test_fresh_init_tam_required(self):
repository.put(Manifest.MANIFEST_ID, key.encrypt(msgpack.packb({
'version': 1,
'archives': {},
- 'timestamp': (datetime.utcnow() + timedelta(days=1)).isoformat(),
+ 'timestamp': (datetime.utcnow() + timedelta(days=1)).strftime(ISO_FORMAT),
})))
repository.commit()
diff --git a/src/borg/testsuite/repository.py b/src/borg/testsuite/repository.py
index 1bec1400..e29c7d53 100644
--- a/src/borg/testsuite/repository.py
+++ b/src/borg/testsuite/repository.py
@@ -210,23 +210,6 @@ def test_sparse_delete(self):
self.repository.commit()
assert 0 not in [segment for segment, _ in self.repository.io.segment_iterator()]
- def test_uncommitted_garbage(self):
- # uncommitted garbage should be no problem, it is cleaned up automatically.
- # we just have to be careful with invalidation of cached FDs in LoggedIO.
- self.repository.put(H(0), b'foo')
- self.repository.commit()
- # write some crap to a uncommitted segment file
- last_segment = self.repository.io.get_latest_segment()
- with open(self.repository.io.segment_filename(last_segment + 1), 'wb') as f:
- f.write(MAGIC + b'crapcrapcrap')
- self.repository.close()
- # usually, opening the repo and starting a transaction should trigger a cleanup.
- self.repository = self.open()
- with self.repository:
- self.repository.put(H(0), b'bar') # this may trigger compact_segments()
- self.repository.commit()
- # the point here is that nothing blows up with an exception.
-
class RepositoryCommitTestCase(RepositoryTestCaseBase):
| {
"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": 7
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-xdist pytest-cov pytest-benchmark",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc libssl-dev openssl libacl1-dev libacl1 liblz4-dev liblz4-1 build-essential"
],
"python": "3.9",
"reqs_path": [
"requirements.d/development.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/borgbackup/borg.git@2eab60ff49a4ad8f86c7dd562d8dd38eae66d70b#egg=borgbackup
cachetools==5.5.2
chardet==5.2.0
colorama==0.4.6
coverage==7.8.0
Cython==3.0.12
distlib==0.3.9
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
iniconfig==2.1.0
msgpack-python==0.5.6
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
py-cpuinfo==9.0.0
pyproject-api==1.9.0
pytest==8.3.5
pytest-benchmark==5.1.0
pytest-cov==6.0.0
pytest-xdist==3.6.1
pyzmq==26.3.0
setuptools-scm==8.2.0
tomli==2.2.1
tox==4.25.0
typing_extensions==4.13.0
virtualenv==20.29.3
| name: borg
channels:
- defaults
- https://repo.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
- cython==3.0.12
- distlib==0.3.9
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- iniconfig==2.1.0
- msgpack-python==0.5.6
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- py-cpuinfo==9.0.0
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-benchmark==5.1.0
- pytest-cov==6.0.0
- pytest-xdist==3.6.1
- pyzmq==26.3.0
- setuptools-scm==8.2.0
- tomli==2.2.1
- tox==4.25.0
- typing-extensions==4.13.0
- virtualenv==20.29.3
prefix: /opt/conda/envs/borg
| [
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_fresh_init_tam_required"
]
| [
"src/borg/testsuite/archiver.py::test_return_codes[python]",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_check_usage",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_corrupted_manifest",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_corrupted_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_file_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_manifest",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable2",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_not_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_path",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_repository",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_chunks",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_files",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_chunks_archive",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_old_version_interfered",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_sort_option",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test1",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_consistency",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_invalid_rpc",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_max_data_size",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_rpc_exception_transport",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_corrupted_commit_segment",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_corrupted_segment",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_missing_commit_segment",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_no_commits"
]
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_put_get_delete_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_attic013_acl_bug",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_empty_repository",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_extra_chunks",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_duplicate_archive",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_item_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_metadata",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data_unencrypted",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_doesnt_leak",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::test_get_args",
"src/borg/testsuite/archiver.py::test_chunk_content_equal",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_basic",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_empty",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_strip_components",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_simple",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-both]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-both]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--no-files-cache-no_files_cache-False-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--no-files-cache-no_files_cache-False-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--no-files-cache-no_files_cache-False-both]",
"src/borg/testsuite/archiver.py::test_parse_storage_quota",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark-parser1]",
"src/borg/testsuite/archiver.py::test_help_formatting[break-lock-parser2]",
"src/borg/testsuite/archiver.py::test_help_formatting[change-passphrase-parser3]",
"src/borg/testsuite/archiver.py::test_help_formatting[check-parser4]",
"src/borg/testsuite/archiver.py::test_help_formatting[create-parser5]",
"src/borg/testsuite/archiver.py::test_help_formatting[debug",
"src/borg/testsuite/archiver.py::test_help_formatting[debug-parser16]",
"src/borg/testsuite/archiver.py::test_help_formatting[delete-parser17]",
"src/borg/testsuite/archiver.py::test_help_formatting[diff-parser18]",
"src/borg/testsuite/archiver.py::test_help_formatting[export-tar-parser19]",
"src/borg/testsuite/archiver.py::test_help_formatting[extract-parser20]",
"src/borg/testsuite/archiver.py::test_help_formatting[help-parser21]",
"src/borg/testsuite/archiver.py::test_help_formatting[info-parser22]",
"src/borg/testsuite/archiver.py::test_help_formatting[init-parser23]",
"src/borg/testsuite/archiver.py::test_help_formatting[key",
"src/borg/testsuite/archiver.py::test_help_formatting[key-parser28]",
"src/borg/testsuite/archiver.py::test_help_formatting[list-parser29]",
"src/borg/testsuite/archiver.py::test_help_formatting[mount-parser30]",
"src/borg/testsuite/archiver.py::test_help_formatting[prune-parser31]",
"src/borg/testsuite/archiver.py::test_help_formatting[recreate-parser32]",
"src/borg/testsuite/archiver.py::test_help_formatting[rename-parser33]",
"src/borg/testsuite/archiver.py::test_help_formatting[serve-parser34]",
"src/borg/testsuite/archiver.py::test_help_formatting[umount-parser35]",
"src/borg/testsuite/archiver.py::test_help_formatting[upgrade-parser36]",
"src/borg/testsuite/archiver.py::test_help_formatting[with-lock-parser37]",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[patterns-\\nFile",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[placeholders-\\nRepository",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[compression-\\nIt",
"src/borg/testsuite/repository.py::RepositoryTestCase::test1",
"src/borg/testsuite/repository.py::RepositoryTestCase::test2",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_consistency",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_consistency2",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_list",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_max_data_size",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_overwrite_in_same_transaction",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_scan",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_single_kind_transactions",
"src/borg/testsuite/repository.py::LocalRepositoryTestCase::test_sparse1",
"src/borg/testsuite/repository.py::LocalRepositoryTestCase::test_sparse2",
"src/borg/testsuite/repository.py::LocalRepositoryTestCase::test_sparse_delete",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_crash_before_compact_segments",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_crash_before_deleting_compacted_segments",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_crash_before_write_index",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_ignores_commit_tag_in_data",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_moved_deletes_are_tracked",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_replay_lock_upgrade",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_replay_lock_upgrade_old",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_replay_of_missing_index",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_shadow_index_rollback",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_shadowed_entries_are_preserved",
"src/borg/testsuite/repository.py::RepositoryAppendOnlyTestCase::test_append_only",
"src/borg/testsuite/repository.py::RepositoryAppendOnlyTestCase::test_destroy_append_only",
"src/borg/testsuite/repository.py::RepositoryFreeSpaceTestCase::test_additional_free_space",
"src/borg/testsuite/repository.py::RepositoryFreeSpaceTestCase::test_create_free_space",
"src/borg/testsuite/repository.py::QuotaTestCase::test_exceed_quota",
"src/borg/testsuite/repository.py::QuotaTestCase::test_tracking",
"src/borg/testsuite/repository.py::NonceReservation::test_commit_nonce_reservation",
"src/borg/testsuite/repository.py::NonceReservation::test_commit_nonce_reservation_asserts",
"src/borg/testsuite/repository.py::NonceReservation::test_get_free_nonce",
"src/borg/testsuite/repository.py::NonceReservation::test_get_free_nonce_asserts",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_corrupted_hints",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_deleted_hints",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_deleted_index",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_index",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_index_corrupted",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_index_corrupted_without_integrity",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_index_outside_transaction",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_subtly_corrupted_hints",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_subtly_corrupted_hints_without_integrity",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_unknown_integrity_version",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_unreadable_hints",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_unreadable_index",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_crash_before_compact",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_corrupted_commit_segment",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_corrupted_segment",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_index_too_new",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_missing_commit_segment",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_missing_index",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_missing_segment",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_no_commits",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test2",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_borg_cmd",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_consistency2",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_list",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_overwrite_in_same_transaction",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_scan",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_single_kind_transactions",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_ssh_cmd",
"src/borg/testsuite/repository.py::RemoteLegacyFree::test_legacy_free",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_crash_before_compact",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_index_too_new",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_missing_index",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_missing_segment",
"src/borg/testsuite/repository.py::RemoteLoggerTestCase::test_info_to_correct_local_child",
"src/borg/testsuite/repository.py::RemoteLoggerTestCase::test_post11_format_messages",
"src/borg/testsuite/repository.py::RemoteLoggerTestCase::test_pre11_format_messages",
"src/borg/testsuite/repository.py::RemoteLoggerTestCase::test_remote_messages_screened",
"src/borg/testsuite/repository.py::RemoteLoggerTestCase::test_stderr_messages"
]
| []
| BSD License | 1,652 | [
"src/borg/helpers/manifest.py",
"src/borg/archive.py",
"src/borg/helpers/time.py",
"src/borg/helpers/parseformat.py",
"src/borg/repository.py",
"src/borg/constants.py",
"src/borg/archiver.py"
]
| [
"src/borg/helpers/manifest.py",
"src/borg/archive.py",
"src/borg/helpers/time.py",
"src/borg/helpers/parseformat.py",
"src/borg/repository.py",
"src/borg/constants.py",
"src/borg/archiver.py"
]
|
|
OpenMined__PySyft-216 | 02ba82e94de28b2dca463f06c22c7f4df4f78dd3 | 2017-09-05 05:27:42 | 06ce023225dd613d8fb14ab2046135b93ab22376 | diff --git a/syft/tensor.py b/syft/tensor.py
index c1aa0e310e..859dd0ff4f 100644
--- a/syft/tensor.py
+++ b/syft/tensor.py
@@ -858,6 +858,19 @@ class TensorBase(object):
else:
return self.data.size
+ def cumprod(self, dim=0):
+ """Returns the cumulative product of elements in the dimension dim."""
+ if self.encrypted:
+ return NotImplemented
+ return syft.math.cumprod(self, dim)
+
+ def cumprod_(self, dim=0):
+ """calculate in-place the cumulative product of elements in the dimension dim."""
+ if self.encrypted:
+ return NotImplemented
+ self.data = syft.math.cumprod(self, dim).data
+ return self
+
def split(self, split_size, dim=0):
"""Returns tuple of tensors of equally sized tensor/chunks (if possible)"""
if self.encrypted:
| Implement Default cumprod Functionality for Base Tensor Type
**User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, cumprod() should return a new tensor. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation.
**Acceptance Criteria:**
- If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error.
- a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors.
- inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. | OpenMined/PySyft | diff --git a/tests/test_tensor.py b/tests/test_tensor.py
index fcded4a250..edd6a9d92c 100644
--- a/tests/test_tensor.py
+++ b/tests/test_tensor.py
@@ -647,6 +647,23 @@ class nonzeroTests(unittest.TestCase):
self.assertTrue(np.array_equal(t2.data, np.array([[0, 1, 1], [0, 1, 2]])))
+class cumprodTest(unittest.TestCase):
+ def testCumprod(self):
+ t1 = TensorBase(np.array([[1, 2, 3], [4, 5, 6]]))
+ t2 = TensorBase(np.array([[1.0, 2.0, 3.0], [4.0, 10.0, 18.0]]))
+ t3 = TensorBase(np.array([[1, 2, 6], [4, 20, 120]]))
+ self.assertTrue(np.equal(t1.cumprod(dim=0), t2).all())
+ self.assertTrue(np.equal(t1.cumprod(dim=1), t3).all())
+
+ def testCumprod_(self):
+ t1 = TensorBase(np.array([[1, 2, 3], [4, 5, 6]]))
+ t2 = TensorBase(np.array([[1.0, 2.0, 3.0], [4.0, 10.0, 18.0]]))
+ t3 = TensorBase(np.array([[1, 2, 6], [4, 20, 120]]))
+ self.assertTrue(np.equal(t1.cumprod_(dim=0), t2).all())
+ t1 = TensorBase(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]))
+ self.assertTrue(np.equal(t1.cumprod_(dim=1), t3).all())
+
+
class splitTests(unittest.TestCase):
def testSplit(self):
t1 = TensorBase(np.arange(8.0))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | PySyft/hydrogen | {
"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": [
"line_profiler",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y musl-dev g++ libgmp3-dev libmpfr-dev ca-certificates libmpc-dev"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | args==0.1.0
attrs==22.2.0
certifi==2021.5.30
clint==0.5.1
flake8==5.0.4
importlib-metadata==4.2.0
iniconfig==1.1.1
line-profiler==4.1.3
mccabe==0.7.0
numpy==1.19.5
packaging==21.3
phe==1.5.0
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pyRserve==1.0.4
pytest==7.0.1
pytest-flake8==1.1.1
-e git+https://github.com/OpenMined/PySyft.git@02ba82e94de28b2dca463f06c22c7f4df4f78dd3#egg=syft
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: PySyft
channels:
- defaults
- https://repo.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:
- args==0.1.0
- attrs==22.2.0
- clint==0.5.1
- flake8==5.0.4
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- line-profiler==4.1.3
- mccabe==0.7.0
- numpy==1.19.5
- packaging==21.3
- phe==1.5.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pyrserve==1.0.4
- pytest==7.0.1
- pytest-flake8==1.1.1
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/PySyft
| [
"tests/test_tensor.py::cumprodTest::testCumprod",
"tests/test_tensor.py::cumprodTest::testCumprod_"
]
| []
| [
"tests/test_tensor.py::DimTests::testAsView",
"tests/test_tensor.py::DimTests::testDimOne",
"tests/test_tensor.py::DimTests::testResize",
"tests/test_tensor.py::DimTests::testResizeAs",
"tests/test_tensor.py::DimTests::testSize",
"tests/test_tensor.py::DimTests::testView",
"tests/test_tensor.py::AddTests::testInplace",
"tests/test_tensor.py::AddTests::testScalar",
"tests/test_tensor.py::AddTests::testSimple",
"tests/test_tensor.py::CeilTests::testCeil",
"tests/test_tensor.py::CeilTests::testCeil_",
"tests/test_tensor.py::ZeroTests::testZero",
"tests/test_tensor.py::FloorTests::testFloor_",
"tests/test_tensor.py::SubTests::testInplace",
"tests/test_tensor.py::SubTests::testScalar",
"tests/test_tensor.py::SubTests::testSimple",
"tests/test_tensor.py::MaxTests::testAxis",
"tests/test_tensor.py::MaxTests::testNoDim",
"tests/test_tensor.py::MultTests::testInplace",
"tests/test_tensor.py::MultTests::testScalar",
"tests/test_tensor.py::MultTests::testSimple",
"tests/test_tensor.py::DivTests::testInplace",
"tests/test_tensor.py::DivTests::testScalar",
"tests/test_tensor.py::DivTests::testSimple",
"tests/test_tensor.py::AbsTests::testabs",
"tests/test_tensor.py::AbsTests::testabs_",
"tests/test_tensor.py::ShapeTests::testShape",
"tests/test_tensor.py::SqrtTests::testSqrt",
"tests/test_tensor.py::SqrtTests::testSqrt_",
"tests/test_tensor.py::SumTests::testDimIsNotNoneInt",
"tests/test_tensor.py::SumTests::testDimNoneInt",
"tests/test_tensor.py::EqualTests::testEqOp",
"tests/test_tensor.py::EqualTests::testEqual",
"tests/test_tensor.py::EqualTests::testIneqOp",
"tests/test_tensor.py::EqualTests::testNotEqual",
"tests/test_tensor.py::IndexTests::testIndexing",
"tests/test_tensor.py::sigmoidTests::testSigmoid",
"tests/test_tensor.py::addmm::testaddmm1d",
"tests/test_tensor.py::addmm::testaddmm2d",
"tests/test_tensor.py::addmm::testaddmm_1d",
"tests/test_tensor.py::addmm::testaddmm_2d",
"tests/test_tensor.py::addcmulTests::testaddcmul1d",
"tests/test_tensor.py::addcmulTests::testaddcmul2d",
"tests/test_tensor.py::addcmulTests::testaddcmul_1d",
"tests/test_tensor.py::addcmulTests::testaddcmul_2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_2d",
"tests/test_tensor.py::addmvTests::testaddmv",
"tests/test_tensor.py::addmvTests::testaddmv_",
"tests/test_tensor.py::addbmmTests::testaddbmm",
"tests/test_tensor.py::addbmmTests::testaddbmm_",
"tests/test_tensor.py::baddbmmTests::testbaddbmm",
"tests/test_tensor.py::baddbmmTests::testbaddbmm_",
"tests/test_tensor.py::transposeTests::testT",
"tests/test_tensor.py::transposeTests::testT_",
"tests/test_tensor.py::transposeTests::testTranspose",
"tests/test_tensor.py::transposeTests::testTranspose_",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze_",
"tests/test_tensor.py::expTests::testexp",
"tests/test_tensor.py::expTests::testexp_",
"tests/test_tensor.py::fracTests::testfrac",
"tests/test_tensor.py::fracTests::testfrac_",
"tests/test_tensor.py::rsqrtTests::testrsqrt",
"tests/test_tensor.py::rsqrtTests::testrsqrt_",
"tests/test_tensor.py::signTests::testsign",
"tests/test_tensor.py::signTests::testsign_",
"tests/test_tensor.py::numpyTests::testnumpy",
"tests/test_tensor.py::reciprocalTests::testreciprocal",
"tests/test_tensor.py::reciprocalTests::testrsqrt_",
"tests/test_tensor.py::logTests::testLog",
"tests/test_tensor.py::logTests::testLog1p",
"tests/test_tensor.py::logTests::testLog1p_",
"tests/test_tensor.py::logTests::testLog_",
"tests/test_tensor.py::clampTests::testClampFloat",
"tests/test_tensor.py::clampTests::testClampFloatInPlace",
"tests/test_tensor.py::clampTests::testClampInt",
"tests/test_tensor.py::clampTests::testClampIntInPlace",
"tests/test_tensor.py::bernoulliTests::testBernoulli",
"tests/test_tensor.py::bernoulliTests::testBernoulli_",
"tests/test_tensor.py::uniformTests::testUniform",
"tests/test_tensor.py::uniformTests::testUniform_",
"tests/test_tensor.py::fillTests::testFill_",
"tests/test_tensor.py::topkTests::testTopK",
"tests/test_tensor.py::tolistTests::testToList",
"tests/test_tensor.py::traceTests::testTrace",
"tests/test_tensor.py::roundTests::testRound",
"tests/test_tensor.py::roundTests::testRound_",
"tests/test_tensor.py::repeatTests::testRepeat",
"tests/test_tensor.py::powTests::testPow",
"tests/test_tensor.py::powTests::testPow_",
"tests/test_tensor.py::prodTests::testProd",
"tests/test_tensor.py::randomTests::testRandom_",
"tests/test_tensor.py::nonzeroTests::testNonZero",
"tests/test_tensor.py::splitTests::testSplit",
"tests/test_tensor.py::squeezeTests::testSqueeze",
"tests/test_tensor.py::expandAsTests::testExpandAs"
]
| []
| Apache License 2.0 | 1,653 | [
"syft/tensor.py"
]
| [
"syft/tensor.py"
]
|
|
pydicom__pydicom-500 | 7783dce0013448e9c1acdb1b06e4ffbe97c3d334 | 2017-09-05 09:34:53 | bef49851e7c3b70edd43cc40fc84fe905e78d5ba | pep8speaks: Hello @mrbean-bremen! Thanks for submitting the PR.
- In the file [`pydicom/tests/test_uid.py`](https://github.com/pydicom/pydicom/blob/43d2c913f18863dfff70f8a052187f422f067a0e/pydicom/tests/test_uid.py), following are the PEP8 issues :
> [Line 64:16](https://github.com/pydicom/pydicom/blob/43d2c913f18863dfff70f8a052187f422f067a0e/pydicom/tests/test_uid.py#L64): [E714](https://duckduckgo.com/?q=pep8%20E714) test for object identity should be 'is not'
> [Line 187:80](https://github.com/pydicom/pydicom/blob/43d2c913f18863dfff70f8a052187f422f067a0e/pydicom/tests/test_uid.py#L187): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (80 > 79 characters)
> [Line 190:80](https://github.com/pydicom/pydicom/blob/43d2c913f18863dfff70f8a052187f422f067a0e/pydicom/tests/test_uid.py#L190): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (81 > 79 characters)
scaramallion: Apart from that, looks good
massich: There are several things that I don't understand. First of all, I can't reproduce the error. But appart from that i don't understand the implementation of [UID's `__eq__` function](https://github.com/pydicom/pydicom/blob/7783dce0013448e9c1acdb1b06e4ffbe97c3d334/pydicom/uid.py#L63) which ends up bringing up the problems here: ` if str.__str__(self) in UID_dictionary:`
Couldn't it be easier to have an implentation of `__eq__` that looked more like this:
```py
def __eq__(self, other):
"""Return True if `self` or `self.name` equals `other`."""
if isinstance(other, UID):
return self.name == other.name
elif isinstance(other, str):
return self.name == other
else:
raise NotImplementedError
```
mrbean-bremen: First, this would not work as intended, if `self` is a predefined UID and `other` is the UID string of that uid.
Second, this would not fix the infinite recursion while accessing `self.name`.
massich: (following from [this](https://github.com/pydicom/pydicom/pull/500#discussion_r137766395) conversation)
>> And using, lambda _: 88888888888 as the new `__hash__` function is clear that I'm using a constant arbitrary value.
>
>No, we need to use the hash of an existing uid.
I still don't see it. I've to say though that at some point I recall seing somewhere that its iterated through the `UID_dictionary` but I can recall where now (and I couldn't find it).
I think that a constant value should be enough. But I might be wrong for what I just said. Anyhow if an arbitrary constant cannot be used I would make more explicit that we are testing to an arbitrary hash of an uid existing in the dictionary.
```py
def test_name_with_equal_hash(self):
 """Test that UID name works for UID with same hash as predefined UID.
This is a regression test from #499 where infinite recursion ... (little description needed)
 """
class MockedUID(UID):
def __hash__(self):
ARBITRARY_UID_HASH_CONST = hash(UID_dictionary[0])
return ARBITRARY_UID_HASH_CONST
uid = MockedUID('1.2.3')
assert uid.name == '1.2.3'
```
If declaring a constant seems overkill then: `return hash(UID_dictionary[0])` + a comment saying that any hash from a uid within UID_dictionary would do the job. (In other words a comment that convince the reader why `return 42` or `return hash('42')` is not suited)
massich: But I understand that we might be nitpicking here, and this is just a bugfix.
mrbean-bremen: @massich - is that ok for you?
massich: I would still do `hash(UID_dictionary[0])` instead of JPEGLOSSLY since it is more clear. But again, this is nitpicking.
mrbean-bremen: >I would still do hash(UID_dictionary[0]) instead of JPEGLOSSLY since it is more clear.
I didn't do this because `UID_dictionary` is in a private package and not supposed to be accessed. | diff --git a/pydicom/uid.py b/pydicom/uid.py
index 483159e47..741450672 100644
--- a/pydicom/uid.py
+++ b/pydicom/uid.py
@@ -162,15 +162,16 @@ class UID(str):
@property
def name(self):
"""Return the UID name from the UID dictionary."""
- if self in UID_dictionary:
+ uid_string = str.__str__(self)
+ if uid_string in UID_dictionary:
return UID_dictionary[self][0]
- return str.__str__(self)
+ return uid_string
@property
def type(self):
"""Return the UID type from the UID dictionary."""
- if self in UID_dictionary:
+ if str.__str__(self) in UID_dictionary:
return UID_dictionary[self][1]
return ''
@@ -178,7 +179,7 @@ class UID(str):
@property
def info(self):
"""Return the UID info from the UID dictionary."""
- if self in UID_dictionary:
+ if str.__str__(self) in UID_dictionary:
return UID_dictionary[self][2]
return ''
@@ -186,7 +187,7 @@ class UID(str):
@property
def is_retired(self):
"""Return True if the UID is retired, False otherwise or if private."""
- if self in UID_dictionary:
+ if str.__str__(self) in UID_dictionary:
return bool(UID_dictionary[self][3])
return False
| Crash with specific UIDs
The following crashes with infinite recursion under Python 2.7:
``` python
def test_name_with_equal_hash(self):
uid = UID('1.3.12.2.1107.5.2.18.41538.2017072416190348328326500')
assert uid.name == '1.3.12.2.1107.5.2.18.41538.2017072416190348328326500'
```
If accessing the name, it is checked if the UID string is one of the predefined strings.
The given UID has the same hash as a predefined UID (Basic Voice Audio Waveform Storage), and therefore the `__eq__` operator is invoked. This operator compares the UID names, what leads to the recursion.
In 0.99 and previous versions, the crash happened in `UID.__init()`, with `AttributeError: 'UID' object has no attribute 'name'` (happened in the field with SOPInstanceUID).
In Python 3, the string hash has changed, so it does not occur there, at least for this specific UID.
| pydicom/pydicom | diff --git a/pydicom/tests/test_uid.py b/pydicom/tests/test_uid.py
index f035c4cdd..2d7938b89 100644
--- a/pydicom/tests/test_uid.py
+++ b/pydicom/tests/test_uid.py
@@ -3,7 +3,7 @@
import pytest
-from pydicom.uid import UID, generate_uid, PYDICOM_ROOT_UID
+from pydicom.uid import UID, generate_uid, PYDICOM_ROOT_UID, JPEGLSLossy
class TestGenerateUID(object):
@@ -61,7 +61,6 @@ class TestUID(object):
assert not self.uid == 'Explicit VR Little Endian'
# Issue 96
assert not self.uid == 3
- assert not self.uid is None
def test_inequality(self):
"""Test that UID.__ne__ works."""
@@ -73,7 +72,6 @@ class TestUID(object):
assert self.uid != 'Explicit VR Little Endian'
# Issue 96
assert self.uid != 3
- assert self.uid is not None
def test_hash(self):
"""Test that UID.__hash_- works."""
@@ -183,6 +181,21 @@ class TestUID(object):
assert self.uid.name == 'Implicit VR Little Endian'
assert UID('1.2.840.10008.5.1.4.1.1.2').name == 'CT Image Storage'
+ def test_name_with_equal_hash(self):
+ """Test that UID name works for UID with same hash as predefined UID.
+ """
+ class MockedUID(UID):
+ # Force the UID to return the same hash as one of the
+ # uid dictionary entries (any will work).
+ # The resulting hash collision forces the usage of the `eq`
+ # operator while checking for containment in the uid dictionary
+ # (regression test for issue #499)
+ def __hash__(self):
+ return hash(JPEGLSLossy)
+
+ uid = MockedUID('1.2.3')
+ assert uid.name == '1.2.3'
+
def test_type(self):
"""Test that UID.type works."""
assert self.uid.type == 'Transfer Syntax'
| {
"commit_name": "merge_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 1
} | 0.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": [
"numpy>=1.16.0",
"pytest",
"pytest-cov"
],
"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
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
numpy==1.19.5
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/pydicom/pydicom.git@7783dce0013448e9c1acdb1b06e4ffbe97c3d334#egg=pydicom
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-cov==4.0.0
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: pydicom
channels:
- defaults
- https://repo.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
- numpy==1.19.5
- pytest-cov==4.0.0
- tomli==1.2.3
prefix: /opt/conda/envs/pydicom
| [
"pydicom/tests/test_uid.py::TestUID::test_name_with_equal_hash"
]
| []
| [
"pydicom/tests/test_uid.py::TestGenerateUID::test_generate_uid",
"pydicom/tests/test_uid.py::TestUID::test_equality",
"pydicom/tests/test_uid.py::TestUID::test_inequality",
"pydicom/tests/test_uid.py::TestUID::test_hash",
"pydicom/tests/test_uid.py::TestUID::test_str",
"pydicom/tests/test_uid.py::TestUID::test_is_implicit_vr",
"pydicom/tests/test_uid.py::TestUID::test_is_little_endian",
"pydicom/tests/test_uid.py::TestUID::test_is_deflated",
"pydicom/tests/test_uid.py::TestUID::test_is_transfer_syntax",
"pydicom/tests/test_uid.py::TestUID::test_is_compressed",
"pydicom/tests/test_uid.py::TestUID::test_is_encapsulated",
"pydicom/tests/test_uid.py::TestUID::test_name",
"pydicom/tests/test_uid.py::TestUID::test_type",
"pydicom/tests/test_uid.py::TestUID::test_info",
"pydicom/tests/test_uid.py::TestUID::test_is_retired",
"pydicom/tests/test_uid.py::TestUID::test_is_valid",
"pydicom/tests/test_uid.py::TestUID::test_is_private",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_equality",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_inequality",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_hash",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_str",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_implicit_vr",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_little_endian",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_deflated",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_transfer_syntax",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_compressed",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_encapsulated",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_name",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_type",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_info",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_retired",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_valid",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_private"
]
| []
| MIT License | 1,654 | [
"pydicom/uid.py"
]
| [
"pydicom/uid.py"
]
|
Clinical-Genomics__scout-593 | 7b2419a20dd5dbae88f21b9a2afe2c2d4ad5277f | 2017-09-05 12:38:59 | 8e1c3acd430a1f57f712aac29847e71cac8308f3 | diff --git a/scout/adapter/mongo/query.py b/scout/adapter/mongo/query.py
index 3a07b82d8..055963b99 100644
--- a/scout/adapter/mongo/query.py
+++ b/scout/adapter/mongo/query.py
@@ -114,15 +114,16 @@ class QueryHandler(object):
cadd_query = {'cadd_score': {'$gt': float(cadd)}}
logger.debug("Adding cadd_score: %s to query" % cadd)
- if query.get('cadd_inclusive') == 'yes':
+ if query.get('cadd_inclusive') == True:
cadd_query = {
'$or': [
cadd_query,
{'cadd_score': {'$exists': False}}
- ]}
+ ]}
logger.debug("Adding cadd inclusive to query")
mongo_query['$and'].append(cadd_query)
+
if query.get('genetic_models'):
models = query['genetic_models']
| CADD score filter monday-issue!
Thank you kindly for the quick inclusion of CADD score filtering! Will make a couple of our doctors very happy.
One major caveat though: the current version seems to filter out unknown CADD scores as well (similar to the unknown frequency bug)! Not intended usage..
| Clinical-Genomics/scout | diff --git a/tests/adapter/test_query.py b/tests/adapter/test_query.py
index e5aee3586..2d12aa555 100644
--- a/tests/adapter/test_query.py
+++ b/tests/adapter/test_query.py
@@ -57,7 +57,7 @@ def test_build_cadd_exclusive(adapter):
def test_build_cadd_inclusive(adapter):
case_id = 'cust000'
cadd = 10.0
- cadd_inclusive = 'yes'
+ cadd_inclusive = True
query = {'cadd_score': cadd, 'cadd_inclusive': cadd_inclusive}
mongo_query = adapter.build_query(case_id, query=query)
| {
"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
} | 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": [
"cython",
"pytest",
"pytest-flask",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt",
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | babel==2.17.0
blinker==1.9.0
cachelib==0.13.0
certifi==2025.1.31
charset-normalizer==3.4.1
click==8.1.8
coloredlogs==15.0.1
coverage==7.8.0
Cython==3.0.12
cyvcf2==0.31.1
dnspython==2.7.0
dominate==2.9.1
exceptiongroup==1.2.2
Flask==3.1.0
flask-babel==4.0.0
Flask-Bootstrap==3.3.7.1
Flask-DebugToolbar==0.16.0
Flask-Login==0.6.3
Flask-Mail==0.10.0
Flask-Markdown==0.3
Flask-OAuthlib==0.9.6
Flask-PyMongo==3.0.1
Flask-WTF==1.2.2
humanfriendly==10.0
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
intervaltree==3.1.0
invoke==2.2.0
itsdangerous==2.2.0
Jinja2==3.1.6
livereload==2.7.1
loqusdb==2.6.0
Markdown==3.7
MarkupSafe==3.0.2
mongo-adapter==0.3.3
mongomock==4.3.0
numpy==2.0.2
oauthlib==2.1.0
packaging==24.2
path==17.1.0
path.py==12.5.0
ped-parser==1.6.6
pluggy==1.5.0
pymongo==4.11.3
pytest==8.3.5
pytest-cov==6.0.0
pytest-flask==1.3.0
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.2
query-phenomizer==1.2.1
requests==2.32.3
requests-oauthlib==1.1.0
-e git+https://github.com/Clinical-Genomics/scout.git@7b2419a20dd5dbae88f21b9a2afe2c2d4ad5277f#egg=scout_browser
sentinels==1.0.0
six==1.17.0
sortedcontainers==2.4.0
tomli==2.2.1
tornado==6.4.2
urllib3==2.3.0
vcftoolbox==1.5.1
visitor==0.1.3
Werkzeug==3.1.3
WTForms==3.2.1
zipp==3.21.0
| name: scout
channels:
- defaults
- https://repo.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:
- babel==2.17.0
- blinker==1.9.0
- cachelib==0.13.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- click==8.1.8
- coloredlogs==15.0.1
- coverage==7.8.0
- cython==3.0.12
- cyvcf2==0.31.1
- dnspython==2.7.0
- dominate==2.9.1
- exceptiongroup==1.2.2
- flask==3.1.0
- flask-babel==4.0.0
- flask-bootstrap==3.3.7.1
- flask-debugtoolbar==0.16.0
- flask-login==0.6.3
- flask-mail==0.10.0
- flask-markdown==0.3
- flask-oauthlib==0.9.6
- flask-pymongo==3.0.1
- flask-wtf==1.2.2
- humanfriendly==10.0
- idna==3.10
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- intervaltree==3.1.0
- invoke==2.2.0
- itsdangerous==2.2.0
- jinja2==3.1.6
- livereload==2.7.1
- loqusdb==2.6.0
- markdown==3.7
- markupsafe==3.0.2
- mongo-adapter==0.3.3
- mongomock==4.3.0
- numpy==2.0.2
- oauthlib==2.1.0
- packaging==24.2
- path==17.1.0
- path-py==12.5.0
- ped-parser==1.6.6
- pluggy==1.5.0
- pymongo==4.11.3
- pytest==8.3.5
- pytest-cov==6.0.0
- pytest-flask==1.3.0
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==6.0.2
- query-phenomizer==1.2.1
- requests==2.32.3
- requests-oauthlib==1.1.0
- sentinels==1.0.0
- six==1.17.0
- sortedcontainers==2.4.0
- tomli==2.2.1
- tornado==6.4.2
- urllib3==2.3.0
- vcftoolbox==1.5.1
- visitor==0.1.3
- werkzeug==3.1.3
- wtforms==3.2.1
- zipp==3.21.0
prefix: /opt/conda/envs/scout
| [
"tests/adapter/test_query.py::test_build_cadd_inclusive"
]
| []
| [
"tests/adapter/test_query.py::test_build_query",
"tests/adapter/test_query.py::test_build_thousand_g_query",
"tests/adapter/test_query.py::test_build_non_existing_thousand_g",
"tests/adapter/test_query.py::test_build_cadd_exclusive",
"tests/adapter/test_query.py::test_build_thousand_g_and_cadd",
"tests/adapter/test_query.py::test_build_chrom",
"tests/adapter/test_query.py::test_build_range"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,655 | [
"scout/adapter/mongo/query.py"
]
| [
"scout/adapter/mongo/query.py"
]
|
|
pre-commit__pre-commit-605 | 8b14c6c5ae24757b0f6f60979a9ffe06039c298f | 2017-09-05 15:06:06 | 3e507bf8bdb601bcf2e15bbe7cab76a970bbf1ec | diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py
index ac418a7..8b80bef 100644
--- a/pre_commit/commands/run.py
+++ b/pre_commit/commands/run.py
@@ -36,13 +36,6 @@ def _hook_msg_start(hook, verbose):
)
-def get_changed_files(new, old):
- return cmd_output(
- 'git', 'diff', '--no-ext-diff', '--name-only',
- '{}...{}'.format(old, new),
- )[1].splitlines()
-
-
def filter_filenames_by_types(filenames, types, exclude_types):
types, exclude_types = frozenset(types), frozenset(exclude_types)
ret = []
@@ -56,7 +49,7 @@ def filter_filenames_by_types(filenames, types, exclude_types):
def get_filenames(args, include_expr, exclude_expr):
if args.origin and args.source:
getter = git.get_files_matching(
- lambda: get_changed_files(args.origin, args.source),
+ lambda: git.get_changed_files(args.origin, args.source),
)
elif args.hook_stage == 'commit-msg':
def getter(*_):
diff --git a/pre_commit/git.py b/pre_commit/git.py
index 4b519c8..cdf807b 100644
--- a/pre_commit/git.py
+++ b/pre_commit/git.py
@@ -15,6 +15,14 @@ from pre_commit.util import memoize_by_cwd
logger = logging.getLogger('pre_commit')
+def zsplit(s):
+ s = s.strip('\0')
+ if s:
+ return s.split('\0')
+ else:
+ return []
+
+
def get_root():
try:
return cmd_output('git', 'rev-parse', '--show-toplevel')[1].strip()
@@ -67,25 +75,32 @@ def get_conflicted_files():
# If they resolved the merge conflict by choosing a mesh of both sides
# this will also include the conflicted files
tree_hash = cmd_output('git', 'write-tree')[1].strip()
- merge_diff_filenames = cmd_output(
- 'git', 'diff', '--no-ext-diff',
- '-m', tree_hash, 'HEAD', 'MERGE_HEAD', '--name-only',
- )[1].splitlines()
+ merge_diff_filenames = zsplit(cmd_output(
+ 'git', 'diff', '--name-only', '--no-ext-diff', '-z',
+ '-m', tree_hash, 'HEAD', 'MERGE_HEAD',
+ )[1])
return set(merge_conflict_filenames) | set(merge_diff_filenames)
@memoize_by_cwd
def get_staged_files():
- return cmd_output(
- 'git', 'diff', '--staged', '--name-only', '--no-ext-diff',
+ return zsplit(cmd_output(
+ 'git', 'diff', '--staged', '--name-only', '--no-ext-diff', '-z',
# Everything except for D
'--diff-filter=ACMRTUXB',
- )[1].splitlines()
+ )[1])
@memoize_by_cwd
def get_all_files():
- return cmd_output('git', 'ls-files')[1].splitlines()
+ return zsplit(cmd_output('git', 'ls-files', '-z')[1])
+
+
+def get_changed_files(new, old):
+ return zsplit(cmd_output(
+ 'git', 'diff', '--name-only', '--no-ext-diff', '-z',
+ '{}...{}'.format(old, new),
+ )[1])
def get_files_matching(all_file_list_strategy):
| Non-English directories are skipped
Looks like pre-commit skips non-English directories. Please take a look at those:
* https://github.com/GolangShow/golangshow.com/commit/df0529b104739ba8d1de9182d37dfb80bbddf679
* https://travis-ci.org/GolangShow/golangshow.com/builds/271948939
A relevant bit from the full Travis build output:
```
$ pre-commit run --all-files
[…]
Trim Trailing Whitespace.................................................Failed
hookid: trailing-whitespace
Files were modified by this hook. Additional output:
Fixing public/episode/2017/04-14-096/index.html
Fixing public/episode/2016/03-31-050/index.html
[…]
Fixing public/episode/2016/09-01-072/index.html
Fixing public/episode/2015/12-29-036/index.html
The command "pre-commit run --all-files" exited with 1.
$ git status
HEAD detached at df0529b
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: "public/categories/\320\263\320\276\321\201\321\202\320\270/index.html"
modified: "public/categories/\320\263\320\276\321\201\321\202\320\270/index.xml"
modified: "public/categories/\320\270\320\275\321\202\320\265\321\200\320\262\321\214\321\216/index.html"
modified: "public/categories/\320\270\320\275\321\202\320\265\321\200\320\262\321\214\321\216/index.xml"
modified: "public/categories/\320\270\321\202\320\276\320\263\320\270/index.html"
modified: "public/categories/\320\270\321\202\320\276\320\263\320\270/index.xml"
modified: "public/categories/\320\272\320\260\320\274\320\270\320\275/index.html"
modified: "public/categories/\320\272\320\260\320\274\320\270\320\275/index.xml"
modified: "public/categories/\320\275\320\276\320\262\320\276\321\201\321\202\320\270/index.html"
modified: "public/categories/\320\275\320\276\320\262\320\276\321\201\321\202\320\270/index.xml"
modified: public/js/highlight.pack.js
modified: public/page/1/index.html
no changes added to commit (use "git add" and/or "git commit -a")
```
Those directories in `public/categories/` are `гости`, `итоги`, `камин`, `новости`, and `интервью`. | pre-commit/pre-commit | diff --git a/tests/commands/run_test.py b/tests/commands/run_test.py
index 924d097..5ed0ad8 100644
--- a/tests/commands/run_test.py
+++ b/tests/commands/run_test.py
@@ -15,7 +15,6 @@ from pre_commit.commands.install_uninstall import install
from pre_commit.commands.run import _compute_cols
from pre_commit.commands.run import _get_skips
from pre_commit.commands.run import _has_unmerged_paths
-from pre_commit.commands.run import get_changed_files
from pre_commit.commands.run import run
from pre_commit.runner import Runner
from pre_commit.util import cmd_output
@@ -501,18 +500,6 @@ def test_hook_install_failure(mock_out_store_directory, tempdir_factory):
assert '☃'.encode('UTF-8') + '²'.encode('latin1') in stdout
-def test_get_changed_files():
- files = get_changed_files(
- '78c682a1d13ba20e7cb735313b9314a74365cd3a',
- '3387edbb1288a580b37fe25225aa0b856b18ad1a',
- )
- assert files == ['CHANGELOG.md', 'setup.py']
-
- # files changed in source but not in origin should not be returned
- files = get_changed_files('HEAD~10', 'HEAD')
- assert files == []
-
-
def test_lots_of_files(mock_out_store_directory, tempdir_factory):
# windows xargs seems to have a bug, here's a regression test for
# our workaround
diff --git a/tests/git_test.py b/tests/git_test.py
index 0500a42..4f67911 100644
--- a/tests/git_test.py
+++ b/tests/git_test.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
@@ -162,3 +163,63 @@ OTHER_MERGE_MSG = MERGE_MSG + b'\tother_conflict_file\n'
def test_parse_merge_msg_for_conflicts(input, expected_output):
ret = git.parse_merge_msg_for_conflicts(input)
assert ret == expected_output
+
+
+def test_get_changed_files():
+ files = git.get_changed_files(
+ '78c682a1d13ba20e7cb735313b9314a74365cd3a',
+ '3387edbb1288a580b37fe25225aa0b856b18ad1a',
+ )
+ assert files == ['CHANGELOG.md', 'setup.py']
+
+ # files changed in source but not in origin should not be returned
+ files = git.get_changed_files('HEAD~10', 'HEAD')
+ assert files == []
+
+
[email protected](
+ ('s', 'expected'),
+ (
+ ('foo\0bar\0', ['foo', 'bar']),
+ ('foo\0', ['foo']),
+ ('', []),
+ ('foo', ['foo']),
+ ),
+)
+def test_zsplit(s, expected):
+ assert git.zsplit(s) == expected
+
+
[email protected]
+def non_ascii_repo(tmpdir):
+ repo = tmpdir.join('repo').ensure_dir()
+ with repo.as_cwd():
+ cmd_output('git', 'init', '.')
+ cmd_output('git', 'commit', '--allow-empty', '-m', 'initial commit')
+ repo.join('интервью').ensure()
+ cmd_output('git', 'add', '.')
+ cmd_output('git', 'commit', '--allow-empty', '-m', 'initial commit')
+ yield repo
+
+
+def test_all_files_non_ascii(non_ascii_repo):
+ ret = git.get_all_files()
+ assert ret == ['интервью']
+
+
+def test_staged_files_non_ascii(non_ascii_repo):
+ non_ascii_repo.join('интервью').write('hi')
+ cmd_output('git', 'add', '.')
+ assert git.get_staged_files() == ['интервью']
+
+
+def test_changed_files_non_ascii(non_ascii_repo):
+ ret = git.get_changed_files('HEAD', 'HEAD^')
+ assert ret == ['интервью']
+
+
+def test_get_conflicted_files_non_ascii(in_merge_conflict):
+ open('интервью', 'a').close()
+ cmd_output('git', 'add', '.')
+ ret = git.get_conflicted_files()
+ assert ret == {'conflict_file', 'интервью'}
| {
"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": 2
} | 0.18 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aspy.yaml==1.3.0
cached-property==2.0.1
coverage==7.8.0
distlib==0.3.9
exceptiongroup==1.2.2
filelock==3.18.0
flake8==7.2.0
identify==2.6.9
iniconfig==2.1.0
mccabe==0.7.0
mock==5.2.0
nodeenv==1.9.1
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
-e git+https://github.com/pre-commit/pre-commit.git@8b14c6c5ae24757b0f6f60979a9ffe06039c298f#egg=pre_commit
pycodestyle==2.13.0
pyflakes==3.3.1
pytest==8.3.5
pytest-env==1.1.5
PyYAML==6.0.2
six==1.17.0
tomli==2.2.1
virtualenv==20.29.3
| name: pre-commit
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- 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:
- aspy-yaml==1.3.0
- cached-property==2.0.1
- coverage==7.8.0
- distlib==0.3.9
- exceptiongroup==1.2.2
- filelock==3.18.0
- flake8==7.2.0
- identify==2.6.9
- iniconfig==2.1.0
- mccabe==0.7.0
- mock==5.2.0
- nodeenv==1.9.1
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pytest==8.3.5
- pytest-env==1.1.5
- pyyaml==6.0.2
- six==1.17.0
- tomli==2.2.1
- virtualenv==20.29.3
prefix: /opt/conda/envs/pre-commit
| [
"tests/git_test.py::test_get_changed_files",
"tests/git_test.py::test_zsplit[foo\\x00bar\\x00-expected0]",
"tests/git_test.py::test_zsplit[foo\\x00-expected1]",
"tests/git_test.py::test_zsplit[-expected2]",
"tests/git_test.py::test_zsplit[foo-expected3]",
"tests/git_test.py::test_all_files_non_ascii",
"tests/git_test.py::test_staged_files_non_ascii",
"tests/git_test.py::test_changed_files_non_ascii",
"tests/git_test.py::test_get_conflicted_files_non_ascii"
]
| [
"tests/commands/run_test.py::test_arbitrary_bytes_hook",
"tests/commands/run_test.py::test_hook_install_failure"
]
| [
"tests/commands/run_test.py::test_run_all_hooks_failing",
"tests/commands/run_test.py::test_hook_that_modifies_but_returns_zero",
"tests/commands/run_test.py::test_types_hook_repository",
"tests/commands/run_test.py::test_exclude_types_hook_repository",
"tests/commands/run_test.py::test_show_diff_on_failure",
"tests/commands/run_test.py::test_run[options0-outputs0-0-True]",
"tests/commands/run_test.py::test_run[options1-outputs1-0-True]",
"tests/commands/run_test.py::test_run[options2-outputs2-0-True]",
"tests/commands/run_test.py::test_run[options3-outputs3-1-True]",
"tests/commands/run_test.py::test_run[options4-outputs4-0-True]",
"tests/commands/run_test.py::test_run[options5-outputs5-0-True]",
"tests/commands/run_test.py::test_run[options6-outputs6-0-False]",
"tests/commands/run_test.py::test_run_output_logfile",
"tests/commands/run_test.py::test_always_run",
"tests/commands/run_test.py::test_always_run_alt_config",
"tests/commands/run_test.py::test_origin_source_error_msg[master-master-False]",
"tests/commands/run_test.py::test_origin_source_error_msg[master--True]",
"tests/commands/run_test.py::test_origin_source_error_msg[-master-True]",
"tests/commands/run_test.py::test_has_unmerged_paths[some-True]",
"tests/commands/run_test.py::test_has_unmerged_paths[-False]",
"tests/commands/run_test.py::test_merge_conflict",
"tests/commands/run_test.py::test_merge_conflict_modified",
"tests/commands/run_test.py::test_merge_conflict_resolved",
"tests/commands/run_test.py::test_compute_cols[hooks0-True-80]",
"tests/commands/run_test.py::test_compute_cols[hooks1-False-81]",
"tests/commands/run_test.py::test_compute_cols[hooks2-True-85]",
"tests/commands/run_test.py::test_compute_cols[hooks3-False-82]",
"tests/commands/run_test.py::test_get_skips[environ0-expected_output0]",
"tests/commands/run_test.py::test_get_skips[environ1-expected_output1]",
"tests/commands/run_test.py::test_get_skips[environ2-expected_output2]",
"tests/commands/run_test.py::test_get_skips[environ3-expected_output3]",
"tests/commands/run_test.py::test_get_skips[environ4-expected_output4]",
"tests/commands/run_test.py::test_get_skips[environ5-expected_output5]",
"tests/commands/run_test.py::test_get_skips[environ6-expected_output6]",
"tests/commands/run_test.py::test_skip_hook",
"tests/commands/run_test.py::test_hook_id_not_in_non_verbose_output",
"tests/commands/run_test.py::test_hook_id_in_verbose_output",
"tests/commands/run_test.py::test_multiple_hooks_same_id",
"tests/commands/run_test.py::test_non_ascii_hook_id",
"tests/commands/run_test.py::test_stdout_write_bug_py26",
"tests/commands/run_test.py::test_lots_of_files",
"tests/commands/run_test.py::test_push_hook",
"tests/commands/run_test.py::test_commit_msg_hook",
"tests/commands/run_test.py::test_local_hook_passes",
"tests/commands/run_test.py::test_local_hook_fails",
"tests/commands/run_test.py::test_error_with_unstaged_config",
"tests/commands/run_test.py::test_no_unstaged_error_with_all_files_or_files[opts0]",
"tests/commands/run_test.py::test_no_unstaged_error_with_all_files_or_files[opts1]",
"tests/commands/run_test.py::test_files_running_subdir",
"tests/commands/run_test.py::test_pass_filenames[True-hook_args0-foo.py]",
"tests/commands/run_test.py::test_pass_filenames[False-hook_args1-]",
"tests/commands/run_test.py::test_pass_filenames[True-hook_args2-some",
"tests/commands/run_test.py::test_pass_filenames[False-hook_args3-some",
"tests/git_test.py::test_get_root_at_root",
"tests/git_test.py::test_get_root_deeper",
"tests/git_test.py::test_get_root_not_git_dir",
"tests/git_test.py::test_get_staged_files_deleted",
"tests/git_test.py::test_is_not_in_merge_conflict",
"tests/git_test.py::test_is_in_merge_conflict",
"tests/git_test.py::test_cherry_pick_conflict",
"tests/git_test.py::test_get_files_matching_base",
"tests/git_test.py::test_matches_broken_symlink",
"tests/git_test.py::test_get_files_matching_total_match",
"tests/git_test.py::test_does_search_instead_of_match",
"tests/git_test.py::test_does_not_include_deleted_fileS",
"tests/git_test.py::test_exclude_removes_files",
"tests/git_test.py::test_get_conflicted_files",
"tests/git_test.py::test_get_conflicted_files_unstaged_files",
"tests/git_test.py::test_parse_merge_msg_for_conflicts[Merge"
]
| []
| MIT License | 1,656 | [
"pre_commit/git.py",
"pre_commit/commands/run.py"
]
| [
"pre_commit/git.py",
"pre_commit/commands/run.py"
]
|
|
borgbackup__borg-3002 | 9afec263c98c0cb6c733c5c451d26f1cb0a251fd | 2017-09-06 04:16:07 | a439fa3e720c8bb2a82496768ffcce282fb7f7b7 | diff --git a/src/borg/repository.py b/src/borg/repository.py
index ca55c698..dada3c14 100644
--- a/src/borg/repository.py
+++ b/src/borg/repository.py
@@ -1176,6 +1176,8 @@ def cleanup(self, transaction_id):
count = 0
for segment, filename in self.segment_iterator(reverse=True):
if segment > transaction_id:
+ if segment in self.fds:
+ del self.fds[segment]
truncate_and_unlink(filename)
count += 1
else:
@@ -1232,6 +1234,12 @@ def get_write_fd(self, no_new=False, raise_full=False):
self._write_fd = SyncFile(self.segment_filename(self.segment), binary=True)
self._write_fd.write(MAGIC)
self.offset = MAGIC_LEN
+ if self.segment in self.fds:
+ # we may have a cached fd for a segment file we already deleted and
+ # we are writing now a new segment file to same file name. get rid of
+ # of the cached fd that still refers to the old file, so it will later
+ # get repopulated (on demand) with a fd that refers to the new file.
+ del self.fds[self.segment]
return self._write_fd
def get_fd(self, segment):
| with-lock crashes with 1.1.0-rc2
I just upgraded from borgbackup-1.1.0-b3 to rc2, found an issue within minutes.
A simple example, borgbackup is version 1.1.0-rc2
> $ borgbackup --version
borgbackup 1.1.0rc2
> $ borgbackup with-lock mail-01.borg ls
[Files are listed here]
> Data integrity error: Segment entry data short read [segment 391, offset 1590]: expected 1890652, got 2497 bytes
> Traceback (most recent call last):
> File "borg/archiver.py", line 3968, in main
> File "borg/archiver.py", line 3896, in run
> File "borg/archiver.py", line 148, in wrapper
> File "borg/archiver.py", line 1677, in do_with_lock
> File "borg/repository.py", line 411, in commit
> File "borg/repository.py", line 685, in compact_segments
> File "borg/repository.py", line 1292, in iter_objects
> File "borg/repository.py", line 1373, in _read
> borg.helpers.IntegrityError: Data integrity error: Segment entry data short read [segment 391, offset 1590]: expected 1890652, got 2497 bytes
>
> Platform: Linux thor 4.8.0-1-amd64 #1 SMP Debian 4.8.5-1 (2016-10-28) x86_64
> Linux: debian stretch/sid
> Borg: 1.1.0rc2 Python: CPython 3.5.3
> PID: 31905 CWD: /data/borg-WedFriSun
> sys.argv: ['borgbackup', 'with-lock', 'mail-01.borg', 'ls']
> SSH_ORIGINAL_COMMAND: None
>
With 1.1.0-b3 it works fine.
No errors when running check
> $ borgbackup check mail-01.borg
> Enter passphrase for key /data/borg-WedFriSun/mail-01.borg:
>
| borgbackup/borg | diff --git a/src/borg/testsuite/repository.py b/src/borg/testsuite/repository.py
index e29c7d53..1bec1400 100644
--- a/src/borg/testsuite/repository.py
+++ b/src/borg/testsuite/repository.py
@@ -210,6 +210,23 @@ def test_sparse_delete(self):
self.repository.commit()
assert 0 not in [segment for segment, _ in self.repository.io.segment_iterator()]
+ def test_uncommitted_garbage(self):
+ # uncommitted garbage should be no problem, it is cleaned up automatically.
+ # we just have to be careful with invalidation of cached FDs in LoggedIO.
+ self.repository.put(H(0), b'foo')
+ self.repository.commit()
+ # write some crap to a uncommitted segment file
+ last_segment = self.repository.io.get_latest_segment()
+ with open(self.repository.io.segment_filename(last_segment + 1), 'wb') as f:
+ f.write(MAGIC + b'crapcrapcrap')
+ self.repository.close()
+ # usually, opening the repo and starting a transaction should trigger a cleanup.
+ self.repository = self.open()
+ with self.repository:
+ self.repository.put(H(0), b'bar') # this may trigger compact_segments()
+ self.repository.commit()
+ # the point here is that nothing blows up with an exception.
+
class RepositoryCommitTestCase(RepositoryTestCaseBase):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 1
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-xdist",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc libacl1-dev libacl1 libssl-dev liblz4-dev libzstd-dev build-essential pkg-config python3-pkgconfig"
],
"python": "3.9",
"reqs_path": [
"requirements.d/development.txt",
"requirements.d/docs.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.16
babel==2.17.0
-e git+https://github.com/borgbackup/borg.git@9afec263c98c0cb6c733c5c451d26f1cb0a251fd#egg=borgbackup
cachetools==5.5.2
certifi==2025.1.31
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
coverage==7.8.0
Cython==3.0.12
distlib==0.3.9
docutils==0.21.2
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
guzzle_sphinx_theme==0.7.11
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
MarkupSafe==3.0.2
msgpack-python==0.5.6
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
py-cpuinfo==9.0.0
Pygments==2.19.1
pyproject-api==1.9.0
pytest==8.3.5
pytest-benchmark==5.1.0
pytest-cov==6.0.0
pytest-xdist==3.6.1
pyzmq==26.3.0
requests==2.32.3
setuptools-scm==8.2.0
snowballstemmer==2.2.0
Sphinx==7.4.7
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
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: borg
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- babel==2.17.0
- cachetools==5.5.2
- certifi==2025.1.31
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- coverage==7.8.0
- cython==3.0.12
- distlib==0.3.9
- docutils==0.21.2
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- guzzle-sphinx-theme==0.7.11
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- markupsafe==3.0.2
- msgpack-python==0.5.6
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- py-cpuinfo==9.0.0
- pygments==2.19.1
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-benchmark==5.1.0
- pytest-cov==6.0.0
- pytest-xdist==3.6.1
- pyzmq==26.3.0
- requests==2.32.3
- setuptools-scm==8.2.0
- snowballstemmer==2.2.0
- sphinx==7.4.7
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- 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/borg
| [
"src/borg/testsuite/repository.py::LocalRepositoryTestCase::test_uncommitted_garbage"
]
| [
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test1",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_consistency",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_invalid_rpc",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_max_data_size",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_rpc_exception_transport",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_corrupted_commit_segment",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_corrupted_segment",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_missing_commit_segment",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_no_commits"
]
| [
"src/borg/testsuite/repository.py::RepositoryTestCase::test1",
"src/borg/testsuite/repository.py::RepositoryTestCase::test2",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_consistency",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_consistency2",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_list",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_max_data_size",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_overwrite_in_same_transaction",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_scan",
"src/borg/testsuite/repository.py::RepositoryTestCase::test_single_kind_transactions",
"src/borg/testsuite/repository.py::LocalRepositoryTestCase::test_sparse1",
"src/borg/testsuite/repository.py::LocalRepositoryTestCase::test_sparse2",
"src/borg/testsuite/repository.py::LocalRepositoryTestCase::test_sparse_delete",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_crash_before_compact_segments",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_crash_before_deleting_compacted_segments",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_crash_before_write_index",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_ignores_commit_tag_in_data",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_moved_deletes_are_tracked",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_replay_lock_upgrade",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_replay_lock_upgrade_old",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_replay_of_missing_index",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_shadow_index_rollback",
"src/borg/testsuite/repository.py::RepositoryCommitTestCase::test_shadowed_entries_are_preserved",
"src/borg/testsuite/repository.py::RepositoryAppendOnlyTestCase::test_append_only",
"src/borg/testsuite/repository.py::RepositoryAppendOnlyTestCase::test_destroy_append_only",
"src/borg/testsuite/repository.py::RepositoryFreeSpaceTestCase::test_additional_free_space",
"src/borg/testsuite/repository.py::RepositoryFreeSpaceTestCase::test_create_free_space",
"src/borg/testsuite/repository.py::QuotaTestCase::test_exceed_quota",
"src/borg/testsuite/repository.py::QuotaTestCase::test_tracking",
"src/borg/testsuite/repository.py::NonceReservation::test_commit_nonce_reservation",
"src/borg/testsuite/repository.py::NonceReservation::test_commit_nonce_reservation_asserts",
"src/borg/testsuite/repository.py::NonceReservation::test_get_free_nonce",
"src/borg/testsuite/repository.py::NonceReservation::test_get_free_nonce_asserts",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_corrupted_hints",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_deleted_hints",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_deleted_index",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_index",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_index_corrupted",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_index_corrupted_without_integrity",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_index_outside_transaction",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_subtly_corrupted_hints",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_subtly_corrupted_hints_without_integrity",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_unknown_integrity_version",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_unreadable_hints",
"src/borg/testsuite/repository.py::RepositoryAuxiliaryCorruptionTestCase::test_unreadable_index",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_crash_before_compact",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_corrupted_commit_segment",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_corrupted_segment",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_index_too_new",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_missing_commit_segment",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_missing_index",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_missing_segment",
"src/borg/testsuite/repository.py::RepositoryCheckTestCase::test_repair_no_commits",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test2",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_borg_cmd",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_consistency2",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_list",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_overwrite_in_same_transaction",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_scan",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_single_kind_transactions",
"src/borg/testsuite/repository.py::RemoteRepositoryTestCase::test_ssh_cmd",
"src/borg/testsuite/repository.py::RemoteLegacyFree::test_legacy_free",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_crash_before_compact",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_index_too_new",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_missing_index",
"src/borg/testsuite/repository.py::RemoteRepositoryCheckTestCase::test_repair_missing_segment",
"src/borg/testsuite/repository.py::RemoteLoggerTestCase::test_info_to_correct_local_child",
"src/borg/testsuite/repository.py::RemoteLoggerTestCase::test_post11_format_messages",
"src/borg/testsuite/repository.py::RemoteLoggerTestCase::test_pre11_format_messages",
"src/borg/testsuite/repository.py::RemoteLoggerTestCase::test_remote_messages_screened",
"src/borg/testsuite/repository.py::RemoteLoggerTestCase::test_stderr_messages"
]
| []
| BSD License | 1,657 | [
"src/borg/repository.py"
]
| [
"src/borg/repository.py"
]
|
|
theelous3__asks-34 | e4a5b42a0f02002fc18dc60c09761a3922521de3 | 2017-09-06 10:50:17 | e4a5b42a0f02002fc18dc60c09761a3922521de3 | diff --git a/asks/request.py b/asks/request.py
index 8361383..c1cfe6c 100644
--- a/asks/request.py
+++ b/asks/request.py
@@ -544,13 +544,20 @@ class Request:
except (KeyError, AttributeError):
resp_data['headers']['set-cookie'] = [str(header[1],
'utf-8')]
+
+ # check whether we should receive body according to RFC 7230
+ # https://tools.ietf.org/html/rfc7230#section-3.3.3
get_body = False
try:
if int(resp_data['headers']['content-length']) > 0:
get_body = True
except KeyError:
- if resp_data['headers']['transfer-encoding'] == 'chunked':
- get_body = True
+ try:
+ if resp_data['headers']['transfer-encoding'] == 'chunked':
+ get_body = True
+ except KeyError:
+ if resp_data['headers']['connection'] == 'close':
+ get_body = True
if get_body:
if self.callback is not None:
| KeyError: 'transfer-encoding'
```
Traceback (most recent call last):
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/asks/request.py", line 549, in _catch_response
if int(resp_data['headers']['content-length']) > 0:
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/asks/req_structs.py", line 79, in __getitem__
return self._store[key.lower()][1]
KeyError: 'content-length'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/curio/kernel.py", line 826, in _run_coro
trap = current._send(current.next_value)
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/curio/task.py", line 96, in _task_runner
return await coro
File "/home/laura/dev/discord/automoderator/automoderator/core/engine.py", line 133, in _handle_rule
await fn(ctx, **kwargs)
File "/home/laura/dev/discord/automoderator/automoderator/core/engine.py", line 175, in action_delete_message
await msg.delete()
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/curious/dataclasses/message.py", line 231, in delete
await self._bot.http.delete_message(self.channel.id, self.id)
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/curious/http/httpclient.py", line 596, in delete_message
data = await self.delete(url, "messages:{}".format(channel_id))
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/curious/http/httpclient.py", line 378, in delete
return await self.request(("DELETE", bucket), method="DELETE", path=url, *args, **kwargs)
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/curious/http/httpclient.py", line 251, in request
response = await self._make_request(*args, **kwargs)
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/curious/http/httpclient.py", line 212, in _make_request
return await self.session.request(*args, headers=headers, **kwargs)
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/asks/sessions.py", line 156, in request
sock, r = await req_obj.make_request()
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/asks/request.py", line 203, in make_request
response_obj = await self._request_io(req, req_body, hconnection)
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/asks/request.py", line 240, in _request_io
response_obj = await self._catch_response(hconnection)
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/asks/request.py", line 553, in _catch_response
if resp_data['headers']['transfer-encoding'] == 'chunked':
File "/home/laura/.local/share/virtualenvs/automoderator-nZfczLQS/lib/python3.6/site-packages/asks/req_structs.py", line 79, in __getitem__
return self._store[key.lower()][1]
KeyError: 'transfer-encoding'
```
Errors when a HTTP server sends neither a Content-Length nor a Transfer-Encoding. | theelous3/asks | diff --git a/tests/test_asks_curio.py b/tests/test_asks_curio.py
index f255e48..b504c38 100644
--- a/tests/test_asks_curio.py
+++ b/tests/test_asks_curio.py
@@ -190,6 +190,13 @@ async def test_stream():
assert len(img) == 8090
+# Test connection close without content-length and transfer-encoding
+@curio_run
+async def test_connection_close():
+ r = await asks.get('https://www.ua-region.com.ua/search/?q=rrr')
+ assert r.text
+
+
# Test callback
callback_data = b''
async def callback_example(chunk):
diff --git a/tests/test_asks_trio.py b/tests/test_asks_trio.py
index 8a87bd8..322edd3 100644
--- a/tests/test_asks_trio.py
+++ b/tests/test_asks_trio.py
@@ -193,6 +193,13 @@ async def test_stream():
assert len(img) == 8090
+# Test connection close without content-length and transfer-encoding
+@trio_run
+async def test_connection_close():
+ r = await asks.get('https://www.ua-region.com.ua/search/?q=rrr')
+ assert r.text
+
+
# Test callback
callback_data = b''
async def callback_example(chunk):
| {
"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
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "",
"pip_packages": [
"pytest",
"pylint",
"git+https://github.com/python-trio/trio.git",
"git+https://github.com/dabeaz/curio.git"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/theelous3/asks.git@e4a5b42a0f02002fc18dc60c09761a3922521de3#egg=asks
astroid==3.3.9
attrs==25.3.0
curio @ git+https://github.com/dabeaz/curio.git@148454621f9bd8dd843f591e87715415431f6979
dill==0.3.9
exceptiongroup==1.2.2
h11==0.14.0
idna==3.10
iniconfig==2.1.0
isort==6.0.1
mccabe==0.7.0
outcome==1.3.0.post0
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
pylint==3.3.6
pytest==8.3.5
sniffio==1.3.1
sortedcontainers==2.4.0
tomli==2.2.1
tomlkit==0.13.2
trio @ git+https://github.com/python-trio/trio.git@d6c4cae0e4405fc96c507bcd73e365e890c25732
typing_extensions==4.13.0
| name: asks
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- astroid==3.3.9
- attrs==25.3.0
- curio==1.6
- dill==0.3.9
- exceptiongroup==1.2.2
- h11==0.14.0
- idna==3.10
- iniconfig==2.1.0
- isort==6.0.1
- mccabe==0.7.0
- outcome==1.3.0.post0
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- pylint==3.3.6
- pytest==8.3.5
- sniffio==1.3.1
- sortedcontainers==2.4.0
- tomli==2.2.1
- tomlkit==0.13.2
- trio==0.29.0+dev
- typing-extensions==4.13.0
prefix: /opt/conda/envs/asks
| [
"tests/test_asks_curio.py::test_connection_close",
"tests/test_asks_trio.py::test_connection_close"
]
| [
"tests/test_asks_trio.py::test_http_timeout_error",
"tests/test_asks_trio.py::test_http_timeout",
"tests/test_asks_trio.py::test_hsession_smallpool",
"tests/test_asks_trio.py::test_session_stateful",
"tests/test_asks_trio.py::test_session_stateful_double",
"tests/test_asks_trio.py::test_Session_smallpool"
]
| [
"tests/test_asks_curio.py::test_https_get",
"tests/test_asks_curio.py::test_bad_www_and_schema_get",
"tests/test_asks_curio.py::test_https_get_alt",
"tests/test_asks_curio.py::test_http_get",
"tests/test_asks_curio.py::test_http_redirect",
"tests/test_asks_curio.py::test_http_max_redirect_error",
"tests/test_asks_curio.py::test_http_max_redirect",
"tests/test_asks_curio.py::test_http_timeout_error",
"tests/test_asks_curio.py::test_http_timeout",
"tests/test_asks_curio.py::test_param_dict_set",
"tests/test_asks_curio.py::test_data_dict_set",
"tests/test_asks_curio.py::test_cookie_dict_send",
"tests/test_asks_curio.py::test_header_set",
"tests/test_asks_curio.py::test_file_send_single",
"tests/test_asks_curio.py::test_file_send_double",
"tests/test_asks_curio.py::test_file_and_data_send",
"tests/test_asks_curio.py::test_json_send",
"tests/test_asks_curio.py::test_gzip",
"tests/test_asks_curio.py::test_deflate",
"tests/test_asks_curio.py::test_chunked_te",
"tests/test_asks_curio.py::test_stream",
"tests/test_asks_curio.py::test_callback",
"tests/test_asks_curio.py::test_hsession_smallpool",
"tests/test_asks_curio.py::test_session_stateful",
"tests/test_asks_curio.py::test_session_stateful_double",
"tests/test_asks_curio.py::test_Session_smallpool",
"tests/test_asks_trio.py::test_https_get",
"tests/test_asks_trio.py::test_bad_www_and_schema_get",
"tests/test_asks_trio.py::test_https_get_alt",
"tests/test_asks_trio.py::test_http_get",
"tests/test_asks_trio.py::test_http_redirect",
"tests/test_asks_trio.py::test_http_max_redirect_error",
"tests/test_asks_trio.py::test_http_max_redirect",
"tests/test_asks_trio.py::test_param_dict_set",
"tests/test_asks_trio.py::test_data_dict_set",
"tests/test_asks_trio.py::test_cookie_dict_send",
"tests/test_asks_trio.py::test_header_set",
"tests/test_asks_trio.py::test_file_send_single",
"tests/test_asks_trio.py::test_file_send_double",
"tests/test_asks_trio.py::test_file_and_data_send",
"tests/test_asks_trio.py::test_json_send",
"tests/test_asks_trio.py::test_gzip",
"tests/test_asks_trio.py::test_deflate",
"tests/test_asks_trio.py::test_chunked_te",
"tests/test_asks_trio.py::test_stream",
"tests/test_asks_trio.py::test_callback"
]
| []
| MIT License | 1,658 | [
"asks/request.py"
]
| [
"asks/request.py"
]
|
|
cloudant__python-cloudant-325 | ef15286b311f8cb222a1ddd28f78c7e87c1e9652 | 2017-09-06 12:07:57 | eda73e429f404db7c22c1ccd4c265b5c70063dae | diff --git a/CHANGES.rst b/CHANGES.rst
index c683e44..d429d65 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,5 +1,7 @@
Unreleased
==========
+- [NEW] Added API for upcoming Bluemix Identity and Access Management support for Cloudant on Bluemix. Note: IAM API key support is not yet enabled in the service.
+- [NEW] Added HTTP basic authentication support.
- [NEW] Added ``Result.all()`` convenience method.
- [NEW] Allow ``service_name`` to be specified when instantiating from a Bluemix VCAP_SERVICES environment variable.
- [IMPROVED] Updated ``posixpath.join`` references to use ``'/'.join`` when concatenating URL parts.
diff --git a/Jenkinsfile b/Jenkinsfile
index b89cb5c..2bc5d88 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -1,26 +1,48 @@
-// Define the test routine for different python versions
-def test_python(pythonVersion)
-{
+def getEnvForSuite(suiteName) {
+ // Base environment variables
+ def envVars = [
+ "CLOUDANT_ACCOUNT=$DB_USER",
+ "RUN_CLOUDANT_TESTS=1",
+ "SKIP_DB_UPDATES=1" // Disable pending resolution of case 71610
+ ]
+ // Add test suite specific environment variables
+ switch(suiteName) {
+ case 'basic':
+ envVars.add("RUN_BASIC_AUTH_TESTS=1")
+ break
+ case 'cookie':
+ break
+ case 'iam':
+ // Setting IAM_API_KEY forces tests to run using an IAM enabled client.
+ envVars.add("IAM_API_KEY=$DB_IAM_API_KEY")
+ break
+ default:
+ error("Unknown test suite environment ${suiteName}")
+ }
+ return envVars
+}
+
+def setupPythonAndTest(pythonVersion, testSuite) {
node {
// Unstash the source on this node
unstash name: 'source'
// Set up the environment and test
- withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'clientlibs-test', usernameVariable: 'DB_USER', passwordVariable: 'DB_PASSWORD']]) {
- try {
- sh """ virtualenv tmp -p /usr/local/lib/python${pythonVersion}/bin/${pythonVersion.startsWith('3') ? "python3" : "python"}
- . ./tmp/bin/activate
- echo \$DB_USER
- export RUN_CLOUDANT_TESTS=1
- export CLOUDANT_ACCOUNT=\$DB_USER
- # Temporarily disable the _db_updates tests pending resolution of case 71610
- export SKIP_DB_UPDATES=1
- pip install -r requirements.txt
- pip install -r test-requirements.txt
- pylint ./src/cloudant
- nosetests -w ./tests/unit --with-xunit"""
- } finally {
- // Load the test results
- junit 'nosetests.xml'
+ withCredentials([usernamePassword(credentialsId: 'clientlibs-test', usernameVariable: 'DB_USER', passwordVariable: 'DB_PASSWORD'),
+ string(credentialsId: 'clientlibs-test-iam', variable: 'DB_IAM_API_KEY')]) {
+ withEnv(getEnvForSuite("${testSuite}")) {
+ try {
+ sh """
+ virtualenv tmp -p /usr/local/lib/python${pythonVersion}/bin/${pythonVersion.startsWith('3') ? "python3" : "python"}
+ . ./tmp/bin/activate
+ pip install -r requirements.txt
+ pip install -r test-requirements.txt
+ pylint ./src/cloudant
+ nosetests -w ./tests/unit --with-xunit
+ """
+ } finally {
+ // Load the test results
+ junit 'nosetests.xml'
+ }
}
}
}
@@ -34,10 +56,14 @@ stage('Checkout'){
stash name: 'source'
}
}
+
stage('Test'){
- // Run tests in parallel for multiple python versions
parallel(
- Python2: {test_python('2.7.12')},
- Python3: {test_python('3.5.2')}
+ 'Python2-BASIC': { setupPythonAndTest('2.7.12', 'basic') },
+ 'Python3-BASIC': { setupPythonAndTest('3.5.2', 'basic') },
+ 'Python2-COOKIE': { setupPythonAndTest('2.7.12', 'cookie') },
+ 'Python3-COOKIE': { setupPythonAndTest('3.5.2', 'cookie') },
+ 'Python2-IAM': { setupPythonAndTest('2.7.12', 'iam') },
+ 'Python3-IAM': { setupPythonAndTest('3.5.2', 'iam') }
)
}
diff --git a/src/cloudant/_client_session.py b/src/cloudant/_client_session.py
new file mode 100644
index 0000000..289b131
--- /dev/null
+++ b/src/cloudant/_client_session.py
@@ -0,0 +1,285 @@
+#!/usr/bin/env python
+# Copyright (c) 2015, 2017 IBM Corp. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Module containing client session classes.
+"""
+import base64
+import json
+import os
+
+from requests import RequestException, Session
+
+from ._2to3 import bytes_, unicode_, url_join
+from .error import CloudantException
+
+
+class ClientSession(Session):
+ """
+ This class extends Session and provides a default timeout.
+ """
+
+ def __init__(self, username=None, password=None, session_url=None, **kwargs):
+ super(ClientSession, self).__init__()
+
+ self._username = username
+ self._password = password
+ self._session_url = session_url
+
+ self._auto_renew = kwargs.get('auto_renew', False)
+ self._timeout = kwargs.get('timeout', None)
+
+ def base64_user_pass(self):
+ """
+ Composes a basic http auth string, suitable for use with the
+ _replicator database, and other places that need it.
+
+ :returns: Basic http authentication string
+ """
+ if self._username is None or self._password is None:
+ return None
+
+ hash_ = base64.urlsafe_b64encode(bytes_("{username}:{password}".format(
+ username=self._username,
+ password=self._password
+ )))
+ return "Basic {0}".format(unicode_(hash_))
+
+ # pylint: disable=arguments-differ
+ def request(self, method, url, **kwargs):
+ """
+ Overrides ``requests.Session.request`` to set the timeout.
+ """
+ resp = super(ClientSession, self).request(
+ method, url, timeout=self._timeout, **kwargs)
+
+ return resp
+
+ def info(self):
+ """
+ Get session information.
+ """
+ if self._session_url is None:
+ return None
+
+ resp = self.get(self._session_url)
+ resp.raise_for_status()
+ return resp.json()
+
+ def set_credentials(self, username, password):
+ """
+ Set a new username and password.
+
+ :param str username: New username.
+ :param str password: New password.
+ """
+ if username is not None:
+ self._username = username
+
+ if password is not None:
+ self._password = password
+
+ def login(self):
+ """
+ No-op method - not implemented here.
+ """
+ pass
+
+ def logout(self):
+ """
+ No-op method - not implemented here.
+ """
+ pass
+
+
+class BasicSession(ClientSession):
+ """
+ This class extends ClientSession to provide basic access authentication.
+ """
+
+ def __init__(self, username, password, server_url, **kwargs):
+ super(BasicSession, self).__init__(
+ username=username,
+ password=password,
+ session_url=url_join(server_url, '_session'),
+ **kwargs)
+
+ def request(self, method, url, **kwargs):
+ """
+ Overrides ``requests.Session.request`` to provide basic access
+ authentication.
+ """
+ auth = None
+ if self._username is not None and self._password is not None:
+ auth = (self._username, self._password)
+
+ return super(BasicSession, self).request(
+ method, url, auth=auth, **kwargs)
+
+
+class CookieSession(ClientSession):
+ """
+ This class extends ClientSession and provides cookie authentication.
+ """
+
+ def __init__(self, username, password, server_url, **kwargs):
+ super(CookieSession, self).__init__(
+ username=username,
+ password=password,
+ session_url=url_join(server_url, '_session'),
+ **kwargs)
+
+ def login(self):
+ """
+ Perform cookie based user login.
+ """
+ resp = super(CookieSession, self).request(
+ 'POST',
+ self._session_url,
+ data={'name': self._username, 'password': self._password},
+ )
+ resp.raise_for_status()
+
+ def logout(self):
+ """
+ Logout cookie based user.
+ """
+ resp = super(CookieSession, self).request('DELETE', self._session_url)
+ resp.raise_for_status()
+
+ def request(self, method, url, **kwargs):
+ """
+ Overrides ``requests.Session.request`` to renew the cookie and then
+ retry the original request (if required).
+ """
+ resp = super(CookieSession, self).request(method, url, **kwargs)
+
+ if not self._auto_renew:
+ return resp
+
+ is_expired = any((
+ resp.status_code == 403 and
+ resp.json().get('error') == 'credentials_expired',
+ resp.status_code == 401
+ ))
+
+ if is_expired:
+ self.login()
+ resp = super(CookieSession, self).request(method, url, **kwargs)
+
+ return resp
+
+
+class IAMSession(ClientSession):
+ """
+ This class extends ClientSession and provides IAM authentication.
+ """
+
+ def __init__(self, api_key, server_url, **kwargs):
+ super(IAMSession, self).__init__(
+ session_url=url_join(server_url, '_iam_session'),
+ **kwargs)
+
+ self._api_key = api_key
+ self._token_url = os.environ.get(
+ 'IAM_TOKEN_URL', 'https://iam.bluemix.net/oidc/token')
+
+ def login(self):
+ """
+ Perform IAM cookie based user login.
+ """
+ access_token = self._get_access_token()
+ try:
+ super(IAMSession, self).request(
+ 'POST',
+ self._session_url,
+ headers={'Content-Type': 'application/json'},
+ data=json.dumps({'access_token': access_token})
+ ).raise_for_status()
+
+ except RequestException:
+ raise CloudantException(
+ 'Failed to exchange IAM token with Cloudant')
+
+ def logout(self):
+ """
+ Logout IAM cookie based user.
+ """
+ self.cookies.clear()
+
+ def request(self, method, url, **kwargs):
+ """
+ Overrides ``requests.Session.request`` to renew the IAM cookie
+ and then retry the original request (if required).
+ """
+ # The CookieJar API prevents callers from getting an individual Cookie
+ # object by name.
+ # We are forced to use the only exposed method of discarding expired
+ # cookies from the CookieJar. Internally this involves iterating over
+ # the entire CookieJar and calling `.is_expired()` on each Cookie
+ # object.
+ self.cookies.clear_expired_cookies()
+
+ if self._auto_renew and 'IAMSession' not in self.cookies.keys():
+ self.login()
+
+ resp = super(IAMSession, self).request(method, url, **kwargs)
+
+ if not self._auto_renew:
+ return resp
+
+ if resp.status_code == 401:
+ self.login()
+ resp = super(IAMSession, self).request(method, url, **kwargs)
+
+ return resp
+
+ # pylint: disable=arguments-differ, unused-argument
+ def set_credentials(self, username, api_key):
+ """
+ Set a new IAM API key.
+
+ :param str username: Username parameter is unused.
+ :param str api_key: New IAM API key.
+ """
+ if api_key is not None:
+ self._api_key = api_key
+
+ def _get_access_token(self):
+ """
+ Get IAM access token using API key.
+ """
+ err = 'Failed to contact IAM token service'
+ try:
+ resp = super(IAMSession, self).request(
+ 'POST',
+ self._token_url,
+ auth=('bx', 'bx'), # required for user API keys
+ headers={'Accepts': 'application/json'},
+ data={
+ 'grant_type': 'urn:ibm:params:oauth:grant-type:apikey',
+ 'response_type': 'cloud_iam',
+ 'apikey': self._api_key
+ }
+ )
+ err = resp.json().get('errorMessage', err)
+ resp.raise_for_status()
+
+ return resp.json()['access_token']
+
+ except KeyError:
+ raise CloudantException('Invalid response from IAM token service')
+
+ except RequestException:
+ raise CloudantException(err)
diff --git a/src/cloudant/_common_util.py b/src/cloudant/_common_util.py
index 05e3bd3..e44df3d 100644
--- a/src/cloudant/_common_util.py
+++ b/src/cloudant/_common_util.py
@@ -17,14 +17,12 @@ Module containing miscellaneous classes, functions, and constants used
throughout the library.
"""
-import os
import sys
import platform
from collections import Sequence
import json
-from requests import RequestException, Session
-from ._2to3 import LONGTYPE, STRTYPE, NONETYPE, UNITYPE, iteritems_, url_join
+from ._2to3 import LONGTYPE, STRTYPE, NONETYPE, UNITYPE, iteritems_
from .error import CloudantArgumentError, CloudantException
# Library Constants
@@ -290,211 +288,6 @@ class _Code(str):
return str.__new__(cls, code)
-class ClientSession(Session):
- """
- This class extends Session and provides a default timeout.
- """
-
- def __init__(self, **kwargs):
- super(ClientSession, self).__init__()
- self._timeout = kwargs.get('timeout', None)
-
- def request(self, method, url, **kwargs): # pylint: disable=W0221
- """
- Overrides ``requests.Session.request`` to set the timeout.
- """
- resp = super(ClientSession, self).request(
- method, url, timeout=self._timeout, **kwargs)
-
- return resp
-
-
-class CookieSession(ClientSession):
- """
- This class extends ClientSession and provides cookie authentication.
- """
-
- def __init__(self, username, password, server_url, **kwargs):
- super(CookieSession, self).__init__(**kwargs)
- self._username = username
- self._password = password
- self._auto_renew = kwargs.get('auto_renew', False)
- self._session_url = url_join(server_url, '_session')
-
- def info(self):
- """
- Get cookie based login user information.
- """
- resp = self.get(self._session_url)
- resp.raise_for_status()
-
- return resp.json()
-
- def login(self):
- """
- Perform cookie based user login.
- """
- resp = super(CookieSession, self).request(
- 'POST',
- self._session_url,
- data={'name': self._username, 'password': self._password},
- )
- resp.raise_for_status()
-
- def logout(self):
- """
- Logout cookie based user.
- """
- resp = super(CookieSession, self).request('DELETE', self._session_url)
- resp.raise_for_status()
-
- def request(self, method, url, **kwargs): # pylint: disable=W0221
- """
- Overrides ``requests.Session.request`` to renew the cookie and then
- retry the original request (if required).
- """
- resp = super(CookieSession, self).request(method, url, **kwargs)
-
- if not self._auto_renew:
- return resp
-
- is_expired = any((
- resp.status_code == 403 and
- resp.json().get('error') == 'credentials_expired',
- resp.status_code == 401
- ))
-
- if is_expired:
- self.login()
- resp = super(CookieSession, self).request(method, url, **kwargs)
-
- return resp
-
- def set_credentials(self, username, password):
- """
- Set a new username and password.
-
- :param str username: New username.
- :param str password: New password.
- """
- if username is not None:
- self._username = username
-
- if password is not None:
- self._password = password
-
-
-class IAMSession(ClientSession):
- """
- This class extends ClientSession and provides IAM authentication.
- """
-
- def __init__(self, api_key, server_url, **kwargs):
- super(IAMSession, self).__init__(**kwargs)
- self._api_key = api_key
- self._auto_renew = kwargs.get('auto_renew', False)
- self._session_url = url_join(server_url, '_iam_session')
- self._token_url = os.environ.get(
- 'IAM_TOKEN_URL', 'https://iam.bluemix.net/oidc/token')
-
- def info(self):
- """
- Get IAM cookie based login user information.
- """
- resp = self.get(self._session_url)
- resp.raise_for_status()
-
- return resp.json()
-
- def login(self):
- """
- Perform IAM cookie based user login.
- """
- access_token = self._get_access_token()
- try:
- super(IAMSession, self).request(
- 'POST',
- self._session_url,
- headers={'Content-Type': 'application/json'},
- data=json.dumps({'access_token': access_token})
- ).raise_for_status()
-
- except RequestException:
- raise CloudantException(
- 'Failed to exchange IAM token with Cloudant')
-
- def logout(self):
- """
- Logout IAM cookie based user.
- """
- self.cookies.clear()
-
- def request(self, method, url, **kwargs): # pylint: disable=W0221
- """
- Overrides ``requests.Session.request`` to renew the IAM cookie
- and then retry the original request (if required).
- """
- # The CookieJar API prevents callers from getting an individual Cookie
- # object by name.
- # We are forced to use the only exposed method of discarding expired
- # cookies from the CookieJar. Internally this involves iterating over
- # the entire CookieJar and calling `.is_expired()` on each Cookie
- # object.
- self.cookies.clear_expired_cookies()
-
- if self._auto_renew and 'IAMSession' not in self.cookies.keys():
- self.login()
-
- resp = super(IAMSession, self).request(method, url, **kwargs)
-
- if not self._auto_renew:
- return resp
-
- if resp.status_code == 401:
- self.login()
- resp = super(IAMSession, self).request(method, url, **kwargs)
-
- return resp
-
- def set_credentials(self, username, api_key):
- """
- Set a new IAM API key.
-
- :param str username: Username parameter is unused.
- :param str api_key: New IAM API key.
- """
- if api_key is not None:
- self._api_key = api_key
-
- def _get_access_token(self):
- """
- Get IAM access token using API key.
- """
- err = 'Failed to contact IAM token service'
- try:
- resp = super(IAMSession, self).request(
- 'POST',
- self._token_url,
- auth=('bx', 'bx'), # required for user API keys
- headers={'Accepts': 'application/json'},
- data={
- 'grant_type': 'urn:ibm:params:oauth:grant-type:apikey',
- 'response_type': 'cloud_iam',
- 'apikey': self._api_key
- }
- )
- err = resp.json().get('errorMessage', err)
- resp.raise_for_status()
-
- return resp.json()['access_token']
-
- except KeyError:
- raise CloudantException('Invalid response from IAM token service')
-
- except RequestException:
- raise CloudantException(err)
-
-
class CloudFoundryService(object):
""" Manages Cloud Foundry service configuration. """
diff --git a/src/cloudant/client.py b/src/cloudant/client.py
index ce7d493..abf3f5f 100755
--- a/src/cloudant/client.py
+++ b/src/cloudant/client.py
@@ -16,10 +16,14 @@
Top level API module that maps to a Cloudant or CouchDB client connection
instance.
"""
-import base64
import json
-from ._2to3 import bytes_, unicode_
+from ._client_session import (
+ BasicSession,
+ ClientSession,
+ CookieSession,
+ IAMSession
+)
from .database import CloudantDatabase, CouchDatabase
from .feed import Feed, InfiniteFeed
from .error import (
@@ -29,10 +33,9 @@ from .error import (
from ._common_util import (
USER_AGENT,
append_response_error_content,
- ClientSession,
CloudFoundryService,
- CookieSession,
- IAMSession)
+ )
+
class CouchDB(dict):
"""
@@ -67,6 +70,8 @@ class CouchDB(dict):
`Requests library timeout argument
<http://docs.python-requests.org/en/master/user/quickstart/#timeouts>`_.
but will apply to every request made using this client.
+ :param bool use_basic_auth: Keyword argument, if set to True performs basic
+ access authentication with server. Default is False.
:param bool use_iam: Keyword argument, if set to True performs
IAM authentication with server. Default is False.
Use :func:`~cloudant.client.CouchDB.iam` to construct an IAM
@@ -86,7 +91,9 @@ class CouchDB(dict):
self._timeout = kwargs.get('timeout', None)
self.r_session = None
self._auto_renew = kwargs.get('auto_renew', False)
+ self._use_basic_auth = kwargs.get('use_basic_auth', False)
self._use_iam = kwargs.get('use_iam', False)
+
connect_to_couch = kwargs.get('connect', False)
if connect_to_couch and self._DATABASE_CLASS == CouchDatabase:
self.connect()
@@ -100,7 +107,16 @@ class CouchDB(dict):
self.session_logout()
if self.admin_party:
- self.r_session = ClientSession(timeout=self._timeout)
+ self.r_session = ClientSession(
+ timeout=self._timeout
+ )
+ elif self._use_basic_auth:
+ self.r_session = BasicSession(
+ self._user,
+ self._auth_token,
+ self.server_url,
+ timeout=self._timeout
+ )
elif self._use_iam:
self.r_session = IAMSession(
self._auth_token,
@@ -146,9 +162,6 @@ class CouchDB(dict):
:returns: Dictionary of session info for the current session.
"""
- if self.admin_party:
- return None
-
return self.r_session.info()
def session_cookie(self):
@@ -157,19 +170,26 @@ class CouchDB(dict):
:returns: Session cookie for the current session
"""
- if self.admin_party:
- return None
return self.r_session.cookies.get('AuthSession')
def session_login(self, user=None, passwd=None):
"""
Performs a session login by posting the auth information
to the _session endpoint.
+
+ :param str user: Username used to connect to server.
+ :param str auth_token: Authentication token used to connect to server.
"""
- if self.admin_party:
- return
+ self.change_credentials(user=user, auth_token=passwd)
- self.r_session.set_credentials(user, passwd)
+ def change_credentials(self, user=None, auth_token=None):
+ """
+ Change login credentials.
+
+ :param str user: Username used to connect to server.
+ :param str auth_token: Authentication token used to connect to server.
+ """
+ self.r_session.set_credentials(user, auth_token)
self.r_session.login()
def session_logout(self):
@@ -177,9 +197,6 @@ class CouchDB(dict):
Performs a session logout and clears the current session by
sending a delete request to the _session endpoint.
"""
- if self.admin_party:
- return
-
self.r_session.logout()
def basic_auth_str(self):
@@ -189,13 +206,7 @@ class CouchDB(dict):
:returns: Basic http authentication string
"""
- if self.admin_party:
- return None
- hash_ = base64.urlsafe_b64encode(bytes_("{username}:{password}".format(
- username=self._user,
- password=self._auth_token
- )))
- return "Basic {0}".format(unicode_(hash_))
+ return self.r_session.base64_user_pass()
def all_dbs(self):
"""
diff --git a/src/cloudant/database.py b/src/cloudant/database.py
index 1992d61..cf53f6f 100644
--- a/src/cloudant/database.py
+++ b/src/cloudant/database.py
@@ -94,11 +94,13 @@ class CouchDatabase(dict):
:returns: Dictionary containing authentication information
"""
- if self.admin_party:
+ session = self.client.session()
+ if session is None:
return None
+
return {
"basic_auth": self.client.basic_auth_str(),
- "user_ctx": self.client.session()['userCtx']
+ "user_ctx": session.get('userCtx')
}
def exists(self):
| Add Basic authentication support to setting up a client session
See #49
| cloudant/python-cloudant | diff --git a/tests/unit/auth_renewal_tests.py b/tests/unit/auth_renewal_tests.py
index 3d9b7cc..b5fb48b 100644
--- a/tests/unit/auth_renewal_tests.py
+++ b/tests/unit/auth_renewal_tests.py
@@ -23,9 +23,9 @@ import os
import requests
import time
-from cloudant._common_util import CookieSession
+from cloudant._client_session import CookieSession
-from .unit_t_db_base import UnitTestDbBase
+from .unit_t_db_base import skip_if_not_cookie_auth, UnitTestDbBase
@unittest.skipIf(os.environ.get('ADMIN_PARTY') == 'true', 'Skipping - Admin Party mode')
class AuthRenewalTests(UnitTestDbBase):
@@ -44,7 +44,8 @@ class AuthRenewalTests(UnitTestDbBase):
Override UnitTestDbBase.tearDown() with no tear down
"""
pass
-
+
+ @skip_if_not_cookie_auth
def test_client_db_doc_stack_success(self):
"""
Ensure that auto renewal of cookie auth happens as expected and applies
@@ -109,6 +110,7 @@ class AuthRenewalTests(UnitTestDbBase):
self.client.disconnect()
del self.client
+ @skip_if_not_cookie_auth
def test_client_db_doc_stack_failure(self):
"""
Ensure that when the regular requests.Session is used that
diff --git a/tests/unit/client_tests.py b/tests/unit/client_tests.py
index db78861..114a9e3 100644
--- a/tests/unit/client_tests.py
+++ b/tests/unit/client_tests.py
@@ -27,17 +27,19 @@ import base64
import sys
import os
import datetime
+import mock
from requests import ConnectTimeout, HTTPError
from time import sleep
from cloudant import cloudant, cloudant_bluemix, couchdb, couchdb_admin_party
from cloudant.client import Cloudant, CouchDB
+from cloudant._client_session import BasicSession, CookieSession
+from cloudant.database import CloudantDatabase
from cloudant.error import CloudantArgumentError, CloudantClientException
from cloudant.feed import Feed, InfiniteFeed
-from cloudant._common_util import CookieSession
-from .unit_t_db_base import UnitTestDbBase
+from .unit_t_db_base import skip_if_not_cookie_auth, UnitTestDbBase
from .. import bytes_, str_
class CloudantClientExceptionTests(unittest.TestCase):
@@ -162,6 +164,7 @@ class ClientTests(UnitTestDbBase):
self.client.disconnect()
self.assertIsNone(self.client.r_session)
+ @skip_if_not_cookie_auth
def test_auto_renew_enabled(self):
"""
Test that CookieSession is used when auto_renew is enabled.
@@ -176,6 +179,7 @@ class ClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_auto_renew_enabled_with_auto_connect(self):
"""
Test that CookieSession is used when auto_renew is enabled along with
@@ -190,6 +194,7 @@ class ClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_session(self):
"""
Test getting session information.
@@ -205,6 +210,7 @@ class ClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_session_cookie(self):
"""
Test getting the session cookie.
@@ -219,6 +225,101 @@ class ClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @mock.patch('cloudant._client_session.Session.request')
+ def test_session_basic(self, m_req):
+ """
+ Test using basic access authentication.
+ """
+ m_response_ok = mock.MagicMock()
+ type(m_response_ok).status_code = mock.PropertyMock(return_value=200)
+ m_response_ok.json.return_value = ['animaldb']
+ m_req.return_value = m_response_ok
+
+ client = Cloudant('foo', 'bar', url=self.url, use_basic_auth=True)
+ client.connect()
+ self.assertIsInstance(client.r_session, BasicSession)
+
+ all_dbs = client.all_dbs()
+
+ m_req.assert_called_once_with(
+ 'GET',
+ self.url + '/_all_dbs',
+ allow_redirects=True,
+ auth=('foo', 'bar'), # uses HTTP Basic Auth
+ timeout=None
+ )
+
+ self.assertEquals(all_dbs, ['animaldb'])
+
+ @mock.patch('cloudant._client_session.Session.request')
+ def test_session_basic_with_no_credentials(self, m_req):
+ """
+ Test using basic access authentication with no credentials.
+ """
+ m_response_ok = mock.MagicMock()
+ type(m_response_ok).status_code = mock.PropertyMock(return_value=200)
+ m_req.return_value = m_response_ok
+
+ client = Cloudant(None, None, url=self.url, use_basic_auth=True)
+ client.connect()
+ self.assertIsInstance(client.r_session, BasicSession)
+
+ db = client['animaldb']
+
+ m_req.assert_called_once_with(
+ 'HEAD',
+ self.url + '/animaldb',
+ allow_redirects=False,
+ auth=None, # ensure no authentication specified
+ timeout=None
+ )
+
+ self.assertIsInstance(db, CloudantDatabase)
+
+ @mock.patch('cloudant._client_session.Session.request')
+ def test_change_credentials_basic(self, m_req):
+ """
+ Test changing credentials when using basic access authentication.
+ """
+ # mock 200
+ m_response_ok = mock.MagicMock()
+ m_response_ok.json.return_value = ['animaldb']
+
+ # mock 401
+ m_response_bad = mock.MagicMock()
+ m_response_bad.raise_for_status.side_effect = HTTPError('401 Unauthorized')
+
+ m_req.side_effect = [m_response_bad, m_response_ok]
+
+ client = Cloudant('foo', 'bar', url=self.url, use_basic_auth=True)
+ client.connect()
+ self.assertIsInstance(client.r_session, BasicSession)
+
+ with self.assertRaises(HTTPError):
+ client.all_dbs() # expected 401
+
+ m_req.assert_called_with(
+ 'GET',
+ self.url + '/_all_dbs',
+ allow_redirects=True,
+ auth=('foo', 'bar'), # uses HTTP Basic Auth
+ timeout=None
+ )
+
+ # use valid credentials
+ client.change_credentials('baz', 'qux')
+ all_dbs = client.all_dbs()
+
+ m_req.assert_called_with(
+ 'GET',
+ self.url + '/_all_dbs',
+ allow_redirects=True,
+ auth=('baz', 'qux'), # uses HTTP Basic Auth
+ timeout=None
+ )
+ self.assertEquals(all_dbs, ['animaldb'])
+
+ @skip_if_not_cookie_auth
def test_basic_auth_str(self):
"""
Test getting the basic authentication string.
@@ -493,6 +594,7 @@ class CloudantClientTests(UnitTestDbBase):
Cloudant specific client unit tests
"""
+ @skip_if_not_cookie_auth
def test_cloudant_session_login(self):
"""
Test that the Cloudant client session successfully authenticates.
@@ -505,6 +607,7 @@ class CloudantClientTests(UnitTestDbBase):
self.client.session_login()
self.assertNotEqual(self.client.session_cookie(), old_cookie)
+ @skip_if_not_cookie_auth
def test_cloudant_session_login_with_new_credentials(self):
"""
Test that the Cloudant client session fails to authenticate when
@@ -517,6 +620,7 @@ class CloudantClientTests(UnitTestDbBase):
self.assertTrue(str(cm.exception).find('Name or password is incorrect'))
+ @skip_if_not_cookie_auth
def test_cloudant_context_helper(self):
"""
Test that the cloudant context helper works as expected.
@@ -528,6 +632,7 @@ class CloudantClientTests(UnitTestDbBase):
except Exception as err:
self.fail('Exception {0} was raised.'.format(str(err)))
+ @skip_if_not_cookie_auth
def test_cloudant_bluemix_context_helper(self):
"""
Test that the cloudant_bluemix context helper works as expected.
@@ -592,6 +697,7 @@ class CloudantClientTests(UnitTestDbBase):
'https://{0}.cloudant.com'.format(self.account)
)
+ @skip_if_not_cookie_auth
def test_bluemix_constructor(self):
"""
Test instantiating a client object using a VCAP_SERVICES environment
@@ -624,6 +730,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
c.disconnect()
+ @skip_if_not_cookie_auth
def test_bluemix_constructor_specify_instance_name(self):
"""
Test instantiating a client object using a VCAP_SERVICES environment
@@ -656,6 +763,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
c.disconnect()
+ @skip_if_not_cookie_auth
def test_bluemix_constructor_with_multiple_services(self):
"""
Test instantiating a client object using a VCAP_SERVICES environment
@@ -723,6 +831,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_connect_timeout(self):
"""
Test that a connect timeout occurs when instantiating
@@ -749,6 +858,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_billing_data(self):
"""
Test the retrieval of billing data
@@ -843,6 +953,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_volume_usage_data(self):
"""
Test the retrieval of volume usage data
@@ -934,6 +1045,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_requests_usage_data(self):
"""
Test the retrieval of requests usage data
@@ -1025,6 +1137,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_shared_databases(self):
"""
Test the retrieval of shared database list
@@ -1035,6 +1148,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_generate_api_key(self):
"""
Test the generation of an API key for this client account
@@ -1048,6 +1162,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_cors_configuration(self):
"""
Test the retrieval of the current CORS configuration for this client
@@ -1061,6 +1176,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_cors_origins(self):
"""
Test the retrieval of the CORS origins list
@@ -1072,6 +1188,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_disable_cors(self):
"""
Test disabling CORS (assuming CORS is enabled)
@@ -1092,6 +1209,7 @@ class CloudantClientTests(UnitTestDbBase):
finally:
self.client.disconnect()
+ @skip_if_not_cookie_auth
def test_update_cors_configuration(self):
"""
Test updating CORS configuration
diff --git a/tests/unit/database_tests.py b/tests/unit/database_tests.py
index 94e6fea..9a35c3e 100644
--- a/tests/unit/database_tests.py
+++ b/tests/unit/database_tests.py
@@ -38,7 +38,7 @@ from cloudant.index import Index, TextIndex, SpecialIndex
from cloudant.feed import Feed, InfiniteFeed
from tests.unit._test_util import LONG_NUMBER
-from .unit_t_db_base import UnitTestDbBase
+from .unit_t_db_base import skip_if_not_cookie_auth, UnitTestDbBase
from .. import unicode_
class CloudantDatabaseExceptionTests(unittest.TestCase):
@@ -151,6 +151,7 @@ class DatabaseTests(UnitTestDbBase):
'/'.join((self.client.server_url, self.test_dbname))
)
+ @skip_if_not_cookie_auth
def test_retrieve_creds(self):
"""
Test retrieving client credentials. The client credentials are None if
@@ -370,6 +371,7 @@ class DatabaseTests(UnitTestDbBase):
ddoc = self.db.get_design_document('_design/ddoc01')
self.assertEqual(ddoc, local_ddoc)
+ @skip_if_not_cookie_auth
def test_get_security_document(self):
"""
Test retrieving the database security document
@@ -995,6 +997,7 @@ class CloudantDatabaseTests(UnitTestDbBase):
with self.assertRaises(TypeError):
database.unshare_database(share)
+ @skip_if_not_cookie_auth
def test_security_document(self):
"""
Test the retrieval of the security document.
@@ -1004,6 +1007,7 @@ class CloudantDatabaseTests(UnitTestDbBase):
expected = {'cloudant': {share: ['_reader']}}
self.assertDictEqual(self.db.security_document(), expected)
+ @skip_if_not_cookie_auth
def test_share_database_default_permissions(self):
"""
Test the sharing of a database applying default permissions.
@@ -1014,6 +1018,7 @@ class CloudantDatabaseTests(UnitTestDbBase):
expected = {'cloudant': {share: ['_reader']}}
self.assertDictEqual(self.db.security_document(), expected)
+ @skip_if_not_cookie_auth
def test_share_database(self):
"""
Test the sharing of a database.
@@ -1024,6 +1029,7 @@ class CloudantDatabaseTests(UnitTestDbBase):
expected = {'cloudant': {share: ['_writer']}}
self.assertDictEqual(self.db.security_document(), expected)
+ @skip_if_not_cookie_auth
def test_share_database_with_redundant_role_entries(self):
"""
Test the sharing of a database works when the list of roles contains
@@ -1066,6 +1072,7 @@ class CloudantDatabaseTests(UnitTestDbBase):
'\'_db_updates\', \'_design\', \'_shards\', \'_security\']'
)
+ @skip_if_not_cookie_auth
def test_unshare_database(self):
"""
Test the un-sharing of a database from a specified user.
diff --git a/tests/unit/iam_auth_tests.py b/tests/unit/iam_auth_tests.py
index a65d3f0..d6b3c04 100644
--- a/tests/unit/iam_auth_tests.py
+++ b/tests/unit/iam_auth_tests.py
@@ -19,8 +19,8 @@ import json
import mock
from cloudant._2to3 import Cookie
-from cloudant._common_util import IAMSession
from cloudant.client import Cloudant
+from cloudant._client_session import IAMSession
MOCK_API_KEY = 'CqbrIYzdO3btWV-5t4teJLY_etfT_dkccq-vO-5vCXSo'
@@ -97,7 +97,7 @@ class IAMAuthTests(unittest.TestCase):
self.assertEquals(iam._api_key, new_api_key)
- @mock.patch('cloudant._common_util.ClientSession.request')
+ @mock.patch('cloudant._client_session.ClientSession.request')
def test_iam_get_access_token(self, m_req):
m_response = mock.MagicMock()
m_response.json.return_value = MOCK_OIDC_TOKEN_RESPONSE
@@ -122,8 +122,8 @@ class IAMAuthTests(unittest.TestCase):
self.assertTrue(m_response.raise_for_status.called)
self.assertTrue(m_response.json.called)
- @mock.patch('cloudant._common_util.ClientSession.request')
- @mock.patch('cloudant._common_util.IAMSession._get_access_token')
+ @mock.patch('cloudant._client_session.ClientSession.request')
+ @mock.patch('cloudant._client_session.IAMSession._get_access_token')
def test_iam_login(self, m_token, m_req):
m_token.return_value = MOCK_ACCESS_TOKEN
m_response = mock.MagicMock()
@@ -150,7 +150,7 @@ class IAMAuthTests(unittest.TestCase):
iam.logout()
self.assertEqual(len(iam.cookies.keys()), 0)
- @mock.patch('cloudant._common_util.ClientSession.get')
+ @mock.patch('cloudant._client_session.ClientSession.get')
def test_iam_get_session_info(self, m_get):
m_info = {'ok': True, 'info': {'authentication_db': '_users'}}
@@ -166,8 +166,8 @@ class IAMAuthTests(unittest.TestCase):
self.assertEqual(info, m_info)
self.assertTrue(m_response.raise_for_status.called)
- @mock.patch('cloudant._common_util.IAMSession.login')
- @mock.patch('cloudant._common_util.ClientSession.request')
+ @mock.patch('cloudant._client_session.IAMSession.login')
+ @mock.patch('cloudant._client_session.ClientSession.request')
def test_iam_first_request(self, m_req, m_login):
# mock 200
m_response_ok = mock.MagicMock()
@@ -191,8 +191,8 @@ class IAMAuthTests(unittest.TestCase):
self.assertEqual(m_req.call_count, 1)
self.assertEqual(resp.status_code, 200)
- @mock.patch('cloudant._common_util.IAMSession.login')
- @mock.patch('cloudant._common_util.ClientSession.request')
+ @mock.patch('cloudant._client_session.IAMSession.login')
+ @mock.patch('cloudant._client_session.ClientSession.request')
def test_iam_renew_cookie_on_expiry(self, m_req, m_login):
# mock 200
m_response_ok = mock.MagicMock()
@@ -213,8 +213,8 @@ class IAMAuthTests(unittest.TestCase):
self.assertEqual(m_req.call_count, 1)
self.assertEqual(resp.status_code, 200)
- @mock.patch('cloudant._common_util.IAMSession.login')
- @mock.patch('cloudant._common_util.ClientSession.request')
+ @mock.patch('cloudant._client_session.IAMSession.login')
+ @mock.patch('cloudant._client_session.ClientSession.request')
def test_iam_renew_cookie_on_401_success(self, m_req, m_login):
# mock 200
m_response_ok = mock.MagicMock()
@@ -243,8 +243,8 @@ class IAMAuthTests(unittest.TestCase):
self.assertEqual(m_login.call_count, 2)
self.assertEqual(m_req.call_count, 3)
- @mock.patch('cloudant._common_util.IAMSession.login')
- @mock.patch('cloudant._common_util.ClientSession.request')
+ @mock.patch('cloudant._client_session.IAMSession.login')
+ @mock.patch('cloudant._client_session.ClientSession.request')
def test_iam_renew_cookie_on_401_failure(self, m_req, m_login):
# mock 401
m_response_bad = mock.MagicMock()
@@ -269,8 +269,8 @@ class IAMAuthTests(unittest.TestCase):
self.assertEqual(m_login.call_count, 3)
self.assertEqual(m_req.call_count, 4)
- @mock.patch('cloudant._common_util.IAMSession.login')
- @mock.patch('cloudant._common_util.ClientSession.request')
+ @mock.patch('cloudant._client_session.IAMSession.login')
+ @mock.patch('cloudant._client_session.ClientSession.request')
def test_iam_renew_cookie_disabled(self, m_req, m_login):
# mock 401
m_response_bad = mock.MagicMock()
@@ -292,8 +292,8 @@ class IAMAuthTests(unittest.TestCase):
self.assertEqual(m_login.call_count, 1) # no attempt to renew
self.assertEqual(m_req.call_count, 2)
- @mock.patch('cloudant._common_util.IAMSession.login')
- @mock.patch('cloudant._common_util.ClientSession.request')
+ @mock.patch('cloudant._client_session.IAMSession.login')
+ @mock.patch('cloudant._client_session.ClientSession.request')
def test_iam_client_create(self, m_req, m_login):
# mock 200
m_response_ok = mock.MagicMock()
@@ -315,8 +315,8 @@ class IAMAuthTests(unittest.TestCase):
self.assertEqual(m_req.call_count, 1)
self.assertEqual(dbs, ['animaldb'])
- @mock.patch('cloudant._common_util.IAMSession.login')
- @mock.patch('cloudant._common_util.IAMSession.set_credentials')
+ @mock.patch('cloudant._client_session.IAMSession.login')
+ @mock.patch('cloudant._client_session.IAMSession.set_credentials')
def test_iam_client_session_login(self, m_set, m_login):
# create IAM client
client = Cloudant.iam('foo', MOCK_API_KEY)
@@ -331,8 +331,8 @@ class IAMAuthTests(unittest.TestCase):
self.assertEqual(m_login.call_count, 2)
self.assertEqual(m_set.call_count, 2)
- @mock.patch('cloudant._common_util.IAMSession.login')
- @mock.patch('cloudant._common_util.IAMSession.set_credentials')
+ @mock.patch('cloudant._client_session.IAMSession.login')
+ @mock.patch('cloudant._client_session.IAMSession.set_credentials')
def test_iam_client_session_login_with_new_credentials(self, m_set, m_login):
# create IAM client
client = Cloudant.iam('foo', MOCK_API_KEY)
diff --git a/tests/unit/replicator_tests.py b/tests/unit/replicator_tests.py
index 74d0846..5c23140 100644
--- a/tests/unit/replicator_tests.py
+++ b/tests/unit/replicator_tests.py
@@ -34,7 +34,7 @@ from cloudant.replicator import Replicator
from cloudant.document import Document
from cloudant.error import CloudantReplicatorException, CloudantClientException
-from .unit_t_db_base import UnitTestDbBase
+from .unit_t_db_base import skip_if_not_cookie_auth, UnitTestDbBase
from .. import unicode_
class CloudantReplicatorExceptionTests(unittest.TestCase):
@@ -157,6 +157,7 @@ class ReplicatorTests(UnitTestDbBase):
clone = Replicator(self.client)
clone.create_replication(self.db, self.target_db)
+ @skip_if_not_cookie_auth
@flaky(max_runs=3)
def test_create_replication(self):
"""
@@ -300,6 +301,7 @@ class ReplicatorTests(UnitTestDbBase):
match = [repl_id for repl_id in all_repl_ids if repl_id in repl_ids]
self.assertEqual(set(repl_ids), set(match))
+ @skip_if_not_cookie_auth
def test_retrieve_replication_state(self):
"""
Test that the replication state can be retrieved for a replication
@@ -341,6 +343,7 @@ class ReplicatorTests(UnitTestDbBase):
)
self.assertIsNone(repl_state)
+ @skip_if_not_cookie_auth
def test_stop_replication(self):
"""
Test that a replication can be stopped.
@@ -376,6 +379,7 @@ class ReplicatorTests(UnitTestDbBase):
'Replication with id {} not found.'.format(repl_id)
)
+ @skip_if_not_cookie_auth
def test_follow_replication(self):
"""
Test that follow_replication(...) properly iterates updated
diff --git a/tests/unit/unit_t_db_base.py b/tests/unit/unit_t_db_base.py
index c0b62b7..ccec69a 100644
--- a/tests/unit/unit_t_db_base.py
+++ b/tests/unit/unit_t_db_base.py
@@ -68,6 +68,15 @@ from cloudant.design_document import DesignDocument
from .. import unicode_
+
+def skip_if_not_cookie_auth(f):
+ def wrapper(*args):
+ if not args[0].use_cookie_auth:
+ raise unittest.SkipTest('Test only supports cookie authentication')
+ return f(*args)
+ return wrapper
+
+
class UnitTestDbBase(unittest.TestCase):
"""
The base class for all unit tests targeting a database
@@ -133,14 +142,19 @@ class UnitTestDbBase(unittest.TestCase):
def set_up_client(self, auto_connect=False, auto_renew=False, encoder=None,
timeout=(30,300)):
+ self.user = os.environ.get('DB_USER', None)
+ self.pwd = os.environ.get('DB_PASSWORD', None)
+ self.use_cookie_auth = True
+
if os.environ.get('RUN_CLOUDANT_TESTS') is None:
+ self.url = os.environ['DB_URL']
+
admin_party = False
- if (os.environ.get('ADMIN_PARTY') and
- os.environ.get('ADMIN_PARTY') == 'true'):
+ if os.environ.get('ADMIN_PARTY') == 'true':
admin_party = True
- self.user = os.environ.get('DB_USER', None)
- self.pwd = os.environ.get('DB_PASSWORD', None)
- self.url = os.environ['DB_URL']
+
+ self.use_cookie_auth = False
+ # construct Cloudant client (using admin party mode)
self.client = CouchDB(
self.user,
self.pwd,
@@ -153,22 +167,50 @@ class UnitTestDbBase(unittest.TestCase):
)
else:
self.account = os.environ.get('CLOUDANT_ACCOUNT')
- self.user = os.environ.get('DB_USER')
- self.pwd = os.environ.get('DB_PASSWORD')
self.url = os.environ.get(
'DB_URL',
'https://{0}.cloudant.com'.format(self.account))
- self.client = Cloudant(
- self.user,
- self.pwd,
- url=self.url,
- x_cloudant_user=self.account,
- connect=auto_connect,
- auto_renew=auto_renew,
- encoder=encoder,
- timeout=timeout
- )
+ if os.environ.get('RUN_BASIC_AUTH_TESTS'):
+ self.use_cookie_auth = False
+ # construct Cloudant client (using basic access authentication)
+ self.client = Cloudant(
+ self.user,
+ self.pwd,
+ url=self.url,
+ x_cloudant_user=self.account,
+ connect=auto_connect,
+ auto_renew=auto_renew,
+ encoder=encoder,
+ timeout=timeout,
+ use_basic_auth=True,
+ )
+ elif os.environ.get('IAM_API_KEY'):
+ self.use_cookie_auth = False
+ # construct Cloudant client (using IAM authentication)
+ self.client = Cloudant(
+ None, # username is not required
+ os.environ.get('IAM_API_KEY'),
+ url=self.url,
+ x_cloudant_user=self.account,
+ connect=auto_connect,
+ auto_renew=auto_renew,
+ encoder=encoder,
+ timeout=timeout,
+ use_iam=True,
+ )
+ else:
+ # construct Cloudant client (using cookie authentication)
+ self.client = Cloudant(
+ self.user,
+ self.pwd,
+ url=self.url,
+ x_cloudant_user=self.account,
+ connect=auto_connect,
+ auto_renew=auto_renew,
+ encoder=encoder,
+ timeout=timeout
+ )
def tearDown(self):
"""
@@ -285,17 +327,9 @@ class UnitTestDbBase(unittest.TestCase):
'bar2': ['_reader']
}
}
- if os.environ.get('ADMIN_PARTY') == 'true':
- resp = requests.put(
- '/'.join([self.db.database_url, '_security']),
- data=json.dumps(self.sdoc),
- headers={'Content-Type': 'application/json'}
- )
- else:
- resp = requests.put(
- '/'.join([self.db.database_url, '_security']),
- auth=(self.user, self.pwd),
- data=json.dumps(self.sdoc),
- headers={'Content-Type': 'application/json'}
- )
+ resp = self.client.r_session.put(
+ '/'.join([self.db.database_url, '_security']),
+ data=json.dumps(self.sdoc),
+ headers={'Content-Type': 'application/json'}
+ )
self.assertEqual(resp.status_code, 200)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_issue_reference",
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 3,
"issue_text_score": 3,
"test_score": 3
},
"num_modified_files": 5
} | 2.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"nose",
"pytest"
],
"pre_install": null,
"python": "3.5",
"reqs_path": [
"requirements.txt",
"test-requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
astroid==2.11.7
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
-e git+https://github.com/cloudant/python-cloudant.git@ef15286b311f8cb222a1ddd28f78c7e87c1e9652#egg=cloudant
dill==0.3.4
docutils==0.18.1
flaky==3.8.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
iniconfig==1.1.1
isort==5.10.1
Jinja2==3.0.3
lazy-object-proxy==1.7.1
MarkupSafe==2.0.1
mccabe==0.7.0
mock==1.3.0
nose==1.3.7
packaging==21.3
pbr==6.1.1
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
Pygments==2.14.0
pylint==2.13.9
pyparsing==3.1.4
pytest==7.0.1
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
tomli==1.2.3
typed-ast==1.5.5
typing_extensions==4.1.1
urllib3==1.26.20
wrapt==1.16.0
zipp==3.6.0
| name: python-cloudant
channels:
- defaults
- https://repo.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
- astroid==2.11.7
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- dill==0.3.4
- docutils==0.18.1
- flaky==3.8.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- isort==5.10.1
- jinja2==3.0.3
- lazy-object-proxy==1.7.1
- markupsafe==2.0.1
- mccabe==0.7.0
- mock==1.3.0
- nose==1.3.7
- packaging==21.3
- pbr==6.1.1
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pygments==2.14.0
- pylint==2.13.9
- pyparsing==3.1.4
- pytest==7.0.1
- 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
- tomli==1.2.3
- typed-ast==1.5.5
- typing-extensions==4.1.1
- urllib3==1.26.20
- wrapt==1.16.0
- zipp==3.6.0
prefix: /opt/conda/envs/python-cloudant
| [
"tests/unit/client_tests.py::CloudantClientExceptionTests::test_raise_using_invalid_code",
"tests/unit/client_tests.py::CloudantClientExceptionTests::test_raise_with_proper_code_and_args",
"tests/unit/client_tests.py::CloudantClientExceptionTests::test_raise_without_args",
"tests/unit/client_tests.py::CloudantClientExceptionTests::test_raise_without_code",
"tests/unit/client_tests.py::ClientTests::test_change_credentials_basic",
"tests/unit/client_tests.py::ClientTests::test_constructor_with_url",
"tests/unit/client_tests.py::ClientTests::test_session_basic",
"tests/unit/client_tests.py::ClientTests::test_session_basic_with_no_credentials",
"tests/unit/database_tests.py::CloudantDatabaseExceptionTests::test_raise_using_invalid_code",
"tests/unit/database_tests.py::CloudantDatabaseExceptionTests::test_raise_with_proper_code_and_args",
"tests/unit/database_tests.py::CloudantDatabaseExceptionTests::test_raise_without_args",
"tests/unit/database_tests.py::CloudantDatabaseExceptionTests::test_raise_without_code",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_client_create",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_client_session_login",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_client_session_login_with_new_credentials",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_first_request",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_get_access_token",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_get_session_info",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_login",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_logout",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_renew_cookie_disabled",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_renew_cookie_on_401_failure",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_renew_cookie_on_401_success",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_renew_cookie_on_expiry",
"tests/unit/iam_auth_tests.py::IAMAuthTests::test_iam_set_credentials",
"tests/unit/replicator_tests.py::CloudantReplicatorExceptionTests::test_raise_using_invalid_code",
"tests/unit/replicator_tests.py::CloudantReplicatorExceptionTests::test_raise_with_proper_code_and_args",
"tests/unit/replicator_tests.py::CloudantReplicatorExceptionTests::test_raise_without_args",
"tests/unit/replicator_tests.py::CloudantReplicatorExceptionTests::test_raise_without_code"
]
| [
"tests/unit/client_tests.py::ClientTests::test_set_non_db_value_via_setitem",
"tests/unit/database_tests.py::DatabaseTests::test_view_clean_up",
"tests/unit/replicator_tests.py::ReplicatorTests::test_timeout_in_create_replication",
"tests/unit/client_tests.py::ClientTests::test_all_dbs",
"tests/unit/client_tests.py::ClientTests::test_auto_connect",
"tests/unit/client_tests.py::ClientTests::test_connect",
"tests/unit/client_tests.py::ClientTests::test_couchdb_context_helper",
"tests/unit/client_tests.py::ClientTests::test_create_db_via_setitem",
"tests/unit/client_tests.py::ClientTests::test_create_delete_database",
"tests/unit/client_tests.py::ClientTests::test_create_existing_database",
"tests/unit/client_tests.py::ClientTests::test_db_updates_feed_call",
"tests/unit/client_tests.py::ClientTests::test_delete_cached_db_object_via_delitem",
"tests/unit/client_tests.py::ClientTests::test_delete_non_existing_database",
"tests/unit/client_tests.py::ClientTests::test_delete_remote_db_via_delitem",
"tests/unit/client_tests.py::ClientTests::test_get_cached_db_object_via_get",
"tests/unit/client_tests.py::ClientTests::test_get_db_via_getitem",
"tests/unit/client_tests.py::ClientTests::test_get_non_existing_db_via_getitem",
"tests/unit/client_tests.py::ClientTests::test_get_remote_db_via_get",
"tests/unit/client_tests.py::ClientTests::test_keys",
"tests/unit/client_tests.py::ClientTests::test_local_set_db_value_via_setitem",
"tests/unit/client_tests.py::ClientTests::test_multiple_connect",
"tests/unit/database_tests.py::DatabaseTests::test_all_docs_get",
"tests/unit/database_tests.py::DatabaseTests::test_all_docs_get_with_long_type",
"tests/unit/database_tests.py::DatabaseTests::test_all_docs_post",
"tests/unit/database_tests.py::DatabaseTests::test_all_docs_post_empty_key_list",
"tests/unit/database_tests.py::DatabaseTests::test_all_docs_post_multiple_params",
"tests/unit/database_tests.py::DatabaseTests::test_bulk_docs_creation",
"tests/unit/database_tests.py::DatabaseTests::test_bulk_docs_update",
"tests/unit/database_tests.py::DatabaseTests::test_bulk_docs_uses_custom_encoder",
"tests/unit/database_tests.py::DatabaseTests::test_changes_feed_call",
"tests/unit/database_tests.py::DatabaseTests::test_changes_inifinite_feed_call",
"tests/unit/database_tests.py::DatabaseTests::test_constructor",
"tests/unit/database_tests.py::DatabaseTests::test_create_db_delete_db",
"tests/unit/database_tests.py::DatabaseTests::test_create_design_document",
"tests/unit/database_tests.py::DatabaseTests::test_create_doc_with_update_handler",
"tests/unit/database_tests.py::DatabaseTests::test_create_document_that_already_exists",
"tests/unit/database_tests.py::DatabaseTests::test_create_document_with_id",
"tests/unit/database_tests.py::DatabaseTests::test_create_document_without_id",
"tests/unit/database_tests.py::DatabaseTests::test_create_empty_document",
"tests/unit/database_tests.py::DatabaseTests::test_custom_result_context_manager",
"tests/unit/database_tests.py::DatabaseTests::test_database_request_fails_after_client_disconnects",
"tests/unit/database_tests.py::DatabaseTests::test_delete_exception",
"tests/unit/database_tests.py::DatabaseTests::test_document_iteration_completeness",
"tests/unit/database_tests.py::DatabaseTests::test_document_iteration_over_fetch_limit",
"tests/unit/database_tests.py::DatabaseTests::test_document_iteration_returns_valid_documents",
"tests/unit/database_tests.py::DatabaseTests::test_document_iteration_under_fetch_limit",
"tests/unit/database_tests.py::DatabaseTests::test_exists",
"tests/unit/database_tests.py::DatabaseTests::test_exists_raises_httperror",
"tests/unit/database_tests.py::DatabaseTests::test_get_db_via_getitem",
"tests/unit/database_tests.py::DatabaseTests::test_get_list_function_result",
"tests/unit/database_tests.py::DatabaseTests::test_get_list_function_result_with_invalid_argument",
"tests/unit/database_tests.py::DatabaseTests::test_get_non_existing_doc_via_getitem",
"tests/unit/database_tests.py::DatabaseTests::test_get_security_document",
"tests/unit/database_tests.py::DatabaseTests::test_get_set_revision_limit",
"tests/unit/database_tests.py::DatabaseTests::test_get_show_result",
"tests/unit/database_tests.py::DatabaseTests::test_keys",
"tests/unit/database_tests.py::DatabaseTests::test_missing_revisions",
"tests/unit/database_tests.py::DatabaseTests::test_missing_revisions_uses_custom_encoder",
"tests/unit/database_tests.py::DatabaseTests::test_retrieve_creds",
"tests/unit/database_tests.py::DatabaseTests::test_retrieve_db_metadata",
"tests/unit/database_tests.py::DatabaseTests::test_retrieve_db_url",
"tests/unit/database_tests.py::DatabaseTests::test_retrieve_design_document",
"tests/unit/database_tests.py::DatabaseTests::test_retrieve_design_document_list",
"tests/unit/database_tests.py::DatabaseTests::test_retrieve_design_documents",
"tests/unit/database_tests.py::DatabaseTests::test_retrieve_document_count",
"tests/unit/database_tests.py::DatabaseTests::test_retrieve_raw_view_results",
"tests/unit/database_tests.py::DatabaseTests::test_retrieve_view_results",
"tests/unit/database_tests.py::DatabaseTests::test_revisions_diff",
"tests/unit/database_tests.py::DatabaseTests::test_revs_diff_uses_custom_encoder",
"tests/unit/database_tests.py::DatabaseTests::test_update_doc_with_update_handler",
"tests/unit/database_tests.py::DatabaseTests::test_update_handler_raises_httperror",
"tests/unit/replicator_tests.py::ReplicatorTests::test_constructor",
"tests/unit/replicator_tests.py::ReplicatorTests::test_constructor_failure",
"tests/unit/replicator_tests.py::ReplicatorTests::test_create_replication",
"tests/unit/replicator_tests.py::ReplicatorTests::test_create_replication_without_a_source",
"tests/unit/replicator_tests.py::ReplicatorTests::test_create_replication_without_a_target",
"tests/unit/replicator_tests.py::ReplicatorTests::test_follow_replication",
"tests/unit/replicator_tests.py::ReplicatorTests::test_list_replications",
"tests/unit/replicator_tests.py::ReplicatorTests::test_replication_with_generated_id",
"tests/unit/replicator_tests.py::ReplicatorTests::test_retrieve_replication_state",
"tests/unit/replicator_tests.py::ReplicatorTests::test_retrieve_replication_state_using_invalid_id",
"tests/unit/replicator_tests.py::ReplicatorTests::test_stop_replication",
"tests/unit/replicator_tests.py::ReplicatorTests::test_stop_replication_using_invalid_id"
]
| []
| []
| Apache License 2.0 | 1,659 | [
"src/cloudant/_client_session.py",
"src/cloudant/_common_util.py",
"src/cloudant/client.py",
"src/cloudant/database.py",
"CHANGES.rst",
"Jenkinsfile"
]
| [
"src/cloudant/_client_session.py",
"src/cloudant/_common_util.py",
"src/cloudant/client.py",
"src/cloudant/database.py",
"CHANGES.rst",
"Jenkinsfile"
]
|
|
pydicom__pydicom-501 | 7783dce0013448e9c1acdb1b06e4ffbe97c3d334 | 2017-09-06 22:15:35 | bef49851e7c3b70edd43cc40fc84fe905e78d5ba | diff --git a/pydicom/uid.py b/pydicom/uid.py
index 483159e47..741450672 100644
--- a/pydicom/uid.py
+++ b/pydicom/uid.py
@@ -162,15 +162,16 @@ class UID(str):
@property
def name(self):
"""Return the UID name from the UID dictionary."""
- if self in UID_dictionary:
+ uid_string = str.__str__(self)
+ if uid_string in UID_dictionary:
return UID_dictionary[self][0]
- return str.__str__(self)
+ return uid_string
@property
def type(self):
"""Return the UID type from the UID dictionary."""
- if self in UID_dictionary:
+ if str.__str__(self) in UID_dictionary:
return UID_dictionary[self][1]
return ''
@@ -178,7 +179,7 @@ class UID(str):
@property
def info(self):
"""Return the UID info from the UID dictionary."""
- if self in UID_dictionary:
+ if str.__str__(self) in UID_dictionary:
return UID_dictionary[self][2]
return ''
@@ -186,7 +187,7 @@ class UID(str):
@property
def is_retired(self):
"""Return True if the UID is retired, False otherwise or if private."""
- if self in UID_dictionary:
+ if str.__str__(self) in UID_dictionary:
return bool(UID_dictionary[self][3])
return False
diff --git a/pydicom/valuerep.py b/pydicom/valuerep.py
index 3f07ef740..1521c16e1 100644
--- a/pydicom/valuerep.py
+++ b/pydicom/valuerep.py
@@ -517,6 +517,7 @@ def MultiString(val, valtype=str):
class PersonName3(object):
def __init__(self, val, encodings=default_encoding):
if isinstance(val, PersonName3):
+ encodings = val.encodings
val = val.original_string
self.original_string = val
| Encoding type lost with PersonName3
#### Description
Encodings lost when converting DataElements that use PersonName3
#### Steps/Code to Reproduce
```python
from pydicom.charset import decode
from pydicom.dataelem import DataElement
elem = DataElement(0x00100010, 'PN', 'Test')
decode(elem, ['ISO 2022 IR 126'])
assert 'iso_ir_126' in elem.values.encodings
```
#### Actual Results
elem.values.encodings is set to ['iso8859', 'iso8859', 'iso8859'] because `charset.decode` calls
`data_element.value = data_element.value.decode(encodings)`. The `DataElement.value` setter then converts the `PersonName3` object with the correct encodings into a new `PersonName3` object with default encodings.
#### Versions
python 3
| pydicom/pydicom | diff --git a/pydicom/tests/test_charset.py b/pydicom/tests/test_charset.py
index 7cb62bd75..bb8f838f5 100644
--- a/pydicom/tests/test_charset.py
+++ b/pydicom/tests/test_charset.py
@@ -10,6 +10,7 @@ import pydicom.charset
from pydicom import dicomio
from pydicom.data import get_charset_files
from pydicom.data import get_testdata_files
+from pydicom.dataelem import DataElement
latin1_file = get_charset_files("chrFren.dcm")[0]
jp_file = get_charset_files("chrH31.dcm")[0]
@@ -85,6 +86,18 @@ class charsetTests(unittest.TestCase):
'\033$B$d$^$@\033(B^\033$B$?$m$&\033(B')
self.assertEqual(expected, ds.PatientName)
+ def test_bad_charset(self):
+ """Test bad charset defaults to ISO IR 6"""
+ # Python 3: elem.value is PersonName3, Python 2: elem.value is str
+ elem = DataElement(0x00100010, 'PN', 'CITIZEN')
+ pydicom.charset.decode(elem, ['ISO 2022 IR 126'])
+ # After decode Python 2: elem.value is PersonNameUnicode
+ assert 'iso_ir_126' in elem.value.encodings
+ assert 'iso8859' not in elem.value.encodings
+ # default encoding is iso8859
+ pydicom.charset.decode(elem, [])
+ assert 'iso8859' in elem.value.encodings
+
if __name__ == "__main__":
# This is called if run alone, but not if loaded through run_tests.py
diff --git a/pydicom/tests/test_uid.py b/pydicom/tests/test_uid.py
index f035c4cdd..2d7938b89 100644
--- a/pydicom/tests/test_uid.py
+++ b/pydicom/tests/test_uid.py
@@ -3,7 +3,7 @@
import pytest
-from pydicom.uid import UID, generate_uid, PYDICOM_ROOT_UID
+from pydicom.uid import UID, generate_uid, PYDICOM_ROOT_UID, JPEGLSLossy
class TestGenerateUID(object):
@@ -61,7 +61,6 @@ class TestUID(object):
assert not self.uid == 'Explicit VR Little Endian'
# Issue 96
assert not self.uid == 3
- assert not self.uid is None
def test_inequality(self):
"""Test that UID.__ne__ works."""
@@ -73,7 +72,6 @@ class TestUID(object):
assert self.uid != 'Explicit VR Little Endian'
# Issue 96
assert self.uid != 3
- assert self.uid is not None
def test_hash(self):
"""Test that UID.__hash_- works."""
@@ -183,6 +181,21 @@ class TestUID(object):
assert self.uid.name == 'Implicit VR Little Endian'
assert UID('1.2.840.10008.5.1.4.1.1.2').name == 'CT Image Storage'
+ def test_name_with_equal_hash(self):
+ """Test that UID name works for UID with same hash as predefined UID.
+ """
+ class MockedUID(UID):
+ # Force the UID to return the same hash as one of the
+ # uid dictionary entries (any will work).
+ # The resulting hash collision forces the usage of the `eq`
+ # operator while checking for containment in the uid dictionary
+ # (regression test for issue #499)
+ def __hash__(self):
+ return hash(JPEGLSLossy)
+
+ uid = MockedUID('1.2.3')
+ assert uid.name == '1.2.3'
+
def test_type(self):
"""Test that UID.type works."""
assert self.uid.type == 'Transfer Syntax'
diff --git a/pydicom/tests/test_valuerep.py b/pydicom/tests/test_valuerep.py
index cd4e0a7fb..49ff72625 100644
--- a/pydicom/tests/test_valuerep.py
+++ b/pydicom/tests/test_valuerep.py
@@ -310,6 +310,15 @@ class PersonNametests(unittest.TestCase):
msg = "PersonName3 not equal comparison did not work correctly"
self.assertFalse(pn != "John^Doe", msg)
+ def test_encoding_carried(self):
+ """Test encoding is carried over to a new PN3 object"""
+ # Issue 466
+ from pydicom.valuerep import PersonName3
+ pn = PersonName3("John^Doe", encodings='iso_ir_126')
+ assert pn.encodings == ['iso_ir_126', 'iso_ir_126', 'iso_ir_126']
+ pn2 = PersonName3(pn)
+ assert pn2.encodings == ['iso_ir_126', 'iso_ir_126', 'iso_ir_126']
+
class DateTimeTests(unittest.TestCase):
"""Unit tests for DA, DT, TM conversion to datetime objects"""
| {
"commit_name": "merge_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": 1,
"test_score": 0
},
"num_modified_files": 2
} | 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": [
"pytest",
"pytest-cov"
],
"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
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
-e git+https://github.com/pydicom/pydicom.git@7783dce0013448e9c1acdb1b06e4ffbe97c3d334#egg=pydicom
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
pytest==6.2.4
pytest-cov==4.0.0
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: pydicom
channels:
- defaults
- https://repo.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
- pytest-cov==4.0.0
- tomli==1.2.3
prefix: /opt/conda/envs/pydicom
| [
"pydicom/tests/test_charset.py::charsetTests::test_bad_charset",
"pydicom/tests/test_uid.py::TestUID::test_name_with_equal_hash",
"pydicom/tests/test_valuerep.py::PersonNametests::test_encoding_carried"
]
| []
| [
"pydicom/tests/test_charset.py::charsetTests::testEncodingWithSpecificTags",
"pydicom/tests/test_charset.py::charsetTests::testEncodings",
"pydicom/tests/test_charset.py::charsetTests::testExplicitISO2022_IR6",
"pydicom/tests/test_charset.py::charsetTests::testLatin1",
"pydicom/tests/test_charset.py::charsetTests::testMultiPN",
"pydicom/tests/test_charset.py::charsetTests::testNestedCharacterSets",
"pydicom/tests/test_charset.py::charsetTests::testStandardFile",
"pydicom/tests/test_uid.py::TestGenerateUID::test_generate_uid",
"pydicom/tests/test_uid.py::TestUID::test_equality",
"pydicom/tests/test_uid.py::TestUID::test_inequality",
"pydicom/tests/test_uid.py::TestUID::test_hash",
"pydicom/tests/test_uid.py::TestUID::test_str",
"pydicom/tests/test_uid.py::TestUID::test_is_implicit_vr",
"pydicom/tests/test_uid.py::TestUID::test_is_little_endian",
"pydicom/tests/test_uid.py::TestUID::test_is_deflated",
"pydicom/tests/test_uid.py::TestUID::test_is_transfer_syntax",
"pydicom/tests/test_uid.py::TestUID::test_is_compressed",
"pydicom/tests/test_uid.py::TestUID::test_is_encapsulated",
"pydicom/tests/test_uid.py::TestUID::test_name",
"pydicom/tests/test_uid.py::TestUID::test_type",
"pydicom/tests/test_uid.py::TestUID::test_info",
"pydicom/tests/test_uid.py::TestUID::test_is_retired",
"pydicom/tests/test_uid.py::TestUID::test_is_valid",
"pydicom/tests/test_uid.py::TestUID::test_is_private",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_equality",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_inequality",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_hash",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_str",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_implicit_vr",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_little_endian",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_deflated",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_transfer_syntax",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_compressed",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_encapsulated",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_name",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_type",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_info",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_retired",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_valid",
"pydicom/tests/test_uid.py::TestUIDPrivate::test_is_private",
"pydicom/tests/test_valuerep.py::TMPickleTest::testPickling",
"pydicom/tests/test_valuerep.py::DTPickleTest::testPickling",
"pydicom/tests/test_valuerep.py::DAPickleTest::testPickling",
"pydicom/tests/test_valuerep.py::DSfloatPickleTest::testPickling",
"pydicom/tests/test_valuerep.py::DSdecimalPickleTest::testPickling",
"pydicom/tests/test_valuerep.py::ISPickleTest::testPickling",
"pydicom/tests/test_valuerep.py::BadValueReadtests::testReadBadValueInVRDefault",
"pydicom/tests/test_valuerep.py::BadValueReadtests::testReadBadValueInVREnforceValidValue",
"pydicom/tests/test_valuerep.py::DecimalStringtests::testInvalidDecimalStrings",
"pydicom/tests/test_valuerep.py::DecimalStringtests::testValidDecimalStrings",
"pydicom/tests/test_valuerep.py::PersonNametests::testCopy",
"pydicom/tests/test_valuerep.py::PersonNametests::testFormatting",
"pydicom/tests/test_valuerep.py::PersonNametests::testLastFirst",
"pydicom/tests/test_valuerep.py::PersonNametests::testNotEqual",
"pydicom/tests/test_valuerep.py::PersonNametests::testThreeComponent",
"pydicom/tests/test_valuerep.py::PersonNametests::testUnicodeJp",
"pydicom/tests/test_valuerep.py::PersonNametests::testUnicodeKr",
"pydicom/tests/test_valuerep.py::DateTimeTests::testDate",
"pydicom/tests/test_valuerep.py::DateTimeTests::testDateTime",
"pydicom/tests/test_valuerep.py::DateTimeTests::testTime"
]
| []
| MIT License | 1,660 | [
"pydicom/uid.py",
"pydicom/valuerep.py"
]
| [
"pydicom/uid.py",
"pydicom/valuerep.py"
]
|
|
zopefoundation__zope.security-31 | f2de4625c116085404958724468899dbe784bce6 | 2017-09-07 20:55:32 | c192803b8e92255aea5c45349fdbd478b173224f | diff --git a/CHANGES.rst b/CHANGES.rst
index c264be8..0bcf42b 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,6 +4,11 @@ Changes
4.1.2 (unreleased)
------------------
+- Fix `issue 7
+ <https://github.com/zopefoundation/zope.security/issues/7`_: The
+ pure-Python proxy didn't propagate ``TypeError`` from ``__repr__``
+ and ``__str__`` like the C implementation did.
+
- Fix `issue 27 <https://github.com/zopefoundation/zope.security/issues/27>`_:
iteration of ``zope.interface.providedBy()`` is now allowed by
default on all versions of Python. Previously it only worked on
diff --git a/src/zope/security/proxy.py b/src/zope/security/proxy.py
index 302257a..60dcae8 100644
--- a/src/zope/security/proxy.py
+++ b/src/zope/security/proxy.py
@@ -219,6 +219,11 @@ class ProxyPy(PyProxyBase):
def __str__(self):
try:
return _check_name(PyProxyBase.__str__)(self)
+ # The C implementation catches almost all exceptions; the
+ # exception is a TypeError that's raised when the repr returns
+ # the wrong type of object.
+ except TypeError:
+ raise
except:
# The C implementation catches all exceptions.
wrapped = super(PyProxyBase, self).__getattribute__('_wrapped')
@@ -229,8 +234,12 @@ class ProxyPy(PyProxyBase):
def __repr__(self):
try:
return _check_name(PyProxyBase.__repr__)(self)
+ # The C implementation catches almost all exceptions; the
+ # exception is a TypeError that's raised when the repr returns
+ # the wrong type of object.
+ except TypeError:
+ raise
except:
- # The C implementation catches all exceptions.
wrapped = super(PyProxyBase, self).__getattribute__('_wrapped')
return '<security proxied %s.%s instance at %s>' %(
wrapped.__class__.__module__, wrapped.__class__.__name__,
| security proxy breaks python expectation w/ str and repr
In https://bugs.launchpad.net/zope.security/+bug/156762, Barry Warsaw ([email protected]) reported:
> In Python, when an object has a `__repr__()` but no `__str__()`, and `str()` is called on that object, Python will fall back to calling `__repr__()`, as documented here:
>
> http://www.python.org/doc/current/ref/customization.html#l2h-179
>
> ``` python
> >> class Foo(object):
> ... def __repr__(self): return 'my repr'
> ...
> >> repr(Foo())
> 'my repr'
> >> str(Foo())
> 'my repr'
> ```
>
> However, Zope's security proxy does not mimic this behavior correctly. In the following, `listx` is an object of type `MailingList` which has a `__repr__()` but no `__str__()`:
>
> ``` python
> >> str(listx)
> '<security proxied canonical.launchpad.database.mailinglist.MailingList instance at 0xa7aca2c>'
> >> repr(listx)
> '<MailingList for team "teamx"; status=ACTIVE at 0xa7aca2c>'
> ```
>
> The `str(listx)` should print the same thing as `repr(listx)`.
| zopefoundation/zope.security | diff --git a/src/zope/security/tests/test_proxy.py b/src/zope/security/tests/test_proxy.py
index ca4a8a3..20f66da 100644
--- a/src/zope/security/tests/test_proxy.py
+++ b/src/zope/security/tests/test_proxy.py
@@ -19,31 +19,10 @@ import sys
from zope.security._compat import PYTHON2, PYPY, PURE_PYTHON
def _skip_if_not_Py2(testfunc):
- from functools import update_wrapper
- if not PYTHON2:
- def dummy(self):
- pass
- update_wrapper(dummy, testfunc)
- return dummy
- return testfunc
+ return unittest.skipUnless(PYTHON2, "Only on Py2")(testfunc)
def _skip_if_Py2(testfunc):
- from functools import update_wrapper
- if PYTHON2:
- def dummy(self):
- pass
- update_wrapper(dummy, testfunc)
- return dummy
- return testfunc
-
-def _skip_if_pypy250(testfunc):
- from functools import update_wrapper
- if PYPY and sys.pypy_version_info[:3] == (2,5,0):
- def dummy(self):
- pass
- update_wrapper(dummy, testfunc)
- return dummy
- return testfunc
+ return unittest.skipIf(PYTHON2, "Only on Py3")(testfunc)
class ProxyTestBase(object):
@@ -168,6 +147,20 @@ class ProxyTestBase(object):
'<security proxied %s.object '
'instance at %s>' % (_BUILTINS, address))
+ def test__str__fails_return(self):
+ from zope.security.interfaces import ForbiddenAttribute
+ class CustomStr(object):
+ def __str__(self):
+ "<CustomStr>" # Docstring, not a return
+
+ target = CustomStr()
+ checker = DummyChecker(ForbiddenAttribute, allowed=('__str__'))
+ proxy = self._makeOne(target, checker)
+ with self.assertRaises(TypeError):
+ str(target)
+ with self.assertRaises(TypeError):
+ str(proxy)
+
def test___repr___checker_allows_str(self):
target = object()
checker = DummyChecker()
@@ -186,6 +179,59 @@ class ProxyTestBase(object):
'<security proxied %s.object '
'instance at %s>' % (_BUILTINS, address))
+ def test__str__falls_through_to_repr_when_both_allowed(self):
+ from zope.security.interfaces import ForbiddenAttribute
+ class CustomRepr(object):
+ def __repr__(self):
+ return "<CustomRepr>"
+
+ target = CustomRepr()
+ checker = DummyChecker(ForbiddenAttribute, allowed=("__str__", '__repr__'))
+ proxy = self._makeOne(target, checker)
+ self.assertEqual(repr(proxy), "<CustomRepr>")
+ self.assertEqual(str(target), "<CustomRepr>")
+ self.assertEqual(str(proxy), str(target))
+
+ def test__str__doesnot_fall_through_to_repr_when_str_not_allowed(self):
+ from zope.security.interfaces import ForbiddenAttribute
+ class CustomRepr(object):
+ def __repr__(self):
+ return "<CustomRepr>"
+
+ target = CustomRepr()
+ checker = DummyChecker(ForbiddenAttribute, allowed=('__repr__'))
+ proxy = self._makeOne(target, checker)
+ self.assertEqual(repr(proxy), "<CustomRepr>")
+ self.assertEqual(str(target), "<CustomRepr>")
+ self.assertIn("<security proxied zope.security", str(proxy))
+
+ def test__str__doesnot_fall_through_to_repr_when_repr_not_allowed(self):
+ from zope.security.interfaces import ForbiddenAttribute
+ class CustomRepr(object):
+ def __repr__(self):
+ return "<CustomRepr>"
+
+ target = CustomRepr()
+ checker = DummyChecker(ForbiddenAttribute, allowed=('__str__'))
+ proxy = self._makeOne(target, checker)
+ self.assertEqual(str(target), "<CustomRepr>")
+ self.assertEqual(str(proxy), str(target))
+ self.assertIn("<security proxied zope.security", repr(proxy))
+
+ def test__str__falls_through_to_repr_but_repr_fails_return(self):
+ from zope.security.interfaces import ForbiddenAttribute
+ class CustomRepr(object):
+ def __repr__(self):
+ "<CustomRepr>" # Docstring, not a return
+
+ target = CustomRepr()
+ checker = DummyChecker(ForbiddenAttribute, allowed=('__repr__'))
+ proxy = self._makeOne(target, checker)
+ with self.assertRaises(TypeError):
+ repr(target)
+ with self.assertRaises(TypeError):
+ repr(proxy)
+
@_skip_if_not_Py2
def test___cmp___w_self(self):
target = object()
@@ -1713,12 +1759,6 @@ class ProxyTests(unittest.TestCase):
self.assertEqual(self.c, getChecker(self.p))
- # XXX: PyPy 2.5.0 has a bug where proxys around types
- # aren't correctly hashable, which breaks this part of the
- # test. This is fixed in 2.5.1+, but as of 2015-05-28,
- # TravisCI still uses 2.5.0.
-
- @_skip_if_pypy250
def testProxiedClassicClassAsDictKey(self):
from zope.security.proxy import ProxyFactory
class C(object):
@@ -1727,7 +1767,6 @@ class ProxyTests(unittest.TestCase):
pC = ProxyFactory(C, self.c)
self.assertEqual(d[pC], d[C])
- @_skip_if_pypy250
def testProxiedNewClassAsDictKey(self):
from zope.security.proxy import ProxyFactory
class C(object):
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"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": 3
},
"num_modified_files": 2
} | 4.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio",
"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
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
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
six==1.17.0
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
zope.component==5.1.0
zope.event==4.6
zope.hookable==5.4
zope.i18nmessageid==5.1.1
zope.interface==5.5.2
zope.location==4.3
zope.proxy==4.6.1
zope.schema==6.2.1
-e git+https://github.com/zopefoundation/zope.security.git@f2de4625c116085404958724468899dbe784bce6#egg=zope.security
| name: zope.security
channels:
- defaults
- https://repo.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
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- six==1.17.0
- tomli==1.2.3
- zope-component==5.1.0
- zope-event==4.6
- zope-hookable==5.4
- zope-i18nmessageid==5.1.1
- zope-interface==5.5.2
- zope-location==4.3
- zope-proxy==4.6.1
- zope-schema==6.2.1
prefix: /opt/conda/envs/zope.security
| [
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test__str__fails_return",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test__str__falls_through_to_repr_but_repr_fails_return"
]
| []
| [
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___abs___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___abs___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___add___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___add___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___and___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___and___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___bool___",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___call___w_checker_forbidden_attribute",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___call___w_checker_ok",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___call___w_checker_unauthorized",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___contains___hit_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___contains___miss_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___contains___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___delattr___w_checker_forbidden_attribute",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___delattr___w_checker_ok",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___delattr___w_checker_unauthorized",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___divmod___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___divmod___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___float___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___float___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___floordiv___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___floordiv___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___getattr___w_checker_forbidden_attribute",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___getattr___w_checker_ok",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___getattr___w_checker_unauthorized",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___getitem___mapping_hit_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___getitem___mapping_miss_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___getitem___mapping_w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___getitem___sequence_hit_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___getitem___sequence_miss_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___getitem___sequence_w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___hash___w_self",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___iadd___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___iadd___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___iadd___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___iand___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___iand___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___iand___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ifloordiv___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ifloordiv___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ifloordiv___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ilshift___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ilshift___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ilshift___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___imod___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___imod___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___imod___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___imul___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___imul___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___imul___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___int___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___int___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___invert___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___invert___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ior___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ior___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ior___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ipow___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ipow___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ipow___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___irshift___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___irshift___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___irshift___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___isub___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___isub___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___isub___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___itruediv___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___itruediv___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___itruediv___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ixor___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ixor___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___ixor___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___len___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___len___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___lshift___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___lshift___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___mod___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___mod___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___mul___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___mul___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___neg___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___neg___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___or___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___or___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___pos___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___pos___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___pow___w_x_proxied_allowed",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___pow___w_x_proxied_forbidden",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___pow___w_y_proxied_allowed",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___pow___w_y_proxied_forbidden",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___pow___w_z_proxied_allowed",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___pow___w_z_proxied_forbidden",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___repr___checker_allows_str",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___repr___checker_forbids_str",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___rshift___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___rshift___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___setattr___w_checker_forbidden_attribute",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___setattr___w_checker_ok",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___setattr___w_checker_unauthorized",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___setitem___mapping_hit_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___setitem___mapping_w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___setitem___sequence_hit_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___setitem___sequence_miss_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___setitem___sequence_w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___str___checker_allows_str",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___str___checker_forbids_str",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___sub___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___sub___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___truediv___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___truediv___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___xor___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test___xor___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test__str__doesnot_fall_through_to_repr_when_repr_not_allowed",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test__str__doesnot_fall_through_to_repr_when_str_not_allowed",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test__str__fails_return",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test__str__falls_through_to_repr_but_repr_fails_return",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test__str__falls_through_to_repr_when_both_allowed",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test_binops",
"src/zope/security/tests/test_proxy.py::ProxyCTests::test_ctor_w_checker_None",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___abs___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___abs___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___add___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___add___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___and___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___and___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___bool___",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___call___w_checker_forbidden_attribute",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___call___w_checker_ok",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___call___w_checker_unauthorized",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___contains___hit_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___contains___miss_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___contains___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___delattr___w__checker",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___delattr___w__wrapped",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___delattr___w_checker_forbidden_attribute",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___delattr___w_checker_ok",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___delattr___w_checker_unauthorized",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___divmod___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___divmod___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___float___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___float___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___floordiv___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___floordiv___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___getattr___w_checker_forbidden_attribute",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___getattr___w_checker_ok",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___getattr___w_checker_unauthorized",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___getitem___mapping_hit_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___getitem___mapping_miss_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___getitem___mapping_w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___getitem___sequence_hit_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___getitem___sequence_miss_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___getitem___sequence_w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___hash___w_self",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___iadd___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___iadd___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___iadd___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___iand___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___iand___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___iand___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ifloordiv___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ifloordiv___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ifloordiv___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ilshift___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ilshift___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ilshift___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___imod___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___imod___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___imod___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___imul___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___imul___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___imul___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___int___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___int___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___invert___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___invert___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ior___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ior___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ior___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ipow___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ipow___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ipow___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___irshift___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___irshift___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___irshift___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___isub___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___isub___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___isub___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___itruediv___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___itruediv___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___itruediv___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ixor___inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ixor___not_inplace_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___ixor___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___len___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___len___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___lshift___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___lshift___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___mod___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___mod___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___mul___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___mul___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___neg___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___neg___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___or___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___or___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___pos___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___pos___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___pow___w_x_proxied_allowed",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___pow___w_x_proxied_forbidden",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___pow___w_y_proxied_allowed",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___pow___w_y_proxied_forbidden",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___pow___w_z_proxied_allowed",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___pow___w_z_proxied_forbidden",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___repr___checker_allows_str",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___repr___checker_forbids_str",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___rshift___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___rshift___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___setattr___w_checker_forbidden_attribute",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___setattr___w_checker_ok",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___setattr___w_checker_unauthorized",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___setitem___mapping_hit_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___setitem___mapping_w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___setitem___sequence_hit_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___setitem___sequence_miss_w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___setitem___sequence_w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___str___checker_allows_str",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___str___checker_forbids_str",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___sub___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___sub___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___truediv___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___truediv___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___xor___w_checker_allows",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test___xor___w_checker_forbids",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test__str__doesnot_fall_through_to_repr_when_repr_not_allowed",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test__str__doesnot_fall_through_to_repr_when_str_not_allowed",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test__str__falls_through_to_repr_when_both_allowed",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test_binops",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test_ctor_w_checker",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test_ctor_w_checker_None",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test_getObjectPy_initial_conditions",
"src/zope/security/tests/test_proxy.py::ProxyPyTests::test_wrapper_checker_unaccessible",
"src/zope/security/tests/test_proxy.py::Test_getTestProxyItems::test_w_empty_checker",
"src/zope/security/tests/test_proxy.py::Test_getTestProxyItems::test_w_non_empty_checker",
"src/zope/security/tests/test_proxy.py::Test_isinstance::test_w_proxied_object",
"src/zope/security/tests/test_proxy.py::Test_isinstance::test_w_unproxied_object",
"src/zope/security/tests/test_proxy.py::ProxyTests::testCallFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testCallOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testContainsFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testContainsOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testDelItemFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testDelItemOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testDerivation",
"src/zope/security/tests/test_proxy.py::ProxyTests::testGetAttrFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testGetAttrOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testGetChecker",
"src/zope/security/tests/test_proxy.py::ProxyTests::testGetItemFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testGetItemOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testGetObject",
"src/zope/security/tests/test_proxy.py::ProxyTests::testHashOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testIterFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testIterOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testLenFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testLenOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testNextFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testNextOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testNonzeroOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testProxiedClassicClassAsDictKey",
"src/zope/security/tests/test_proxy.py::ProxyTests::testProxiedNewClassAsDictKey",
"src/zope/security/tests/test_proxy.py::ProxyTests::testRepr",
"src/zope/security/tests/test_proxy.py::ProxyTests::testRichCompareOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testSetAttrFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testSetAttrOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testSetItemFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testSetItemOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testSetSliceFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testSetSliceOK",
"src/zope/security/tests/test_proxy.py::ProxyTests::testSliceFail",
"src/zope/security/tests/test_proxy.py::ProxyTests::testStr",
"src/zope/security/tests/test_proxy.py::ProxyTests::test_binops",
"src/zope/security/tests/test_proxy.py::ProxyTests::test_inplace",
"src/zope/security/tests/test_proxy.py::ProxyTests::test_unops",
"src/zope/security/tests/test_proxy.py::test_using_mapping_slots_hack",
"src/zope/security/tests/test_proxy.py::LocationProxySecurityCheckerTests::test_LocationProxy_gets_a_security_checker_when_importing_z_security",
"src/zope/security/tests/test_proxy.py::test_suite"
]
| []
| Zope Public License 2.1 | 1,661 | [
"CHANGES.rst",
"src/zope/security/proxy.py"
]
| [
"CHANGES.rst",
"src/zope/security/proxy.py"
]
|
|
oasis-open__cti-python-stix2-52 | adac43708b52884c82bb3fae7127effa57de5017 | 2017-09-08 17:11:59 | 58f39f80af5cbfe02879c2efa4b3b4ef7a504390 | diff --git a/stix2/__init__.py b/stix2/__init__.py
index c2aae2e..35b65b0 100644
--- a/stix2/__init__.py
+++ b/stix2/__init__.py
@@ -7,7 +7,7 @@ from .common import (TLP_AMBER, TLP_GREEN, TLP_RED, TLP_WHITE, CustomMarking,
ExternalReference, GranularMarking, KillChainPhase,
MarkingDefinition, StatementMarking, TLPMarking)
from .core import Bundle, _register_type, parse
-from .environment import ObjectFactory
+from .environment import Environment, ObjectFactory
from .observables import (URL, AlternateDataStream, ArchiveExt, Artifact,
AutonomousSystem, CustomObservable, Directory,
DomainName, EmailAddress, EmailMessage,
@@ -41,6 +41,13 @@ from .patterns import (AndBooleanExpression, AndObservationExpression,
from .sdo import (AttackPattern, Campaign, CourseOfAction, CustomObject,
Identity, Indicator, IntrusionSet, Malware, ObservedData,
Report, ThreatActor, Tool, Vulnerability)
+from .sources import CompositeDataSource
+from .sources.filesystem import (FileSystemSink, FileSystemSource,
+ FileSystemStore)
+from .sources.filters import Filter
+from .sources.memory import MemorySink, MemorySource, MemoryStore
+from .sources.taxii import (TAXIICollectionSink, TAXIICollectionSource,
+ TAXIICollectionStore)
from .sro import Relationship, Sighting
from .utils import get_dict, new_version, revoke
from .version import __version__
diff --git a/stix2/core.py b/stix2/core.py
index be2a53d..0271e34 100644
--- a/stix2/core.py
+++ b/stix2/core.py
@@ -75,13 +75,13 @@ def parse(data, allow_custom=False):
"""Deserialize a string or file-like object into a STIX object.
Args:
- data: The STIX 2 string to be parsed.
+ data (str, dict, file-like object): The STIX 2 content to be parsed.
allow_custom (bool): Whether to allow custom properties or not. Default: False.
Returns:
An instantiated Python STIX object.
- """
+ """
obj = get_dict(data)
if 'type' not in obj:
@@ -96,6 +96,6 @@ def parse(data, allow_custom=False):
def _register_type(new_type):
"""Register a custom STIX Object type.
- """
+ """
OBJ_MAP[new_type._type] = new_type
diff --git a/stix2/environment.py b/stix2/environment.py
index f855755..8e24c9b 100644
--- a/stix2/environment.py
+++ b/stix2/environment.py
@@ -1,22 +1,22 @@
import copy
+from .core import parse as _parse
+from .sources import CompositeDataSource, DataSource, DataStore
-class ObjectFactory(object):
- """Object Factory
- Used to easily create STIX objects with default values for certain
- properties.
+class ObjectFactory(object):
+ """Easily create STIX objects with default values for certain properties.
Args:
- created_by_ref: Default created_by_ref value to apply to all
+ created_by_ref (optional): Default created_by_ref value to apply to all
objects created by this factory.
- created: Default created value to apply to all
+ created (optional): Default created value to apply to all
objects created by this factory.
- external_references: Default `external_references` value to apply
+ external_references (optional): Default `external_references` value to apply
to all objects created by this factory.
- object_marking_refs: Default `object_marking_refs` value to apply
+ object_marking_refs (optional): Default `object_marking_refs` value to apply
to all objects created by this factory.
- list_append: When a default is set for a list property like
+ list_append (bool, optional): When a default is set for a list property like
`external_references` or `object_marking_refs` and a value for
that property is passed into `create()`, if this is set to True,
that value will be added to the list alongside the default. If
@@ -44,6 +44,13 @@ class ObjectFactory(object):
self._list_properties = ['external_references', 'object_marking_refs']
def create(self, cls, **kwargs):
+ """Create a STIX object using object factory defaults.
+
+ Args:
+ cls: the python-stix2 class of the object to be created (eg. Indicator)
+ **kwargs: The property/value pairs of the STIX object to be created
+ """
+
# Use self.defaults as the base, but update with any explicit args
# provided by the user.
properties = copy.deepcopy(self._defaults)
@@ -66,3 +73,84 @@ class ObjectFactory(object):
properties.update(**kwargs)
return cls(**properties)
+
+
+class Environment(object):
+ """
+
+ Args:
+ factory (ObjectFactory, optional): Factory for creating objects with common
+ defaults for certain properties.
+ store (DataStore, optional): Data store providing the source and sink for the
+ environment.
+ source (DataSource, optional): Source for retrieving STIX objects.
+ sink (DataSink, optional): Destination for saving STIX objects.
+ Invalid if `store` is also provided.
+ """
+
+ def __init__(self, factory=ObjectFactory(), store=None, source=None, sink=None):
+ self.factory = factory
+ self.source = CompositeDataSource()
+ if store:
+ self.source.add_data_source(store.source)
+ self.sink = store.sink
+ if source:
+ self.source.add_data_source(source)
+ if sink:
+ if store:
+ raise ValueError("Data store already provided! Environment may only have one data sink.")
+ self.sink = sink
+
+ def create(self, *args, **kwargs):
+ return self.factory.create(*args, **kwargs)
+ create.__doc__ = ObjectFactory.create.__doc__
+
+ def get(self, *args, **kwargs):
+ try:
+ return self.source.get(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('Environment has no data source to query')
+ get.__doc__ = DataStore.get.__doc__
+
+ def all_versions(self, *args, **kwargs):
+ """Retrieve all versions of a single STIX object by ID.
+ """
+ try:
+ return self.source.all_versions(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('Environment has no data source to query')
+ all_versions.__doc__ = DataStore.all_versions.__doc__
+
+ def query(self, *args, **kwargs):
+ """Retrieve STIX objects matching a set of filters.
+ """
+ try:
+ return self.source.query(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('Environment has no data source to query')
+ query.__doc__ = DataStore.query.__doc__
+
+ def add_filters(self, *args, **kwargs):
+ try:
+ return self.source.add_filters(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('Environment has no data source')
+ add_filters.__doc__ = DataSource.add_filters.__doc__
+
+ def add_filter(self, *args, **kwargs):
+ try:
+ return self.source.add_filter(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('Environment has no data source')
+ add_filter.__doc__ = DataSource.add_filter.__doc__
+
+ def add(self, *args, **kwargs):
+ try:
+ return self.sink.add(*args, **kwargs)
+ except AttributeError:
+ raise AttributeError('Environment has no data sink to put objects in')
+ add.__doc__ = DataStore.add.__doc__
+
+ def parse(self, *args, **kwargs):
+ return _parse(*args, **kwargs)
+ parse.__doc__ = _parse.__doc__
diff --git a/stix2/sources/__init__.py b/stix2/sources/__init__.py
index b50fd1d..cb6e5b5 100644
--- a/stix2/sources/__init__.py
+++ b/stix2/sources/__init__.py
@@ -5,7 +5,7 @@ Classes:
DataStore
DataSink
DataSource
- STIXCommonPropertyFilters
+ CompositeDataSource
TODO:Test everything
@@ -45,30 +45,29 @@ class DataStore(object):
self.sink = sink
def get(self, stix_id):
- """
+ """Retrieve the most recent version of a single STIX object by ID.
+
Notes:
Translate API get() call to the appropriate DataSource call.
Args:
- stix_id (str): the id of the STIX 2.0 object to retrieve. Should
- return a single object, the most recent version of the object
- specified by the "id".
+ stix_id (str): the id of the STIX 2.0 object to retrieve.
Returns:
- stix_obj (dictionary): the STIX object to be returned
+ stix_obj (dictionary): the single most recent version of the STIX
+ object specified by the "id".
"""
return self.source.get(stix_id)
def all_versions(self, stix_id):
- """
+ """Retrieve all versions of a single STIX object by ID.
+
Implement:
Translate all_versions() call to the appropriate DataSource call
Args:
- stix_id (str): the id of the STIX 2.0 object to retrieve. Should
- return a single object, the most recent version of the object
- specified by the "id".
+ stix_id (str): the id of the STIX 2.0 object to retrieve.
Returns:
stix_objs (list): a list of STIX objects (where each object is a
@@ -78,7 +77,8 @@ class DataStore(object):
return self.source.all_versions(stix_id)
def query(self, query):
- """
+ """Retrieve STIX objects matching a set of filters.
+
Notes:
Implement the specific data source API calls, processing,
functionality required for retrieving query from the data source.
@@ -95,10 +95,15 @@ class DataStore(object):
return self.source.query(query=query)
def add(self, stix_objs):
- """
+ """Store STIX objects.
+
Notes:
Translate add() to the appropriate DataSink call().
+ Args:
+ stix_objs (list): a list of STIX objects (where each object is a
+ STIX object)
+
"""
return self.sink.add(stix_objs)
@@ -116,11 +121,16 @@ class DataSink(object):
self.id = make_id()
def add(self, stix_objs):
- """
+ """Store STIX objects.
+
Notes:
Implement the specific data sink API calls, processing,
functionality required for adding data to the sink
+ Args:
+ stix_objs (list): a list of STIX objects (where each object is a
+ STIX object)
+
"""
raise NotImplementedError()
@@ -201,16 +211,22 @@ class DataSource(object):
raise NotImplementedError()
def add_filters(self, filters):
- """Add multiple filters to the DataSource.
+ """Add multiple filters to be applied to all queries for STIX objects.
Args:
filters (list): list of filters (dict) to add to the Data Source.
+
"""
for filter in filters:
self.add_filter(filter)
def add_filter(self, filter):
- """Add a filter."""
+ """Add a filter to be applied to all queries for STIX objects.
+
+ Args:
+ filter: filter to add to the Data Source.
+
+ """
# check filter field is a supported STIX 2.0 common field
if filter.field not in STIX_COMMON_FIELDS:
raise ValueError("Filter 'field' is not a STIX 2.0 common property. Currently only STIX object common properties supported")
@@ -226,7 +242,7 @@ class DataSource(object):
self.filters.add(filter)
def apply_common_filters(self, stix_objs, query):
- """Evaluates filters against a set of STIX 2.0 objects
+ """Evaluate filters against a set of STIX 2.0 objects.
Supports only STIX 2.0 common property fields
@@ -300,11 +316,10 @@ class DataSource(object):
class CompositeDataSource(DataSource):
- """Composite Data Source
+ """Controller for all the defined/configured STIX Data Sources.
- Acts as a controller for all the defined/configured STIX Data Sources
- e.g. a user can define n Data Sources - creating Data Source (objects)
- for each. There is only one instance of this for any python STIX 2.0
+ E.g. a user can define n Data Sources - creating Data Source (objects)
+ for each. There is only one instance of this for any Python STIX 2.0
application.
Attributes:
@@ -314,8 +329,7 @@ class CompositeDataSource(DataSource):
"""
def __init__(self):
- """
- Creates a new STIX Data Source.
+ """Create a new STIX Data Source.
Args:
name (str): A string containing the name to attach in the
@@ -348,6 +362,9 @@ class CompositeDataSource(DataSource):
stix_obj (dict): the STIX object to be returned.
"""
+ if not self.get_all_data_sources():
+ raise AttributeError('CompositeDataSource has no data sources')
+
all_data = []
# for every configured Data Source, call its retrieve handler
@@ -384,6 +401,9 @@ class CompositeDataSource(DataSource):
all_data (list): list of STIX objects that have the specified id
"""
+ if not self.get_all_data_sources():
+ raise AttributeError('CompositeDataSource has no data sources')
+
all_data = []
all_filters = self.filters
@@ -403,9 +423,7 @@ class CompositeDataSource(DataSource):
return all_data
def query(self, query=None, _composite_filters=None):
- """Composite data source query
-
- Federate the query to all Data Sources attached to the
+ """Federate the query to all Data Sources attached to the
Composite Data Source.
Args:
@@ -418,6 +436,9 @@ class CompositeDataSource(DataSource):
all_data (list): list of STIX objects to be returned
"""
+ if not self.get_all_data_sources():
+ raise AttributeError('CompositeDataSource has no data sources')
+
if not query:
query = []
@@ -448,6 +469,8 @@ class CompositeDataSource(DataSource):
to the Composite Data Source
"""
+ if not isinstance(data_sources, list):
+ data_sources = [data_sources]
for ds in data_sources:
if issubclass(ds.__class__, DataSource):
if ds.id in self.data_sources:
diff --git a/stix2/sources/memory.py b/stix2/sources/memory.py
index 9eca969..95d053c 100644
--- a/stix2/sources/memory.py
+++ b/stix2/sources/memory.py
@@ -22,33 +22,22 @@ import collections
import json
import os
-from stix2validator import validate_instance
-
from stix2 import Bundle
from stix2.sources import DataSink, DataSource, DataStore
from stix2.sources.filters import Filter
-def _add(store, stix_data):
+def _add(store, stix_data=None):
"""Adds stix objects to MemoryStore/Source/Sink."""
if isinstance(stix_data, collections.Mapping):
# stix objects are in a bundle
- # verify STIX json data
- r = validate_instance(stix_data)
# make dictionary of the objects for easy lookup
- if r.is_valid:
- for stix_obj in stix_data["objects"]:
- store.data[stix_obj["id"]] = stix_obj
- else:
- raise ValueError("Error: data passed was found to not be valid by the STIX 2 Validator: \n%s", r.as_dict())
+ for stix_obj in stix_data["objects"]:
+ store.data[stix_obj["id"]] = stix_obj
elif isinstance(stix_data, list):
# stix objects are in a list
for stix_obj in stix_data:
- r = validate_instance(stix_obj)
- if r.is_valid:
- store.data[stix_obj["id"]] = stix_obj
- else:
- raise ValueError("Error: STIX object %s is not valid under STIX 2 validator.\n%s", stix_obj["id"], r)
+ store.data[stix_obj["id"]] = stix_obj
else:
raise ValueError("stix_data must be in bundle format or raw list")
@@ -56,7 +45,7 @@ def _add(store, stix_data):
class MemoryStore(DataStore):
"""
"""
- def __init__(self, stix_data):
+ def __init__(self, stix_data=None):
"""
Notes:
It doesn't make sense to create a MemoryStore by passing
@@ -83,7 +72,7 @@ class MemoryStore(DataStore):
class MemorySink(DataSink):
"""
"""
- def __init__(self, stix_data, _store=False):
+ def __init__(self, stix_data=None, _store=False):
"""
Args:
stix_data (dictionary OR list): valid STIX 2.0 content in
@@ -114,7 +103,7 @@ class MemorySink(DataSink):
class MemorySource(DataSource):
- def __init__(self, stix_data, _store=False):
+ def __init__(self, stix_data=None, _store=False):
"""
Args:
stix_data (dictionary OR list): valid STIX 2.0 content in
@@ -193,10 +182,5 @@ class MemorySource(DataSource):
file_path = os.path.abspath(file_path)
stix_data = json.load(open(file_path, "r"))
- r = validate_instance(stix_data)
-
- if r.is_valid:
- for stix_obj in stix_data["objects"]:
- self.data[stix_obj["id"]] = stix_obj
-
- raise ValueError("Error: STIX data loaded from file (%s) was found to not be validated by STIX 2 Validator.\n%s", file_path, r)
+ for stix_obj in stix_data["objects"]:
+ self.data[stix_obj["id"]] = stix_obj
| Create "Environment" class
This is an abstraction that will encompass a data source, data sink, and object factory, and potentially other state, in a unified interface for interacting with external STIX repositories. | oasis-open/cti-python-stix2 | diff --git a/stix2/test/test_environment.py b/stix2/test/test_environment.py
index 9be8101..0871bb5 100644
--- a/stix2/test/test_environment.py
+++ b/stix2/test/test_environment.py
@@ -1,7 +1,9 @@
+import pytest
+
import stix2
-from .constants import (FAKE_TIME, IDENTITY_ID, IDENTITY_KWARGS,
- INDICATOR_KWARGS)
+from .constants import (FAKE_TIME, IDENTITY_ID, IDENTITY_KWARGS, INDICATOR_ID,
+ INDICATOR_KWARGS, MALWARE_ID)
def test_object_factory_created_by_ref_str():
@@ -81,3 +83,106 @@ def test_object_factory_list_replace():
ind = factory.create(stix2.Indicator, external_references=ext_ref2, **INDICATOR_KWARGS)
assert len(ind.external_references) == 1
assert ind.external_references[0].source_name == "Yet Another Threat Report"
+
+
+def test_environment_functions():
+ env = stix2.Environment(stix2.ObjectFactory(created_by_ref=IDENTITY_ID),
+ stix2.MemoryStore())
+
+ # Create a STIX object
+ ind = env.create(stix2.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS)
+ assert ind.created_by_ref == IDENTITY_ID
+
+ # Add objects to datastore
+ ind2 = ind.new_version(labels=['benign'])
+ env.add([ind, ind2])
+
+ # Get both versions of the object
+ resp = env.all_versions(INDICATOR_ID)
+ assert len(resp) == 1 # should be 2, but MemoryStore only keeps 1 version of objects
+
+ # Get just the most recent version of the object
+ resp = env.get(INDICATOR_ID)
+ assert resp['labels'][0] == 'benign'
+
+ # Search on something other than id
+ query = [stix2.Filter('type', '=', 'vulnerability')]
+ resp = env.query(query)
+ assert len(resp) == 0
+
+ # See different results after adding filters to the environment
+ env.add_filters([stix2.Filter('type', '=', 'indicator'),
+ stix2.Filter('created_by_ref', '=', IDENTITY_ID)])
+ env.add_filter(stix2.Filter('labels', '=', 'benign')) # should be 'malicious-activity'
+ resp = env.get(INDICATOR_ID)
+ assert resp['labels'][0] == 'benign' # should be 'malicious-activity'
+
+
+def test_environment_source_and_sink():
+ ind = stix2.Indicator(id=INDICATOR_ID, **INDICATOR_KWARGS)
+ env = stix2.Environment(source=stix2.MemorySource([ind]), sink=stix2.MemorySink([ind]))
+ assert env.get(INDICATOR_ID).labels[0] == 'malicious-activity'
+
+
+def test_environment_datastore_and_sink():
+ with pytest.raises(ValueError) as excinfo:
+ stix2.Environment(factory=stix2.ObjectFactory(),
+ store=stix2.MemoryStore(), sink=stix2.MemorySink)
+ assert 'Data store already provided' in str(excinfo.value)
+
+
+def test_environment_no_datastore():
+ env = stix2.Environment(factory=stix2.ObjectFactory())
+
+ with pytest.raises(AttributeError) as excinfo:
+ env.add(stix2.Indicator(**INDICATOR_KWARGS))
+ assert 'Environment has no data sink to put objects in' in str(excinfo.value)
+
+ with pytest.raises(AttributeError) as excinfo:
+ env.get(INDICATOR_ID)
+ assert 'Environment has no data source' in str(excinfo.value)
+
+ with pytest.raises(AttributeError) as excinfo:
+ env.all_versions(INDICATOR_ID)
+ assert 'Environment has no data source' in str(excinfo.value)
+
+ with pytest.raises(AttributeError) as excinfo:
+ env.query(INDICATOR_ID)
+ assert 'Environment has no data source' in str(excinfo.value)
+
+ with pytest.raises(AttributeError) as excinfo:
+ env.add_filters(INDICATOR_ID)
+ assert 'Environment has no data source' in str(excinfo.value)
+
+ with pytest.raises(AttributeError) as excinfo:
+ env.add_filter(INDICATOR_ID)
+ assert 'Environment has no data source' in str(excinfo.value)
+
+
+def test_environment_datastore_and_no_object_factory():
+ # Uses a default object factory
+ env = stix2.Environment(store=stix2.MemoryStore())
+ ind = env.create(stix2.Indicator, id=INDICATOR_ID, **INDICATOR_KWARGS)
+ assert ind.id == INDICATOR_ID
+
+
+def test_parse_malware():
+ env = stix2.Environment()
+ data = """{
+ "type": "malware",
+ "id": "malware--fedcba98-7654-3210-fedc-ba9876543210",
+ "created": "2017-01-01T12:34:56.000Z",
+ "modified": "2017-01-01T12:34:56.000Z",
+ "name": "Cryptolocker",
+ "labels": [
+ "ransomware"
+ ]
+ }"""
+ mal = env.parse(data)
+
+ assert mal.type == 'malware'
+ assert mal.id == MALWARE_ID
+ assert mal.created == FAKE_TIME
+ assert mal.modified == FAKE_TIME
+ assert mal.labels == ['ransomware']
+ assert mal.name == "Cryptolocker"
| {
"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": 3,
"test_score": 3
},
"num_modified_files": 5
} | 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": null,
"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"
} | alabaster==0.7.13
antlr4-python3-runtime==4.9.3
appdirs==1.4.4
attrs==21.4.0
Babel==2.11.0
bump2version==1.0.1
bumpversion==0.6.0
certifi==2021.5.30
cfgv==3.3.1
charset-normalizer==2.0.12
colorama==0.4.5
coverage==6.2
cpe==1.3.1
distlib==0.3.9
docutils==0.18.1
filelock==3.4.1
identify==2.4.4
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.2.3
iniconfig==1.1.1
itsdangerous==2.0.1
Jinja2==3.0.3
jsonpointer==2.3
jsonschema==3.2.0
MarkupSafe==2.0.1
nodeenv==1.6.0
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
pre-commit==2.17.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
pytest-cov==4.0.0
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.1
requests==2.27.1
requests-cache==0.7.5
rfc3339-validator==0.1.4
rfc3986-validator==0.1.1
simplejson==3.20.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-prompt==1.5.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
-e git+https://github.com/oasis-open/cti-python-stix2.git@adac43708b52884c82bb3fae7127effa57de5017#egg=stix2
stix2-patterns==2.0.0
stix2-validator==3.0.2
taxii2-client==2.3.0
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
url-normalize==1.4.3
urllib3==1.26.20
virtualenv==20.16.2
webcolors==1.11.1
zipp==3.6.0
| name: cti-python-stix2
channels:
- defaults
- https://repo.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
- antlr4-python3-runtime==4.9.3
- appdirs==1.4.4
- attrs==21.4.0
- babel==2.11.0
- bump2version==1.0.1
- bumpversion==0.6.0
- cfgv==3.3.1
- charset-normalizer==2.0.12
- colorama==0.4.5
- coverage==6.2
- cpe==1.3.1
- distlib==0.3.9
- docutils==0.18.1
- filelock==3.4.1
- identify==2.4.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- importlib-resources==5.2.3
- iniconfig==1.1.1
- itsdangerous==2.0.1
- jinja2==3.0.3
- jsonpointer==2.3
- jsonschema==3.2.0
- markupsafe==2.0.1
- nodeenv==1.6.0
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- pre-commit==2.17.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- pytest-cov==4.0.0
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==6.0.1
- requests==2.27.1
- requests-cache==0.7.5
- rfc3339-validator==0.1.4
- rfc3986-validator==0.1.1
- simplejson==3.20.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-prompt==1.5.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
- stix2-patterns==2.0.0
- stix2-validator==3.0.2
- taxii2-client==2.3.0
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- url-normalize==1.4.3
- urllib3==1.26.20
- virtualenv==20.16.2
- webcolors==1.11.1
- zipp==3.6.0
prefix: /opt/conda/envs/cti-python-stix2
| [
"stix2/test/test_environment.py::test_environment_functions",
"stix2/test/test_environment.py::test_environment_source_and_sink",
"stix2/test/test_environment.py::test_environment_datastore_and_sink",
"stix2/test/test_environment.py::test_environment_no_datastore",
"stix2/test/test_environment.py::test_environment_datastore_and_no_object_factory",
"stix2/test/test_environment.py::test_parse_malware"
]
| []
| [
"stix2/test/test_environment.py::test_object_factory_created_by_ref_str",
"stix2/test/test_environment.py::test_object_factory_created_by_ref_obj",
"stix2/test/test_environment.py::test_object_factory_override_default",
"stix2/test/test_environment.py::test_object_factory_created",
"stix2/test/test_environment.py::test_object_factory_external_resource",
"stix2/test/test_environment.py::test_object_factory_obj_markings",
"stix2/test/test_environment.py::test_object_factory_list_append",
"stix2/test/test_environment.py::test_object_factory_list_replace"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,662 | [
"stix2/environment.py",
"stix2/sources/__init__.py",
"stix2/sources/memory.py",
"stix2/core.py",
"stix2/__init__.py"
]
| [
"stix2/environment.py",
"stix2/sources/__init__.py",
"stix2/sources/memory.py",
"stix2/core.py",
"stix2/__init__.py"
]
|
|
NeuralEnsemble__python-neo-382 | fec5dfca4edd6a2a04cc0b8e274d01009a1c0362 | 2017-09-09 15:14:24 | f0285a7ab15ff6535d3e6736e0163c4fa6aea091 | diff --git a/neo/core/analogsignal.py b/neo/core/analogsignal.py
index aa971c80..fec332ea 100644
--- a/neo/core/analogsignal.py
+++ b/neo/core/analogsignal.py
@@ -251,7 +251,7 @@ class AnalogSignal(BaseNeo, pq.Quantity):
self.file_origin = getattr(obj, 'file_origin', None)
self.description = getattr(obj, 'description', None)
- # Parents objects
+ # Parent objects
self.segment = getattr(obj, 'segment', None)
self.channel_index = getattr(obj, 'channel_index', None)
@@ -437,7 +437,10 @@ class AnalogSignal(BaseNeo, pq.Quantity):
new = self.__class__(signal=signal, units=to_u,
sampling_rate=self.sampling_rate)
new._copy_data_complement(self)
+ new.channel_index = self.channel_index
+ new.segment = self.segment
new.annotations.update(self.annotations)
+
return new
def duplicate_with_new_array(self, signal):
diff --git a/neo/core/container.py b/neo/core/container.py
index f59c1641..5f4535bf 100644
--- a/neo/core/container.py
+++ b/neo/core/container.py
@@ -3,8 +3,7 @@
This module implements generic container base class that all neo container
object inherit from. It provides shared methods for all container types.
-:class:`Container` is derived from :class:`BaseNeo` but is
-defined in :module:`neo.core.analogsignalarray`.
+:class:`Container` is derived from :class:`BaseNeo`
"""
# needed for python 3 compatibility
diff --git a/neo/core/irregularlysampledsignal.py b/neo/core/irregularlysampledsignal.py
index 62e9c4ac..8d919a8d 100644
--- a/neo/core/irregularlysampledsignal.py
+++ b/neo/core/irregularlysampledsignal.py
@@ -208,6 +208,10 @@ class IrregularlySampledSignal(BaseNeo, pq.Quantity):
self.file_origin = getattr(obj, 'file_origin', None)
self.description = getattr(obj, 'description', None)
+ # Parent objects
+ self.segment = getattr(obj, 'segment', None)
+ self.channel_index = getattr(obj, 'channel_index', None)
+
def __repr__(self):
'''
Returns a string representing the :class:`IrregularlySampledSignal`.
@@ -456,6 +460,8 @@ class IrregularlySampledSignal(BaseNeo, pq.Quantity):
signal = cf * self.magnitude
new = self.__class__(times=self.times, signal=signal, units=to_u)
new._copy_data_complement(self)
+ new.channel_index = self.channel_index
+ new.segment = self.segment
new.annotations.update(self.annotations)
return new
diff --git a/neo/core/spiketrain.py b/neo/core/spiketrain.py
index 5d874d95..79e3527d 100644
--- a/neo/core/spiketrain.py
+++ b/neo/core/spiketrain.py
@@ -330,12 +330,15 @@ class SpikeTrain(BaseNeo, pq.Quantity):
if self.dimensionality == pq.quantity.validate_dimensionality(units):
return self.copy()
spikes = self.view(pq.Quantity)
- return SpikeTrain(times=spikes, t_stop=self.t_stop, units=units,
- sampling_rate=self.sampling_rate,
- t_start=self.t_start, waveforms=self.waveforms,
- left_sweep=self.left_sweep, name=self.name,
- file_origin=self.file_origin,
- description=self.description, **self.annotations)
+ obj = SpikeTrain(times=spikes, t_stop=self.t_stop, units=units,
+ sampling_rate=self.sampling_rate,
+ t_start=self.t_start, waveforms=self.waveforms,
+ left_sweep=self.left_sweep, name=self.name,
+ file_origin=self.file_origin,
+ description=self.description, **self.annotations)
+ obj.segment = self.segment
+ obj.unit = self.unit
+ return obj
def __reduce__(self):
'''
| AnalogSignal.rescale() does not preserve parent objects
The same is true for IrregularlySampledSignal and SpikeTrain. | NeuralEnsemble/python-neo | diff --git a/neo/test/coretest/test_analogsignal.py b/neo/test/coretest/test_analogsignal.py
index e56e48ab..bfadb827 100644
--- a/neo/test/coretest/test_analogsignal.py
+++ b/neo/test/coretest/test_analogsignal.py
@@ -302,7 +302,7 @@ class TestAnalogSignalArrayMethods(unittest.TestCase):
self.signal1 = AnalogSignal(self.data1quant, sampling_rate=1*pq.kHz,
name='spam', description='eggs',
file_origin='testfile.txt', arg1='test')
- self.signal1.segment = 1
+ self.signal1.segment = Segment()
self.signal1.channel_index = ChannelIndex(index=[0])
def test__compliant(self):
@@ -392,8 +392,8 @@ class TestAnalogSignalArrayMethods(unittest.TestCase):
def test__copy_should_let_access_to_parents_objects(self):
##copy
result = self.signal1.copy()
- self.assertEqual(result.segment, self.signal1.segment)
- self.assertEqual(result.channel_index, self.signal1.channel_index)
+ self.assertIs(result.segment, self.signal1.segment)
+ self.assertIs(result.channel_index, self.signal1.channel_index)
## deep copy (not fixed yet)
#result = copy.deepcopy(self.signal1)
#self.assertEqual(result.segment, self.signal1.segment)
@@ -452,6 +452,11 @@ class TestAnalogSignalArrayMethods(unittest.TestCase):
assert_array_equal(result.magnitude, self.data1.reshape(-1, 1))
assert_same_sub_schema(result, self.signal1)
+ self.assertIsInstance(result.channel_index, ChannelIndex)
+ self.assertIsInstance(result.segment, Segment)
+ self.assertIs(result.channel_index, self.signal1.channel_index)
+ self.assertIs(result.segment, self.signal1.segment)
+
def test__rescale_new(self):
result = self.signal1.copy()
result = result.rescale(pq.pA)
@@ -466,6 +471,11 @@ class TestAnalogSignalArrayMethods(unittest.TestCase):
self.assertEqual(result.units, 1*pq.pA)
assert_arrays_almost_equal(np.array(result), self.data1.reshape(-1, 1)*1000., 1e-10)
+ self.assertIsInstance(result.channel_index, ChannelIndex)
+ self.assertIsInstance(result.segment, Segment)
+ self.assertIs(result.channel_index, self.signal1.channel_index)
+ self.assertIs(result.segment, self.signal1.segment)
+
def test__rescale_new_incompatible_ValueError(self):
self.assertRaises(ValueError, self.signal1.rescale, pq.mV)
diff --git a/neo/test/coretest/test_irregularysampledsignal.py b/neo/test/coretest/test_irregularysampledsignal.py
index 1d379f65..c21cf68e 100644
--- a/neo/test/coretest/test_irregularysampledsignal.py
+++ b/neo/test/coretest/test_irregularysampledsignal.py
@@ -19,7 +19,7 @@ else:
HAVE_IPYTHON = True
from neo.core.irregularlysampledsignal import IrregularlySampledSignal
-from neo.core import Segment
+from neo.core import Segment, ChannelIndex
from neo.test.tools import (assert_arrays_almost_equal, assert_arrays_equal,
assert_neo_object_is_compliant,
assert_same_sub_schema)
@@ -271,6 +271,8 @@ class TestIrregularlySampledSignalArrayMethods(unittest.TestCase):
description='eggs',
file_origin='testfile.txt',
arg1='test')
+ self.signal1.segment = Segment()
+ self.signal1.channel_index = ChannelIndex([0])
def test__compliant(self):
assert_neo_object_is_compliant(self.signal1)
@@ -345,6 +347,11 @@ class TestIrregularlySampledSignalArrayMethods(unittest.TestCase):
assert_array_equal(result.times, self.time1quant)
assert_same_sub_schema(result, self.signal1)
+ self.assertIsInstance(result.channel_index, ChannelIndex)
+ self.assertIsInstance(result.segment, Segment)
+ self.assertIs(result.channel_index, self.signal1.channel_index)
+ self.assertIs(result.segment, self.signal1.segment)
+
def test__rescale_new(self):
result = self.signal1.copy()
result = result.rescale(pq.uV)
@@ -360,6 +367,11 @@ class TestIrregularlySampledSignalArrayMethods(unittest.TestCase):
assert_arrays_almost_equal(np.array(result), self.data1.reshape(-1, 1)*1000., 1e-10)
assert_array_equal(result.times, self.time1quant)
+ self.assertIsInstance(result.channel_index, ChannelIndex)
+ self.assertIsInstance(result.segment, Segment)
+ self.assertIs(result.channel_index, self.signal1.channel_index)
+ self.assertIs(result.segment, self.signal1.segment)
+
def test__rescale_new_incompatible_ValueError(self):
self.assertRaises(ValueError, self.signal1.rescale, pq.nA)
@@ -550,6 +562,11 @@ class TestIrregularlySampledSignalArrayMethods(unittest.TestCase):
self.assertIsInstance(sig_as_q, pq.Quantity)
assert_array_equal(self.data1, sig_as_q.magnitude.flat)
+ def test__copy_should_preserve_parent_objects(self):
+ result = self.signal1.copy()
+ self.assertIs(result.segment, self.signal1.segment)
+ self.assertIs(result.channel_index, self.signal1.channel_index)
+
class TestIrregularlySampledSignalCombination(unittest.TestCase):
def setUp(self):
diff --git a/neo/test/coretest/test_spiketrain.py b/neo/test/coretest/test_spiketrain.py
index 47c8dd23..4a1bbacd 100644
--- a/neo/test/coretest/test_spiketrain.py
+++ b/neo/test/coretest/test_spiketrain.py
@@ -1394,11 +1394,16 @@ class TestChanging(unittest.TestCase):
def test__rescale(self):
data = [3, 4, 5] * pq.ms
train = SpikeTrain(data, t_start=0.5, t_stop=10.0)
+ train.segment = Segment()
+ train.unit = Unit()
result = train.rescale(pq.s)
assert_neo_object_is_compliant(train)
assert_neo_object_is_compliant(result)
assert_arrays_equal(train, result)
self.assertEqual(result.units, 1 * pq.s)
+ self.assertIs(result.segment, train.segment)
+ self.assertIs(result.unit, train.unit)
+
def test__rescale_same_units(self):
data = [3, 4, 5] * pq.ms
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"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"
],
"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
importlib-metadata==4.8.3
iniconfig==1.1.1
-e git+https://github.com/NeuralEnsemble/python-neo.git@fec5dfca4edd6a2a04cc0b8e274d01009a1c0362#egg=neo
nose==1.3.7
numpy==1.19.5
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyparsing==3.1.4
pytest==7.0.1
quantities==0.13.0
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: python-neo
channels:
- defaults
- https://repo.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
- nose==1.3.7
- numpy==1.19.5
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyparsing==3.1.4
- pytest==7.0.1
- quantities==0.13.0
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/python-neo
| [
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__rescale_new",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__rescale_same",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test__copy_should_preserve_parent_objects",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test__rescale_new",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test__rescale_same",
"neo/test/coretest/test_spiketrain.py::TestChanging::test__rescale"
]
| [
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalCombination::test__add_quantity_should_preserve_data_complement",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalCombination::test__add_two_consistent_signals_should_preserve_data_complement",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalFunctions::test__pickle",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalProperties::test_IrregularlySampledSignal_repr",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_time_slice",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_time_slice_differnt_units",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_time_slice_empty",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_time_slice_none_both",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_time_slice_none_start",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_time_slice_none_stop",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_time_slice_out_of_boundries",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalCombination::test__add_two_consistent_signals_should_preserve_data_complement",
"neo/test/coretest/test_irregularysampledsignal.py::TestAnalogSignalFunctions::test__pickle",
"neo/test/coretest/test_spiketrain.py::TestPropertiesMethods::test__repr"
]
| [
"neo/test/coretest/test_analogsignal.py::Test__generate_datasets::test__fake_neo__cascade",
"neo/test/coretest/test_analogsignal.py::Test__generate_datasets::test__fake_neo__nocascade",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create2D_with_copy_false_should_return_view",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_from_array_no_units_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_from_list",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_from_np_array",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_from_quantities_array",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_from_quantities_array_inconsistent_units_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_inconsistent_sampling_rate_and_period_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_with_None_sampling_rate_should_raise_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_with_None_t_start_should_raise_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_with_additional_argument",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_with_copy_false_should_return_view",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_with_copy_true_should_return_copy",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalConstructor::test__create_without_sampling_rate_or_period_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__compliant",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__duplicate_with_new_array",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__duration_getter",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__repr",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__sampling_period_getter",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__sampling_period_setter",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__sampling_period_setter_None_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__sampling_period_setter_not_quantity_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__sampling_rate_getter",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__sampling_rate_setter",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__sampling_rate_setter_None_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__sampling_rate_setter_not_quantity_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__t_start_setter_None_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__t_stop_getter",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalProperties::test__times_getter",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__comparison_with_inconsistent_units_should_raise_Exception",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__compliant",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__copy_should_let_access_to_parents_objects",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__getitem_out_of_bounds_IndexError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__getitem_should_return_single_quantity",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__rescale_new_incompatible_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__simple_statistics",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__slice_should_change_sampling_period",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__slice_should_let_access_to_parents_objects",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__slice_should_modify_linked_channelindex",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test__slice_should_return_AnalogSignalArray",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test_as_array",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test_as_quantity",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalArrayMethods::test_comparison_operators",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalEquality::test__signals_with_different_data_complement_should_be_not_equal",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalCombination::test__add_const_quantity_should_preserve_data_complement",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalCombination::test__add_signals_with_inconsistent_data_complement_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalCombination::test__compliant",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalCombination::test__divide_by_const_should_preserve_data_complement",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalCombination::test__mult_by_const_float_should_preserve_data_complement",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalCombination::test__subtract_const_should_preserve_data_complement",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalCombination::test__subtract_from_const_should_return_signal",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalSampling::test___get_sampling_rate__period_array_rate_none_TypeError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalSampling::test___get_sampling_rate__period_none_rate_float_TypeError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalSampling::test___get_sampling_rate__period_none_rate_none_ValueError",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalSampling::test___get_sampling_rate__period_none_rate_quant",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalSampling::test___get_sampling_rate__period_quant_rate_none",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalSampling::test___get_sampling_rate__period_rate_equivalent",
"neo/test/coretest/test_analogsignal.py::TestAnalogSignalSampling::test___get_sampling_rate__period_rate_not_equivalent_ValueError",
"neo/test/coretest/test_irregularysampledsignal.py::Test__generate_datasets::test__fake_neo__cascade",
"neo/test/coretest/test_irregularysampledsignal.py::Test__generate_datasets::test__fake_neo__nocascade",
"neo/test/coretest/test_irregularysampledsignal.py::Test__generate_datasets::test__get_fake_values",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalConstruction::test_IrregularlySampledSignal_creation_times_units_signal_units",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalConstruction::test_IrregularlySampledSignal_creation_units_arg",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalConstruction::test_IrregularlySampledSignal_creation_units_rescale",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalConstruction::test_IrregularlySampledSignal_different_lens_ValueError",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalConstruction::test_IrregularlySampledSignal_no_signal_units_ValueError",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalConstruction::test_IrregularlySampledSignal_no_time_units_ValueError",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalProperties::test__compliant",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalProperties::test__duration_getter",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalProperties::test__sampling_intervals_getter",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalProperties::test__t_start_getter",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalProperties::test__t_stop_getter",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test__comparison_with_inconsistent_units_should_raise_Exception",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test__compliant",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test__getitem_out_of_bounds_IndexError",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test__getitem_should_return_single_quantity",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test__rescale_new_incompatible_ValueError",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test__slice_should_return_IrregularlySampledSignal",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_as_array",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_as_quantity",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_comparison_operators",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_mean_interpolation_NotImplementedError",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_resample_NotImplementedError",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalArrayMethods::test_simple_statistics",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalCombination::test__add_const_quantity_should_preserve_data_complement",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalCombination::test__add_signals_with_inconsistent_dimension_ValueError",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalCombination::test__add_signals_with_inconsistent_times_AssertionError",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalCombination::test__compliant",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalCombination::test__divide_signal_by_const_should_preserve_data_complement",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalCombination::test__mult_signal_by_const_array_should_preserve_data_complement",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalCombination::test__mult_signal_by_const_float_should_preserve_data_complement",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalCombination::test__subtract_const_should_preserve_data_complement",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalCombination::test__subtract_from_const_should_return_signal",
"neo/test/coretest/test_irregularysampledsignal.py::TestIrregularlySampledSignalEquality::test__signals_with_different_times_should_be_not_equal",
"neo/test/coretest/test_spiketrain.py::Test__generate_datasets::test__fake_neo__cascade",
"neo/test/coretest/test_spiketrain.py::Test__generate_datasets::test__fake_neo__nocascade",
"neo/test/coretest/test_spiketrain.py::Test__generate_datasets::test__get_fake_values",
"neo/test/coretest/test_spiketrain.py::Testcheck_has_dimensions_time::test__check_has_dimensions_time",
"neo/test/coretest/test_spiketrain.py::Testcheck_time_in_range::test__check_time_in_range_above",
"neo/test/coretest/test_spiketrain.py::Testcheck_time_in_range::test__check_time_in_range_above_below",
"neo/test/coretest/test_spiketrain.py::Testcheck_time_in_range::test__check_time_in_range_above_below_scale",
"neo/test/coretest/test_spiketrain.py::Testcheck_time_in_range::test__check_time_in_range_above_scale",
"neo/test/coretest/test_spiketrain.py::Testcheck_time_in_range::test__check_time_in_range_below",
"neo/test/coretest/test_spiketrain.py::Testcheck_time_in_range::test__check_time_in_range_below_scale",
"neo/test/coretest/test_spiketrain.py::Testcheck_time_in_range::test__check_time_in_range_empty_array",
"neo/test/coretest/test_spiketrain.py::Testcheck_time_in_range::test__check_time_in_range_exact",
"neo/test/coretest/test_spiketrain.py::Testcheck_time_in_range::test__check_time_in_range_inside",
"neo/test/coretest/test_spiketrain.py::Testcheck_time_in_range::test__check_time_in_range_scale",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_empty",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_empty_no_t_start",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_array",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_array_no_start_stop_units",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_array_no_start_stop_units_set_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_array_no_start_stop_units_with_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_array_set_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_array_with_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_array_with_incompatible_units_ValueError",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_array_without_units_should_raise_ValueError",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_list",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_list_no_start_stop_units",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_list_no_start_stop_units_set_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_list_set_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_list_without_units_should_raise_ValueError",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_array",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_array_no_start_stop_units",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_array_no_start_stop_units_set_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_array_no_start_stop_units_with_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_array_set_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_array_units",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_array_units_no_start_stop_units",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_array_units_set_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_array_units_with_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_array_with_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_from_quantity_units_no_start_stop_units_set_dtype",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_minimal",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_with_len_times_different_size_than_waveform_shape1_ValueError",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test__create_with_times_outside_tstart_tstop_ValueError",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test_default_tstart",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test_defaults",
"neo/test/coretest/test_spiketrain.py::TestConstructor::test_tstop_units_conversion",
"neo/test/coretest/test_spiketrain.py::TestSorting::test_sort",
"neo/test/coretest/test_spiketrain.py::TestSlice::test_compliant",
"neo/test/coretest/test_spiketrain.py::TestSlice::test_slice",
"neo/test/coretest/test_spiketrain.py::TestSlice::test_slice_from_beginning",
"neo/test/coretest/test_spiketrain.py::TestSlice::test_slice_negative_idxs",
"neo/test/coretest/test_spiketrain.py::TestSlice::test_slice_to_end",
"neo/test/coretest/test_spiketrain.py::TestTimeSlice::test_compliant",
"neo/test/coretest/test_spiketrain.py::TestTimeSlice::test_time_slice_differnt_units",
"neo/test/coretest/test_spiketrain.py::TestTimeSlice::test_time_slice_empty",
"neo/test/coretest/test_spiketrain.py::TestTimeSlice::test_time_slice_matching_ends",
"neo/test/coretest/test_spiketrain.py::TestTimeSlice::test_time_slice_none_both",
"neo/test/coretest/test_spiketrain.py::TestTimeSlice::test_time_slice_none_start",
"neo/test/coretest/test_spiketrain.py::TestTimeSlice::test_time_slice_none_stop",
"neo/test/coretest/test_spiketrain.py::TestTimeSlice::test_time_slice_out_of_boundries",
"neo/test/coretest/test_spiketrain.py::TestTimeSlice::test_time_slice_typical",
"neo/test/coretest/test_spiketrain.py::TestDuplicateWithNewData::test_deep_copy_attributes",
"neo/test/coretest/test_spiketrain.py::TestDuplicateWithNewData::test_duplicate_with_new_data",
"neo/test/coretest/test_spiketrain.py::TestAttributesAnnotations::test_annotations",
"neo/test/coretest/test_spiketrain.py::TestAttributesAnnotations::test_autoset_universally_recommended_attributes",
"neo/test/coretest/test_spiketrain.py::TestAttributesAnnotations::test_set_universally_recommended_attributes",
"neo/test/coretest/test_spiketrain.py::TestChanging::test__adding_time",
"neo/test/coretest/test_spiketrain.py::TestChanging::test__changing_multiple_spiketimes",
"neo/test/coretest/test_spiketrain.py::TestChanging::test__changing_multiple_spiketimes_should_check_time_in_range",
"neo/test/coretest/test_spiketrain.py::TestChanging::test__changing_spiketime_should_check_time_in_range",
"neo/test/coretest/test_spiketrain.py::TestChanging::test__rescale_incompatible_units_ValueError",
"neo/test/coretest/test_spiketrain.py::TestChanging::test__rescale_same_units",
"neo/test/coretest/test_spiketrain.py::TestChanging::test__subtracting_time",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_change_with_copy_default",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_change_with_copy_default_and_data_not_quantity",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_change_with_copy_false",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_change_with_copy_false_and_data_not_quantity",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_change_with_copy_false_and_dtype_change",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_change_with_copy_false_and_fake_rescale",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_change_with_copy_false_and_rescale_true",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_change_with_copy_true",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_change_with_copy_true_and_data_not_quantity",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_changing_slice_changes_original_spiketrain",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_changing_slice_changes_original_spiketrain_with_copy_false",
"neo/test/coretest/test_spiketrain.py::TestChanging::test_init_with_rescale",
"neo/test/coretest/test_spiketrain.py::TestPropertiesMethods::test__children",
"neo/test/coretest/test_spiketrain.py::TestPropertiesMethods::test__compliant",
"neo/test/coretest/test_spiketrain.py::TestPropertiesMethods::test__duration",
"neo/test/coretest/test_spiketrain.py::TestPropertiesMethods::test__right_sweep",
"neo/test/coretest/test_spiketrain.py::TestPropertiesMethods::test__sampling_period",
"neo/test/coretest/test_spiketrain.py::TestPropertiesMethods::test__spike_duration",
"neo/test/coretest/test_spiketrain.py::TestMiscellaneous::test__different_dtype_for_t_start_and_array",
"neo/test/coretest/test_spiketrain.py::TestMiscellaneous::test_as_array",
"neo/test/coretest/test_spiketrain.py::TestMiscellaneous::test_as_quantity"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,663 | [
"neo/core/irregularlysampledsignal.py",
"neo/core/container.py",
"neo/core/spiketrain.py",
"neo/core/analogsignal.py"
]
| [
"neo/core/irregularlysampledsignal.py",
"neo/core/container.py",
"neo/core/spiketrain.py",
"neo/core/analogsignal.py"
]
|
|
numpy__numpydoc-111 | b215bed82942ed61bc39b18a5b9891e8b43553a2 | 2017-09-10 13:00:26 | 8c1e85c746d1c95b9433b2ae97057b7f447c83d1 | diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py
index 074a7f7..b0ef3d7 100644
--- a/numpydoc/docscrape.py
+++ b/numpydoc/docscrape.py
@@ -213,7 +213,8 @@ class NumpyDocString(collections.Mapping):
return params
- _name_rgx = re.compile(r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|"
+ _name_rgx = re.compile(r"^\s*(:(?P<role>\w+):"
+ r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_.-]+)`|"
r" (?P<name2>[a-zA-Z0-9_.-]+))\s*", re.X)
def _parse_see_also(self, content):
| docscrape doesn't parse :meth:`~matplotlib.axes.Axes.plot` (including '~')
The `docscrape.parse_item_name` method can't parse the above text, because of the tilde. If I manually add a `~` to the regex on line 187 of `docscrape.py` things seem to work just fine. Is this a known issue, or have I done something wrong with my sphinx syntax?
| numpy/numpydoc | diff --git a/numpydoc/tests/test_docscrape.py b/numpydoc/tests/test_docscrape.py
index 2ae51c6..37d4b77 100644
--- a/numpydoc/tests/test_docscrape.py
+++ b/numpydoc/tests/test_docscrape.py
@@ -665,21 +665,23 @@ def test_see_also():
func_f, func_g, :meth:`func_h`, func_j,
func_k
:obj:`baz.obj_q`
+ :obj:`~baz.obj_r`
:class:`class_j`: fubar
foobar
""")
- assert len(doc6['See Also']) == 12
+ assert len(doc6['See Also']) == 13
for func, desc, role in doc6['See Also']:
if func in ('func_a', 'func_b', 'func_c', 'func_f',
- 'func_g', 'func_h', 'func_j', 'func_k', 'baz.obj_q'):
+ 'func_g', 'func_h', 'func_j', 'func_k', 'baz.obj_q',
+ '~baz.obj_r'):
assert(not desc)
else:
assert(desc)
if func == 'func_h':
assert role == 'meth'
- elif func == 'baz.obj_q':
+ elif func == 'baz.obj_q' or func == '~baz.obj_r':
assert role == 'obj'
elif func == 'class_j':
assert role == 'class'
| {
"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": 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": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"pip install --upgrade pip setuptools",
"pip install nose"
],
"python": "3.6",
"reqs_path": [
"requirements/base.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
docutils==0.18.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
nose==1.3.7
-e git+https://github.com/numpy/numpydoc.git@b215bed82942ed61bc39b18a5b9891e8b43553a2#egg=numpydoc
packaging==21.3
pluggy==1.0.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
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==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: numpydoc
channels:
- defaults
- https://repo.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
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_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
- docutils==0.18.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- nose==1.3.7
- packaging==21.3
- pip==21.3.1
- pluggy==1.0.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- setuptools==59.6.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==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/numpydoc
| [
"numpydoc/tests/test_docscrape.py::test_see_also"
]
| []
| [
"numpydoc/tests/test_docscrape.py::test_signature",
"numpydoc/tests/test_docscrape.py::test_summary",
"numpydoc/tests/test_docscrape.py::test_extended_summary",
"numpydoc/tests/test_docscrape.py::test_parameters",
"numpydoc/tests/test_docscrape.py::test_other_parameters",
"numpydoc/tests/test_docscrape.py::test_returns",
"numpydoc/tests/test_docscrape.py::test_yields",
"numpydoc/tests/test_docscrape.py::test_returnyield",
"numpydoc/tests/test_docscrape.py::test_section_twice",
"numpydoc/tests/test_docscrape.py::test_notes",
"numpydoc/tests/test_docscrape.py::test_references",
"numpydoc/tests/test_docscrape.py::test_examples",
"numpydoc/tests/test_docscrape.py::test_index",
"numpydoc/tests/test_docscrape.py::test_str",
"numpydoc/tests/test_docscrape.py::test_yield_str",
"numpydoc/tests/test_docscrape.py::test_sphinx_str",
"numpydoc/tests/test_docscrape.py::test_sphinx_yields_str",
"numpydoc/tests/test_docscrape.py::test_parameters_without_extended_description",
"numpydoc/tests/test_docscrape.py::test_escape_stars",
"numpydoc/tests/test_docscrape.py::test_empty_extended_summary",
"numpydoc/tests/test_docscrape.py::test_raises",
"numpydoc/tests/test_docscrape.py::test_warns",
"numpydoc/tests/test_docscrape.py::test_see_also_parse_error",
"numpydoc/tests/test_docscrape.py::test_see_also_print",
"numpydoc/tests/test_docscrape.py::test_empty_first_line",
"numpydoc/tests/test_docscrape.py::test_no_summary",
"numpydoc/tests/test_docscrape.py::test_unicode",
"numpydoc/tests/test_docscrape.py::test_plot_examples",
"numpydoc/tests/test_docscrape.py::test_class_members",
"numpydoc/tests/test_docscrape.py::test_duplicate_signature",
"numpydoc/tests/test_docscrape.py::test_class_members_doc",
"numpydoc/tests/test_docscrape.py::test_class_members_doc_sphinx",
"numpydoc/tests/test_docscrape.py::test_templated_sections"
]
| []
| BSD License | 1,664 | [
"numpydoc/docscrape.py"
]
| [
"numpydoc/docscrape.py"
]
|
|
nipy__nipype-2179 | 7ead69d1aeb24f0d0884efe03075ef7de1759e1c | 2017-09-10 18:53:22 | 14161a590a3166b5a9c0f4afd42ff1acf843a960 | diff --git a/nipype/interfaces/afni/utils.py b/nipype/interfaces/afni/utils.py
index e20fe1d5f..88a317b8c 100644
--- a/nipype/interfaces/afni/utils.py
+++ b/nipype/interfaces/afni/utils.py
@@ -602,12 +602,12 @@ class CatMatvecInputSpec(AFNICommandInputSpec):
"This feature could be used, with clever scripting, to input"
"a matrix directly on the command line to program 3dWarp.",
argstr="-MATRIX",
- xor=['oneline','fourXfour'])
+ xor=['oneline', 'fourxfour'])
oneline = traits.Bool(
descr="indicates that the resulting matrix"
"will simply be written as 12 numbers on one line.",
argstr="-ONELINE",
- xor=['matrix','fourXfour'])
+ xor=['matrix', 'fourxfour'])
fourxfour = traits.Bool(
descr="Output matrix in augmented form (last row is 0 0 0 1)"
"This option does not work with -MATRIX or -ONELINE",
| typo in trait name of AFNI CatMatvec interface
### Summary
typo in `afni.Catmatvec`: trait name is `fourxfour` not `fourXfour`
https://github.com/nipy/nipype/blob/master/nipype/interfaces/afni/utils.py#L610
### Actual behavior
```Python
from nipype.interfaces import afni
cat_matvec = afni.CatMatvec()
cat_matvec.inputs.oneline = True
```
throws
```Python
AttributeError: 'CatMatvecInputSpec' object has no attribute 'fourXfour'
```
### Platform details:
Please paste the output of: `python -c "import nipype; print(nipype.get_info()); print(nipype.__version__)"`
{'nibabel_version': '2.1.0', 'sys_executable': '/home/salma/anaconda2/bin/python', 'networkx_version': '1.11', 'numpy_version': '1.13.1', 'sys_platform': 'linux2', 'sys_version': '2.7.13 |Anaconda custom (64-bit)| (default, Dec 20 2016, 23:09:15) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]', 'commit_source': u'repository', 'commit_hash': '7ead69d', 'pkg_path': 'nipype', 'nipype_version': u'1.0.0-dev+g7ead69d', 'traits_version': '4.6.0', 'scipy_version': '0.19.1'}
1.0.0-dev+g7ead69d
| nipy/nipype | diff --git a/nipype/interfaces/afni/tests/test_auto_CatMatvec.py b/nipype/interfaces/afni/tests/test_auto_CatMatvec.py
index 4b79cd91d..d3d94569b 100644
--- a/nipype/interfaces/afni/tests/test_auto_CatMatvec.py
+++ b/nipype/interfaces/afni/tests/test_auto_CatMatvec.py
@@ -23,11 +23,11 @@ def test_CatMatvec_inputs():
),
matrix=dict(argstr='-MATRIX',
descr="indicates that the resulting matrix willbe written to outfile in the 'MATRIX(...)' format (FORM 3).This feature could be used, with clever scripting, to inputa matrix directly on the command line to program 3dWarp.",
- xor=['oneline', 'fourXfour'],
+ xor=['oneline', 'fourxfour'],
),
oneline=dict(argstr='-ONELINE',
descr='indicates that the resulting matrixwill simply be written as 12 numbers on one line.',
- xor=['matrix', 'fourXfour'],
+ xor=['matrix', 'fourxfour'],
),
out_file=dict(argstr=' > %s',
descr='File to write concattenated matvecs to',
| {
"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.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"
],
"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
click==8.0.4
configparser==5.2.0
decorator==4.4.2
funcsigs==1.0.2
future==1.0.0
importlib-metadata==4.8.3
iniconfig==1.1.1
isodate==0.6.1
lxml==5.3.1
mock==5.2.0
networkx==2.5.1
nibabel==3.2.2
-e git+https://github.com/nipy/nipype.git@7ead69d1aeb24f0d0884efe03075ef7de1759e1c#egg=nipype
numpy==1.19.5
packaging==21.3
pluggy==1.0.0
prov==1.5.0
py==1.11.0
pydotplus==2.0.2
pyparsing==3.1.4
pytest==7.0.1
python-dateutil==2.9.0.post0
rdflib==5.0.0
scipy==1.5.4
simplejson==3.20.1
six==1.17.0
tomli==1.2.3
traits==6.4.1
typing_extensions==4.1.1
zipp==3.6.0
| name: nipype
channels:
- defaults
- https://repo.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
- click==8.0.4
- configparser==5.2.0
- decorator==4.4.2
- funcsigs==1.0.2
- future==1.0.0
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- isodate==0.6.1
- lxml==5.3.1
- mock==5.2.0
- networkx==2.5.1
- nibabel==3.2.2
- numpy==1.19.5
- packaging==21.3
- pluggy==1.0.0
- prov==1.5.0
- py==1.11.0
- pydotplus==2.0.2
- pyparsing==3.1.4
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- rdflib==5.0.0
- scipy==1.5.4
- simplejson==3.20.1
- six==1.17.0
- tomli==1.2.3
- traits==6.4.1
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/nipype
| [
"nipype/interfaces/afni/tests/test_auto_CatMatvec.py::test_CatMatvec_inputs"
]
| []
| [
"nipype/interfaces/afni/tests/test_auto_CatMatvec.py::test_CatMatvec_outputs"
]
| []
| Apache License 2.0 | 1,666 | [
"nipype/interfaces/afni/utils.py"
]
| [
"nipype/interfaces/afni/utils.py"
]
|
|
borgbackup__borg-3024 | dcf5e77253d35ca625d53f356cd2b969f4f4c6fd | 2017-09-11 00:58:21 | a439fa3e720c8bb2a82496768ffcce282fb7f7b7 | codecov-io: # [Codecov](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=h1) Report
> Merging [#3024](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=desc) into [master](https://codecov.io/gh/borgbackup/borg/commit/7c5a9d89b2a8deac84a641bb4ccad00a575a2765?src=pr&el=desc) will **decrease** coverage by `0.83%`.
> The diff coverage is `100%`.
[](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree)
```diff
@@ Coverage Diff @@
## master #3024 +/- ##
==========================================
- Coverage 86% 85.16% -0.84%
==========================================
Files 36 36
Lines 8891 8894 +3
Branches 1468 1468
==========================================
- Hits 7647 7575 -72
- Misses 844 914 +70
- Partials 400 405 +5
```
| [Impacted Files](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/borg/archive.py](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree#diff-c3JjL2JvcmcvYXJjaGl2ZS5weQ==) | `83.1% <100%> (-0.83%)` | :arrow_down: |
| [src/borg/cache.py](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree#diff-c3JjL2JvcmcvY2FjaGUucHk=) | `86.53% <100%> (+0.01%)` | :arrow_up: |
| [src/borg/archiver.py](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree#diff-c3JjL2JvcmcvYXJjaGl2ZXIucHk=) | `86.64% <100%> (+0.01%)` | :arrow_up: |
| [src/borg/xattr.py](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree#diff-c3JjL2JvcmcveGF0dHIucHk=) | `59.5% <0%> (-23.5%)` | :arrow_down: |
| [src/borg/platform/\_\_init\_\_.py](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree#diff-c3JjL2JvcmcvcGxhdGZvcm0vX19pbml0X18ucHk=) | `73.68% <0%> (-15.79%)` | :arrow_down: |
| [src/borg/platform/base.py](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree#diff-c3JjL2JvcmcvcGxhdGZvcm0vYmFzZS5weQ==) | `75.9% <0%> (-10.85%)` | :arrow_down: |
| [src/borg/helpers/usergroup.py](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree#diff-c3JjL2JvcmcvaGVscGVycy91c2VyZ3JvdXAucHk=) | `59.45% <0%> (-5.41%)` | :arrow_down: |
| [src/borg/helpers/fs.py](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree#diff-c3JjL2JvcmcvaGVscGVycy9mcy5weQ==) | `93.18% <0%> (-2.28%)` | :arrow_down: |
| [src/borg/helpers/misc.py](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=tree#diff-c3JjL2JvcmcvaGVscGVycy9taXNjLnB5) | `80.86% <0%> (-0.87%)` | :arrow_down: |
------
[Continue to review full report at Codecov](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=footer). Last update [7c5a9d8...f104f47](https://codecov.io/gh/borgbackup/borg/pull/3024?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).
ThomasWaldmann: any feedback?
enkore: I don't like extra options for such obscure details. I think it would be better to conclude either possibility and have no new option.
ThomasWaldmann: I don't like them either, but there is no clear choice here.
A lot of tools just use mtime and mtime is faster.
ctime is safer because userspace software can't do weird stuff with it, but slower if someone does a chmod/chown/ln over bigger amounts of data.
So the rationale of this PR is "do it safe by default, leave option to do it quick (if admin can assert no strange stuff is going on with mtime)".
ThomasWaldmann: about using `max(mtime, ctime)` instead of just `ctime`:
good:
- if a fs would return a completely broken ctime (like always 0), our cache would use mtime and still work
bad:
- more complex behaviour
ThomasWaldmann: I'm going to merge this soon as I don't see any better alternative.
Whether using max(mtime, ctime) is any good / is really needed is still an open question.
Guess if we supported native windows, using max() would be good as there ctime is creation time (not change time), thus not helpful for what we need.
enkore: I think max(mtime, ctime) is kinda like the worst combination of both. It still re-chunks on metadata-only changes, but doesn't have the idiot-safety of ctime.
ThomasWaldmann: Hm? It would keep the safety of ctime IF ctime is supported by the OS / fs in a UNIX-like way.
The problem with mtime is that it can be faked to stay same, even though the file was changed.
ctime would change to a bigger numerical value and can't be faked, so max(ctime, mtime) would result in the ctime for such a case.
The only cases when max(ctime, mtime) result in mtime is when ctime does not work at all (like always 0, not sure if that can be seen out there) or when ctime means creation time and thus is always smaller than mtime.
enkore: Ah right.
enkore: Right, but I could e.g. change the mtime to some very large value (mtime > ctime), modify the file, re-set mtime to the large value etc.
ThomasWaldmann: Yup, that would escape the change detection if there was a backup after the first far-future mtime change, but before the file modification. Crap.
ThomasWaldmann: ctime << 64 + mtime?
ThomasWaldmann: Note: i kept it as a cmdline option rather than env var.
We have --ignore-inode and --no-files-cache now, but they can be superceded by just using the respective --cache-mode options. So, 1 option less long term than before this changeset.
For local UNIX file systems and when valuing safety over speed, no option must be used.
If ctime or inode numbers are not working as expected, options can be used to work around that.
Using env vars for this feels somehow more clunky, esp. when the source filesystems need different cache mode values.
ThomasWaldmann: src/borg/archiver.py:2614:1: W293 blank line contains whitespace
https://travis-ci.org/borgbackup/borg/jobs/280267622
There is no whitespace.
enkore: Ok. I think it would be better to use less cryptic option names, consider `--cache-mode=ignore-inode,mtime`.
ThomasWaldmann: @enkore can you do a final review before I merge this? | diff --git a/docs/internals/data-structures.rst b/docs/internals/data-structures.rst
index 045b476b..7c6d46b6 100644
--- a/docs/internals/data-structures.rst
+++ b/docs/internals/data-structures.rst
@@ -738,7 +738,7 @@ b) with ``create --chunker-params 19,23,21,4095`` (default):
mem_usage = 0.31GiB
-.. note:: There is also the ``--no-files-cache`` option to switch off the files cache.
+.. note:: There is also the ``--files-cache=disabled`` option to disable the files cache.
You'll save some memory, but it will need to read / chunk all the files as
it can not skip unmodified files then.
diff --git a/src/borg/archive.py b/src/borg/archive.py
index 3cb0b7cf..9bb2b8b1 100644
--- a/src/borg/archive.py
+++ b/src/borg/archive.py
@@ -1087,13 +1087,13 @@ def process_stdin(self, path, cache):
self.add_item(item)
return 'i' # stdin
- def process_file(self, path, st, cache, ignore_inode=False):
+ def process_file(self, path, st, cache, ignore_inode=False, files_cache_mode=DEFAULT_FILES_CACHE_MODE):
with self.create_helper(path, st, None) as (item, status, hardlinked, hardlink_master): # no status yet
is_special_file = is_special(st.st_mode)
if not hardlinked or hardlink_master:
if not is_special_file:
path_hash = self.key.id_hash(safe_encode(os.path.join(self.cwd, path)))
- ids = cache.file_known_and_unchanged(path_hash, st, ignore_inode)
+ ids = cache.file_known_and_unchanged(path_hash, st, ignore_inode, files_cache_mode)
else:
# in --read-special mode, we may be called for special files.
# there should be no information in the cache about special files processed in
@@ -1126,7 +1126,7 @@ def process_file(self, path, st, cache, ignore_inode=False):
if not is_special_file:
# we must not memorize special files, because the contents of e.g. a
# block or char device will change without its mtime/size/inode changing.
- cache.memorize_file(path_hash, st, [c.id for c in item.chunks])
+ cache.memorize_file(path_hash, st, [c.id for c in item.chunks], files_cache_mode)
status = status or 'M' # regular file, modified (if not 'A' already)
self.stats.nfiles += 1
item.update(self.metadata_collector.stat_attrs(st, path))
diff --git a/src/borg/archiver.py b/src/borg/archiver.py
index 394d802b..039587dd 100644
--- a/src/borg/archiver.py
+++ b/src/borg/archiver.py
@@ -45,7 +45,7 @@
from .helpers import EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR
from .helpers import Error, NoManifestError, set_ec
from .helpers import positive_int_validator, location_validator, archivename_validator, ChunkerParams
-from .helpers import PrefixSpec, SortBySpec
+from .helpers import PrefixSpec, SortBySpec, FilesCacheMode
from .helpers import BaseFormatter, ItemFormatter, ArchiveFormatter
from .helpers import format_timedelta, format_file_size, parse_file_size, format_archive
from .helpers import safe_encode, remove_surrogates, bin_to_hex, prepare_dump_dict
@@ -346,7 +346,7 @@ def measurement_run(repo, path):
compression = '--compression=none'
# measure create perf (without files cache to always have it chunking)
t_start = time.monotonic()
- rc = self.do_create(self.parse_args(['create', compression, '--no-files-cache', archive + '1', path]))
+ rc = self.do_create(self.parse_args(['create', compression, '--files-cache=disabled', archive + '1', path]))
t_end = time.monotonic()
dt_create = t_end - t_start
assert rc == 0
@@ -485,6 +485,7 @@ def create_inner(archive, cache, fso):
self.output_filter = args.output_filter
self.output_list = args.output_list
self.ignore_inode = args.ignore_inode
+ self.files_cache_mode = args.files_cache_mode
dry_run = args.dry_run
t0 = datetime.utcnow()
t0_monotonic = time.monotonic()
@@ -548,7 +549,7 @@ def _process(self, fso, cache, matcher, exclude_caches, exclude_if_present,
return
if stat.S_ISREG(st.st_mode):
if not dry_run:
- status = fso.process_file(path, st, cache, self.ignore_inode)
+ status = fso.process_file(path, st, cache, self.ignore_inode, self.files_cache_mode)
elif stat.S_ISDIR(st.st_mode):
if recurse:
tag_paths = dir_is_tagged(path, exclude_caches, exclude_if_present)
@@ -1960,14 +1961,17 @@ def do_subcommand_help(self, parser, args):
def preprocess_args(self, args):
deprecations = [
- # ('--old', '--new', 'Warning: "--old" has been deprecated. Use "--new" instead.'),
+ # ('--old', '--new' or None, 'Warning: "--old" has been deprecated. Use "--new" instead.'),
('--list-format', '--format', 'Warning: "--list-format" has been deprecated. Use "--format" instead.'),
('--keep-tag-files', '--keep-exclude-tags', 'Warning: "--keep-tag-files" has been deprecated. Use "--keep-exclude-tags" instead.'),
+ ('--ignore-inode', None, 'Warning: "--ignore-inode" has been deprecated. Use "--files-cache=ctime,size" or "...=mtime,size" instead.'),
+ ('--no-files-cache', None, 'Warning: "--no-files-cache" has been deprecated. Use "--files-cache=disabled" instead.'),
]
for i, arg in enumerate(args[:]):
for old_name, new_name, warning in deprecations:
if arg.startswith(old_name):
- args[i] = arg.replace(old_name, new_name)
+ if new_name is not None:
+ args[i] = arg.replace(old_name, new_name)
print(warning, file=sys.stderr)
return args
@@ -2595,13 +2599,39 @@ def define_archive_filters_group(subparser, *, sort_by=True, first_last=True):
{now}, {utcnow}, {fqdn}, {hostname}, {user} and some others.
Backup speed is increased by not reprocessing files that are already part of
- existing archives and weren't modified. Normally, detecting file modifications
- will take inode information into consideration. This is problematic for files
- located on sshfs and similar network file systems which do not provide stable
- inode numbers, such files will always be considered modified. The
- ``--ignore-inode`` flag can be used to prevent this and improve performance.
- This flag will reduce reliability of change detection however, with files
- considered unmodified as long as their size and modification time are unchanged.
+ existing archives and weren't modified. The detection of unmodified files is
+ done by comparing multiple file metadata values with previous values kept in
+ the files cache.
+
+ This comparison can operate in different modes as given by ``--files-cache``:
+
+ - ctime,size,inode (default)
+ - mtime,size,inode (default behaviour of borg versions older than 1.1.0rc4)
+ - ctime,size (ignore the inode number)
+ - mtime,size (ignore the inode number)
+ - rechunk,ctime (all files are considered modified - rechunk, cache ctime)
+ - rechunk,mtime (all files are considered modified - rechunk, cache mtime)
+ - disabled (disable the files cache, all files considered modified - rechunk)
+
+ inode number: better safety, but often unstable on network filesystems
+
+ Normally, detecting file modifications will take inode information into
+ consideration to improve the reliability of file change detection.
+ This is problematic for files located on sshfs and similar network file
+ systems which do not provide stable inode numbers, such files will always
+ be considered modified. You can use modes without `inode` in this case to
+ improve performance, but reliability of change detection might be reduced.
+
+ ctime vs. mtime: safety vs. speed
+
+ - ctime is a rather safe way to detect changes to a file (metadata and contents)
+ as it can not be set from userspace. But, a metadata-only change will already
+ update the ctime, so there might be some unnecessary chunking/hashing even
+ without content changes. Some filesystems do not support ctime (change time).
+ - mtime usually works and only updates if file contents were changed. But mtime
+ can be arbitrarily set from userspace, e.g. to set mtime back to the same value
+ it had before a content change happened. This can be used maliciously as well as
+ well-meant, but in both cases mtime based cache modes can be problematic.
The mount points of filesystems or filesystem snapshots should be the same for every
creation of a new archive to ensure fast operation. This is because the file cache that
@@ -2692,7 +2722,7 @@ def define_archive_filters_group(subparser, *, sort_by=True, first_last=True):
subparser.add_argument('--json', action='store_true',
help='output stats as JSON. Implies ``--stats``.')
subparser.add_argument('--no-cache-sync', dest='no_cache_sync', action='store_true',
- help='experimental: do not synchronize the cache. Implies ``--no-files-cache``.')
+ help='experimental: do not synchronize the cache. Implies not using the files cache.')
define_exclusion_group(subparser, tag_files=True)
@@ -2707,6 +2737,9 @@ def define_archive_filters_group(subparser, *, sort_by=True, first_last=True):
help='do not store ctime into archive')
fs_group.add_argument('--ignore-inode', dest='ignore_inode', action='store_true',
help='ignore inode data in the file metadata cache used to detect unchanged files.')
+ fs_group.add_argument('--files-cache', metavar='MODE', dest='files_cache_mode',
+ type=FilesCacheMode, default=DEFAULT_FILES_CACHE_MODE_UI,
+ help='operate files cache in MODE. default: %s' % DEFAULT_FILES_CACHE_MODE_UI)
fs_group.add_argument('--read-special', dest='read_special', action='store_true',
help='open and read block and char device files as well as FIFOs as if they were '
'regular files. Also follows symlinks pointing to these kinds of files.')
diff --git a/src/borg/cache.py b/src/borg/cache.py
index a9e7be27..227858bc 100644
--- a/src/borg/cache.py
+++ b/src/borg/cache.py
@@ -12,7 +12,7 @@
logger = create_logger()
-from .constants import CACHE_README
+from .constants import CACHE_README, DEFAULT_FILES_CACHE_MODE
from .hashindex import ChunkIndex, ChunkIndexEntry, CacheSynchronizer
from .helpers import Location
from .helpers import Error
@@ -34,7 +34,8 @@
from .remote import cache_if_remote
from .repository import LIST_SCAN_LIMIT
-FileCacheEntry = namedtuple('FileCacheEntry', 'age inode size mtime chunk_ids')
+# note: cmtime might me either a ctime or a mtime timestamp
+FileCacheEntry = namedtuple('FileCacheEntry', 'age inode size cmtime chunk_ids')
class SecurityManager:
@@ -492,7 +493,7 @@ def close(self):
def _read_files(self):
self.files = {}
- self._newest_mtime = None
+ self._newest_cmtime = None
logger.debug('Reading files cache ...')
with IntegrityCheckedFile(path=os.path.join(self.path, 'files'), write=False,
@@ -538,18 +539,18 @@ def commit(self):
self.security_manager.save(self.manifest, self.key)
pi = ProgressIndicatorMessage(msgid='cache.commit')
if self.files is not None:
- if self._newest_mtime is None:
+ if self._newest_cmtime is None:
# was never set because no files were modified/added
- self._newest_mtime = 2 ** 63 - 1 # nanoseconds, good until y2262
+ self._newest_cmtime = 2 ** 63 - 1 # nanoseconds, good until y2262
ttl = int(os.environ.get('BORG_FILES_CACHE_TTL', 20))
pi.output('Saving files cache')
with IntegrityCheckedFile(path=os.path.join(self.path, 'files'), write=True) as fd:
for path_hash, item in self.files.items():
- # Only keep files seen in this backup that are older than newest mtime seen in this backup -
- # this is to avoid issues with filesystem snapshots and mtime granularity.
+ # Only keep files seen in this backup that are older than newest cmtime seen in this backup -
+ # this is to avoid issues with filesystem snapshots and cmtime granularity.
# Also keep files from older backups that have not reached BORG_FILES_CACHE_TTL yet.
entry = FileCacheEntry(*msgpack.unpackb(item))
- if entry.age == 0 and bigint_to_int(entry.mtime) < self._newest_mtime or \
+ if entry.age == 0 and bigint_to_int(entry.cmtime) < self._newest_cmtime or \
entry.age > 0 and entry.age < ttl:
msgpack.pack((path_hash, entry), fd)
self.cache_config.integrity['files'] = fd.integrity_data
@@ -902,37 +903,47 @@ def chunk_decref(self, id, stats, wait=True):
else:
stats.update(-size, -csize, False)
- def file_known_and_unchanged(self, path_hash, st, ignore_inode=False):
- if not (self.do_files and stat.S_ISREG(st.st_mode)):
+ def file_known_and_unchanged(self, path_hash, st, ignore_inode=False, cache_mode=DEFAULT_FILES_CACHE_MODE):
+ if 'd' in cache_mode or not self.do_files or not stat.S_ISREG(st.st_mode): # d(isabled)
return None
if self.files is None:
self._read_files()
+ if 'r' in cache_mode: # r(echunk)
+ return None
entry = self.files.get(path_hash)
if not entry:
return None
entry = FileCacheEntry(*msgpack.unpackb(entry))
- if (entry.size == st.st_size and bigint_to_int(entry.mtime) == st.st_mtime_ns and
- (ignore_inode or entry.inode == st.st_ino)):
- # we ignored the inode number in the comparison above or it is still same.
- # if it is still the same, replacing it in the tuple doesn't change it.
- # if we ignored it, a reason for doing that is that files were moved to a new
- # disk / new fs (so a one-time change of inode number is expected) and we wanted
- # to avoid everything getting chunked again. to be able to re-enable the inode
- # number comparison in a future backup run (and avoid chunking everything
- # again at that time), we need to update the inode number in the cache with what
- # we see in the filesystem.
- self.files[path_hash] = msgpack.packb(entry._replace(inode=st.st_ino, age=0))
- return entry.chunk_ids
- else:
+ if 's' in cache_mode and entry.size != st.st_size:
return None
-
- def memorize_file(self, path_hash, st, ids):
- if not (self.do_files and stat.S_ISREG(st.st_mode)):
+ if 'i' in cache_mode and not ignore_inode and entry.inode != st.st_ino:
+ return None
+ if 'c' in cache_mode and bigint_to_int(entry.cmtime) != st.st_ctime_ns:
+ return None
+ elif 'm' in cache_mode and bigint_to_int(entry.cmtime) != st.st_mtime_ns:
+ return None
+ # we ignored the inode number in the comparison above or it is still same.
+ # if it is still the same, replacing it in the tuple doesn't change it.
+ # if we ignored it, a reason for doing that is that files were moved to a new
+ # disk / new fs (so a one-time change of inode number is expected) and we wanted
+ # to avoid everything getting chunked again. to be able to re-enable the inode
+ # number comparison in a future backup run (and avoid chunking everything
+ # again at that time), we need to update the inode number in the cache with what
+ # we see in the filesystem.
+ self.files[path_hash] = msgpack.packb(entry._replace(inode=st.st_ino, age=0))
+ return entry.chunk_ids
+
+ def memorize_file(self, path_hash, st, ids, cache_mode=DEFAULT_FILES_CACHE_MODE):
+ # note: r(echunk) modes will update the files cache, d(isabled) mode won't
+ if 'd' in cache_mode or not self.do_files or not stat.S_ISREG(st.st_mode):
return
- mtime_ns = safe_ns(st.st_mtime_ns)
- entry = FileCacheEntry(age=0, inode=st.st_ino, size=st.st_size, mtime=int_to_bigint(mtime_ns), chunk_ids=ids)
+ if 'c' in cache_mode:
+ cmtime_ns = safe_ns(st.st_ctime_ns)
+ elif 'm' in cache_mode:
+ cmtime_ns = safe_ns(st.st_mtime_ns)
+ entry = FileCacheEntry(age=0, inode=st.st_ino, size=st.st_size, cmtime=int_to_bigint(cmtime_ns), chunk_ids=ids)
self.files[path_hash] = msgpack.packb(entry)
- self._newest_mtime = max(self._newest_mtime or 0, mtime_ns)
+ self._newest_cmtime = max(self._newest_cmtime or 0, cmtime_ns)
class AdHocCache(CacheStatsMixin):
@@ -973,10 +984,10 @@ def __exit__(self, exc_type, exc_val, exc_tb):
files = None
do_files = False
- def file_known_and_unchanged(self, path_hash, st, ignore_inode=False):
+ def file_known_and_unchanged(self, path_hash, st, ignore_inode=False, cache_mode=DEFAULT_FILES_CACHE_MODE):
return None
- def memorize_file(self, path_hash, st, ids):
+ def memorize_file(self, path_hash, st, ids, cache_mode=DEFAULT_FILES_CACHE_MODE):
pass
def add_chunk(self, id, chunk, stats, overwrite=False, wait=True):
diff --git a/src/borg/constants.py b/src/borg/constants.py
index 36d6ee45..4f2a430d 100644
--- a/src/borg/constants.py
+++ b/src/borg/constants.py
@@ -60,6 +60,10 @@
# chunker params for the items metadata stream, finer granularity
ITEMS_CHUNKER_PARAMS = (15, 19, 17, HASH_WINDOW_SIZE)
+# operating mode of the files cache (for fast skipping of unchanged files)
+DEFAULT_FILES_CACHE_MODE_UI = 'ctime,size,inode'
+DEFAULT_FILES_CACHE_MODE = 'cis' # == CacheMode(DEFAULT_FILES_CACHE_MODE_UI)
+
# return codes returned by borg command
# when borg is killed by signal N, rc = 128 + N
EXIT_SUCCESS = 0 # everything done, no problems
diff --git a/src/borg/helpers/parseformat.py b/src/borg/helpers/parseformat.py
index f926bbe9..0889eea9 100644
--- a/src/borg/helpers/parseformat.py
+++ b/src/borg/helpers/parseformat.py
@@ -117,6 +117,22 @@ def ChunkerParams(s):
return int(chunk_min), int(chunk_max), int(chunk_mask), int(window_size)
+def FilesCacheMode(s):
+ ENTRIES_MAP = dict(ctime='c', mtime='m', size='s', inode='i', rechunk='r', disabled='d')
+ VALID_MODES = ('cis', 'ims', 'cs', 'ms', 'cr', 'mr', 'd') # letters in alpha order
+ entries = set(s.strip().split(','))
+ if not entries <= set(ENTRIES_MAP):
+ raise ValueError('cache mode must be a comma-separated list of: %s' % ','.join(sorted(ENTRIES_MAP)))
+ short_entries = {ENTRIES_MAP[entry] for entry in entries}
+ mode = ''.join(sorted(short_entries))
+ if mode not in VALID_MODES:
+ raise ValueError('cache mode short must be one of: %s' % ','.join(VALID_MODES))
+ return mode
+
+
+assert FilesCacheMode(DEFAULT_FILES_CACHE_MODE_UI) == DEFAULT_FILES_CACHE_MODE # keep these 2 values in sync!
+
+
def partial_format(format, mapping):
"""
Apply format.format_map(mapping) while preserving unknown keys
| Files cache: use ctime instead of mtime
ctime can't be set via userspace, while mtime is easily manipulated.
For most files (e.g. not extracted from tarballs, or installed by a package manager) these two are the same, which limits the impact of the change on existing file caches.
- Works with sshfs? -> (YES) (see below)
@verygreen noted that in the Windows world ctime usually means "creation" not "change" time
- Works with windows+cygwin? -> YES
- Works with native windows? -> NO
| borgbackup/borg | diff --git a/src/borg/testsuite/archiver.py b/src/borg/testsuite/archiver.py
index c9ba6605..11579377 100644
--- a/src/borg/testsuite/archiver.py
+++ b/src/borg/testsuite/archiver.py
@@ -318,8 +318,6 @@ def create_test_files(self):
"""Create a minimal test case including all supported file types
"""
# File
- self.create_regular_file('empty', size=0)
- os.utime('input/empty', (MAX_S, MAX_S))
self.create_regular_file('file1', size=1024 * 80)
self.create_regular_file('flagfile', size=1024)
# Directory
@@ -370,6 +368,8 @@ def create_test_files(self):
if e.errno not in (errno.EINVAL, errno.ENOSYS):
raise
have_root = False
+ time.sleep(1) # "empty" must have newer timestamp than other files
+ self.create_regular_file('empty', size=0)
return have_root
@@ -1591,9 +1591,8 @@ def test_file_status(self):
"""test that various file status show expected results
clearly incomplete: only tests for the weird "unchanged" status for now"""
- now = time.time()
self.create_regular_file('file1', size=1024 * 80)
- os.utime('input/file1', (now - 5, now - 5)) # 5 seconds ago
+ time.sleep(1) # file2 must have newer timestamps than file1
self.create_regular_file('file2', size=1024 * 80)
self.cmd('init', '--encryption=repokey', self.repository_location)
output = self.cmd('create', '--list', self.repository_location + '::test', 'input')
@@ -1606,12 +1605,51 @@ def test_file_status(self):
# https://borgbackup.readthedocs.org/en/latest/faq.html#i-am-seeing-a-added-status-for-a-unchanged-file
self.assert_in("A input/file2", output)
+ def test_file_status_cs_cache_mode(self):
+ """test that a changed file with faked "previous" mtime still gets backed up in ctime,size cache_mode"""
+ self.create_regular_file('file1', contents=b'123')
+ time.sleep(1) # file2 must have newer timestamps than file1
+ self.create_regular_file('file2', size=10)
+ self.cmd('init', '--encryption=repokey', self.repository_location)
+ output = self.cmd('create', '--list', '--files-cache=ctime,size', self.repository_location + '::test1', 'input')
+ # modify file1, but cheat with the mtime (and atime) and also keep same size:
+ st = os.stat('input/file1')
+ self.create_regular_file('file1', contents=b'321')
+ os.utime('input/file1', ns=(st.st_atime_ns, st.st_mtime_ns))
+ # this mode uses ctime for change detection, so it should find file1 as modified
+ output = self.cmd('create', '--list', '--files-cache=ctime,size', self.repository_location + '::test2', 'input')
+ self.assert_in("A input/file1", output)
+
+ def test_file_status_ms_cache_mode(self):
+ """test that a chmod'ed file with no content changes does not get chunked again in mtime,size cache_mode"""
+ self.create_regular_file('file1', size=10)
+ time.sleep(1) # file2 must have newer timestamps than file1
+ self.create_regular_file('file2', size=10)
+ self.cmd('init', '--encryption=repokey', self.repository_location)
+ output = self.cmd('create', '--list', '--files-cache=mtime,size', self.repository_location + '::test1', 'input')
+ # change mode of file1, no content change:
+ st = os.stat('input/file1')
+ os.chmod('input/file1', st.st_mode ^ stat.S_IRWXO) # this triggers a ctime change, but mtime is unchanged
+ # this mode uses mtime for change detection, so it should find file1 as unmodified
+ output = self.cmd('create', '--list', '--files-cache=mtime,size', self.repository_location + '::test2', 'input')
+ self.assert_in("U input/file1", output)
+
+ def test_file_status_rc_cache_mode(self):
+ """test that files get rechunked unconditionally in rechunk,ctime cache mode"""
+ self.create_regular_file('file1', size=10)
+ time.sleep(1) # file2 must have newer timestamps than file1
+ self.create_regular_file('file2', size=10)
+ self.cmd('init', '--encryption=repokey', self.repository_location)
+ output = self.cmd('create', '--list', '--files-cache=rechunk,ctime', self.repository_location + '::test1', 'input')
+ # no changes here, but this mode rechunks unconditionally
+ output = self.cmd('create', '--list', '--files-cache=rechunk,ctime', self.repository_location + '::test2', 'input')
+ self.assert_in("A input/file1", output)
+
def test_file_status_excluded(self):
"""test that excluded paths are listed"""
- now = time.time()
self.create_regular_file('file1', size=1024 * 80)
- os.utime('input/file1', (now - 5, now - 5)) # 5 seconds ago
+ time.sleep(1) # file2 must have newer timestamps than file1
self.create_regular_file('file2', size=1024 * 80)
if has_lchflags:
self.create_regular_file('file3', size=1024 * 80)
@@ -1647,9 +1685,8 @@ def test_create_json(self):
assert 'stats' in archive
def test_create_topical(self):
- now = time.time()
self.create_regular_file('file1', size=1024 * 80)
- os.utime('input/file1', (now-5, now-5))
+ time.sleep(1) # file2 must have newer timestamps than file1
self.create_regular_file('file2', size=1024 * 80)
self.cmd('init', '--encryption=repokey', self.repository_location)
# no listing by default
@@ -2363,7 +2400,7 @@ def test_recreate_rechunkify(self):
fd.write(b'b' * 280)
self.cmd('init', '--encryption=repokey', self.repository_location)
self.cmd('create', '--chunker-params', '7,9,8,128', self.repository_location + '::test1', 'input')
- self.cmd('create', self.repository_location + '::test2', 'input', '--no-files-cache')
+ self.cmd('create', self.repository_location + '::test2', 'input', '--files-cache=disabled')
list = self.cmd('list', self.repository_location + '::test1', 'input/large_file',
'--format', '{num_chunks} {unique_chunks}')
num_chunks, unique_chunks = map(int, list.split(' '))
@@ -3513,7 +3550,6 @@ def define_common_options(add_common_option):
add_common_option('-p', '--progress', dest='progress', action='store_true', help='foo')
add_common_option('--lock-wait', dest='lock_wait', type=int, metavar='N', default=1,
help='(default: %(default)d).')
- add_common_option('--no-files-cache', dest='no_files_cache', action='store_false', help='foo')
@pytest.fixture
def basic_parser(self):
@@ -3555,7 +3591,6 @@ def parse_vars_from_line(*line):
def test_simple(self, parse_vars_from_line):
assert parse_vars_from_line('--error') == {
- 'no_files_cache': True,
'append': [],
'lock_wait': 1,
'log_level': 'error',
@@ -3563,7 +3598,6 @@ def test_simple(self, parse_vars_from_line):
}
assert parse_vars_from_line('--error', 'subcommand', '--critical') == {
- 'no_files_cache': True,
'append': [],
'lock_wait': 1,
'log_level': 'critical',
@@ -3576,7 +3610,6 @@ def test_simple(self, parse_vars_from_line):
parse_vars_from_line('--append-only', 'subcommand')
assert parse_vars_from_line('--append=foo', '--append', 'bar', 'subcommand', '--append', 'baz') == {
- 'no_files_cache': True,
'append': ['foo', 'bar', 'baz'],
'lock_wait': 1,
'log_level': 'warning',
@@ -3589,7 +3622,6 @@ def test_simple(self, parse_vars_from_line):
@pytest.mark.parametrize('flag,args_key,args_value', (
('-p', 'progress', True),
('--lock-wait=3', 'lock_wait', 3),
- ('--no-files-cache', 'no_files_cache', False),
))
def test_flag_position_independence(self, parse_vars_from_line, position, flag, args_key, args_value):
line = []
@@ -3600,7 +3632,6 @@ def test_flag_position_independence(self, parse_vars_from_line, position, flag,
line.append(flag)
result = {
- 'no_files_cache': True,
'append': [],
'lock_wait': 1,
'log_level': 'warning',
| {
"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": 3
},
"num_modified_files": 6
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-xdist",
"pytest-cov"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc libacl1-dev libacl1 libssl-dev liblz4-dev libzstd-dev build-essential pkg-config python3-pkgconfig"
],
"python": "3.9",
"reqs_path": [
"requirements.d/development.txt",
"requirements.d/docs.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.16
babel==2.17.0
-e git+https://github.com/borgbackup/borg.git@dcf5e77253d35ca625d53f356cd2b969f4f4c6fd#egg=borgbackup
cachetools==5.5.2
certifi==2025.1.31
chardet==5.2.0
charset-normalizer==3.4.1
colorama==0.4.6
coverage==7.8.0
Cython==3.0.12
distlib==0.3.9
docutils==0.21.2
exceptiongroup==1.2.2
execnet==2.1.1
filelock==3.18.0
guzzle_sphinx_theme==0.7.11
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
MarkupSafe==3.0.2
msgpack-python==0.5.6
packaging==24.2
platformdirs==4.3.7
pluggy==1.5.0
py-cpuinfo==9.0.0
Pygments==2.19.1
pyproject-api==1.9.0
pytest==8.3.5
pytest-benchmark==5.1.0
pytest-cov==6.0.0
pytest-xdist==3.6.1
pyzmq==26.3.0
requests==2.32.3
setuptools-scm==8.2.0
snowballstemmer==2.2.0
Sphinx==7.4.7
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
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: borg
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- babel==2.17.0
- cachetools==5.5.2
- certifi==2025.1.31
- chardet==5.2.0
- charset-normalizer==3.4.1
- colorama==0.4.6
- coverage==7.8.0
- cython==3.0.12
- distlib==0.3.9
- docutils==0.21.2
- exceptiongroup==1.2.2
- execnet==2.1.1
- filelock==3.18.0
- guzzle-sphinx-theme==0.7.11
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- markupsafe==3.0.2
- msgpack-python==0.5.6
- packaging==24.2
- platformdirs==4.3.7
- pluggy==1.5.0
- py-cpuinfo==9.0.0
- pygments==2.19.1
- pyproject-api==1.9.0
- pytest==8.3.5
- pytest-benchmark==5.1.0
- pytest-cov==6.0.0
- pytest-xdist==3.6.1
- pyzmq==26.3.0
- requests==2.32.3
- setuptools-scm==8.2.0
- snowballstemmer==2.2.0
- sphinx==7.4.7
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- 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/borg
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_cs_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_ms_cache_mode",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_rc_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_cs_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_ms_cache_mode",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_rc_cache_mode"
]
| [
"src/borg/testsuite/archiver.py::test_return_codes[python]",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_multiple",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_check_usage",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_corrupted_manifest",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_corrupted_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_file_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_manifest",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_disable2",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_not_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_common_options",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_auto_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_none_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_compressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_no_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_stdin",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_manifest",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_refcount_obj",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_multiple",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_detect_attic_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_repository_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_size",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_rechunkify",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_recompress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_path",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_remote_repo_restrict_to_repository",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_chunks",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_cache_files",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_chunks_archive",
"src/borg/testsuite/archiver.py::ArchiverCorruptionTestCase::test_old_version_interfered",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_sort_option"
]
| [
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lz4_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_lzma_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_compression_zlib_uncompressible",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_debug_put_get_delete_obj",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_force",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_nested_repositories",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::ArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_attic013_acl_bug",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_empty_repository",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_extra_chunks",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_manifest_rebuild_duplicate_archive",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_item_chunk",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_missing_archive_metadata",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data",
"src/borg/testsuite/archiver.py::ArchiverCheckTestCase::test_verify_data_unencrypted",
"src/borg/testsuite/archiver.py::ManifestAuthenticationTest::test_fresh_init_tam_required",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_aes_counter_uniqueness_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_atime",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_bad_filters",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_benchmark_crud",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_break_lock",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_check_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_comment",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_corrupted_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_but_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_exclude_folder_no_recurse",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_intermediate_folders_first",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_pattern_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_read_special_broken_symlink",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_topical",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_create_without_root",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_archive_items",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_dump_repo_objs",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_debug_profile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_double_force",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_delete_repo",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_keep_tagged_deprecation",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_gz",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_export_tar_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_include_exclude_regex_from_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_pattern_opt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_progress",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_extract_with_pattern",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_file_status_excluded",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_help",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_info",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_interrupt",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_init_requires_encryption_option",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_keyfile",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_qr",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_export_repokey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_errors",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_key_import_paperkey",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_chunk_counts",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_format",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_hash",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_json_args",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_list_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_log_json",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_overwrite",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_path_normalization",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_off",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_progress_on",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_glob",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_prefix",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_prune_repository_save_space",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_basic",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_dry_run",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_caches",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_keep_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_exclude_tagged",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_list_output",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_skips_nothing_to_do",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_subtree_hardlinks",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_recreate_target_rc",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repeated_files",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_move",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection2_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_no_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_repository_swap_detection_repokey_blank_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_security_dir_compat",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_sparse_file",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_doesnt_leak",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_strip_components_links",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_symlink_extract",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_umask",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unix_socket",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_cache_sync",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_change_passphrase",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_create",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_delete",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_read",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_feature_on_rename",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_mandatory_feature_in_cache",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unknown_unencrypted",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_unusual_filenames",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_usage",
"src/borg/testsuite/archiver.py::RemoteArchiverTestCase::test_with_lock",
"src/borg/testsuite/archiver.py::DiffArchiverTestCase::test_basic_functionality",
"src/borg/testsuite/archiver.py::test_get_args",
"src/borg/testsuite/archiver.py::test_chunk_content_equal",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_basic",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_empty",
"src/borg/testsuite/archiver.py::TestBuildFilter::test_strip_components",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_simple",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[-p-progress-True-both]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-before]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-after]",
"src/borg/testsuite/archiver.py::TestCommonOptions::test_flag_position_independence[--lock-wait=3-lock_wait-3-both]",
"src/borg/testsuite/archiver.py::test_parse_storage_quota",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark",
"src/borg/testsuite/archiver.py::test_help_formatting[benchmark-parser1]",
"src/borg/testsuite/archiver.py::test_help_formatting[break-lock-parser2]",
"src/borg/testsuite/archiver.py::test_help_formatting[change-passphrase-parser3]",
"src/borg/testsuite/archiver.py::test_help_formatting[check-parser4]",
"src/borg/testsuite/archiver.py::test_help_formatting[create-parser5]",
"src/borg/testsuite/archiver.py::test_help_formatting[debug",
"src/borg/testsuite/archiver.py::test_help_formatting[debug-parser16]",
"src/borg/testsuite/archiver.py::test_help_formatting[delete-parser17]",
"src/borg/testsuite/archiver.py::test_help_formatting[diff-parser18]",
"src/borg/testsuite/archiver.py::test_help_formatting[export-tar-parser19]",
"src/borg/testsuite/archiver.py::test_help_formatting[extract-parser20]",
"src/borg/testsuite/archiver.py::test_help_formatting[help-parser21]",
"src/borg/testsuite/archiver.py::test_help_formatting[info-parser22]",
"src/borg/testsuite/archiver.py::test_help_formatting[init-parser23]",
"src/borg/testsuite/archiver.py::test_help_formatting[key",
"src/borg/testsuite/archiver.py::test_help_formatting[key-parser28]",
"src/borg/testsuite/archiver.py::test_help_formatting[list-parser29]",
"src/borg/testsuite/archiver.py::test_help_formatting[mount-parser30]",
"src/borg/testsuite/archiver.py::test_help_formatting[prune-parser31]",
"src/borg/testsuite/archiver.py::test_help_formatting[recreate-parser32]",
"src/borg/testsuite/archiver.py::test_help_formatting[rename-parser33]",
"src/borg/testsuite/archiver.py::test_help_formatting[serve-parser34]",
"src/borg/testsuite/archiver.py::test_help_formatting[umount-parser35]",
"src/borg/testsuite/archiver.py::test_help_formatting[upgrade-parser36]",
"src/borg/testsuite/archiver.py::test_help_formatting[with-lock-parser37]",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[patterns-\\nFile",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[placeholders-\\nRepository",
"src/borg/testsuite/archiver.py::test_help_formatting_helptexts[compression-\\nIt"
]
| []
| BSD License | 1,667 | [
"src/borg/archive.py",
"src/borg/helpers/parseformat.py",
"src/borg/constants.py",
"docs/internals/data-structures.rst",
"src/borg/archiver.py",
"src/borg/cache.py"
]
| [
"src/borg/archive.py",
"src/borg/helpers/parseformat.py",
"src/borg/constants.py",
"docs/internals/data-structures.rst",
"src/borg/archiver.py",
"src/borg/cache.py"
]
|
jnothman__searchgrid-6 | 071a5c348caaf7f24889a7d0fd609c75521be3c9 | 2017-09-11 06:44:03 | 071a5c348caaf7f24889a7d0fd609c75521be3c9 | diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index 98c5a72..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,29 +0,0 @@
-BSD 3-Clause License
-
-Copyright (c) 2017, Joel Nothman
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-* Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
-* Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
-* Neither the name of the copyright holder nor the names of its
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/README.rst b/README.rst
index dabcc64..e57dd0d 100644
--- a/README.rst
+++ b/README.rst
@@ -47,6 +47,11 @@ and use in Python::
search = make_grid_search(estimator, cv=..., scoring=...)
search.fit(X, y)
+Or search for the best among multiple distinct estimators/pipelines::
+
+ search = make_grid_search([estimator1, estimator2], cv=..., scoring=...)
+ search.fit(X, y)
+
Motivating examples
...................
@@ -147,7 +152,6 @@ Searching over multiple grids.
... reduce=[kbest, pca])
>>> gs = make_grid_search(pipe)
-
.. |py-versions| image:: https://img.shields.io/pypi/pyversions/Django.svg
:alt: Python versions supported
diff --git a/searchgrid.py b/searchgrid.py
index dcbff65..bbe4862 100644
--- a/searchgrid.py
+++ b/searchgrid.py
@@ -1,7 +1,8 @@
-from collections import Mapping
-import itertools
+from collections import Mapping as _Mapping
+import itertools as _itertools
from sklearn.model_selection import GridSearchCV as _GridSearchCV
+from sklearn.pipeline import Pipeline as _Pipeline
def set_grid(estimator, **grid):
@@ -32,7 +33,7 @@ def _update_grid(dest, src, prefix=None):
src = [{prefix + k: v for k, v in d.items()}
for d in src]
out = []
- for d1, d2 in itertools.product(dest, src):
+ for d1, d2 in _itertools.product(dest, src):
out_d = d1.copy()
out_d.update(d2)
out.append(out_d)
@@ -41,7 +42,7 @@ def _update_grid(dest, src, prefix=None):
def _build_param_grid(estimator):
grid = getattr(estimator, '_param_grid', {})
- if isinstance(grid, Mapping):
+ if isinstance(grid, _Mapping):
grid = [grid]
# handle estimator parameters having their own grids
@@ -100,14 +101,26 @@ def build_param_grid(estimator):
return out
+def _check_estimator(estimator):
+ if isinstance(estimator, list):
+ estimator = set_grid(_Pipeline([('root', estimator[0])]),
+ root=estimator)
+ elif not hasattr(estimator, 'fit'):
+ raise ValueError('Expected estimator, but %r does not have .fit'
+ % estimator)
+ return estimator
+
+
def make_grid_search(estimator, **kwargs):
"""Construct a GridSearchCV with the given estimator and its set grid
Parameters
----------
- estimator : scikit-learn compatible estimator
+ estimator : (list of) estimator
+ When a list, the estimators are searched over.
kwargs
Other parameters to the
:class:`sklearn.model_selection.GridSearchCV` constructor.
"""
+ estimator = _check_estimator(estimator)
return _GridSearchCV(estimator, build_param_grid(estimator), **kwargs)
| make_grid_search(list)
One should not need to create a pipeline just to search over multiple alternative estimators. | jnothman/searchgrid | diff --git a/test_searchgrid.py b/test_searchgrid.py
index fccfb1d..242b268 100644
--- a/test_searchgrid.py
+++ b/test_searchgrid.py
@@ -3,7 +3,8 @@ from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.feature_selection import SelectKBest
-from searchgrid import set_grid, build_param_grid
+from sklearn.datasets import load_iris
+from searchgrid import set_grid, build_param_grid, make_grid_search
@pytest.mark.parametrize(('estimator', 'param_grid'), [
@@ -45,3 +46,21 @@ def test_build_param_grid_set_estimator():
'clf__degree': [2, 3], 'sel__k': [2, 3]},
{'clf': [clf2, clf4], 'sel__k': [2, 3]}]
assert build_param_grid(estimator) == param_grid
+
+
+def test_make_grid_search():
+ X, y = load_iris(return_X_y=True)
+ lr = LogisticRegression()
+ svc = set_grid(SVC(), kernel=['poly'], degree=[2, 3])
+ gs1 = make_grid_search(lr, cv=5) # empty grid
+ gs2 = make_grid_search(svc, cv=5)
+ gs3 = make_grid_search([lr, svc], cv=5)
+ for gs, n_results in [(gs1, 1), (gs2, 2), (gs3, 3)]:
+ gs.fit(X, y)
+ assert gs.cv == 5
+ assert len(gs.cv_results_['params']) == n_results
+
+ svc_mask = gs3.cv_results_['param_root'] == svc
+ assert svc_mask.sum() == 2
+ assert gs3.cv_results_['param_root__degree'][svc_mask].tolist() == [2, 3]
+ assert gs3.cv_results_['param_root'][~svc_mask].tolist() == [lr]
| {
"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": 2,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 2
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov"
],
"pre_install": null,
"python": "3.6",
"reqs_path": [
"doc/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
coverage==6.2
docutils==0.18.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
iniconfig==1.1.1
Jinja2==3.0.3
joblib==1.1.1
MarkupSafe==2.0.1
numpy==1.19.5
numpydoc==1.1.0
packaging==21.3
pluggy==1.0.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytz==2025.2
requests==2.27.1
scikit-learn==0.24.2
scipy==1.5.4
-e git+https://github.com/jnothman/searchgrid.git@071a5c348caaf7f24889a7d0fd609c75521be3c9#egg=searchgrid
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
threadpoolctl==3.1.0
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: searchgrid
channels:
- defaults
- https://repo.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
- coverage==6.2
- docutils==0.18.1
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jinja2==3.0.3
- joblib==1.1.1
- markupsafe==2.0.1
- numpy==1.19.5
- numpydoc==1.1.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytz==2025.2
- requests==2.27.1
- scikit-learn==0.24.2
- scipy==1.5.4
- 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
- threadpoolctl==3.1.0
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/searchgrid
| [
"test_searchgrid.py::test_make_grid_search"
]
| []
| [
"test_searchgrid.py::test_build_param_grid[estimator0-param_grid0]",
"test_searchgrid.py::test_build_param_grid[estimator1-param_grid1]",
"test_searchgrid.py::test_build_param_grid[estimator2-param_grid2]",
"test_searchgrid.py::test_build_param_grid_set_estimator"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,668 | [
"LICENSE",
"searchgrid.py",
"README.rst"
]
| [
"LICENSE",
"searchgrid.py",
"README.rst"
]
|
|
biocore__deblur-156 | fd259a74f516a22db8db790ab2cd3a1afab96b22 | 2017-09-11 17:42:04 | fd259a74f516a22db8db790ab2cd3a1afab96b22 | diff --git a/ChangeLog.md b/ChangeLog.md
index ea3e5aa..a8981f9 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -4,6 +4,8 @@
### Features
+* Added `--left-trim-length` to allow for trimming nucleotides on the 5' end of each sequence. Please see [issue #154](https://github.com/biocore/deblur/issues/154) for more information.
+
### Backward-incompatible changes [stable]
### Performance enhancements
diff --git a/deblur/workflow.py b/deblur/workflow.py
index 6eb21f7..0f7d55a 100644
--- a/deblur/workflow.py
+++ b/deblur/workflow.py
@@ -100,7 +100,7 @@ def sequence_generator(input_fp):
yield (record.metadata['id'], str(record))
-def trim_seqs(input_seqs, trim_len):
+def trim_seqs(input_seqs, trim_len, left_trim_len):
"""Trim FASTA sequences to specified length.
Parameters
@@ -109,6 +109,9 @@ def trim_seqs(input_seqs, trim_len):
The list of input sequences in (label, sequence) format
trim_len : int
Sequence trimming length. Specify a value of -1 to disable trimming.
+ left_trim_len : int
+ Sequence trimming from the 5' end. A value of 0 will disable this trim.
+
Returns
-------
@@ -132,7 +135,7 @@ def trim_seqs(input_seqs, trim_len):
yield label, seq
elif len(seq) >= trim_len:
okseqs += 1
- yield label, seq[:trim_len]
+ yield label, seq[left_trim_len:trim_len]
if okseqs < 0.01*totseqs:
logger = logging.getLogger(__name__)
@@ -771,8 +774,8 @@ def create_otu_table(output_fp, deblurred_list,
def launch_workflow(seqs_fp, working_dir, mean_error, error_dist,
- indel_prob, indel_max, trim_length, min_size, ref_fp,
- ref_db_fp, threads_per_sample=1,
+ indel_prob, indel_max, trim_length, left_trim_length,
+ min_size, ref_fp, ref_db_fp, threads_per_sample=1,
sim_thresh=None, coverage_thresh=None):
"""Launch full deblur workflow for a single post split-libraries fasta file
@@ -792,6 +795,8 @@ def launch_workflow(seqs_fp, working_dir, mean_error, error_dist,
maximal indel number
trim_length: integer
sequence trim length
+ left_trim_length: integer
+ trim the first n reads
min_size: integer
upper limit on sequence abundance (discard sequences below limit)
ref_fp: tuple
@@ -823,7 +828,8 @@ def launch_workflow(seqs_fp, working_dir, mean_error, error_dist,
with open(output_trim_fp, 'w') as out_f:
for label, seq in trim_seqs(
input_seqs=sequence_generator(seqs_fp),
- trim_len=trim_length):
+ trim_len=trim_length,
+ left_trim_len=left_trim_length):
out_f.write(">%s\n%s\n" % (label, seq))
# Step 2: Dereplicate sequences
output_derep_fp = join(working_dir,
diff --git a/scripts/deblur b/scripts/deblur
index bd9704d..f5d9dcc 100755
--- a/scripts/deblur
+++ b/scripts/deblur
@@ -420,6 +420,10 @@ def build_biom_table(seqs_fp, output_biom_fp, min_reads, file_type, log_level,
"trim-length will be discarded. A value of -1 can be "
"specified to skip trimming; this assumes all sequences "
"have an identical length."))
[email protected]('--left-trim-length', required=False, type=int,
+ show_default=True, default=0,
+ help=("Trim the first N bases from every sequence. A value of 0 "
+ "disables this trim."))
@click.option('--pos-ref-fp', required=False, multiple=True,
default=[], show_default=False,
type=click.Path(resolve_path=True, readable=True, exists=True,
@@ -518,9 +522,9 @@ def build_biom_table(seqs_fp, output_biom_fp, min_reads, file_type, log_level,
def workflow(seqs_fp, output_dir, pos_ref_fp, pos_ref_db_fp,
neg_ref_fp, neg_ref_db_fp, overwrite,
mean_error, error_dist, indel_prob, indel_max,
- trim_length, min_reads, min_size, threads_per_sample,
- keep_tmp_files, log_level, log_file, jobs_to_start,
- is_worker_thread):
+ trim_length, left_trim_length, min_reads, min_size,
+ threads_per_sample, keep_tmp_files, log_level, log_file,
+ jobs_to_start, is_worker_thread):
"""Launch deblur workflow"""
start_log(level=log_level * 10, filename=log_file)
logger = logging.getLogger(__name__)
@@ -623,6 +627,7 @@ def workflow(seqs_fp, output_dir, pos_ref_fp, pos_ref_db_fp,
mean_error=mean_error,
error_dist=error_dist, indel_prob=indel_prob,
indel_max=indel_max, trim_length=trim_length,
+ left_trim_length=left_trim_length,
min_size=min_size, ref_fp=ref_fp, ref_db_fp=ref_db_fp,
threads_per_sample=threads_per_sample)
if deblurred_file_name is None:
@@ -651,7 +656,8 @@ def workflow(seqs_fp, output_dir, pos_ref_fp, pos_ref_db_fp,
# also create biom tables with
# only sequences matching the pos_ref_fp sequences (reference-hit.biom)
- # and only sequences not matching the pos_ref_fp sequences (reference-non-hit.biom)
+ # and only sequences not matching the pos_ref_fp sequences
+ # (reference-non-hit.biom)
tmp_files = remove_artifacts_from_biom_table(output_fp, outputfasta_fp,
pos_ref_fp, output_dir,
pos_ref_db_fp,
| Support "left trimming" on sequences
It would be useful if in addition to the normal trimming (at the end of the sequence), there was a parameter to trim initial bases of a sequence. | biocore/deblur | diff --git a/deblur/test/test_workflow.py b/deblur/test/test_workflow.py
index 0ea7174..b9bc8c6 100644
--- a/deblur/test/test_workflow.py
+++ b/deblur/test/test_workflow.py
@@ -128,7 +128,7 @@ class workflowTests(TestCase):
("seq5", "gagtgcgagatgcgtggtgagg"),
("seq6", "ggatgcgagatgcgtggtgatt"),
("seq7", "agggcgagattcctagtgga--")]
- obs = trim_seqs(seqs, -1)
+ obs = trim_seqs(seqs, -1, 0)
self.assertEqual(list(obs), seqs)
def test_trim_seqs_notrim_outofbounds(self):
@@ -140,7 +140,7 @@ class workflowTests(TestCase):
("seq6", "ggatgcgagatgcgtggtgatt"),
("seq7", "agggcgagattcctagtgga--")]
with self.assertRaises(ValueError):
- list(trim_seqs(seqs, -2))
+ list(trim_seqs(seqs, -2, 0))
def test_trim_seqs(self):
seqs = [("seq1", "tagggcaagactccatggtatga"),
@@ -150,7 +150,7 @@ class workflowTests(TestCase):
("seq5", "gagtgcgagatgcgtggtgagg"),
("seq6", "ggatgcgagatgcgtggtgatt"),
("seq7", "agggcgagattcctagtgga--")]
- obs = trim_seqs(seqs, 20)
+ obs = trim_seqs(seqs, 20, 0)
self.assertTrue(isinstance(obs, GeneratorType))
@@ -162,6 +162,26 @@ class workflowTests(TestCase):
("seq7", "agggcgagattcctagtgga")]
self.assertEqual(list(obs), exp)
+ def test_trim_seqs_left(self):
+ seqs = [("seq1", "tagggcaagactccatggtatga"),
+ ("seq2", "cggaggcgagatgcgtggta"),
+ ("seq3", "tactagcaagattcctggtaaagga"),
+ ("seq4", "aggatgcgagatgcgtg"),
+ ("seq5", "gagtgcgagatgcgtggtgagg"),
+ ("seq6", "ggatgcgagatgcgtggtgatt"),
+ ("seq7", "agggcgagattcctagtgga--")]
+ obs = trim_seqs(seqs, 20, 5)
+
+ self.assertTrue(isinstance(obs, GeneratorType))
+
+ exp = [("seq1", "caagactccatggta"),
+ ("seq2", "gcgagatgcgtggta"),
+ ("seq3", "gcaagattcctggta"),
+ ("seq5", "cgagatgcgtggtga"),
+ ("seq6", "cgagatgcgtggtga"),
+ ("seq7", "gagattcctagtgga")]
+ self.assertEqual(list(obs), exp)
+
def test_dereplicate_seqs_remove_singletons(self):
""" Test dereplicate_seqs() method functionality with
removing singletons
@@ -622,12 +642,14 @@ class workflowTests(TestCase):
indel_prob = 0.01
indel_max = 3
min_size = 2
+ left_trim_length = 0
nochimera = launch_workflow(seqs_fp=seqs_fp, working_dir=output_fp,
mean_error=mean_error,
error_dist=error_dist,
indel_prob=indel_prob,
indel_max=indel_max,
trim_length=trim_length,
+ left_trim_length=left_trim_length,
min_size=min_size,
ref_fp=(ref_fp,),
ref_db_fp=ref_db_fp,
@@ -789,6 +811,7 @@ class workflowTests(TestCase):
min_size = 2
# trim length longer than sequences
trim_length = -1
+ left_trim_length = 0
threads = 1
output_fp = launch_workflow(seqs_fp=seqs_fp,
@@ -798,6 +821,7 @@ class workflowTests(TestCase):
indel_prob=indel_prob,
indel_max=indel_max,
trim_length=trim_length,
+ left_trim_length=left_trim_length,
min_size=min_size,
ref_fp=(ref_fp,),
ref_db_fp=ref_db_fp,
@@ -826,6 +850,7 @@ class workflowTests(TestCase):
min_size = 2
# trim length longer than sequences
trim_length = 151
+ left_trim_length = 0
threads = 1
with self.assertWarns(UserWarning):
launch_workflow(seqs_fp=seqs_fp, working_dir=output_fp,
@@ -834,6 +859,7 @@ class workflowTests(TestCase):
indel_prob=indel_prob,
indel_max=indel_max,
trim_length=trim_length,
+ left_trim_length=left_trim_length,
min_size=min_size,
ref_fp=(ref_fp,),
ref_db_fp=ref_db_fp,
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 3
} | 1.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio"
],
"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"
} | asttokens==3.0.0
biom-format==2.1.16
certifi==2025.1.31
charset-normalizer==3.4.1
click==8.1.8
contourpy==1.3.0
coverage==7.8.0
cycler==0.12.1
Cython==3.0.12
-e git+https://github.com/biocore/deblur.git@fd259a74f516a22db8db790ab2cd3a1afab96b22#egg=deblur
decorator==5.2.1
exceptiongroup==1.2.2
execnet==2.1.1
executing==2.2.0
fonttools==4.56.0
h5py==3.13.0
hdmedians==0.14.2
idna==3.10
importlib_resources==6.5.2
iniconfig==2.1.0
ipython==8.18.1
jedi==0.19.2
kiwisolver==1.4.7
matplotlib==3.9.4
matplotlib-inline==0.1.7
natsort==8.4.0
numpy==1.26.4
packaging==24.2
pandas==2.2.3
parso==0.8.4
pexpect==4.9.0
pillow==11.1.0
pluggy==1.5.0
prompt_toolkit==3.0.50
ptyprocess==0.7.0
pure_eval==0.2.3
Pygments==2.19.1
pyparsing==3.2.3
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
pytz==2025.2
requests==2.32.3
scikit-bio==0.5.9
scipy==1.10.1
six==1.17.0
stack-data==0.6.3
tomli==2.2.1
traitlets==5.14.3
typing_extensions==4.13.0
tzdata==2025.2
urllib3==2.3.0
wcwidth==0.2.13
zipp==3.21.0
| name: deblur
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- asttokens==3.0.0
- biom-format==2.1.16
- certifi==2025.1.31
- charset-normalizer==3.4.1
- click==8.1.8
- contourpy==1.3.0
- coverage==7.8.0
- cycler==0.12.1
- cython==3.0.12
- decorator==5.2.1
- exceptiongroup==1.2.2
- execnet==2.1.1
- executing==2.2.0
- fonttools==4.56.0
- h5py==3.13.0
- hdmedians==0.14.2
- idna==3.10
- importlib-resources==6.5.2
- iniconfig==2.1.0
- ipython==8.18.1
- jedi==0.19.2
- kiwisolver==1.4.7
- matplotlib==3.9.4
- matplotlib-inline==0.1.7
- natsort==8.4.0
- numpy==1.26.4
- packaging==24.2
- pandas==2.2.3
- parso==0.8.4
- pexpect==4.9.0
- pillow==11.1.0
- pluggy==1.5.0
- prompt-toolkit==3.0.50
- ptyprocess==0.7.0
- pure-eval==0.2.3
- pygments==2.19.1
- pyparsing==3.2.3
- 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
- pytz==2025.2
- requests==2.32.3
- scikit-bio==0.5.9
- scipy==1.10.1
- six==1.17.0
- stack-data==0.6.3
- tomli==2.2.1
- traitlets==5.14.3
- typing-extensions==4.13.0
- tzdata==2025.2
- urllib3==2.3.0
- wcwidth==0.2.13
- zipp==3.21.0
prefix: /opt/conda/envs/deblur
| [
"deblur/test/test_workflow.py::workflowTests::test_trim_seqs",
"deblur/test/test_workflow.py::workflowTests::test_trim_seqs_left",
"deblur/test/test_workflow.py::workflowTests::test_trim_seqs_notrim",
"deblur/test/test_workflow.py::workflowTests::test_trim_seqs_notrim_outofbounds"
]
| [
"deblur/test/test_workflow.py::workflowTests::test_build_index_sortmerna",
"deblur/test/test_workflow.py::workflowTests::test_build_index_sortmerna_fail",
"deblur/test/test_workflow.py::workflowTests::test_create_otu_table",
"deblur/test/test_workflow.py::workflowTests::test_create_otu_table_same_sampleid",
"deblur/test/test_workflow.py::workflowTests::test_dereplicate_seqs",
"deblur/test/test_workflow.py::workflowTests::test_dereplicate_seqs_remove_singletons",
"deblur/test/test_workflow.py::workflowTests::test_launch_workflow",
"deblur/test/test_workflow.py::workflowTests::test_launch_workflow_incorrect_trim",
"deblur/test/test_workflow.py::workflowTests::test_launch_workflow_skip_trim",
"deblur/test/test_workflow.py::workflowTests::test_multiple_sequence_alignment",
"deblur/test/test_workflow.py::workflowTests::test_remove_artifacts_from_biom_table",
"deblur/test/test_workflow.py::workflowTests::test_remove_artifacts_seqs",
"deblur/test/test_workflow.py::workflowTests::test_remove_artifacts_seqs_index_prebuilt",
"deblur/test/test_workflow.py::workflowTests::test_remove_artifacts_seqs_negate",
"deblur/test/test_workflow.py::workflowTests::test_remove_chimeras_denovo_from_seqs"
]
| [
"deblur/test/test_workflow.py::workflowTests::test_fasta_from_biom",
"deblur/test/test_workflow.py::workflowTests::test_filter_minreads_samples_from_table",
"deblur/test/test_workflow.py::workflowTests::test_get_fastq_variant",
"deblur/test/test_workflow.py::workflowTests::test_get_files_for_table",
"deblur/test/test_workflow.py::workflowTests::test_sample_id_from_read_id",
"deblur/test/test_workflow.py::workflowTests::test_sequence_generator_fasta",
"deblur/test/test_workflow.py::workflowTests::test_sequence_generator_fastq",
"deblur/test/test_workflow.py::workflowTests::test_sequence_generator_invalid_format",
"deblur/test/test_workflow.py::workflowTests::test_split_sequence_file_on_sample_ids_to_files"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,670 | [
"ChangeLog.md",
"deblur/workflow.py",
"scripts/deblur"
]
| [
"ChangeLog.md",
"deblur/workflow.py",
"scripts/deblur"
]
|
|
construct__construct-399 | 670eb6c1b6e9f6c9e6ea7102d08d115612818134 | 2017-09-12 17:19:41 | 670eb6c1b6e9f6c9e6ea7102d08d115612818134 | diff --git a/construct/core.py b/construct/core.py
index 85406a7..9b3bbc4 100644
--- a/construct/core.py
+++ b/construct/core.py
@@ -1126,17 +1126,12 @@ class RepeatUntil(Subconstruct):
super(RepeatUntil, self).__init__(subcon)
self.predicate = predicate
def _parse(self, stream, context, path):
- try:
- obj = []
- while True:
- subobj = self.subcon._parse(stream, context, path)
- obj.append(subobj)
- if self.predicate(subobj, obj, context):
- return ListContainer(obj)
- except ExplicitError:
- raise
- except ConstructError:
- raise RangeError("missing terminator when parsing")
+ obj = []
+ while True:
+ subobj = self.subcon._parse(stream, context, path)
+ obj.append(subobj)
+ if self.predicate(subobj, obj, context):
+ return ListContainer(obj)
def _build(self, obj, stream, context, path):
for i, subobj in enumerate(obj):
self.subcon._build(subobj, stream, context, path)
| RepeatUntil catches too broad of Exception, gives misleading message
The following code:
```python
from construct import RepeatUntil, Const, Struct, Int32ul
data = b"\x01\x00\x00\x00" * 10
TEN_ONES = Struct(
RepeatUntil(lambda obj, lst, ctx: len(lst) == 10, Const(Int32ul, 1))
)
TEN_TWOS = Struct(
RepeatUntil(lambda obj, lst, ctx: len(lst) == 10, Const(Int32ul, 2))
)
TEN_ONES.parse(data) # Works
TEN_TWOS.parse(data) # Opaque/Misleading Exception
```
Gives the error message:
```
$> env/bin/python test_construct.py
Traceback (most recent call last):
File "test_construct.py", line 16, in <module>
TEN_TWOS.parse(data)
File "env/lib/python2.7/site-packages/construct/core.py", line 161, in parse
return self.parse_stream(BytesIO(data), context, **kw)
File "env/lib/python2.7/site-packages/construct/core.py", line 174, in parse_stream
return self._parse(stream, context2, "(parsing)")
File "env/lib/python2.7/site-packages/construct/core.py", line 844, in _parse
subobj = sc._parse(stream, context, path)
File "env/lib/python2.7/site-packages/construct/core.py", line 1140, in _parse
raise RangeError("missing terminator when parsing")
construct.core.RangeError: missing terminator when parsing
```
But this not what I expected. For instance, with the following code:
```python
from construct import Const, Struct, Int32ul
data = b"\x01\x00\x00\x00"
ONE = Struct(
Const(Int32ul, 1)
)
TWO = Struct(
Const(Int32ul, 2)
)
ONE.parse(data) # Works
TWO.parse(data) # Expected Exception given
```
Gives the error message:
```
$> env/bin/python test_construct2.py
Traceback (most recent call last):
File "test_construct2.py", line 15, in <module>
TWO.parse(data) # Expected Exception given
File "env/lib/python2.7/site-packages/construct/core.py", line 161, in parse
return self.parse_stream(BytesIO(data), context, **kw)
File "env/lib/python2.7/site-packages/construct/core.py", line 174, in parse_stream
return self._parse(stream, context2, "(parsing)")
File "env/lib/python2.7/site-packages/construct/core.py", line 844, in _parse
subobj = sc._parse(stream, context, path)
File "env/lib/python2.7/site-packages/construct/core.py", line 1883, in _parse
raise ConstError("expected %r but parsed %r" % (self.value, obj))
construct.core.ConstError: expected 2 but parsed 1
```
Which is the error message I would have expected from the first example.
In fact, changing [this line](https://github.com/construct/construct/blob/670eb6c1b6e9f6c9e6ea7102d08d115612818134/construct/core.py#L1139) to `raise` gives the expected Exception.
The `RepeatUntil` implementation is catching too broad of Exceptions, and returning misleading error messages as a result. | construct/construct | diff --git a/tests/test_all.py b/tests/test_all.py
index 7681026..d9ef53e 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -252,7 +252,7 @@ class TestCore(unittest.TestCase):
def test_repeatuntil(self):
assert RepeatUntil(obj_ == 9, Byte).parse(b"\x02\x03\x09garbage") == [2,3,9]
assert RepeatUntil(obj_ == 9, Byte).build([2,3,9,1,1,1]) == b"\x02\x03\x09"
- assert raises(RepeatUntil(obj_ == 9, Byte).parse, b"\x02\x03\x08") == RangeError
+ assert raises(RepeatUntil(obj_ == 9, Byte).parse, b"\x02\x03\x08") == FieldError
assert raises(RepeatUntil(obj_ == 9, Byte).build, [2,3,8]) == RangeError
assert raises(RepeatUntil(obj_ == 9, Byte).sizeof) == SizeofError
assert RepeatUntil(lambda x,lst,ctx: lst[-2:]==[0,0], Byte).parse(b"\x01\x00\x00\xff") == [1,0,0]
| {
"commit_name": "merge_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 0,
"test_score": 3
},
"num_modified_files": 1
} | 2.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"numpy"
],
"pre_install": null,
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | -e git+https://github.com/construct/construct.git@670eb6c1b6e9f6c9e6ea7102d08d115612818134#egg=construct
coverage==7.8.0
exceptiongroup==1.2.2
iniconfig==2.1.0
numpy==2.0.2
packaging==24.2
pluggy==1.5.0
pytest==8.3.5
pytest-cov==6.0.0
tomli==2.2.1
| name: construct
channels:
- defaults
- https://repo.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
- numpy==2.0.2
- packaging==24.2
- pluggy==1.5.0
- pytest==8.3.5
- pytest-cov==6.0.0
- tomli==2.2.1
prefix: /opt/conda/envs/construct
| [
"tests/test_all.py::TestCore::test_repeatuntil"
]
| []
| [
"tests/test_all.py::TestCore::test_aligned",
"tests/test_all.py::TestCore::test_alignedstruct",
"tests/test_all.py::TestCore::test_array",
"tests/test_all.py::TestCore::test_bitsinteger",
"tests/test_all.py::TestCore::test_bitsswapped",
"tests/test_all.py::TestCore::test_bitsswapped_from_issue_145",
"tests/test_all.py::TestCore::test_bitstruct",
"tests/test_all.py::TestCore::test_bitstruct_from_issue_39",
"tests/test_all.py::TestCore::test_bitwise",
"tests/test_all.py::TestCore::test_bytes",
"tests/test_all.py::TestCore::test_bytesinteger",
"tests/test_all.py::TestCore::test_byteswapped",
"tests/test_all.py::TestCore::test_byteswapped_from_issue_70",
"tests/test_all.py::TestCore::test_bytewise",
"tests/test_all.py::TestCore::test_check",
"tests/test_all.py::TestCore::test_checksum",
"tests/test_all.py::TestCore::test_compressed_bzip2",
"tests/test_all.py::TestCore::test_compressed_gzip",
"tests/test_all.py::TestCore::test_compressed_lzma",
"tests/test_all.py::TestCore::test_compressed_prefixed",
"tests/test_all.py::TestCore::test_compressed_zlib",
"tests/test_all.py::TestCore::test_computed",
"tests/test_all.py::TestCore::test_const",
"tests/test_all.py::TestCore::test_context",
"tests/test_all.py::TestCore::test_cstring",
"tests/test_all.py::TestCore::test_default",
"tests/test_all.py::TestCore::test_embeddedbitstruct",
"tests/test_all.py::TestCore::test_embeddedif_issue_296",
"tests/test_all.py::TestCore::test_embeddedswitch_issue_312",
"tests/test_all.py::TestCore::test_enum",
"tests/test_all.py::TestCore::test_error",
"tests/test_all.py::TestCore::test_expradapter",
"tests/test_all.py::TestCore::test_exprsymmetricadapter",
"tests/test_all.py::TestCore::test_exprvalidator",
"tests/test_all.py::TestCore::test_filter",
"tests/test_all.py::TestCore::test_flag",
"tests/test_all.py::TestCore::test_flagsenum",
"tests/test_all.py::TestCore::test_floats",
"tests/test_all.py::TestCore::test_floats_randomized",
"tests/test_all.py::TestCore::test_focusedseq",
"tests/test_all.py::TestCore::test_formatfield",
"tests/test_all.py::TestCore::test_formatfield_floats_randomized",
"tests/test_all.py::TestCore::test_formatfield_ints_randomized",
"tests/test_all.py::TestCore::test_from_issue_171",
"tests/test_all.py::TestCore::test_from_issue_175",
"tests/test_all.py::TestCore::test_from_issue_231",
"tests/test_all.py::TestCore::test_from_issue_244",
"tests/test_all.py::TestCore::test_from_issue_246",
"tests/test_all.py::TestCore::test_from_issue_269",
"tests/test_all.py::TestCore::test_from_issue_28",
"tests/test_all.py::TestCore::test_from_issue_298",
"tests/test_all.py::TestCore::test_from_issue_324",
"tests/test_all.py::TestCore::test_from_issue_357",
"tests/test_all.py::TestCore::test_from_issue_362",
"tests/test_all.py::TestCore::test_from_issue_60",
"tests/test_all.py::TestCore::test_from_issue_71",
"tests/test_all.py::TestCore::test_from_issue_76",
"tests/test_all.py::TestCore::test_from_issue_87",
"tests/test_all.py::TestCore::test_globally_encoded_strings",
"tests/test_all.py::TestCore::test_greedybytes",
"tests/test_all.py::TestCore::test_greedyrange",
"tests/test_all.py::TestCore::test_greedystring",
"tests/test_all.py::TestCore::test_hanging_issue_280",
"tests/test_all.py::TestCore::test_hex",
"tests/test_all.py::TestCore::test_hex_regression_188",
"tests/test_all.py::TestCore::test_hexdump",
"tests/test_all.py::TestCore::test_hexdump_regression_188",
"tests/test_all.py::TestCore::test_if",
"tests/test_all.py::TestCore::test_ifthenelse",
"tests/test_all.py::TestCore::test_indexing",
"tests/test_all.py::TestCore::test_ints",
"tests/test_all.py::TestCore::test_ints24",
"tests/test_all.py::TestCore::test_ipaddress_from_issue_95",
"tests/test_all.py::TestCore::test_lazybound",
"tests/test_all.py::TestCore::test_lazybound_node",
"tests/test_all.py::TestCore::test_lazyrange",
"tests/test_all.py::TestCore::test_lazysequence",
"tests/test_all.py::TestCore::test_lazysequence_kwctor",
"tests/test_all.py::TestCore::test_lazysequence_nested_embedded",
"tests/test_all.py::TestCore::test_lazystruct",
"tests/test_all.py::TestCore::test_lazystruct_kwctor",
"tests/test_all.py::TestCore::test_lazystruct_nested_embedded",
"tests/test_all.py::TestCore::test_namedtuple",
"tests/test_all.py::TestCore::test_nonbytes_checksum_issue_323",
"tests/test_all.py::TestCore::test_noneof",
"tests/test_all.py::TestCore::test_numpy",
"tests/test_all.py::TestCore::test_ondemand",
"tests/test_all.py::TestCore::test_ondemandpointer",
"tests/test_all.py::TestCore::test_oneof",
"tests/test_all.py::TestCore::test_operators",
"tests/test_all.py::TestCore::test_optional",
"tests/test_all.py::TestCore::test_padded",
"tests/test_all.py::TestCore::test_padding",
"tests/test_all.py::TestCore::test_pascalstring",
"tests/test_all.py::TestCore::test_pass",
"tests/test_all.py::TestCore::test_peek",
"tests/test_all.py::TestCore::test_pointer",
"tests/test_all.py::TestCore::test_prefixed",
"tests/test_all.py::TestCore::test_prefixedarray",
"tests/test_all.py::TestCore::test_probe",
"tests/test_all.py::TestCore::test_probeinto",
"tests/test_all.py::TestCore::test_range",
"tests/test_all.py::TestCore::test_rawcopy",
"tests/test_all.py::TestCore::test_rawcopy_issue_289",
"tests/test_all.py::TestCore::test_rawcopy_issue_358",
"tests/test_all.py::TestCore::test_rebuffered",
"tests/test_all.py::TestCore::test_rebuild",
"tests/test_all.py::TestCore::test_renamed",
"tests/test_all.py::TestCore::test_restreamed",
"tests/test_all.py::TestCore::test_restreamed_partial_read",
"tests/test_all.py::TestCore::test_seek",
"tests/test_all.py::TestCore::test_select",
"tests/test_all.py::TestCore::test_select_kwctor",
"tests/test_all.py::TestCore::test_sequence",
"tests/test_all.py::TestCore::test_sequence_nested_embedded",
"tests/test_all.py::TestCore::test_slicing",
"tests/test_all.py::TestCore::test_stopif",
"tests/test_all.py::TestCore::test_string",
"tests/test_all.py::TestCore::test_struct",
"tests/test_all.py::TestCore::test_struct_kwctor",
"tests/test_all.py::TestCore::test_struct_nested_embedded",
"tests/test_all.py::TestCore::test_struct_proper_context",
"tests/test_all.py::TestCore::test_struct_sizeof_context_nesting",
"tests/test_all.py::TestCore::test_switch",
"tests/test_all.py::TestCore::test_switch_issue_357",
"tests/test_all.py::TestCore::test_tell",
"tests/test_all.py::TestCore::test_terminated",
"tests/test_all.py::TestCore::test_union",
"tests/test_all.py::TestCore::test_union_issue_348",
"tests/test_all.py::TestCore::test_union_kwctor",
"tests/test_all.py::TestCore::test_varint",
"tests/test_all.py::TestCore::test_varint_randomized"
]
| []
| MIT License | 1,671 | [
"construct/core.py"
]
| [
"construct/core.py"
]
|
|
byu-oit__awslogin-30 | 8411dc178a022c92be40eeea820bcce1b15c2450 | 2017-09-12 19:21:23 | 71d40473479eff970f1078395600019e960c2a54 | diff --git a/README.rst b/README.rst
index ce35b06..0bdbd4b 100644
--- a/README.rst
+++ b/README.rst
@@ -66,6 +66,7 @@ To use it:
arguments as well.
- Run ``awslogin --profile <profile name>`` to specifiy an alternative
profile
+- Run ``awslogin --region <region name>`` to specify a different region. The default region is *us-west-2*.
- Run ``awslogin --status`` for the current status of the default profile
- Run ``awslogin --status --profile dev`` for the current status of the
dev profile
diff --git a/byu_awslogin/index.py b/byu_awslogin/index.py
index 7abb2fc..b0a82a6 100755
--- a/byu_awslogin/index.py
+++ b/byu_awslogin/index.py
@@ -22,7 +22,7 @@ except ImportError:
from .util.data_cache import get_status, load_cached_adfs_auth
from .login import cached_login, non_cached_login
-__VERSION__ = '0.12.3'
+__VERSION__ = '0.12.4'
# Enable VT Mode on windows terminal code from:
# https://bugs.python.org/issue29059
@@ -41,8 +41,9 @@ if platform.system().lower() == 'windows':
@click.option('-a', '--account', help='Account to login with')
@click.option('-r', '--role', help='Role to use after login')
@click.option('-p', '--profile', default='default', help='Profile to use store credentials. Defaults to default')
[email protected]('--region', default='us-west-2', help="The AWS region you will be hitting")
@click.option('-s', '--status', is_flag=True, default=False, help='Display current logged in status. Use profile all to see all statuses')
-def cli(account, role, profile, status):
+def cli(account, role, profile, region, status):
_ensure_min_python_version()
# Display status and exit if the user specified the "-s" flag
@@ -53,10 +54,10 @@ def cli(account, role, profile, status):
# Use cached SAML assertion if already logged in, else login to ADFS
adfs_auth_result = load_cached_adfs_auth()
if adfs_auth_result:
- cached_login(account, role, profile, adfs_auth_result)
+ cached_login(account, role, profile, region, adfs_auth_result)
pass
else:
- non_cached_login(account, role, profile)
+ non_cached_login(account, role, profile, region)
def _ensure_min_python_version():
diff --git a/byu_awslogin/login.py b/byu_awslogin/login.py
index deb5354..01abe74 100644
--- a/byu_awslogin/login.py
+++ b/byu_awslogin/login.py
@@ -8,16 +8,16 @@ from .util.consoleeffects import Colors
from .util.data_cache import load_last_netid, write_to_config_file, write_to_cred_file, cache_adfs_auth
-def cached_login(account, role, profile, adfs_auth_result):
+def cached_login(account, role, profile, region, adfs_auth_result):
saml_assertion = get_saml_assertion(adfs_auth_result)
if not saml_assertion: # Not logged in anymore, so need to re-login
- non_cached_login(account, role, profile)
+ non_cached_login(account, role, profile, region)
else: # Still logged in and got a SAML assertion properly
- _perform_login(adfs_auth_result, saml_assertion, account, role, profile, None)
+ _perform_login(adfs_auth_result, saml_assertion, account, role, profile, None, region)
-def non_cached_login(account, role, profile):
+def non_cached_login(account, role, profile, region):
# Get the federated credentials from the user
net_id, username = _get_user_ids(profile)
password = getpass.getpass()
@@ -35,10 +35,10 @@ def non_cached_login(account, role, profile):
del password
saml_assertion = get_saml_assertion(adfs_auth_result)
- _perform_login(adfs_auth_result, saml_assertion, account, role, profile, net_id)
+ _perform_login(adfs_auth_result, saml_assertion, account, role, profile, net_id, region)
-def _perform_login(adfs_auth_result, saml_assertion, account, role, profile, net_id):
+def _perform_login(adfs_auth_result, saml_assertion, account, role, profile, net_id, region):
account_roles_to_assume = _prompt_for_roles_to_assume(saml_assertion, account, role)
# Assume all requested roles and set in the environment
@@ -50,7 +50,7 @@ def _perform_login(adfs_auth_result, saml_assertion, account, role, profile, net
profile = account_role_to_assume.account_name
write_to_cred_file(profile, aws_session_token)
- write_to_config_file(profile, net_id, 'us-west-2', account_role_to_assume.role_name,
+ write_to_config_file(profile, net_id, region, account_role_to_assume.role_name,
account_role_to_assume.account_name)
_print_status_message(account_role_to_assume)
| Add optional parameter for region
Add an optional parameter to specify a region other than us-west-2. Use case is a Alexa and lex and potentially others aren't available in us-west-2 | byu-oit/awslogin | diff --git a/test/byu_awslogin/test_login.py b/test/byu_awslogin/test_login.py
index 70f60dc..ce1b289 100644
--- a/test/byu_awslogin/test_login.py
+++ b/test/byu_awslogin/test_login.py
@@ -21,7 +21,7 @@ def test_cached_login(mock_cache_adfs_auth, mock_write_to_config_file,
]
mock_assume_role.return_value = "FakeSessionToken"
- cached_login("FakeAccount", None, "default", {})
+ cached_login("FakeAccount", None, "default", {}, 'us-west-2')
assert mock_get_saml_assertion.call_count == 1
assert mock_prompt_roles.call_count == 1
@@ -54,7 +54,7 @@ def test_non_cached_login(mock_cache_adfs_auth, mock_write_to_config_file,
]
mock_assume_role.return_value = "FakeSessionToken"
- non_cached_login("FakeAccount", None, "default")
+ non_cached_login("FakeAccount", None, "default", 'us-west-2')
assert mock_get_user_ids.call_count == 1
assert mock_get_password.call_count == 1
| {
"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": 3
} | lxml | {
"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 python3.6"
],
"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
awscli==1.11.96
beautifulsoup4==4.6.0
boto3==1.4.4
botocore==1.5.59
-e git+https://github.com/byu-oit/awslogin.git@8411dc178a022c92be40eeea820bcce1b15c2450#egg=byu_awslogin
certifi==2017.4.17
chardet==3.0.3
click==8.0.4
colorama==0.3.7
docutils==0.13.1
idna==2.5
importlib-metadata==4.8.3
iniconfig==1.1.1
jmespath==0.9.3
lxml==5.3.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pyasn1==0.5.1
pyparsing==3.1.4
pytest==7.0.1
python-dateutil==2.6.0
PyYAML==3.12
requests==2.17.3
rsa==3.4.2
s3transfer==0.1.10
six==1.10.0
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.21.1
zipp==3.6.0
| name: awslogin
channels:
- defaults
- https://repo.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
- awscli==1.11.96
- beautifulsoup4==4.6.0
- boto3==1.4.4
- botocore==1.5.59
- certifi==2017.4.17
- chardet==3.0.3
- click==8.0.4
- colorama==0.3.7
- docutils==0.13.1
- idna==2.5
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jmespath==0.9.3
- lxml==5.3.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pyasn1==0.5.1
- pyparsing==3.1.4
- pytest==7.0.1
- python-dateutil==2.6.0
- pyyaml==3.12
- requests==2.17.3
- rsa==3.4.2
- s3transfer==0.1.10
- six==1.10.0
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.21.1
- zipp==3.6.0
prefix: /opt/conda/envs/awslogin
| [
"test/byu_awslogin/test_login.py::test_cached_login",
"test/byu_awslogin/test_login.py::test_non_cached_login"
]
| []
| []
| []
| Apache License 2.0 | 1,672 | [
"README.rst",
"byu_awslogin/index.py",
"byu_awslogin/login.py"
]
| [
"README.rst",
"byu_awslogin/index.py",
"byu_awslogin/login.py"
]
|
|
OpenMined__PySyft-232 | 6c049ac8c4c2e9598bbd495d9a5fd716d3e46126 | 2017-09-12 20:03:09 | 06ce023225dd613d8fb14ab2046135b93ab22376 | diff --git a/syft/tensor.py b/syft/tensor.py
index 0aed1c3ef8..7d31e2e430 100644
--- a/syft/tensor.py
+++ b/syft/tensor.py
@@ -1034,6 +1034,67 @@ class TensorBase(object):
hist, edges = np.histogram(np.array(self.data), bins=bins, range=(min, max))
return TensorBase(hist)
+ def scatter_(self, dim, index, src):
+ """
+ Writes all values from the Tensor src into self at the indices specified in the index Tensor.
+ The indices are specified with respect to the given dimension, dim, in the manner described in gather().
+
+ :param dim: The axis along which to index
+ :param index: The indices of elements to scatter
+ :param src: The source element(s) to scatter
+ :return: self
+ """
+ index = _ensure_tensorbase(index)
+ if self.encrypted or index.encrypted:
+ return NotImplemented
+ if index.data.dtype != np.dtype('int_'):
+ raise TypeError("The values of index must be integers")
+ if self.data.ndim != index.data.ndim:
+ raise ValueError("Index should have the same number of dimensions as output")
+ if dim >= self.data.ndim or dim < -self.data.ndim:
+ raise IndexError("dim is out of range")
+ if dim < 0:
+ # Not sure why scatter should accept dim < 0, but that is the behavior in PyTorch's scatter
+ dim = self.data.ndim + dim
+ idx_xsection_shape = index.data.shape[:dim] + index.data.shape[dim + 1:]
+ self_xsection_shape = self.data.shape[:dim] + self.data.shape[dim + 1:]
+ if idx_xsection_shape != self_xsection_shape:
+ raise ValueError("Except for dimension " + str(dim) +
+ ", all dimensions of index and output should be the same size")
+ if (index.data >= self.data.shape[dim]).any() or (index.data < 0).any():
+ raise IndexError("The values of index must be between 0 and (self.data.shape[dim] -1)")
+
+ def make_slice(arr, dim, i):
+ slc = [slice(None)] * arr.ndim
+ slc[dim] = i
+ return slc
+
+ # We use index and dim parameters to create idx
+ # idx is in a form that can be used as a NumPy advanced index for scattering of src param. in self.data
+ idx = [[*np.indices(idx_xsection_shape).reshape(index.data.ndim - 1, -1),
+ index.data[make_slice(index.data, dim, i)].reshape(1, -1)[0]] for i in range(index.data.shape[dim])]
+ idx = list(np.concatenate(idx, axis=1))
+ idx.insert(dim, idx.pop())
+
+ if not np.isscalar(src):
+ src = _ensure_tensorbase(src)
+ if index.data.shape[dim] > src.data.shape[dim]:
+ raise IndexError("Dimension " + str(dim) + "of index can not be bigger than that of src ")
+ src_shape = src.data.shape[:dim] + src.data.shape[dim + 1:]
+ if idx_xsection_shape != src_shape:
+ raise ValueError("Except for dimension " +
+ str(dim) + ", all dimensions of index and src should be the same size")
+ # src_idx is a NumPy advanced index for indexing of elements in the src
+ src_idx = list(idx)
+ src_idx.pop(dim)
+ src_idx.insert(dim, np.repeat(np.arange(index.data.shape[dim]), np.prod(idx_xsection_shape)))
+ self.data[idx] = src.data[src_idx]
+
+ else:
+ self.data[idx] = src
+
+ return self
+
def serialize(self):
return pickle.dumps(self)
| Implement Default scatter Functionality for Base Tensor Type
**User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, scatter_() should operate inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation.
**Acceptance Criteria:**
- If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error.
- a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors.
- inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. | OpenMined/PySyft | diff --git a/tests/test_tensor.py b/tests/test_tensor.py
index d666b46e88..f586ff59ac 100644
--- a/tests/test_tensor.py
+++ b/tests/test_tensor.py
@@ -726,5 +726,100 @@ class notEqualTests(unittest.TestCase):
self.assertTrue(syft.equal(t1, TensorBase([1, 1, 1, 0])))
+class scatterTests(unittest.TestCase):
+ def testScatter_Numerical0(self):
+ t = TensorBase(np.zeros((3, 5)))
+ idx = TensorBase(np.array([[0, 0, 0, 0, 0]]))
+ src = 1.0
+ dim = 0
+ t.scatter_(dim=dim, index=idx, src=src)
+ self.assertTrue(np.array_equal(t.data, np.array([[1, 1, 1, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])))
+
+ def testScatter_Numerical1(self):
+ t = TensorBase(np.zeros((3, 5)))
+ idx = TensorBase(np.array([[0], [0], [0]]))
+ src = 1.0
+ dim = 1
+ t.scatter_(dim=dim, index=idx, src=src)
+ self.assertTrue(np.array_equal(t.data, np.array([[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]])))
+
+ def testScatter_Numerical2(self):
+ t = TensorBase(np.zeros((3, 5)))
+ idx = TensorBase(np.array([[0], [0], [0]]))
+ src = 1.0
+ dim = -1
+ t.scatter_(dim=dim, index=idx, src=src)
+ self.assertTrue(np.array_equal(t.data, np.array([[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]])))
+
+ def testScatter_Numerical3(self):
+ t = TensorBase(np.zeros((3, 5)))
+ idx = TensorBase(np.array([[0, 0, 0, 0, 0]]))
+ src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]))
+ dim = 0
+ t.scatter_(dim=dim, index=idx, src=src)
+ self.assertTrue(np.array_equal(t.data, np.array([[1, 2, 3, 4, 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])))
+
+ def testScatter_Numerical4(self):
+ t = TensorBase(np.zeros((3, 5)))
+ idx = TensorBase(np.array([[0, 0, 0, 0, 0]]))
+ src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]))
+ dim = -2
+ t.scatter_(dim=dim, index=idx, src=src)
+ self.assertTrue(np.array_equal(t.data, np.array([[1, 2, 3, 4, 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])))
+
+ def testScatter_Numerical5(self):
+ t = TensorBase(np.zeros((3, 5)))
+ idx = TensorBase(np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]))
+ src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]))
+ dim = 0
+ t.scatter_(dim=dim, index=idx, src=src)
+ self.assertTrue(np.array_equal(t.data, np.array([[6, 7, 8, 9, 10], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])))
+
+ def testScatter_Numerical6(self):
+ t = TensorBase(np.zeros((3, 4, 5)))
+ idx = [[[3, 0, 1, 1, 2], [0, 3, 3, 3, 3]], [[2, 0, 0, 0, 0], [2, 1, 0, 2, 0]],
+ [[0, 0, 1, 0, 2], [1, 3, 2, 2, 2]]]
+ src = [[[7, 84, 99, 71, 44], [79, 57, 2, 37, 62]], [[31, 44, 43, 54, 56], [72, 52, 21, 89, 95]],
+ [[5, 3, 99, 4, 52], [32, 88, 58, 62, 9]]]
+ dim = 1
+ t.scatter_(dim=dim, index=idx, src=src)
+ expected = [[[79, 84, 0, 0, 0], [0, 0, 99, 71, 0], [0, 0, 0, 0, 44], [7, 57, 2, 37, 62]],
+ [[0, 44, 21, 54, 95], [0, 52, 0, 0, 0], [72, 0, 0, 89, 0], [0, 0, 0, 0, 0]],
+ [[5, 3, 0, 4, 0], [32, 0, 99, 0, 0], [0, 0, 58, 62, 9], [0, 88, 0, 0, 0]]]
+ self.assertTrue(np.array_equal(t.data, np.array(expected)))
+
+ def testScatter_IndexType(self):
+ t = TensorBase(np.zeros((3, 5)))
+ idx = TensorBase(np.array([[0.0, 0.0, 0.0, 0.0, 0.0]]))
+ src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]))
+ dim = 0
+ with self.assertRaises(Exception):
+ t.scatter_(dim=dim, index=idx, src=src)
+
+ def testScatter_IndexOutOfRange(self):
+ t = TensorBase(np.zeros((3, 5)))
+ idx = TensorBase(np.array([[5, 0, 0, 0, 0]]))
+ src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]))
+ dim = 0
+ with self.assertRaises(Exception):
+ t.scatter_(dim=dim, index=idx, src=src)
+
+ def testScatter_DimOutOfRange(self):
+ t = TensorBase(np.zeros((3, 5)))
+ idx = TensorBase(np.array([[0, 0, 0, 0, 0]]))
+ src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]))
+ dim = 4
+ with self.assertRaises(Exception):
+ t.scatter_(dim=dim, index=idx, src=src)
+
+ def testScatter_index_src_dimension_mismatch(self):
+ t = TensorBase(np.zeros((3, 5)))
+ idx = TensorBase(np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]))
+ src = TensorBase(np.array([[1, 2, 3, 4, 5]]))
+ dim = 1
+ with self.assertRaises(Exception):
+ t.scatter_(dim=dim, index=idx, src=src)
+
+
if __name__ == "__main__":
unittest.main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 1
} | PySyft/hydrogen | {
"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-flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc musl-dev g++ libgmp3-dev libmpfr-dev ca-certificates libmpc-dev"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | args==0.1.0
attrs==22.2.0
certifi==2021.5.30
clint==0.5.1
flake8==5.0.4
importlib-metadata==4.2.0
iniconfig==1.1.1
line-profiler==4.1.3
mccabe==0.7.0
numpy==1.19.5
packaging==21.3
phe==1.5.0
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pyRserve==1.0.4
pytest==7.0.1
pytest-flake8==1.1.1
scipy==1.5.4
-e git+https://github.com/OpenMined/PySyft.git@6c049ac8c4c2e9598bbd495d9a5fd716d3e46126#egg=syft
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: PySyft
channels:
- defaults
- https://repo.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:
- args==0.1.0
- attrs==22.2.0
- clint==0.5.1
- flake8==5.0.4
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- line-profiler==4.1.3
- mccabe==0.7.0
- numpy==1.19.5
- packaging==21.3
- phe==1.5.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pyrserve==1.0.4
- pytest==7.0.1
- pytest-flake8==1.1.1
- scipy==1.5.4
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/PySyft
| [
"tests/test_tensor.py::scatterTests::testScatter_Numerical0",
"tests/test_tensor.py::scatterTests::testScatter_Numerical1",
"tests/test_tensor.py::scatterTests::testScatter_Numerical2",
"tests/test_tensor.py::scatterTests::testScatter_Numerical3",
"tests/test_tensor.py::scatterTests::testScatter_Numerical4",
"tests/test_tensor.py::scatterTests::testScatter_Numerical5",
"tests/test_tensor.py::scatterTests::testScatter_Numerical6"
]
| []
| [
"tests/test_tensor.py::DimTests::testAsView",
"tests/test_tensor.py::DimTests::testDimOne",
"tests/test_tensor.py::DimTests::testResize",
"tests/test_tensor.py::DimTests::testResizeAs",
"tests/test_tensor.py::DimTests::testSize",
"tests/test_tensor.py::DimTests::testView",
"tests/test_tensor.py::AddTests::testInplace",
"tests/test_tensor.py::AddTests::testScalar",
"tests/test_tensor.py::AddTests::testSimple",
"tests/test_tensor.py::CeilTests::testCeil",
"tests/test_tensor.py::CeilTests::testCeil_",
"tests/test_tensor.py::ZeroTests::testZero",
"tests/test_tensor.py::FloorTests::testFloor_",
"tests/test_tensor.py::SubTests::testInplace",
"tests/test_tensor.py::SubTests::testScalar",
"tests/test_tensor.py::SubTests::testSimple",
"tests/test_tensor.py::MaxTests::testAxis",
"tests/test_tensor.py::MaxTests::testNoDim",
"tests/test_tensor.py::MultTests::testInplace",
"tests/test_tensor.py::MultTests::testScalar",
"tests/test_tensor.py::MultTests::testSimple",
"tests/test_tensor.py::DivTests::testInplace",
"tests/test_tensor.py::DivTests::testScalar",
"tests/test_tensor.py::DivTests::testSimple",
"tests/test_tensor.py::AbsTests::testabs",
"tests/test_tensor.py::AbsTests::testabs_",
"tests/test_tensor.py::ShapeTests::testShape",
"tests/test_tensor.py::SqrtTests::testSqrt",
"tests/test_tensor.py::SqrtTests::testSqrt_",
"tests/test_tensor.py::SumTests::testDimIsNotNoneInt",
"tests/test_tensor.py::SumTests::testDimNoneInt",
"tests/test_tensor.py::EqualTests::testEqOp",
"tests/test_tensor.py::EqualTests::testEqual",
"tests/test_tensor.py::EqualTests::testIneqOp",
"tests/test_tensor.py::EqualTests::testNotEqual",
"tests/test_tensor.py::IndexTests::testIndexing",
"tests/test_tensor.py::sigmoidTests::testSigmoid",
"tests/test_tensor.py::addmm::testaddmm1d",
"tests/test_tensor.py::addmm::testaddmm2d",
"tests/test_tensor.py::addmm::testaddmm_1d",
"tests/test_tensor.py::addmm::testaddmm_2d",
"tests/test_tensor.py::addcmulTests::testaddcmul1d",
"tests/test_tensor.py::addcmulTests::testaddcmul2d",
"tests/test_tensor.py::addcmulTests::testaddcmul_1d",
"tests/test_tensor.py::addcmulTests::testaddcmul_2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_2d",
"tests/test_tensor.py::addmvTests::testaddmv",
"tests/test_tensor.py::addmvTests::testaddmv_",
"tests/test_tensor.py::addbmmTests::testaddbmm",
"tests/test_tensor.py::addbmmTests::testaddbmm_",
"tests/test_tensor.py::baddbmmTests::testbaddbmm",
"tests/test_tensor.py::baddbmmTests::testbaddbmm_",
"tests/test_tensor.py::transposeTests::testT",
"tests/test_tensor.py::transposeTests::testT_",
"tests/test_tensor.py::transposeTests::testTranspose",
"tests/test_tensor.py::transposeTests::testTranspose_",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze_",
"tests/test_tensor.py::expTests::testexp",
"tests/test_tensor.py::expTests::testexp_",
"tests/test_tensor.py::fracTests::testfrac",
"tests/test_tensor.py::fracTests::testfrac_",
"tests/test_tensor.py::rsqrtTests::testrsqrt",
"tests/test_tensor.py::rsqrtTests::testrsqrt_",
"tests/test_tensor.py::signTests::testsign",
"tests/test_tensor.py::signTests::testsign_",
"tests/test_tensor.py::numpyTests::testnumpy",
"tests/test_tensor.py::reciprocalTests::testreciprocal",
"tests/test_tensor.py::reciprocalTests::testrsqrt_",
"tests/test_tensor.py::logTests::testLog",
"tests/test_tensor.py::logTests::testLog1p",
"tests/test_tensor.py::logTests::testLog1p_",
"tests/test_tensor.py::logTests::testLog_",
"tests/test_tensor.py::clampTests::testClampFloat",
"tests/test_tensor.py::clampTests::testClampFloatInPlace",
"tests/test_tensor.py::clampTests::testClampInt",
"tests/test_tensor.py::clampTests::testClampIntInPlace",
"tests/test_tensor.py::cloneTests::testClone",
"tests/test_tensor.py::chunkTests::testChunk",
"tests/test_tensor.py::chunkTests::testChunkSameSize",
"tests/test_tensor.py::bernoulliTests::testBernoulli",
"tests/test_tensor.py::bernoulliTests::testBernoulli_",
"tests/test_tensor.py::uniformTests::testUniform",
"tests/test_tensor.py::uniformTests::testUniform_",
"tests/test_tensor.py::fillTests::testFill_",
"tests/test_tensor.py::topkTests::testTopK",
"tests/test_tensor.py::tolistTests::testToList",
"tests/test_tensor.py::traceTests::testTrace",
"tests/test_tensor.py::roundTests::testRound",
"tests/test_tensor.py::roundTests::testRound_",
"tests/test_tensor.py::repeatTests::testRepeat",
"tests/test_tensor.py::powTests::testPow",
"tests/test_tensor.py::powTests::testPow_",
"tests/test_tensor.py::prodTests::testProd",
"tests/test_tensor.py::randomTests::testRandom_",
"tests/test_tensor.py::nonzeroTests::testNonZero",
"tests/test_tensor.py::cumprodTest::testCumprod",
"tests/test_tensor.py::cumprodTest::testCumprod_",
"tests/test_tensor.py::splitTests::testSplit",
"tests/test_tensor.py::squeezeTests::testSqueeze",
"tests/test_tensor.py::expandAsTests::testExpandAs",
"tests/test_tensor.py::meanTests::testMean",
"tests/test_tensor.py::notEqualTests::testNe",
"tests/test_tensor.py::notEqualTests::testNe_",
"tests/test_tensor.py::scatterTests::testScatter_DimOutOfRange",
"tests/test_tensor.py::scatterTests::testScatter_IndexOutOfRange",
"tests/test_tensor.py::scatterTests::testScatter_IndexType",
"tests/test_tensor.py::scatterTests::testScatter_index_src_dimension_mismatch"
]
| []
| Apache License 2.0 | 1,673 | [
"syft/tensor.py"
]
| [
"syft/tensor.py"
]
|
|
OpenMined__PySyft-233 | 57cb74b0ec8a69c285a002e0a190d4c6603a06bc | 2017-09-13 02:59:10 | 06ce023225dd613d8fb14ab2046135b93ab22376 | diff --git a/syft/tensor.py b/syft/tensor.py
index 765d418508..a016eb8cfa 100644
--- a/syft/tensor.py
+++ b/syft/tensor.py
@@ -1051,9 +1051,8 @@ class TensorBase(object):
def scatter_(self, dim, index, src):
"""
- Writes all values from the Tensor src into self at the indices specified in the index Tensor.
- The indices are specified with respect to the given dimension, dim, in the manner described in gather().
-
+ Writes all values from the Tensor ``src`` into ``self`` at the indices specified in the ``index`` Tensor.
+ The indices are specified with respect to the given dimension, ``dim``, in the manner described in gather().
:param dim: The axis along which to index
:param index: The indices of elements to scatter
:param src: The source element(s) to scatter
@@ -1110,6 +1109,32 @@ class TensorBase(object):
return self
+ def gather(self, dim, index):
+ """
+ Gathers values along an axis specified by ``dim``.
+ For a 3-D tensor the output is specified by:
+ out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0
+ out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1
+ out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2
+ :param dim: The axis along which to index
+ :param index: A tensor of indices of elements to gather
+ :return: tensor of gathered values
+ """
+ index = _ensure_tensorbase(index)
+ if self.encrypted or index.encrypted:
+ return NotImplemented
+ idx_xsection_shape = index.data.shape[:dim] + index.data.shape[dim + 1:]
+ self_xsection_shape = self.data.shape[:dim] + self.data.shape[dim + 1:]
+ if idx_xsection_shape != self_xsection_shape:
+ raise ValueError("Except for dimension " + str(dim) +
+ ", all dimensions of index and self should be the same size")
+ if index.data.dtype != np.dtype('int_'):
+ raise TypeError("The values of index must be integers")
+ data_swaped = np.swapaxes(self.data, 0, dim)
+ index_swaped = np.swapaxes(index, 0, dim)
+ gathered = np.choose(index_swaped, data_swaped)
+ return TensorBase(np.swapaxes(gathered, 0, dim))
+
def serialize(self):
return pickle.dumps(self)
| Implement Default gather Functionality for Base Tensor Type
**User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, gather() should return a new tensor. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation.
**Acceptance Criteria:**
- If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error.
- a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors.
- inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. | OpenMined/PySyft | diff --git a/tests/test_tensor.py b/tests/test_tensor.py
index ce477234fe..fbeb064be6 100644
--- a/tests/test_tensor.py
+++ b/tests/test_tensor.py
@@ -750,6 +750,23 @@ class notEqualTests(unittest.TestCase):
self.assertTrue(syft.equal(t1, TensorBase([1, 1, 1, 0])))
+class gatherTests(unittest.TestCase):
+ def testGatherNumerical1(self):
+ t = TensorBase(np.array([[65, 17], [14, 25], [76, 22]]))
+ idx = TensorBase(np.array([[0], [1], [0]]))
+ dim = 1
+ result = t.gather(dim=dim, index=idx)
+ self.assertTrue(np.array_equal(result.data, np.array([[65], [25], [76]])))
+
+ def testGatherNumerical2(self):
+ t = TensorBase(np.array([[47, 74, 44], [56, 9, 37]]))
+ idx = TensorBase(np.array([[0, 0, 1], [1, 1, 0], [0, 1, 0]]))
+ dim = 0
+ result = t.gather(dim=dim, index=idx)
+ expexted = [[47, 74, 37], [56, 9, 44.], [47, 9, 44]]
+ self.assertTrue(np.array_equal(result.data, np.array(expexted)))
+
+
class scatterTests(unittest.TestCase):
def testScatter_Numerical0(self):
t = TensorBase(np.zeros((3, 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": 0,
"test_score": 0
},
"num_modified_files": 1
} | PySyft/hydrogen | {
"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": [
"line_profiler",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y musl-dev g++ libgmp3-dev libmpfr-dev ca-certificates"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | args==0.1.0
clint==0.5.1
exceptiongroup==1.2.2
flake8==7.2.0
iniconfig==2.1.0
line_profiler==4.2.0
mccabe==0.7.0
numpy==1.26.4
packaging==24.2
phe==1.5.0
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.2
pyRserve==1.0.4
pytest==8.3.5
pytest-flake8==1.3.0
scipy==1.13.1
-e git+https://github.com/OpenMined/PySyft.git@57cb74b0ec8a69c285a002e0a190d4c6603a06bc#egg=syft
tomli==2.2.1
| name: PySyft
channels:
- defaults
- https://repo.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:
- args==0.1.0
- clint==0.5.1
- exceptiongroup==1.2.2
- flake8==7.2.0
- iniconfig==2.1.0
- line-profiler==4.2.0
- mccabe==0.7.0
- numpy==1.26.4
- packaging==24.2
- phe==1.5.0
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.2
- pyrserve==1.0.4
- pytest==8.3.5
- pytest-flake8==1.3.0
- scipy==1.13.1
- tomli==2.2.1
prefix: /opt/conda/envs/PySyft
| [
"tests/test_tensor.py::gatherTests::testGatherNumerical1",
"tests/test_tensor.py::gatherTests::testGatherNumerical2"
]
| [
"tests/test_tensor.py::scatterTests::testScatter_Numerical0",
"tests/test_tensor.py::scatterTests::testScatter_Numerical1",
"tests/test_tensor.py::scatterTests::testScatter_Numerical2",
"tests/test_tensor.py::scatterTests::testScatter_Numerical3",
"tests/test_tensor.py::scatterTests::testScatter_Numerical4",
"tests/test_tensor.py::scatterTests::testScatter_Numerical5",
"tests/test_tensor.py::scatterTests::testScatter_Numerical6"
]
| [
"tests/test_tensor.py::DimTests::testAsView",
"tests/test_tensor.py::DimTests::testDimOne",
"tests/test_tensor.py::DimTests::testResize",
"tests/test_tensor.py::DimTests::testResizeAs",
"tests/test_tensor.py::DimTests::testSize",
"tests/test_tensor.py::DimTests::testView",
"tests/test_tensor.py::AddTests::testInplace",
"tests/test_tensor.py::AddTests::testScalar",
"tests/test_tensor.py::AddTests::testSimple",
"tests/test_tensor.py::CeilTests::testCeil",
"tests/test_tensor.py::CeilTests::testCeil_",
"tests/test_tensor.py::ZeroTests::testZero",
"tests/test_tensor.py::FloorTests::testFloor_",
"tests/test_tensor.py::SubTests::testInplace",
"tests/test_tensor.py::SubTests::testScalar",
"tests/test_tensor.py::SubTests::testSimple",
"tests/test_tensor.py::MaxTests::testAxis",
"tests/test_tensor.py::MaxTests::testNoDim",
"tests/test_tensor.py::MultTests::testInplace",
"tests/test_tensor.py::MultTests::testScalar",
"tests/test_tensor.py::MultTests::testSimple",
"tests/test_tensor.py::DivTests::testInplace",
"tests/test_tensor.py::DivTests::testScalar",
"tests/test_tensor.py::DivTests::testSimple",
"tests/test_tensor.py::AbsTests::testabs",
"tests/test_tensor.py::AbsTests::testabs_",
"tests/test_tensor.py::ShapeTests::testShape",
"tests/test_tensor.py::SqrtTests::testSqrt",
"tests/test_tensor.py::SqrtTests::testSqrt_",
"tests/test_tensor.py::SumTests::testDimIsNotNoneInt",
"tests/test_tensor.py::SumTests::testDimNoneInt",
"tests/test_tensor.py::EqualTests::testEqOp",
"tests/test_tensor.py::EqualTests::testEqual",
"tests/test_tensor.py::EqualTests::testIneqOp",
"tests/test_tensor.py::EqualTests::testNotEqual",
"tests/test_tensor.py::IndexTests::testIndexing",
"tests/test_tensor.py::sigmoidTests::testSigmoid",
"tests/test_tensor.py::addmm::testaddmm1d",
"tests/test_tensor.py::addmm::testaddmm2d",
"tests/test_tensor.py::addmm::testaddmm_1d",
"tests/test_tensor.py::addmm::testaddmm_2d",
"tests/test_tensor.py::addcmulTests::testaddcmul1d",
"tests/test_tensor.py::addcmulTests::testaddcmul2d",
"tests/test_tensor.py::addcmulTests::testaddcmul_1d",
"tests/test_tensor.py::addcmulTests::testaddcmul_2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_2d",
"tests/test_tensor.py::addmvTests::testaddmv",
"tests/test_tensor.py::addmvTests::testaddmv_",
"tests/test_tensor.py::addbmmTests::testaddbmm",
"tests/test_tensor.py::addbmmTests::testaddbmm_",
"tests/test_tensor.py::baddbmmTests::testbaddbmm",
"tests/test_tensor.py::baddbmmTests::testbaddbmm_",
"tests/test_tensor.py::transposeTests::testT",
"tests/test_tensor.py::transposeTests::testT_",
"tests/test_tensor.py::transposeTests::testTranspose",
"tests/test_tensor.py::transposeTests::testTranspose_",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze_",
"tests/test_tensor.py::expTests::testexp",
"tests/test_tensor.py::expTests::testexp_",
"tests/test_tensor.py::fracTests::testfrac",
"tests/test_tensor.py::fracTests::testfrac_",
"tests/test_tensor.py::rsqrtTests::testrsqrt",
"tests/test_tensor.py::rsqrtTests::testrsqrt_",
"tests/test_tensor.py::signTests::testsign",
"tests/test_tensor.py::signTests::testsign_",
"tests/test_tensor.py::numpyTests::testnumpy",
"tests/test_tensor.py::reciprocalTests::testreciprocal",
"tests/test_tensor.py::reciprocalTests::testrsqrt_",
"tests/test_tensor.py::logTests::testLog",
"tests/test_tensor.py::logTests::testLog1p",
"tests/test_tensor.py::logTests::testLog1p_",
"tests/test_tensor.py::logTests::testLog_",
"tests/test_tensor.py::clampTests::testClampFloat",
"tests/test_tensor.py::clampTests::testClampFloatInPlace",
"tests/test_tensor.py::clampTests::testClampInt",
"tests/test_tensor.py::clampTests::testClampIntInPlace",
"tests/test_tensor.py::cloneTests::testClone",
"tests/test_tensor.py::chunkTests::testChunk",
"tests/test_tensor.py::chunkTests::testChunkSameSize",
"tests/test_tensor.py::gtTests::testGtInPlaceWithNumber",
"tests/test_tensor.py::gtTests::testGtInPlaceWithTensor",
"tests/test_tensor.py::gtTests::testGtWithNumber",
"tests/test_tensor.py::gtTests::testGtWithTensor",
"tests/test_tensor.py::bernoulliTests::testBernoulli",
"tests/test_tensor.py::bernoulliTests::testBernoulli_",
"tests/test_tensor.py::uniformTests::testUniform",
"tests/test_tensor.py::uniformTests::testUniform_",
"tests/test_tensor.py::fillTests::testFill_",
"tests/test_tensor.py::topkTests::testTopK",
"tests/test_tensor.py::tolistTests::testToList",
"tests/test_tensor.py::traceTests::testTrace",
"tests/test_tensor.py::roundTests::testRound",
"tests/test_tensor.py::roundTests::testRound_",
"tests/test_tensor.py::repeatTests::testRepeat",
"tests/test_tensor.py::powTests::testPow",
"tests/test_tensor.py::powTests::testPow_",
"tests/test_tensor.py::prodTests::testProd",
"tests/test_tensor.py::randomTests::testRandom_",
"tests/test_tensor.py::nonzeroTests::testNonZero",
"tests/test_tensor.py::cumprodTest::testCumprod",
"tests/test_tensor.py::cumprodTest::testCumprod_",
"tests/test_tensor.py::splitTests::testSplit",
"tests/test_tensor.py::squeezeTests::testSqueeze",
"tests/test_tensor.py::expandAsTests::testExpandAs",
"tests/test_tensor.py::meanTests::testMean",
"tests/test_tensor.py::notEqualTests::testNe",
"tests/test_tensor.py::notEqualTests::testNe_",
"tests/test_tensor.py::scatterTests::testScatter_DimOutOfRange",
"tests/test_tensor.py::scatterTests::testScatter_IndexOutOfRange",
"tests/test_tensor.py::scatterTests::testScatter_IndexType",
"tests/test_tensor.py::scatterTests::testScatter_index_src_dimension_mismatch"
]
| []
| Apache License 2.0 | 1,674 | [
"syft/tensor.py"
]
| [
"syft/tensor.py"
]
|
|
scrapy__scrapy-2923 | b8fabeed8652d22725959345700b9e7d00073de4 | 2017-09-13 08:20:43 | 86c322c3a819405020cd884f128246ae55b6eaeb | diff --git a/docs/topics/media-pipeline.rst b/docs/topics/media-pipeline.rst
index e948913a4..9580a15d9 100644
--- a/docs/topics/media-pipeline.rst
+++ b/docs/topics/media-pipeline.rst
@@ -15,7 +15,8 @@ typically you'll either use the Files Pipeline or the Images Pipeline.
Both pipelines implement these features:
* Avoid re-downloading media that was downloaded recently
-* Specifying where to store the media (filesystem directory, Amazon S3 bucket)
+* Specifying where to store the media (filesystem directory, Amazon S3 bucket,
+ Google Cloud Storage bucket)
The Images Pipeline has a few extra functions for processing images:
@@ -116,10 +117,11 @@ For the Images Pipeline, set the :setting:`IMAGES_STORE` setting::
Supported Storage
=================
-File system is currently the only officially supported storage, but there is
-also support for storing files in `Amazon S3`_.
+File system is currently the only officially supported storage, but there are
+also support for storing files in `Amazon S3`_ and `Google Cloud Storage`_.
.. _Amazon S3: https://aws.amazon.com/s3/
+.. _Google Cloud Storage: https://cloud.google.com/storage/
File system storage
-------------------
@@ -171,6 +173,25 @@ For more information, see `canned ACLs`_ in the Amazon S3 Developer Guide.
.. _canned ACLs: http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl
+Google Cloud Storage
+---------------------
+
+.. setting:: GCS_PROJECT_ID
+
+:setting:`FILES_STORE` and :setting:`IMAGES_STORE` can represent a Google Cloud Storage
+bucket. Scrapy will automatically upload the files to the bucket. (requires `google-cloud-storage`_ )
+
+.. _google-cloud-storage: https://cloud.google.com/storage/docs/reference/libraries#client-libraries-install-python
+
+For example, these are valid :setting:`IMAGES_STORE` and :setting:`GCS_PROJECT_ID` settings::
+
+ IMAGES_STORE = 'gs://bucket/images/'
+ GCS_PROJECT_ID = 'project_id'
+
+For information about authentication, see this `documentation`_.
+
+.. _documentation: https://cloud.google.com/docs/authentication/production
+
Usage example
=============
diff --git a/scrapy/pipelines/files.py b/scrapy/pipelines/files.py
index eae03752a..7fdb8a086 100644
--- a/scrapy/pipelines/files.py
+++ b/scrapy/pipelines/files.py
@@ -194,6 +194,47 @@ class S3FilesStore(object):
return extra
+class GCSFilesStore(object):
+
+ GCS_PROJECT_ID = None
+
+ CACHE_CONTROL = 'max-age=172800'
+
+ def __init__(self, uri):
+ from google.cloud import storage
+ client = storage.Client(project=self.GCS_PROJECT_ID)
+ bucket, prefix = uri[5:].split('/', 1)
+ self.bucket = client.bucket(bucket)
+ self.prefix = prefix
+
+ def stat_file(self, path, info):
+ def _onsuccess(blob):
+ if blob:
+ checksum = blob.md5_hash
+ last_modified = time.mktime(blob.updated.timetuple())
+ return {'checksum': checksum, 'last_modified': last_modified}
+ else:
+ return {}
+
+ return threads.deferToThread(self.bucket.get_blob, path).addCallback(_onsuccess)
+
+ def _get_content_type(self, headers):
+ if headers and 'Content-Type' in headers:
+ return headers['Content-Type']
+ else:
+ return 'application/octet-stream'
+
+ def persist_file(self, path, buf, info, meta=None, headers=None):
+ blob = self.bucket.blob(self.prefix + path)
+ blob.cache_control = self.CACHE_CONTROL
+ blob.metadata = {k: str(v) for k, v in six.iteritems(meta or {})}
+ return threads.deferToThread(
+ blob.upload_from_string,
+ data=buf.getvalue(),
+ content_type=self._get_content_type(headers)
+ )
+
+
class FilesPipeline(MediaPipeline):
"""Abstract pipeline that implement the file downloading
@@ -219,6 +260,7 @@ class FilesPipeline(MediaPipeline):
'': FSFilesStore,
'file': FSFilesStore,
's3': S3FilesStore,
+ 'gs': GCSFilesStore,
}
DEFAULT_FILES_URLS_FIELD = 'file_urls'
DEFAULT_FILES_RESULT_FIELD = 'files'
@@ -258,6 +300,9 @@ class FilesPipeline(MediaPipeline):
s3store.AWS_SECRET_ACCESS_KEY = settings['AWS_SECRET_ACCESS_KEY']
s3store.POLICY = settings['FILES_STORE_S3_ACL']
+ gcs_store = cls.STORE_SCHEMES['gs']
+ gcs_store.GCS_PROJECT_ID = settings['GCS_PROJECT_ID']
+
store_uri = settings['FILES_STORE']
return cls(store_uri, settings=settings)
diff --git a/scrapy/pipelines/images.py b/scrapy/pipelines/images.py
index bc449431f..c5fc12afe 100644
--- a/scrapy/pipelines/images.py
+++ b/scrapy/pipelines/images.py
@@ -91,6 +91,9 @@ class ImagesPipeline(FilesPipeline):
s3store.AWS_SECRET_ACCESS_KEY = settings['AWS_SECRET_ACCESS_KEY']
s3store.POLICY = settings['IMAGES_STORE_S3_ACL']
+ gcs_store = cls.STORE_SCHEMES['gs']
+ gcs_store.GCS_PROJECT_ID = settings['GCS_PROJECT_ID']
+
store_uri = settings['IMAGES_STORE']
return cls(store_uri, settings=settings)
diff --git a/tox.ini b/tox.ini
index c7e1e43c9..0608693ba 100644
--- a/tox.ini
+++ b/tox.ini
@@ -11,6 +11,7 @@ deps =
-rrequirements.txt
# Extras
botocore
+ google-cloud-storage
Pillow != 3.0.0
leveldb
-rtests/requirements.txt
@@ -18,6 +19,8 @@ passenv =
S3_TEST_FILE_URI
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
+ GCS_TEST_FILE_URI
+ GCS_PROJECT_ID
commands =
py.test --cov=scrapy --cov-report= {posargs:scrapy tests}
| Google Cloud Storage Support (Storage backends)
Does it make sense to support [Google Cloud Storage](https://cloud.google.com/products/cloud-storage/) as storage backend? Boto already supports Cloud storage: http://boto.readthedocs.org/en/latest/ref/gs.html
| scrapy/scrapy | diff --git a/scrapy/utils/test.py b/scrapy/utils/test.py
index d2ef68912..60b931f48 100644
--- a/scrapy/utils/test.py
+++ b/scrapy/utils/test.py
@@ -20,6 +20,12 @@ def assert_aws_environ():
if 'AWS_ACCESS_KEY_ID' not in os.environ:
raise SkipTest("AWS keys not found")
+
+def assert_gcs_environ():
+ if 'GCS_PROJECT_ID' not in os.environ:
+ raise SkipTest("GCS_PROJECT_ID not found")
+
+
def skip_if_no_boto():
try:
is_botocore()
@@ -45,6 +51,15 @@ def get_s3_content_and_delete(bucket, path, with_key=False):
bucket.delete_key(path)
return (content, key) if with_key else content
+def get_gcs_content_and_delete(bucket, path):
+ from google.cloud import storage
+ client = storage.Client(project=os.environ.get('GCS_PROJECT_ID'))
+ bucket = client.get_bucket(bucket)
+ blob = bucket.get_blob(path)
+ content = blob.download_as_string()
+ bucket.delete_blob(path)
+ return content, blob
+
def get_crawler(spidercls=None, settings_dict=None):
"""Return an unconfigured Crawler object. If settings_dict is given, it
will be used to populate the crawler settings with a project level
diff --git a/tests/test_pipeline_files.py b/tests/test_pipeline_files.py
index e3ec04b8d..c761bd606 100644
--- a/tests/test_pipeline_files.py
+++ b/tests/test_pipeline_files.py
@@ -11,12 +11,13 @@ from six import BytesIO
from twisted.trial import unittest
from twisted.internet import defer
-from scrapy.pipelines.files import FilesPipeline, FSFilesStore, S3FilesStore
+from scrapy.pipelines.files import FilesPipeline, FSFilesStore, S3FilesStore, GCSFilesStore
from scrapy.item import Item, Field
from scrapy.http import Request, Response
from scrapy.settings import Settings
from scrapy.utils.python import to_bytes
from scrapy.utils.test import assert_aws_environ, get_s3_content_and_delete
+from scrapy.utils.test import assert_gcs_environ, get_gcs_content_and_delete
from scrapy.utils.boto import is_botocore
from tests import mock
@@ -375,6 +376,31 @@ class TestS3FilesStore(unittest.TestCase):
self.assertEqual(key.content_type, 'image/png')
+class TestGCSFilesStore(unittest.TestCase):
+ @defer.inlineCallbacks
+ def test_persist(self):
+ assert_gcs_environ()
+ uri = os.environ.get('GCS_TEST_FILE_URI')
+ if not uri:
+ raise unittest.SkipTest("No GCS URI available for testing")
+ data = b"TestGCSFilesStore: \xe2\x98\x83"
+ buf = BytesIO(data)
+ meta = {'foo': 'bar'}
+ path = 'full/filename'
+ store = GCSFilesStore(uri)
+ yield store.persist_file(path, buf, info=None, meta=meta, headers=None)
+ s = yield store.stat_file(path, info=None)
+ self.assertIn('last_modified', s)
+ self.assertIn('checksum', s)
+ self.assertEqual(s['checksum'], 'zc2oVgXkbQr2EQdSdw3OPA==')
+ u = urlparse(uri)
+ content, blob = get_gcs_content_and_delete(u.hostname, u.path[1:]+path)
+ self.assertEqual(content, data)
+ self.assertEqual(blob.metadata, {'foo': 'bar'})
+ self.assertEqual(blob.cache_control, GCSFilesStore.CACHE_CONTROL)
+ self.assertEqual(blob.content_type, 'application/octet-stream')
+
+
class ItemWithFiles(Item):
file_urls = Field()
files = Field()
| {
"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": 3,
"issue_text_score": 2,
"test_score": 2
},
"num_modified_files": 4
} | 1.4 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"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"
} | attrs==25.3.0
Automat==24.8.1
cffi==1.17.1
constantly==23.10.4
cryptography==44.0.2
cssselect==1.3.0
exceptiongroup==1.2.2
hyperlink==21.0.0
idna==3.10
incremental==24.7.2
iniconfig==2.1.0
jmespath==1.0.1
lxml==5.3.1
packaging==24.2
parsel==1.10.0
pluggy==1.5.0
pyasn1==0.6.1
pyasn1_modules==0.4.2
pycparser==2.22
PyDispatcher==2.0.7
pyOpenSSL==25.0.0
pytest==8.3.5
queuelib==1.7.0
-e git+https://github.com/scrapy/scrapy.git@b8fabeed8652d22725959345700b9e7d00073de4#egg=Scrapy
service-identity==24.2.0
six==1.17.0
tomli==2.2.1
Twisted==24.11.0
typing_extensions==4.13.0
w3lib==2.3.1
zope.interface==7.2
| name: scrapy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==25.3.0
- automat==24.8.1
- cffi==1.17.1
- constantly==23.10.4
- cryptography==44.0.2
- cssselect==1.3.0
- exceptiongroup==1.2.2
- hyperlink==21.0.0
- idna==3.10
- incremental==24.7.2
- iniconfig==2.1.0
- jmespath==1.0.1
- lxml==5.3.1
- packaging==24.2
- parsel==1.10.0
- pluggy==1.5.0
- pyasn1==0.6.1
- pyasn1-modules==0.4.2
- pycparser==2.22
- pydispatcher==2.0.7
- pyopenssl==25.0.0
- pytest==8.3.5
- queuelib==1.7.0
- service-identity==24.2.0
- six==1.17.0
- tomli==2.2.1
- twisted==24.11.0
- typing-extensions==4.13.0
- w3lib==2.3.1
- zope-interface==7.2
prefix: /opt/conda/envs/scrapy
| [
"tests/test_pipeline_files.py::FilesPipelineTestCase::test_file_expired",
"tests/test_pipeline_files.py::FilesPipelineTestCase::test_file_not_expired",
"tests/test_pipeline_files.py::FilesPipelineTestCase::test_file_path",
"tests/test_pipeline_files.py::FilesPipelineTestCase::test_fs_store",
"tests/test_pipeline_files.py::DeprecatedFilesPipelineTestCase::test_default_file_key_method",
"tests/test_pipeline_files.py::DeprecatedFilesPipelineTestCase::test_overridden_file_key_method",
"tests/test_pipeline_files.py::FilesPipelineTestCaseCustomSettings::test_cls_attrs_with_DEFAULT_prefix",
"tests/test_pipeline_files.py::FilesPipelineTestCaseCustomSettings::test_custom_settings_and_class_attrs_for_subclasses",
"tests/test_pipeline_files.py::FilesPipelineTestCaseCustomSettings::test_custom_settings_for_subclasses",
"tests/test_pipeline_files.py::FilesPipelineTestCaseCustomSettings::test_different_settings_for_different_instances",
"tests/test_pipeline_files.py::FilesPipelineTestCaseCustomSettings::test_no_custom_settings_for_subclasses",
"tests/test_pipeline_files.py::FilesPipelineTestCaseCustomSettings::test_subclass_attributes_preserved_if_no_settings",
"tests/test_pipeline_files.py::FilesPipelineTestCaseCustomSettings::test_subclass_attrs_preserved_custom_settings",
"tests/test_pipeline_files.py::FilesPipelineTestCaseCustomSettings::test_user_defined_subclass_default_key_names",
"tests/test_pipeline_files.py::TestS3FilesStore::test_persist"
]
| [
"tests/test_pipeline_files.py::FilesPipelineTestCaseFields::test_item_fields_default",
"tests/test_pipeline_files.py::FilesPipelineTestCaseFields::test_item_fields_override_settings"
]
| []
| []
| BSD 3-Clause "New" or "Revised" License | 1,675 | [
"docs/topics/media-pipeline.rst",
"scrapy/pipelines/files.py",
"tox.ini",
"scrapy/pipelines/images.py"
]
| [
"docs/topics/media-pipeline.rst",
"scrapy/pipelines/files.py",
"tox.ini",
"scrapy/pipelines/images.py"
]
|
|
opsdroid__opsdroid-225 | b67d32310da842dddddb9b907f731a03d0562a2f | 2017-09-13 19:56:13 | b67d32310da842dddddb9b907f731a03d0562a2f | coveralls:
[](https://coveralls.io/builds/13259107)
Coverage decreased (-0.4%) to 95.253% when pulling **5231408d02b3e69aa963d1702af1a18cfdbfbe24 on jacobtomlinson:env-var-config** into **b67d32310da842dddddb9b907f731a03d0562a2f on opsdroid:master**.
coveralls:
[](https://coveralls.io/builds/13259374)
Coverage decreased (-0.4%) to 95.253% when pulling **f1c3e2f87b7f8c3cb565f8d4054662747b861f47 on jacobtomlinson:env-var-config** into **b67d32310da842dddddb9b907f731a03d0562a2f on opsdroid:master**.
coveralls:
[](https://coveralls.io/builds/13259976)
Coverage increased (+0.05%) to 95.712% when pulling **4d1c90850d0a42784b4c11c25a97cd7792510ec2 on jacobtomlinson:env-var-config** into **b67d32310da842dddddb9b907f731a03d0562a2f on opsdroid:master**.
| diff --git a/docs/configuration-reference.md b/docs/configuration-reference.md
index 2370bf9..cefea9c 100644
--- a/docs/configuration-reference.md
+++ b/docs/configuration-reference.md
@@ -176,3 +176,15 @@ databases:
repo: https://github.com/username/mymongofork.git
no-cache: true
```
+
+## Environment variables
+
+You can use environment variables in your config. You need to specify the variable in the place of a value.
+
+```yaml
+skills:
+ - name: myawesomeskill
+ somekey: $ENVIRONMENT_VARIABLE
+```
+
+_Note: Your environment variable names must consist of uppercase characters and underscores only. The value must also be just the environment variable, you cannot currently mix env vars inside strings._
\ No newline at end of file
diff --git a/opsdroid/loader.py b/opsdroid/loader.py
index 055b499..73ec3c5 100644
--- a/opsdroid/loader.py
+++ b/opsdroid/loader.py
@@ -6,6 +6,7 @@ import sys
import shutil
import subprocess
import importlib
+import re
import yaml
from opsdroid.const import (
DEFAULT_GIT_URL, MODULES_DIRECTORY, DEFAULT_MODULES_PATH,
@@ -135,6 +136,17 @@ class Loader:
_LOGGER.info("No configuration files found.")
config_path = self.create_default_config(DEFAULT_CONFIG_PATH)
+ env_var_pattern = re.compile(r'^\$([A-Z_]*)$')
+ yaml.add_implicit_resolver("!envvar", env_var_pattern)
+
+ def envvar_constructor(loader, node):
+ """Yaml parser for env vars."""
+ value = loader.construct_scalar(node)
+ [env_var] = env_var_pattern.match(value).groups()
+ return os.environ[env_var]
+
+ yaml.add_constructor('!envvar', envvar_constructor)
+
try:
with open(config_path, 'r') as stream:
_LOGGER.info("Loaded config from %s", config_path)
| Allow usage of env vars in config
The configuration should be parsed for environment variables when loaded. This would allow for secrets like api keys to be kept outside of the opsdroid configuration.
#### Example
```yaml
connectors:
- name: slack
default-room: '#general'
bot-name: "opsdroid"
icon-emoji: ":robot:"
api-token: "$SLACK_API_KEY"
```
In this example `$SLACK_API_KEY` would be replaced with the contents of the environment variable of the same name. | opsdroid/opsdroid | diff --git a/tests/configs/minimal_with_envs.yaml b/tests/configs/minimal_with_envs.yaml
new file mode 100644
index 0000000..ce97849
--- /dev/null
+++ b/tests/configs/minimal_with_envs.yaml
@@ -0,0 +1,1 @@
+test: $ENVVAR
\ No newline at end of file
diff --git a/tests/test_loader.py b/tests/test_loader.py
index ae78a18..fcb2fbc 100644
--- a/tests/test_loader.py
+++ b/tests/test_loader.py
@@ -29,6 +29,13 @@ class TestLoader(unittest.TestCase):
config = loader.load_config_file(["tests/configs/minimal.yaml"])
self.assertIsNotNone(config)
+ def test_load_config_file_with_env_vars(self):
+ opsdroid, loader = self.setup()
+ os.environ["ENVVAR"] = 'test'
+ config = loader.load_config_file(
+ ["tests/configs/minimal_with_envs.yaml"])
+ self.assertEqual(config["test"], os.environ["ENVVAR"])
+
def test_create_default_config(self):
test_config_path = "/tmp/test_config_path/configuration.yaml"
opsdroid, loader = self.setup()
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 0,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
} | 0.8 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist"
],
"pre_install": [
"apt-get update",
"apt-get install -y git"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aiohttp==2.1.0
arrow==0.10.0
async-timeout==4.0.2
attrs==22.2.0
certifi==2021.5.30
chardet==5.0.0
coverage==6.2
execnet==1.9.0
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
multidict==5.2.0
-e git+https://github.com/opsdroid/opsdroid.git@b67d32310da842dddddb9b907f731a03d0562a2f#egg=opsdroid
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycron==0.40
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
pytest-xdist==3.0.2
python-dateutil==2.9.0.post0
PyYAML==3.12
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
yarl==0.10.3
zipp==3.6.0
| name: opsdroid
channels:
- defaults
- https://repo.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:
- aiohttp==2.1.0
- arrow==0.10.0
- async-timeout==4.0.2
- attrs==22.2.0
- chardet==5.0.0
- coverage==6.2
- execnet==1.9.0
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- multidict==5.2.0
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycron==0.40
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-cov==4.0.0
- pytest-xdist==3.0.2
- python-dateutil==2.9.0.post0
- pyyaml==3.12
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- yarl==0.10.3
- zipp==3.6.0
prefix: /opt/conda/envs/opsdroid
| [
"tests/test_loader.py::TestLoader::test_load_config_file_with_env_vars"
]
| []
| [
"tests/test_loader.py::TestLoader::test_build_module_path",
"tests/test_loader.py::TestLoader::test_check_cache_leaves",
"tests/test_loader.py::TestLoader::test_check_cache_removes_dir",
"tests/test_loader.py::TestLoader::test_check_cache_removes_file",
"tests/test_loader.py::TestLoader::test_create_default_config",
"tests/test_loader.py::TestLoader::test_generate_config_if_none_exist",
"tests/test_loader.py::TestLoader::test_git_clone",
"tests/test_loader.py::TestLoader::test_import_module",
"tests/test_loader.py::TestLoader::test_import_module_failure",
"tests/test_loader.py::TestLoader::test_import_module_new",
"tests/test_loader.py::TestLoader::test_install_default_remote_module",
"tests/test_loader.py::TestLoader::test_install_existing_module",
"tests/test_loader.py::TestLoader::test_install_local_module_dir",
"tests/test_loader.py::TestLoader::test_install_local_module_failure",
"tests/test_loader.py::TestLoader::test_install_local_module_file",
"tests/test_loader.py::TestLoader::test_install_missing_local_module",
"tests/test_loader.py::TestLoader::test_install_specific_local_git_module",
"tests/test_loader.py::TestLoader::test_install_specific_local_path_module",
"tests/test_loader.py::TestLoader::test_install_specific_remote_module",
"tests/test_loader.py::TestLoader::test_load_broken_config_file",
"tests/test_loader.py::TestLoader::test_load_config",
"tests/test_loader.py::TestLoader::test_load_config_file",
"tests/test_loader.py::TestLoader::test_load_empty_config",
"tests/test_loader.py::TestLoader::test_load_modules",
"tests/test_loader.py::TestLoader::test_load_non_existant_config_file",
"tests/test_loader.py::TestLoader::test_pip_install_deps",
"tests/test_loader.py::TestLoader::test_reload_modules"
]
| []
| Apache License 2.0 | 1,676 | [
"docs/configuration-reference.md",
"opsdroid/loader.py"
]
| [
"docs/configuration-reference.md",
"opsdroid/loader.py"
]
|
OpenMined__PySyft-237 | 1df96853cc9f1e97f7b106eae3de5a6f62284809 | 2017-09-13 22:12:37 | 06ce023225dd613d8fb14ab2046135b93ab22376 | diff --git a/syft/tensor.py b/syft/tensor.py
index 8ed5efad8d..6cf00090e3 100644
--- a/syft/tensor.py
+++ b/syft/tensor.py
@@ -1160,6 +1160,22 @@ class TensorBase(object):
def deserialize(b):
return pickle.loads(b)
+ def index_select(self, dim, index):
+ """
+ Returns a new Tensor which indexes the ``input`` Tensor along
+ dimension ``dim`` using the entries in ``index``.
+
+ :param dim: dimension in which to index
+ :param index: 1D tensor containing the indices to index
+ :return: Tensor of selected indices
+ """
+ index = _ensure_tensorbase(index)
+ if self.encrypted or index.encrypted:
+ return NotImplemented
+ if index.data.ndim > 1:
+ raise ValueError("Index is supposed to be 1D")
+ return TensorBase(self.data.take(index, axis=dim))
+
def mv(self, tensorvector):
if self.encrypted:
raise NotImplemented
| Implement Default select Functionality for Base Tensor Type
**User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, select() should return a new tensor. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation.
**Acceptance Criteria:**
- If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error.
- a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors.
- inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. | OpenMined/PySyft | diff --git a/tests/test_tensor.py b/tests/test_tensor.py
index f876fdf5ef..365a9e96dc 100644
--- a/tests/test_tensor.py
+++ b/tests/test_tensor.py
@@ -751,6 +751,16 @@ class notEqualTests(unittest.TestCase):
self.assertTrue(syft.equal(t1, TensorBase([1, 1, 1, 0])))
+class index_selectTests(unittest.TestCase):
+ def testIndex_select(self):
+ t = TensorBase(np.reshape(np.arange(0, 2 * 3 * 4), (2, 3, 4)))
+ idx = np.array([1, 0])
+ dim = 2
+ result = t.index_select(dim=dim, index=idx)
+ expected = np.array([[[1, 0], [5, 4], [9, 8]], [[13, 12], [17, 16], [21, 20]]])
+ self.assertTrue(np.array_equal(result.data, expected))
+
+
class gatherTests(unittest.TestCase):
def testGatherNumerical1(self):
t = TensorBase(np.array([[65, 17], [14, 25], [76, 22]]))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 1
} | PySyft/hydrogen | {
"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": [
"line_profiler",
"pytest",
"pytest-flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y musl-dev g++ libgmp3-dev libmpfr-dev ca-certificates libmpc-dev"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | args==0.1.0
clint==0.5.1
exceptiongroup==1.2.2
flake8==7.2.0
iniconfig==2.1.0
line_profiler==4.2.0
mccabe==0.7.0
numpy==1.26.4
packaging==24.2
phe==1.5.0
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.1
pyRserve==1.0.4
pytest==8.3.5
pytest-flake8==1.3.0
scipy==1.13.1
-e git+https://github.com/OpenMined/PySyft.git@1df96853cc9f1e97f7b106eae3de5a6f62284809#egg=syft
tomli==2.2.1
| name: PySyft
channels:
- defaults
- https://repo.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:
- args==0.1.0
- clint==0.5.1
- exceptiongroup==1.2.2
- flake8==7.2.0
- iniconfig==2.1.0
- line-profiler==4.2.0
- mccabe==0.7.0
- numpy==1.26.4
- packaging==24.2
- phe==1.5.0
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.1
- pyrserve==1.0.4
- pytest==8.3.5
- pytest-flake8==1.3.0
- scipy==1.13.1
- tomli==2.2.1
prefix: /opt/conda/envs/PySyft
| [
"tests/test_tensor.py::index_selectTests::testIndex_select"
]
| [
"tests/test_tensor.py::scatterTests::testScatter_Numerical0",
"tests/test_tensor.py::scatterTests::testScatter_Numerical1",
"tests/test_tensor.py::scatterTests::testScatter_Numerical2",
"tests/test_tensor.py::scatterTests::testScatter_Numerical3",
"tests/test_tensor.py::scatterTests::testScatter_Numerical4",
"tests/test_tensor.py::scatterTests::testScatter_Numerical5",
"tests/test_tensor.py::scatterTests::testScatter_Numerical6"
]
| [
"tests/test_tensor.py::DimTests::testAsView",
"tests/test_tensor.py::DimTests::testDimOne",
"tests/test_tensor.py::DimTests::testResize",
"tests/test_tensor.py::DimTests::testResizeAs",
"tests/test_tensor.py::DimTests::testSize",
"tests/test_tensor.py::DimTests::testView",
"tests/test_tensor.py::AddTests::testInplace",
"tests/test_tensor.py::AddTests::testScalar",
"tests/test_tensor.py::AddTests::testSimple",
"tests/test_tensor.py::CeilTests::testCeil",
"tests/test_tensor.py::CeilTests::testCeil_",
"tests/test_tensor.py::ZeroTests::testZero",
"tests/test_tensor.py::FloorTests::testFloor_",
"tests/test_tensor.py::SubTests::testInplace",
"tests/test_tensor.py::SubTests::testScalar",
"tests/test_tensor.py::SubTests::testSimple",
"tests/test_tensor.py::MaxTests::testAxis",
"tests/test_tensor.py::MaxTests::testNoDim",
"tests/test_tensor.py::MultTests::testInplace",
"tests/test_tensor.py::MultTests::testScalar",
"tests/test_tensor.py::MultTests::testSimple",
"tests/test_tensor.py::DivTests::testInplace",
"tests/test_tensor.py::DivTests::testScalar",
"tests/test_tensor.py::DivTests::testSimple",
"tests/test_tensor.py::AbsTests::testabs",
"tests/test_tensor.py::AbsTests::testabs_",
"tests/test_tensor.py::ShapeTests::testShape",
"tests/test_tensor.py::SqrtTests::testSqrt",
"tests/test_tensor.py::SqrtTests::testSqrt_",
"tests/test_tensor.py::SumTests::testDimIsNotNoneInt",
"tests/test_tensor.py::SumTests::testDimNoneInt",
"tests/test_tensor.py::EqualTests::testEqOp",
"tests/test_tensor.py::EqualTests::testEqual",
"tests/test_tensor.py::EqualTests::testIneqOp",
"tests/test_tensor.py::EqualTests::testNotEqual",
"tests/test_tensor.py::IndexTests::testIndexing",
"tests/test_tensor.py::sigmoidTests::testSigmoid",
"tests/test_tensor.py::addmm::testaddmm1d",
"tests/test_tensor.py::addmm::testaddmm2d",
"tests/test_tensor.py::addmm::testaddmm_1d",
"tests/test_tensor.py::addmm::testaddmm_2d",
"tests/test_tensor.py::addcmulTests::testaddcmul1d",
"tests/test_tensor.py::addcmulTests::testaddcmul2d",
"tests/test_tensor.py::addcmulTests::testaddcmul_1d",
"tests/test_tensor.py::addcmulTests::testaddcmul_2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_2d",
"tests/test_tensor.py::addmvTests::testaddmv",
"tests/test_tensor.py::addmvTests::testaddmv_",
"tests/test_tensor.py::addbmmTests::testaddbmm",
"tests/test_tensor.py::addbmmTests::testaddbmm_",
"tests/test_tensor.py::baddbmmTests::testbaddbmm",
"tests/test_tensor.py::baddbmmTests::testbaddbmm_",
"tests/test_tensor.py::transposeTests::testT",
"tests/test_tensor.py::transposeTests::testT_",
"tests/test_tensor.py::transposeTests::testTranspose",
"tests/test_tensor.py::transposeTests::testTranspose_",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze_",
"tests/test_tensor.py::expTests::testexp",
"tests/test_tensor.py::expTests::testexp_",
"tests/test_tensor.py::fracTests::testfrac",
"tests/test_tensor.py::fracTests::testfrac_",
"tests/test_tensor.py::rsqrtTests::testrsqrt",
"tests/test_tensor.py::rsqrtTests::testrsqrt_",
"tests/test_tensor.py::signTests::testsign",
"tests/test_tensor.py::signTests::testsign_",
"tests/test_tensor.py::numpyTests::testnumpy",
"tests/test_tensor.py::reciprocalTests::testreciprocal",
"tests/test_tensor.py::reciprocalTests::testrsqrt_",
"tests/test_tensor.py::logTests::testLog",
"tests/test_tensor.py::logTests::testLog1p",
"tests/test_tensor.py::logTests::testLog1p_",
"tests/test_tensor.py::logTests::testLog_",
"tests/test_tensor.py::clampTests::testClampFloat",
"tests/test_tensor.py::clampTests::testClampFloatInPlace",
"tests/test_tensor.py::clampTests::testClampInt",
"tests/test_tensor.py::clampTests::testClampIntInPlace",
"tests/test_tensor.py::cloneTests::testClone",
"tests/test_tensor.py::chunkTests::testChunk",
"tests/test_tensor.py::chunkTests::testChunkSameSize",
"tests/test_tensor.py::gtTests::testGtInPlaceWithNumber",
"tests/test_tensor.py::gtTests::testGtInPlaceWithTensor",
"tests/test_tensor.py::gtTests::testGtWithNumber",
"tests/test_tensor.py::gtTests::testGtWithTensor",
"tests/test_tensor.py::bernoulliTests::testBernoulli",
"tests/test_tensor.py::bernoulliTests::testBernoulli_",
"tests/test_tensor.py::uniformTests::testUniform",
"tests/test_tensor.py::uniformTests::testUniform_",
"tests/test_tensor.py::fillTests::testFill_",
"tests/test_tensor.py::topkTests::testTopK",
"tests/test_tensor.py::tolistTests::testToList",
"tests/test_tensor.py::traceTests::testTrace",
"tests/test_tensor.py::roundTests::testRound",
"tests/test_tensor.py::roundTests::testRound_",
"tests/test_tensor.py::repeatTests::testRepeat",
"tests/test_tensor.py::powTests::testPow",
"tests/test_tensor.py::powTests::testPow_",
"tests/test_tensor.py::prodTests::testProd",
"tests/test_tensor.py::randomTests::testRandom_",
"tests/test_tensor.py::nonzeroTests::testNonZero",
"tests/test_tensor.py::cumprodTest::testCumprod",
"tests/test_tensor.py::cumprodTest::testCumprod_",
"tests/test_tensor.py::splitTests::testSplit",
"tests/test_tensor.py::squeezeTests::testSqueeze",
"tests/test_tensor.py::expandAsTests::testExpandAs",
"tests/test_tensor.py::meanTests::testMean",
"tests/test_tensor.py::notEqualTests::testNe",
"tests/test_tensor.py::notEqualTests::testNe_",
"tests/test_tensor.py::gatherTests::testGatherNumerical1",
"tests/test_tensor.py::gatherTests::testGatherNumerical2",
"tests/test_tensor.py::scatterTests::testScatter_DimOutOfRange",
"tests/test_tensor.py::scatterTests::testScatter_IndexOutOfRange",
"tests/test_tensor.py::scatterTests::testScatter_IndexType",
"tests/test_tensor.py::scatterTests::testScatter_index_src_dimension_mismatch"
]
| []
| Apache License 2.0 | 1,677 | [
"syft/tensor.py"
]
| [
"syft/tensor.py"
]
|
|
ucfopen__canvasapi-76 | 7eb0ec8ec2d8b9c5b6036edb3a93014b241c4fe6 | 2017-09-15 17:55:20 | f2faa1835e104aae764a1fc7638c284d2888639f | diff --git a/canvasapi/course.py b/canvasapi/course.py
index 8cd5329..7b87e2d 100644
--- a/canvasapi/course.py
+++ b/canvasapi/course.py
@@ -1,4 +1,5 @@
from __future__ import absolute_import, division, print_function, unicode_literals
+from warnings import warn
from six import python_2_unicode_compatible
@@ -1134,12 +1135,15 @@ class Course(CanvasObject):
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.submission.Submission`
"""
+ if 'grouped' in kwargs:
+ warn('The `grouped` parameter must be empty. Removing kwarg `grouped`.')
+ del kwargs['grouped']
+
return PaginatedList(
Submission,
self._requester,
'GET',
'courses/%s/students/submissions' % (self.id),
- grouped=False,
_kwargs=combine_kwargs(**kwargs)
)
diff --git a/canvasapi/section.py b/canvasapi/section.py
index 5d74533..f9f86ca 100644
--- a/canvasapi/section.py
+++ b/canvasapi/section.py
@@ -1,4 +1,5 @@
from __future__ import absolute_import, division, print_function, unicode_literals
+from warnings import warn
from six import python_2_unicode_compatible
@@ -157,12 +158,15 @@ class Section(CanvasObject):
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.submission.Submission`
"""
+ if 'grouped' in kwargs:
+ warn('The `grouped` parameter must be empty. Removing kwarg `grouped`.')
+ del kwargs['grouped']
+
return PaginatedList(
Submission,
self._requester,
'GET',
'sections/%s/students/submissions' % (self.id),
- grouped=False,
_kwargs=combine_kwargs(**kwargs)
)
| Course.list_multiple_submissions mismanages grouped response
The `Course.list_multiple_submissions` method returns a paginated list of `Submission` instances. However, printing any of these instances using its default string conversion fails:
```python
submissions = course.list_multiple_submissions(student_ids='all', assignment_ids=(123, 456))
for submission in submissions:
print(submission)
```
> `AttributeError: 'Submission' object has no attribute 'id'`
If instead I print each submission’s `__class__` and attribute dictionary, I see something rather strange. The class is indeed `canvasapi.submission.Submission`. However, the attributes are not those that a `Submission` should have. Ignoring the double-underscore internal attributes, each `submission` instance has:
- `_requester`
- `attributes`
- `integration_id`
- `section_id`
- `set_attributes`
- `sis_user_id`
- `submissions`
- `to_json`
- `user_id`
The `sis_user_id` and `user_id` attributes tell me that this is some sort of person-identifying structure along the lines of a `User` or `Enrollment` object. But it does not have the complete set of attributes for either of those. The value of the `submissions` attribute is a list of dicts; I believe that each of these dicts corresponds to one `Submission` object.
The `Course.list_multiple_submissions` method produces a `GET /api/v1/courses/:course_id/students/submissions` request, and [the documentation for that request](https://canvas.instructure.com/doc/api/submissions.html#method.submissions_api.for_students) shows that its response can take one of two forms depending on the `grouped` parameter. I can see that the `Course.list_multiple_submissions` implementation always hard-codes `grouped=False`, but the response coming back looks exactly like the Canvas API documentation example of a *grouped* response, complete with those `submissions` attributes giving lists of `Submission` objects.
So it seems that the `grouped=False` aspect of the request is not working as intended. I don’t know why; is this a Canvas bug or a `canvasapi` bug? Either way, the current behavior certainly is not working as intended. `canvasapi` should either request a non-grouped response in a way that works, or else it should process the grouped response in a way that respects the actual structure and meaning of the returned data.
For now I am working around this myself by building new `Submission` instances out of the dicts in each of the `submissions` attributes, like this:
```python
groups = course.list_multiple_submissions(student_ids='all', assignment_ids=assignmentIds)
submissions = [Submission(course._requester, raw) for raw in chain.from_iterable(group.submissions for group in groups)]
```
But clearly that is not how the API is intended to be used. | ucfopen/canvasapi | diff --git a/tests/test_course.py b/tests/test_course.py
index 09b5e4c..b2bc030 100644
--- a/tests/test_course.py
+++ b/tests/test_course.py
@@ -1,7 +1,8 @@
from __future__ import absolute_import, division, print_function, unicode_literals
+import os
import unittest
import uuid
-import os
+import warnings
import requests_mock
from six import text_type
@@ -647,6 +648,25 @@ class TestCourse(unittest.TestCase):
self.assertEqual(len(submission_list), 2)
self.assertIsInstance(submission_list[0], Submission)
+ def test_list_multiple_submissions_grouped_param(self, m):
+ register_uris({'course': ['list_multiple_submissions']}, m)
+
+ with warnings.catch_warnings(record=True) as warning_list:
+ warnings.simplefilter('always')
+ submissions = self.course.list_multiple_submissions(grouped=True)
+ submission_list = [submission for submission in submissions]
+
+ # Ensure using the `grouped` param raises a warning
+ self.assertEqual(len(warning_list), 1)
+ self.assertEqual(warning_list[-1].category, UserWarning)
+ self.assertEqual(
+ text_type(warning_list[-1].message),
+ 'The `grouped` parameter must be empty. Removing kwarg `grouped`.'
+ )
+
+ self.assertEqual(len(submission_list), 2)
+ self.assertIsInstance(submission_list[0], Submission)
+
# get_submission()
def test_get_submission(self, m):
register_uris({'course': ['get_submission']}, m)
diff --git a/tests/test_section.py b/tests/test_section.py
index c26ba21..b3313fa 100644
--- a/tests/test_section.py
+++ b/tests/test_section.py
@@ -1,7 +1,9 @@
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
+import warnings
import requests_mock
+from six import text_type
from canvasapi import Canvas
from canvasapi.enrollment import Enrollment
@@ -104,6 +106,25 @@ class TestSection(unittest.TestCase):
self.assertEqual(len(submission_list), 2)
self.assertIsInstance(submission_list[0], Submission)
+ def test_list_multiple_submissions_grouped_param(self, m):
+ register_uris({'section': ['list_multiple_submissions']}, m)
+
+ with warnings.catch_warnings(record=True) as warning_list:
+ warnings.simplefilter('always')
+ submissions = self.section.list_multiple_submissions(grouped=True)
+ submission_list = [submission for submission in submissions]
+
+ # Ensure using the `grouped` param raises a warning
+ self.assertEqual(len(warning_list), 1)
+ self.assertEqual(warning_list[-1].category, UserWarning)
+ self.assertEqual(
+ text_type(warning_list[-1].message),
+ 'The `grouped` parameter must be empty. Removing kwarg `grouped`.'
+ )
+
+ self.assertEqual(len(submission_list), 2)
+ self.assertIsInstance(submission_list[0], Submission)
+
# get_submission()
def test_get_submission(self, m):
register_uris({'section': ['get_submission']}, m)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 2
} | 0.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements.txt",
"dev_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
-e git+https://github.com/ucfopen/canvasapi.git@7eb0ec8ec2d8b9c5b6036edb3a93014b241c4fe6#egg=canvasapi
certifi==2021.5.30
charset-normalizer==2.0.12
coverage==6.2
docutils==0.18.1
execnet==1.9.0
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
pycodestyle==2.10.0
pyflakes==3.0.1
Pygments==2.14.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
pytz==2025.2
requests==2.27.1
requests-mock==1.12.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-rtd-theme==2.0.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: canvasapi
channels:
- defaults
- https://repo.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
- coverage==6.2
- docutils==0.18.1
- execnet==1.9.0
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- packaging==21.3
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.10.0
- pyflakes==3.0.1
- pygments==2.14.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
- pytz==2025.2
- requests==2.27.1
- requests-mock==1.12.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-rtd-theme==2.0.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/canvasapi
| [
"tests/test_course.py::TestCourse::test_list_multiple_submissions_grouped_param",
"tests/test_section.py::TestSection::test_list_multiple_submissions_grouped_param"
]
| []
| [
"tests/test_course.py::TestCourse::test__str__",
"tests/test_course.py::TestCourse::test_conclude",
"tests/test_course.py::TestCourse::test_course_files",
"tests/test_course.py::TestCourse::test_create_assignment",
"tests/test_course.py::TestCourse::test_create_assignment_fail",
"tests/test_course.py::TestCourse::test_create_assignment_group",
"tests/test_course.py::TestCourse::test_create_course_section",
"tests/test_course.py::TestCourse::test_create_discussion_topic",
"tests/test_course.py::TestCourse::test_create_external_feed",
"tests/test_course.py::TestCourse::test_create_external_tool",
"tests/test_course.py::TestCourse::test_create_folder",
"tests/test_course.py::TestCourse::test_create_group_category",
"tests/test_course.py::TestCourse::test_create_module",
"tests/test_course.py::TestCourse::test_create_module_fail",
"tests/test_course.py::TestCourse::test_create_page",
"tests/test_course.py::TestCourse::test_create_page_fail",
"tests/test_course.py::TestCourse::test_create_quiz",
"tests/test_course.py::TestCourse::test_create_quiz_fail",
"tests/test_course.py::TestCourse::test_delete",
"tests/test_course.py::TestCourse::test_delete_external_feed",
"tests/test_course.py::TestCourse::test_edit_front_page",
"tests/test_course.py::TestCourse::test_enroll_user",
"tests/test_course.py::TestCourse::test_get_assignment",
"tests/test_course.py::TestCourse::test_get_assignment_group",
"tests/test_course.py::TestCourse::test_get_assignments",
"tests/test_course.py::TestCourse::test_get_course_level_assignment_data",
"tests/test_course.py::TestCourse::test_get_course_level_participation_data",
"tests/test_course.py::TestCourse::test_get_course_level_student_summary_data",
"tests/test_course.py::TestCourse::test_get_discussion_topic",
"tests/test_course.py::TestCourse::test_get_discussion_topics",
"tests/test_course.py::TestCourse::test_get_enrollments",
"tests/test_course.py::TestCourse::test_get_external_tool",
"tests/test_course.py::TestCourse::test_get_external_tools",
"tests/test_course.py::TestCourse::test_get_file",
"tests/test_course.py::TestCourse::test_get_folder",
"tests/test_course.py::TestCourse::test_get_full_discussion_topic",
"tests/test_course.py::TestCourse::test_get_module",
"tests/test_course.py::TestCourse::test_get_modules",
"tests/test_course.py::TestCourse::test_get_page",
"tests/test_course.py::TestCourse::test_get_pages",
"tests/test_course.py::TestCourse::test_get_quiz",
"tests/test_course.py::TestCourse::test_get_quiz_fail",
"tests/test_course.py::TestCourse::test_get_quizzes",
"tests/test_course.py::TestCourse::test_get_recent_students",
"tests/test_course.py::TestCourse::test_get_section",
"tests/test_course.py::TestCourse::test_get_settings",
"tests/test_course.py::TestCourse::test_get_submission",
"tests/test_course.py::TestCourse::test_get_user",
"tests/test_course.py::TestCourse::test_get_user_id_type",
"tests/test_course.py::TestCourse::test_get_user_in_a_course_level_assignment_data",
"tests/test_course.py::TestCourse::test_get_user_in_a_course_level_messaging_data",
"tests/test_course.py::TestCourse::test_get_user_in_a_course_level_participation_data",
"tests/test_course.py::TestCourse::test_get_users",
"tests/test_course.py::TestCourse::test_list_assignment_groups",
"tests/test_course.py::TestCourse::test_list_external_feeds",
"tests/test_course.py::TestCourse::test_list_folders",
"tests/test_course.py::TestCourse::test_list_gradeable_students",
"tests/test_course.py::TestCourse::test_list_group_categories",
"tests/test_course.py::TestCourse::test_list_groups",
"tests/test_course.py::TestCourse::test_list_multiple_submissions",
"tests/test_course.py::TestCourse::test_list_sections",
"tests/test_course.py::TestCourse::test_list_submissions",
"tests/test_course.py::TestCourse::test_list_tabs",
"tests/test_course.py::TestCourse::test_mark_submission_as_read",
"tests/test_course.py::TestCourse::test_mark_submission_as_unread",
"tests/test_course.py::TestCourse::test_preview_html",
"tests/test_course.py::TestCourse::test_reorder_pinned_topics",
"tests/test_course.py::TestCourse::test_reorder_pinned_topics_no_list",
"tests/test_course.py::TestCourse::test_reset",
"tests/test_course.py::TestCourse::test_show_front_page",
"tests/test_course.py::TestCourse::test_subit_assignment_fail",
"tests/test_course.py::TestCourse::test_submit_assignment",
"tests/test_course.py::TestCourse::test_update",
"tests/test_course.py::TestCourse::test_update_settings",
"tests/test_course.py::TestCourse::test_update_submission",
"tests/test_course.py::TestCourse::test_update_tab",
"tests/test_course.py::TestCourse::test_upload",
"tests/test_course.py::TestCourseNickname::test__str__",
"tests/test_course.py::TestCourseNickname::test_remove",
"tests/test_section.py::TestSection::test__str__",
"tests/test_section.py::TestSection::test_cross_list_section",
"tests/test_section.py::TestSection::test_decross_list_section",
"tests/test_section.py::TestSection::test_delete",
"tests/test_section.py::TestSection::test_edit",
"tests/test_section.py::TestSection::test_get_enrollments",
"tests/test_section.py::TestSection::test_get_submission",
"tests/test_section.py::TestSection::test_list_multiple_submissions",
"tests/test_section.py::TestSection::test_list_submissions",
"tests/test_section.py::TestSection::test_mark_submission_as_read",
"tests/test_section.py::TestSection::test_mark_submission_as_unread",
"tests/test_section.py::TestSection::test_subit_assignment_fail",
"tests/test_section.py::TestSection::test_submit_assignment",
"tests/test_section.py::TestSection::test_update_submission"
]
| []
| MIT License | 1,678 | [
"canvasapi/course.py",
"canvasapi/section.py"
]
| [
"canvasapi/course.py",
"canvasapi/section.py"
]
|
|
zopefoundation__Zope-182 | 571aada50a4c7390e716a7bf027810cac481f632 | 2017-09-15 21:09:56 | 6fe9a941d5c63e6de80b63e98d4701bbae00f020 | diff --git a/CHANGES.rst b/CHANGES.rst
index f0925e1e3..923b94331 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -11,7 +11,10 @@ https://github.com/zopefoundation/Zope/blob/4.0a6/CHANGES.rst
4.0b2 (unreleased)
------------------
-- Nothing changed yet.
+Bugfixes
+++++++++
+
+- Fix special double under methods on `HTTPRequest.record` class.
4.0b1 (2017-09-15)
diff --git a/src/ZPublisher/HTTPRequest.py b/src/ZPublisher/HTTPRequest.py
index 2d5bef13e..0ba7a0beb 100644
--- a/src/ZPublisher/HTTPRequest.py
+++ b/src/ZPublisher/HTTPRequest.py
@@ -1797,17 +1797,22 @@ class record(object):
'keys',
'items',
'values',
- 'copy',
- 'has_key',
- '__contains__',
- '__iter__',
- '__len__'):
+ 'copy'):
return getattr(self.__dict__, key)
raise AttributeError(key)
+ def __contains__(self, key):
+ return key in self.__dict__
+
def __getitem__(self, key):
return self.__dict__[key]
+ def __iter__(self):
+ return iter(self.__dict__)
+
+ def __len__(self):
+ return len(self.__dict__)
+
def __str__(self):
return ", ".join("%s: %s" % item for item in
sorted(self.__dict__.items()))
| Form-value gets turned into a request-record instead of a dict
Form-value gets turned into a request-record instead of a dict
A doctest with a item
<input type="checkbox" value="1" name="index.enabled:records" id="created_enabled" checked="checked" />
fails in Zope 4 since index is transformed to a ZPublisher.HTTPRequest.record instance.
In the button-handler the value is gotten from the rest and checked for some value:
data = REQUEST.get('index', [])
for index in data:
enabled = 'enabled' in index
The last line results in "KeyError: 0" since data is a list of ZPublisher.HTTPRequest.record instances which calls `self.__dict__[key]` on `__getitem__`.
I fixed the respective code using `enabled = 'enabled' in index.keys()` in https://github.com/plone/Products.ATContentTypes/pull/41 and the feature in which this happened is deprecated anyway. But there might be a issue with processInputs in HTTPRequest (or a issue with the form itself).
| zopefoundation/Zope | diff --git a/src/ZPublisher/tests/testHTTPRequest.py b/src/ZPublisher/tests/testHTTPRequest.py
index 7d12a1ccf..5dd152cec 100644
--- a/src/ZPublisher/tests/testHTTPRequest.py
+++ b/src/ZPublisher/tests/testHTTPRequest.py
@@ -33,9 +33,54 @@ if sys.version_info >= (3, ):
class RecordTests(unittest.TestCase):
- def test_repr(self):
+ def _makeOne(self):
from ZPublisher.HTTPRequest import record
- rec = record()
+ return record()
+
+ def test_dict_methods(self):
+ rec = self._makeOne()
+ rec.a = 1
+ self.assertEqual(rec['a'], 1)
+ self.assertEqual(rec.get('a'), 1)
+ self.assertEqual(list(rec.keys()), ['a'])
+ self.assertEqual(list(rec.values()), [1])
+ self.assertEqual(list(rec.items()), [('a', 1)])
+
+ def test_dict_special_methods(self):
+ rec = self._makeOne()
+ rec.a = 1
+ self.assertTrue('a' in rec)
+ self.assertFalse('b' in rec)
+ self.assertEqual(len(rec), 1)
+ self.assertEqual(list(iter(rec)), ['a'])
+
+ def test_copy(self):
+ rec = self._makeOne()
+ rec.a = 1
+ rec.b = 'foo'
+ new_rec = rec.copy()
+ self.assertIsInstance(new_rec, dict)
+ self.assertEqual(new_rec, {'a': 1, 'b': 'foo'})
+
+ def test_eq(self):
+ rec1 = self._makeOne()
+ self.assertFalse(rec1, {})
+ rec2 = self._makeOne()
+ self.assertEqual(rec1, rec2)
+ rec1.a = 1
+ self.assertNotEqual(rec1, rec2)
+ rec2.a = 1
+ self.assertEqual(rec1, rec2)
+ rec2.b = 'foo'
+ self.assertNotEqual(rec1, rec2)
+
+ def test_str(self):
+ rec = self._makeOne()
+ rec.a = 1
+ self.assertEqual(str(rec), 'a: 1')
+
+ def test_repr(self):
+ rec = self._makeOne()
rec.a = 1
rec.b = 'foo'
r = repr(rec)
| {
"commit_name": "merge_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": 2
},
"num_modified_files": 2
} | 4.01 | {
"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 python3-dev gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | AccessControl==7.2
Acquisition==6.1
AuthEncoding==6.0
beautifulsoup4==4.13.3
BTrees==6.1
cffi==1.17.1
Chameleon==4.6.0
coverage==7.8.0
DateTime==5.5
DocumentTemplate==4.6
exceptiongroup==1.2.2
execnet==2.1.1
ExtensionClass==6.0
importlib_metadata==8.6.1
iniconfig==2.1.0
MultiMapping==5.0
multipart==1.2.1
packaging==24.2
PasteDeploy==3.1.0
Persistence==5.1
persistent==6.1.1
pluggy==1.5.0
pycparser==2.22
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-gettext==5.0
pytz==2025.2
RestrictedPython==8.0
roman==5.0
six==1.17.0
soupsieve==2.6
tomli==2.2.1
transaction==5.0
typing_extensions==4.13.0
waitress==3.0.2
WebOb==1.8.9
WebTest==3.0.4
WSGIProxy2==0.5.1
z3c.pt==4.5
zc.lockfile==3.0.post1
ZConfig==4.2
zExceptions==5.0
zipp==3.21.0
ZODB==6.0
zodbpickle==4.2
-e git+https://github.com/zopefoundation/Zope.git@571aada50a4c7390e716a7bf027810cac481f632#egg=Zope
zope.annotation==5.1
zope.browser==3.1
zope.browsermenu==5.1
zope.browserpage==5.0
zope.browserresource==5.2
zope.cachedescriptors==5.1
zope.component==6.0
zope.configuration==6.0
zope.container==6.1
zope.contentprovider==6.0
zope.contenttype==5.2
zope.deferredimport==5.0
zope.deprecation==5.1
zope.dottedname==6.0
zope.event==5.0
zope.exceptions==5.2
zope.filerepresentation==6.1
zope.globalrequest==2.0
zope.hookable==7.0
zope.i18n==5.2
zope.i18nmessageid==7.0
zope.interface==7.2
zope.lifecycleevent==5.1
zope.location==5.1
zope.pagetemplate==5.1
zope.processlifetime==3.1
zope.proxy==6.1
zope.ptresource==5.1
zope.publisher==7.3
zope.schema==7.0.1
zope.security==7.3
zope.sequencesort==5.1
zope.site==5.1
zope.size==5.1
zope.structuredtext==5.0
zope.tal==5.1
zope.tales==6.1
zope.testbrowser==7.0.1
zope.testing==5.1
zope.traversing==5.1
zope.viewlet==5.1
| name: Zope
channels:
- defaults
- https://repo.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:
- accesscontrol==7.2
- acquisition==6.1
- authencoding==6.0
- beautifulsoup4==4.13.3
- btrees==6.1
- cffi==1.17.1
- chameleon==4.6.0
- coverage==7.8.0
- datetime==5.5
- documenttemplate==4.6
- exceptiongroup==1.2.2
- execnet==2.1.1
- extensionclass==6.0
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- multimapping==5.0
- multipart==1.2.1
- packaging==24.2
- pastedeploy==3.1.0
- persistence==5.1
- persistent==6.1.1
- pluggy==1.5.0
- pycparser==2.22
- 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-gettext==5.0
- pytz==2025.2
- restrictedpython==8.0
- roman==5.0
- six==1.17.0
- soupsieve==2.6
- tomli==2.2.1
- transaction==5.0
- typing-extensions==4.13.0
- waitress==3.0.2
- webob==1.8.9
- webtest==3.0.4
- wsgiproxy2==0.5.1
- z3c-pt==4.5
- zc-lockfile==3.0.post1
- zconfig==4.2
- zexceptions==5.0
- zipp==3.21.0
- zodb==6.0
- zodbpickle==4.2
- zope-annotation==5.1
- zope-browser==3.1
- zope-browsermenu==5.1
- zope-browserpage==5.0
- zope-browserresource==5.2
- zope-cachedescriptors==5.1
- zope-component==6.0
- zope-configuration==6.0
- zope-container==6.1
- zope-contentprovider==6.0
- zope-contenttype==5.2
- zope-deferredimport==5.0
- zope-deprecation==5.1
- zope-dottedname==6.0
- zope-event==5.0
- zope-exceptions==5.2
- zope-filerepresentation==6.1
- zope-globalrequest==2.0
- zope-hookable==7.0
- zope-i18n==5.2
- zope-i18nmessageid==7.0
- zope-interface==7.2
- zope-lifecycleevent==5.1
- zope-location==5.1
- zope-pagetemplate==5.1
- zope-processlifetime==3.1
- zope-proxy==6.1
- zope-ptresource==5.1
- zope-publisher==7.3
- zope-schema==7.0.1
- zope-security==7.3
- zope-sequencesort==5.1
- zope-site==5.1
- zope-size==5.1
- zope-structuredtext==5.0
- zope-tal==5.1
- zope-tales==6.1
- zope-testbrowser==7.0.1
- zope-testing==5.1
- zope-traversing==5.1
- zope-viewlet==5.1
prefix: /opt/conda/envs/Zope
| [
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_dict_special_methods",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_eq"
]
| [
"src/ZPublisher/tests/testHTTPRequest.py::TestHTTPRequestZope3Views::test_no_traversal_of_view_request_attribute"
]
| [
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_copy",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_dict_methods",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_repr",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_str",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test___bobo_traverse___raises",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_simple",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_with_embedded_colon",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_doesnt_re_clean_environ",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_keeps_only_last_PARENT",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_keeps_preserves__auth",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_direct_interfaces",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_request_subclass",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_response_class",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_updates_method_to_GET",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_close_removes_stdin_references",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_in_qs_gets_form_var",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_not_in_qs_still_gets_attr",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_override_via_form_other",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_one_trusted_proxy",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_trusted_proxy_last",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_trusted_proxy_no_REMOTE_ADDR",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_wo_trusted_proxy",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_case_insensitive",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_exact",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_literal_turns_off_case_normalization",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_nonesuch",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_nonesuch_with_default",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_underscore_is_dash",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getVirtualRoot",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_fallback",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_in_qs",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_property_accessor",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_property_override_via_form_other",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_semantics",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_method_GET",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_method_POST",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_no_docstring_on_instance",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_parses_json_cookies",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_postProcessInputs",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_cookie_parsing",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_defaults",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_defaults_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_dotted_name_as_tuple",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_large_input_gets_tempfile",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_marshalling_into_sequences",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_records_w_sequences",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_records_w_sequences_tainted",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_containers",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_containers_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_marshalling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_marshalling_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_tainted_attribute_raises",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_tainted_values_cleans_exceptions",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_unicode_conversions",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_unicode_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_with_file_upload_gets_iterator",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_marshalling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_marshalling_w_Taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_resolve_url_doesnt_send_endrequestevent",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_resolve_url_errorhandling"
]
| []
| Zope Public License 2.1 | 1,679 | [
"src/ZPublisher/HTTPRequest.py",
"CHANGES.rst"
]
| [
"src/ZPublisher/HTTPRequest.py",
"CHANGES.rst"
]
|
|
pre-commit__pre-commit-622 | 773a817f7fa300c5561e7d27ff6a67b11c261fc5 | 2017-09-17 22:23:10 | 3a7806ea30507dbfba6571260210420a62f8022d | diff --git a/pre_commit/staged_files_only.py b/pre_commit/staged_files_only.py
index cfd6381..1d0c364 100644
--- a/pre_commit/staged_files_only.py
+++ b/pre_commit/staged_files_only.py
@@ -8,6 +8,7 @@ import time
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
+from pre_commit.util import mkdirp
logger = logging.getLogger('pre_commit')
@@ -43,6 +44,7 @@ def staged_files_only(patch_dir):
'Stashing unstaged files to {}.'.format(patch_filename),
)
# Save the current unstaged changes as a patch
+ mkdirp(patch_dir)
with io.open(patch_filename, 'wb') as patch_file:
patch_file.write(diff_stdout_binary)
| Unstaged files + never ran pre-commit => "No such file or directory: .../.cache/pre-commit/patch..."
```
$ pre-commit run
[WARNING] Unstaged files detected.
[INFO] Stashing unstaged files to /home/asottile/.cache/pre-commit/patch1505686307.
An unexpected error has occurred: IOError: [Errno 2] No such file or directory: '/home/asottile/.cache/pre-commit/patch1505686307'
Check the log at /home/asottile/.cache/pre-commit/pre-commit.log
```
Stacktrace:
```python
Traceback (most recent call last):
File "/home/asottile/workspace/pre-commit/pre_commit/error_handler.py", line 44, in error_handler
yield
File "/home/asottile/workspace/pre-commit/pre_commit/main.py", line 231, in main
return run(runner, args)
File "/home/asottile/workspace/pre-commit/pre_commit/commands/run.py", line 249, in run
with ctx:
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/home/asottile/workspace/pre-commit/pre_commit/staged_files_only.py", line 46, in staged_files_only
with io.open(patch_filename, 'wb') as patch_file:
IOError: [Errno 2] No such file or directory: '/home/asottile/.cache/pre-commit/patch1505686307'
``` | pre-commit/pre-commit | diff --git a/tests/staged_files_only_test.py b/tests/staged_files_only_test.py
index aec55f5..36b1985 100644
--- a/tests/staged_files_only_test.py
+++ b/tests/staged_files_only_test.py
@@ -75,6 +75,15 @@ def test_foo_something_unstaged(foo_staged, patch_dir):
_test_foo_state(foo_staged, 'herp\nderp\n', 'AM')
+def test_does_not_crash_patch_dir_does_not_exist(foo_staged, patch_dir):
+ with io.open(foo_staged.foo_filename, 'w') as foo_file:
+ foo_file.write('hello\nworld\n')
+
+ shutil.rmtree(patch_dir)
+ with staged_files_only(patch_dir):
+ pass
+
+
def test_something_unstaged_ext_diff_tool(foo_staged, patch_dir, tmpdir):
diff_tool = tmpdir.join('diff-tool.sh')
diff_tool.write('#!/usr/bin/env bash\necho "$@"\n')
| {
"commit_name": "head_commit",
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
} | 1.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": null,
"pre_install": null,
"python": "3.6",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | aspy.yaml==1.3.0
attrs==22.2.0
cached-property==1.5.2
certifi==2021.5.30
coverage==6.2
distlib==0.3.9
filelock==3.4.1
flake8==5.0.4
identify==2.4.4
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
mccabe==0.7.0
mock==5.2.0
nodeenv==1.6.0
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
-e git+https://github.com/pre-commit/pre-commit.git@773a817f7fa300c5561e7d27ff6a67b11c261fc5#egg=pre_commit
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
pytest-env==0.6.2
PyYAML==6.0.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
virtualenv==20.17.1
zipp==3.6.0
| name: pre-commit
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- certifi=2021.5.30=py36h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.3=he6710b0_2
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=1.1.1w=h7f8727e_0
- pip=21.2.2=py36h06a4308_0
- python=3.6.13=h12debd9_1
- readline=8.2=h5eee18b_0
- setuptools=58.0.4=py36h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- aspy-yaml==1.3.0
- attrs==22.2.0
- cached-property==1.5.2
- coverage==6.2
- distlib==0.3.9
- filelock==3.4.1
- flake8==5.0.4
- identify==2.4.4
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- mccabe==0.7.0
- mock==5.2.0
- nodeenv==1.6.0
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-env==0.6.2
- pyyaml==6.0.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- virtualenv==20.17.1
- zipp==3.6.0
prefix: /opt/conda/envs/pre-commit
| [
"tests/staged_files_only_test.py::test_does_not_crash_patch_dir_does_not_exist"
]
| []
| [
"tests/staged_files_only_test.py::test_foo_staged",
"tests/staged_files_only_test.py::test_foo_nothing_unstaged",
"tests/staged_files_only_test.py::test_foo_something_unstaged",
"tests/staged_files_only_test.py::test_something_unstaged_ext_diff_tool",
"tests/staged_files_only_test.py::test_foo_something_unstaged_diff_color_always",
"tests/staged_files_only_test.py::test_foo_both_modify_non_conflicting",
"tests/staged_files_only_test.py::test_foo_both_modify_conflicting",
"tests/staged_files_only_test.py::test_img_staged",
"tests/staged_files_only_test.py::test_img_nothing_unstaged",
"tests/staged_files_only_test.py::test_img_something_unstaged",
"tests/staged_files_only_test.py::test_img_conflict",
"tests/staged_files_only_test.py::test_stage_utf8_changes",
"tests/staged_files_only_test.py::test_stage_non_utf8_changes",
"tests/staged_files_only_test.py::test_non_utf8_conflicting_diff",
"tests/staged_files_only_test.py::test_crlf[true-True-True]",
"tests/staged_files_only_test.py::test_crlf[true-True-False]",
"tests/staged_files_only_test.py::test_crlf[true-False-True]",
"tests/staged_files_only_test.py::test_crlf[true-False-False]",
"tests/staged_files_only_test.py::test_crlf[false-True-True]",
"tests/staged_files_only_test.py::test_crlf[false-True-False]",
"tests/staged_files_only_test.py::test_crlf[false-False-True]",
"tests/staged_files_only_test.py::test_crlf[false-False-False]",
"tests/staged_files_only_test.py::test_crlf[input-True-True]",
"tests/staged_files_only_test.py::test_crlf[input-True-False]",
"tests/staged_files_only_test.py::test_crlf[input-False-True]",
"tests/staged_files_only_test.py::test_crlf[input-False-False]",
"tests/staged_files_only_test.py::test_whitespace_errors",
"tests/staged_files_only_test.py::test_autocrlf_commited_crlf"
]
| []
| MIT License | 1,680 | [
"pre_commit/staged_files_only.py"
]
| [
"pre_commit/staged_files_only.py"
]
|
|
zhmcclient__python-zhmcclient-443 | 6b163ed76601e39d54eadd28577bdb18ad82181d | 2017-09-18 08:40:13 | 6b163ed76601e39d54eadd28577bdb18ad82181d | diff --git a/zhmcclient_mock/_urihandler.py b/zhmcclient_mock/_urihandler.py
index 3124ff2..d703b52 100644
--- a/zhmcclient_mock/_urihandler.py
+++ b/zhmcclient_mock/_urihandler.py
@@ -503,10 +503,11 @@ class CpcExportPortNamesListHandler(object):
class MetricsContextsHandler(object):
@staticmethod
- def post(hmc, uri, uri_parms, body, logon_required, wait_for_completion):
+ def post(method, hmc, uri, uri_parms, body, logon_required,
+ wait_for_completion):
"""Operation: Create Metrics Context."""
assert wait_for_completion is True # always synchronous
- check_required_fields('POST', uri, body,
+ check_required_fields(method, uri, body,
['anticipated-frequency-seconds'])
new_metrics_context = hmc.metrics_contexts.add(body)
result = {
@@ -519,21 +520,21 @@ class MetricsContextsHandler(object):
class MetricsContextHandler(object):
@staticmethod
- def delete(hmc, uri, uri_parms, logon_required):
+ def delete(method, hmc, uri, uri_parms, logon_required):
"""Operation: Delete Metrics Context."""
try:
metrics_context = hmc.lookup_by_uri(uri)
except KeyError:
- raise InvalidResourceError('DELETE', uri)
+ raise InvalidResourceError(method, uri)
hmc.metrics_contexts.remove(metrics_context.oid)
@staticmethod
- def get(hmc, uri, uri_parms, logon_required):
+ def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: Get Metrics."""
try:
metrics_context = hmc.lookup_by_uri(uri)
except KeyError:
- raise InvalidResourceError('GET', uri)
+ raise InvalidResourceError(method, uri)
result = metrics_context.get_metric_values_response()
return result
| zhmcclient_mock/_urihandler.py:315: TypeError
[test_27.log.txt](https://github.com/zhmcclient/python-zhmcclient/files/1309064/test_27.log.txt)
### Actual behavior
MetricsContextHandlersTests.test_create_get_delete_context fails due to a TypeError in file zhmcclient_mock/_urihandler.py, line 315.
This unit test error avoids to run successfully in Travis for master branch.
### Expected behavior
### Execution environment
* zhmcclient version: master
| zhmcclient/python-zhmcclient | diff --git a/tests/unit/zhmcclient_mock/test_urihandler.py b/tests/unit/zhmcclient_mock/test_urihandler.py
index 7c23cd4..324a9b5 100755
--- a/tests/unit/zhmcclient_mock/test_urihandler.py
+++ b/tests/unit/zhmcclient_mock/test_urihandler.py
@@ -21,12 +21,11 @@ from __future__ import absolute_import, print_function
import requests.packages.urllib3
import unittest
-# from datetime import datetime
+from datetime import datetime
from mock import MagicMock
-# from zhmcclient_mock._hmc import FakedHmc, FakedMetricGroupDefinition, \
-# FakedMetricObjectValues
-from zhmcclient_mock._hmc import FakedHmc
+from zhmcclient_mock._hmc import FakedHmc, FakedMetricGroupDefinition, \
+ FakedMetricObjectValues
from zhmcclient_mock._urihandler import HTTPError, InvalidResourceError, \
InvalidMethodError, CpcNotInDpmError, CpcInDpmError, \
@@ -1033,134 +1032,134 @@ class MetricsContextHandlersTests(unittest.TestCase):
)
self.urihandler = UriHandler(self.uris)
-# def test_create_get_delete_context(self):
-#
-# mc_mgr = self.hmc.metrics_contexts
-#
-# # Prepare faked metric group definitions
-#
-# mg_name = 'partition-usage'
-# mg_def = FakedMetricGroupDefinition(
-# name=mg_name,
-# types=[
-# ('metric-1', 'string-metric'),
-# ('metric-2', 'integer-metric'),
-# ])
-# mg_info = {
-# 'group-name': mg_name,
-# 'metric-infos': [
-# {
-# 'metric-name': 'metric-1',
-# 'metric-type': 'string-metric',
-# },
-# {
-# 'metric-name': 'metric-2',
-# 'metric-type': 'integer-metric',
-# },
-# ],
-# }
-# mc_mgr.add_metric_group_definition(mg_def)
-#
-# mg_name2 = 'cpc-usage'
-# mg_def2 = FakedMetricGroupDefinition(
-# name=mg_name2,
-# types=[
-# ('metric-3', 'string-metric'),
-# ('metric-4', 'integer-metric'),
-# ])
-# mg_info2 = {
-# 'group-name': mg_name2,
-# 'metric-infos': [
-# {
-# 'metric-name': 'metric-3',
-# 'metric-type': 'string-metric',
-# },
-# {
-# 'metric-name': 'metric-4',
-# 'metric-type': 'integer-metric',
-# },
-# ],
-# }
-# mc_mgr.add_metric_group_definition(mg_def2)
-#
-# # Prepare faked metric values
-#
-# mo_val1_input = FakedMetricObjectValues(
-# group_name=mg_name,
-# resource_uri='/api/partitions/fake-oid',
-# timestamp=datetime(2017, 9, 5, 12, 13, 10, 0),
-# values=[
-# ('metric-1', "a"),
-# ('metric-2', 5),
-# ])
-# mc_mgr.add_metric_values(mo_val1_input)
-#
-# mo_val2_input = FakedMetricObjectValues(
-# group_name=mg_name,
-# resource_uri='/api/partitions/fake-oid',
-# timestamp=datetime(2017, 9, 5, 12, 13, 20, 0),
-# values=[
-# ('metric-1', "b"),
-# ('metric-2', -7),
-# ])
-# mc_mgr.add_metric_values(mo_val2_input)
-#
-# mo_val3_input = FakedMetricObjectValues(
-# group_name=mg_name2,
-# resource_uri='/api/cpcs/fake-oid',
-# timestamp=datetime(2017, 9, 5, 12, 13, 10, 0),
-# values=[
-# ('metric-1', "c"),
-# ('metric-2', 0),
-# ])
-# mc_mgr.add_metric_values(mo_val3_input)
-#
-# body = {
-# 'anticipated-frequency-seconds': '10',
-# 'metric-groups': [mg_name, mg_name2],
-# }
-#
-# # the create function to be tested:
-# resp = self.urihandler.post(self.hmc, '/api/services/metrics/context',
-# body, True, True)
-#
-# self.assertIsInstance(resp, dict)
-# self.assertIn('metrics-context-uri', resp)
-# uri = resp['metrics-context-uri']
-# self.assertTrue(uri.startswith('/api/services/metrics/context/'))
-# self.assertIn('metric-group-infos', resp)
-# mg_infos = resp['metric-group-infos']
-# self.assertEqual(mg_infos, [mg_info, mg_info2])
-#
-# # the get function to be tested:
-# mv_resp = self.urihandler.get(self.hmc, uri, True)
-#
-# exp_mv_resp = '''"partition-usage"
-# "/api/partitions/fake-oid"
-# 1504613590000
-# "a",5
-#
-# "/api/partitions/fake-oid"
-# 1504613600000
-# "b",-7
-#
-#
-# "cpc-usage"
-# "/api/cpcs/fake-oid"
-# 1504613590000
-# "c",0
-#
-#
-#
-# '''
-# self.assertEqual(
-# mv_resp, exp_mv_resp,
-# "Actual response string:\n{!r}\n"
-# "Expected response string:\n{!r}\n".
-# format(mv_resp, exp_mv_resp))
-#
-# # the delete function to be tested:
-# self.urihandler.delete(self.hmc, uri, True)
+ def test_create_get_delete_context(self):
+
+ mc_mgr = self.hmc.metrics_contexts
+
+ # Prepare faked metric group definitions
+
+ mg_name = 'partition-usage'
+ mg_def = FakedMetricGroupDefinition(
+ name=mg_name,
+ types=[
+ ('metric-1', 'string-metric'),
+ ('metric-2', 'integer-metric'),
+ ])
+ mg_info = {
+ 'group-name': mg_name,
+ 'metric-infos': [
+ {
+ 'metric-name': 'metric-1',
+ 'metric-type': 'string-metric',
+ },
+ {
+ 'metric-name': 'metric-2',
+ 'metric-type': 'integer-metric',
+ },
+ ],
+ }
+ mc_mgr.add_metric_group_definition(mg_def)
+
+ mg_name2 = 'cpc-usage'
+ mg_def2 = FakedMetricGroupDefinition(
+ name=mg_name2,
+ types=[
+ ('metric-3', 'string-metric'),
+ ('metric-4', 'integer-metric'),
+ ])
+ mg_info2 = {
+ 'group-name': mg_name2,
+ 'metric-infos': [
+ {
+ 'metric-name': 'metric-3',
+ 'metric-type': 'string-metric',
+ },
+ {
+ 'metric-name': 'metric-4',
+ 'metric-type': 'integer-metric',
+ },
+ ],
+ }
+ mc_mgr.add_metric_group_definition(mg_def2)
+
+ # Prepare faked metric values
+
+ mo_val1_input = FakedMetricObjectValues(
+ group_name=mg_name,
+ resource_uri='/api/partitions/fake-oid',
+ timestamp=datetime(2017, 9, 5, 12, 13, 10, 0),
+ values=[
+ ('metric-1', "a"),
+ ('metric-2', 5),
+ ])
+ mc_mgr.add_metric_values(mo_val1_input)
+
+ mo_val2_input = FakedMetricObjectValues(
+ group_name=mg_name,
+ resource_uri='/api/partitions/fake-oid',
+ timestamp=datetime(2017, 9, 5, 12, 13, 20, 0),
+ values=[
+ ('metric-1', "b"),
+ ('metric-2', -7),
+ ])
+ mc_mgr.add_metric_values(mo_val2_input)
+
+ mo_val3_input = FakedMetricObjectValues(
+ group_name=mg_name2,
+ resource_uri='/api/cpcs/fake-oid',
+ timestamp=datetime(2017, 9, 5, 12, 13, 10, 0),
+ values=[
+ ('metric-1', "c"),
+ ('metric-2', 0),
+ ])
+ mc_mgr.add_metric_values(mo_val3_input)
+
+ body = {
+ 'anticipated-frequency-seconds': '10',
+ 'metric-groups': [mg_name, mg_name2],
+ }
+
+ # the create function to be tested:
+ resp = self.urihandler.post(self.hmc, '/api/services/metrics/context',
+ body, True, True)
+
+ self.assertIsInstance(resp, dict)
+ self.assertIn('metrics-context-uri', resp)
+ uri = resp['metrics-context-uri']
+ self.assertTrue(uri.startswith('/api/services/metrics/context/'))
+ self.assertIn('metric-group-infos', resp)
+ mg_infos = resp['metric-group-infos']
+ self.assertEqual(mg_infos, [mg_info, mg_info2])
+
+ # the get function to be tested:
+ mv_resp = self.urihandler.get(self.hmc, uri, True)
+
+ exp_mv_resp = '''"partition-usage"
+"/api/partitions/fake-oid"
+1504613590000
+"a",5
+
+"/api/partitions/fake-oid"
+1504613600000
+"b",-7
+
+
+"cpc-usage"
+"/api/cpcs/fake-oid"
+1504613590000
+"c",0
+
+
+
+'''
+ self.assertEqual(
+ mv_resp, exp_mv_resp,
+ "Actual response string:\n{!r}\n"
+ "Expected response string:\n{!r}\n".
+ format(mv_resp, exp_mv_resp))
+
+ # the delete function to be tested:
+ self.urihandler.delete(self.hmc, uri, True)
class AdapterHandlersTests(unittest.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": 2,
"test_score": 2
},
"num_modified_files": 1
} | 0.16 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio",
"mock"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.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
click-repl==0.3.0
click-spinner==0.1.10
coverage==7.8.0
decorator==5.2.1
docopt==0.6.2
exceptiongroup==1.2.2
execnet==2.1.1
idna==3.10
iniconfig==2.1.0
mock==5.2.0
packaging==24.2
pbr==6.1.1
pluggy==1.5.0
progressbar2==4.5.0
prompt_toolkit==3.0.50
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-utils==3.9.1
pytz==2025.2
requests==2.32.3
six==1.17.0
stomp.py==8.2.0
tabulate==0.9.0
tomli==2.2.1
typing_extensions==4.13.0
urllib3==2.3.0
wcwidth==0.2.13
websocket-client==1.8.0
-e git+https://github.com/zhmcclient/python-zhmcclient.git@6b163ed76601e39d54eadd28577bdb18ad82181d#egg=zhmcclient
| name: python-zhmcclient
channels:
- defaults
- https://repo.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
- click-repl==0.3.0
- click-spinner==0.1.10
- coverage==7.8.0
- decorator==5.2.1
- docopt==0.6.2
- exceptiongroup==1.2.2
- execnet==2.1.1
- idna==3.10
- iniconfig==2.1.0
- mock==5.2.0
- packaging==24.2
- pbr==6.1.1
- pluggy==1.5.0
- progressbar2==4.5.0
- prompt-toolkit==3.0.50
- 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-utils==3.9.1
- pytz==2025.2
- requests==2.32.3
- six==1.17.0
- stomp-py==8.2.0
- tabulate==0.9.0
- tomli==2.2.1
- typing-extensions==4.13.0
- urllib3==2.3.0
- wcwidth==0.2.13
- websocket-client==1.8.0
prefix: /opt/conda/envs/python-zhmcclient
| [
"tests/unit/zhmcclient_mock/test_urihandler.py::MetricsContextHandlersTests::test_create_get_delete_context"
]
| []
| [
"tests/unit/zhmcclient_mock/test_urihandler.py::HTTPErrorTests::test_attributes",
"tests/unit/zhmcclient_mock/test_urihandler.py::HTTPErrorTests::test_response",
"tests/unit/zhmcclient_mock/test_urihandler.py::InvalidResourceErrorTests::test_attributes_no_handler",
"tests/unit/zhmcclient_mock/test_urihandler.py::InvalidResourceErrorTests::test_attributes_with_handler",
"tests/unit/zhmcclient_mock/test_urihandler.py::InvalidMethodErrorTests::test_attributes_no_handler",
"tests/unit/zhmcclient_mock/test_urihandler.py::InvalidMethodErrorTests::test_attributes_with_handler",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcNotInDpmErrorTests::test_attributes",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcInDpmErrorTests::test_attributes",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_empty",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_invalid_format_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_invalid_format_2",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_invalid_format_3",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_none",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_one_leading_amp",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_one_missing_name",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_one_missing_value",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_one_normal",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_one_trailing_amp",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_space_name_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_space_name_2",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_space_name_3",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_space_name_4",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_space_value_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_space_value_2",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_space_value_3",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_space_value_4",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_two_normal",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_two_same_normal",
"tests/unit/zhmcclient_mock/test_urihandler.py::ParseQueryParmsTests::test_two_same_one_normal",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerEmptyTests::test_uris_empty_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerEmptyTests::test_uris_empty_2",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_err_begin_extra",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_err_begin_missing",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_err_end2_extra",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_err_end2_missing",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_err_end2_slash",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_err_end_extra",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_err_end_missing",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_err_end_slash",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_ok1",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_ok2",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerHandlerSimpleTests::test_ok3",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerMethodTests::test_delete_cpc2",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerMethodTests::test_get_cpc1",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerMethodTests::test_get_cpcs",
"tests/unit/zhmcclient_mock/test_urihandler.py::UriHandlerMethodTests::test_post_cpcs",
"tests/unit/zhmcclient_mock/test_urihandler.py::GenericGetPropertiesHandlerTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::GenericUpdatePropertiesHandlerTests::test_update_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::VersionHandlerTests::test_get_version",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcHandlersTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcHandlersTests::test_list",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcHandlersTests::test_update_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcStartStopHandlerTests::test_start_classic",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcStartStopHandlerTests::test_stop_classic",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcStartStopHandlerTests::test_stop_start_dpm",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcExportPortNamesListHandlerTests::test_invoke_err_no_input",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcExportPortNamesListHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcImportProfilesHandlerTests::test_invoke_err_no_input",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcImportProfilesHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcExportProfilesHandlerTests::test_invoke_err_no_input",
"tests/unit/zhmcclient_mock/test_urihandler.py::CpcExportProfilesHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::AdapterHandlersTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::AdapterHandlersTests::test_list",
"tests/unit/zhmcclient_mock/test_urihandler.py::AdapterHandlersTests::test_update_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::AdapterChangeCryptoTypeHandlerTests::test_invoke_err_no_body",
"tests/unit/zhmcclient_mock/test_urihandler.py::AdapterChangeCryptoTypeHandlerTests::test_invoke_err_no_crypto_type_field",
"tests/unit/zhmcclient_mock/test_urihandler.py::AdapterChangeCryptoTypeHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::NetworkPortHandlersTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::NetworkPortHandlersTests::test_update_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::StoragePortHandlersTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::StoragePortHandlersTests::test_update_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionHandlersTests::test_create_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionHandlersTests::test_delete_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionHandlersTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionHandlersTests::test_list",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionHandlersTests::test_update_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionStartStopHandlerTests::test_start_stop",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionScsiDumpHandlerTests::test_invoke_err_missing_fields_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionScsiDumpHandlerTests::test_invoke_err_missing_fields_2",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionScsiDumpHandlerTests::test_invoke_err_missing_fields_3",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionScsiDumpHandlerTests::test_invoke_err_no_body",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionScsiDumpHandlerTests::test_invoke_err_status_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionScsiDumpHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionPswRestartHandlerTests::test_invoke_err_status_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionPswRestartHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionMountIsoImageHandlerTests::test_invoke_err_queryparm_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionMountIsoImageHandlerTests::test_invoke_err_queryparm_2",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionMountIsoImageHandlerTests::test_invoke_err_status_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionMountIsoImageHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionUnmountIsoImageHandlerTests::test_invoke_err_status_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionUnmountIsoImageHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionIncreaseCryptoConfigHandlerTests::test_invoke_err_missing_body",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionIncreaseCryptoConfigHandlerTests::test_invoke_err_status_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionIncreaseCryptoConfigHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionDecreaseCryptoConfigHandlerTests::test_invoke_err_missing_body",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionDecreaseCryptoConfigHandlerTests::test_invoke_err_status_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionDecreaseCryptoConfigHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionChangeCryptoConfigHandlerTests::test_invoke_err_missing_body",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionChangeCryptoConfigHandlerTests::test_invoke_err_missing_field_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionChangeCryptoConfigHandlerTests::test_invoke_err_missing_field_2",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionChangeCryptoConfigHandlerTests::test_invoke_err_status_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::PartitionChangeCryptoConfigHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::HbaHandlerTests::test_create_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::HbaHandlerTests::test_delete_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::HbaHandlerTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::HbaHandlerTests::test_list",
"tests/unit/zhmcclient_mock/test_urihandler.py::HbaHandlerTests::test_update_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::HbaReassignPortHandlerTests::test_invoke_err_missing_body",
"tests/unit/zhmcclient_mock/test_urihandler.py::HbaReassignPortHandlerTests::test_invoke_err_missing_field_1",
"tests/unit/zhmcclient_mock/test_urihandler.py::HbaReassignPortHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::NicHandlerTests::test_create_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::NicHandlerTests::test_delete_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::NicHandlerTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::NicHandlerTests::test_list",
"tests/unit/zhmcclient_mock/test_urihandler.py::NicHandlerTests::test_update_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::VirtualFunctionHandlerTests::test_create_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::VirtualFunctionHandlerTests::test_delete_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::VirtualFunctionHandlerTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::VirtualFunctionHandlerTests::test_list",
"tests/unit/zhmcclient_mock/test_urihandler.py::VirtualFunctionHandlerTests::test_update_verify",
"tests/unit/zhmcclient_mock/test_urihandler.py::VirtualSwitchHandlersTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::VirtualSwitchHandlersTests::test_list",
"tests/unit/zhmcclient_mock/test_urihandler.py::VirtualSwitchGetVnicsHandlerTests::test_invoke_ok",
"tests/unit/zhmcclient_mock/test_urihandler.py::LparHandlersTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::LparHandlersTests::test_list",
"tests/unit/zhmcclient_mock/test_urihandler.py::LparActLoadDeactHandlerTests::test_start_stop",
"tests/unit/zhmcclient_mock/test_urihandler.py::ResetActProfileHandlersTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::ResetActProfileHandlersTests::test_list",
"tests/unit/zhmcclient_mock/test_urihandler.py::ImageActProfileHandlersTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::ImageActProfileHandlersTests::test_list",
"tests/unit/zhmcclient_mock/test_urihandler.py::LoadActProfileHandlersTests::test_get",
"tests/unit/zhmcclient_mock/test_urihandler.py::LoadActProfileHandlersTests::test_list"
]
| []
| Apache License 2.0 | 1,681 | [
"zhmcclient_mock/_urihandler.py"
]
| [
"zhmcclient_mock/_urihandler.py"
]
|
|
pydicom__pydicom-505 | fdabbfe94a898a76f38636c69136df4a17e72640 | 2017-09-18 15:49:52 | bef49851e7c3b70edd43cc40fc84fe905e78d5ba | pep8speaks: Hello @rzinkstok! Thanks for submitting the PR.
- In the file [`pydicom/filereader.py`](https://github.com/pydicom/pydicom/blob/22a0ca81718f71d3f38328a0f747a0d17b2dd1ab/pydicom/filereader.py), following are the PEP8 issues :
> [Line 489:80](https://github.com/pydicom/pydicom/blob/22a0ca81718f71d3f38328a0f747a0d17b2dd1ab/pydicom/filereader.py#L489): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (86 > 79 characters)
> [Line 505:80](https://github.com/pydicom/pydicom/blob/22a0ca81718f71d3f38328a0f747a0d17b2dd1ab/pydicom/filereader.py#L505): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (98 > 79 characters)
darcymason: I think this looks good. Thanks.
@pydicom/pydcom-fff, can someone do a second check?
mrbean-bremen: Looks good for me. | diff --git a/pydicom/filereader.py b/pydicom/filereader.py
index 427791b16..8fd751fa1 100644
--- a/pydicom/filereader.py
+++ b/pydicom/filereader.py
@@ -488,6 +488,20 @@ def _read_file_meta_info(fp):
start_file_meta = fp.tell()
file_meta = read_dataset(fp, is_implicit_VR=False, is_little_endian=True,
stop_when=_not_group_0002)
+ if not file_meta:
+ return file_meta
+
+ # Test the file meta for correct interpretation by requesting the first
+ # data element: if it fails, retry loading the file meta with an
+ # implicit VR (issue #503)
+ try:
+ file_meta[list(file_meta)[0].tag]
+ except NotImplementedError:
+ fp.seek(start_file_meta)
+ file_meta = read_dataset(fp, is_implicit_VR=True,
+ is_little_endian=True,
+ stop_when=_not_group_0002)
+
# Log if the Group Length doesn't match actual length
if 'FileMetaInformationGroupLength' in file_meta:
# FileMetaInformationGroupLength must be 12 bytes long and its value
@@ -501,6 +515,7 @@ def _read_file_meta_info(fp):
"bytes)."
.format(file_meta.FileMetaInformationGroupLength,
length_file_meta))
+
return file_meta
| Support for DICOM files with implicit VR file meta
#### Description
Up to pydicom 0.9.9, it was possible to read a DICOM file that lacked any file meta. When using pydicom from the current master branch, this is no longer the case. When no file meta is present in a DICOM file, the `_read_file_meta` function returns a dataset containing only a group length data element, and then a crash occurs when the TransferSyntaxUID is requested from the file_meta_dataset (line 634 in filereader.py).
It can be fixed by having the `_read_file_meta_info` function return an empty dataset instead. For my solution, see https://github.com/rzinkstok/pydicom/commit/d246f92066a7b4fc8b28ed7f18b28281fc1568f0. I can start a pull request if that is appreciated.
I'm not sure whether the current behavior is intended. Of course, files without meta info are not DICOM-compliant, but our DICOM archives contains a huge amount of old files without file meta, so it would be really convenient if pydicom could read these files without too much fuss.
#### Steps/Code to Reproduce
Get a file without file meta (I can supply such a file) and run the following:
```py
from pydicom import read_file
f = read_file("very_old_ct_slice.dcm", force=True)
print(f.PatientName)
```
#### Expected Results
No error is thrown and the name of the patient is printed.
#### Actual Results
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/vagrant/Projects/pydicom/src/pydicom/pydicom/filereader.py", line 804, in read_file
force=force, specific_tags=specific_tags)
File "/home/vagrant/Projects/pydicom/src/pydicom/pydicom/filereader.py", line 634, in read_partial
transfer_syntax = file_meta_dataset.get("TransferSyntaxUID")
File "/home/vagrant/Projects/pydicom/src/pydicom/pydicom/dataset.py", line 431, in get
return getattr(self, key)
File "/home/vagrant/Projects/pydicom/src/pydicom/pydicom/dataset.py", line 475, in __getattr__
return self[tag].value
File "/home/vagrant/Projects/pydicom/src/pydicom/pydicom/dataset.py", line 554, in __getitem__
self[tag] = DataElement_from_raw(data_elem, character_set)
File "/home/vagrant/Projects/pydicom/src/pydicom/pydicom/dataelem.py", line 493, in DataElement_from_raw
raise NotImplementedError("{0:s} in tag {1!r}".format(str(e), raw.tag))
NotImplementedError: Unknown Value Representation '' in tag (0002, 0010)
```
#### Versions
Platform: Linux-4.4.0-93-generic-x86_64-with-Ubuntu-16.04-xenial
Python: ('Python', '2.7.11+ (default, Apr 17 2016, 14:00:29) \n[GCC 5.3.1 20160413]')
Pydicom: 1.0.0a1, at commit ac905d951c95f1d2474b8cd1c35c8eb055e5273b
| pydicom/pydicom | diff --git a/pydicom/tests/test_filereader.py b/pydicom/tests/test_filereader.py
index 9941e488c..dd2c44cc4 100644
--- a/pydicom/tests/test_filereader.py
+++ b/pydicom/tests/test_filereader.py
@@ -664,6 +664,17 @@ class ReaderTests(unittest.TestCase):
self.assertTrue(ds.preamble is None)
self.assertEqual(ds.file_meta, Dataset())
+ def test_file_meta_dataset_implicit_vr(self):
+ """Test reading a file meta dataset that is implicit VR"""
+
+ bytestream = (b'\x02\x00\x10\x00\x12\x00\x00\x00'
+ b'\x31\x2e\x32\x2e\x38\x34\x30\x2e'
+ b'\x31\x30\x30\x30\x38\x2e\x31\x2e'
+ b'\x32\x00')
+ fp = BytesIO(bytestream)
+ ds = read_file(fp, force=True)
+ self.assertTrue('TransferSyntaxUID' in ds.file_meta)
+
def test_no_dataset(self):
"""Test reading no elements or preamble produces empty Dataset"""
bytestream = b''
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_hyperlinks",
"has_git_commit_hash"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 0
},
"num_modified_files": 1
} | 0.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": [
"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==22.2.0
certifi==2021.5.30
coverage==6.2
execnet==1.9.0
importlib-metadata==4.8.3
iniconfig==1.1.1
packaging==21.3
pluggy==1.0.0
py==1.11.0
-e git+https://github.com/pydicom/pydicom.git@fdabbfe94a898a76f38636c69136df4a17e72640#egg=pydicom
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
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: pydicom
channels:
- defaults
- https://repo.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
- execnet==1.9.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
- pytest-asyncio==0.16.0
- pytest-cov==4.0.0
- pytest-mock==3.6.1
- pytest-xdist==3.0.2
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/pydicom
| [
"pydicom/tests/test_filereader.py::ReaderTests::test_file_meta_dataset_implicit_vr"
]
| [
"pydicom/tests/test_filereader.py::DeferredReadTests::testFileExists",
"pydicom/tests/test_filereader.py::DeferredReadTests::testTimeCheck",
"pydicom/tests/test_filereader.py::DeferredReadTests::testValuesIdentical",
"pydicom/tests/test_filereader.py::DeferredReadTests::testZippedDeferred"
]
| [
"pydicom/tests/test_filereader.py::ReaderTests::testCT",
"pydicom/tests/test_filereader.py::ReaderTests::testDeflate",
"pydicom/tests/test_filereader.py::ReaderTests::testDir",
"pydicom/tests/test_filereader.py::ReaderTests::testEmptyNumbersTag",
"pydicom/tests/test_filereader.py::ReaderTests::testExplicitVRBigEndianNoMeta",
"pydicom/tests/test_filereader.py::ReaderTests::testExplicitVRLittleEndianNoMeta",
"pydicom/tests/test_filereader.py::ReaderTests::testMR",
"pydicom/tests/test_filereader.py::ReaderTests::testNestedPrivateSQ",
"pydicom/tests/test_filereader.py::ReaderTests::testNoForce",
"pydicom/tests/test_filereader.py::ReaderTests::testNoMetaGroupLength",
"pydicom/tests/test_filereader.py::ReaderTests::testNoPixelsRead",
"pydicom/tests/test_filereader.py::ReaderTests::testNoTransferSyntaxInMeta",
"pydicom/tests/test_filereader.py::ReaderTests::testPlanarConfig",
"pydicom/tests/test_filereader.py::ReaderTests::testPrivateSQ",
"pydicom/tests/test_filereader.py::ReaderTests::testRTDose",
"pydicom/tests/test_filereader.py::ReaderTests::testRTPlan",
"pydicom/tests/test_filereader.py::ReaderTests::testRTstruct",
"pydicom/tests/test_filereader.py::ReaderTests::testSpecificTags",
"pydicom/tests/test_filereader.py::ReaderTests::testSpecificTagsWithUnknownLengthSQ",
"pydicom/tests/test_filereader.py::ReaderTests::testSpecificTagsWithUnknownLengthTag",
"pydicom/tests/test_filereader.py::ReaderTests::testUTF8FileName",
"pydicom/tests/test_filereader.py::ReaderTests::test_commandset_no_dataset",
"pydicom/tests/test_filereader.py::ReaderTests::test_correct_ambiguous_vr",
"pydicom/tests/test_filereader.py::ReaderTests::test_correct_ambiguous_vr_compressed",
"pydicom/tests/test_filereader.py::ReaderTests::test_group_length_wrong",
"pydicom/tests/test_filereader.py::ReaderTests::test_long_specific_char_set",
"pydicom/tests/test_filereader.py::ReaderTests::test_meta_no_dataset",
"pydicom/tests/test_filereader.py::ReaderTests::test_no_dataset",
"pydicom/tests/test_filereader.py::ReaderTests::test_no_preamble_command_group_dataset",
"pydicom/tests/test_filereader.py::ReaderTests::test_no_preamble_file_meta_dataset",
"pydicom/tests/test_filereader.py::ReaderTests::test_preamble_command_meta_no_dataset",
"pydicom/tests/test_filereader.py::ReaderTests::test_preamble_commandset_no_dataset",
"pydicom/tests/test_filereader.py::ReaderTests::test_preamble_meta_no_dataset",
"pydicom/tests/test_filereader.py::ReaderTests::test_read_file_does_not_raise",
"pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_AE",
"pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OD_explicit_little",
"pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OD_implicit_little",
"pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OL_explicit_little",
"pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_OL_implicit_little",
"pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UC_explicit_little",
"pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UC_implicit_little",
"pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UR_explicit_little",
"pydicom/tests/test_filereader.py::ReadDataElementTests::test_read_UR_implicit_little",
"pydicom/tests/test_filereader.py::ReadTruncatedFileTests::testReadFileWithMissingPixelData",
"pydicom/tests/test_filereader.py::FileLikeTests::testReadFileGivenFileLikeObject",
"pydicom/tests/test_filereader.py::FileLikeTests::testReadFileGivenFileObject"
]
| []
| MIT License | 1,682 | [
"pydicom/filereader.py"
]
| [
"pydicom/filereader.py"
]
|
OpenMined__PySyft-240 | 50c50da091ae6734237302efa5324d7dbed59164 | 2017-09-18 20:25:43 | 06ce023225dd613d8fb14ab2046135b93ab22376 | diff --git a/syft/tensor.py b/syft/tensor.py
index 553420c417..8c97892ea3 100644
--- a/syft/tensor.py
+++ b/syft/tensor.py
@@ -1160,6 +1160,37 @@ class TensorBase(object):
def deserialize(b):
return pickle.loads(b)
+ def remainder(self, divisor):
+ """
+ Computes the element-wise remainder of division.
+ The divisor and dividend may contain both for integer and floating point numbers.
+ The remainder has the same sign as the divisor.
+ When ``divisor`` is a Tensor, the shapes of ``self`` and ``divisor`` must be broadcastable.
+ :param divisor: The divisor. This may be either a number or a tensor.
+ :return: result tensor
+ """
+ if self.encrypted:
+ return NotImplemented
+ if not np.isscalar(divisor):
+ divisor = _ensure_tensorbase(divisor)
+ return TensorBase(np.remainder(self.data, divisor))
+
+ def remainder_(self, divisor):
+ """
+ Computes the element-wise remainder of division.
+ The divisor and dividend may contain both for integer and floating point numbers.
+ The remainder has the same sign as the divisor.
+ When ``divisor`` is a Tensor, the shapes of ``self`` and ``divisor`` must be broadcastable.
+ :param divisor: The divisor. This may be either a number or a tensor.
+ :return: self
+ """
+ if self.encrypted:
+ return NotImplemented
+ if not np.isscalar(divisor):
+ divisor = _ensure_tensorbase(divisor)
+ self.data = np.remainder(self.data, divisor)
+ return self
+
def index_select(self, dim, index):
"""
Returns a new Tensor which indexes the ``input`` Tensor along
| Implement Default remainder Functionality for Base Tensor Type
**User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, remainder() should return a new tensor, but remainder_() should operate inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation.
**Acceptance Criteria:**
- If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error.
- a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors.
- inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. | OpenMined/PySyft | diff --git a/tests/test_tensor.py b/tests/test_tensor.py
index e8429080be..9eaf6c42c6 100644
--- a/tests/test_tensor.py
+++ b/tests/test_tensor.py
@@ -873,6 +873,23 @@ class scatterTests(unittest.TestCase):
t.scatter_(dim=dim, index=idx, src=src)
+class remainderTests(unittest.TestCase):
+ def testRemainder(self):
+ t = TensorBase([[-2, -3], [4, 1]])
+ result = t.remainder(1.5)
+ self.assertTrue(np.array_equal(result.data, np.array([[1, 0], [1, 1]])))
+
+ def testRemainder_broadcasting(self):
+ t = TensorBase([[-2, -3], [4, 1]])
+ result = t.remainder([2, -3])
+ self.assertTrue(np.array_equal(result.data, np.array([[0, 0], [0, -2]])))
+
+ def testRemainder_(self):
+ t = TensorBase([[-2, -3], [4, 1]])
+ t.remainder_(2)
+ self.assertTrue(np.array_equal(t.data, np.array([[0, 1], [0, 1]])))
+
+
class testMv(unittest.TestCase):
def mvTest(self):
mat = TensorBase([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | PySyft/hydrogen | {
"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-flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y musl-dev g++ libgmp3-dev libmpfr-dev ca-certificates"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | args==0.1.0
clint==0.5.1
exceptiongroup==1.2.2
flake8==7.2.0
iniconfig==2.1.0
line_profiler==4.2.0
mccabe==0.7.0
numpy==1.26.4
packaging==24.2
phe==1.5.0
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.2
pyRserve==1.0.4
pytest==8.3.5
pytest-flake8==1.3.0
scipy==1.13.1
-e git+https://github.com/OpenMined/PySyft.git@50c50da091ae6734237302efa5324d7dbed59164#egg=syft
tomli==2.2.1
| name: PySyft
channels:
- defaults
- https://repo.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:
- args==0.1.0
- clint==0.5.1
- exceptiongroup==1.2.2
- flake8==7.2.0
- iniconfig==2.1.0
- line-profiler==4.2.0
- mccabe==0.7.0
- numpy==1.26.4
- packaging==24.2
- phe==1.5.0
- pluggy==1.5.0
- pycodestyle==2.13.0
- pyflakes==3.3.2
- pyrserve==1.0.4
- pytest==8.3.5
- pytest-flake8==1.3.0
- scipy==1.13.1
- tomli==2.2.1
prefix: /opt/conda/envs/PySyft
| [
"tests/test_tensor.py::remainderTests::testRemainder",
"tests/test_tensor.py::remainderTests::testRemainder_",
"tests/test_tensor.py::remainderTests::testRemainder_broadcasting"
]
| [
"tests/test_tensor.py::scatterTests::testScatter_Numerical0",
"tests/test_tensor.py::scatterTests::testScatter_Numerical1",
"tests/test_tensor.py::scatterTests::testScatter_Numerical2",
"tests/test_tensor.py::scatterTests::testScatter_Numerical3",
"tests/test_tensor.py::scatterTests::testScatter_Numerical4",
"tests/test_tensor.py::scatterTests::testScatter_Numerical5",
"tests/test_tensor.py::scatterTests::testScatter_Numerical6"
]
| [
"tests/test_tensor.py::DimTests::testAsView",
"tests/test_tensor.py::DimTests::testDimOne",
"tests/test_tensor.py::DimTests::testResize",
"tests/test_tensor.py::DimTests::testResizeAs",
"tests/test_tensor.py::DimTests::testSize",
"tests/test_tensor.py::DimTests::testView",
"tests/test_tensor.py::AddTests::testInplace",
"tests/test_tensor.py::AddTests::testScalar",
"tests/test_tensor.py::AddTests::testSimple",
"tests/test_tensor.py::CeilTests::testCeil",
"tests/test_tensor.py::CeilTests::testCeil_",
"tests/test_tensor.py::ZeroTests::testZero",
"tests/test_tensor.py::FloorTests::testFloor_",
"tests/test_tensor.py::SubTests::testInplace",
"tests/test_tensor.py::SubTests::testScalar",
"tests/test_tensor.py::SubTests::testSimple",
"tests/test_tensor.py::MaxTests::testAxis",
"tests/test_tensor.py::MaxTests::testNoDim",
"tests/test_tensor.py::MultTests::testInplace",
"tests/test_tensor.py::MultTests::testScalar",
"tests/test_tensor.py::MultTests::testSimple",
"tests/test_tensor.py::DivTests::testInplace",
"tests/test_tensor.py::DivTests::testScalar",
"tests/test_tensor.py::DivTests::testSimple",
"tests/test_tensor.py::AbsTests::testabs",
"tests/test_tensor.py::AbsTests::testabs_",
"tests/test_tensor.py::ShapeTests::testShape",
"tests/test_tensor.py::SqrtTests::testSqrt",
"tests/test_tensor.py::SqrtTests::testSqrt_",
"tests/test_tensor.py::SumTests::testDimIsNotNoneInt",
"tests/test_tensor.py::SumTests::testDimNoneInt",
"tests/test_tensor.py::EqualTests::testEqOp",
"tests/test_tensor.py::EqualTests::testEqual",
"tests/test_tensor.py::EqualTests::testIneqOp",
"tests/test_tensor.py::EqualTests::testNotEqual",
"tests/test_tensor.py::IndexTests::testIndexing",
"tests/test_tensor.py::sigmoidTests::testSigmoid",
"tests/test_tensor.py::addmm::testaddmm1d",
"tests/test_tensor.py::addmm::testaddmm2d",
"tests/test_tensor.py::addmm::testaddmm_1d",
"tests/test_tensor.py::addmm::testaddmm_2d",
"tests/test_tensor.py::addcmulTests::testaddcmul1d",
"tests/test_tensor.py::addcmulTests::testaddcmul2d",
"tests/test_tensor.py::addcmulTests::testaddcmul_1d",
"tests/test_tensor.py::addcmulTests::testaddcmul_2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_2d",
"tests/test_tensor.py::addmvTests::testaddmv",
"tests/test_tensor.py::addmvTests::testaddmv_",
"tests/test_tensor.py::addbmmTests::testaddbmm",
"tests/test_tensor.py::addbmmTests::testaddbmm_",
"tests/test_tensor.py::baddbmmTests::testbaddbmm",
"tests/test_tensor.py::baddbmmTests::testbaddbmm_",
"tests/test_tensor.py::transposeTests::testT",
"tests/test_tensor.py::transposeTests::testT_",
"tests/test_tensor.py::transposeTests::testTranspose",
"tests/test_tensor.py::transposeTests::testTranspose_",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze_",
"tests/test_tensor.py::expTests::testexp",
"tests/test_tensor.py::expTests::testexp_",
"tests/test_tensor.py::fracTests::testfrac",
"tests/test_tensor.py::fracTests::testfrac_",
"tests/test_tensor.py::rsqrtTests::testrsqrt",
"tests/test_tensor.py::rsqrtTests::testrsqrt_",
"tests/test_tensor.py::signTests::testsign",
"tests/test_tensor.py::signTests::testsign_",
"tests/test_tensor.py::numpyTests::testnumpy",
"tests/test_tensor.py::reciprocalTests::testreciprocal",
"tests/test_tensor.py::reciprocalTests::testrsqrt_",
"tests/test_tensor.py::logTests::testLog",
"tests/test_tensor.py::logTests::testLog1p",
"tests/test_tensor.py::logTests::testLog1p_",
"tests/test_tensor.py::logTests::testLog_",
"tests/test_tensor.py::clampTests::testClampFloat",
"tests/test_tensor.py::clampTests::testClampFloatInPlace",
"tests/test_tensor.py::clampTests::testClampInt",
"tests/test_tensor.py::clampTests::testClampIntInPlace",
"tests/test_tensor.py::cloneTests::testClone",
"tests/test_tensor.py::chunkTests::testChunk",
"tests/test_tensor.py::chunkTests::testChunkSameSize",
"tests/test_tensor.py::gtTests::testGtInPlaceWithNumber",
"tests/test_tensor.py::gtTests::testGtInPlaceWithTensor",
"tests/test_tensor.py::gtTests::testGtWithNumber",
"tests/test_tensor.py::gtTests::testGtWithTensor",
"tests/test_tensor.py::bernoulliTests::testBernoulli",
"tests/test_tensor.py::bernoulliTests::testBernoulli_",
"tests/test_tensor.py::uniformTests::testUniform",
"tests/test_tensor.py::uniformTests::testUniform_",
"tests/test_tensor.py::fillTests::testFill_",
"tests/test_tensor.py::topkTests::testTopK",
"tests/test_tensor.py::tolistTests::testToList",
"tests/test_tensor.py::traceTests::testTrace",
"tests/test_tensor.py::roundTests::testRound",
"tests/test_tensor.py::roundTests::testRound_",
"tests/test_tensor.py::repeatTests::testRepeat",
"tests/test_tensor.py::powTests::testPow",
"tests/test_tensor.py::powTests::testPow_",
"tests/test_tensor.py::prodTests::testProd",
"tests/test_tensor.py::randomTests::testRandom_",
"tests/test_tensor.py::nonzeroTests::testNonZero",
"tests/test_tensor.py::cumprodTest::testCumprod",
"tests/test_tensor.py::cumprodTest::testCumprod_",
"tests/test_tensor.py::splitTests::testSplit",
"tests/test_tensor.py::squeezeTests::testSqueeze",
"tests/test_tensor.py::expandAsTests::testExpandAs",
"tests/test_tensor.py::meanTests::testMean",
"tests/test_tensor.py::notEqualTests::testNe",
"tests/test_tensor.py::notEqualTests::testNe_",
"tests/test_tensor.py::index_selectTests::testIndex_select",
"tests/test_tensor.py::gatherTests::testGatherNumerical1",
"tests/test_tensor.py::gatherTests::testGatherNumerical2",
"tests/test_tensor.py::scatterTests::testScatter_DimOutOfRange",
"tests/test_tensor.py::scatterTests::testScatter_IndexOutOfRange",
"tests/test_tensor.py::scatterTests::testScatter_IndexType",
"tests/test_tensor.py::scatterTests::testScatter_index_src_dimension_mismatch",
"tests/test_tensor.py::masked_scatter_Tests::testMasked_scatter_1",
"tests/test_tensor.py::masked_scatter_Tests::testMasked_scatter_braodcasting1",
"tests/test_tensor.py::masked_scatter_Tests::testMasked_scatter_braodcasting2",
"tests/test_tensor.py::eqTests::testEqInPlaceWithNumber",
"tests/test_tensor.py::eqTests::testEqInPlaceWithTensor",
"tests/test_tensor.py::eqTests::testEqWithNumber",
"tests/test_tensor.py::eqTests::testEqWithTensor"
]
| []
| Apache License 2.0 | 1,683 | [
"syft/tensor.py"
]
| [
"syft/tensor.py"
]
|
|
di__vladiate-40 | 577cfae7c7835e89e592af7cd024d6e9de084ed1 | 2017-09-18 22:22:30 | 9d7c5dd83f76ff651a69d085145255c27f8ce33c | diff --git a/setup.py b/setup.py
index 8de8422..62b35f8 100644
--- a/setup.py
+++ b/setup.py
@@ -4,7 +4,7 @@ import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
-__version__ = '0.0.16'
+__version__ = '0.0.17'
class PyTest(TestCommand):
diff --git a/tox.ini b/tox.ini
index 4b85cd7..80f6311 100644
--- a/tox.ini
+++ b/tox.ini
@@ -4,13 +4,29 @@
# and then run "tox" from this directory.
[tox]
-envlist = py27, py35
+envlist = begin,py{27,35,36},lint,end
+
+[testenv:py27]
+basepython = python2.7
+
+[testenv:py35]
+basepython = python3.5
+
+[testenv:py36]
+basepython = python3.6
+
+[testenv:lint]
+commands = flake8
[testenv]
-commands = coverage erase
- coverage run --source=vladiate setup.py test
- coverage combine
- coverage report --include=*
+commands = coverage run --source=vladiate setup.py test
deps =
pytest
coverage
+ flake8
+
+[testenv:begin]
+commands = coverage erase
+
+[testenv:end]
+commands = coverage report -m --include=*
diff --git a/vladiate/validators.py b/vladiate/validators.py
index bbbb18c..a425c2c 100644
--- a/vladiate/validators.py
+++ b/vladiate/validators.py
@@ -185,16 +185,16 @@ class NotEmptyValidator(Validator):
def __init__(self):
self.fail_count = 0
+ self.failed = False
def validate(self, field, row={}):
if field == '':
+ self.failed = True
raise ValidationException("Row has emtpy field in column")
@property
def bad(self):
- # Return an empty set to conform to the protocol. The 'bad' fields
- # would all be empty strings anyways
- return set()
+ return self.failed
class Ignore(Validator):
diff --git a/vladiate/vlad.py b/vladiate/vlad.py
index b0eb438..0233152 100644
--- a/vladiate/vlad.py
+++ b/vladiate/vlad.py
@@ -41,14 +41,24 @@ class Vlad(object):
" {} failed {} time(s) ({:.1%}) on field: '{}'".format(
validator.__class__.__name__, validator.fail_count,
validator.fail_count / self.line_count, field_name))
- invalid = list(validator.bad)
- shown = ["'{}'".format(field) for field in invalid[:99]]
- hidden = ["'{}'".format(field) for field in invalid[99:]]
- self.logger.error(
- " Invalid fields: [{}]".format(", ".join(shown)))
- if hidden:
+ try:
+ # If self.bad is iterable, it contains the fields which
+ # caused it to fail
+ invalid = list(validator.bad)
+ shown = [
+ "'{}'".format(field) for field in invalid[:99]
+ ]
+ hidden = [
+ "'{}'".format(field)
+ for field in invalid[99:]
+ ]
self.logger.error(
- " ({} more suppressed)".format(len(hidden)))
+ " Invalid fields: [{}]".format(", ".join(shown)))
+ if hidden:
+ self.logger.error(
+ " ({} more suppressed)".format(len(hidden)))
+ except TypeError:
+ pass
def _log_missing_validators(self):
self.logger.error(" Missing validators for:")
| NotEmptyValidator minimal logging
NotEmptyValidator always returns an empty set for it's bad property regardless of failure causing the Vlad class to return False and log the general "Failed :(" message without an indication of the field that failed or the times it failed. Solution proposed below avoids repetition of empty strings in logger output while providing logging on par with the other Validators.
```python
class NotEmptyValidator(Validator):
''' Validates that a field is not empty '''
def __init__(self):
self.fail_count = 0
self.empty = set([])
def validate(self, field, row={}):
if field == '':
self.empty.add(field)
raise ValidationException("Row has empty field in column")
@property
def bad(self):
return self.empty
````
| di/vladiate | diff --git a/vladiate/test/test_validators.py b/vladiate/test/test_validators.py
index 66d431d..7b80686 100644
--- a/vladiate/test/test_validators.py
+++ b/vladiate/test/test_validators.py
@@ -196,7 +196,7 @@ def test_non_empty_validator_fails():
with pytest.raises(ValidationException):
validator.validate("")
- assert validator.bad == set()
+ assert validator.bad is True
def test_ignore_validator():
diff --git a/vladiate/test/test_vlads.py b/vladiate/test/test_vlads.py
index fd55f94..4b077ae 100644
--- a/vladiate/test/test_vlads.py
+++ b/vladiate/test/test_vlads.py
@@ -3,7 +3,8 @@ import pytest
from ..vlad import Vlad
from ..inputs import LocalFile, String
from ..validators import (
- EmptyValidator, FloatValidator, SetValidator, UniqueValidator
+ EmptyValidator, FloatValidator, NotEmptyValidator, SetValidator,
+ UniqueValidator,
)
@@ -144,3 +145,21 @@ def test_ignore_missing_validators():
assert vlad.validate()
assert vlad.missing_validators == {'Column B'}
+
+
+def test_when_bad_is_non_iterable():
+ source = String('Column A,Column B\n,foo')
+
+ class TestVlad(Vlad):
+ validators = {
+ 'Column A': [NotEmptyValidator()],
+ 'Column B': [NotEmptyValidator()],
+ }
+
+ vlad = TestVlad(source=source)
+
+ assert not vlad.validate()
+ assert vlad.validators['Column A'][0].fail_count == 1
+ assert vlad.validators['Column A'][0].bad
+ assert vlad.validators['Column B'][0].fail_count == 0
+ assert not vlad.validators['Column B'][0].bad
| {
"commit_name": "merge_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": 0
},
"num_modified_files": 4
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[dev]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pretend",
"pytest",
"flake8"
],
"pre_install": [],
"python": "3.9",
"reqs_path": null,
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | boto==2.49.0
exceptiongroup==1.2.2
flake8==7.2.0
iniconfig==2.1.0
mccabe==0.7.0
packaging==24.2
pluggy==1.5.0
pretend==1.0.9
pycodestyle==2.13.0
pyflakes==3.3.2
pytest==8.3.5
tomli==2.2.1
-e git+https://github.com/di/vladiate.git@577cfae7c7835e89e592af7cd024d6e9de084ed1#egg=vladiate
| name: vladiate
channels:
- defaults
- https://repo.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:
- boto==2.49.0
- exceptiongroup==1.2.2
- flake8==7.2.0
- iniconfig==2.1.0
- mccabe==0.7.0
- packaging==24.2
- pluggy==1.5.0
- pretend==1.0.9
- pycodestyle==2.13.0
- pyflakes==3.3.2
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/vladiate
| [
"vladiate/test/test_validators.py::test_non_empty_validator_fails",
"vladiate/test/test_vlads.py::test_when_bad_is_non_iterable"
]
| []
| [
"vladiate/test/test_validators.py::test_cast_validator",
"vladiate/test/test_validators.py::test_float_validator_works[42]",
"vladiate/test/test_validators.py::test_float_validator_works[42.0]",
"vladiate/test/test_validators.py::test_float_validator_works[-42.0]",
"vladiate/test/test_validators.py::test_float_validator_fails[foo]",
"vladiate/test/test_validators.py::test_float_validator_fails[",
"vladiate/test/test_validators.py::test_float_validator_fails[7..0]",
"vladiate/test/test_validators.py::test_float_validator_fails[4,200]",
"vladiate/test/test_validators.py::test_int_validator_works[42]",
"vladiate/test/test_validators.py::test_int_validator_fails[foo]",
"vladiate/test/test_validators.py::test_int_validator_fails[",
"vladiate/test/test_validators.py::test_int_validator_fails[7..0]",
"vladiate/test/test_validators.py::test_int_validator_fails[4,200]",
"vladiate/test/test_validators.py::test_int_validator_fails[42.0]",
"vladiate/test/test_validators.py::test_int_validator_fails[-42.0]",
"vladiate/test/test_validators.py::test_set_validator_works[field_set0-foo]",
"vladiate/test/test_validators.py::test_set_validator_works[field_set1-foo]",
"vladiate/test/test_validators.py::test_set_validator_empty_ok",
"vladiate/test/test_validators.py::test_set_validator_fails[field_set0-bar]",
"vladiate/test/test_validators.py::test_set_validator_fails[field_set1-bar]",
"vladiate/test/test_validators.py::test_set_validator_fails[field_set2-baz]",
"vladiate/test/test_validators.py::test_unique_validator_works[fields0-row0-unique_with0]",
"vladiate/test/test_validators.py::test_unique_validator_works[fields1-row1-unique_with1]",
"vladiate/test/test_validators.py::test_unique_validator_works[fields2-row2-unique_with2]",
"vladiate/test/test_validators.py::test_unique_validator_works[fields3-row3-unique_with3]",
"vladiate/test/test_validators.py::test_unique_validator_fails[fields0-row0-unique_with0-ValidationException-bad0]",
"vladiate/test/test_validators.py::test_unique_validator_fails[fields1-row1-unique_with1-ValidationException-bad1]",
"vladiate/test/test_validators.py::test_unique_validator_fails[fields2-row2-unique_with2-BadValidatorException-bad2]",
"vladiate/test/test_validators.py::test_regex_validator_works[foo.*-foo]",
"vladiate/test/test_validators.py::test_regex_validator_works[foo.*-foobar]",
"vladiate/test/test_validators.py::test_regex_validator_allows_empty",
"vladiate/test/test_validators.py::test_regex_validator_fails[foo.*-afoo]",
"vladiate/test/test_validators.py::test_regex_validator_fails[^$-foo]",
"vladiate/test/test_validators.py::test_range_validator_works",
"vladiate/test/test_validators.py::test_range_validator_fails",
"vladiate/test/test_validators.py::test_range_validator_handles_bad_values",
"vladiate/test/test_validators.py::test_empty_validator_works",
"vladiate/test/test_validators.py::test_empty_validator_fails",
"vladiate/test/test_validators.py::test_non_empty_validator_works",
"vladiate/test/test_validators.py::test_ignore_validator",
"vladiate/test/test_validators.py::test_base_class_raises",
"vladiate/test/test_vlads.py::test_initialize_vlad",
"vladiate/test/test_vlads.py::test_initialize_vlad_with_alternative_delimiter",
"vladiate/test/test_vlads.py::test_initialize_vlad_no_source",
"vladiate/test/test_vlads.py::test_unused_validator_fails_validation",
"vladiate/test/test_vlads.py::test_validators_in_class_variable_are_used",
"vladiate/test/test_vlads.py::test_missing_validators",
"vladiate/test/test_vlads.py::test_no_fieldnames",
"vladiate/test/test_vlads.py::test_fails_validation",
"vladiate/test/test_vlads.py::test_gt_99_failures",
"vladiate/test/test_vlads.py::test_ignore_missing_validators"
]
| []
| MIT License | 1,684 | [
"setup.py",
"vladiate/validators.py",
"tox.ini",
"vladiate/vlad.py"
]
| [
"setup.py",
"vladiate/validators.py",
"tox.ini",
"vladiate/vlad.py"
]
|
|
Clinical-Genomics__scout-615 | 8e1c3acd430a1f57f712aac29847e71cac8308f3 | 2017-09-19 07:25:28 | 8e1c3acd430a1f57f712aac29847e71cac8308f3 | diff --git a/scout/adapter/mongo/query.py b/scout/adapter/mongo/query.py
index 055963b99..267969642 100644
--- a/scout/adapter/mongo/query.py
+++ b/scout/adapter/mongo/query.py
@@ -13,11 +13,13 @@ class QueryHandler(object):
'thousand_genomes_frequency': float,
'exac_frequency': float,
'cadd_score': float,
+ 'cadd_inclusive": boolean,
'genetic_models': list(str),
'hgnc_symbols': list,
'region_annotations': list,
'functional_annotations': list,
'clinsig': list,
+ 'clinsig_confident_always_returned': boolean,
'variant_type': str(('research', 'clinical')),
'chrom': str,
'start': int,
@@ -45,8 +47,27 @@ class QueryHandler(object):
mongo_query['variant_type'] = query.get('variant_type', 'clinical')
logger.debug("Set variant type to %s", mongo_query['variant_type'])
- mongo_query['$and'] = []
+ # Requests to filter based on gene panels, hgnc_symbols or
+ # coordinate ranges must always be honored. They are always added to
+ # query as top level, implicit '$and'.
+ if query.get('hgnc_symbols') and query.get('gene_panels'):
+ gene_query = [
+ {'hgnc_symbols': {'$in': query['hgnc_symbols']}},
+ {'panels': {'$in': query['gene_panels']}}
+ ]
+ mongo_query['$or']=gene_query
+ else:
+ if query.get('hgnc_symbols'):
+ hgnc_symbols = query['hgnc_symbols']
+ mongo_query['hgnc_symbols'] = {'$in': hgnc_symbols}
+ logger.debug("Adding hgnc_symbols: %s to query" %
+ ', '.join(hgnc_symbols))
+
+ if query.get('gene_panels'):
+ gene_panels = query['gene_panels']
+ mongo_query['panels'] = {'$in': gene_panels}
+
if query.get('chrom'):
chromosome = query['chrom']
mongo_query['chromosome'] = chromosome
@@ -59,6 +80,20 @@ class QueryHandler(object):
mongo_query['end'] = {
'$gte': int(query['start'])
}
+
+ mongo_query_minor = []
+
+ # A minor, excluding filter criteria will hide variants in general,
+ # but can be overridden by an including, major filter criteria
+ # such as a Pathogenic ClinSig.
+ # If there are no major criteria given, all minor criteria are added as a
+ # top level '$and' to the query.
+ # If there is only one major criteria given without any minor, it will also be
+ # added as a top level '$and'.
+ # Otherwise, major criteria are added as a high level '$or' and all minor criteria
+ # are joined together with them as a single lower level '$and'.
+
+ mongo_query_minor = []
if query.get('thousand_genomes_frequency') is not None:
thousandg = query.get('thousand_genomes_frequency')
@@ -69,7 +104,7 @@ class QueryHandler(object):
else:
# Replace comma with dot
- mongo_query['$and'].append(
+ mongo_query_minor.append(
{
'$or': [
{
@@ -94,7 +129,7 @@ class QueryHandler(object):
if exac == '-1':
mongo_query['exac_frequency'] = {'$exists': False}
else:
- mongo_query['$and'].append({
+ mongo_query_minor.append({
'$or': [
{'exac_frequency': {'$lt': float(exac)}},
{'exac_frequency': {'$exists': False}}
@@ -102,7 +137,7 @@ class QueryHandler(object):
})
if query.get('local_obs') is not None:
- mongo_query['$and'].append({
+ mongo_query_minor.append({
'$or': [
{'local_obs_old': {'$exists': False}},
{'local_obs_old': {'$lt': query['local_obs'] + 1}},
@@ -122,44 +157,25 @@ class QueryHandler(object):
]}
logger.debug("Adding cadd inclusive to query")
- mongo_query['$and'].append(cadd_query)
+ mongo_query_minor.append(cadd_query)
-
if query.get('genetic_models'):
models = query['genetic_models']
- mongo_query['genetic_models'] = {'$in': models}
+ mongo_query_minor.append({'genetic_models': {'$in': models}})
logger.debug("Adding genetic_models: %s to query" %
', '.join(models))
- if query.get('hgnc_symbols') and query.get('gene_panels'):
- gene_query = {
- '$or': [
- {'hgnc_symbols': {'$in': query['hgnc_symbols']}},
- {'panels': {'$in': query['gene_panels']}}
- ]}
- mongo_query['$and'].append(gene_query)
- else:
- if query.get('hgnc_symbols'):
- hgnc_symbols = query['hgnc_symbols']
- mongo_query['hgnc_symbols'] = {'$in': hgnc_symbols}
- logger.debug("Adding hgnc_symbols: %s to query" %
- ', '.join(hgnc_symbols))
-
- if query.get('gene_panels'):
- gene_panels = query['gene_panels']
- mongo_query['panels'] = {'$in': gene_panels}
-
if query.get('functional_annotations'):
functional = query['functional_annotations']
- mongo_query['genes.functional_annotation'] = {'$in': functional}
+ mongo_query_minor.append({'genes.functional_annotation': {'$in': functional}})
logger.debug("Adding functional_annotations %s to query" %
', '.join(functional))
if query.get('region_annotations'):
region = query['region_annotations']
- mongo_query['genes.region_annotation'] = {'$in': region}
+ mongo_query_minor.append({'genes.region_annotation': {'$in': region}})
logger.debug("Adding region_annotations %s to query" %
', '.join(region))
@@ -178,24 +194,17 @@ class QueryHandler(object):
]}
logger.debug("Adding size inclusive to query.")
- mongo_query['$and'].append(size_query)
+ mongo_query_minor.append(size_query)
if query.get('svtype'):
svtype = query['svtype']
- mongo_query['sub_category'] = {'$in': svtype}
+ mongo_query_minor.append({'sub_category': {'$in': svtype}})
logger.debug("Adding SV_type %s to query" %
', '.join(svtype))
- if query.get('clinsig'):
- logger.debug("add CLINSIG filter for rank: %s" %
- ', '.join(query['clinsig']))
- rank = [int(item) for item in query['clinsig']]
-
- mongo_query['clnsig.value'] = {'$in': rank}
-
if query.get('depth'):
logger.debug("add depth filter")
- mongo_query['$and'].append({
+ mongo_query_minor.append({
'tumor.read_depth': {
'$gt': query.get('depth'),
}
@@ -203,7 +212,7 @@ class QueryHandler(object):
if query.get('alt_count'):
logger.debug("add min alt count filter")
- mongo_query['$and'].append({
+ mongo_query_minor.append({
'tumor.alt_depth': {
'$gt': query.get('alt_count'),
}
@@ -211,20 +220,57 @@ class QueryHandler(object):
if query.get('control_frequency'):
logger.debug("add minimum control frequency filter")
- mongo_query['$and'].append({
+ mongo_query_minor.append({
'normal.alt_freq': {
'$lt': float(query.get('control_frequency')),
}
})
+ mongo_query_major = None
+
+ # Given a request to always return confident clinical variants,
+ # add the clnsig query as a major criteria, but only
+ # trust clnsig entries with trusted revstat levels.
+
+ if query.get('clinsig'):
+ rank = [int(item) for item in query['clinsig']]
+
+ if query.get('clinsig_confident_always_returned') == True:
+
+ trusted_revision_level = ['mult', 'single', 'exp', 'guideline']
+
+ mongo_query_major = { "clnsig":
+ {
+ '$elemMatch': { 'value':
+ { '$in': rank },
+ 'revstat':
+ { '$in': trusted_revision_level }
+ }
+ }
+ }
+
+ else:
+ logger.debug("add CLINSIG filter for rank: %s" %
+ ', '.join(str(query['clinsig'])))
+ if mongo_query_minor:
+ mongo_query_minor.append({'clnsig.value': {'$in': rank}})
+ else:
+ # if this is the only minor critera, use implicit and.
+ mongo_query['clnsig.value'] = {'$in': rank}
+
+ if mongo_query_minor and mongo_query_major:
+ mongo_query['$or'] = [ {'$and': mongo_query_minor }, mongo_query_major ]
+ elif mongo_query_minor:
+ mongo_query['$and'] = mongo_query_minor
+ elif mongo_query_major:
+ mongo_query['clnsig'] = mongo_query_major['clnsig']
+
if variant_ids:
mongo_query['variant_id'] = {'$in': variant_ids}
logger.debug("Adding variant_ids %s to query" % ', '.join(variant_ids))
-
- if not mongo_query['$and']:
- del mongo_query['$and']
-
+
+
logger.debug("mongo query: %s", mongo_query)
return mongo_query
diff --git a/scout/server/blueprints/variants/forms.py b/scout/server/blueprints/variants/forms.py
index b5c6cd20b..bab4716d7 100644
--- a/scout/server/blueprints/variants/forms.py
+++ b/scout/server/blueprints/variants/forms.py
@@ -55,8 +55,9 @@ class FiltersForm(FlaskForm):
genetic_models = SelectMultipleField(choices=GENETIC_MODELS)
cadd_score = BetterDecimalField('CADD', places=2)
- cadd_inclusive = BooleanField()
+ cadd_inclusive = BooleanField('CADD inclusive')
clinsig = SelectMultipleField('CLINSIG', choices=CLINSIG_OPTIONS)
+ clinsig_confident_always_returned = BooleanField('All CLINSIG confident')
thousand_genomes_frequency = BetterDecimalField('1000 Genomes', places=2)
exac_frequency = BetterDecimalField('ExAC', places=2)
@@ -79,8 +80,9 @@ class SvFiltersForm(FlaskForm):
genetic_models = SelectMultipleField(choices=GENETIC_MODELS)
cadd_score = BetterDecimalField('CADD', places=2)
- cadd_inclusive = BooleanField()
+ cadd_inclusive = BooleanField('CADD inclusive')
clinsig = SelectMultipleField('CLINSIG', choices=CLINSIG_OPTIONS)
+ clinsig_confident_always_returned = BooleanField('All CLINSIG confident')
chrom = TextField('Chromosome')
size = TextField('Length')
diff --git a/scout/server/blueprints/variants/templates/variants/variants.html b/scout/server/blueprints/variants/templates/variants/variants.html
index 2a769f604..0f21f0919 100644
--- a/scout/server/blueprints/variants/templates/variants/variants.html
+++ b/scout/server/blueprints/variants/templates/variants/variants.html
@@ -217,11 +217,11 @@
{{ form.hgnc_symbols.label(class="control-label") }}
{{ form.hgnc_symbols(class="form-control") }}
</div>
- <div class="col-xs-3">
+ <div class="col-xs-2">
{{ form.cadd_score.label(class="control-label") }}
{{ form.cadd_score(class="form-control") }}
</div>
- <div class="col-xs-3">
+ <div class="col-xs-2">
{{ form.cadd_inclusive.label(class="control-label") }}
<div>{{ form.cadd_inclusive() }}</div>
</div>
@@ -229,6 +229,10 @@
{{ form.clinsig.label(class="control-label") }}
{{ form.clinsig(class="form-control") }}
</div>
+ <div class="col-xs-2">
+ {{ form.clinsig_confident_always_returned.label(class="control-label") }}
+ <div>{{ form.clinsig_confident_always_returned() }}</div>
+ </div>
</div>
</div>
<div class="form-group">
@@ -256,6 +260,8 @@
case_name=case.display_name, variant_type=form.variant_type.data,
functional_annotations=severe_so_terms,
region_annotations=['exonic', 'splicing'],
+ clinsig=[4,5],
+ clinsig_confident_always_returned=True,
thousand_genomes_frequency=institute.frequency_cutoff,
gene_panels=form.data.get('gene_panels')) }}"
class="btn btn-default form-control">
| Always allow ClinVar Pathogenic, Likely Pathogenic through Clinical filter
It is counterintuitive to find known clinical pathogenic mutation filtered out as a result of a "clinical filter". Also apply to local "marked causatives" - but there we already have a sufficient mechanism? | Clinical-Genomics/scout | diff --git a/tests/adapter/test_query.py b/tests/adapter/test_query.py
index 2d12aa555..d6c424276 100644
--- a/tests/adapter/test_query.py
+++ b/tests/adapter/test_query.py
@@ -91,6 +91,101 @@ def test_build_thousand_g_and_cadd(adapter):
}
]
+def test_build_clinsig(adapter):
+ case_id = 'cust000'
+ clinsig_items = [ 3, 4, 5 ]
+ query = {'clinsig': clinsig_items}
+
+ mongo_query = adapter.build_query(case_id, query=query)
+
+ assert mongo_query['clnsig.value'] == {
+ '$in': clinsig_items
+ }
+
+def test_build_clinsig_filter(adapter):
+ case_id = 'cust000'
+ clinsig_items = [ 4, 5 ]
+ region_annotation = ['exonic', 'splicing']
+
+ query = {'region_annotations': region_annotation,
+ 'clinsig': clinsig_items }
+
+ mongo_query = adapter.build_query(case_id, query=query)
+
+ assert mongo_query['$and'] == [
+ { 'genes.region_annotation':
+ {'$in': region_annotation }
+ },
+ { 'clnsig.value':
+ { '$in': clinsig_items }
+ }
+ ]
+
+def test_build_clinsig_always(adapter):
+ case_id = 'cust000'
+ clinsig_confident_always_returned = True
+ clinsig_items = [ 4, 5 ]
+ region_annotation = ['exonic', 'splicing']
+ freq=0.01
+
+ query = {'region_annotations': region_annotation,
+ 'clinsig': clinsig_items,
+ 'clinsig_confident_always_returned': clinsig_confident_always_returned,
+ 'thousand_genomes_frequency': freq
+ }
+
+ mongo_query = adapter.build_query(case_id, query=query)
+
+ assert mongo_query['$or'] == [
+ { '$and':
+ [ {
+ '$or':[
+ {'thousand_genomes_frequency': {'$lt': freq}},
+ {'thousand_genomes_frequency': {'$exists': False}}
+ ]
+ },
+ {'genes.region_annotation':
+ {'$in': region_annotation }
+ },
+ ]},
+ { 'clnsig':
+ {
+ '$elemMatch': { 'value':
+ { '$in' : clinsig_items },
+ 'revstat':
+ { '$in' : ['mult',
+ 'single',
+ 'exp',
+ 'guideline']
+ }
+ }
+ }
+ }
+ ]
+
+def test_build_clinsig_always_only(adapter):
+ case_id = 'cust000'
+ clinsig_confident_always_returned = True
+ clinsig_items = [ 4, 5 ]
+
+ query = {'clinsig': clinsig_items,
+ 'clinsig_confident_always_returned': clinsig_confident_always_returned
+ }
+
+ mongo_query = adapter.build_query(case_id, query=query)
+
+ assert mongo_query['clnsig'] == {
+ '$elemMatch': { 'value':
+ { '$in' : clinsig_items },
+ 'revstat':
+ { '$in' : ['mult',
+ 'single',
+ 'exp',
+ 'guideline']
+ }
+ }
+ }
+
def test_build_chrom(adapter):
case_id = 'cust000'
chrom = '1'
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 3
} | 3.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"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"
} | babel==2.17.0
blinker==1.9.0
cachelib==0.13.0
certifi==2025.1.31
charset-normalizer==3.4.1
click==8.1.8
coloredlogs==15.0.1
Cython==3.0.12
cyvcf2==0.31.1
dnspython==2.7.0
dominate==2.9.1
exceptiongroup==1.2.2
Flask==3.1.0
flask-babel==4.0.0
Flask-Bootstrap==3.3.7.1
Flask-DebugToolbar==0.16.0
Flask-Login==0.6.3
Flask-Mail==0.10.0
Flask-Markdown==0.3
Flask-OAuthlib==0.9.6
Flask-PyMongo==3.0.1
Flask-WTF==1.2.2
humanfriendly==10.0
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
intervaltree==3.1.0
itsdangerous==2.2.0
Jinja2==3.1.6
livereload==2.7.1
loqusdb==2.6.0
Markdown==3.7
MarkupSafe==3.0.2
mongo-adapter==0.3.3
mongomock==4.3.0
numpy==2.0.2
oauthlib==2.1.0
packaging==24.2
path==17.1.0
path.py==12.5.0
ped-parser==1.6.6
pluggy==1.5.0
pymongo==4.11.3
pytest==8.3.5
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.2
query-phenomizer==1.2.1
requests==2.32.3
requests-oauthlib==1.1.0
-e git+https://github.com/Clinical-Genomics/scout.git@8e1c3acd430a1f57f712aac29847e71cac8308f3#egg=scout_browser
sentinels==1.0.0
six==1.17.0
sortedcontainers==2.4.0
tomli==2.2.1
tornado==6.4.2
urllib3==2.3.0
vcftoolbox==1.5.1
visitor==0.1.3
Werkzeug==3.1.3
WTForms==3.2.1
zipp==3.21.0
| name: scout
channels:
- defaults
- https://repo.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:
- babel==2.17.0
- blinker==1.9.0
- cachelib==0.13.0
- certifi==2025.1.31
- charset-normalizer==3.4.1
- click==8.1.8
- coloredlogs==15.0.1
- cython==3.0.12
- cyvcf2==0.31.1
- dnspython==2.7.0
- dominate==2.9.1
- exceptiongroup==1.2.2
- flask==3.1.0
- flask-babel==4.0.0
- flask-bootstrap==3.3.7.1
- flask-debugtoolbar==0.16.0
- flask-login==0.6.3
- flask-mail==0.10.0
- flask-markdown==0.3
- flask-oauthlib==0.9.6
- flask-pymongo==3.0.1
- flask-wtf==1.2.2
- humanfriendly==10.0
- idna==3.10
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- intervaltree==3.1.0
- itsdangerous==2.2.0
- jinja2==3.1.6
- livereload==2.7.1
- loqusdb==2.6.0
- markdown==3.7
- markupsafe==3.0.2
- mongo-adapter==0.3.3
- mongomock==4.3.0
- numpy==2.0.2
- oauthlib==2.1.0
- packaging==24.2
- path==17.1.0
- path-py==12.5.0
- ped-parser==1.6.6
- pluggy==1.5.0
- pymongo==4.11.3
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==6.0.2
- query-phenomizer==1.2.1
- requests==2.32.3
- requests-oauthlib==1.1.0
- sentinels==1.0.0
- six==1.17.0
- sortedcontainers==2.4.0
- tomli==2.2.1
- tornado==6.4.2
- urllib3==2.3.0
- vcftoolbox==1.5.1
- visitor==0.1.3
- werkzeug==3.1.3
- wtforms==3.2.1
- zipp==3.21.0
prefix: /opt/conda/envs/scout
| [
"tests/adapter/test_query.py::test_build_clinsig",
"tests/adapter/test_query.py::test_build_clinsig_filter",
"tests/adapter/test_query.py::test_build_clinsig_always",
"tests/adapter/test_query.py::test_build_clinsig_always_only"
]
| []
| [
"tests/adapter/test_query.py::test_build_query",
"tests/adapter/test_query.py::test_build_thousand_g_query",
"tests/adapter/test_query.py::test_build_non_existing_thousand_g",
"tests/adapter/test_query.py::test_build_cadd_exclusive",
"tests/adapter/test_query.py::test_build_cadd_inclusive",
"tests/adapter/test_query.py::test_build_thousand_g_and_cadd",
"tests/adapter/test_query.py::test_build_chrom",
"tests/adapter/test_query.py::test_build_range"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,685 | [
"scout/adapter/mongo/query.py",
"scout/server/blueprints/variants/forms.py",
"scout/server/blueprints/variants/templates/variants/variants.html"
]
| [
"scout/adapter/mongo/query.py",
"scout/server/blueprints/variants/forms.py",
"scout/server/blueprints/variants/templates/variants/variants.html"
]
|
|
ESSS__conda-devenv-57 | 7867067acadb89f7da61af330d85caa31b284dd8 | 2017-09-19 11:13:53 | 7867067acadb89f7da61af330d85caa31b284dd8 | diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
index 2be5977..ddda924 100644
--- a/CONTRIBUTING.rst
+++ b/CONTRIBUTING.rst
@@ -55,9 +55,9 @@ If you are proposing a feature:
Get Started!
------------
-Ready to contribute? Here's how to set up `conda-devenv` for local development.
+Ready to contribute? Here's how to set up ``conda-devenv`` for local development.
-1. Fork the `conda-devenv` repo on GitHub.
+1. Fork the ``conda-devenv`` repo on GitHub.
2. Clone your fork locally::
$ git clone [email protected]:your_name_here/conda-devenv.git
@@ -65,7 +65,8 @@ Ready to contribute? Here's how to set up `conda-devenv` for local development.
3. Create a new conda environment for developing::
$ conda create -n devenv --file requirements_dev.txt
- $ conda develop conda_devenv
+ $ source activate devenv
+ $ pip install -e .
4. Create a branch for local development::
diff --git a/conda_devenv/devenv.py b/conda_devenv/devenv.py
index 8591c61..4e43d3a 100644
--- a/conda_devenv/devenv.py
+++ b/conda_devenv/devenv.py
@@ -48,7 +48,7 @@ def handle_includes(root_filename, root_yaml):
))
with open(included_filename, "r") as f:
jinja_contents = render_jinja(f.read(), included_filename)
- included_yaml_dict = yaml.load(jinja_contents)
+ included_yaml_dict = yaml.safe_load(jinja_contents)
if included_yaml_dict is None:
raise ValueError("The file '{included_filename}' which was"
" included by '{filename}' is empty."
@@ -329,7 +329,6 @@ def write_activate_deactivate_scripts(args, conda_yaml_dict, environment):
info = json.loads(info)
envs = info["envs"]
- env_directory = None
for env in envs:
if os.path.basename(env) == env_name:
env_directory = env
@@ -376,12 +375,21 @@ def main(args=None):
"includes the 'environment' section.", action="store_true")
parser.add_argument("--no-prune", help="Don't pass --prune flag to conda-env.", action="store_true")
parser.add_argument("--output-file", nargs="?", help="Output filename.")
- parser.add_argument("--quiet", action="store_true", default=False)
+ parser.add_argument("--quiet", action="store_true", default=False, help="Do not show progress")
+ parser.add_argument("--version", action="store_true", default=False, help="Show version and exit")
args = parser.parse_args(args)
+ if args.version:
+ from ._version import version
+ print('conda-devenv version {0}'.format(version))
+ return 0
+
filename = args.file
filename = os.path.abspath(filename)
+ if not os.path.isfile(filename):
+ print('File "{0}" does not exist.'.format(filename), file=sys.stderr)
+ return 1
is_devenv_input_file = filename.endswith('.devenv.yml')
if is_devenv_input_file:
diff --git a/requirements_dev.txt b/requirements_dev.txt
index a41d034..c2c73e0 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -8,6 +8,6 @@ coverage
Sphinx
cryptography
PyYAML
-pytest
+pytest >= 3
pytest-datadir >= 1.0
pytest-mock
diff --git a/setup.py b/setup.py
index c8e4a86..158e834 100644
--- a/setup.py
+++ b/setup.py
@@ -52,6 +52,7 @@ setup(
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
+ 'Programming Language :: Python :: 3.6',
],
test_suite='tests',
tests_require=test_requirements
| Add --version flag | ESSS/conda-devenv | diff --git a/tests/test_main.py b/tests/test_main.py
index feb2425..f1e1a27 100644
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -90,3 +90,27 @@ def test_print_full(tmpdir, capsys):
assert 'environment:' in out
assert 'PYTHONPATH:' in out
+
+def test_version(capsys):
+ """
+ Test --version flag.
+ """
+ from conda_devenv._version import version
+ assert devenv.main(['--version']) == 0
+ out, err = capsys.readouterr()
+ assert err == ''
+ assert version in out
+
+ import conda_devenv
+ assert conda_devenv.__version__ == version
+
+
[email protected]('explicit_file', [True, False])
+def test_error_message_environment_file_not_found(capsys, tmpdir, explicit_file, monkeypatch):
+ monkeypatch.chdir(str(tmpdir))
+ args = ['--file', 'invalid.devenv.yml'] if explicit_file else []
+ expected_name = 'invalid.devenv.yml' if explicit_file else 'environment.devenv.yml'
+ assert devenv.main(args) == 1
+ out, err = capsys.readouterr()
+ assert out == ''
+ assert err == 'File "{0}" does not exist.\n'.format(str(tmpdir / expected_name))
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 1
},
"num_modified_files": 4
} | 0.9 | {
"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",
"pytest-datadir"
],
"pre_install": [],
"python": "3.6",
"reqs_path": [
"requirements_dev.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
bump2version==1.0.1
bumpversion==0.6.0
certifi==2021.5.30
cffi==1.15.1
charset-normalizer==2.0.12
-e git+https://github.com/ESSS/conda-devenv.git@7867067acadb89f7da61af330d85caa31b284dd8#egg=conda_devenv
coverage==6.2
cryptography==40.0.2
distlib==0.3.9
docutils==0.17.1
filelock==3.4.1
flake8==5.0.4
idna==3.10
imagesize==1.4.1
importlib-metadata==4.2.0
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mccabe==0.7.0
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pycparser==2.21
pyflakes==2.5.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytest-datadir==1.4.1
pytest-mock==3.6.1
pytz==2025.2
PyYAML==6.0.1
requests==2.27.1
six==1.17.0
snowballstemmer==2.2.0
Sphinx==4.3.2
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.16.2
watchdog==2.3.1
zipp==3.6.0
| name: conda-devenv
channels:
- defaults
- https://repo.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
- bump2version==1.0.1
- bumpversion==0.6.0
- cffi==1.15.1
- charset-normalizer==2.0.12
- coverage==6.2
- cryptography==40.0.2
- distlib==0.3.9
- docutils==0.17.1
- filelock==3.4.1
- flake8==5.0.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.2.0
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mccabe==0.7.0
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pycparser==2.21
- pyflakes==2.5.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-datadir==1.4.1
- pytest-mock==3.6.1
- pytz==2025.2
- pyyaml==6.0.1
- requests==2.27.1
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==4.3.2
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.16.2
- watchdog==2.3.1
- zipp==3.6.0
prefix: /opt/conda/envs/conda-devenv
| [
"tests/test_main.py::test_version",
"tests/test_main.py::test_error_message_environment_file_not_found[True]",
"tests/test_main.py::test_error_message_environment_file_not_found[False]"
]
| [
"tests/test_main.py::test_handle_input_file[True-environment.devenv.yml-1]",
"tests/test_main.py::test_handle_input_file[False-environment.devenv.yml-1]",
"tests/test_main.py::test_print[environment.devenv.yml]",
"tests/test_main.py::test_print_full"
]
| [
"tests/test_main.py::test_handle_input_file[True-environment.yml-0]",
"tests/test_main.py::test_handle_input_file[False-environment.yml-0]",
"tests/test_main.py::test_print[environment.yml]"
]
| []
| MIT License | 1,686 | [
"setup.py",
"requirements_dev.txt",
"conda_devenv/devenv.py",
"CONTRIBUTING.rst"
]
| [
"setup.py",
"requirements_dev.txt",
"conda_devenv/devenv.py",
"CONTRIBUTING.rst"
]
|
|
CORE-GATECH-GROUP__serpent-tools-4 | 606a90d665a15a16c437dd1fb72ef014aa480142 | 2017-09-19 15:34:09 | 606a90d665a15a16c437dd1fb72ef014aa480142 | diff --git a/serpentTools/__init__.py b/serpentTools/__init__.py
index 8af8d0f..d38090d 100644
--- a/serpentTools/__init__.py
+++ b/serpentTools/__init__.py
@@ -1,7 +1,7 @@
from serpentTools import settings
from serpentTools import parsers
-__version__ = '0.1.1'
+__version__ = '0.1.2'
# List TODOS/feature requests here for now
# Messages/Errors
diff --git a/serpentTools/objects/__init__.py b/serpentTools/objects/__init__.py
index 42ee6c0..8f2e2cd 100644
--- a/serpentTools/objects/__init__.py
+++ b/serpentTools/objects/__init__.py
@@ -146,8 +146,18 @@ class DepletedMaterial(_SupportingObject):
AttributeError
If the names of the isotopes have not been obtained and specific
isotopes have been requested
+ KeyError
+ If at least one of the days requested is not present
"""
- returnX = timePoints is None
+ if timePoints is not None:
+ returnX = False
+ timeCheck = self._checkTimePoints(xUnits, timePoints)
+ if any(timeCheck):
+ raise KeyError('The following times were not present in file {}'
+ '\n{}'.format(self._container.filePath,
+ ', '.join(timeCheck)))
+ else:
+ returnX = True
if names and 'names' not in self._container.metadata:
raise AttributeError('Parser {} has not stored the isotope names.'
.format(self._container))
@@ -164,6 +174,12 @@ class DepletedMaterial(_SupportingObject):
return yVals, xVals
return yVals
+ def _checkTimePoints(self, xUnits, timePoints):
+ valid = self[xUnits]
+ badPoints = [str(time) for time in timePoints if time not in valid]
+ return badPoints
+
+
def _getXSlice(self, xUnits, timePoints):
allX = self[xUnits]
if timePoints is not None:
diff --git a/serpentTools/parsers/branching.py b/serpentTools/parsers/branching.py
index 6817810..8efd2f1 100644
--- a/serpentTools/parsers/branching.py
+++ b/serpentTools/parsers/branching.py
@@ -1,9 +1,9 @@
"""Parser responsible for reading the ``*coe.m`` files"""
-from serpentTools.parsers import _BaseReader
+from serpentTools.objects.readers import BaseReader
-class BranchingReader(_BaseReader):
+class BranchingReader(BaseReader):
"""
Parser responsible for reading and working with automated branching files.
diff --git a/serpentTools/parsers/bumat.py b/serpentTools/parsers/bumat.py
index 70ead0a..27c155b 100644
--- a/serpentTools/parsers/bumat.py
+++ b/serpentTools/parsers/bumat.py
@@ -1,9 +1,9 @@
"""Parser responsible for reading the ``*bumat<n>.m`` files"""
-from serpentTools.parsers import _MaterialReader
+from serpentTools.objects.readers import MaterialReader
-class BumatReader(_MaterialReader):
+class BumatReader(MaterialReader):
"""
Parser responsible for reading and working with burned material files.
diff --git a/serpentTools/parsers/detector.py b/serpentTools/parsers/detector.py
index ea40920..9c4c33c 100644
--- a/serpentTools/parsers/detector.py
+++ b/serpentTools/parsers/detector.py
@@ -1,9 +1,9 @@
"""Parser responsible for reading the ``*det<n>.m`` files"""
-from serpentTools.parsers import _BaseReader
+from serpentTools.objects.readers import BaseReader
-class DetectorReader(_BaseReader):
+class DetectorReader(BaseReader):
"""
Parser responsible for reading and working with detector files.
diff --git a/serpentTools/parsers/fissionMatrix.py b/serpentTools/parsers/fissionMatrix.py
index 58af81d..3923415 100644
--- a/serpentTools/parsers/fissionMatrix.py
+++ b/serpentTools/parsers/fissionMatrix.py
@@ -1,9 +1,9 @@
"""Parser responsible for reading the ``*fmtx<n>.m`` files"""
-from serpentTools.parsers import _BaseReader
+from serpentTools.objects.readers import BaseReader
-class FissionMatrixReader(_BaseReader):
+class FissionMatrixReader(BaseReader):
"""
Parser responsible for reading and working with fission matrix files.
diff --git a/serpentTools/parsers/results.py b/serpentTools/parsers/results.py
index f33b68c..ae4f1ef 100644
--- a/serpentTools/parsers/results.py
+++ b/serpentTools/parsers/results.py
@@ -1,9 +1,9 @@
"""Parser responsible for reading the ``*res.m`` files"""
-from serpentTools.parsers import _BaseReader
+from serpentTools.objects.readers import BaseReader
-class ResultsReader(_BaseReader):
+class ResultsReader(BaseReader):
"""
Parser responsible for reading and working with result files.
| `getXY` for `DepletedMaterial` raises unhelpful value error if days missing from object
If a depleted material is asked to get some quantity for days that are not present, the following error is raised:
```
File "C:\Users\ajohnson400\AppData\Local\Continuum\Anaconda3\lib\site-packages\serpenttools-0.1.1rc0-py3.5.egg\serpentTools\objects\__init__.py", line 162, in getXY
else allY[rowId][:])
ValueError: could not broadcast input array from shape (19) into shape (0)
```
The value of `colIndices` is an empty list for this case. | CORE-GATECH-GROUP/serpent-tools | diff --git a/serpentTools/tests/test_depletion.py b/serpentTools/tests/test_depletion.py
index 0574305..d7f6d52 100644
--- a/serpentTools/tests/test_depletion.py
+++ b/serpentTools/tests/test_depletion.py
@@ -156,6 +156,17 @@ class DepletedMaterialTester(_DepletionTestHelper):
names=['Xe135'])
numpy.testing.assert_equal(actualDays, self.reader.metadata['days'])
+ def test_getXY_raisesError_badTime(self):
+ """Verify that a ValueError is raised for non-present requested days."""
+ badDays = [-1, 0, 50]
+ with self.assertRaises(KeyError):
+ self.material.getXY('days', 'adens', timePoints=badDays)
+
+ def test_fetchData(self):
+ """Verify that key errors are raised when bad data are requested."""
+ with self.assertRaises(KeyError):
+ _ = self.material['fake units']
+
if __name__ == '__main__':
unittest.main()
| {
"commit_name": "merge_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": 2
},
"num_modified_files": 7
} | unknown | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "pytest",
"pip_packages": [
"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"
} | contourpy==1.3.0
cycler==0.12.1
drewtils==0.1.9
exceptiongroup @ file:///croot/exceptiongroup_1706031385326/work
fonttools==4.56.0
importlib_resources==6.5.2
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
kiwisolver==1.4.7
matplotlib==3.9.4
numpy==2.0.2
packaging @ file:///croot/packaging_1734472117206/work
pillow==11.1.0
pluggy @ file:///croot/pluggy_1733169602837/work
pyparsing==3.2.3
pytest @ file:///croot/pytest_1738938843180/work
python-dateutil==2.9.0.post0
-e git+https://github.com/CORE-GATECH-GROUP/serpent-tools.git@606a90d665a15a16c437dd1fb72ef014aa480142#egg=serpentTools
six==1.17.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
zipp==3.21.0
| name: serpent-tools
channels:
- defaults
- https://repo.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:
- contourpy==1.3.0
- cycler==0.12.1
- drewtils==0.1.9
- fonttools==4.56.0
- importlib-resources==6.5.2
- kiwisolver==1.4.7
- matplotlib==3.9.4
- numpy==2.0.2
- pillow==11.1.0
- pyparsing==3.2.3
- python-dateutil==2.9.0.post0
- six==1.17.0
- zipp==3.21.0
prefix: /opt/conda/envs/serpent-tools
| [
"serpentTools/tests/test_depletion.py::DepletedMaterialTester::test_getXY_raisesError_badTime"
]
| []
| [
"serpentTools/tests/test_depletion.py::DepletionTester::test_ReadMaterials",
"serpentTools/tests/test_depletion.py::DepletionTester::test_metadata",
"serpentTools/tests/test_depletion.py::DepletedMaterialTester::test_fetchData",
"serpentTools/tests/test_depletion.py::DepletedMaterialTester::test_getXY_adens",
"serpentTools/tests/test_depletion.py::DepletedMaterialTester::test_getXY_adensAndTime",
"serpentTools/tests/test_depletion.py::DepletedMaterialTester::test_getXY_burnup_full",
"serpentTools/tests/test_depletion.py::DepletedMaterialTester::test_getXY_burnup_slice",
"serpentTools/tests/test_depletion.py::DepletedMaterialTester::test_materials"
]
| []
| MIT License | 1,688 | [
"serpentTools/parsers/fissionMatrix.py",
"serpentTools/parsers/branching.py",
"serpentTools/parsers/bumat.py",
"serpentTools/parsers/detector.py",
"serpentTools/parsers/results.py",
"serpentTools/objects/__init__.py",
"serpentTools/__init__.py"
]
| [
"serpentTools/parsers/fissionMatrix.py",
"serpentTools/parsers/branching.py",
"serpentTools/parsers/bumat.py",
"serpentTools/parsers/detector.py",
"serpentTools/parsers/results.py",
"serpentTools/objects/__init__.py",
"serpentTools/__init__.py"
]
|
|
wookayin__gpustat-28 | a38bc5fd11add4a8ab805f5b327020196ce558d0 | 2017-09-19 17:20:15 | a38bc5fd11add4a8ab805f5b327020196ce558d0 | cjw85: Changed: `power.use` -> `power.draw`, and `power.limit` -> `enforced.power.limit` as given by `nvidia-smi --query`. Changed API properties to be consistent (whilst not being verbose for the second case).
wookayin: Between `power.limit` and `enforced.power.limit`, what is the quantity you are seeking to print out? I thought it was `power.limit`, but you do `enforced.power.limit`, right?
cjw85: I'm calling `N.nvmlDeviceGetEnforcedPowerLimit` so `enforced.power.limit` is the correct form. This is described as "the minimum of various power limiters.", so seems to be the most relevant to display in the simple interface (and provide in the simple API). | diff --git a/gpustat.py b/gpustat.py
index 4ec8a41..df936c4 100755
--- a/gpustat.py
+++ b/gpustat.py
@@ -113,6 +113,24 @@ class GPUStat(object):
v = self.entry['utilization.gpu']
return int(v) if v is not None else None
+ @property
+ def power_draw(self):
+ """
+ Returns the GPU power usage in Watts,
+ or None if the information is not available.
+ """
+ v = self.entry['power.draw']
+ return int(v) if v is not None else None
+
+ @property
+ def power_limit(self):
+ """
+ Returns the (enforced) GPU power limit in Watts,
+ or None if the information is not available.
+ """
+ v = self.entry['enforced.power.limit']
+ return int(v) if v is not None else None
+
@property
def processes(self):
"""
@@ -126,6 +144,7 @@ class GPUStat(object):
show_cmd=False,
show_user=False,
show_pid=False,
+ show_power=False,
gpuname_width=16,
term=Terminal(),
):
@@ -150,6 +169,8 @@ class GPUStat(object):
colors['CUser'] = term.bold_black # gray
colors['CUtil'] = _conditional(lambda: int(self.entry['utilization.gpu']) < 30,
term.green, term.bold_green)
+ colors['CPowU'] = term.bold_red
+ colors['CPowL'] = term.red
if not with_colors:
for k in list(colors.keys()):
@@ -160,10 +181,14 @@ class GPUStat(object):
else: return str(v)
# build one-line display information
- reps = ("%(C1)s[{entry[index]}]%(C0)s %(CName)s{entry[name]:{gpuname_width}}%(C0)s |" +
- "%(CTemp)s{entry[temperature.gpu]:>3}'C%(C0)s, %(CUtil)s{entry[utilization.gpu]:>3} %%%(C0)s | " +
- "%(C1)s%(CMemU)s{entry[memory.used]:>5}%(C0)s / %(CMemT)s{entry[memory.total]:>5}%(C0)s MB"
- ) % colors
+ # we want power use optional, but if deserves being grouped with temperature and utilization
+ reps = "%(C1)s[{entry[index]}]%(C0)s %(CName)s{entry[name]:{gpuname_width}}%(C0)s |" \
+ "%(CTemp)s{entry[temperature.gpu]:>3}'C%(C0)s, %(CUtil)s{entry[utilization.gpu]:>3} %%%(C0)s"
+
+ if show_power:
+ reps += ", %(CPowU)s{entry[power.draw]:>3}%(C0)s / %(CPowL)s{entry[enforced.power.limit]:>3}%(C0)s W"
+ reps += " | %(C1)s%(CMemU)s{entry[memory.used]:>5}%(C0)s / %(CMemT)s{entry[memory.total]:>5}%(C0)s MB"
+ reps = (reps) % colors
reps = reps.format(entry={k: _repr(v) for (k, v) in self.entry.items()},
gpuname_width=gpuname_width)
reps += " |"
@@ -252,6 +277,16 @@ class GPUStatCollection(object):
except N.NVMLError:
utilization = None # Not supported
+ try:
+ power = N.nvmlDeviceGetPowerUsage(handle)
+ except:
+ power = None
+
+ try:
+ power_limit = N.nvmlDeviceGetEnforcedPowerLimit(handle)
+ except:
+ power_limit = None
+
processes = []
try:
nv_comp_processes = N.nvmlDeviceGetComputeRunningProcesses(handle)
@@ -284,6 +319,8 @@ class GPUStatCollection(object):
'name': name,
'temperature.gpu': temperature,
'utilization.gpu': utilization.gpu if utilization else None,
+ 'power.draw': int(power / 1000) if power is not None else None,
+ 'enforced.power.limit': int(power_limit / 1000) if power is not None else None,
# Convert bytes into MBytes
'memory.used': int(memory.used / 1024 / 1024) if memory else None,
'memory.total': int(memory.total / 1024 / 1024) if memory else None,
@@ -323,7 +360,7 @@ class GPUStatCollection(object):
def print_formatted(self, fp=sys.stdout, force_color=False, no_color=False,
show_cmd=False, show_user=False, show_pid=False,
- gpuname_width=16,
+ show_power=False, gpuname_width=16,
):
# ANSI color configuration
if force_color and no_color:
@@ -355,6 +392,7 @@ class GPUStatCollection(object):
show_cmd=show_cmd,
show_user=show_user,
show_pid=show_pid,
+ show_power=show_power,
gpuname_width=gpuname_width,
term=t_color)
fp.write('\n')
@@ -430,6 +468,8 @@ def main():
help='Display username of running process')
parser.add_argument('-p', '--show-pid', action='store_true',
help='Display PID of running process')
+ parser.add_argument('-P', '--show-power', action='store_true',
+ help='Show GPU power usage (and limit)')
parser.add_argument('--gpuname-width', type=int, default=16,
help='The minimum column width of GPU names, defaults to 16')
parser.add_argument('--json', action='store_true', default=False,
| Power usage
Hi,
How to add power usage and efficiency information ? | wookayin/gpustat | diff --git a/test_gpustat.py b/test_gpustat.py
index 0ac0279..4b81978 100644
--- a/test_gpustat.py
+++ b/test_gpustat.py
@@ -72,6 +72,18 @@ def _configure_mock(N, Process,
mock_handles[2]: 71,
}.get(handle, RuntimeError))
+ N.nvmlDeviceGetPowerUsage = _raise_ex(lambda handle: {
+ mock_handles[0]: 125000,
+ mock_handles[1]: 100000,
+ mock_handles[2]: 250000,
+ }.get(handle, RuntimeError))
+
+ N.nvmlDeviceGetEnforcedPowerLimit = _raise_ex(lambda handle: {
+ mock_handles[0]: 250000,
+ mock_handles[1]: 250000,
+ mock_handles[2]: 250000,
+ }.get(handle, RuntimeError))
+
mock_memory_t = namedtuple("Memory_t", ['total', 'used'])
N.nvmlDeviceGetMemoryInfo.side_effect = _raise_ex(lambda handle: {
mock_handles[0]: mock_memory_t(total=12883853312, used=8000*MB),
@@ -147,7 +159,7 @@ class TestGPUStat(unittest.TestCase):
gpustats = gpustat.new_query()
fp = StringIO()
- gpustats.print_formatted(fp=fp, no_color=False, show_user=True, show_cmd=True, show_pid=True)
+ gpustats.print_formatted(fp=fp, no_color=False, show_user=True, show_cmd=True, show_pid=True, show_power=True)
result = fp.getvalue()
print(result)
@@ -157,9 +169,9 @@ class TestGPUStat(unittest.TestCase):
unescaped = '\n'.join(unescaped.split('\n')[1:])
expected = """\
-[0] GeForce GTX TITAN 0 | 80'C, 76 % | 8000 / 12287 MB | user1:python/48448(4000M) user2:python/153223(4000M)
-[1] GeForce GTX TITAN 1 | 36'C, 0 % | 9000 / 12189 MB | user1:torch/192453(3000M) user3:caffe/194826(6000M)
-[2] GeForce GTX TITAN 2 | 71'C, ?? % | 0 / 12189 MB | (Not Supported)
+[0] GeForce GTX TITAN 0 | 80'C, 76 %, 125 / 250 W | 8000 / 12287 MB | user1:python/48448(4000M) user2:python/153223(4000M)
+[1] GeForce GTX TITAN 1 | 36'C, 0 %, 100 / 250 W | 9000 / 12189 MB | user1:torch/192453(3000M) user3:caffe/194826(6000M)
+[2] GeForce GTX TITAN 2 | 71'C, ?? %, 250 / 250 W | 0 / 12189 MB | (Not Supported)
"""
self.maxDiff = 4096
self.assertEqual(unescaped, expected)
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 3,
"test_score": 2
},
"num_modified_files": 1
} | 0.3 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"mock"
],
"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
blessings==1.7
certifi==2021.5.30
-e git+https://github.com/wookayin/gpustat.git@a38bc5fd11add4a8ab805f5b327020196ce558d0#egg=gpustat
importlib-metadata==4.8.3
iniconfig==1.1.1
mock==5.2.0
nvidia-ml-py3==7.352.0
packaging==21.3
pluggy==1.0.0
psutil==7.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: gpustat
channels:
- defaults
- https://repo.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
- blessings==1.7
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mock==5.2.0
- nvidia-ml-py3==7.352.0
- packaging==21.3
- pluggy==1.0.0
- psutil==7.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/gpustat
| [
"test_gpustat.py::TestGPUStat::test_new_query_mocked"
]
| []
| [
"test_gpustat.py::TestGPUStat::test_attributes_and_items",
"test_gpustat.py::TestGPUStat::test_new_query_mocked_nonexistent_pid"
]
| []
| MIT License | 1,689 | [
"gpustat.py"
]
| [
"gpustat.py"
]
|
laterpay__laterpay-client-python-108 | 87100aa64f880f61f9cdda81f1675c7650fc7c2e | 2017-09-20 14:33:27 | 87100aa64f880f61f9cdda81f1675c7650fc7c2e | diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9257c1d..5da76e2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
## 5.4.0 (under development)
+* Added the `connection_handler` to `LaterPayClient` to simplify connection
+ pooling.
+
## 5.3.1
* Only passed one of `lptoken` and `muid` to `/access` calls. Passing both is
diff --git a/laterpay/__init__.py b/laterpay/__init__.py
index 6fb563a..45417c3 100644
--- a/laterpay/__init__.py
+++ b/laterpay/__init__.py
@@ -112,7 +112,8 @@ class LaterPayClient(object):
api_root='https://api.laterpay.net',
web_root='https://web.laterpay.net',
lptoken=None,
- timeout_seconds=10):
+ timeout_seconds=10,
+ connection_handler=None):
"""
Instantiate a LaterPay API client.
@@ -122,6 +123,9 @@ class LaterPayClient(object):
:param timeout_seconds: number of seconds after which backend api
requests (e.g. /access) will time out (10 by default).
+ :param connection_handler: Defaults to Python requests. Set it to
+ ``requests.Session()`` to use a `Python requests Session object
+ <http://docs.python-requests.org/en/master/user/advanced/#session-objects>`_.
"""
self.cp_key = cp_key
@@ -130,6 +134,7 @@ class LaterPayClient(object):
self.shared_secret = shared_secret
self.lptoken = lptoken
self.timeout_seconds = timeout_seconds
+ self.connection_handler = connection_handler or requests
def get_gettoken_redirect(self, return_to):
"""
@@ -408,9 +413,9 @@ class LaterPayClient(object):
"""
Perform a request to /access API and return obtained data.
- This method uses ``requests.get`` to fetch the data and then calls
- ``.raise_for_status()`` on the response. It does not handle any errors
- raised by ``requests`` API.
+ This method uses ``requests.get`` or ``requests.Session().get`` to
+ fetch the data and then calls ``.raise_for_status()`` on the response.
+ It does not handle any errors raised by ``requests`` API.
:param article_ids: list of article ids or a single article id as a
string
@@ -421,7 +426,7 @@ class LaterPayClient(object):
url = self.get_access_url()
headers = self.get_request_headers()
- response = requests.get(
+ response = self.connection_handler.get(
url,
params=params,
headers=headers,
| Added support for `requests.Session`
Sometimes it's desirable to use [`requests.Session()`](http://docs.python-requests.org/en/master/user/advanced/#session-objects) over `requests.get()`. | laterpay/laterpay-client-python | diff --git a/tests/test_client.py b/tests/test_client.py
index bc9e37f..f59f98b 100644
--- a/tests/test_client.py
+++ b/tests/test_client.py
@@ -427,6 +427,34 @@ class TestLaterPayClient(unittest.TestCase):
method='GET',
)
+ @mock.patch('time.time')
+ def test_get_access_data_connection_handler(self, time_time_mock):
+ time_time_mock.return_value = 123
+ connection_handler = mock.Mock()
+ client = LaterPayClient(
+ 'fake-cp-key',
+ 'fake-shared-secret',
+ connection_handler=connection_handler,
+ )
+
+ client.get_access_data(
+ ['article-1', 'article-2'],
+ lptoken='fake-lptoken',
+ )
+
+ connection_handler.get.assert_called_once_with(
+ 'https://api.laterpay.net/access',
+ headers=client.get_request_headers(),
+ params={
+ 'article_id': ['article-1', 'article-2'],
+ 'ts': '123',
+ 'hmac': '198717d5c98b89ec3b509784758a98323f167ca6d42c363672169cfc',
+ 'cp': 'fake-cp-key',
+ 'lptoken': 'fake-lptoken',
+ },
+ timeout=10,
+ )
+
@mock.patch('laterpay.signing.sign')
@mock.patch('time.time')
def test_get_access_params(self, time_time_mock, sign_mock):
| {
"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": 2
},
"num_modified_files": 2
} | 5.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",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [],
"python": "3.5",
"reqs_path": [
"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
charset-normalizer==2.0.12
cookies==2.2.1
coverage==6.2
execnet==1.9.0
flake8==2.6.0
furl==0.4.95
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
-e git+https://github.com/laterpay/laterpay-client-python.git@87100aa64f880f61f9cdda81f1675c7650fc7c2e#egg=laterpay_client
mccabe==0.5.3
mock==2.0.0
orderedmultidict==1.0.1
packaging==21.3
pbr==6.1.1
pluggy==1.0.0
py==1.11.0
pycodestyle==2.0.0
pydocstyle==1.0.0
pyflakes==1.2.3
PyJWT==2.4.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
responses==0.5.1
six==1.17.0
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0
| name: laterpay-client-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:
- attrs==22.2.0
- charset-normalizer==2.0.12
- cookies==2.2.1
- coverage==6.2
- execnet==1.9.0
- flake8==2.6.0
- furl==0.4.95
- idna==3.10
- importlib-metadata==4.8.3
- iniconfig==1.1.1
- mccabe==0.5.3
- mock==2.0.0
- orderedmultidict==1.0.1
- packaging==21.3
- pbr==6.1.1
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.0.0
- pydocstyle==1.0.0
- pyflakes==1.2.3
- pyjwt==2.4.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
- responses==0.5.1
- six==1.17.0
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- zipp==3.6.0
prefix: /opt/conda/envs/laterpay-client-python
| [
"tests/test_client.py::TestLaterPayClient::test_get_access_data_connection_handler"
]
| [
"tests/test_client.py::TestLaterPayClient::test_get_manual_ident_token",
"tests/test_client.py::TestLaterPayClient::test_get_manual_ident_token_muid",
"tests/test_client.py::TestLaterPayClient::test_get_manual_ident_url"
]
| [
"tests/test_client.py::TestItemDefinition::test_invalid_expiry",
"tests/test_client.py::TestItemDefinition::test_invalid_period",
"tests/test_client.py::TestItemDefinition::test_invalid_pricing",
"tests/test_client.py::TestItemDefinition::test_invalid_sub_id",
"tests/test_client.py::TestItemDefinition::test_item_definition",
"tests/test_client.py::TestItemDefinition::test_sub_id",
"tests/test_client.py::TestLaterPayClient::test_get_access_data_success",
"tests/test_client.py::TestLaterPayClient::test_get_access_data_success_muid",
"tests/test_client.py::TestLaterPayClient::test_get_access_params",
"tests/test_client.py::TestLaterPayClient::test_get_add_url",
"tests/test_client.py::TestLaterPayClient::test_get_buy_url",
"tests/test_client.py::TestLaterPayClient::test_get_controls_balance_url_all_defaults",
"tests/test_client.py::TestLaterPayClient::test_get_controls_balance_url_all_set",
"tests/test_client.py::TestLaterPayClient::test_get_controls_links_url_all_defaults",
"tests/test_client.py::TestLaterPayClient::test_get_controls_links_url_all_set_long",
"tests/test_client.py::TestLaterPayClient::test_get_controls_links_url_all_set_short",
"tests/test_client.py::TestLaterPayClient::test_get_gettoken_redirect",
"tests/test_client.py::TestLaterPayClient::test_get_login_dialog_url_with_use_dialog_api_false",
"tests/test_client.py::TestLaterPayClient::test_get_logout_dialog_url_with_use_dialog_api_false",
"tests/test_client.py::TestLaterPayClient::test_get_signup_dialog_url",
"tests/test_client.py::TestLaterPayClient::test_get_subscribe_url",
"tests/test_client.py::TestLaterPayClient::test_get_web_url_itemdefinition_value_none",
"tests/test_client.py::TestLaterPayClient::test_has_token",
"tests/test_client.py::TestLaterPayClient::test_web_url_consumable",
"tests/test_client.py::TestLaterPayClient::test_web_url_dialog",
"tests/test_client.py::TestLaterPayClient::test_web_url_failure_url",
"tests/test_client.py::TestLaterPayClient::test_web_url_jsevents",
"tests/test_client.py::TestLaterPayClient::test_web_url_muid",
"tests/test_client.py::TestLaterPayClient::test_web_url_product_key",
"tests/test_client.py::TestLaterPayClient::test_web_url_return_url",
"tests/test_client.py::TestLaterPayClient::test_web_url_transaction_reference"
]
| []
| MIT License | 1,690 | [
"laterpay/__init__.py",
"CHANGELOG.md"
]
| [
"laterpay/__init__.py",
"CHANGELOG.md"
]
|
|
hylang__hy-1431 | db210929d0d74d38232eef1a3cfaf81fc6508087 | 2017-09-20 17:44:35 | 5c720c0110908e3f47dba2e4cc1c820d16f359a1 | diff --git a/NEWS b/NEWS
index cc19a6be..8fe2294b 100644
--- a/NEWS
+++ b/NEWS
@@ -39,6 +39,8 @@ Changes from 0.13.0
* Fixed a crash when `with` suppresses an exception. `with` now returns
`None` in this case.
* Fixed a crash when --repl-output-fn raises an exception
+ * Fixed a crash when HyTypeError was raised with objects that had no
+ source position
* `assoc` now evaluates its arguments only once each
* `break` and `continue` now raise an error when given arguments
instead of silently ignoring them
diff --git a/hy/errors.py b/hy/errors.py
index 6fb00fdf..a1e04c50 100644
--- a/hy/errors.py
+++ b/hy/errors.py
@@ -43,41 +43,47 @@ class HyTypeError(TypeError):
def __str__(self):
- line = self.expression.start_line
- start = self.expression.start_column
- end = self.expression.end_column
-
- source = []
- if self.source is not None:
- source = self.source.split("\n")[line-1:self.expression.end_line]
-
- if line == self.expression.end_line:
- length = end - start
- else:
- length = len(source[0]) - start
-
result = ""
- result += ' File "%s", line %d, column %d\n\n' % (self.filename,
- line,
- start)
-
- if len(source) == 1:
- result += ' %s\n' % colored.red(source[0])
- result += ' %s%s\n' % (' '*(start-1),
- colored.green('^' + '-'*(length-1) + '^'))
- if len(source) > 1:
- result += ' %s\n' % colored.red(source[0])
- result += ' %s%s\n' % (' '*(start-1),
- colored.green('^' + '-'*length))
- if len(source) > 2: # write the middle lines
- for line in source[1:-1]:
- result += ' %s\n' % colored.red("".join(line))
- result += ' %s\n' % colored.green("-"*len(line))
-
- # write the last line
- result += ' %s\n' % colored.red("".join(source[-1]))
- result += ' %s\n' % colored.green('-'*(end-1) + '^')
+ if all(getattr(self.expression, x, None) is not None
+ for x in ("start_line", "start_column", "end_column")):
+
+ line = self.expression.start_line
+ start = self.expression.start_column
+ end = self.expression.end_column
+
+ source = []
+ if self.source is not None:
+ source = self.source.split("\n")[line-1:self.expression.end_line]
+
+ if line == self.expression.end_line:
+ length = end - start
+ else:
+ length = len(source[0]) - start
+
+ result += ' File "%s", line %d, column %d\n\n' % (self.filename,
+ line,
+ start)
+
+ if len(source) == 1:
+ result += ' %s\n' % colored.red(source[0])
+ result += ' %s%s\n' % (' '*(start-1),
+ colored.green('^' + '-'*(length-1) + '^'))
+ if len(source) > 1:
+ result += ' %s\n' % colored.red(source[0])
+ result += ' %s%s\n' % (' '*(start-1),
+ colored.green('^' + '-'*length))
+ if len(source) > 2: # write the middle lines
+ for line in source[1:-1]:
+ result += ' %s\n' % colored.red("".join(line))
+ result += ' %s\n' % colored.green("-"*len(line))
+
+ # write the last line
+ result += ' %s\n' % colored.red("".join(source[-1]))
+ result += ' %s\n' % colored.green('-'*(end-1) + '^')
+
+ else:
+ result += ' File "%s", unknown location\n' % self.filename
result += colored.yellow("%s: %s\n\n" %
(self.__class__.__name__,
| repl shouldn't crash
```Hy
=> (defmacro bad [] `(macro-error 'x ""))
<function <lambda> at 0x000001D01D0ED7B8>
=> (bad)
Traceback (most recent call last):
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 99, in runsource
ast_callback)
File "c:\users\me\documents\github\hy\hy\importer.py", line 198, in hy_eval
eval(ast_compile(_ast, "<eval_body>", "exec"), namespace)
File "<eval_body>", line 1, in <module>
hy.errors.HyMacroExpansionError: <exception str() failed>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\ME\workspace\hy36-gilch\Scripts\hy-script.py", line 11, in <module>
load_entry_point('hy', 'console_scripts', 'hy')()
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 346, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 341, in cmdline_handler
return run_repl(spy=options.spy, output_fn=options.repl_output_fn)
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 236, in run_repl
os=platform.system()
File "C:\Users\ME\AppData\Local\Programs\Python\Python36\lib\code.py", line 233, in interact
more = self.push(line)
File "C:\Users\ME\AppData\Local\Programs\Python\Python36\lib\code.py", line 259, in push
more = self.runsource(source, self.filename)
File "c:\users\me\documents\github\hy\hy\cmdline.py", line 105, in runsource
print(e, file=sys.stderr)
File "c:\users\me\documents\github\hy\hy\errors.py", line 46, in __str__
line = self.expression.start_line
AttributeError: 'HySymbol' object has no attribute 'start_line'
```
The repl should report errors, but not exit. | hylang/hy | diff --git a/tests/test_bin.py b/tests/test_bin.py
index ad2ea132..0b2a0ad5 100644
--- a/tests/test_bin.py
+++ b/tests/test_bin.py
@@ -138,6 +138,16 @@ def test_bin_hy_stdin_except_do():
assert "zzz" in output
+def test_bin_hy_stdin_unlocatable_hytypeerror():
+ # https://github.com/hylang/hy/issues/1412
+ # The chief test of interest here is the returncode assertion
+ # inside run_cmd.
+ _, err = run_cmd("hy", """
+ (import hy.errors)
+ (raise (hy.errors.HyTypeError '[] (+ "A" "Z")))""")
+ assert "AZ" in err
+
+
def test_bin_hy_stdin_bad_repr():
# https://github.com/hylang/hy/issues/1389
output, err = run_cmd("hy", """
| {
"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": 1,
"test_score": 0
},
"num_modified_files": 2
} | 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",
"flake8",
"tox",
"Pygments",
"Sphinx",
"sphinx_rtd_theme"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alabaster==0.7.13
appdirs==1.4.4
args==0.1.0
astor==0.8.1
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
clint==0.5.1
coverage==6.2
distlib==0.3.9
docutils==0.17.1
filelock==3.4.1
flake8==5.0.4
-e git+https://github.com/hylang/hy.git@db210929d0d74d38232eef1a3cfaf81fc6508087#egg=hy
idna==3.10
imagesize==1.4.1
importlib-metadata==4.2.0
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
mccabe==0.7.0
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
rply==0.7.8
six==1.17.0
snowballstemmer==2.2.0
Sphinx==4.3.2
sphinx-rtd-theme==1.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
toml==0.10.2
tomli==1.2.3
tox==3.28.0
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.16.2
zipp==3.6.0
| name: hy
channels:
- defaults
- https://repo.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
- appdirs==1.4.4
- args==0.1.0
- astor==0.8.1
- attrs==22.2.0
- babel==2.11.0
- charset-normalizer==2.0.12
- clint==0.5.1
- coverage==6.2
- distlib==0.3.9
- docutils==0.17.1
- filelock==3.4.1
- flake8==5.0.4
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==4.2.0
- importlib-resources==5.4.0
- iniconfig==1.1.1
- jinja2==3.0.3
- markupsafe==2.0.1
- mccabe==0.7.0
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- rply==0.7.8
- six==1.17.0
- snowballstemmer==2.2.0
- sphinx==4.3.2
- sphinx-rtd-theme==1.3.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- toml==0.10.2
- tomli==1.2.3
- tox==3.28.0
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.16.2
- zipp==3.6.0
prefix: /opt/conda/envs/hy
| [
"tests/test_bin.py::test_bin_hy_stdin_unlocatable_hytypeerror"
]
| [
"tests/test_bin.py::test_bin_hy_stdin",
"tests/test_bin.py::test_bin_hy_icmd_and_spy"
]
| [
"tests/test_bin.py::test_bin_hy",
"tests/test_bin.py::test_bin_hy_stdin_multiline",
"tests/test_bin.py::test_bin_hy_stdin_comments",
"tests/test_bin.py::test_bin_hy_stdin_assignment",
"tests/test_bin.py::test_bin_hy_stdin_as_arrow",
"tests/test_bin.py::test_bin_hy_stdin_error_underline_alignment",
"tests/test_bin.py::test_bin_hy_stdin_except_do",
"tests/test_bin.py::test_bin_hy_stdin_bad_repr",
"tests/test_bin.py::test_bin_hy_stdin_hy_repr",
"tests/test_bin.py::test_bin_hy_cmd",
"tests/test_bin.py::test_bin_hy_icmd",
"tests/test_bin.py::test_bin_hy_icmd_file",
"tests/test_bin.py::test_bin_hy_missing_file",
"tests/test_bin.py::test_bin_hy_file_with_args",
"tests/test_bin.py::test_bin_hyc",
"tests/test_bin.py::test_bin_hyc_missing_file",
"tests/test_bin.py::test_hy2py",
"tests/test_bin.py::test_bin_hy_builtins",
"tests/test_bin.py::test_bin_hy_main",
"tests/test_bin.py::test_bin_hy_main_args",
"tests/test_bin.py::test_bin_hy_main_exitvalue",
"tests/test_bin.py::test_bin_hy_no_main",
"tests/test_bin.py::test_bin_hy_byte_compile[hy",
"tests/test_bin.py::test_bin_hy_module_main",
"tests/test_bin.py::test_bin_hy_module_main_args",
"tests/test_bin.py::test_bin_hy_module_main_exitvalue",
"tests/test_bin.py::test_bin_hy_module_no_main"
]
| []
| MIT License | 1,691 | [
"NEWS",
"hy/errors.py"
]
| [
"NEWS",
"hy/errors.py"
]
|
|
di__vladiate-42 | 81892a0a29bd668bc12c72e17b3f2f62f7ed0377 | 2017-09-20 21:12:58 | 9d7c5dd83f76ff651a69d085145255c27f8ce33c | diff --git a/README.rst b/README.rst
index f36c851..77af67e 100644
--- a/README.rst
+++ b/README.rst
@@ -236,6 +236,8 @@ Vladiate comes with a few common validators built-in:
:``unique_with=[]``:
List of field names to make the primary field unique with.
+ :``empty_ok=False``:
+ Specify whether a field which is an empty string should be ignored.
*class* ``RegexValidator``
@@ -243,6 +245,8 @@ Vladiate comes with a few common validators built-in:
:``pattern=r'di^'``:
The regex pattern. Fails for all fields by default.
+ :``empty_ok=False``:
+ Specify whether a field which is an empty string should be ignored.
*class* ``RangeValidator``
@@ -253,6 +257,8 @@ Vladiate comes with a few common validators built-in:
The low value of the range.
:``high``:
The high value of the range.
+ :``empty_ok=False``:
+ Specify whether a field which is an empty string should be ignored.
*class* ``EmptyValidator``
diff --git a/setup.py b/setup.py
index 62b35f8..b5c8c72 100644
--- a/setup.py
+++ b/setup.py
@@ -4,7 +4,7 @@ import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
-__version__ = '0.0.17'
+__version__ = '0.0.18'
class PyTest(TestCommand):
diff --git a/vladiate/validators.py b/vladiate/validators.py
index a425c2c..72dccdb 100644
--- a/vladiate/validators.py
+++ b/vladiate/validators.py
@@ -6,8 +6,9 @@ from vladiate.exceptions import ValidationException, BadValidatorException
class Validator(object):
''' Generic Validator class '''
- def __init__(self):
+ def __init__(self, empty_ok=False):
self.fail_count = 0
+ self.empty_ok = empty_ok
@property
def bad(self):
@@ -22,8 +23,8 @@ class Validator(object):
class CastValidator(Validator):
''' Validates that a field can be cast to a float '''
- def __init__(self):
- super(CastValidator, self).__init__()
+ def __init__(self, **kwargs):
+ super(CastValidator, self).__init__(**kwargs)
self.invalid_set = set([])
def validate(self, field, row={}):
@@ -42,29 +43,27 @@ class CastValidator(Validator):
class FloatValidator(CastValidator):
''' Validates that a field can be cast to a float '''
- def __init__(self, empty_ok=False):
- super(FloatValidator, self).__init__()
- self.empty_ok = empty_ok
+ def __init__(self, **kwargs):
+ super(FloatValidator, self).__init__(**kwargs)
self.cast = float
class IntValidator(CastValidator):
''' Validates that a field can be cast to an int '''
- def __init__(self, empty_ok=False):
- super(IntValidator, self).__init__()
- self.empty_ok = empty_ok
+ def __init__(self, **kwargs):
+ super(IntValidator, self).__init__(**kwargs)
self.cast = int
class SetValidator(Validator):
''' Validates that a field is in the given set '''
- def __init__(self, valid_set=[], empty_ok=False):
- super(SetValidator, self).__init__()
+ def __init__(self, valid_set=[], **kwargs):
+ super(SetValidator, self).__init__(**kwargs)
self.valid_set = set(valid_set)
self.invalid_set = set([])
- if empty_ok:
+ if self.empty_ok:
self.valid_set.add('')
def validate(self, field, row={}):
@@ -81,8 +80,8 @@ class SetValidator(Validator):
class UniqueValidator(Validator):
''' Validates that a field is unique within the file '''
- def __init__(self, unique_with=[]):
- super(UniqueValidator, self).__init__()
+ def __init__(self, unique_with=[], **kwargs):
+ super(UniqueValidator, self).__init__(**kwargs)
self.unique_values = set([])
self.duplicates = set([])
self.unique_with = unique_with
@@ -119,10 +118,9 @@ class UniqueValidator(Validator):
class RegexValidator(Validator):
''' Validates that a field matches a given regex '''
- def __init__(self, pattern=r'di^', empty_ok=False):
- super(RegexValidator, self).__init__()
+ def __init__(self, pattern=r'di^', **kwargs):
+ super(RegexValidator, self).__init__(**kwargs)
self.regex = re.compile(pattern)
- self.empty_ok = empty_ok
self.failures = set([])
def validate(self, field, row={}):
@@ -137,13 +135,16 @@ class RegexValidator(Validator):
class RangeValidator(Validator):
- def __init__(self, low, high):
+ def __init__(self, low, high, **kwargs):
+ super(RangeValidator, self).__init__(**kwargs)
self.fail_count = 0
self.low = low
self.high = high
self.outside = set()
def validate(self, field, row={}):
+ if field == '' and self.empty_ok:
+ return
try:
value = float(field)
if not self.low <= value <= self.high:
@@ -164,8 +165,8 @@ class RangeValidator(Validator):
class EmptyValidator(Validator):
''' Validates that a field is always empty '''
- def __init__(self):
- super(EmptyValidator, self).__init__()
+ def __init__(self, **kwargs):
+ super(EmptyValidator, self).__init__(**kwargs)
self.nonempty = set([])
def validate(self, field, row={}):
@@ -183,7 +184,8 @@ class EmptyValidator(Validator):
class NotEmptyValidator(Validator):
''' Validates that a field is not empty '''
- def __init__(self):
+ def __init__(self, **kwargs):
+ super(NotEmptyValidator, self).__init__(**kwargs)
self.fail_count = 0
self.failed = False
| RangeValidator has no empty_ok parameter
RangeValidator has no option to allow empty records in a field. RangeValidator fails if the field contains an empty record "". Propose to add an empty_ok parameter to the RangeValidator class similar to other validators as shown below:
```python
class RangeValidator(Validator):
def __init__(self, low, high, empty_ok=False):
self.fail_count = 0
self.low = low
self.high = high
self.empty_ok = empty_ok
self.outside = set()
def validate(self, field, row={}):
if field == '' and self.empty_ok:
pass
else:
try:
value = float(field)
if not self.low <= value <= self.high:
raise ValueError
except ValueError:
self.outside.add(field)
raise ValidationException(
"'{}' is not in range {} to {}".format(
field, self.low, self.high
)
)
@property
def bad(self):
return self.outside
``` | di/vladiate | diff --git a/vladiate/test/test_validators.py b/vladiate/test/test_validators.py
index 7b80686..369e9a4 100644
--- a/vladiate/test/test_validators.py
+++ b/vladiate/test/test_validators.py
@@ -81,12 +81,6 @@ def test_set_validator_works(field_set, field):
assert field in validator.valid_set
-def test_set_validator_empty_ok():
- validator = SetValidator(['foo'], empty_ok=True)
- validator.validate('')
- assert '' in validator.valid_set
-
-
@pytest.mark.parametrize('field_set, field', [
([], 'bar'),
(['foo'], 'bar'),
@@ -139,10 +133,6 @@ def test_regex_validator_works(pattern, field):
RegexValidator(pattern).validate(field)
-def test_regex_validator_allows_empty():
- RegexValidator(r'foo.*', empty_ok=True).validate('')
-
-
@pytest.mark.parametrize('pattern, field', [
(r'foo.*', 'afoo'),
(r'^$', 'foo'),
@@ -213,3 +203,16 @@ def test_base_class_raises():
with pytest.raises(NotImplementedError):
validator.validate(stub(), stub())
+
+
[email protected]('validator_class,args', [
+ (SetValidator, [['foo']]),
+ (RegexValidator, [r'foo.*']),
+ (IntValidator, []),
+ (FloatValidator, []),
+ (RangeValidator, [0, 42]),
+ (UniqueValidator, []),
+])
+def test_all_validators_support_empty_ok(validator_class, args):
+ validator = validator_class(*args, empty_ok=True)
+ validator.validate('')
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 3
} | 0.0 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[s3]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pretend",
"pytest",
"black"
],
"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"
} | black==23.3.0
boto==2.49.0
certifi @ file:///croot/certifi_1671487769961/work/certifi
click==8.1.8
exceptiongroup==1.2.2
importlib-metadata==6.7.0
iniconfig==2.0.0
mypy-extensions==1.0.0
packaging==24.0
pathspec==0.11.2
platformdirs==4.0.0
pluggy==1.2.0
pretend==1.0.9
pytest==7.4.4
tomli==2.0.1
typed-ast==1.5.5
typing_extensions==4.7.1
-e git+https://github.com/di/vladiate.git@81892a0a29bd668bc12c72e17b3f2f62f7ed0377#egg=vladiate
zipp==3.15.0
| name: vladiate
channels:
- defaults
- https://repo.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:
- black==23.3.0
- boto==2.49.0
- click==8.1.8
- exceptiongroup==1.2.2
- importlib-metadata==6.7.0
- iniconfig==2.0.0
- mypy-extensions==1.0.0
- packaging==24.0
- pathspec==0.11.2
- platformdirs==4.0.0
- pluggy==1.2.0
- pretend==1.0.9
- pytest==7.4.4
- tomli==2.0.1
- typed-ast==1.5.5
- typing-extensions==4.7.1
- zipp==3.15.0
prefix: /opt/conda/envs/vladiate
| [
"vladiate/test/test_validators.py::test_all_validators_support_empty_ok[RangeValidator-args4]",
"vladiate/test/test_validators.py::test_all_validators_support_empty_ok[UniqueValidator-args5]"
]
| []
| [
"vladiate/test/test_validators.py::test_cast_validator",
"vladiate/test/test_validators.py::test_float_validator_works[42]",
"vladiate/test/test_validators.py::test_float_validator_works[42.0]",
"vladiate/test/test_validators.py::test_float_validator_works[-42.0]",
"vladiate/test/test_validators.py::test_float_validator_fails[foo]",
"vladiate/test/test_validators.py::test_float_validator_fails[",
"vladiate/test/test_validators.py::test_float_validator_fails[7..0]",
"vladiate/test/test_validators.py::test_float_validator_fails[4,200]",
"vladiate/test/test_validators.py::test_int_validator_works[42]",
"vladiate/test/test_validators.py::test_int_validator_fails[foo]",
"vladiate/test/test_validators.py::test_int_validator_fails[",
"vladiate/test/test_validators.py::test_int_validator_fails[7..0]",
"vladiate/test/test_validators.py::test_int_validator_fails[4,200]",
"vladiate/test/test_validators.py::test_int_validator_fails[42.0]",
"vladiate/test/test_validators.py::test_int_validator_fails[-42.0]",
"vladiate/test/test_validators.py::test_set_validator_works[field_set0-foo]",
"vladiate/test/test_validators.py::test_set_validator_works[field_set1-foo]",
"vladiate/test/test_validators.py::test_set_validator_fails[field_set0-bar]",
"vladiate/test/test_validators.py::test_set_validator_fails[field_set1-bar]",
"vladiate/test/test_validators.py::test_set_validator_fails[field_set2-baz]",
"vladiate/test/test_validators.py::test_unique_validator_works[fields0-row0-unique_with0]",
"vladiate/test/test_validators.py::test_unique_validator_works[fields1-row1-unique_with1]",
"vladiate/test/test_validators.py::test_unique_validator_works[fields2-row2-unique_with2]",
"vladiate/test/test_validators.py::test_unique_validator_works[fields3-row3-unique_with3]",
"vladiate/test/test_validators.py::test_unique_validator_fails[fields0-row0-unique_with0-ValidationException-bad0]",
"vladiate/test/test_validators.py::test_unique_validator_fails[fields1-row1-unique_with1-ValidationException-bad1]",
"vladiate/test/test_validators.py::test_unique_validator_fails[fields2-row2-unique_with2-BadValidatorException-bad2]",
"vladiate/test/test_validators.py::test_regex_validator_works[foo.*-foo]",
"vladiate/test/test_validators.py::test_regex_validator_works[foo.*-foobar]",
"vladiate/test/test_validators.py::test_regex_validator_fails[foo.*-afoo]",
"vladiate/test/test_validators.py::test_regex_validator_fails[^$-foo]",
"vladiate/test/test_validators.py::test_range_validator_works",
"vladiate/test/test_validators.py::test_range_validator_fails",
"vladiate/test/test_validators.py::test_range_validator_handles_bad_values",
"vladiate/test/test_validators.py::test_empty_validator_works",
"vladiate/test/test_validators.py::test_empty_validator_fails",
"vladiate/test/test_validators.py::test_non_empty_validator_works",
"vladiate/test/test_validators.py::test_non_empty_validator_fails",
"vladiate/test/test_validators.py::test_ignore_validator",
"vladiate/test/test_validators.py::test_base_class_raises",
"vladiate/test/test_validators.py::test_all_validators_support_empty_ok[SetValidator-args0]",
"vladiate/test/test_validators.py::test_all_validators_support_empty_ok[RegexValidator-args1]",
"vladiate/test/test_validators.py::test_all_validators_support_empty_ok[IntValidator-args2]",
"vladiate/test/test_validators.py::test_all_validators_support_empty_ok[FloatValidator-args3]"
]
| []
| MIT License | 1,692 | [
"README.rst",
"vladiate/validators.py",
"setup.py"
]
| [
"README.rst",
"vladiate/validators.py",
"setup.py"
]
|
|
tornadoweb__tornado-2157 | 34c43f4775971ab9b2b8ed43356f218add6387b2 | 2017-09-21 18:10:28 | 03f13800e854a6fc9e6efa2168e694d9599348bd | diff --git a/tornado/websocket.py b/tornado/websocket.py
index d5a7fa89..c6804ca0 100644
--- a/tornado/websocket.py
+++ b/tornado/websocket.py
@@ -616,6 +616,14 @@ class WebSocketProtocol13(WebSocketProtocol):
def accept_connection(self):
try:
self._handle_websocket_headers()
+ except ValueError:
+ self.handler.set_status(400)
+ log_msg = "Missing/Invalid WebSocket headers"
+ self.handler.finish(log_msg)
+ gen_log.debug(log_msg)
+ return
+
+ try:
self._accept_connection()
except ValueError:
gen_log.debug("Malformed WebSocket request received",
| AttributeError if Websocket client misses required header
If the client misses required header for websocket handshake, the server raises AttributeError.
Minimal code for reproduce
### Client
```python
import socket
REQ_1 = ('GET /ws HTTP/1.1\r\n'
'Host: example.com:9221\r\n'
'Upgrade: websocket\r\n'
'Connection: Upgrade\r\n'
# 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n'
'Sec-WebSocket-Version: 13\r\n'
'\r\n')
conn = socket.create_connection(('127.0.0.1', 9221))
conn.send(REQ_1.encode('utf-8'))
resp_1 = conn.recv(10 * 1024)
```
### Server
```python
import tornado.ioloop
import tornado.web
import tornado.websocket
class WsHandler(tornado.websocket.WebSocketHandler):
pass
def make_app():
return tornado.web.Application([
(r'/ws', WsHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(9221)
tornado.ioloop.IOLoop.current().start()
```
### Traceback
```
ERROR:tornado.application:Uncaught exception GET /ws (127.0.0.1)
HTTPServerRequest(protocol='http', host='example.com:8000', method='GET', uri='/ws', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Host': 'example.com:8000', 'Upgrade': 'websocket', 'Connection': 'Upgrade', 'Sec-Websocket-Version': '13'})
Traceback (most recent call last):
File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/websocket.py", line 618, in accept_connection
self._handle_websocket_headers()
File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/websocket.py", line 634, in _handle_websocket_headers
raise ValueError("Missing/Invalid WebSocket headers")
ValueError: Missing/Invalid WebSocket headers
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/web.py", line 1467, in _stack_context_handle_exception
raise_exc_info((type, value, traceback))
File "<string>", line 4, in raise_exc_info
File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/web.py", line 1669, in wrapper
result = method(self, *args, **kwargs)
File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/websocket.py", line 196, in get
self.ws_connection.accept_connection()
File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/websocket.py", line 623, in accept_connection
self._abort()
File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/websocket.py", line 512, in _abort
self.stream.close() # forcibly tear down the connection
AttributeError: 'NoneType' object has no attribute 'close'
ERROR:tornado.access:500 GET /ws (127.0.0.1) 4.13ms
```
It seems that `WebSocketProtocol13.accept_connection` calls `WebSocketProtocol._abort` immediately if there is missing required headers, however, it is before the handshake, thus there is yet no `self.stream` whereas the _abort function tries to `self.stream.close()`. Also, the _abort function calls `self.close()` and there is also the same buggy code which calls `self.stream.close()` without checking the nullity of `self.stream`. | tornadoweb/tornado | diff --git a/tornado/test/websocket_test.py b/tornado/test/websocket_test.py
index 5a2a6577..54734d81 100644
--- a/tornado/test/websocket_test.py
+++ b/tornado/test/websocket_test.py
@@ -193,6 +193,13 @@ class WebSocketTest(WebSocketBaseTestCase):
response = self.fetch('/echo')
self.assertEqual(response.code, 400)
+ def test_missing_websocket_key(self):
+ response = self.fetch('/echo',
+ headers={'Connection': 'Upgrade',
+ 'Upgrade': 'WebSocket',
+ 'Sec-WebSocket-Version': '13'})
+ self.assertEqual(response.code, 400)
+
def test_bad_websocket_version(self):
response = self.fetch('/echo',
headers={'Connection': 'Upgrade',
| {
"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
} | 4.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": [
"sphinx",
"sphinx_rtd_theme",
"codecov",
"virtualenv",
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements/base.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
codecov==2.1.13
coverage==6.2
distlib==0.3.9
docutils==0.18.1
filelock==3.4.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
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-rtd-theme==2.0.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
-e git+https://github.com/tornadoweb/tornado.git@34c43f4775971ab9b2b8ed43356f218add6387b2#egg=tornado
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.17.1
zipp==3.6.0
| 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
- 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
- codecov==2.1.13
- coverage==6.2
- distlib==0.3.9
- docutils==0.18.1
- filelock==3.4.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
- packaging==21.3
- platformdirs==2.4.0
- pluggy==1.0.0
- py==1.11.0
- pygments==2.14.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytz==2025.2
- requests==2.27.1
- snowballstemmer==2.2.0
- sphinx==5.3.0
- sphinx-rtd-theme==2.0.0
- sphinxcontrib-applehelp==1.0.2
- sphinxcontrib-devhelp==1.0.2
- sphinxcontrib-htmlhelp==2.0.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.3
- sphinxcontrib-serializinghtml==1.1.5
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- virtualenv==20.17.1
- zipp==3.6.0
prefix: /opt/conda/envs/tornado
| [
"tornado/test/websocket_test.py::WebSocketTest::test_missing_websocket_key"
]
| []
| [
"tornado/test/websocket_test.py::WebSocketTest::test_async_prepare",
"tornado/test/websocket_test.py::WebSocketTest::test_bad_websocket_version",
"tornado/test/websocket_test.py::WebSocketTest::test_binary_message",
"tornado/test/websocket_test.py::WebSocketTest::test_check_origin_invalid",
"tornado/test/websocket_test.py::WebSocketTest::test_check_origin_invalid_partial_url",
"tornado/test/websocket_test.py::WebSocketTest::test_check_origin_invalid_subdomains",
"tornado/test/websocket_test.py::WebSocketTest::test_check_origin_valid_no_path",
"tornado/test/websocket_test.py::WebSocketTest::test_check_origin_valid_with_path",
"tornado/test/websocket_test.py::WebSocketTest::test_client_close_reason",
"tornado/test/websocket_test.py::WebSocketTest::test_coroutine",
"tornado/test/websocket_test.py::WebSocketTest::test_error_in_on_message",
"tornado/test/websocket_test.py::WebSocketTest::test_http_request",
"tornado/test/websocket_test.py::WebSocketTest::test_path_args",
"tornado/test/websocket_test.py::WebSocketTest::test_render_message",
"tornado/test/websocket_test.py::WebSocketTest::test_server_close_reason",
"tornado/test/websocket_test.py::WebSocketTest::test_unicode_message",
"tornado/test/websocket_test.py::WebSocketTest::test_websocket_callbacks",
"tornado/test/websocket_test.py::WebSocketTest::test_websocket_close_buffered_data",
"tornado/test/websocket_test.py::WebSocketTest::test_websocket_gen",
"tornado/test/websocket_test.py::WebSocketTest::test_websocket_header_echo",
"tornado/test/websocket_test.py::WebSocketTest::test_websocket_headers",
"tornado/test/websocket_test.py::WebSocketTest::test_websocket_http_fail",
"tornado/test/websocket_test.py::WebSocketTest::test_websocket_http_success",
"tornado/test/websocket_test.py::WebSocketTest::test_websocket_network_fail",
"tornado/test/websocket_test.py::WebSocketTest::test_write_after_close",
"tornado/test/websocket_test.py::WebSocketNativeCoroutineTest::test_native_coroutine",
"tornado/test/websocket_test.py::NoCompressionTest::test_message_sizes",
"tornado/test/websocket_test.py::ServerOnlyCompressionTest::test_message_sizes",
"tornado/test/websocket_test.py::ClientOnlyCompressionTest::test_message_sizes",
"tornado/test/websocket_test.py::DefaultCompressionTest::test_message_sizes",
"tornado/test/websocket_test.py::PythonMaskFunctionTest::test_mask",
"tornado/test/websocket_test.py::CythonMaskFunctionTest::test_mask",
"tornado/test/websocket_test.py::ServerPeriodicPingTest::test_server_ping",
"tornado/test/websocket_test.py::ClientPeriodicPingTest::test_client_ping",
"tornado/test/websocket_test.py::MaxMessageSizeTest::test_large_message"
]
| []
| Apache License 2.0 | 1,693 | [
"tornado/websocket.py"
]
| [
"tornado/websocket.py"
]
|
|
pydap__pydap-146 | 4ae73e393b0d52bce9d1cf5571945a9ed884d526 | 2017-09-21 23:35:30 | eb8ee96bdf150642bf2e0603f406d2053af02424 | rabernat: Is anyone maintaining this package? Why haven't PR's like this one been merged? | diff --git a/setup.py b/setup.py
index 7471f20..79675e6 100644
--- a/setup.py
+++ b/setup.py
@@ -9,7 +9,8 @@ install_requires = [
'Jinja2',
'docopt',
'six >= 1.4.0',
- 'beautifulsoup4'
+ 'beautifulsoup4',
+ 'requests'
]
if sys.version_info < (3, 5):
@@ -32,14 +33,13 @@ docs_extras = [
]
cas_extras = [
- 'requests',
'lxml'
- ]
+]
hdl_netcdf_extras = [
'netCDF4',
'ordereddict'
- ]
+]
tests_require = (functions_extras + cas_extras + server_extras +
hdl_netcdf_extras +
diff --git a/src/pydap/handlers/csv/__init__.py b/src/pydap/handlers/csv/__init__.py
index 38ded4c..717079b 100644
--- a/src/pydap/handlers/csv/__init__.py
+++ b/src/pydap/handlers/csv/__init__.py
@@ -114,7 +114,7 @@ class CSVHandler(BaseHandler):
BaseHandler.__init__(self)
try:
- with open(filepath, 'Ur') as fp:
+ with open(filepath, 'r') as fp:
reader = csv.reader(fp, quoting=csv.QUOTE_NONNUMERIC)
vars = next(reader)
except Exception as exc:
@@ -257,7 +257,7 @@ class CSVData(IterData):
def stream(self):
"""Generator that yield lines of the file."""
try:
- with open(self.filepath, 'Ur') as fp:
+ with open(self.filepath, 'r') as fp:
reader = csv.reader(fp, quoting=csv.QUOTE_NONNUMERIC)
next(reader) # consume var names
for row in reader:
diff --git a/src/pydap/handlers/lib.py b/src/pydap/handlers/lib.py
index dca98b8..ffef4e8 100644
--- a/src/pydap/handlers/lib.py
+++ b/src/pydap/handlers/lib.py
@@ -120,7 +120,7 @@ class BaseHandler(object):
'Origin, X-Requested-With, Content-Type')
return res(environ, start_response)
- except:
+ except Exception:
# should the exception be catched?
if environ.get('x-wsgiorg.throw_errors'):
raise
@@ -456,7 +456,7 @@ def build_filter(expression, template):
col = keys.index(token)
target = target[token]
a = operator.itemgetter(col)
- except:
+ except Exception:
raise ConstraintExpressionError(
'Invalid constraint expression: "{expression}" '
'("{id}" is not a valid variable)'.format(
@@ -474,7 +474,7 @@ def build_filter(expression, template):
def b(row):
return value
- except:
+ except Exception:
raise ConstraintExpressionError(
'Invalid constraint expression: "{expression}" '
'("{id}" is not valid)'.format(
diff --git a/src/pydap/lib.py b/src/pydap/lib.py
index ed55eb9..7bfc7ea 100644
--- a/src/pydap/lib.py
+++ b/src/pydap/lib.py
@@ -125,7 +125,7 @@ def encode(obj):
"""Return an object encoded to its DAP representation."""
try:
return '%.6g' % obj
- except:
+ except Exception:
return '"{0}"'.format(obj)
diff --git a/src/pydap/model.py b/src/pydap/model.py
index 335f0c3..ee9b486 100644
--- a/src/pydap/model.py
+++ b/src/pydap/model.py
@@ -381,7 +381,7 @@ class StructureType(DapType, Mapping):
"""Lazy shortcut return children."""
try:
return self[attr]
- except:
+ except Exception:
return DapType.__getattr__(self, attr)
def __contains__(self, key):
@@ -408,7 +408,7 @@ class StructureType(DapType, Mapping):
if len(splitted) > 1:
try:
return self[splitted[0]]['.'.join(splitted[1:])]
- except KeyError:
+ except (KeyError, IndexError):
return self['.'.join(splitted[1:])]
else:
raise
diff --git a/src/pydap/parsers/__init__.py b/src/pydap/parsers/__init__.py
index 7068faa..aab33ed 100644
--- a/src/pydap/parsers/__init__.py
+++ b/src/pydap/parsers/__init__.py
@@ -74,12 +74,12 @@ def parse_selection(expression, dataset):
try:
id1 = get_var(dataset, id1)
- except:
+ except Exception:
id1 = ast.literal_eval(id1)
try:
id2 = get_var(dataset, id2)
- except:
+ except Exception:
id2 = ast.literal_eval(id2)
return id1, op, id2
diff --git a/src/pydap/wsgi/app.py b/src/pydap/wsgi/app.py
index b735b10..578187e 100644
--- a/src/pydap/wsgi/app.py
+++ b/src/pydap/wsgi/app.py
@@ -155,7 +155,7 @@ def alphanum_key(s):
def tryint(s):
try:
return int(s)
- except:
+ except Exception:
return s
return [tryint(c) for c in re.split('([0-9]+)', s)]
diff --git a/src/pydap/wsgi/ssf.py b/src/pydap/wsgi/ssf.py
index e85eed4..785c7d4 100644
--- a/src/pydap/wsgi/ssf.py
+++ b/src/pydap/wsgi/ssf.py
@@ -183,10 +183,10 @@ def eval_function(dataset, function, functions):
try:
names = re.sub(r'\[.*?\]', '', str(token)).split('.')
return reduce(operator.getitem, [dataset] + names)
- except:
+ except Exception:
try:
return ast.literal_eval(token)
- except:
+ except Exception:
return token
args = map(parse, tokenize(args))
| requests missing from requirements
It appears pydap uses the requests pacakge, but it's not listed in the setup.py:
```
install_requires = [
'numpy',
'Webob',
'Jinja2',
'docopt',
'six >= 1.4.0',
'beautifulsoup4'
]
```
| pydap/pydap | diff --git a/src/pydap/tests/test_model.py b/src/pydap/tests/test_model.py
index c2e8fee..35e7e77 100644
--- a/src/pydap/tests/test_model.py
+++ b/src/pydap/tests/test_model.py
@@ -248,8 +248,10 @@ def test_StructureType_getitem():
"""Test item retrieval."""
var = StructureType("var")
child = BaseType("child")
+ child.data = np.array([[[0, 1]]])
var["child"] = child
assert var["child"] is child
+ assert var["child.child"] is child
with pytest.raises(KeyError):
var["unloved child"]
with pytest.raises(KeyError):
diff --git a/src/pydap/tests/test_responses_error.py b/src/pydap/tests/test_responses_error.py
index 70e35ab..3c9f06e 100644
--- a/src/pydap/tests/test_responses_error.py
+++ b/src/pydap/tests/test_responses_error.py
@@ -11,7 +11,7 @@ class TestErrorResponse(unittest.TestCase):
# create an exception that would happen in runtime
try:
1/0
- except:
+ except Exception:
error = ErrorResponse(sys.exc_info())
req = Request.blank('/')
| {
"commit_name": "merge_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": 0,
"test_score": 3
},
"num_modified_files": 8
} | 3.2 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[server,handlers.netcdf,testing]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-attrib",
"requests-mock",
"requests"
],
"pre_install": [
"apt-get update",
"apt-get install -y libhdf5-serial-dev netcdf-bin libnetcdf-dev"
],
"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
beautifulsoup4==4.12.3
certifi==2021.5.30
cftime==1.6.0
charset-normalizer==2.0.12
coards==1.0.5
coverage==6.2
docopt==0.6.2
flake8==5.0.4
gsw==3.0.6
gunicorn==21.2.0
idna==3.10
importlib-metadata==4.2.0
iniconfig==1.1.1
Jinja2==3.0.3
lxml==5.3.1
MarkupSafe==2.0.1
mccabe==0.7.0
netCDF4==1.6.2
numpy==1.19.5
ordereddict==1.1
packaging==21.3
PasteDeploy==2.1.1
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
-e git+https://github.com/pydap/pydap.git@4ae73e393b0d52bce9d1cf5571945a9ed884d526#egg=Pydap
pyflakes==2.5.0
pyparsing==3.1.4
pytest==7.0.1
pytest-attrib==0.1.3
pytest-cov==4.0.0
requests==2.27.1
requests-mock==1.12.1
six==1.17.0
soupsieve==2.3.2.post1
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
waitress==2.0.0
WebOb==1.8.9
WebTest==3.0.0
zipp==3.6.0
| name: pydap
channels:
- defaults
- https://repo.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
- beautifulsoup4==4.12.3
- cftime==1.6.0
- charset-normalizer==2.0.12
- coards==1.0.5
- coverage==6.2
- docopt==0.6.2
- flake8==5.0.4
- gsw==3.0.6
- gunicorn==21.2.0
- idna==3.10
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- jinja2==3.0.3
- lxml==5.3.1
- markupsafe==2.0.1
- mccabe==0.7.0
- netcdf4==1.6.2
- numpy==1.19.5
- ordereddict==1.1
- packaging==21.3
- pastedeploy==2.1.1
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pytest==7.0.1
- pytest-attrib==0.1.3
- pytest-cov==4.0.0
- requests==2.27.1
- requests-mock==1.12.1
- six==1.17.0
- soupsieve==2.3.2.post1
- tomli==1.2.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- waitress==2.0.0
- webob==1.8.9
- webtest==3.0.0
- zipp==3.6.0
prefix: /opt/conda/envs/pydap
| [
"src/pydap/tests/test_model.py::test_StructureType_getitem"
]
| []
| [
"src/pydap/tests/test_model.py::test_DapType_quote",
"src/pydap/tests/test_model.py::test_DapType_attributes",
"src/pydap/tests/test_model.py::test_DapType_id",
"src/pydap/tests/test_model.py::test_DapType_repr",
"src/pydap/tests/test_model.py::test_DapType_id_property",
"src/pydap/tests/test_model.py::test_DapType_getattr",
"src/pydap/tests/test_model.py::test_DapType_children",
"src/pydap/tests/test_model.py::test_BaseType_no_data",
"src/pydap/tests/test_model.py::test_BaseType_data_and_dimensions",
"src/pydap/tests/test_model.py::test_BaseType_repr",
"src/pydap/tests/test_model.py::test_BaseType_dtype",
"src/pydap/tests/test_model.py::test_BaseType_shape",
"src/pydap/tests/test_model.py::test_BaseType_size",
"src/pydap/tests/test_model.py::test_BaseType_ndim",
"src/pydap/tests/test_model.py::test_BaseType_copy",
"src/pydap/tests/test_model.py::test_BaseType_comparisons",
"src/pydap/tests/test_model.py::test_BaseType_sequence_protocol",
"src/pydap/tests/test_model.py::test_BaseType_iter_protocol",
"src/pydap/tests/test_model.py::test_BaseType_array",
"src/pydap/tests/test_model.py::test_StructureType_init",
"src/pydap/tests/test_model.py::test_StructureType_instance",
"src/pydap/tests/test_model.py::test_StructureType_repr",
"src/pydap/tests/test_model.py::test_StructureType_len",
"src/pydap/tests/test_model.py::test_StructureType_contains",
"src/pydap/tests/test_model.py::test_StructureType_lazy_attribute",
"src/pydap/tests/test_model.py::test_StructureType_children",
"src/pydap/tests/test_model.py::test_StructureType_setitem",
"src/pydap/tests/test_model.py::test_StructureType_getitem_tuple",
"src/pydap/tests/test_model.py::test_StructureType_delitem",
"src/pydap/tests/test_model.py::test_StructureType_get_data",
"src/pydap/tests/test_model.py::test_StructureType_set_data",
"src/pydap/tests/test_model.py::test_StructureType_copy",
"src/pydap/tests/test_model.py::test_DatasetType_setitem",
"src/pydap/tests/test_model.py::test_DatasetType_id",
"src/pydap/tests/test_model.py::test_SequenceType_data",
"src/pydap/tests/test_model.py::test_SequenceType_len",
"src/pydap/tests/test_model.py::test_SequenceType_iterdata",
"src/pydap/tests/test_model.py::test_SequenceType_iter",
"src/pydap/tests/test_model.py::test_SequenceType_iter_deprecation",
"src/pydap/tests/test_model.py::test_SequenceType_items",
"src/pydap/tests/test_model.py::test_SequenceType_values",
"src/pydap/tests/test_model.py::test_SequenceType_getitem",
"src/pydap/tests/test_model.py::test_SequenceType_copy",
"src/pydap/tests/test_model.py::test_GridType_repr",
"src/pydap/tests/test_model.py::test_GridType_dtype",
"src/pydap/tests/test_model.py::test_GridType_shape",
"src/pydap/tests/test_model.py::test_GridType_size",
"src/pydap/tests/test_model.py::test_GridType_ndim",
"src/pydap/tests/test_model.py::test_GridType_len",
"src/pydap/tests/test_model.py::test_GridType_getitem",
"src/pydap/tests/test_model.py::test_GridType_getitem_not_tuple",
"src/pydap/tests/test_model.py::test_GridType_array",
"src/pydap/tests/test_model.py::test_GridType_array2",
"src/pydap/tests/test_model.py::test_GridType_maps",
"src/pydap/tests/test_model.py::test_GridType_dimensions",
"src/pydap/tests/test_responses_error.py::TestErrorResponse::test_body",
"src/pydap/tests/test_responses_error.py::TestErrorResponse::test_charset",
"src/pydap/tests/test_responses_error.py::TestErrorResponse::test_content_type",
"src/pydap/tests/test_responses_error.py::TestErrorResponse::test_headers",
"src/pydap/tests/test_responses_error.py::TestErrorResponse::test_status"
]
| []
| MIT License | 1,694 | [
"src/pydap/handlers/lib.py",
"src/pydap/lib.py",
"setup.py",
"src/pydap/parsers/__init__.py",
"src/pydap/model.py",
"src/pydap/handlers/csv/__init__.py",
"src/pydap/wsgi/ssf.py",
"src/pydap/wsgi/app.py"
]
| [
"src/pydap/handlers/lib.py",
"src/pydap/lib.py",
"setup.py",
"src/pydap/parsers/__init__.py",
"src/pydap/model.py",
"src/pydap/handlers/csv/__init__.py",
"src/pydap/wsgi/ssf.py",
"src/pydap/wsgi/app.py"
]
|
jupyterhub__kubespawner-84 | ae1c6d6f58a45c2ba4b9e2fa81d50b16503f9874 | 2017-09-21 23:51:11 | 054f6d61cb23232983ca3db74177b2732f15de14 | diff --git a/jupyterhub_config.py b/jupyterhub_config.py
index cce2c68..e59a17d 100644
--- a/jupyterhub_config.py
+++ b/jupyterhub_config.py
@@ -19,6 +19,7 @@ c.KubeSpawner.singleuser_image_spec = 'yuvipanda/simple-singleuser:v1'
# The spawned containers need to be able to talk to the hub through the proxy!
c.KubeSpawner.hub_connect_ip = os.environ['HUB_CONNECT_IP']
+c.KubeSpawner.singleuser_service_account = 'default'
# Do not use any authentication at all - any username / password will work.
c.JupyterHub.authenticator_class = 'dummyauthenticator.DummyAuthenticator'
diff --git a/kubespawner/objects.py b/kubespawner/objects.py
index 36ea5da..3848f2e 100644
--- a/kubespawner/objects.py
+++ b/kubespawner/objects.py
@@ -7,6 +7,8 @@ from kubernetes.client.models.v1_pod_spec import V1PodSpec
from kubernetes.client.models.v1_object_meta import V1ObjectMeta
from kubernetes.client.models.v1_pod_security_context import V1PodSecurityContext
from kubernetes.client.models.v1_local_object_reference import V1LocalObjectReference
+from kubernetes.client.models.v1_volume import V1Volume
+from kubernetes.client.models.v1_volume_mount import V1VolumeMount
from kubernetes.client.models.v1_container import V1Container
from kubernetes.client.models.v1_security_context import V1SecurityContext
@@ -40,6 +42,7 @@ def make_pod(
mem_guarantee,
lifecycle_hooks,
init_containers,
+ service_account,
):
"""
Make a k8s pod specification for running a user notebook.
@@ -106,6 +109,8 @@ def make_pod(
Dictionary of lifecycle hooks
- init_containers:
List of initialization containers belonging to the pod.
+ - service_account:
+ Service account to mount on the pod. None disables mounting
"""
pod = V1Pod()
@@ -150,6 +155,28 @@ def make_pod(
notebook_container.lifecycle = lifecycle_hooks
notebook_container.resources = V1ResourceRequirements()
+ if service_account is None:
+ # Add a hack to ensure that no service accounts are mounted in spawned pods
+ # This makes sure that we don"t accidentally give access to the whole
+ # kubernetes API to the users in the spawned pods.
+ # Note: We don't simply use `automountServiceAccountToken` here since we wanna be compatible
+ # with older kubernetes versions too for now.
+ hack_volume = V1Volume()
+ hack_volume.name = "no-api-access-please"
+ hack_volume.empty_dir = {}
+ hack_volumes = [hack_volume]
+
+ hack_volume_mount = V1VolumeMount()
+ hack_volume_mount.name = "no-api-access-please"
+ hack_volume_mount.mount_path = "/var/run/secrets/kubernetes.io/serviceaccount"
+ hack_volume_mount.read_only = True
+ hack_volume_mounts = [hack_volume_mount]
+ else:
+ hack_volumes = []
+ hack_volume_mounts = []
+
+ pod.service_account_name = service_account
+
if run_privileged:
container_security_context = V1SecurityContext()
container_security_context.privileged = True
@@ -167,11 +194,11 @@ def make_pod(
notebook_container.resources.limits['cpu'] = cpu_limit
if mem_limit:
notebook_container.resources.limits['memory'] = mem_limit
- notebook_container.volume_mounts = volume_mounts
+ notebook_container.volume_mounts = volume_mounts + hack_volume_mounts
pod.spec.containers.append(notebook_container)
pod.spec.init_containers = init_containers
- pod.spec.volumes = volumes
+ pod.spec.volumes = volumes + hack_volumes
return pod
diff --git a/kubespawner/spawner.py b/kubespawner/spawner.py
index 24a50e3..19e6c38 100644
--- a/kubespawner/spawner.py
+++ b/kubespawner/spawner.py
@@ -21,8 +21,6 @@ from traitlets.config import SingletonConfigurable
from traitlets import Type, Unicode, List, Integer, Union, Dict, Bool, Any
from jupyterhub.spawner import Spawner
from jupyterhub.traitlets import Command
-from kubernetes.client.models.v1_volume import V1Volume
-from kubernetes.client.models.v1_volume_mount import V1VolumeMount
from kubernetes.client.rest import ApiException
from kubernetes import client
import escapism
@@ -149,6 +147,24 @@ class KubeSpawner(Spawner):
"""
).tag(config=True)
+ singleuser_service_account = Unicode(
+ None,
+ allow_none=True,
+ config=True,
+ help="""
+ The service account to be mounted in the spawned user pod.
+
+ When set to None (the default), no service account is mounted, and the default service account
+ is explicitly disabled.
+
+ This serviceaccount must already exist in the namespace the user pod is being spawned in.
+
+ WARNING: Be careful with this configuration! Make sure the service account being mounted
+ has the minimal permissions needed, and nothing more. When misconfigured, this can easily
+ give arbitrary users root over your entire cluster.
+ """
+ )
+
pod_name_template = Unicode(
'jupyter-{username}',
config=True,
@@ -623,19 +639,6 @@ class KubeSpawner(Spawner):
else:
real_cmd = None
- # Add a hack to ensure that no service accounts are mounted in spawned pods
- # This makes sure that we don"t accidentally give access to the whole
- # kubernetes API to the users in the spawned pods.
- # See https://github.com/kubernetes/kubernetes/issues/16779#issuecomment-157460294
- hack_volume = V1Volume()
- hack_volume.name = "no-api-access-please"
- hack_volume.empty_dir = {}
-
- hack_volume_mount = V1VolumeMount()
- hack_volume_mount.name = "no-api-access-please"
- hack_volume_mount.mount_path = "/var/run/secrets/kubernetes.io/serviceaccount"
- hack_volume_mount.read_only = True
-
# Default set of labels, picked up from
# https://github.com/kubernetes/helm/blob/master/docs/chart_best_practices/labels.md
labels = {
@@ -659,8 +662,8 @@ class KubeSpawner(Spawner):
fs_gid=singleuser_fs_gid,
run_privileged=self.singleuser_privileged,
env=self.get_env(),
- volumes=self._expand_all(self.volumes) + [hack_volume],
- volume_mounts=self._expand_all(self.volume_mounts) + [hack_volume_mount],
+ volumes=self._expand_all(self.volumes),
+ volume_mounts=self._expand_all(self.volume_mounts),
working_dir=self.singleuser_working_dir,
labels=labels,
cpu_limit=self.cpu_limit,
@@ -669,6 +672,7 @@ class KubeSpawner(Spawner):
mem_guarantee=self.mem_guarantee,
lifecycle_hooks=self.singleuser_lifecycle_hooks,
init_containers=self.singleuser_init_containers,
+ service_account=self.singleuser_service_account
)
def get_pvc_manifest(self):
| Add support for setting singleuser service account
Currently we disable all service account mounting from inside the pod.
We should allow people to:
1. Specify that the default serviceaccount needs to be mounted
2. Specify that an arbitrary service account should be created and then mounted.
The default would still be no sa, but would be something you can override. This would be great for people who wanna launch helm charts from inside the notebook. | jupyterhub/kubespawner | diff --git a/tests/test_objects.py b/tests/test_objects.py
index a95ab56..5994de1 100644
--- a/tests/test_objects.py
+++ b/tests/test_objects.py
@@ -33,6 +33,7 @@ def test_make_simplest_pod():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -51,14 +52,14 @@ def test_make_simplest_pod():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {},
"requests": {}
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -90,6 +91,7 @@ def test_make_labeled_pod():
labels={"test": "true"},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -108,14 +110,14 @@ def test_make_labeled_pod():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {},
"requests": {}
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -147,6 +149,7 @@ def test_make_pod_with_image_pull_secrets():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -168,14 +171,14 @@ def test_make_pod_with_image_pull_secrets():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {},
"requests": {}
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -208,6 +211,7 @@ def test_set_pod_uid_fs_gid():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -229,14 +233,14 @@ def test_set_pod_uid_fs_gid():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {},
"requests": {}
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -268,6 +272,7 @@ def test_run_privileged_container():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -293,10 +298,10 @@ def test_run_privileged_container():
"securityContext": {
"privileged": True,
},
- "volumeMounts": []
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -328,6 +333,7 @@ def test_make_pod_resources_all():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -348,7 +354,7 @@ def test_make_pod_resources_all():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {
"cpu": 2,
@@ -361,7 +367,7 @@ def test_make_pod_resources_all():
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -396,6 +402,7 @@ def test_make_pod_with_env():
labels={},
lifecycle_hooks=None,
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -414,7 +421,7 @@ def test_make_pod_with_env():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {
},
@@ -423,7 +430,7 @@ def test_make_pod_with_env():
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -461,6 +468,7 @@ def test_make_pod_with_lifecycle():
}
},
init_containers=None,
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -479,7 +487,7 @@ def test_make_pod_with_lifecycle():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {
},
@@ -495,7 +503,7 @@ def test_make_pod_with_lifecycle():
}
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
@@ -539,6 +547,7 @@ def test_make_pod_with_init_containers():
'command': ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;']
}
],
+ service_account=None
)) == {
"metadata": {
"name": "test",
@@ -557,7 +566,7 @@ def test_make_pod_with_init_containers():
"name": "notebook-port",
"containerPort": 8888
}],
- 'volumeMounts': [],
+ 'volumeMounts': [{'name': 'no-api-access-please', 'mountPath': '/var/run/secrets/kubernetes.io/serviceaccount', 'readOnly': True}],
"resources": {
"limits": {
},
@@ -579,7 +588,7 @@ def test_make_pod_with_init_containers():
"command": ["sh", "-c", "until nslookup mydb; do echo waiting for mydb; sleep 2; done;"]
}
],
- 'volumes': [],
+ 'volumes': [{'name': 'no-api-access-please', 'emptyDir': {}}],
},
"kind": "Pod",
"apiVersion": "v1"
| {
"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": 3,
"issue_text_score": 1,
"test_score": 3
},
"num_modified_files": 3
} | 0.6 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.6",
"reqs_path": [
"requirements/base.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | alembic==1.7.7
async-generator==1.10
attrs==22.2.0
cachetools==4.2.4
certifi==2021.5.30
certipy==0.1.3
cffi==1.15.1
charset-normalizer==2.0.12
cryptography==40.0.2
decorator==5.1.1
entrypoints==0.4
escapism==1.0.1
google-auth==2.22.0
greenlet==2.0.2
idna==3.10
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
ipaddress==1.0.23
ipython-genutils==0.2.0
Jinja2==3.0.3
jsonschema==3.2.0
jupyter-telemetry==0.1.0
jupyterhub==2.3.1
-e git+https://github.com/jupyterhub/kubespawner.git@ae1c6d6f58a45c2ba4b9e2fa81d50b16503f9874#egg=jupyterhub_kubespawner
kubernetes==3.0.0
Mako==1.1.6
MarkupSafe==2.0.1
oauthlib==3.2.2
packaging==21.3
pamela==1.2.0
pluggy==1.0.0
prometheus-client==0.17.1
py==1.11.0
pyasn1==0.5.1
pyasn1-modules==0.3.0
pycparser==2.21
pyOpenSSL==23.2.0
pyparsing==3.1.4
pyrsistent==0.18.0
pytest==7.0.1
python-dateutil==2.9.0.post0
python-json-logger==2.0.7
PyYAML==6.0.1
requests==2.27.1
rsa==4.9
ruamel.yaml==0.18.3
ruamel.yaml.clib==0.2.8
six==1.17.0
SQLAlchemy==1.4.54
tomli==1.2.3
tornado==6.1
traitlets==4.3.3
typing_extensions==4.1.1
urllib3==1.26.20
websocket-client==0.40.0
zipp==3.6.0
| name: kubespawner
channels:
- defaults
- https://repo.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:
- alembic==1.7.7
- async-generator==1.10
- attrs==22.2.0
- cachetools==4.2.4
- certipy==0.1.3
- cffi==1.15.1
- charset-normalizer==2.0.12
- cryptography==40.0.2
- decorator==5.1.1
- entrypoints==0.4
- escapism==1.0.1
- google-auth==2.22.0
- greenlet==2.0.2
- idna==3.10
- importlib-metadata==4.8.3
- importlib-resources==5.4.0
- iniconfig==1.1.1
- ipaddress==1.0.23
- ipython-genutils==0.2.0
- jinja2==3.0.3
- jsonschema==3.2.0
- jupyter-telemetry==0.1.0
- jupyterhub==2.3.1
- kubernetes==3.0.0
- mako==1.1.6
- markupsafe==2.0.1
- oauthlib==3.2.2
- packaging==21.3
- pamela==1.2.0
- pluggy==1.0.0
- prometheus-client==0.17.1
- py==1.11.0
- pyasn1==0.5.1
- pyasn1-modules==0.3.0
- pycparser==2.21
- pyopenssl==23.2.0
- pyparsing==3.1.4
- pyrsistent==0.18.0
- pytest==7.0.1
- python-dateutil==2.9.0.post0
- python-json-logger==2.0.7
- pyyaml==6.0.1
- requests==2.27.1
- rsa==4.9
- ruamel-yaml==0.18.3
- ruamel-yaml-clib==0.2.8
- six==1.17.0
- sqlalchemy==1.4.54
- tomli==1.2.3
- tornado==6.1
- traitlets==4.3.3
- typing-extensions==4.1.1
- urllib3==1.26.20
- websocket-client==0.40.0
- zipp==3.6.0
prefix: /opt/conda/envs/kubespawner
| [
"tests/test_objects.py::test_make_simplest_pod",
"tests/test_objects.py::test_make_labeled_pod",
"tests/test_objects.py::test_make_pod_with_image_pull_secrets",
"tests/test_objects.py::test_set_pod_uid_fs_gid",
"tests/test_objects.py::test_run_privileged_container",
"tests/test_objects.py::test_make_pod_resources_all",
"tests/test_objects.py::test_make_pod_with_env",
"tests/test_objects.py::test_make_pod_with_lifecycle",
"tests/test_objects.py::test_make_pod_with_init_containers"
]
| []
| [
"tests/test_objects.py::test_make_pvc_simple",
"tests/test_objects.py::test_make_resources_all"
]
| []
| BSD 3-Clause "New" or "Revised" License | 1,695 | [
"jupyterhub_config.py",
"kubespawner/objects.py",
"kubespawner/spawner.py"
]
| [
"jupyterhub_config.py",
"kubespawner/objects.py",
"kubespawner/spawner.py"
]
|
|
OpenMined__PySyft-250 | 6d94259b46fb6516ab20773cbbb9bb6ddac3d3cd | 2017-09-23 09:32:13 | 06ce023225dd613d8fb14ab2046135b93ab22376 | diff --git a/syft/tensor.py b/syft/tensor.py
index 02a63a36d7..553420c417 100644
--- a/syft/tensor.py
+++ b/syft/tensor.py
@@ -1200,6 +1200,21 @@ class TensorBase(object):
out_flat = [s if m == 0 else source_iter.__next__().item() for m, s in mask_self_iter]
self.data = np.reshape(out_flat, self.data.shape)
+ def eq(self, t):
+ """Returns a new Tensor having boolean True values where an element of the calling tensor is equal to the second Tensor, False otherwise.
+ The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor."""
+ if self.encrypted:
+ return NotImplemented
+ return TensorBase(np.equal(self.data, _ensure_tensorbase(t).data))
+
+ def eq_(self, t):
+ """Writes in-place, boolean True values where an element of the calling tensor is equal to the second Tensor, False otherwise.
+ The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor."""
+ if self.encrypted:
+ return NotImplemented
+ self.data = np.equal(self.data, _ensure_tensorbase(t).data)
+ return self
+
def mv(tensormat, tensorvector):
""" matrix and vector multiplication """
| Implement Default eq Functionality for Base Tensor Type
**User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, eq() should return a new tensor and eq_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation.
**Acceptance Criteria:**
- If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error.
- a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors.
- inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. | OpenMined/PySyft | diff --git a/tests/test_tensor.py b/tests/test_tensor.py
index 3ca9315457..e8429080be 100644
--- a/tests/test_tensor.py
+++ b/tests/test_tensor.py
@@ -908,5 +908,29 @@ class masked_scatter_Tests(unittest.TestCase):
self.assertTrue(np.array_equal(t, TensorBase([[1, 2, 3], [1, 1, 1]])))
+class eqTests(unittest.TestCase):
+ def testEqWithTensor(self):
+ t1 = TensorBase(np.arange(5))
+ t2 = TensorBase(np.arange(5)[-1::-1])
+ truth_values = t1.eq(t2)
+ self.assertEqual(truth_values, [False, False, True, False, False])
+
+ def testEqWithNumber(self):
+ t1 = TensorBase(np.arange(5))
+ truth_values = t1.eq(1)
+ self.assertEqual(truth_values, [False, True, False, False, False])
+
+ def testEqInPlaceWithTensor(self):
+ t1 = TensorBase(np.arange(5))
+ t2 = TensorBase(np.arange(5)[-1::-1])
+ t1.eq_(t2)
+ self.assertEqual(t1, [False, False, True, False, False])
+
+ def testEqInPlaceWithNumber(self):
+ t1 = TensorBase(np.arange(5))
+ t1.eq_(1)
+ self.assertEqual(t1, [False, True, False, False, False])
+
+
if __name__ == "__main__":
unittest.main()
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 1
} | PySyft/hydrogen | {
"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-flake8"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc musl-dev g++ libgmp3-dev libmpfr-dev ca-certificates libmpc-dev"
],
"python": "3.6",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | args==0.1.0
attrs==22.2.0
certifi==2021.5.30
clint==0.5.1
flake8==5.0.4
importlib-metadata==4.2.0
iniconfig==1.1.1
line-profiler==4.1.3
mccabe==0.7.0
numpy==1.19.5
packaging==21.3
phe==1.5.0
pluggy==1.0.0
py==1.11.0
pycodestyle==2.9.1
pyflakes==2.5.0
pyparsing==3.1.4
pyRserve==1.0.4
pytest==7.0.1
pytest-flake8==1.1.1
scipy==1.5.4
-e git+https://github.com/OpenMined/PySyft.git@6d94259b46fb6516ab20773cbbb9bb6ddac3d3cd#egg=syft
tomli==1.2.3
typing_extensions==4.1.1
zipp==3.6.0
| name: PySyft
channels:
- defaults
- https://repo.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:
- args==0.1.0
- attrs==22.2.0
- clint==0.5.1
- flake8==5.0.4
- importlib-metadata==4.2.0
- iniconfig==1.1.1
- line-profiler==4.1.3
- mccabe==0.7.0
- numpy==1.19.5
- packaging==21.3
- phe==1.5.0
- pluggy==1.0.0
- py==1.11.0
- pycodestyle==2.9.1
- pyflakes==2.5.0
- pyparsing==3.1.4
- pyrserve==1.0.4
- pytest==7.0.1
- pytest-flake8==1.1.1
- scipy==1.5.4
- tomli==1.2.3
- typing-extensions==4.1.1
- zipp==3.6.0
prefix: /opt/conda/envs/PySyft
| [
"tests/test_tensor.py::eqTests::testEqInPlaceWithNumber",
"tests/test_tensor.py::eqTests::testEqInPlaceWithTensor",
"tests/test_tensor.py::eqTests::testEqWithNumber",
"tests/test_tensor.py::eqTests::testEqWithTensor"
]
| []
| [
"tests/test_tensor.py::DimTests::testAsView",
"tests/test_tensor.py::DimTests::testDimOne",
"tests/test_tensor.py::DimTests::testResize",
"tests/test_tensor.py::DimTests::testResizeAs",
"tests/test_tensor.py::DimTests::testSize",
"tests/test_tensor.py::DimTests::testView",
"tests/test_tensor.py::AddTests::testInplace",
"tests/test_tensor.py::AddTests::testScalar",
"tests/test_tensor.py::AddTests::testSimple",
"tests/test_tensor.py::CeilTests::testCeil",
"tests/test_tensor.py::CeilTests::testCeil_",
"tests/test_tensor.py::ZeroTests::testZero",
"tests/test_tensor.py::FloorTests::testFloor_",
"tests/test_tensor.py::SubTests::testInplace",
"tests/test_tensor.py::SubTests::testScalar",
"tests/test_tensor.py::SubTests::testSimple",
"tests/test_tensor.py::MaxTests::testAxis",
"tests/test_tensor.py::MaxTests::testNoDim",
"tests/test_tensor.py::MultTests::testInplace",
"tests/test_tensor.py::MultTests::testScalar",
"tests/test_tensor.py::MultTests::testSimple",
"tests/test_tensor.py::DivTests::testInplace",
"tests/test_tensor.py::DivTests::testScalar",
"tests/test_tensor.py::DivTests::testSimple",
"tests/test_tensor.py::AbsTests::testabs",
"tests/test_tensor.py::AbsTests::testabs_",
"tests/test_tensor.py::ShapeTests::testShape",
"tests/test_tensor.py::SqrtTests::testSqrt",
"tests/test_tensor.py::SqrtTests::testSqrt_",
"tests/test_tensor.py::SumTests::testDimIsNotNoneInt",
"tests/test_tensor.py::SumTests::testDimNoneInt",
"tests/test_tensor.py::EqualTests::testEqOp",
"tests/test_tensor.py::EqualTests::testEqual",
"tests/test_tensor.py::EqualTests::testIneqOp",
"tests/test_tensor.py::EqualTests::testNotEqual",
"tests/test_tensor.py::IndexTests::testIndexing",
"tests/test_tensor.py::sigmoidTests::testSigmoid",
"tests/test_tensor.py::addmm::testaddmm1d",
"tests/test_tensor.py::addmm::testaddmm2d",
"tests/test_tensor.py::addmm::testaddmm_1d",
"tests/test_tensor.py::addmm::testaddmm_2d",
"tests/test_tensor.py::addcmulTests::testaddcmul1d",
"tests/test_tensor.py::addcmulTests::testaddcmul2d",
"tests/test_tensor.py::addcmulTests::testaddcmul_1d",
"tests/test_tensor.py::addcmulTests::testaddcmul_2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv2d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_1d",
"tests/test_tensor.py::addcdivTests::testaddcdiv_2d",
"tests/test_tensor.py::addmvTests::testaddmv",
"tests/test_tensor.py::addmvTests::testaddmv_",
"tests/test_tensor.py::addbmmTests::testaddbmm",
"tests/test_tensor.py::addbmmTests::testaddbmm_",
"tests/test_tensor.py::baddbmmTests::testbaddbmm",
"tests/test_tensor.py::baddbmmTests::testbaddbmm_",
"tests/test_tensor.py::transposeTests::testT",
"tests/test_tensor.py::transposeTests::testT_",
"tests/test_tensor.py::transposeTests::testTranspose",
"tests/test_tensor.py::transposeTests::testTranspose_",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze",
"tests/test_tensor.py::unsqueezeTests::testUnsqueeze_",
"tests/test_tensor.py::expTests::testexp",
"tests/test_tensor.py::expTests::testexp_",
"tests/test_tensor.py::fracTests::testfrac",
"tests/test_tensor.py::fracTests::testfrac_",
"tests/test_tensor.py::rsqrtTests::testrsqrt",
"tests/test_tensor.py::rsqrtTests::testrsqrt_",
"tests/test_tensor.py::signTests::testsign",
"tests/test_tensor.py::signTests::testsign_",
"tests/test_tensor.py::numpyTests::testnumpy",
"tests/test_tensor.py::reciprocalTests::testreciprocal",
"tests/test_tensor.py::reciprocalTests::testrsqrt_",
"tests/test_tensor.py::logTests::testLog",
"tests/test_tensor.py::logTests::testLog1p",
"tests/test_tensor.py::logTests::testLog1p_",
"tests/test_tensor.py::logTests::testLog_",
"tests/test_tensor.py::clampTests::testClampFloat",
"tests/test_tensor.py::clampTests::testClampFloatInPlace",
"tests/test_tensor.py::clampTests::testClampInt",
"tests/test_tensor.py::clampTests::testClampIntInPlace",
"tests/test_tensor.py::cloneTests::testClone",
"tests/test_tensor.py::chunkTests::testChunk",
"tests/test_tensor.py::chunkTests::testChunkSameSize",
"tests/test_tensor.py::gtTests::testGtInPlaceWithNumber",
"tests/test_tensor.py::gtTests::testGtInPlaceWithTensor",
"tests/test_tensor.py::gtTests::testGtWithNumber",
"tests/test_tensor.py::gtTests::testGtWithTensor",
"tests/test_tensor.py::bernoulliTests::testBernoulli",
"tests/test_tensor.py::bernoulliTests::testBernoulli_",
"tests/test_tensor.py::uniformTests::testUniform",
"tests/test_tensor.py::uniformTests::testUniform_",
"tests/test_tensor.py::fillTests::testFill_",
"tests/test_tensor.py::topkTests::testTopK",
"tests/test_tensor.py::tolistTests::testToList",
"tests/test_tensor.py::traceTests::testTrace",
"tests/test_tensor.py::roundTests::testRound",
"tests/test_tensor.py::roundTests::testRound_",
"tests/test_tensor.py::repeatTests::testRepeat",
"tests/test_tensor.py::powTests::testPow",
"tests/test_tensor.py::powTests::testPow_",
"tests/test_tensor.py::prodTests::testProd",
"tests/test_tensor.py::randomTests::testRandom_",
"tests/test_tensor.py::nonzeroTests::testNonZero",
"tests/test_tensor.py::cumprodTest::testCumprod",
"tests/test_tensor.py::cumprodTest::testCumprod_",
"tests/test_tensor.py::splitTests::testSplit",
"tests/test_tensor.py::squeezeTests::testSqueeze",
"tests/test_tensor.py::expandAsTests::testExpandAs",
"tests/test_tensor.py::meanTests::testMean",
"tests/test_tensor.py::notEqualTests::testNe",
"tests/test_tensor.py::notEqualTests::testNe_",
"tests/test_tensor.py::index_selectTests::testIndex_select",
"tests/test_tensor.py::gatherTests::testGatherNumerical1",
"tests/test_tensor.py::gatherTests::testGatherNumerical2",
"tests/test_tensor.py::scatterTests::testScatter_DimOutOfRange",
"tests/test_tensor.py::scatterTests::testScatter_IndexOutOfRange",
"tests/test_tensor.py::scatterTests::testScatter_IndexType",
"tests/test_tensor.py::scatterTests::testScatter_Numerical0",
"tests/test_tensor.py::scatterTests::testScatter_Numerical1",
"tests/test_tensor.py::scatterTests::testScatter_Numerical2",
"tests/test_tensor.py::scatterTests::testScatter_Numerical3",
"tests/test_tensor.py::scatterTests::testScatter_Numerical4",
"tests/test_tensor.py::scatterTests::testScatter_Numerical5",
"tests/test_tensor.py::scatterTests::testScatter_Numerical6",
"tests/test_tensor.py::scatterTests::testScatter_index_src_dimension_mismatch",
"tests/test_tensor.py::masked_scatter_Tests::testMasked_scatter_1",
"tests/test_tensor.py::masked_scatter_Tests::testMasked_scatter_braodcasting1",
"tests/test_tensor.py::masked_scatter_Tests::testMasked_scatter_braodcasting2"
]
| []
| Apache License 2.0 | 1,696 | [
"syft/tensor.py"
]
| [
"syft/tensor.py"
]
|
|
witchard__grole-9 | 58338694c664442a76e3c64e277c1873d13e2420 | 2017-09-23 16:40:17 | 58338694c664442a76e3c64e277c1873d13e2420 | diff --git a/grole.py b/grole.py
index be7559d..d1443fd 100755
--- a/grole.py
+++ b/grole.py
@@ -15,6 +15,7 @@ import pathlib
import html
import sys
import argparse
+import logging
from collections import defaultdict
__author__ = 'witchard'
@@ -310,6 +311,7 @@ class Grole:
self._handlers = defaultdict(list)
self.env = {'doc': []}
self.env.update(env)
+ self._logger = logging.getLogger('grole')
def route(self, path_regex, methods=['GET'], doc=True):
"""
@@ -338,7 +340,7 @@ class Grole:
Parses requests, finds appropriate handlers and returns responses
"""
peer = writer.get_extra_info('peername')
- print('New connection from {}'.format(peer))
+ self._logger.debug('New connection from {}'.format(peer))
try:
# Loop handling requests
while True:
@@ -361,7 +363,7 @@ class Grole:
res = Response(data=res)
except:
# Error - log it and return 500
- traceback.print_exc()
+ self._logger.error(traceback.format_exc())
res = Response(code=500, reason='Internal Server Error')
break
@@ -371,9 +373,9 @@ class Grole:
# Respond
await res._write(writer)
- print('{}: {} -> {}'.format(peer, req.path, res.code))
+ self._logger.info('{}: {} -> {}'.format(peer, req.path, res.code))
except EOFError:
- print('Connection closed from {}'.format(peer))
+ self._logger.debug('Connection closed from {}'.format(peer))
def run(self, host='localhost', port=1234):
"""
@@ -390,7 +392,7 @@ class Grole:
server = loop.run_until_complete(coro)
# Run the server
- print('Serving on {}'.format(server.sockets[0].getsockname()))
+ self._logger.info('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
@@ -414,6 +416,11 @@ def parse_args(args=sys.argv[1:]):
default='.')
parser.add_argument('-n', '--noindex', help='do not show directory indexes',
default=False, action='store_true')
+ loglevel = parser.add_mutually_exclusive_group()
+ loglevel.add_argument('-v', '--verbose', help='verbose logging',
+ default=False, action='store_true')
+ loglevel.add_argument('-q', '--quiet', help='quiet logging',
+ default=False, action='store_true')
return parser.parse_args(args)
def main(args=sys.argv[1:]):
@@ -421,6 +428,12 @@ def main(args=sys.argv[1:]):
Run Grole static file server
"""
args = parse_args(args)
+ if args.verbose:
+ logging.basicConfig(level=logging.DEBUG)
+ elif args.quiet:
+ logging.basicConfig(level=logging.ERROR)
+ else:
+ logging.basicConfig(level=logging.INFO)
app = Grole()
serve_static(app, '', args.directory, not args.noindex)
app.run(args.address, args.port)
| Use logging library instead of print | witchard/grole | diff --git a/test/test_args.py b/test/test_args.py
index 5c50383..97a2df6 100644
--- a/test/test_args.py
+++ b/test/test_args.py
@@ -10,11 +10,21 @@ class TestArgs(unittest.TestCase):
self.assertEqual(args.port, 1234)
self.assertEqual(args.directory, '.')
self.assertEqual(args.noindex, False)
+ self.assertEqual(args.verbose, False)
+ self.assertEqual(args.quiet, False)
def test_override(self):
- args = grole.parse_args(['-a', 'foo', '-p', '27', '-d', 'bar', '-n'])
+ args = grole.parse_args(['-a', 'foo', '-p', '27', '-d', 'bar', '-n', '-v'])
self.assertEqual(args.address, 'foo')
self.assertEqual(args.port, 27)
self.assertEqual(args.directory, 'bar')
self.assertEqual(args.noindex, True)
+ self.assertEqual(args.verbose, True)
+ self.assertEqual(args.quiet, False)
+ def test_error(self):
+ try:
+ grole.parse_args(['-q', '-v'])
+ except SystemExit:
+ return
+ self.fail('Did not error on mutually exclusive args')
| {
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 2,
"test_score": 3
},
"num_modified_files": 1
} | 0.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "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
-e git+https://github.com/witchard/grole.git@58338694c664442a76e3c64e277c1873d13e2420#egg=grole
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
packaging @ file:///croot/packaging_1734472117206/work
pluggy @ file:///croot/pluggy_1733169602837/work
pytest @ file:///croot/pytest_1738938843180/work
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
| name: grole
channels:
- defaults
- https://repo.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/grole
| [
"test/test_args.py::TestArgs::test_defaults",
"test/test_args.py::TestArgs::test_override"
]
| []
| [
"test/test_args.py::TestArgs::test_error"
]
| []
| MIT License | 1,697 | [
"grole.py"
]
| [
"grole.py"
]
|
|
scitokens__scitokens-35 | d0cd927709952237b90727b30a41f1a0503f13e9 | 2017-09-24 02:38:23 | d0cd927709952237b90727b30a41f1a0503f13e9 | diff --git a/src/scitokens/scitokens.py b/src/scitokens/scitokens.py
index 7fc173e..68ecaa9 100644
--- a/src/scitokens/scitokens.py
+++ b/src/scitokens/scitokens.py
@@ -138,10 +138,34 @@ class SciToken(object):
"""
self._claims[claim] = value
+ def __getitem__(self, claim):
+ """
+ Access the value corresponding to a particular claim; will
+ return claims from both the verified and unverified claims.
+
+ If a claim is not present, then a KeyError is thrown.
+ """
+ if claim in self._claims:
+ return self._claims[claim]
+ if claim in self._verified_claims:
+ return self._verified_claims[claim]
+ raise KeyError(claim)
+
+ def get(self, claim, default=None, verified_only=False):
+ """
+ Return the value associated with a claim, returning the
+ default if the claim is not present. If `verified_only` is
+ True, then a claim is returned only if it is in the verified claims
+ """
+ if verified_only:
+ return self._verified_claims.get(claim, default)
+ return self._claims.get(claim, self._verified_claims.get(claim, default))
+
def clone_chain(self):
"""
Return a new, empty SciToken
"""
+ raise NotImplementedError()
def _deserialize_key(self, key_serialized, unverified_headers):
"""
| Implement `__getitem__`
We should provide a `__getitem__` to allow access of claims.
Open question: should we allow access to verified claims only -- or all claims? | scitokens/scitokens | diff --git a/tests/test_scitokens.py b/tests/test_scitokens.py
index fb30675..1fa48a2 100644
--- a/tests/test_scitokens.py
+++ b/tests/test_scitokens.py
@@ -4,6 +4,9 @@ import sys
import time
import unittest
+import cryptography.hazmat.backends
+import cryptography.hazmat.primitives.asymmetric.rsa
+
# Allow unittests to be run from within the project base.
if os.path.exists("src"):
sys.path.append("src")
@@ -37,7 +40,12 @@ class TestEnforcer(unittest.TestCase):
def setUp(self):
now = time.time()
- self._token = scitokens.SciToken()
+ private_key = cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(
+ public_exponent=65537,
+ key_size=2048,
+ backend=cryptography.hazmat.backends.default_backend()
+ )
+ self._token = scitokens.SciToken(key=private_key)
self._token["foo"] = "bar"
self._token["iat"] = int(now)
self._token["exp"] = int(now + 600)
@@ -45,7 +53,9 @@ class TestEnforcer(unittest.TestCase):
self._token["nbf"] = int(now)
def test_enforce(self):
-
+ """
+ Test the Enforcer object.
+ """
def always_accept(value):
if value or not value:
return True
@@ -72,6 +82,25 @@ class TestEnforcer(unittest.TestCase):
enf.add_validator("foo", always_accept)
self.assertTrue(enf.test(self._token, "read", "/foo/bar"), msg=enf.last_failure)
+ def test_getitem(self):
+ """
+ Test the getters for the SciTokens object.
+ """
+ self.assertEqual(self._token['foo'], 'bar')
+ with self.assertRaises(KeyError):
+ self._token['bar']
+ self.assertEqual(self._token.get('baz'), None)
+ self.assertEqual(self._token.get('foo', 'baz'), 'bar')
+ self.assertEqual(self._token.get('foo', 'baz', verified_only=True), 'baz')
+ self._token.serialize()
+ self.assertEqual(self._token['foo'], 'bar')
+ self.assertEqual(self._token.get('foo', 'baz'), 'bar')
+ self.assertEqual(self._token.get('bar', 'baz'), 'baz')
+ self.assertEqual(self._token.get('bar', 'baz', verified_only=True), 'baz')
+ self._token['bar'] = '1'
+ self.assertEqual(self._token.get('bar', 'baz', verified_only=False), '1')
+ self.assertEqual(self._token.get('bar', 'baz', verified_only=True), 'baz')
+
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": 2,
"issue_text_score": 2,
"test_score": 1
},
"num_modified_files": 1
} | 0.1 | {
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
} | cffi==1.17.1
cryptography==44.0.2
exceptiongroup==1.2.2
iniconfig==2.1.0
packaging==24.2
pluggy==1.5.0
pycparser==2.22
PyJWT==2.10.1
pytest==8.3.5
-e git+https://github.com/scitokens/scitokens.git@d0cd927709952237b90727b30a41f1a0503f13e9#egg=scitokens
tomli==2.2.1
| name: scitokens
channels:
- defaults
- https://repo.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:
- cffi==1.17.1
- cryptography==44.0.2
- exceptiongroup==1.2.2
- iniconfig==2.1.0
- packaging==24.2
- pluggy==1.5.0
- pycparser==2.22
- pyjwt==2.10.1
- pytest==8.3.5
- tomli==2.2.1
prefix: /opt/conda/envs/scitokens
| [
"tests/test_scitokens.py::TestEnforcer::test_getitem"
]
| []
| [
"tests/test_scitokens.py::TestValidation::test_valid",
"tests/test_scitokens.py::TestEnforcer::test_enforce"
]
| []
| Apache License 2.0 | 1,698 | [
"src/scitokens/scitokens.py"
]
| [
"src/scitokens/scitokens.py"
]
|
|
ARMmbed__greentea-237 | 86f5ec3211a8f7f324bcdd3201012945ee0534ac | 2017-09-25 13:51:40 | 86f5ec3211a8f7f324bcdd3201012945ee0534ac | diff --git a/mbed_greentea/mbed_report_api.py b/mbed_greentea/mbed_report_api.py
index da3f0d9..82acb5c 100644
--- a/mbed_greentea/mbed_report_api.py
+++ b/mbed_greentea/mbed_report_api.py
@@ -38,6 +38,13 @@ def exporter_json(test_result_ext, test_suite_properties=None):
@details This is a machine friendly format
"""
import json
+ for target in test_result_ext.values():
+ for suite in target.values():
+ try:
+ suite["single_test_output"] = suite["single_test_output"]\
+ .decode("unicode_escape")
+ except KeyError:
+ pass
return json.dumps(test_result_ext, indent=4)
@@ -211,7 +218,10 @@ def exporter_testcase_junit(test_result_ext, test_suite_properties=None):
test_cases.append(tc)
ts_name = target_name
- test_build_properties = test_suite_properties[target_name] if target_name in test_suite_properties else None
+ if test_suite_properties and target_name in test_suite_properties:
+ test_build_properties = test_suite_properties[target_name]
+ else:
+ test_build_properties = None
ts = TestSuite(ts_name, test_cases, properties=test_build_properties)
test_suites.append(ts)
@@ -584,7 +594,9 @@ def get_result_overlay_dropdowns(result_div_id, test_results):
result_output_div_id = "%s_output" % result_div_id
result_output_dropdown = get_dropdown_html(result_output_div_id,
"Test Output",
- test_results['single_test_output'].rstrip("\n"),
+ test_results['single_test_output']
+ .decode("unicode-escape")
+ .rstrip("\n"),
output_text=True)
# Add a dropdown for the testcases if they are present
@@ -740,10 +752,14 @@ def exporter_html(test_result_ext, test_suite_properties=None):
test_results['single_test_count'] += 1
result_class = get_result_colour_class(test_results['single_test_result'])
+ try:
+ percent_pass = int((test_results['single_test_passes']*100.0)/test_results['single_test_count'])
+ except ZeroDivisionError:
+ percent_pass = 100
this_row += result_cell_template % (result_class,
result_div_id,
test_results['single_test_result'],
- int((test_results['single_test_passes']*100.0)/test_results['single_test_count']),
+ percent_pass,
test_results['single_test_passes'],
test_results['single_test_count'],
result_overlay)
| mbedgt crash with float division by zero
Hi
Here is my command:
mbedgt -V -v -t NUCLEO_F401RE-ARM,NUCLEO_F401RE-GCC_ARM,NUCLEO_F401RE-IAR,NUCLEO_F410RB-ARM,NUCLEO_F410RB-GCC_ARM,NUCLEO_F410RB-IAR,NUCLEO_F411RE-ARM,NUCLEO_F411RE-GCC_ARM,NUCLEO_F411RE-IAR --report-html=/c/xxx.html
It has crashed:
...
mbedgt: all tests finished!
mbedgt: shuffle seed: 0.3680156551
mbedgt: exporting to HTML file
mbedgt: unexpected error:
float division by zero
Traceback (most recent call last):
File "C:\Python27\Scripts\mbedgt-script.py", line 11, in <module>
load_entry_point('mbed-greentea==1.2.6', 'console_scripts', 'mbedgt')()
File "c:\python27\lib\site-packages\mbed_greentea\mbed_greentea_cli.py", line 401, in main
cli_ret = main_cli(opts, args)
File "c:\python27\lib\site-packages\mbed_greentea\mbed_greentea_cli.py", line 1050, in main_cli
html_report = exporter_html(test_report)
File "c:\python27\lib\site-packages\mbed_greentea\mbed_report_api.py", line 747, in exporter_html
int((test_results['single_test_passes']*100.0)/test_results['single_test_count']),
ZeroDivisionError: float division by zero
| ARMmbed/greentea | diff --git a/test/report_api.py b/test/report_api.py
new file mode 100644
index 0000000..122e26e
--- /dev/null
+++ b/test/report_api.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python
+"""
+mbed SDK
+Copyright (c) 2017 ARM Limited
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import unittest
+from mock import patch
+
+from mbed_greentea.mbed_report_api import exporter_html, \
+ exporter_memory_metrics_csv, exporter_testcase_junit, \
+ exporter_testcase_text, exporter_text, exporter_json
+
+
+class ReportEmitting(unittest.TestCase):
+
+
+ report_fns = [exporter_html, exporter_memory_metrics_csv,
+ exporter_testcase_junit, exporter_testcase_text,
+ exporter_text, exporter_json]
+ def test_report_zero_tests(self):
+ test_data = {}
+ for report_fn in self.report_fns:
+ report_fn(test_data)
+
+ def test_report_zero_testcases(self):
+ test_data = {
+ 'k64f-gcc_arm': {
+ 'garbage_test_suite' :{
+ u'single_test_result': u'NOT_RAN',
+ u'elapsed_time': 0.0,
+ u'build_path': u'N/A',
+ u'build_path_abs': u'N/A',
+ u'copy_method': u'N/A',
+ u'image_path': u'N/A',
+ u'single_test_output': b'N/A',
+ u'platform_name': u'k64f',
+ u'test_bin_name': u'N/A',
+ u'testcase_result': {},
+ }
+ }
+ }
+ for report_fn in self.report_fns:
+ report_fn(test_data)
| {
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 1
},
"num_modified_files": 1
} | 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"
} | appdirs==1.4.4
beautifulsoup4==4.13.3
certifi==2025.1.31
charset-normalizer==3.4.1
colorama==0.3.9
coverage==7.8.0
exceptiongroup==1.2.2
execnet==2.1.1
fasteners==0.19
future==1.0.0
idna==3.10
iniconfig==2.1.0
intelhex==2.3.0
junit-xml==1.9
lockfile==0.12.2
-e git+https://github.com/ARMmbed/greentea.git@86f5ec3211a8f7f324bcdd3201012945ee0534ac#egg=mbed_greentea
mbed-host-tests==1.8.15
mbed-ls==1.8.15
mbed-os-tools==1.8.15
mock==5.2.0
packaging==24.2
pluggy==1.5.0
prettytable==2.5.0
pyserial==3.5
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==6.0.0
pytest-mock==3.14.0
pytest-xdist==3.6.1
requests==2.32.3
six==1.17.0
soupsieve==2.6
tomli==2.2.1
typing_extensions==4.13.0
urllib3==2.3.0
wcwidth==0.2.13
| name: greentea
channels:
- defaults
- https://repo.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:
- appdirs==1.4.4
- beautifulsoup4==4.13.3
- certifi==2025.1.31
- charset-normalizer==3.4.1
- colorama==0.3.9
- coverage==7.8.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- fasteners==0.19
- future==1.0.0
- idna==3.10
- iniconfig==2.1.0
- intelhex==2.3.0
- junit-xml==1.9
- lockfile==0.12.2
- mbed-host-tests==1.8.15
- mbed-ls==1.8.15
- mbed-os-tools==1.8.15
- mock==5.2.0
- packaging==24.2
- pluggy==1.5.0
- prettytable==2.5.0
- pyserial==3.5
- pytest==8.3.5
- pytest-asyncio==0.26.0
- pytest-cov==6.0.0
- pytest-mock==3.14.0
- pytest-xdist==3.6.1
- requests==2.32.3
- six==1.17.0
- soupsieve==2.6
- tomli==2.2.1
- typing-extensions==4.13.0
- urllib3==2.3.0
- wcwidth==0.2.13
prefix: /opt/conda/envs/greentea
| [
"test/report_api.py::ReportEmitting::test_report_zero_testcases"
]
| []
| [
"test/report_api.py::ReportEmitting::test_report_zero_tests"
]
| []
| Apache License 2.0 | 1,701 | [
"mbed_greentea/mbed_report_api.py"
]
| [
"mbed_greentea/mbed_report_api.py"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.