instance_id
stringlengths
10
57
patch
stringlengths
261
37.7k
repo
stringlengths
7
53
base_commit
stringlengths
40
40
hints_text
stringclasses
301 values
test_patch
stringlengths
212
2.22M
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
4.94k
PASS_TO_PASS
listlengths
0
7.82k
meta
dict
created_at
stringlengths
25
25
license
stringclasses
8 values
__index_level_0__
int64
0
6.41k
qiboteam__qibo-642
diff --git a/src/qibo/gates/abstract.py b/src/qibo/gates/abstract.py index 00c79562b..831f7a379 100644 --- a/src/qibo/gates/abstract.py +++ b/src/qibo/gates/abstract.py @@ -340,6 +340,11 @@ class ParametrizedGate(Gate): for gate in self.device_gates: # pragma: no cover gate.parameters = x + def on_qubits(self, qubit_map): + gate = super().on_qubits(qubit_map) + gate.parameters = self.parameters + return gate + def substitute_symbols(self): params = list(self._parameters) for i, param in self.symbolic_parameters.items(): diff --git a/src/qibo/gates/gates.py b/src/qibo/gates/gates.py index e08b185c6..0fb66e0e3 100644 --- a/src/qibo/gates/gates.py +++ b/src/qibo/gates/gates.py @@ -1264,6 +1264,7 @@ class Unitary(ParametrizedGate): if self.is_controlled_by: controls = (qubit_map.get(i) for i in self.control_qubits) gate = gate.controlled_by(*controls) + gate.parameters = self.parameters return gate def _dagger(self):
qiboteam/qibo
dce74ac77755ab0a0b88fd93c91d0b6d604a00e9
diff --git a/src/qibo/tests/test_models_circuit_parametrized.py b/src/qibo/tests/test_models_circuit_parametrized.py index 6fb28f60f..3314c49c7 100644 --- a/src/qibo/tests/test_models_circuit_parametrized.py +++ b/src/qibo/tests/test_models_circuit_parametrized.py @@ -190,6 +190,27 @@ def test_set_parameters_with_gate_fusion(backend, trainable): backend.assert_circuitclose(fused_c, c) [email protected]("trainable", [True, False]) +def test_set_parameters_with_light_cone(backend, trainable): + """Check updating parameters of light cone circuit.""" + params = np.random.random(4) + c = Circuit(4) + c.add(gates.RX(0, theta=params[0], trainable=trainable)) + c.add(gates.RY(1, theta=params[1])) + c.add(gates.CZ(0, 1)) + c.add(gates.RX(2, theta=params[2])) + c.add(gates.RY(3, theta=params[3], trainable=trainable)) + c.add(gates.CZ(2, 3)) + if trainable: + c.set_parameters(np.random.random(4)) + else: + c.set_parameters(np.random.random(2)) + target_state = backend.execute_circuit(c) + lc, _ = c.light_cone(1, 2) + final_state = backend.execute_circuit(lc) + backend.assert_allclose(final_state, target_state) + + def test_variable_theta(): """Check that parametrized gates accept `tf.Variable` parameters.""" try:
Circuit.light_cone() resets phases of parametrized gates Example: ```python3 from qibo import gates as gt from qibo.models import Circuit from numpy import asarray, pi from numpy.random import rand qubits = 7 depth = 2 circuit = Circuit(qubits) for _ in range(depth): for qubit in range(qubits): circuit.add(gt.U3(qubit, 0, 0, 0)) cnots_even = asarray([[k, k + 1] for k in range(0, qubits - 1, 2)]) cnots_odd = asarray([[k, k + 1] for k in range(1, qubits - 1, 2)]) for row in cnots_even: circuit.add(gt.CNOT(*row)) for row in cnots_odd: circuit.add(gt.CNOT(*row)) phases = list() for _ in range(depth): p = rand(qubits, 3) p[:, 0] = p[:, 0] * pi p[:, 1] = p[:, 1] * 2*pi p[:, 1] = p[:, 2] * 2*pi phases.append(p) phases = asarray(phases).flatten().reshape(qubits * depth, 3) circuit.set_parameters(phases) print(circuit.get_parameters()) cone = circuit.copy(True) cone.add((gt.Y(k) for k in [1, 2])) cone = cone.light_cone(1, 2)[0] print(cone.get_parameters()) ``` I have tried `cone.set_parameters(phases)` after the deep copy, but it doesn't solve the issue. No matter what, phases are set to 0 after `light_cone()`
0.0
dce74ac77755ab0a0b88fd93c91d0b6d604a00e9
[ "src/qibo/tests/test_models_circuit_parametrized.py::test_set_parameters_with_light_cone[numpy-True]", "src/qibo/tests/test_models_circuit_parametrized.py::test_set_parameters_with_light_cone[numpy-False]" ]
[ "src/qibo/tests/test_models_circuit_parametrized.py::test_rx_parameter_setter[numpy]", "src/qibo/tests/test_models_circuit_parametrized.py::test_set_parameters_with_list[numpy-True]", "src/qibo/tests/test_models_circuit_parametrized.py::test_set_parameters_with_list[numpy-False]", "src/qibo/tests/test_models_circuit_parametrized.py::test_circuit_set_parameters_ungates[numpy-None-True]", "src/qibo/tests/test_models_circuit_parametrized.py::test_circuit_set_parameters_ungates[numpy-None-False]", "src/qibo/tests/test_models_circuit_parametrized.py::test_set_parameters_with_gate_fusion[numpy-True]", "src/qibo/tests/test_models_circuit_parametrized.py::test_set_parameters_with_gate_fusion[numpy-False]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-09-13 08:46:27+00:00
apache-2.0
5,135
qiboteam__qibo-915
diff --git a/doc/source/api-reference/qibo.rst b/doc/source/api-reference/qibo.rst index a38f23454..5285fb7ae 100644 --- a/doc/source/api-reference/qibo.rst +++ b/doc/source/api-reference/qibo.rst @@ -1157,6 +1157,18 @@ Purity .. autofunction:: qibo.quantum_info.purity +Concurrence +""""""""""" + +.. autofunction:: qibo.quantum_info.concurrence + + +Entanglement of formation +""""""""""""""""""""""""" + +.. autofunction:: qibo.quantum_info.entanglement_of_formation + + Entropy """"""" diff --git a/pyproject.toml b/pyproject.toml index 1900176b2..ec165b904 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api" [tool.poetry] name = "qibo" -version = "0.1.14" +version = "0.1.15" description = "A framework for quantum computing with hardware acceleration." authors = ["The Qibo team"] license = "Apache License 2.0" diff --git a/src/qibo/models/error_mitigation.py b/src/qibo/models/error_mitigation.py index 5e8af12f6..561198dc4 100644 --- a/src/qibo/models/error_mitigation.py +++ b/src/qibo/models/error_mitigation.py @@ -383,7 +383,7 @@ def vnCDR( val (list): Expectation value of `observable` with increased noise levels. optimal_params (list): Optimal values for `params`. train_val (dict): Contains the noise-free and noisy expectation values obtained - with the training circuits. + with the training circuits. """ # Set backend diff --git a/src/qibo/quantum_info/metrics.py b/src/qibo/quantum_info/metrics.py index 11de8b2f0..353a67826 100644 --- a/src/qibo/quantum_info/metrics.py +++ b/src/qibo/quantum_info/metrics.py @@ -28,12 +28,130 @@ def purity(state): else: pur = np.real(np.trace(np.dot(state, state))) + # this is necessary to remove the float from inside + # a 0-dim ndarray pur = float(pur) return pur -def entropy(state, base: float = 2, validate: bool = False, backend=None): +def concurrence(state, bipartition, check_purity: bool = True, backend=None): + """Calculates concurrence of a pure bipartite quantum state + :math:`\\rho \\in \\mathcal{H}_{A} \\otimes \\mathcal{H}_{B}` as + + .. math:: + C(\\rho) = \\sqrt{2 \\, (\\text{tr}^{2}(\\rho) - \\text{tr}(\\rho_{B}^{2}))} \\, , + + where :math:`\\rho_{B} = \\text{tr}_{B}(\\rho)` is the reduced density operator + obtained by tracing out the qubits in the ``bipartition`` :math:`B`. + + Args: + state (ndarray): statevector or density matrix. + bipartition (list or tuple or ndarray): qubits in the subsystem to be traced out. + check_purity (bool, optional): if ``True``, checks if ``state`` is pure. If ``False``, + it assumes ``state`` is pure . Defaults to ``True``. + backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be used + in the execution. If ``None``, it uses :class:`qibo.backends.GlobalBackend`. + Defaults to ``None``. + + Returns: + float: Concurrence of :math:`\\rho`. + """ + if backend is None: # pragma: no cover + backend = GlobalBackend() + + if ( + (len(state.shape) not in [1, 2]) + or (len(state) == 0) + or (len(state.shape) == 2 and state.shape[0] != state.shape[1]) + ): + raise_error( + TypeError, + f"Object must have dims either (k,) or (k,k), but have dims {state.shape}.", + ) + + if isinstance(check_purity, bool) is False: + raise_error( + TypeError, + f"check_purity must be type bool, but it is type {type(check_purity)}.", + ) + + nqubits = int(np.log2(state.shape[0])) + + if check_purity is True: + purity_total_system = purity(state) + + mixed = bool(abs(purity_total_system - 1.0) > PRECISION_TOL) + if mixed is True: + raise_error( + NotImplementedError, + "concurrence only implemented for pure quantum states.", + ) + + reduced_density_matrix = ( + backend.partial_trace(state, bipartition, nqubits) + if len(state.shape) == 1 + else backend.partial_trace_density_matrix(state, bipartition, nqubits) + ) + + purity_reduced = purity(reduced_density_matrix) + if purity_reduced - 1.0 > 0.0: + purity_reduced = round(purity_reduced, 7) + + concur = np.sqrt(2 * (1 - purity_reduced)) + + return concur + + +def entanglement_of_formation( + state, bipartition, base: float = 2, check_purity: bool = True, backend=None +): + """Calculates the entanglement of formation :math:`E_{f}` of a pure bipartite + quantum state :math:`\\rho`, which is given by + + .. math:: + E_{f} = H([1 - x, x]) \\, , + + where + + .. math:: + x = \\frac{1 + \\sqrt{1 - C^{2}(\\rho)}}{2} \\, , + + :math:`C(\\rho)` is the :func:`qibo.quantum_info.concurrence` of :math:`\\rho`, + and :math:`H` is the :func:`qibo.quantum_info.shannon_entropy`. + + Args: + state (ndarray): statevector or density matrix. + bipartition (list or tuple or ndarray): qubits in the subsystem to be traced out. + base (float): the base of the log in :func:`qibo.quantum_info.shannon_entropy`. + Defaults to :math:`2`. + check_purity (bool, optional): if ``True``, checks if ``state`` is pure. If ``False``, + it assumes ``state`` is pure . Default: ``True``. + backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be used + in the execution. If ``None``, it uses :class:`qibo.backends.GlobalBackend`. + Defaults to ``None``. + + + Returns: + float: entanglement of formation of state :math:`\\rho`. + """ + if backend is None: # pragma: no cover + backend = GlobalBackend() + + from qibo.quantum_info.utils import shannon_entropy + + concur = concurrence( + state, bipartition=bipartition, check_purity=check_purity, backend=backend + ) + concur = (1 + np.sqrt(1 - concur**2)) / 2 + probabilities = [1 - concur, concur] + + ent_of_form = shannon_entropy(probabilities, base=base, backend=backend) + + return ent_of_form + + +def entropy(state, base: float = 2, check_hermitian: bool = False, backend=None): """The von-Neumann entropy :math:`S(\\rho)` of a quantum state :math:`\\rho`, which is given by @@ -43,7 +161,7 @@ def entropy(state, base: float = 2, validate: bool = False, backend=None): Args: state (ndarray): statevector or density matrix. base (float, optional): the base of the log. Default: 2. - validate (bool, optional): if ``True``, checks if ``state`` is Hermitian. If ``False``, + check_hermitian (bool, optional): if ``True``, checks if ``state`` is Hermitian. If ``False``, it assumes ``state`` is Hermitian . Default: ``False``. backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be used in the execution. If ``None``, it uses @@ -71,7 +189,7 @@ def entropy(state, base: float = 2, validate: bool = False, backend=None): if purity(state) == 1.0: ent = 0.0 else: - if validate is True: + if check_hermitian is True: hermitian = bool( backend.calculate_norm(np.transpose(np.conj(state)) - state) < PRECISION_TOL @@ -115,7 +233,7 @@ def entanglement_entropy( state, bipartition, base: float = 2, - validate: bool = False, + check_hermitian: bool = False, backend=None, ): """Calculates the entanglement entropy :math:`S` of ``state`` :math:`\\rho`, @@ -131,7 +249,7 @@ def entanglement_entropy( state (ndarray): statevector or density matrix. bipartition (list or tuple or ndarray): qubits in the subsystem to be traced out. base (float, optional): the base of the log. Default: 2. - validate (bool, optional): if ``True``, checks if :math:`\\rho_{A}` is Hermitian. + check_hermitian (bool, optional): if ``True``, checks if :math:`\\rho_{A}` is Hermitian. If ``False``, it assumes ``state`` is Hermitian . Default: ``False``. backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be used in the execution. If ``None``, it uses @@ -165,13 +283,16 @@ def entanglement_entropy( ) entropy_entanglement = entropy( - reduced_density_matrix, base=base, validate=validate, backend=backend + reduced_density_matrix, + base=base, + check_hermitian=check_hermitian, + backend=backend, ) return entropy_entanglement -def trace_distance(state, target, validate: bool = False, backend=None): +def trace_distance(state, target, check_hermitian: bool = False, backend=None): """Trace distance between two quantum states, :math:`\\rho` and :math:`\\sigma`: .. math:: @@ -184,7 +305,7 @@ def trace_distance(state, target, validate: bool = False, backend=None): Args: state (ndarray): statevector or density matrix. target (ndarray): statevector or density matrix. - validate (bool, optional): if ``True``, checks if :math:`\\rho - \\sigma` is Hermitian. + check_hermitian (bool, optional): if ``True``, checks if :math:`\\rho - \\sigma` is Hermitian. If ``False``, it assumes the difference is Hermitian. Default: ``False``. backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be used in the execution. If ``None``, it uses :class:`qibo.backends.GlobalBackend`. @@ -214,7 +335,7 @@ def trace_distance(state, target, validate: bool = False, backend=None): target = np.outer(np.conj(target), target) difference = state - target - if validate: + if check_hermitian is True: hermitian = bool( backend.calculate_norm(np.transpose(np.conj(difference)) - difference) <= PRECISION_TOL @@ -278,7 +399,7 @@ def hilbert_schmidt_distance(state, target): return distance -def fidelity(state, target, validate: bool = False): +def fidelity(state, target, check_purity: bool = False): """Fidelity between two quantum states (when at least one state is pure). .. math:: @@ -292,7 +413,7 @@ def fidelity(state, target, validate: bool = False): Args: state (ndarray): statevector or density matrix. target (ndarray): statevector or density matrix. - validate (bool, optional): if ``True``, checks if one of the + check_purity (bool, optional): if ``True``, checks if one of the input states is pure. Defaults to ``False``. Returns: @@ -312,7 +433,7 @@ def fidelity(state, target, validate: bool = False): + f"but have dims {state.shape} and {target.shape}", ) - if validate: + if check_purity is True: purity_state = purity(state) purity_target = purity(target) if ( @@ -337,7 +458,7 @@ def fidelity(state, target, validate: bool = False): return fid -def bures_angle(state, target, validate: bool = False): +def bures_angle(state, target, check_purity: bool = False): """Calculates the Bures angle :math:`D_{A}` between a ``state`` :math:`\\rho` and a ``target`` state :math:`\\sigma`. This is given by @@ -350,18 +471,18 @@ def bures_angle(state, target, validate: bool = False): Args: state (ndarray): statevector or density matrix. target (ndarray): statevector or density matrix. - validate (bool, optional): if ``True``, checks if one of the + check_purity (bool, optional): if ``True``, checks if one of the input states is pure. Defaults to ``False``. Returns: float: Bures angle between ``state`` and ``target``. """ - angle = np.arccos(np.sqrt(fidelity(state, target, validate=validate))) + angle = np.arccos(np.sqrt(fidelity(state, target, check_purity=check_purity))) return angle -def bures_distance(state, target, validate: bool = False): +def bures_distance(state, target, check_purity: bool = False): """Calculates the Bures distance :math:`D_{B}` between a ``state`` :math:`\\rho` and a ``target`` state :math:`\\sigma`. This is given by @@ -374,18 +495,20 @@ def bures_distance(state, target, validate: bool = False): Args: state (ndarray): statevector or density matrix. target (ndarray): statevector or density matrix. - validate (bool, optional): if ``True``, checks if one of the + check_purity (bool, optional): if ``True``, checks if one of the input states is pure. Defaults to ``False``. Returns: float: Bures distance between ``state`` and ``target``. """ - distance = np.sqrt(2 * (1 - np.sqrt(fidelity(state, target, validate=validate)))) + distance = np.sqrt( + 2 * (1 - np.sqrt(fidelity(state, target, check_purity=check_purity))) + ) return distance -def process_fidelity(channel, target=None, validate: bool = False, backend=None): +def process_fidelity(channel, target=None, check_unitary: bool = False, backend=None): """Process fidelity between two quantum channels (when at least one channel is` unitary), .. math:: @@ -396,7 +519,7 @@ def process_fidelity(channel, target=None, validate: bool = False, backend=None) channel: quantum channel. target (optional): quantum channel. If ``None``, target is the Identity channel. Default: ``None``. - validate (bool, optional): if True, checks if one of the + check_unitary (bool, optional): if True, checks if one of the input channels is unitary. Default: ``False``. backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be used in the execution. If ``None``, it uses :class:`qibo.backends.GlobalBackend`. @@ -418,7 +541,7 @@ def process_fidelity(channel, target=None, validate: bool = False, backend=None) dim = int(np.sqrt(channel.shape[0])) - if validate: + if check_unitary is True: norm_channel = backend.calculate_norm( np.dot(np.conj(np.transpose(channel)), channel) - np.eye(dim**2) ) @@ -443,7 +566,9 @@ def process_fidelity(channel, target=None, validate: bool = False, backend=None) return fid -def average_gate_fidelity(channel, target=None, backend=None): +def average_gate_fidelity( + channel, target=None, check_unitary: bool = False, backend=None +): """Average gate fidelity between two quantum channels (when at least one channel is unitary), .. math:: @@ -460,6 +585,8 @@ def average_gate_fidelity(channel, target=None, backend=None): channel: quantum channel :math:`\\mathcal{E}`. target (optional): quantum channel :math:`\\mathcal{U}`. If ``None``, target is the Identity channel. Defaults to ``None``. + check_unitary (bool, optional): if True, checks if one of the + input channels is unitary. Default: ``False``. backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be used in the execution. If ``None``, it uses :class:`qibo.backends.GlobalBackend`. Defaults to ``None``. @@ -471,13 +598,15 @@ def average_gate_fidelity(channel, target=None, backend=None): dim = channel.shape[0] - process_fid = process_fidelity(channel, target, backend=backend) + process_fid = process_fidelity( + channel, target, check_unitary=check_unitary, backend=backend + ) process_fid = (dim * process_fid + 1) / (dim + 1) return process_fid -def gate_error(channel, target=None, backend=None): +def gate_error(channel, target=None, check_unitary: bool = False, backend=None): """Gate error between two quantum channels (when at least one is unitary), which is defined as @@ -491,6 +620,8 @@ def gate_error(channel, target=None, backend=None): channel: quantum channel :math:`\\mathcal{E}`. target (optional): quantum channel :math:`\\mathcal{U}`. If ``None``, target is the Identity channel. Defaults to ``None``. + check_unitary (bool, optional): if True, checks if one of the + input channels is unitary. Default: ``False``. backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be used in the execution. If ``None``, it uses :class:`qibo.backends.GlobalBackend`. Defaults to ``None``. @@ -498,7 +629,9 @@ def gate_error(channel, target=None, backend=None): Returns: float: Gate error between :math:`\\mathcal{E}` and :math:`\\mathcal{U}`. """ - error = 1 - average_gate_fidelity(channel, target, backend=backend) + error = 1 - average_gate_fidelity( + channel, target, check_unitary=check_unitary, backend=backend + ) return error @@ -507,7 +640,7 @@ def meyer_wallach_entanglement(circuit, backend=None): """Computes the Meyer-Wallach entanglement Q of the `circuit`, .. math:: - Q = 1-\\frac{1}{N}\\sum_{k}\\text{Tr}\\left(\\rho_k^2(\\theta_i)\\right) \\, + Q(\\theta) = 1 - \\frac{1}{N} \\, \\sum_{k} \\, \\text{tr}\\left(\\rho_{k^{2}}(\\theta)\\right) \\, . Args: circuit (:class:`qibo.models.Circuit`): Parametrized circuit. diff --git a/src/qibo/quantum_info/utils.py b/src/qibo/quantum_info/utils.py index a24ce866a..a5de30baf 100644 --- a/src/qibo/quantum_info/utils.py +++ b/src/qibo/quantum_info/utils.py @@ -82,7 +82,7 @@ def shannon_entropy(probability_array, base: float = 2, backend=None): Args: probability_array (ndarray or list): a probability array :math:`\\mathbf{p}`. - base (float): the base of the log. Default: 2. + base (float): the base of the log. Defaults to :math:`2`. backend (:class:`qibo.backends.abstract.Backend`, optional): backend to be used in the execution. If ``None``, it uses :class:`qibo.backends.GlobalBackend`. Defaults to ``None``.
qiboteam/qibo
0a84cb2607e4a5daefd0a4644f08b85d638eae10
diff --git a/tests/test_quantum_info_metrics.py b/tests/test_quantum_info_metrics.py index 3be875e48..dabbbe661 100644 --- a/tests/test_quantum_info_metrics.py +++ b/tests/test_quantum_info_metrics.py @@ -10,7 +10,8 @@ def test_purity(backend): with pytest.raises(TypeError): state = np.random.rand(2, 3) state = backend.cast(state, dtype=state.dtype) - purity(state) + test = purity(state) + state = np.array([1.0, 0.0, 0.0, 0.0]) state = backend.cast(state, dtype=state.dtype) backend.assert_allclose(purity(state), 1.0) @@ -21,26 +22,80 @@ def test_purity(backend): dim = 4 state = backend.identity_density_matrix(2) - state = backend.cast(state, dtype=state.dtype) backend.assert_allclose(purity(state), 1.0 / dim) [email protected]("validate", [False, True]) [email protected]("check_purity", [True, False]) [email protected]("base", [2, 10, np.e, 5]) [email protected]("bipartition", [[0], [1]]) +def test_concurrence_and_formation(backend, bipartition, base, check_purity): + with pytest.raises(TypeError): + state = np.random.rand(2, 3) + state = backend.cast(state, dtype=state.dtype) + test = concurrence( + state, bipartition=bipartition, check_purity=check_purity, backend=backend + ) + with pytest.raises(TypeError): + state = random_statevector(4, backend=backend) + test = concurrence( + state, bipartition=bipartition, check_purity="True", backend=backend + ) + + if check_purity is True: + with pytest.raises(NotImplementedError): + state = backend.identity_density_matrix(2, normalize=False) + test = concurrence(state, bipartition=bipartition, backend=backend) + + nqubits = 2 + dim = 2**nqubits + state = random_statevector(dim, backend=backend) + concur = concurrence( + state, bipartition=bipartition, check_purity=check_purity, backend=backend + ) + ent_form = entanglement_of_formation( + state, + bipartition=bipartition, + base=base, + check_purity=check_purity, + backend=backend, + ) + backend.assert_allclose(0.0 <= concur <= np.sqrt(2), True) + backend.assert_allclose(0.0 <= ent_form <= 1.0, True) + + state = np.kron( + random_density_matrix(2, pure=True, backend=backend), + random_density_matrix(2, pure=True, backend=backend), + ) + concur = concurrence(state, bipartition, check_purity=check_purity, backend=backend) + ent_form = entanglement_of_formation( + state, + bipartition=bipartition, + base=base, + check_purity=check_purity, + backend=backend, + ) + backend.assert_allclose(concur, 0.0, atol=10 * PRECISION_TOL) + backend.assert_allclose(ent_form, 0.0, atol=PRECISION_TOL) + + [email protected]("check_hermitian", [False, True]) @pytest.mark.parametrize("base", [2, 10, np.e, 5]) -def test_entropy(backend, base, validate): +def test_entropy(backend, base, check_hermitian): with pytest.raises(ValueError): state = np.array([1.0, 0.0]) state = backend.cast(state, dtype=state.dtype) - test = entropy(state, 0, validate=validate, backend=backend) + test = entropy(state, 0, check_hermitian=check_hermitian, backend=backend) with pytest.raises(TypeError): state = np.random.rand(2, 3) state = backend.cast(state, dtype=state.dtype) - test = entropy(state, base=base, validate=validate, backend=backend) + test = entropy( + state, base=base, check_hermitian=check_hermitian, backend=backend + ) if backend.__class__.__name__ == "CupyBackend": with pytest.raises(NotImplementedError): state = random_unitary(4) state = backend.cast(state, dtype=state.dtype) - test = entropy(state, base=base, validate=True, backend=backend) + test = entropy(state, base=base, check_hermitian=True, backend=backend) state = np.array([1.0, 0.0]) state = backend.cast(state, dtype=state.dtype) @@ -63,22 +118,27 @@ def test_entropy(backend, base, validate): backend.assert_allclose( backend.calculate_norm( - entropy(state, base, validate=validate, backend=backend) - test + entropy(state, base, check_hermitian=check_hermitian, backend=backend) + - test ) < PRECISION_TOL, True, ) [email protected]("validate", [False, True]) [email protected]("check_hermitian", [False, True]) @pytest.mark.parametrize("base", [2, 10, np.e, 5]) @pytest.mark.parametrize("bipartition", [[0], [1]]) -def test_entanglement_entropy(backend, bipartition, base, validate): +def test_entanglement_entropy(backend, bipartition, base, check_hermitian): with pytest.raises(ValueError): state = np.array([1.0, 0.0]) state = backend.cast(state, dtype=state.dtype) test = entanglement_entropy( - state, bipartition=bipartition, base=0, validate=validate, backend=backend + state, + bipartition=bipartition, + base=0, + check_hermitian=check_hermitian, + backend=backend, ) with pytest.raises(TypeError): state = np.random.rand(2, 3) @@ -87,7 +147,7 @@ def test_entanglement_entropy(backend, bipartition, base, validate): state, bipartition=bipartition, base=base, - validate=validate, + check_hermitian=check_hermitian, backend=backend, ) if backend.__class__.__name__ == "CupyBackend": @@ -98,7 +158,7 @@ def test_entanglement_entropy(backend, bipartition, base, validate): state, bipartition=bipartition, base=base, - validate=True, + check_hermitian=True, backend=backend, ) @@ -107,7 +167,11 @@ def test_entanglement_entropy(backend, bipartition, base, validate): state = backend.cast(state, dtype=state.dtype) entang_entrop = entanglement_entropy( - state, bipartition=bipartition, base=base, validate=validate, backend=backend + state, + bipartition=bipartition, + base=base, + check_hermitian=check_hermitian, + backend=backend, ) if base == 2: @@ -127,7 +191,11 @@ def test_entanglement_entropy(backend, bipartition, base, validate): ) entang_entrop = entanglement_entropy( - state, bipartition=bipartition, base=base, validate=validate, backend=backend + state, + bipartition=bipartition, + base=base, + check_hermitian=check_hermitian, + backend=backend, ) backend.assert_allclose(entang_entrop, 0.0, atol=PRECISION_TOL) @@ -159,7 +227,7 @@ def test_trace_distance(backend): target = backend.cast(target, dtype=target.dtype) backend.assert_allclose(trace_distance(state, target, backend=backend), 0.0) backend.assert_allclose( - trace_distance(state, target, validate=True, backend=backend), 0.0 + trace_distance(state, target, check_hermitian=True, backend=backend), 0.0 ) state = np.outer(np.conj(state), state) @@ -168,7 +236,7 @@ def test_trace_distance(backend): target = backend.cast(target, dtype=target.dtype) backend.assert_allclose(trace_distance(state, target, backend=backend), 0.0) backend.assert_allclose( - trace_distance(state, target, validate=True, backend=backend), 0.0 + trace_distance(state, target, check_hermitian=True, backend=backend), 0.0 ) state = np.array([0.0, 1.0, 0.0, 0.0]) @@ -177,7 +245,7 @@ def test_trace_distance(backend): target = backend.cast(target, dtype=target.dtype) backend.assert_allclose(trace_distance(state, target, backend=backend), 1.0) backend.assert_allclose( - trace_distance(state, target, validate=True, backend=backend), 1.0 + trace_distance(state, target, check_hermitian=True, backend=backend), 1.0 ) @@ -241,7 +309,7 @@ def test_fidelity_and_bures(backend): target = np.random.rand(2, 2) state = backend.cast(state, dtype=state.dtype) target = backend.cast(target, dtype=target.dtype) - fidelity(state, target, validate=True) + fidelity(state, target, check_purity=True) state = np.array([0.0, 0.0, 0.0, 1.0]) target = np.array([0.0, 0.0, 0.0, 1.0]) @@ -279,13 +347,13 @@ def test_process_fidelity(backend): with pytest.raises(TypeError): channel = np.random.rand(d**2, d**2) channel = backend.cast(channel, dtype=channel.dtype) - process_fidelity(channel, validate=True, backend=backend) + process_fidelity(channel, check_unitary=True, backend=backend) with pytest.raises(TypeError): channel = np.random.rand(d**2, d**2) target = np.random.rand(d**2, d**2) channel = backend.cast(channel, dtype=channel.dtype) target = backend.cast(target, dtype=target.dtype) - process_fidelity(channel, target, validate=True, backend=backend) + process_fidelity(channel, target, check_unitary=True, backend=backend) channel = np.eye(d**2) channel = backend.cast(channel, dtype=channel.dtype)
Add `concurrence` and `entanglement_of_formation` to `quantum_info` As title says, those two functions are important and current missing
0.0
0a84cb2607e4a5daefd0a4644f08b85d638eae10
[ "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition0-2-False]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition0-2-True]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition0-10-False]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition0-10-True]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition0-2.718281828459045-False]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition0-2.718281828459045-True]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition0-5-False]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition0-5-True]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition1-2-False]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition1-2-True]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition1-10-False]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition1-10-True]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition1-2.718281828459045-False]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition1-2.718281828459045-True]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition1-5-False]", "tests/test_quantum_info_metrics.py::test_entanglement_entropy[numpy-bipartition1-5-True]", "tests/test_quantum_info_metrics.py::test_trace_distance[numpy]", "tests/test_quantum_info_metrics.py::test_fidelity_and_bures[numpy]" ]
[ "tests/test_quantum_info_metrics.py::test_purity[numpy]", "tests/test_quantum_info_metrics.py::test_hilbert_schmidt_distance[numpy]", "tests/test_quantum_info_metrics.py::test_process_fidelity[numpy]", "tests/test_quantum_info_metrics.py::test_meyer_wallach_entanglement[numpy]", "tests/test_quantum_info_metrics.py::test_entangling_capability[numpy]", "tests/test_quantum_info_metrics.py::test_expressibility[numpy]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-24 13:47:54+00:00
apache-2.0
5,136
qiboteam__qibo-953
diff --git a/src/qibo/backends/npmatrices.py b/src/qibo/backends/npmatrices.py index 1413dbf04..80498321d 100644 --- a/src/qibo/backends/npmatrices.py +++ b/src/qibo/backends/npmatrices.py @@ -241,19 +241,29 @@ class NumpyMatrices: dtype=self.dtype, ) - def MS(self, phi0, phi1): + def MS(self, phi0, phi1, theta): plus = self.np.exp(1.0j * (phi0 + phi1)) minus = self.np.exp(1.0j * (phi0 - phi1)) return self.np.array( [ - [1, 0, 0, -1.0j * self.np.conj(plus)], - [0, 1, -1.0j * self.np.conj(minus), 0], - [0, -1.0j * minus, 1, 0], - [-1.0j * plus, 0, 0, 1], + [ + self.np.cos(theta / 2), + 0, + 0, + -1.0j * self.np.conj(plus) * self.np.sin(theta / 2), + ], + [ + 0, + self.np.cos(theta / 2), + -1.0j * self.np.conj(minus) * self.np.sin(theta / 2), + 0, + ], + [0, -1.0j * minus * self.np.sin(theta / 2), self.np.cos(theta / 2), 0], + [-1.0j * plus * self.np.sin(theta / 2), 0, 0, self.np.cos(theta / 2)], ], dtype=self.dtype, - ) / self.np.sqrt(2) + ) @cached_property def TOFFOLI(self): diff --git a/src/qibo/gates/gates.py b/src/qibo/gates/gates.py index c8a913861..11744621d 100644 --- a/src/qibo/gates/gates.py +++ b/src/qibo/gates/gates.py @@ -1374,16 +1374,17 @@ class RZZ(_Rnn_): class MS(ParametrizedGate): - """The Mølmer–Sørensen (MS) gate is a two qubit gate native to trapped ions. + """The (partially entangling) Mølmer–Sørensen (MS) gate + is a two qubit gate native to trapped ions. Corresponds to the following unitary matrix .. math:: - \\frac{1}{\\sqrt{2}} \\, \\begin{pmatrix} - 1 & 0 & 0 & -i e^{-i( \\phi_0 + \\phi_1)} \\\\ - 0 & 1 & -i e^{-i( \\phi_0 - \\phi_1)} \\\\ - 0 & -i e^{i( \\phi_0 - \\phi_1)} & 1 & 0 \\\\ - -i e^{i( \\phi_0 + \\phi_1)} & 0 & 0 & 1 \\\\ + \\begin{pmatrix} + \\cos(\\theta / 2) & 0 & 0 & -i e^{-i( \\phi_0 + \\phi_1)} \\sin(\\theta / 2) \\\\ + 0 & \\cos(\\theta / 2) & -i e^{-i( \\phi_0 - \\phi_1)} \\sin(\\theta / 2) & 0 \\\\ + 0 & -i e^{i( \\phi_0 - \\phi_1)} \\sin(\\theta / 2) & \\cos(\\theta / 2) & 0 \\\\ + -i e^{i( \\phi_0 + \\phi_1)} \\sin(\\theta / 2) & 0 & 0 & \\cos(\\theta / 2) \\\\ \\end{pmatrix} Args: @@ -1391,31 +1392,45 @@ class MS(ParametrizedGate): q1 (int): the second qubit to be swapped id number. phi0 (float): first qubit's phase. phi1 (float): second qubit's phase + theta (float, optional): arbitrary angle in the interval + :math:`0 \\leq \\theta \\leq \\pi /2`. If :math:`\\theta \\rightarrow \\pi / 2`, + the fully-entangling MS gate is defined. Defaults to :math:`\\pi / 2`. trainable (bool): whether gate parameters can be updated using - :meth:`qibo.models.circuit.Circuit.set_parameters` - (default is ``True``). + :meth:`qibo.models.circuit.Circuit.set_parameters`. + Defaults to ``True``. """ # TODO: Check how this works with QASM. - def __init__(self, q0, q1, phi0, phi1, trainable=True): + def __init__(self, q0, q1, phi0, phi1, theta: float = math.pi / 2, trainable=True): super().__init__(trainable) self.name = "ms" self.draw_label = "MS" self.target_qubits = (q0, q1) - self.parameter_names = ["phi0", "phi1"] - self.parameters = phi0, phi1 - self.nparams = 2 + if theta < 0.0 or theta > math.pi / 2: + raise_error( + ValueError, + f"Theta is defined in the interval 0 <= theta <= pi/2, but it is {theta}.", + ) + + self.parameter_names = ["phi0", "phi1", "theta"] + self.parameters = phi0, phi1, theta + self.nparams = 3 self.init_args = [q0, q1] - self.init_kwargs = {"phi0": phi0, "phi1": phi1, "trainable": trainable} + self.init_kwargs = { + "phi0": phi0, + "phi1": phi1, + "theta": theta, + "trainable": trainable, + } def _dagger(self) -> "Gate": """""" q0, q1 = self.target_qubits - phi0, phi1 = self.parameters - return self.__class__(q0, q1, phi0 + math.pi, phi1) + phi0, phi1, theta = self.parameters + return self.__class__(q0, q1, phi0 + math.pi, phi1, theta) class TOFFOLI(Gate):
qiboteam/qibo
f0e23e94191d34b2ffd82fdccefb9c4dda9be926
diff --git a/tests/test_gates_gates.py b/tests/test_gates_gates.py index 37fd4e0e9..4a35676bd 100644 --- a/tests/test_gates_gates.py +++ b/tests/test_gates_gates.py @@ -447,6 +447,13 @@ def test_rzz(backend): def test_ms(backend): phi0 = 0.1234 phi1 = 0.4321 + theta = np.pi / 2 + + with pytest.raises(NotImplementedError): + gates.MS(0, 1, phi0=phi0, phi1=phi1, theta=theta).qasm_label + with pytest.raises(ValueError): + gates.MS(0, 1, phi0=phi0, phi1=phi1, theta=np.pi) + final_state = apply_gates( backend, [gates.H(0), gates.H(1), gates.MS(0, 1, phi0=phi0, phi1=phi1)], @@ -467,9 +474,6 @@ def test_ms(backend): backend.assert_allclose(final_state, target_state) - with pytest.raises(NotImplementedError): - gates.MS(0, 1, phi0=phi0, phi1=phi1).qasm_label - @pytest.mark.parametrize("applyx", [False, True]) def test_toffoli(backend, applyx): @@ -782,7 +786,7 @@ GATES = [ ("RXX", (0, 1, 0.1)), ("RYY", (0, 1, 0.2)), ("RZZ", (0, 1, 0.3)), - ("MS", (0, 1, 0.1, 0.2)), + ("MS", (0, 1, 0.1, 0.2, 0.3)), ]
Extend the IonQ native MS gate to include the partially entangled version We already include the MS gate in Qibo, but recently, IonQ has introduced the Partially Entangled MS gate in their set of native gates. (https://ionq.com/docs/getting-started-with-native-gates) It adds the possibility to change the angle of rotation from 0 to pi/2, and they even claim that small rotations are more accurate on hardware. We should consider adding that angle to our already available MS gate.
0.0
f0e23e94191d34b2ffd82fdccefb9c4dda9be926
[ "tests/test_gates_gates.py::test_ms[numpy]" ]
[ "tests/test_gates_gates.py::test_h[numpy]", "tests/test_gates_gates.py::test_x[numpy]", "tests/test_gates_gates.py::test_y[numpy]", "tests/test_gates_gates.py::test_z[numpy]", "tests/test_gates_gates.py::test_s[numpy]", "tests/test_gates_gates.py::test_sdg[numpy]", "tests/test_gates_gates.py::test_t[numpy]", "tests/test_gates_gates.py::test_tdg[numpy]", "tests/test_gates_gates.py::test_identity[numpy]", "tests/test_gates_gates.py::test_align[numpy]", "tests/test_gates_gates.py::test_rx[numpy]", "tests/test_gates_gates.py::test_ry[numpy]", "tests/test_gates_gates.py::test_rz[numpy-True]", "tests/test_gates_gates.py::test_rz[numpy-False]", "tests/test_gates_gates.py::test_gpi[numpy]", "tests/test_gates_gates.py::test_gpi2[numpy]", "tests/test_gates_gates.py::test_u1[numpy]", "tests/test_gates_gates.py::test_u2[numpy]", "tests/test_gates_gates.py::test_u3[numpy]", "tests/test_gates_gates.py::test_cnot[numpy-False]", "tests/test_gates_gates.py::test_cnot[numpy-True]", "tests/test_gates_gates.py::test_cz[numpy-False]", "tests/test_gates_gates.py::test_cz[numpy-True]", "tests/test_gates_gates.py::test_cun[numpy-CRX-params0]", "tests/test_gates_gates.py::test_cun[numpy-CRY-params1]", "tests/test_gates_gates.py::test_cun[numpy-CRZ-params2]", "tests/test_gates_gates.py::test_cun[numpy-CU1-params3]", "tests/test_gates_gates.py::test_cun[numpy-CU2-params4]", "tests/test_gates_gates.py::test_cun[numpy-CU3-params5]", "tests/test_gates_gates.py::test_swap[numpy]", "tests/test_gates_gates.py::test_iswap[numpy]", "tests/test_gates_gates.py::test_fswap[numpy]", "tests/test_gates_gates.py::test_multiple_swap[numpy]", "tests/test_gates_gates.py::test_fsim[numpy]", "tests/test_gates_gates.py::test_generalized_fsim[numpy]", "tests/test_gates_gates.py::test_generalized_fsim_parameter_setter[numpy]", "tests/test_gates_gates.py::test_rxx[numpy]", "tests/test_gates_gates.py::test_ryy[numpy]", "tests/test_gates_gates.py::test_rzz[numpy]", "tests/test_gates_gates.py::test_toffoli[numpy-False]", "tests/test_gates_gates.py::test_toffoli[numpy-True]", "tests/test_gates_gates.py::test_unitary_initialization[numpy]", "tests/test_gates_gates.py::test_controlled_x[numpy]", "tests/test_gates_gates.py::test_controlled_x_vs_cnot[numpy]", "tests/test_gates_gates.py::test_controlled_x_vs_toffoli[numpy]", "tests/test_gates_gates.py::test_controlled_rx[numpy-False]", "tests/test_gates_gates.py::test_controlled_rx[numpy-True]", "tests/test_gates_gates.py::test_controlled_u1[numpy]", "tests/test_gates_gates.py::test_controlled_u2[numpy]", "tests/test_gates_gates.py::test_controlled_u3[numpy]", "tests/test_gates_gates.py::test_controlled_swap[numpy-False-False]", "tests/test_gates_gates.py::test_controlled_swap[numpy-False-True]", "tests/test_gates_gates.py::test_controlled_swap[numpy-True-False]", "tests/test_gates_gates.py::test_controlled_swap[numpy-True-True]", "tests/test_gates_gates.py::test_controlled_swap_double[numpy-False]", "tests/test_gates_gates.py::test_controlled_swap_double[numpy-True]", "tests/test_gates_gates.py::test_controlled_fsim[numpy]", "tests/test_gates_gates.py::test_dagger[numpy-H-args0]", "tests/test_gates_gates.py::test_dagger[numpy-X-args1]", "tests/test_gates_gates.py::test_dagger[numpy-Y-args2]", "tests/test_gates_gates.py::test_dagger[numpy-Z-args3]", "tests/test_gates_gates.py::test_dagger[numpy-S-args4]", "tests/test_gates_gates.py::test_dagger[numpy-SDG-args5]", "tests/test_gates_gates.py::test_dagger[numpy-T-args6]", "tests/test_gates_gates.py::test_dagger[numpy-TDG-args7]", "tests/test_gates_gates.py::test_dagger[numpy-RX-args8]", "tests/test_gates_gates.py::test_dagger[numpy-RY-args9]", "tests/test_gates_gates.py::test_dagger[numpy-RZ-args10]", "tests/test_gates_gates.py::test_dagger[numpy-GPI-args11]", "tests/test_gates_gates.py::test_dagger[numpy-GPI2-args12]", "tests/test_gates_gates.py::test_dagger[numpy-U1-args13]", "tests/test_gates_gates.py::test_dagger[numpy-U2-args14]", "tests/test_gates_gates.py::test_dagger[numpy-U3-args15]", "tests/test_gates_gates.py::test_dagger[numpy-CNOT-args16]", "tests/test_gates_gates.py::test_dagger[numpy-CRX-args17]", "tests/test_gates_gates.py::test_dagger[numpy-CRZ-args18]", "tests/test_gates_gates.py::test_dagger[numpy-CU1-args19]", "tests/test_gates_gates.py::test_dagger[numpy-CU2-args20]", "tests/test_gates_gates.py::test_dagger[numpy-CU3-args21]", "tests/test_gates_gates.py::test_dagger[numpy-fSim-args22]", "tests/test_gates_gates.py::test_dagger[numpy-RXX-args23]", "tests/test_gates_gates.py::test_dagger[numpy-RYY-args24]", "tests/test_gates_gates.py::test_dagger[numpy-RZZ-args25]", "tests/test_gates_gates.py::test_dagger[numpy-MS-args26]", "tests/test_gates_gates.py::test_controlled_dagger[numpy-H-args0]", "tests/test_gates_gates.py::test_controlled_dagger[numpy-X-args1]", "tests/test_gates_gates.py::test_controlled_dagger[numpy-Y-args2]", "tests/test_gates_gates.py::test_controlled_dagger[numpy-S-args3]", "tests/test_gates_gates.py::test_controlled_dagger[numpy-SDG-args4]", "tests/test_gates_gates.py::test_controlled_dagger[numpy-T-args5]", "tests/test_gates_gates.py::test_controlled_dagger[numpy-TDG-args6]", "tests/test_gates_gates.py::test_controlled_dagger[numpy-RX-args7]", "tests/test_gates_gates.py::test_controlled_dagger[numpy-U1-args8]", "tests/test_gates_gates.py::test_controlled_dagger[numpy-U3-args9]", "tests/test_gates_gates.py::test_dagger_consistency[numpy-0-S-SDG]", "tests/test_gates_gates.py::test_dagger_consistency[numpy-0-T-TDG]", "tests/test_gates_gates.py::test_dagger_consistency[numpy-2-S-SDG]", "tests/test_gates_gates.py::test_dagger_consistency[numpy-2-T-TDG]", "tests/test_gates_gates.py::test_dagger_consistency[numpy-4-S-SDG]", "tests/test_gates_gates.py::test_dagger_consistency[numpy-4-T-TDG]", "tests/test_gates_gates.py::test_controlled_unitary_dagger[numpy]", "tests/test_gates_gates.py::test_generalizedfsim_dagger[numpy]", "tests/test_gates_gates.py::test_gate_basis_rotation[numpy]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-0-controls0-free0]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-2-controls1-free1]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-3-controls2-free2]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-7-controls3-free3]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-5-controls4-free4]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-True-8-controls5-free5]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-0-controls0-free0]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-2-controls1-free1]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-3-controls2-free2]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-7-controls3-free3]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-5-controls4-free4]", "tests/test_gates_gates.py::test_x_decomposition_execution[numpy-False-8-controls5-free5]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-06-26 13:15:17+00:00
apache-2.0
5,137
qiboteam__qibocal-725
diff --git a/src/qibocal/protocols/characterization/__init__.py b/src/qibocal/protocols/characterization/__init__.py index 0d05a986..7fd5da59 100644 --- a/src/qibocal/protocols/characterization/__init__.py +++ b/src/qibocal/protocols/characterization/__init__.py @@ -5,7 +5,7 @@ from .allxy.allxy_drag_pulse_tuning import allxy_drag_pulse_tuning from .allxy.drag_pulse_tuning import drag_pulse_tuning from .classification import single_shot_classification from .coherence.spin_echo import spin_echo -from .coherence.spin_echo_sequence import spin_echo_sequence +from .coherence.spin_echo_signal import spin_echo_signal from .coherence.t1 import t1 from .coherence.t1_sequences import t1_sequences from .coherence.t1_signal import t1_signal @@ -88,7 +88,7 @@ class Operation(Enum): time_of_flight_readout = time_of_flight_readout single_shot_classification = single_shot_classification spin_echo = spin_echo - spin_echo_sequence = spin_echo_sequence + spin_echo_signal = spin_echo_signal allxy = allxy allxy_drag_pulse_tuning = allxy_drag_pulse_tuning drag_pulse_tuning = drag_pulse_tuning diff --git a/src/qibocal/protocols/characterization/coherence/spin_echo.py b/src/qibocal/protocols/characterization/coherence/spin_echo.py index 2e41a172..f4357dd4 100644 --- a/src/qibocal/protocols/characterization/coherence/spin_echo.py +++ b/src/qibocal/protocols/characterization/coherence/spin_echo.py @@ -1,3 +1,4 @@ +from copy import deepcopy from dataclasses import dataclass, field from typing import Optional @@ -26,6 +27,9 @@ class SpinEchoParameters(Parameters): """Final delay between pulses [ns].""" delay_between_pulses_step: int """Step delay between pulses [ns].""" + unrolling: bool = False + """If ``True`` it uses sequence unrolling to deploy multiple sequences in a single instrument call. + Defaults to ``False``.""" @dataclass @@ -83,8 +87,15 @@ def _acquisition( params.delay_between_pulses_step, ) + options = ExecutionParameters( + nshots=params.nshots, + relaxation_time=params.relaxation_time, + acquisition_type=AcquisitionType.DISCRIMINATION, + averaging_mode=AveragingMode.SINGLESHOT, + ) + data = SpinEchoData() - probs = {qubit: [] for qubit in targets} + sequences, all_ro_pulses = [], [] # sweep the parameter for wait in ro_wait_range: # save data as often as defined by points @@ -94,28 +105,35 @@ def _acquisition( RX90_pulses2[qubit].start = RX_pulses[qubit].finish + wait // 2 ro_pulses[qubit].start = RX90_pulses2[qubit].finish - # execute the pulse sequence - results = platform.execute_pulse_sequence( - sequence, - ExecutionParameters( - nshots=params.nshots, - relaxation_time=params.relaxation_time, - acquisition_type=AcquisitionType.DISCRIMINATION, - averaging_mode=AveragingMode.SINGLESHOT, - ), - ) + sequences.append(deepcopy(sequence)) + all_ro_pulses.append(deepcopy(sequence).ro_pulses) - for qubit in targets: - prob = results[ro_pulses[qubit].serial].probability(state=0) - probs[qubit].append(prob) + if params.unrolling: + results = platform.execute_pulse_sequences(sequences, options) - for qubit in targets: - errors = [np.sqrt(prob * (1 - prob) / params.nshots) for prob in probs[qubit]] - data.register_qubit( - t1.CoherenceProbType, - (qubit), - dict(wait=ro_wait_range, prob=probs[qubit], error=errors), - ) + elif not params.unrolling: + results = [ + platform.execute_pulse_sequence(sequence, options) for sequence in sequences + ] + + for ig, (wait, ro_pulses) in enumerate(zip(ro_wait_range, all_ro_pulses)): + for qubit in targets: + serial = ro_pulses.get_qubit_pulses(qubit)[0].serial + if params.unrolling: + result = results[serial][0] + else: + result = results[ig][serial] + prob = result.probability(state=0) + error = np.sqrt(prob * (1 - prob) / params.nshots) + data.register_qubit( + t1.CoherenceProbType, + (qubit), + dict( + wait=np.array([wait]), + prob=np.array([prob]), + error=np.array([error]), + ), + ) return data diff --git a/src/qibocal/protocols/characterization/coherence/spin_echo_sequence.py b/src/qibocal/protocols/characterization/coherence/spin_echo_signal.py similarity index 82% rename from src/qibocal/protocols/characterization/coherence/spin_echo_sequence.py rename to src/qibocal/protocols/characterization/coherence/spin_echo_signal.py index 22cd2dd3..76ffd023 100644 --- a/src/qibocal/protocols/characterization/coherence/spin_echo_sequence.py +++ b/src/qibocal/protocols/characterization/coherence/spin_echo_signal.py @@ -1,3 +1,4 @@ +from copy import deepcopy from dataclasses import dataclass import numpy as np @@ -67,7 +68,15 @@ def _acquisition( params.delay_between_pulses_step, ) + options = ExecutionParameters( + nshots=params.nshots, + relaxation_time=params.relaxation_time, + acquisition_type=AcquisitionType.INTEGRATION, + averaging_mode=AveragingMode.CYCLIC, + ) + data = SpinEchoSignalData() + sequences, all_ro_pulses = [], [] # sweep the parameter for wait in ro_wait_range: @@ -78,19 +87,24 @@ def _acquisition( RX90_pulses2[qubit].start = RX_pulses[qubit].finish + wait // 2 ro_pulses[qubit].start = RX90_pulses2[qubit].finish - # execute the pulse sequence - results = platform.execute_pulse_sequence( - sequence, - ExecutionParameters( - nshots=params.nshots, - relaxation_time=params.relaxation_time, - acquisition_type=AcquisitionType.INTEGRATION, - averaging_mode=AveragingMode.CYCLIC, - ), - ) + sequences.append(deepcopy(sequence)) + all_ro_pulses.append(deepcopy(sequence).ro_pulses) + if params.unrolling: + results = platform.execute_pulse_sequences(sequences, options) + + elif not params.unrolling: + results = [ + platform.execute_pulse_sequence(sequence, options) for sequence in sequences + ] + + for ig, (wait, ro_pulses) in enumerate(zip(ro_wait_range, all_ro_pulses)): for qubit in targets: - result = results[ro_pulses[qubit].serial] + serial = ro_pulses.get_qubit_pulses(qubit)[0].serial + if params.unrolling: + result = results[serial][0] + else: + result = results[ig][serial] data.register_qubit( CoherenceType, (qubit), @@ -100,6 +114,7 @@ def _acquisition( phase=np.array([result.phase]), ), ) + return data @@ -170,5 +185,5 @@ def _update(results: SpinEchoSignalResults, platform: Platform, target: QubitId) update.t2_spin_echo(results.t2_spin_echo[target], platform, target) -spin_echo_sequence = Routine(_acquisition, _fit, _plot, _update) +spin_echo_signal = Routine(_acquisition, _fit, _plot, _update) """SpinEcho Routine object."""
qiboteam/qibocal
7c4d9d3a05ec93a846e1b558e7a944b08ae560e1
diff --git a/tests/runcards/protocols.yml b/tests/runcards/protocols.yml index 85e6a80c..c02a6fa6 100644 --- a/tests/runcards/protocols.yml +++ b/tests/runcards/protocols.yml @@ -503,15 +503,36 @@ actions: delay_between_pulses_step: 1 nshots: 10 - - id: spin_echo_sequence + - id: spin_echo unrolling priority: 0 - operation: spin_echo_sequence + operation: spin_echo + parameters: + delay_between_pulses_start: 0 + delay_between_pulses_end: 5 + delay_between_pulses_step: 1 + nshots: 10 + unrolling: true + + - id: spin_echo_signal + priority: 0 + operation: spin_echo_signal parameters: delay_between_pulses_start: 0 delay_between_pulses_end: 5 delay_between_pulses_step: 1 nshots: 10 + - id: spin_echo_signal unrolling + priority: 0 + operation: spin_echo_signal + parameters: + delay_between_pulses_start: 0 + delay_between_pulses_end: 5 + delay_between_pulses_step: 1 + nshots: 10 + unrolling: true + + - id: flipping priority: 0 operation: flipping
`Spin Echo` experiment slow Currently `spin_echo` is quite slow given that the only implementation that we currently have relies on a `for` loop performed on software. I believe that with the current version of qibolab it is not possible to perform this experiment with a sweeper given that the sequence is the following `RX90 - wait - RX - wait - RX90 - MZ` , correct @stavros11 @hay-k @alecandido? For the time being I was thinking of providing the option to unroll the sequences. If we all agree we could also decide to drop all protocols in qibocal that still perform this sort of for loop and just implement the unrolling. A possible idea would be to provide both unrolling and sweepers whenever possible like I'm doing in #721. After benchmarking both unrolling and sweepers we could eventually decide to keep only one, but I believe that given that we support different drivers it is not a bad idea to keep both.
0.0
7c4d9d3a05ec93a846e1b558e7a944b08ae560e1
[ "tests/test_task_options.py::test_qubits_argument[None-None]" ]
[ "tests/test_cli_utils.py::test_create_qubits_dict", "tests/test_update.py::test_coherence_params_update[qubit3]", "tests/test_update.py::test_virtual_phases_update[pair7]", "tests/test_update.py::test_sweetspot_update[qubit2]", "tests/test_update.py::test_sweetspot_update[qubit4]", "tests/test_update.py::test_virtual_phases_update[pair0]", "tests/test_update.py::test_readout_frequency_update[qubit3]", "tests/test_update.py::test_12_transition_update[qubit0]", "tests/test_update.py::test_readout_amplitude_update[qubit4]", "tests/test_update.py::test_readout_frequency_update[qubit1]", "tests/test_update.py::test_twpa_update[qubit4]", "tests/test_update.py::test_update_bare_resonator_frequency_update[qubit2]", "tests/test_update.py::test_update_bare_resonator_frequency_update[qubit4]", "tests/test_update.py::test_kernel_update[qubit1]", "tests/test_update.py::test_sweetspot_update[qubit0]", "tests/test_update.py::test_twpa_update[qubit1]", "tests/test_update.py::test_drive_frequency_update[qubit1]", "tests/test_update.py::test_coherence_params_update[qubit0]", "tests/test_update.py::test_readout_frequency_update[qubit2]", "tests/test_update.py::test_readout_amplitude_update[qubit1]", "tests/test_update.py::test_CZ_params_update[pair6]", "tests/test_update.py::test_readout_amplitude_update[qubit3]", "tests/test_update.py::test_drive_amplitude_update[qubit0]", "tests/test_update.py::test_CZ_params_update[pair0]", "tests/test_update.py::test_update_bare_resonator_frequency_update[qubit1]", "tests/test_update.py::test_twpa_update[qubit3]", "tests/test_update.py::test_virtual_phases_update[pair2]", "tests/test_update.py::test_classification_update[qubit4]", "tests/test_update.py::test_CZ_params_update[pair4]", "tests/test_update.py::test_classification_update[qubit0]", "tests/test_update.py::test_drive_frequency_update[qubit4]", "tests/test_update.py::test_virtual_phases_update[pair6]", "tests/test_update.py::test_readout_attenuation_update[qubit0]", "tests/test_update.py::test_readout_attenuation_update[qubit2]", "tests/test_update.py::test_update_bare_resonator_frequency_update[qubit0]", "tests/test_update.py::test_drive_amplitude_update[qubit1]", "tests/test_update.py::test_CZ_params_update[pair7]", "tests/test_update.py::test_classification_update[qubit3]", "tests/test_update.py::test_classification_update[qubit2]", "tests/test_update.py::test_drag_pulse_beta_update[qubit3]", "tests/test_update.py::test_update_bare_resonator_frequency_update[qubit3]", "tests/test_update.py::test_drive_amplitude_update[qubit3]", "tests/test_update.py::test_twpa_update[qubit0]", "tests/test_update.py::test_kernel_update[qubit4]", "tests/test_update.py::test_readout_attenuation_update[qubit4]", "tests/test_update.py::test_sweetspot_update[qubit3]", "tests/test_update.py::test_kernel_update[qubit3]", "tests/test_update.py::test_drag_pulse_beta_update[qubit4]", "tests/test_update.py::test_classification_update[qubit1]", "tests/test_update.py::test_readout_frequency_update[qubit4]", "tests/test_update.py::test_12_transition_update[qubit2]", "tests/test_update.py::test_virtual_phases_update[pair4]", "tests/test_update.py::test_coherence_params_update[qubit2]", "tests/test_update.py::test_readout_frequency_update[qubit0]", "tests/test_update.py::test_drag_pulse_beta_update[qubit0]", "tests/test_update.py::test_CZ_params_update[pair2]", "tests/test_update.py::test_virtual_phases_update[pair3]", "tests/test_update.py::test_12_transition_update[qubit1]", "tests/test_update.py::test_drive_amplitude_update[qubit2]", "tests/test_update.py::test_CZ_params_update[pair1]", "tests/test_update.py::test_drag_pulse_beta_update[qubit2]", "tests/test_update.py::test_12_transition_update[qubit3]", "tests/test_update.py::test_coherence_params_update[qubit1]", "tests/test_update.py::test_coherence_params_update[qubit4]", "tests/test_update.py::test_twpa_update[qubit2]", "tests/test_update.py::test_drive_amplitude_update[qubit4]", "tests/test_update.py::test_CZ_params_update[pair3]", "tests/test_update.py::test_readout_attenuation_update[qubit3]", "tests/test_update.py::test_CZ_params_update[pair5]", "tests/test_update.py::test_virtual_phases_update[pair1]", "tests/test_update.py::test_readout_amplitude_update[qubit2]", "tests/test_update.py::test_drive_frequency_update[qubit0]", "tests/test_update.py::test_sweetspot_update[qubit1]", "tests/test_update.py::test_kernel_update[qubit0]", "tests/test_update.py::test_readout_amplitude_update[qubit0]", "tests/test_update.py::test_virtual_phases_update[pair5]", "tests/test_update.py::test_drive_frequency_update[qubit3]", "tests/test_update.py::test_drag_pulse_beta_update[qubit1]", "tests/test_update.py::test_kernel_update[qubit2]", "tests/test_update.py::test_drive_frequency_update[qubit2]", "tests/test_update.py::test_readout_attenuation_update[qubit1]", "tests/test_auto.py::test_execution[card4]", "tests/test_auto.py::test_execution[card2]", "tests/test_auto.py::test_execution[card5]", "tests/test_auto.py::test_execution[card1]", "tests/test_auto.py::test_execution[card3]", "tests/test_auto.py::test_execution[card0]", "tests/test_task_options.py::test_update_argument[True-True]", "tests/test_task_options.py::test_qubits_argument[local_targets1-platform1]", "tests/test_task_options.py::test_update_argument[True-False]", "tests/test_task_options.py::test_parameters_load[False-ReadoutMitigationMatrixParameters]", "tests/test_task_options.py::test_parameters_load[False-SingleShotClassificationParameters]", "tests/test_task_options.py::test_update_argument[False-False]", "tests/test_task_options.py::test_parameters_load[True-SingleShotClassificationParameters]", "tests/test_task_options.py::test_parameters_load[True-ReadoutMitigationMatrixParameters]", "tests/test_task_options.py::test_update_argument[False-True]", "tests/test_task_options.py::test_qubits_argument[local_targets1-None]", "tests/test_protocols.py::test_extract_rabi", "tests/test_classifiers.py::test_predict_from_file", "tests/test_classifiers.py::test_load_model", "tests/test_validators.py::test_chi2[1e-05]", "tests/test_validators.py::test_chi2_error", "tests/test_validators.py::test_chi2[1000]", "tests/test_validators.py::test_error_validator", "tests/test_validators.py::test_validator_with_exception_handled", "tests/test_utils.py::test_eval_magnitude", "tests/test_utils.py::test_cumulative", "tests/test_randomized_benchmarking.py::test_extract_from_data", "tests/test_randomized_benchmarking.py::test_number_to_str[(-0.1+0.1j)]", "tests/test_randomized_benchmarking.py::test_random_clifford[qubits3-10]", "tests/test_randomized_benchmarking.py::test_random_clifford[1-10]", "tests/test_randomized_benchmarking.py::test_PauliErrors", "tests/test_randomized_benchmarking.py::test_random_clifford[2-10]", "tests/test_randomized_benchmarking.py::test_random_clifford[qubits2-10]", "tests/test_randomized_benchmarking.py::test_number_to_str[2]", "tests/test_randomized_benchmarking.py::test_number_to_str[0.555555]", "tests/test_randomized_benchmarking.py::test_1expfitting", "tests/test_randomized_benchmarking.py::test_exp2_fitting" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-02-21 15:59:11+00:00
apache-2.0
5,138
qiboteam__qibocal-808
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e2312594..358c45b5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,7 +11,7 @@ repos: - id: check-merge-conflict - id: debug-statements - repo: https://github.com/psf/black - rev: 24.4.0 + rev: 24.4.2 hooks: - id: black - repo: https://github.com/pycqa/isort diff --git a/src/qibocal/protocols/characterization/flipping.py b/src/qibocal/protocols/characterization/flipping.py index defbbeb1..f9ada5a9 100644 --- a/src/qibocal/protocols/characterization/flipping.py +++ b/src/qibocal/protocols/characterization/flipping.py @@ -21,6 +21,7 @@ from .flipping_signal import ( FlippingSignalResults, _update, flipping_fit, + flipping_sequence, ) from .utils import COLORBAND, COLORBAND_LINE, chi2_reduced @@ -29,14 +30,6 @@ from .utils import COLORBAND, COLORBAND_LINE, chi2_reduced class FlippingParameters(FlippingSignalParameters): """Flipping runcard inputs.""" - nflips_max: int - """Maximum number of flips ([RX(pi) - RX(pi)] sequences). """ - nflips_step: int - """Flip step.""" - unrolling: bool = False - """If ``True`` it uses sequence unrolling to deploy multiple sequences in a single instrument call. - Defaults to ``False``.""" - @dataclass class FlippingResults(FlippingSignalResults): @@ -55,7 +48,6 @@ FlippingType = np.dtype( class FlippingData(FlippingSignalData): """Flipping acquisition outputs.""" - """Pi pulse amplitudes for each qubit.""" data: dict[QubitId, npt.NDArray[FlippingType]] = field(default_factory=dict) """Raw data acquired.""" @@ -82,6 +74,7 @@ def _acquisition( data = FlippingData( resonator_type=platform.resonator_type, + detuning=params.detuning, pi_pulse_amplitudes={ qubit: platform.qubits[qubit].native_gates.RX.amplitude for qubit in targets }, @@ -100,26 +93,13 @@ def _acquisition( for flips in flips_sweep: # create a sequence of pulses for the experiment sequence = PulseSequence() - ro_pulses = {} for qubit in targets: - RX90_pulse = platform.create_RX90_pulse(qubit, start=0) - sequence.add(RX90_pulse) - # execute sequence RX(pi/2) - [RX(pi) - RX(pi)] from 0...flips times - RO - start1 = RX90_pulse.duration - for _ in range(flips): - RX_pulse1 = platform.create_RX_pulse(qubit, start=start1) - start2 = start1 + RX_pulse1.duration - RX_pulse2 = platform.create_RX_pulse(qubit, start=start2) - sequence.add(RX_pulse1) - sequence.add(RX_pulse2) - start1 = start2 + RX_pulse2.duration - - # add ro pulse at the end of the sequence - ro_pulses[qubit] = platform.create_qubit_readout_pulse(qubit, start=start1) - sequence.add(ro_pulses[qubit]) + sequence += flipping_sequence( + platform=platform, qubit=qubit, detuning=params.detuning, flips=flips + ) sequences.append(sequence) - all_ro_pulses.append(ro_pulses) + all_ro_pulses.append(sequence.ro_pulses) # execute the pulse sequence if params.unrolling: @@ -132,7 +112,7 @@ def _acquisition( for ig, (flips, ro_pulses) in enumerate(zip(flips_sweep, all_ro_pulses)): for qubit in targets: - serial = ro_pulses[qubit].serial + serial = ro_pulses.get_qubit_pulses(qubit)[0].serial if params.unrolling: result = results[serial][0] else: @@ -164,11 +144,12 @@ def _fit(data: FlippingData) -> FlippingResults: qubits = data.qubits corrected_amplitudes = {} fitted_parameters = {} - amplitude_correction_factors = {} + delta_amplitude = {} + delta_amplitude_detuned = {} chi2 = {} for qubit in qubits: qubit_data = data[qubit] - pi_pulse_amplitude = data.pi_pulse_amplitudes[qubit] + detuned_pi_pulse_amplitude = data.pi_pulse_amplitudes[qubit] y = qubit_data.prob x = qubit_data.flips @@ -185,6 +166,7 @@ def _fit(data: FlippingData) -> FlippingResults: ) f = x[index] / (x[1] - x[0]) if index is not None else 1 pguess = [0.5, 0.5, 1 / f, np.pi, 0] + try: popt, perr = curve_fit( flipping_fit, @@ -207,9 +189,9 @@ def _fit(data: FlippingData) -> FlippingResults: signed_correction = popt[2] / 2 # The amplitude is directly proportional to the rotation angle corrected_amplitudes[qubit] = ( - float((pi_pulse_amplitude * np.pi) / (np.pi + signed_correction)), + float(detuned_pi_pulse_amplitude * np.pi / (np.pi + signed_correction)), float( - pi_pulse_amplitude + detuned_pi_pulse_amplitude * np.pi * 1 / (np.pi + signed_correction) ** 2 @@ -217,11 +199,26 @@ def _fit(data: FlippingData) -> FlippingResults: / 2 ), ) + fitted_parameters[qubit] = popt - amplitude_correction_factors[qubit] = ( - float(signed_correction / np.pi * pi_pulse_amplitude), - float(perr[2] * pi_pulse_amplitude / np.pi / 2), + + delta_amplitude[qubit] = ( + -signed_correction + * detuned_pi_pulse_amplitude + / (np.pi + signed_correction), + np.abs( + np.pi + * detuned_pi_pulse_amplitude + * np.power(np.pi + signed_correction, -2) + ) + * perr[2] + / 2, + ) + delta_amplitude_detuned[qubit] = ( + delta_amplitude[qubit][0] - data.detuning, + delta_amplitude[qubit][1], ) + chi2[qubit] = ( chi2_reduced( y, @@ -234,7 +231,11 @@ def _fit(data: FlippingData) -> FlippingResults: log.warning(f"Error in flipping fit for qubit {qubit} due to {e}.") return FlippingResults( - corrected_amplitudes, amplitude_correction_factors, fitted_parameters, chi2 + corrected_amplitudes, + delta_amplitude, + delta_amplitude_detuned, + fitted_parameters, + chi2, ) @@ -243,7 +244,6 @@ def _plot(data: FlippingData, target: QubitId, fit: FlippingResults = None): figures = [] fig = go.Figure() - fitting_report = "" qubit_data = data[target] @@ -298,13 +298,15 @@ def _plot(data: FlippingData, target: QubitId, fit: FlippingResults = None): table_dict( target, [ - "Amplitude correction factor", + "Delta amplitude [a.u.]", + "Delta amplitude (with detuning) [a.u.]", "Corrected amplitude [a.u.]", "chi2 reduced", ], [ - np.round(fit.amplitude_factors[target], 4), - np.round(fit.amplitude[target], 4), + fit.delta_amplitude[target], + fit.delta_amplitude_detuned[target], + fit.amplitude[target], fit.chi2[target], ], display_error=True, diff --git a/src/qibocal/protocols/characterization/flipping_signal.py b/src/qibocal/protocols/characterization/flipping_signal.py index db7f60f4..c1ccd7d4 100644 --- a/src/qibocal/protocols/characterization/flipping_signal.py +++ b/src/qibocal/protocols/characterization/flipping_signal.py @@ -28,6 +28,8 @@ class FlippingSignalParameters(Parameters): unrolling: bool = False """If ``True`` it uses sequence unrolling to deploy multiple sequences in a single instrument call. Defaults to ``False``.""" + detuning: float = 0 + """Amplitude detuning.""" @dataclass @@ -36,8 +38,10 @@ class FlippingSignalResults(Results): amplitude: dict[QubitId, tuple[float, Optional[float]]] """Drive amplitude for each qubit.""" - amplitude_factors: dict[QubitId, tuple[float, Optional[float]]] - """Drive amplitude correction factor for each qubit.""" + delta_amplitude: dict[QubitId, tuple[float, Optional[float]]] + """Difference in amplitude between initial value and fit.""" + delta_amplitude_detuned: dict[QubitId, tuple[float, Optional[float]]] + """Difference in amplitude between detuned value and fit.""" fitted_parameters: dict[QubitId, dict[str, float]] """Raw fitting output.""" @@ -51,12 +55,39 @@ class FlippingSignalData(Data): resonator_type: str """Resonator type.""" + detuning: float + """Amplitude detuning.""" pi_pulse_amplitudes: dict[QubitId, float] """Pi pulse amplitudes for each qubit.""" data: dict[QubitId, npt.NDArray[FlippingType]] = field(default_factory=dict) """Raw data acquired.""" +def flipping_sequence(platform: Platform, qubit: QubitId, detuning: float, flips: int): + + sequence = PulseSequence() + RX90_pulse = platform.create_RX90_pulse(qubit, start=0) + sequence.add(RX90_pulse) + # execute sequence RX(pi/2) - [RX(pi) - RX(pi)] from 0...flips times - RO + start1 = RX90_pulse.duration + drive_frequency = platform.qubits[qubit].native_gates.RX.frequency + for _ in range(flips): + RX_pulse1 = platform.create_RX_pulse(qubit, start=start1) + RX_pulse1.frequency = drive_frequency + detuning + start2 = start1 + RX_pulse1.duration + RX_pulse2 = platform.create_RX_pulse(qubit, start=start2) + RX_pulse2.frequency = drive_frequency + detuning + + sequence.add(RX_pulse1) + sequence.add(RX_pulse2) + start1 = start2 + RX_pulse2.duration + + # add ro pulse at the end of the sequence + sequence.add(platform.create_qubit_readout_pulse(qubit, start=start1)) + + return sequence + + def _acquisition( params: FlippingSignalParameters, platform: Platform, @@ -79,6 +110,7 @@ def _acquisition( data = FlippingSignalData( resonator_type=platform.resonator_type, + detuning=params.detuning, pi_pulse_amplitudes={ qubit: platform.qubits[qubit].native_gates.RX.amplitude for qubit in targets }, @@ -97,26 +129,13 @@ def _acquisition( for flips in flips_sweep: # create a sequence of pulses for the experiment sequence = PulseSequence() - ro_pulses = {} for qubit in targets: - RX90_pulse = platform.create_RX90_pulse(qubit, start=0) - sequence.add(RX90_pulse) - # execute sequence RX(pi/2) - [RX(pi) - RX(pi)] from 0...flips times - RO - start1 = RX90_pulse.duration - for _ in range(flips): - RX_pulse1 = platform.create_RX_pulse(qubit, start=start1) - start2 = start1 + RX_pulse1.duration - RX_pulse2 = platform.create_RX_pulse(qubit, start=start2) - sequence.add(RX_pulse1) - sequence.add(RX_pulse2) - start1 = start2 + RX_pulse2.duration - - # add ro pulse at the end of the sequence - ro_pulses[qubit] = platform.create_qubit_readout_pulse(qubit, start=start1) - sequence.add(ro_pulses[qubit]) + sequence += flipping_sequence( + platform=platform, qubit=qubit, detuning=params.detuning, flips=flips + ) sequences.append(sequence) - all_ro_pulses.append(ro_pulses) + all_ro_pulses.append(sequence.ro_pulses) # execute the pulse sequence if params.unrolling: @@ -129,7 +148,7 @@ def _acquisition( for ig, (flips, ro_pulses) in enumerate(zip(flips_sweep, all_ro_pulses)): for qubit in targets: - serial = ro_pulses[qubit].serial + serial = ro_pulses.get_qubit_pulses(qubit)[0].serial if params.unrolling: result = results[serial][0] else: @@ -162,10 +181,11 @@ def _fit(data: FlippingSignalData) -> FlippingSignalResults: qubits = data.qubits corrected_amplitudes = {} fitted_parameters = {} - amplitude_correction_factors = {} + delta_amplitude = {} + delta_amplitude_detuned = {} for qubit in qubits: qubit_data = data[qubit] - pi_pulse_amplitude = data.pi_pulse_amplitudes[qubit] + detuned_pi_pulse_amplitude = data.pi_pulse_amplitudes[qubit] + data.detuning voltages = qubit_data.signal flips = qubit_data.flips y_min = np.min(voltages) @@ -217,18 +237,24 @@ def _fit(data: FlippingSignalData) -> FlippingSignalResults: else: signed_correction = -translated_popt[2] / 2 # The amplitude is directly proportional to the rotation angle - corrected_amplitudes[qubit] = (pi_pulse_amplitude * np.pi) / ( + corrected_amplitudes[qubit] = (detuned_pi_pulse_amplitude * np.pi) / ( np.pi + signed_correction ) fitted_parameters[qubit] = translated_popt - amplitude_correction_factors[qubit] = ( - signed_correction / np.pi * pi_pulse_amplitude + delta_amplitude[qubit] = ( + -signed_correction + * detuned_pi_pulse_amplitude + / (np.pi + signed_correction) ) + delta_amplitude_detuned[qubit] = delta_amplitude[qubit] - data.detuning except Exception as e: log.warning(f"Error in flipping fit for qubit {qubit} due to {e}.") return FlippingSignalResults( - corrected_amplitudes, amplitude_correction_factors, fitted_parameters + corrected_amplitudes, + delta_amplitude, + delta_amplitude_detuned, + fitted_parameters, ) @@ -276,9 +302,14 @@ def _plot(data: FlippingSignalData, target, fit: FlippingSignalResults = None): fitting_report = table_html( table_dict( target, - ["Amplitude correction factor", "Corrected amplitude [a.u.]"], [ - np.round(fit.amplitude_factors[target], 4), + "Delta amplitude [a.u.]", + "Delta amplitude (with detuning) [a.u.]", + "Corrected amplitude [a.u.]", + ], + [ + np.round(fit.delta_amplitude[target], 4), + np.round(fit.delta_amplitude_detuned[target], 4), np.round(fit.amplitude[target], 4), ], )
qiboteam/qibocal
2a6cb04d9bda28ab6960a1d41c97f7ff883c719f
diff --git a/tests/runcards/protocols.yml b/tests/runcards/protocols.yml index 798c0188..b3b69a2c 100644 --- a/tests/runcards/protocols.yml +++ b/tests/runcards/protocols.yml @@ -550,6 +550,7 @@ actions: nflips_max: 10 nflips_step: 1 nshots: 50 + detuning: 0.1 - id: flipping_signal operation: flipping_signal @@ -557,6 +558,7 @@ actions: nflips_max: 10 nflips_step: 1 nshots: 50 + detuning: 0.1 - id: flipping unrolling operation: flipping
Add detuning option to flipping to improve performances
0.0
2a6cb04d9bda28ab6960a1d41c97f7ff883c719f
[ "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-flipping---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-flipping---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-flipping_signal---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-flipping_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-flipping---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-flipping---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-flipping_signal---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-flipping_signal---no-update]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-flipping]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-flipping_signal]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-flipping]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-flipping_signal]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-flipping---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-flipping---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-flipping_signal---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-flipping_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-flipping---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-flipping---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-flipping_signal---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-flipping_signal---no-update]" ]
[ "tests/test_classifiers.py::test_load_model", "tests/test_classifiers.py::test_predict_from_file", "tests/test_cli.py::test_fit_command", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-time", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-resonator", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-resonator_punchout_attenuation---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-resonator_punchout_attenuation---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-qubit", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-rabi---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-rabi---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-rabi", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-rabi_ef---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-rabi_ef---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t1---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t1---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t1_signal---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t1_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t1_signal_single_shot---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t1_signal_single_shot---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t1", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-zeno---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-zeno---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-zeno_signal---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-zeno_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t2---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t2---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t2_signal---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t2_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t2_signal_single_shot---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t2_signal_single_shot---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-t2", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey_signal---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey_signal_detuned---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey_signal_detuned---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey_signal_detuned_unrolled---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey_signal_detuned_unrolled---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-calibrate_state_discrimination---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-calibrate_state_discrimination---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey_detuned---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey_detuned---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey_unrolled_detuned---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-ramsey_unrolled_detuned---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-readout", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-allXY---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-allXY---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-allXY", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-drag_pulse_tuning---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-drag_pulse_tuning---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-spin_echo---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-spin_echo---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-spin_echo", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-spin_echo_signal---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-spin_echo_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-spin_echo_signal_single_shot---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-spin_echo_signal_single_shot---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-spin_echo_signal", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-flipping", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-flipping_signal", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-dispersive", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-chevron", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-cz---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-cz---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-cz", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-resonator_frequency---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-resonator_frequency---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-fast", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-twpa", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-twpa_power_SNR---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-twpa_power_SNR---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-twpa_frequency_SNR---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-twpa_frequency_SNR---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-resonator_amplitude---update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-resonator_amplitude---no-update]", "tests/test_protocols.py::test_auto_command[dummy-protocols.yml-avoided", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-time", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-resonator", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-resonator_punchout_attenuation---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-resonator_punchout_attenuation---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-qubit", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-rabi---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-rabi---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-rabi", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-rabi_ef---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-rabi_ef---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t1---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t1---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t1_signal---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t1_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t1_signal_single_shot---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t1_signal_single_shot---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t1", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-zeno---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-zeno---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-zeno_signal---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-zeno_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t2---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t2---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t2_signal---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t2_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t2_signal_single_shot---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t2_signal_single_shot---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-t2", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey_signal---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey_signal_detuned---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey_signal_detuned---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey_signal_detuned_unrolled---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey_signal_detuned_unrolled---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-calibrate_state_discrimination---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-calibrate_state_discrimination---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey_detuned---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey_detuned---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey_unrolled_detuned---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-ramsey_unrolled_detuned---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-readout", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-allXY---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-allXY---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-allXY", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-drag_pulse_tuning---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-drag_pulse_tuning---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-spin_echo---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-spin_echo---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-spin_echo", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-spin_echo_signal---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-spin_echo_signal---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-spin_echo_signal_single_shot---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-spin_echo_signal_single_shot---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-spin_echo_signal", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-flipping", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-flipping_signal", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-dispersive", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-chevron", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-cz---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-cz---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-cz", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-resonator_frequency---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-resonator_frequency---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-fast", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-twpa", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-twpa_power_SNR---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-twpa_power_SNR---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-twpa_frequency_SNR---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-twpa_frequency_SNR---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-resonator_amplitude---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-resonator_amplitude---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols.yml-avoided", "tests/test_protocols.py::test_auto_command[dummy-rb_noise_protocols.yml-standard", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy0---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy0---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy1---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy1---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy2---update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy2---no-update]", "tests/test_protocols.py::test_auto_command[dummy_couplers-protocols_couplers.yml-coupler", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-time", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-resonator", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-resonator_punchout_attenuation]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-qubit", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-rabi]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-rabi", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-rabi_ef]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-t1]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-t1_signal]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-t1_signal_single_shot]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-t1", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-zeno]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-zeno_signal]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-t2]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-t2_signal]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-t2_signal_single_shot]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-t2", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-ramsey_signal]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-ramsey_signal_detuned]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-ramsey_signal_detuned_unrolled]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-ramsey]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-calibrate_state_discrimination]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-ramsey_detuned]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-ramsey_unrolled_detuned]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-single", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-readout", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-allXY]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-allXY", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-drag_pulse_tuning]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-spin_echo]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-spin_echo", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-spin_echo_signal]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-spin_echo_signal_single_shot]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-spin_echo_signal", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-flipping", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-flipping_signal", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-dispersive", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-chevron", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-cz]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-cz", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-resonator_frequency]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-fast", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-twpa", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-twpa_power_SNR]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-twpa_frequency_SNR]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-resonator_amplitude]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-qutrit]", "tests/test_protocols.py::test_acquire_command[dummy-protocols.yml-avoided", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-time", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-resonator", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-resonator_punchout_attenuation]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-qubit", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-rabi]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-rabi", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-rabi_ef]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-t1]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-t1_signal]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-t1_signal_single_shot]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-t1", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-zeno]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-zeno_signal]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-t2]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-t2_signal]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-t2_signal_single_shot]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-t2", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-ramsey_signal]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-ramsey_signal_detuned]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-ramsey_signal_detuned_unrolled]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-ramsey]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-calibrate_state_discrimination]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-ramsey_detuned]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-ramsey_unrolled_detuned]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-single", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-readout", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-allXY]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-allXY", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-drag_pulse_tuning]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-spin_echo]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-spin_echo", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-spin_echo_signal]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-spin_echo_signal_single_shot]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-spin_echo_signal", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-flipping", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-flipping_signal", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-dispersive", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-chevron", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-cz]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-cz", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-resonator_frequency]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-fast", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-twpa", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-twpa_power_SNR]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-twpa_frequency_SNR]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-resonator_amplitude]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-qutrit]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols.yml-avoided", "tests/test_protocols.py::test_acquire_command[dummy-rb_noise_protocols.yml-standard", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy0]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy1]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy2]", "tests/test_protocols.py::test_acquire_command[dummy_couplers-protocols_couplers.yml-coupler", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-time", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-resonator", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-resonator_punchout_attenuation---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-resonator_punchout_attenuation---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-qubit", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-rabi---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-rabi---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-rabi", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-rabi_ef---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-rabi_ef---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t1---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t1---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t1_signal---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t1_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t1_signal_single_shot---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t1_signal_single_shot---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t1", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-zeno---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-zeno---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-zeno_signal---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-zeno_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t2---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t2---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t2_signal---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t2_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t2_signal_single_shot---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t2_signal_single_shot---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-t2", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey_signal---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey_signal_detuned---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey_signal_detuned---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey_signal_detuned_unrolled---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey_signal_detuned_unrolled---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-calibrate_state_discrimination---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-calibrate_state_discrimination---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey_detuned---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey_detuned---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey_unrolled_detuned---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-ramsey_unrolled_detuned---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-readout", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-allXY---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-allXY---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-allXY", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-drag_pulse_tuning---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-drag_pulse_tuning---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-spin_echo---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-spin_echo---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-spin_echo", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-spin_echo_signal---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-spin_echo_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-spin_echo_signal_single_shot---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-spin_echo_signal_single_shot---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-spin_echo_signal", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-flipping", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-flipping_signal", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-dispersive", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-chevron", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-cz---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-cz---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-cz", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-resonator_frequency---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-resonator_frequency---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-fast", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-twpa", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-twpa_power_SNR---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-twpa_power_SNR---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-twpa_frequency_SNR---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-twpa_frequency_SNR---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-resonator_amplitude---update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-resonator_amplitude---no-update]", "tests/test_protocols.py::test_fit_command[dummy-protocols.yml-avoided", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-time", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-resonator", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-resonator_punchout_attenuation---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-resonator_punchout_attenuation---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-qubit", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-rabi---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-rabi---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-rabi", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-rabi_ef---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-rabi_ef---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t1---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t1---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t1_signal---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t1_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t1_signal_single_shot---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t1_signal_single_shot---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t1", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-zeno---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-zeno---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-zeno_signal---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-zeno_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t2---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t2---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t2_signal---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t2_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t2_signal_single_shot---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t2_signal_single_shot---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-t2", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey_signal---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey_signal_detuned---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey_signal_detuned---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey_signal_detuned_unrolled---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey_signal_detuned_unrolled---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-calibrate_state_discrimination---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-calibrate_state_discrimination---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey_detuned---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey_detuned---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey_unrolled_detuned---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-ramsey_unrolled_detuned---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-readout", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-allXY---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-allXY---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-allXY", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-drag_pulse_tuning---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-drag_pulse_tuning---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-spin_echo---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-spin_echo---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-spin_echo", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-spin_echo_signal---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-spin_echo_signal---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-spin_echo_signal_single_shot---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-spin_echo_signal_single_shot---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-spin_echo_signal", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-flipping", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-flipping_signal", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-dispersive", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-chevron", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-cz---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-cz---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-cz", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-resonator_frequency---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-resonator_frequency---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-fast", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-twpa", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-twpa_power_SNR---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-twpa_power_SNR---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-twpa_frequency_SNR---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-twpa_frequency_SNR---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-resonator_amplitude---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-resonator_amplitude---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols.yml-avoided", "tests/test_protocols.py::test_fit_command[dummy-rb_noise_protocols.yml-standard", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy0---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy0---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy1---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy1---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy2---update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols_couplers.yml-coupler_resonator_spectroscopy2---no-update]", "tests/test_protocols.py::test_fit_command[dummy_couplers-protocols_couplers.yml-coupler", "tests/test_protocols.py::test_extract_rabi", "tests/test_protocols.py::test_resonator_flux_bias", "tests/test_randomized_benchmarking.py::test_1expfitting", "tests/test_randomized_benchmarking.py::test_exp2_fitting", "tests/test_randomized_benchmarking.py::test_PauliErrors", "tests/test_randomized_benchmarking.py::test_random_clifford[1-10]", "tests/test_randomized_benchmarking.py::test_random_clifford[2-10]", "tests/test_randomized_benchmarking.py::test_random_clifford[qubits2-10]", "tests/test_randomized_benchmarking.py::test_random_clifford[qubits3-10]", "tests/test_randomized_benchmarking.py::test_number_to_str[0.555555]", "tests/test_randomized_benchmarking.py::test_number_to_str[2]", "tests/test_randomized_benchmarking.py::test_number_to_str[(-0.1+0.1j)]", "tests/test_task_options.py::test_targets_argument[None-numpy]", "tests/test_task_options.py::test_targets_argument[None-qibolab]", "tests/test_task_options.py::test_targets_argument[local_targets1-numpy]", "tests/test_task_options.py::test_targets_argument[local_targets1-qibolab]", "tests/test_task_options.py::test_update_argument[True-True]", "tests/test_task_options.py::test_update_argument[True-False]", "tests/test_task_options.py::test_update_argument[False-True]", "tests/test_task_options.py::test_update_argument[False-False]", "tests/test_task_options.py::test_parameters_load[True-SingleShotClassificationParameters]", "tests/test_task_options.py::test_parameters_load[True-ReadoutMitigationMatrixParameters]", "tests/test_task_options.py::test_parameters_load[False-SingleShotClassificationParameters]", "tests/test_task_options.py::test_parameters_load[False-ReadoutMitigationMatrixParameters]", "tests/test_update.py::test_readout_frequency_update[qubit0]", "tests/test_update.py::test_readout_frequency_update[qubit1]", "tests/test_update.py::test_readout_frequency_update[qubit2]", "tests/test_update.py::test_readout_frequency_update[qubit3]", "tests/test_update.py::test_readout_frequency_update[qubit4]", "tests/test_update.py::test_update_bare_resonator_frequency_update[qubit0]", "tests/test_update.py::test_update_bare_resonator_frequency_update[qubit1]", "tests/test_update.py::test_update_bare_resonator_frequency_update[qubit2]", "tests/test_update.py::test_update_bare_resonator_frequency_update[qubit3]", "tests/test_update.py::test_update_bare_resonator_frequency_update[qubit4]", "tests/test_update.py::test_readout_amplitude_update[qubit0]", "tests/test_update.py::test_readout_amplitude_update[qubit1]", "tests/test_update.py::test_readout_amplitude_update[qubit2]", "tests/test_update.py::test_readout_amplitude_update[qubit3]", "tests/test_update.py::test_readout_amplitude_update[qubit4]", "tests/test_update.py::test_readout_attenuation_update[qubit0]", "tests/test_update.py::test_readout_attenuation_update[qubit1]", "tests/test_update.py::test_readout_attenuation_update[qubit2]", "tests/test_update.py::test_readout_attenuation_update[qubit3]", "tests/test_update.py::test_readout_attenuation_update[qubit4]", "tests/test_update.py::test_drive_frequency_update[qubit0]", "tests/test_update.py::test_drive_frequency_update[qubit1]", "tests/test_update.py::test_drive_frequency_update[qubit2]", "tests/test_update.py::test_drive_frequency_update[qubit3]", "tests/test_update.py::test_drive_frequency_update[qubit4]", "tests/test_update.py::test_drive_amplitude_update[qubit0]", "tests/test_update.py::test_drive_amplitude_update[qubit1]", "tests/test_update.py::test_drive_amplitude_update[qubit2]", "tests/test_update.py::test_drive_amplitude_update[qubit3]", "tests/test_update.py::test_drive_amplitude_update[qubit4]", "tests/test_update.py::test_classification_update[qubit0]", "tests/test_update.py::test_classification_update[qubit1]", "tests/test_update.py::test_classification_update[qubit2]", "tests/test_update.py::test_classification_update[qubit3]", "tests/test_update.py::test_classification_update[qubit4]", "tests/test_update.py::test_virtual_phases_update[pair0]", "tests/test_update.py::test_virtual_phases_update[pair1]", "tests/test_update.py::test_virtual_phases_update[pair2]", "tests/test_update.py::test_virtual_phases_update[pair3]", "tests/test_update.py::test_virtual_phases_update[pair4]", "tests/test_update.py::test_virtual_phases_update[pair5]", "tests/test_update.py::test_virtual_phases_update[pair6]", "tests/test_update.py::test_virtual_phases_update[pair7]", "tests/test_update.py::test_CZ_params_update[pair0]", "tests/test_update.py::test_CZ_params_update[pair1]", "tests/test_update.py::test_CZ_params_update[pair2]", "tests/test_update.py::test_CZ_params_update[pair3]", "tests/test_update.py::test_CZ_params_update[pair4]", "tests/test_update.py::test_CZ_params_update[pair5]", "tests/test_update.py::test_CZ_params_update[pair6]", "tests/test_update.py::test_CZ_params_update[pair7]", "tests/test_update.py::test_coherence_params_update[qubit0]", "tests/test_update.py::test_coherence_params_update[qubit1]", "tests/test_update.py::test_coherence_params_update[qubit2]", "tests/test_update.py::test_coherence_params_update[qubit3]", "tests/test_update.py::test_coherence_params_update[qubit4]", "tests/test_update.py::test_drag_pulse_beta_update[qubit0]", "tests/test_update.py::test_drag_pulse_beta_update[qubit1]", "tests/test_update.py::test_drag_pulse_beta_update[qubit2]", "tests/test_update.py::test_drag_pulse_beta_update[qubit3]", "tests/test_update.py::test_drag_pulse_beta_update[qubit4]", "tests/test_update.py::test_sweetspot_update[qubit0]", "tests/test_update.py::test_sweetspot_update[qubit1]", "tests/test_update.py::test_sweetspot_update[qubit2]", "tests/test_update.py::test_sweetspot_update[qubit3]", "tests/test_update.py::test_sweetspot_update[qubit4]", "tests/test_update.py::test_12_transition_update[qubit0]", "tests/test_update.py::test_12_transition_update[qubit1]", "tests/test_update.py::test_12_transition_update[qubit2]", "tests/test_update.py::test_12_transition_update[qubit3]", "tests/test_update.py::test_twpa_update[qubit0]", "tests/test_update.py::test_twpa_update[qubit1]", "tests/test_update.py::test_twpa_update[qubit2]", "tests/test_update.py::test_twpa_update[qubit3]", "tests/test_update.py::test_twpa_update[qubit4]", "tests/test_update.py::test_kernel_update[qubit0]", "tests/test_update.py::test_kernel_update[qubit1]", "tests/test_update.py::test_kernel_update[qubit2]", "tests/test_update.py::test_kernel_update[qubit3]", "tests/test_update.py::test_kernel_update[qubit4]", "tests/test_utils.py::test_cumulative", "tests/test_utils.py::test_eval_magnitude" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-04-19 17:15:33+00:00
apache-2.0
5,139
qiboteam__qibolab-549
diff --git a/src/qibolab/compilers/compiler.py b/src/qibolab/compilers/compiler.py index 1ba19a6a..1b2af972 100644 --- a/src/qibolab/compilers/compiler.py +++ b/src/qibolab/compilers/compiler.py @@ -6,6 +6,7 @@ from qibo.config import raise_error from qibolab.compilers.default import ( cz_rule, + gpi2_rule, identity_rule, measurement_rule, rz_rule, @@ -46,6 +47,7 @@ class Compiler: gates.RZ: rz_rule, gates.U3: u3_rule, gates.CZ: cz_rule, + gates.GPI2: gpi2_rule, gates.M: measurement_rule, } ) diff --git a/src/qibolab/compilers/default.py b/src/qibolab/compilers/default.py index c8840d61..1bc5393b 100644 --- a/src/qibolab/compilers/default.py +++ b/src/qibolab/compilers/default.py @@ -24,6 +24,17 @@ def rz_rule(gate, platform): return PulseSequence(), {qubit: gate.parameters[0]} +def gpi2_rule(gate, platform): + """Rule for GPI2.""" + qubit = gate.target_qubits[0] + theta = gate.parameters[0] + + sequence = PulseSequence() + pulse = platform.create_RX90_pulse(qubit, start=0, relative_phase=theta) + sequence.add(pulse) + return sequence, {} + + def u3_rule(gate, platform): """U3 applied as RZ-RX90-RZ-RX90-RZ.""" qubit = gate.target_qubits[0] diff --git a/src/qibolab/transpilers/gate_decompositions.py b/src/qibolab/transpilers/gate_decompositions.py index be12f885..94cd1016 100644 --- a/src/qibolab/transpilers/gate_decompositions.py +++ b/src/qibolab/transpilers/gate_decompositions.py @@ -121,6 +121,8 @@ onequbit_dec.add(gates.RY, lambda gate: [gates.U3(0, gate.parameters[0], 0, 0)]) # apply virtually by changing ``phase`` instead of using pulses onequbit_dec.add(gates.RZ, lambda gate: [gates.RZ(0, gate.parameters[0])]) # apply virtually by changing ``phase`` instead of using pulses +onequbit_dec.add(gates.GPI2, lambda gate: [gates.GPI2(0, gate.parameters[0])]) +# implemented as single RX90 pulse onequbit_dec.add(gates.U1, lambda gate: [gates.RZ(0, gate.parameters[0])]) onequbit_dec.add(gates.U2, lambda gate: [gates.U3(0, np.pi / 2, gate.parameters[0], gate.parameters[1])]) onequbit_dec.add(gates.U3, lambda gate: [gates.U3(0, gate.parameters[0], gate.parameters[1], gate.parameters[2])])
qiboteam/qibolab
c31e5c81c33fd280af1f023873b24f24a1cb3718
diff --git a/tests/test_compilers_default.py b/tests/test_compilers_default.py index dc9cb748..55ef88cc 100644 --- a/tests/test_compilers_default.py +++ b/tests/test_compilers_default.py @@ -100,6 +100,20 @@ def test_rz_to_sequence(platform): assert len(sequence) == 0 +def test_GPI2_to_sequence(platform): + circuit = Circuit(1) + circuit.add(gates.GPI2(0, phi=0.2)) + sequence = compile_circuit(circuit, platform) + assert len(sequence.pulses) == 1 + assert len(sequence.qd_pulses) == 1 + + RX90_pulse = platform.create_RX90_pulse(0, start=0, relative_phase=0.2) + s = PulseSequence(RX90_pulse) + + np.testing.assert_allclose(sequence.duration, RX90_pulse.duration) + assert sequence.serial == s.serial + + def test_u3_to_sequence(platform): circuit = Circuit(1) circuit.add(gates.U3(0, 0.1, 0.2, 0.3)) diff --git a/tests/test_transpilers_gate_decompositions.py b/tests/test_transpilers_gate_decompositions.py index 007223c3..65a7538e 100644 --- a/tests/test_transpilers_gate_decompositions.py +++ b/tests/test_transpilers_gate_decompositions.py @@ -63,6 +63,11 @@ def test_u3_to_native(): assert_matrices_allclose(gate, two_qubit_natives=NativeType.CZ) +def test_gpi2_to_native(): + gate = gates.GPI2(0, phi=0.123) + assert_matrices_allclose(gate, two_qubit_natives=NativeType.CZ) + + @pytest.mark.parametrize("gatename", ["CNOT", "CZ", "SWAP", "iSWAP", "FSWAP"]) @pytest.mark.parametrize( "natives",
Missing GPI2 decomposition In https://github.com/qiboteam/qibocal/pull/452 I'm trying to run a circuit on hardware containing the `GPI2` gate implemented in Qibo and I got the following error. ```sh KeyError: <class 'qibo.gates.gates.GPI2'> ```` If I understood correctly the reason for this is that we are missing the GPI2 gate in the [gate decomposition](https://github.com/qiboteam/qibolab/blob/main/src/qibolab/transpilers/gate_decompositions.py) the transpiler. Actually it would nice to make sure that all gate represented in Qibo have their decomposition also in the transpiler.
0.0
c31e5c81c33fd280af1f023873b24f24a1cb3718
[ "tests/test_transpilers_gate_decompositions.py::test_gpi2_to_native" ]
[ "tests/test_compilers_default.py::test_u3_sim_agreement", "tests/test_transpilers_gate_decompositions.py::test_pauli_to_native[H]", "tests/test_transpilers_gate_decompositions.py::test_pauli_to_native[X]", "tests/test_transpilers_gate_decompositions.py::test_pauli_to_native[Y]", "tests/test_transpilers_gate_decompositions.py::test_pauli_to_native[I]", "tests/test_transpilers_gate_decompositions.py::test_rotations_to_native[RX]", "tests/test_transpilers_gate_decompositions.py::test_rotations_to_native[RY]", "tests/test_transpilers_gate_decompositions.py::test_rotations_to_native[RZ]", "tests/test_transpilers_gate_decompositions.py::test_special_single_qubit_to_native[S]", "tests/test_transpilers_gate_decompositions.py::test_special_single_qubit_to_native[SDG]", "tests/test_transpilers_gate_decompositions.py::test_special_single_qubit_to_native[T]", "tests/test_transpilers_gate_decompositions.py::test_special_single_qubit_to_native[TDG]", "tests/test_transpilers_gate_decompositions.py::test_u1_to_native", "tests/test_transpilers_gate_decompositions.py::test_u2_to_native", "tests/test_transpilers_gate_decompositions.py::test_u3_to_native", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.CZ-CNOT]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.CZ-CZ]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.CZ-SWAP]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.CZ-iSWAP]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.CZ-FSWAP]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.iSWAP0-CNOT]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.iSWAP0-CZ]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.iSWAP0-SWAP]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.iSWAP0-iSWAP]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.iSWAP0-FSWAP]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.iSWAP1-CNOT]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.iSWAP1-CZ]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.iSWAP1-SWAP]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.iSWAP1-iSWAP]", "tests/test_transpilers_gate_decompositions.py::test_two_qubit_to_native[NativeType.iSWAP1-FSWAP]", "tests/test_transpilers_gate_decompositions.py::test_controlled_rotations_to_native[CRX-NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_controlled_rotations_to_native[CRX-NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_controlled_rotations_to_native[CRX-NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_controlled_rotations_to_native[CRY-NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_controlled_rotations_to_native[CRY-NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_controlled_rotations_to_native[CRY-NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_controlled_rotations_to_native[CRZ-NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_controlled_rotations_to_native[CRZ-NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_controlled_rotations_to_native[CRZ-NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_cu1_to_native[NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_cu1_to_native[NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_cu1_to_native[NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_cu2_to_native[NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_cu2_to_native[NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_cu2_to_native[NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_cu3_to_native[NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_cu3_to_native[NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_cu3_to_native[NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_fSim_to_native[NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_fSim_to_native[NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_fSim_to_native[NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_GeneralizedfSim_to_native[NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_GeneralizedfSim_to_native[NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_GeneralizedfSim_to_native[NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_rnn_to_native[RXX-NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_rnn_to_native[RXX-NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_rnn_to_native[RXX-NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_rnn_to_native[RZZ-NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_rnn_to_native[RZZ-NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_rnn_to_native[RZZ-NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_rnn_to_native[RYY-NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_rnn_to_native[RYY-NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_rnn_to_native[RYY-NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_TOFFOLI_to_native[NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_TOFFOLI_to_native[NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_TOFFOLI_to_native[NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_unitary_to_native[1-NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_unitary_to_native[1-NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_unitary_to_native[1-NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_unitary_to_native[2-NativeType.CZ]", "tests/test_transpilers_gate_decompositions.py::test_unitary_to_native[2-NativeType.iSWAP0]", "tests/test_transpilers_gate_decompositions.py::test_unitary_to_native[2-NativeType.iSWAP1]", "tests/test_transpilers_gate_decompositions.py::test_count_1q", "tests/test_transpilers_gate_decompositions.py::test_count_2q" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-08-02 12:48:48+00:00
apache-2.0
5,140
qiboteam__qibolab-603
diff --git a/src/qibolab/dummy.py b/src/qibolab/dummy.py index ac71031b..cf6cab15 100644 --- a/src/qibolab/dummy.py +++ b/src/qibolab/dummy.py @@ -27,6 +27,15 @@ RUNCARD = { "start": 0, "phase": 0, }, + "RX12": { + "duration": 40, + "amplitude": 0.005, + "frequency": 4700000000, + "shape": "Gaussian(5)", + "type": "qd", + "start": 0, + "phase": 0, + }, "MZ": { "duration": 1000, "amplitude": 0.0025, @@ -47,6 +56,15 @@ RUNCARD = { "start": 0, "phase": 0, }, + "RX12": { + "duration": 40, + "amplitude": 0.0484, + "frequency": 4855663000, + "shape": "Drag(5, -0.02)", + "type": "qd", + "start": 0, + "phase": 0, + }, "MZ": { "duration": 620, "amplitude": 0.003575, @@ -67,6 +85,15 @@ RUNCARD = { "start": 0, "phase": 0, }, + "RX12": { + "duration": 40, + "amplitude": 0.005, + "frequency": 2700000000, + "shape": "Gaussian(5)", + "type": "qd", + "start": 0, + "phase": 0, + }, "MZ": { "duration": 1000, "amplitude": 0.0025, @@ -87,6 +114,15 @@ RUNCARD = { "start": 0, "phase": 0, }, + "RX12": { + "duration": 40, + "amplitude": 0.0484, + "frequency": 5855663000, + "shape": "Drag(5, -0.02)", + "type": "qd", + "start": 0, + "phase": 0, + }, "MZ": { "duration": 620, "amplitude": 0.003575, diff --git a/src/qibolab/native.py b/src/qibolab/native.py index 899c3db7..ed04dfd1 100644 --- a/src/qibolab/native.py +++ b/src/qibolab/native.py @@ -188,7 +188,11 @@ class SingleQubitNatives: """Container with the native single-qubit gates acting on a specific qubit.""" RX: Optional[NativePulse] = None + """Pulse to drive the qubit from state 0 to state 1.""" + RX12: Optional[NativePulse] = None + """Pulse to drive to qubit from state 1 to state 2.""" MZ: Optional[NativePulse] = None + """Measurement pulse.""" @property def RX90(self) -> NativePulse: diff --git a/src/qibolab/platform.py b/src/qibolab/platform.py index eff7838f..404ba08f 100644 --- a/src/qibolab/platform.py +++ b/src/qibolab/platform.py @@ -243,6 +243,10 @@ class Platform: qubit = self.get_qubit(qubit) return self.qubits[qubit].native_gates.RX.pulse(start, relative_phase) + def create_RX12_pulse(self, qubit, start=0, relative_phase=0): + qubit = self.get_qubit(qubit) + return self.qubits[qubit].native_gates.RX12.pulse(start, relative_phase) + def create_CZ_pulse_sequence(self, qubits, start=0): # Check in the settings if qubits[0]-qubits[1] is a key pair = tuple(sorted(self.get_qubit(q) for q in qubits))
qiboteam/qibolab
21850791ee303e0d95dec3368cab29f0df41aceb
diff --git a/tests/dummy_qrc/qblox.yml b/tests/dummy_qrc/qblox.yml index f482612e..032b220c 100644 --- a/tests/dummy_qrc/qblox.yml +++ b/tests/dummy_qrc/qblox.yml @@ -26,6 +26,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 + amplitude: 0.5028 + frequency: 5_050_304_836 + # if_frequency: -200_000_000 # difference in qubit frequency + shape: Gaussian(5) + type: qd + relative_start: 0 + phase: 0 MZ: duration: 2000 amplitude: 0.1 @@ -45,6 +54,15 @@ native_gates: type: qd relative_start: 0 phase: 0 # qubit drive + RX12: + duration: 40 # should be multiple of 4 + amplitude: 0.5078 + frequency: 4_852_833_073 # qubit frequency + # if_frequency: -200_000_000 # difference in qubit frequency + shape: Gaussian(5) + type: qd + relative_start: 0 + phase: 0 MZ: duration: 2000 amplitude: 0.2 @@ -64,6 +82,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 # should be multiple of 4 + amplitude: 0.5016 + frequency: 5_795_371_914 # qubit frequency + # if_frequency: -200_000_000 # difference in qubit frequency + shape: Gaussian(5) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 2000 amplitude: 0.25 @@ -83,6 +110,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 # should be multiple of 4 + amplitude: 0.5026 + frequency: 6_761_018_001 # qubit frequency + # if_frequency: -200_000_000 # difference in qubit frequency + shape: Gaussian(5) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 2000 amplitude: 0.2 @@ -102,6 +138,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 # should be multiple of 4 + amplitude: 0.5172 + frequency: 6_586_543_060 # qubit frequency + # if_frequency: -200_000_000 # difference in qubit frequency + shape: Gaussian(5) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 2000 amplitude: 0.4 diff --git a/tests/dummy_qrc/qm.yml b/tests/dummy_qrc/qm.yml index b96e45d7..cb46e54e 100644 --- a/tests/dummy_qrc/qm.yml +++ b/tests/dummy_qrc/qm.yml @@ -41,6 +41,14 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 + amplitude: 0.005 + frequency: 4_700_000_000 + shape: Gaussian(5) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 1000 amplitude: 0.0025 @@ -59,6 +67,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 + amplitude: 0.0484 + frequency: 4_855_663_000 + #frequency: 4_718_515_000 # 02 transition (more likely) + shape: Drag(5, -0.02) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 620 amplitude: 0.003575 @@ -77,6 +94,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 + amplitude: 0.05682 + frequency: 5_800_563_000 + #frequency: 5_661_400_000 # 02 transition + shape: Drag(5, -0.04) #Gaussian(5) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 960 amplitude: 0.00325 @@ -95,6 +121,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 + amplitude: 0.138 + frequency: 6_760_922_000 + #frequency: 6_628_822_000 # 02 transition + shape: Gaussian(5) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 960 amplitude: 0.004225 @@ -112,6 +147,14 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 + amplitude: 0.0617 + frequency: 6_585_053_000 + shape: Drag(5, 0.0) #Gaussian(5) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 640 amplitude: 0.0039 diff --git a/tests/dummy_qrc/rfsoc.yml b/tests/dummy_qrc/rfsoc.yml index 2d179f0c..8a4f5f5e 100644 --- a/tests/dummy_qrc/rfsoc.yml +++ b/tests/dummy_qrc/rfsoc.yml @@ -17,6 +17,8 @@ native_gates: 0: RX: {duration: 30, amplitude: 0.05284168507293318, frequency: 5542341844, shape: Rectangular(), type: qd, relative_start: 0, phase: 0} + RX12: {duration: 30, amplitude: 0.05284168507293318, frequency: 5542341844, + shape: Rectangular(), type: qd, relative_start: 0, phase: 0} MZ: {duration: 600, amplitude: 0.03, frequency: 7371258599, shape: Rectangular(), type: ro, relative_start: 0, phase: 0} two_qubit: {} diff --git a/tests/dummy_qrc/zurich.yml b/tests/dummy_qrc/zurich.yml index e6d6b3b1..3602ca93 100644 --- a/tests/dummy_qrc/zurich.yml +++ b/tests/dummy_qrc/zurich.yml @@ -35,6 +35,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 + amplitude: 0.625 #0.45 + frequency: 4_095_830_788 #doesnt do anything requiered for qibolab to work + # shape: Gaussian(5) + shape: Drag(5, 0.04) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 2000 #2000.e-9 amplitude: .5 # .1 @@ -54,6 +63,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 90 #80 + amplitude: 0.2 #0.2 + frequency: 4_170_000_000 #doesnt do anything requiered for qibolab to work + shape: Gaussian(5) + # shape: Drag(5, 0.04) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 1000 amplitude: .1 # 1 @@ -73,6 +91,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 40 #200 #60 + amplitude: 0.59 + frequency: 4_300_587_281 #4_401_600_000 #4_505_500_000 #4_321_500_000 # 4_541_100_000 #doesnt do anything requiered for qibolab to work + shape: Gaussian(5) + # shape: Drag(5, 0.04) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 2000 amplitude: .54 @@ -92,6 +119,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 90 #80 + amplitude: 0.75 #0.8 + frequency: 4_100_000_000 #doesnt do anything requiered for qibolab to work + shape: Gaussian(5) + # shape: Drag(5, 0.04) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 2000 amplitude: .01 # 1 @@ -111,6 +147,15 @@ native_gates: type: qd # qubit drive relative_start: 0 phase: 0 + RX12: + duration: 53 #110 #80 + amplitude: 1 #0.398 #0.8 + frequency: 4_196_800_000 #Small detuning increase freq #4_248_775_000 #doesnt do anything requiered for qibolab to work + shape: Gaussian(5) + # shape: Drag(5, 0.04) + type: qd # qubit drive + relative_start: 0 + phase: 0 MZ: duration: 1000 amplitude: .5 #.50 # 1 diff --git a/tests/test_dummy.py b/tests/test_dummy.py index 6bca16a5..eae29065 100644 --- a/tests/test_dummy.py +++ b/tests/test_dummy.py @@ -22,6 +22,7 @@ def test_dummy_execute_pulse_sequence(acquisition): platform = create_platform("dummy") sequence = PulseSequence() sequence.add(platform.create_qubit_readout_pulse(0, 0)) + sequence.add(platform.create_RX12_pulse(0, 0)) options = ExecutionParameters(nshots=None, acquisition_type=acquisition) result = platform.execute_pulse_sequence(sequence, options)
Add native pulse to generate state 2 to platform In order to efficiently calibrate two qubit gates we will need to be able to generate and classify also the state $\ket{2}$. See for example qiboteam/qibocal#477 and qiboteam/qibocal#466. I'm currently working on something in qibocal to calibrate this pulse. I guess that the simplest solution would be to add also a native pulse for the this state, right? For a quick summary on how to calibrate this pulse you can have a look here https://learn.qiskit.org/course/quantum-hardware-pulses/accessing-higher-energy-states-with-qiskit-pulse Let me know what you think @stavros11 @AleCandido @igres26 @aorgazf @scarrazza
0.0
21850791ee303e0d95dec3368cab29f0df41aceb
[ "tests/test_dummy.py::test_dummy_execute_pulse_sequence[AcquisitionType.INTEGRATION]", "tests/test_dummy.py::test_dummy_execute_pulse_sequence[AcquisitionType.RAW]" ]
[ "tests/test_dummy.py::test_dummy_initialization", "tests/test_dummy.py::test_dummy_execute_pulse_sequence_fast_reset", "tests/test_dummy.py::test_dummy_execute_pulse_sequence_unrolling[AcquisitionType.INTEGRATION]", "tests/test_dummy.py::test_dummy_execute_pulse_sequence_unrolling[AcquisitionType.DISCRIMINATION]", "tests/test_dummy.py::test_dummy_single_sweep_RAW", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-False]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-False]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-True]", "tests/test_dummy.py::test_dummy_single_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-False]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.frequency]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.duration]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.start]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.gain]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.bias]", "tests/test_dummy.py::test_dummy_double_sweep[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[10-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.duration]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.start]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.gain]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.bias]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.duration]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.start]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.gain]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.bias]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.INTEGRATION-AveragingMode.CYCLIC-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.duration]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.start]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.gain]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.bias]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.SINGLESHOT-Parameter.lo_frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.frequency]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.amplitude]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.duration]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.relative_phase]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.start]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.attenuation]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.gain]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.bias]", "tests/test_dummy.py::test_dummy_single_sweep_multiplex[20-AcquisitionType.DISCRIMINATION-AveragingMode.CYCLIC-Parameter.lo_frequency]" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-09-27 12:32:41+00:00
apache-2.0
5,141
qiboteam__qibolab-659
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 9a58abee..75df67bc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,7 +10,7 @@ repos: - id: check-toml - id: debug-statements - repo: https://github.com/psf/black - rev: 23.10.1 + rev: 23.11.0 hooks: - id: black args: @@ -25,7 +25,7 @@ repos: hooks: - id: pyupgrade - repo: https://github.com/hadialqattan/pycln - rev: v2.3.0 + rev: v2.4.0 hooks: - id: pycln args: diff --git a/src/qibolab/instruments/qblox/controller.py b/src/qibolab/instruments/qblox/controller.py index 245bf018..d2e5fc3e 100644 --- a/src/qibolab/instruments/qblox/controller.py +++ b/src/qibolab/instruments/qblox/controller.py @@ -216,6 +216,7 @@ class QbloxController(Controller): for ro_pulse in sequence.ro_pulses: if options.acquisition_type is AcquisitionType.DISCRIMINATION: _res = acquisition_results[ro_pulse.serial][2] + _res = _res.reshape(nshots, -1) if options.averaging_mode == AveragingMode.SINGLESHOT else _res if average: _res = np.mean(_res, axis=0) else: diff --git a/src/qibolab/instruments/zhinst.py b/src/qibolab/instruments/zhinst.py index 7a1df9ac..e8b5c8db 100644 --- a/src/qibolab/instruments/zhinst.py +++ b/src/qibolab/instruments/zhinst.py @@ -503,8 +503,13 @@ class Zurich(Controller): ) def run_exp(self): - """Compilation settings, compilation step, execution step and data retrival""" - # self.experiment.save("saved_exp") + """ + Compilation settings, compilation step, execution step and data retrival + - Save a experiment Python object: + self.experiment.save("saved_exp") + - Save a experiment compiled experiment (): + self.exp.save("saved_exp") # saving compiled experiment + """ self.exp = self.session.compile(self.experiment, compiler_settings=COMPILER_SETTINGS) # self.exp.save_compiled_experiment("saved_exp") self.results = self.session.run(self.exp) @@ -890,38 +895,18 @@ class Zurich(Controller): """qubit readout pulse, data acquisition and qubit relaxation""" play_after = None - if len(self.sequence_qibo.qf_pulses) != 0 and len(self.sequence_qibo.qd_pulses) != 0: - play_after = ( - self.play_after_set(self.sequence_qibo.qf_pulses, "bias") - if self.sequence_qibo.qf_pulses.finish > self.sequence_qibo.qd_pulses.finish - else self.play_after_set(self.sequence_qibo.qd_pulses, "drive") - ) - if len(self.sequence_qibo.cf_pulses) != 0 and len(self.sequence_qibo.qd_pulses) != 0: - play_after = ( - self.play_after_set(self.sequence_qibo.cf_pulses, "bias_coupler") - if self.sequence_qibo.cf_pulses.finish > self.sequence_qibo.qd_pulses.finish - else self.play_after_set(self.sequence_qibo.qd_pulses, "drive") - ) + # TODO: if we use duration sweepers, the code might not behave as expected + # i.e.: self.sequence_qibo will contain the a pulse or sweeper with a static duration that may screw the comparison + qf_finish = self.sequence_qibo.qf_pulses.finish + qd_finish = self.sequence_qibo.qd_pulses.finish + cf_finish = self.sequence_qibo.cf_pulses.finish - elif len(self.sequence_qibo.qf_pulses) != 0: + if qf_finish > qd_finish and qf_finish > cf_finish: play_after = self.play_after_set(self.sequence_qibo.qf_pulses, "bias") - elif len(self.sequence_qibo.qd_pulses) != 0: + elif qd_finish > qf_finish and qd_finish > cf_finish: play_after = self.play_after_set(self.sequence_qibo.qd_pulses, "drive") - elif ( - len(self.sequence_qibo.qf_pulses) != 0 - and len(self.sequence_qibo.qd_pulses) != 0 - and len(self.sequence_qibo.cf_pulses) != 0 - ): - seq_qf = self.sequence_qibo.qf_pulses.finish - seq_qd = self.sequence_qibo.qd_pulses.finish - seq_cf = self.sequence_qibo.cf_pulses.finish - # add here for flux coupler pulses - if seq_qf > seq_qd and seq_qf > seq_cf: - play_after = self.play_after_set(self.sequence_qibo.qf_pulses, "bias") - elif seq_qd > seq_qf and seq_qd > seq_cf: - play_after = self.play_after_set(self.sequence_qibo.qd_pulses, "drive") - elif seq_cf > seq_qf and seq_cf > seq_qd: - play_after = self.play_after_set(self.sequence_qibo.cf_pulse, "bias_coupler") + elif cf_finish > qf_finish and cf_finish > qd_finish: + play_after = self.play_after_set(self.sequence_qibo.cf_pulses, "bias_coupler") readout_schedule = defaultdict(list) qubit_readout_schedule = defaultdict(list) @@ -946,6 +931,9 @@ class Zurich(Controller): for pulse, q, iq_angle in zip(pulses, qubits, iq_angles): pulse.zhpulse.uid += str(i) + # TODO: if the measure sequence starts after the last pulse, add a delay + # keep in mind that the signal might start before the last pulse + # if sweepers are involved if play_after is None: exp.delay( signal=f"measure{q}", diff --git a/src/qibolab/pulses.py b/src/qibolab/pulses.py index 90c6c1d6..100bf498 100644 --- a/src/qibolab/pulses.py +++ b/src/qibolab/pulses.py @@ -733,7 +733,7 @@ class Pulse: value (se_int | int | np.integer): the time in ns. """ - if not isinstance(value, (se_int, int, np.integer)): + if not isinstance(value, (se_int, int, np.integer, float)): raise TypeError(f"start argument type should be intSymbolicExpression or int, got {type(value).__name__}") if not value >= 0: raise ValueError(f"start argument must be >= 0, got {value}") @@ -749,7 +749,7 @@ class Pulse: else: if isinstance(value, np.integer): self._start = int(value) - elif isinstance(value, int): + else: self._start = value if not self._duration is None: @@ -794,7 +794,7 @@ class Pulse: else: if isinstance(value, np.integer): self._duration = int(value) - elif isinstance(value, int): + else: self._duration = value if not self._start is None:
qiboteam/qibolab
139914889c7dc5e2dc0010abe3a4f4ac7852f225
diff --git a/tests/test_pulses.py b/tests/test_pulses.py index 9c0edb98..b4970f39 100644 --- a/tests/test_pulses.py +++ b/tests/test_pulses.py @@ -158,6 +158,23 @@ def test_pulses_pulse_init(): p11 = FluxPulse(0, 40, 0.9, SNZ(t_half_flux_pulse=17, b_amplitude=0.8), 0, 200) p11 = Pulse(0, 40, 0.9, 400e6, 0, eCap(alpha=2), 0, PulseType.DRIVE) + # initialisation with float duration and start + p12 = Pulse( + start=5.5, + duration=34.33, + amplitude=0.9, + frequency=20_000_000, + relative_phase=1, + shape=Rectangular(), + channel=0, + type=PulseType.READOUT, + qubit=0, + ) + assert repr(p12) == "Pulse(5.5, 34.33, 0.9, 20_000_000, 1, Rectangular(), 0, PulseType.READOUT, 0)" + assert isinstance(p12.start, float) + assert isinstance(p12.duration, float) + assert p12.finish == 5.5 + 34.33 + def test_pulses_pulse_attributes(): channel = 0 @@ -1152,9 +1169,9 @@ def test_pulse_properties(start, duration): check_properties(p0) [email protected]("faulty_start", [10.0, "hello"]) [email protected]("faulty_duration", [100.0, "hello"]) -def test_pulse_setter_errors(faulty_start, faulty_duration): +def test_pulse_setter_errors(): + faulty_duration = "hello" + faulty_start = "hello" with pytest.raises(TypeError): p0 = Pulse(faulty_start, 100, 0.9, 0, 0, Rectangular(), 0) with pytest.raises(TypeError):
Bugs when sweeping drive pulses parameters in qblox driver with `AveragingMode.SINGLESHOT` I found two bugs while running new protocols developed in https://github.com/qiboteam/qibocal/pull/567: 1. `rabi_amplitude` The error triggered is the following ```sh RecursionError: maximum recursion depth exceeded in comparison ``` 2. `rabi_length` Here is an example of a runcard: ```yml platform: qw5q_gold_qblox qubits: [0,1,2,3,4] actions: - id: rabi priority: 0 operation: rabi_length parameters: pulse_duration_start: 10 pulse_duration_end: 200 pulse_duration_step: 4 pulse_amplitude: 0.5 relaxation_time: 100_000 nshots: 1024 ``` In this case I see a single value in the plot: ![image](https://github.com/qiboteam/qibolab/assets/49183315/3123ece7-245e-41ec-b391-83fa327c4f22)
0.0
139914889c7dc5e2dc0010abe3a4f4ac7852f225
[ "tests/test_pulses.py::test_pulses_pulse_init" ]
[ "tests/test_pulses.py::test_pulses_pulse_attributes", "tests/test_pulses.py::test_pulses_is_equal_ignoring_start", "tests/test_pulses.py::test_pulses_pulse_serial", "tests/test_pulses.py::test_pulses_pulseshape_sampling_rate", "tests/test_pulses.py::test_raise_shapeiniterror", "tests/test_pulses.py::test_pulses_pulseshape_drag_shape", "tests/test_pulses.py::test_pulses_pulse_hash", "tests/test_pulses.py::test_pulses_pulse_aliases", "tests/test_pulses.py::test_pulses_pulse_split_pulse", "tests/test_pulses.py::test_pulses_pulsesequence_init", "tests/test_pulses.py::test_pulses_pulsesequence_operators", "tests/test_pulses.py::test_pulses_pulsesequence_add", "tests/test_pulses.py::test_pulses_pulsesequence_clear", "tests/test_pulses.py::test_pulses_pulsesequence_start_finish", "tests/test_pulses.py::test_pulses_pulsesequence_get_channel_pulses", "tests/test_pulses.py::test_pulses_pulsesequence_get_qubit_pulses", "tests/test_pulses.py::test_pulses_pulsesequence_pulses_overlap", "tests/test_pulses.py::test_pulses_pulsesequence_separate_overlapping_pulses", "tests/test_pulses.py::test_pulses_pulse_symbolic_expressions", "tests/test_pulses.py::test_pulses_pulse_pulse_order", "tests/test_pulses.py::test_pulses_waveform", "tests/test_pulses.py::test_pulses_pulseshape_rectangular", "tests/test_pulses.py::test_pulses_pulseshape_gaussian", "tests/test_pulses.py::test_pulses_pulseshape_drag", "tests/test_pulses.py::test_pulses_pulseshape_eq", "tests/test_pulses.py::test_pulse", "tests/test_pulses.py::test_readout_pulse", "tests/test_pulses.py::test_pulse_sequence_add", "tests/test_pulses.py::test_pulse_sequence__add__", "tests/test_pulses.py::test_pulse_sequence__mul__", "tests/test_pulses.py::test_pulse_sequence_add_readout", "tests/test_pulses.py::test_envelope_waveform_i_q", "tests/test_pulses.py::test_pulse_properties[100-0]", "tests/test_pulses.py::test_pulse_properties[100-10]", "tests/test_pulses.py::test_pulse_properties[100-start2]", "tests/test_pulses.py::test_pulse_properties[100-start3]", "tests/test_pulses.py::test_pulse_properties[500-0]", "tests/test_pulses.py::test_pulse_properties[500-10]", "tests/test_pulses.py::test_pulse_properties[500-start2]", "tests/test_pulses.py::test_pulse_properties[500-start3]", "tests/test_pulses.py::test_pulse_properties[duration2-0]", "tests/test_pulses.py::test_pulse_properties[duration2-10]", "tests/test_pulses.py::test_pulse_properties[duration2-start2]", "tests/test_pulses.py::test_pulse_properties[duration2-start3]", "tests/test_pulses.py::test_pulse_properties[duration3-0]", "tests/test_pulses.py::test_pulse_properties[duration3-10]", "tests/test_pulses.py::test_pulse_properties[duration3-start2]", "tests/test_pulses.py::test_pulse_properties[duration3-start3]", "tests/test_pulses.py::test_pulse_setter_errors" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-11-14 12:33:49+00:00
apache-2.0
5,142
qiboteam__qibolab-660
diff --git a/src/qibolab/pulses.py b/src/qibolab/pulses.py index 90c6c1d6..100bf498 100644 --- a/src/qibolab/pulses.py +++ b/src/qibolab/pulses.py @@ -733,7 +733,7 @@ class Pulse: value (se_int | int | np.integer): the time in ns. """ - if not isinstance(value, (se_int, int, np.integer)): + if not isinstance(value, (se_int, int, np.integer, float)): raise TypeError(f"start argument type should be intSymbolicExpression or int, got {type(value).__name__}") if not value >= 0: raise ValueError(f"start argument must be >= 0, got {value}") @@ -749,7 +749,7 @@ class Pulse: else: if isinstance(value, np.integer): self._start = int(value) - elif isinstance(value, int): + else: self._start = value if not self._duration is None: @@ -794,7 +794,7 @@ class Pulse: else: if isinstance(value, np.integer): self._duration = int(value) - elif isinstance(value, int): + else: self._duration = value if not self._start is None:
qiboteam/qibolab
139914889c7dc5e2dc0010abe3a4f4ac7852f225
diff --git a/tests/test_pulses.py b/tests/test_pulses.py index 9c0edb98..b4970f39 100644 --- a/tests/test_pulses.py +++ b/tests/test_pulses.py @@ -158,6 +158,23 @@ def test_pulses_pulse_init(): p11 = FluxPulse(0, 40, 0.9, SNZ(t_half_flux_pulse=17, b_amplitude=0.8), 0, 200) p11 = Pulse(0, 40, 0.9, 400e6, 0, eCap(alpha=2), 0, PulseType.DRIVE) + # initialisation with float duration and start + p12 = Pulse( + start=5.5, + duration=34.33, + amplitude=0.9, + frequency=20_000_000, + relative_phase=1, + shape=Rectangular(), + channel=0, + type=PulseType.READOUT, + qubit=0, + ) + assert repr(p12) == "Pulse(5.5, 34.33, 0.9, 20_000_000, 1, Rectangular(), 0, PulseType.READOUT, 0)" + assert isinstance(p12.start, float) + assert isinstance(p12.duration, float) + assert p12.finish == 5.5 + 34.33 + def test_pulses_pulse_attributes(): channel = 0 @@ -1152,9 +1169,9 @@ def test_pulse_properties(start, duration): check_properties(p0) [email protected]("faulty_start", [10.0, "hello"]) [email protected]("faulty_duration", [100.0, "hello"]) -def test_pulse_setter_errors(faulty_start, faulty_duration): +def test_pulse_setter_errors(): + faulty_duration = "hello" + faulty_start = "hello" with pytest.raises(TypeError): p0 = Pulse(faulty_start, 100, 0.9, 0, 0, Rectangular(), 0) with pytest.raises(TypeError):
Pulse duration validation Currently the pulse duration and start parameters are in integers of nanoseconds. However, this is an issue for instruments with sampling rates that are not 1GSps. For the IcarusQ RFSoC, we are using a [bisection](https://github.com/qiboteam/qibolab/blob/icarusq_multiqubit/src/qibolab/instruments/icarusqfpga.py#L263-L268) to retrieve the sample indices associated with the pulse. Perhaps this parameter can be sanitized on the driver side instead?
0.0
139914889c7dc5e2dc0010abe3a4f4ac7852f225
[ "tests/test_pulses.py::test_pulses_pulse_init" ]
[ "tests/test_pulses.py::test_pulses_pulse_attributes", "tests/test_pulses.py::test_pulses_is_equal_ignoring_start", "tests/test_pulses.py::test_pulses_pulse_serial", "tests/test_pulses.py::test_pulses_pulseshape_sampling_rate", "tests/test_pulses.py::test_raise_shapeiniterror", "tests/test_pulses.py::test_pulses_pulseshape_drag_shape", "tests/test_pulses.py::test_pulses_pulse_hash", "tests/test_pulses.py::test_pulses_pulse_aliases", "tests/test_pulses.py::test_pulses_pulse_split_pulse", "tests/test_pulses.py::test_pulses_pulsesequence_init", "tests/test_pulses.py::test_pulses_pulsesequence_operators", "tests/test_pulses.py::test_pulses_pulsesequence_add", "tests/test_pulses.py::test_pulses_pulsesequence_clear", "tests/test_pulses.py::test_pulses_pulsesequence_start_finish", "tests/test_pulses.py::test_pulses_pulsesequence_get_channel_pulses", "tests/test_pulses.py::test_pulses_pulsesequence_get_qubit_pulses", "tests/test_pulses.py::test_pulses_pulsesequence_pulses_overlap", "tests/test_pulses.py::test_pulses_pulsesequence_separate_overlapping_pulses", "tests/test_pulses.py::test_pulses_pulse_symbolic_expressions", "tests/test_pulses.py::test_pulses_pulse_pulse_order", "tests/test_pulses.py::test_pulses_waveform", "tests/test_pulses.py::test_pulses_pulseshape_rectangular", "tests/test_pulses.py::test_pulses_pulseshape_gaussian", "tests/test_pulses.py::test_pulses_pulseshape_drag", "tests/test_pulses.py::test_pulses_pulseshape_eq", "tests/test_pulses.py::test_pulse", "tests/test_pulses.py::test_readout_pulse", "tests/test_pulses.py::test_pulse_sequence_add", "tests/test_pulses.py::test_pulse_sequence__add__", "tests/test_pulses.py::test_pulse_sequence__mul__", "tests/test_pulses.py::test_pulse_sequence_add_readout", "tests/test_pulses.py::test_envelope_waveform_i_q", "tests/test_pulses.py::test_pulse_properties[100-0]", "tests/test_pulses.py::test_pulse_properties[100-10]", "tests/test_pulses.py::test_pulse_properties[100-start2]", "tests/test_pulses.py::test_pulse_properties[100-start3]", "tests/test_pulses.py::test_pulse_properties[500-0]", "tests/test_pulses.py::test_pulse_properties[500-10]", "tests/test_pulses.py::test_pulse_properties[500-start2]", "tests/test_pulses.py::test_pulse_properties[500-start3]", "tests/test_pulses.py::test_pulse_properties[duration2-0]", "tests/test_pulses.py::test_pulse_properties[duration2-10]", "tests/test_pulses.py::test_pulse_properties[duration2-start2]", "tests/test_pulses.py::test_pulse_properties[duration2-start3]", "tests/test_pulses.py::test_pulse_properties[duration3-0]", "tests/test_pulses.py::test_pulse_properties[duration3-10]", "tests/test_pulses.py::test_pulse_properties[duration3-start2]", "tests/test_pulses.py::test_pulse_properties[duration3-start3]", "tests/test_pulses.py::test_pulse_setter_errors" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-11-14 12:54:01+00:00
apache-2.0
5,143
quaquel__EMAworkbench-229
diff --git a/ema_workbench/em_framework/callbacks.py b/ema_workbench/em_framework/callbacks.py index 8e0ca9e..4f1ee72 100644 --- a/ema_workbench/em_framework/callbacks.py +++ b/ema_workbench/em_framework/callbacks.py @@ -232,7 +232,7 @@ class DefaultCallback(AbstractCallback): shape = outcome.shape if shape is not None: shape = (nr_experiments,) + shape - self.results[outcome.name] = self._setup_outcomes_array(shape, dtype=float) + self.results[outcome.name] = self._setup_outcomes_array(shape, dtype=outcome.dtype) def _store_case(self, experiment): scenario = experiment.scenario diff --git a/ema_workbench/em_framework/outcomes.py b/ema_workbench/em_framework/outcomes.py index 0b0f52b..f7e2707 100644 --- a/ema_workbench/em_framework/outcomes.py +++ b/ema_workbench/em_framework/outcomes.py @@ -104,6 +104,11 @@ class AbstractOutcome(Variable): expected min and max value for outcome, used by HyperVolume convergence metric shape : {tuple, None} optional + must be used in conjunction with dtype. Enables pre-allocation + of data structure for storing results. + dtype : datatype, optional + must be used in conjunction with shape. Enables pre-allocation + of data structure for storing results. Attributes ---------- @@ -112,6 +117,7 @@ class AbstractOutcome(Variable): variable_name : str function : callable shape : tuple + dtype : dataype """ @@ -122,7 +128,14 @@ class AbstractOutcome(Variable): INFO = 0 def __init__( - self, name, kind=INFO, variable_name=None, function=None, expected_range=None, shape=None + self, + name, + kind=INFO, + variable_name=None, + function=None, + expected_range=None, + shape=None, + dtype=None, ): super().__init__(name) @@ -135,6 +148,8 @@ class AbstractOutcome(Variable): raise ValueError("variable name must be a string or list of strings") if expected_range is not None and len(expected_range) != 2: raise ValueError("expected_range must be a min-max tuple") + if (shape is not None and dtype is None) or (dtype is not None and shape is None): + raise ValueError("if using shape or dtype, both need to be provided") register(self) @@ -151,6 +166,7 @@ class AbstractOutcome(Variable): self.function = function self._expected_range = expected_range self.shape = shape + self.dtype = dtype def process(self, values): if self.function: @@ -270,6 +286,8 @@ class ScalarOutcome(AbstractOutcome): expected_range : collection, optional expected min and max value for outcome, used by HyperVolume convergence metric + dtype : datatype, optional + Enables pre-allocation of data structure for storing results. Attributes ---------- @@ -279,6 +297,7 @@ class ScalarOutcome(AbstractOutcome): function : callable shape : tuple expected_range : tuple + dtype : datatype """ @@ -299,8 +318,14 @@ class ScalarOutcome(AbstractOutcome): variable_name=None, function=None, expected_range=None, + dtype=None, ): - super().__init__(name, kind, variable_name=variable_name, function=function) + shape = None + if dtype is not None: + shape = (1,) + super().__init__( + name, kind, variable_name=variable_name, function=function, dtype=dtype, shape=shape + ) self.expected_range = expected_range def process(self, values): @@ -360,7 +385,12 @@ class ArrayOutcome(AbstractOutcome): expected_range : 2 tuple, optional expected min and max value for outcome, used by HyperVolume convergence metric - shape : {tuple, None}, optional + shape : {tuple, None} optional + must be used in conjunction with dtype. Enables pre-allocation + of data structure for storing results. + dtype : datatype, optional + must be used in conjunction with shape. Enables pre-allocation + of data structure for storing results. Attributes ---------- @@ -370,17 +400,21 @@ class ArrayOutcome(AbstractOutcome): function : callable shape : tuple expected_range : tuple + dtype : datatype """ - def __init__(self, name, variable_name=None, function=None, expected_range=None, shape=None): + def __init__( + self, name, variable_name=None, function=None, expected_range=None, shape=None, dtype=None + ): super().__init__( name, variable_name=variable_name, function=function, expected_range=expected_range, shape=shape, + dtype=dtype, ) def process(self, values): @@ -450,7 +484,12 @@ class TimeSeriesOutcome(ArrayOutcome): expected_range : 2 tuple, optional expected min and max value for outcome, used by HyperVolume convergence metric - shape : {tuple, None}, optional + shape : {tuple, None} optional + must be used in conjunction with dtype. Enables pre-allocation + of data structure for storing results. + dtype : datatype, optional + must be used in conjunction with shape. Enables pre-allocation + of data structure for storing results. Attributes ---------- @@ -460,6 +499,7 @@ class TimeSeriesOutcome(ArrayOutcome): function : callable shape : tuple expected_range : tuple + dtype : datatype Notes ----- @@ -469,13 +509,16 @@ class TimeSeriesOutcome(ArrayOutcome): """ - def __init__(self, name, variable_name=None, function=None, expected_range=None, shape=None): + def __init__( + self, name, variable_name=None, function=None, expected_range=None, shape=None, dtype=None + ): super().__init__( name, variable_name=variable_name, function=function, expected_range=expected_range, shape=shape, + dtype=dtype, ) @classmethod
quaquel/EMAworkbench
c46821d5ec99e30f6d16dcdfefa20ca3dee174a5
diff --git a/test/test_em_framework/test_callback.py b/test/test_em_framework/test_callback.py index aa5ceaa..b0663a6 100644 --- a/test/test_em_framework/test_callback.py +++ b/test/test_em_framework/test_callback.py @@ -81,7 +81,7 @@ def test_init(): uncs = [RealParameter("a", 0, 1), RealParameter("b", 0, 1)] outcomes = [ ScalarOutcome("scalar"), - ArrayOutcome("array", shape=(10,)), + ArrayOutcome("array", shape=(10,), dtype=float), TimeSeriesOutcome("timeseries"), ] callback = DefaultCallback(uncs, [], outcomes, nr_experiments=100) diff --git a/test/test_em_framework/test_outcomes.py b/test/test_em_framework/test_outcomes.py index dc32baf..fc6b1b8 100644 --- a/test/test_em_framework/test_outcomes.py +++ b/test/test_em_framework/test_outcomes.py @@ -153,6 +153,14 @@ class TestTimeSeriesOutcome(TestScalarOutcome): outcome.process([1]) + with self.assertRaises(ValueError): + name = "f" + outcome = self.outcome_class(name, function=function, shape=(1,)) + + with self.assertRaises(ValueError): + name = "f" + outcome = self.outcome_class(name, function=function, dtype=float) + class CreateOutcomesTestCase(unittest.TestCase): def test_create_outcomes(self):
enable passing shape as keyword argument in outcomes Currently, the callback sets up the data structures for storing results after the first experiment because only then the exact required shapes are known. By passing the shape as an optional keyword argument (for array and time series outcomes), it becomes possible to pre-allocate these before the first experiment. This also allows catching memory errors before the first run is even conducted. The basic machinery for this is already in place in both AbstractOutcome and the DefaultCallback, the feature, however, was never fully completed. Thinking about this a bit more, I do believe you need to pass both shape and dtype in order to be able to setup the datastructure in advance.
0.0
c46821d5ec99e30f6d16dcdfefa20ca3dee174a5
[ "test/test_em_framework/test_callback.py::test_init", "test/test_em_framework/test_outcomes.py::TestTimeSeriesOutcome::test_process" ]
[ "test/test_em_framework/test_callback.py::test_store_results", "test/test_em_framework/test_callback.py::test_store_cases", "test/test_em_framework/test_callback.py::test_get_results", "test/test_em_framework/test_callback.py::test_filebasedcallback", "test/test_em_framework/test_outcomes.py::TestScalarOutcome::test_outcome", "test/test_em_framework/test_outcomes.py::TestScalarOutcome::test_process", "test/test_em_framework/test_outcomes.py::TestTimeSeriesOutcome::test_outcome", "test/test_em_framework/test_outcomes.py::CreateOutcomesTestCase::test_create_outcomes" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-03-07 07:23:07+00:00
bsd-3-clause
5,144
r1chardj0n3s__parse-132
diff --git a/.gitignore b/.gitignore index c909359..bde949c 100755 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +venv *.pyc *.pyo diff --git a/README.rst b/README.rst index e01aaaf..df881ea 100644 --- a/README.rst +++ b/README.rst @@ -132,7 +132,7 @@ format specification might have been used. Most of `format()`'s `Format Specification Mini-Language`_ is supported: - [[fill]align][0][width][.precision][type] + [[fill]align][sign][0][width][.precision][type] The differences between `parse()` and `format()` are: @@ -143,7 +143,8 @@ The differences between `parse()` and `format()` are: That is, the "#" format character is handled automatically by d, b, o and x formats. For "d" any will be accepted, but for the others the correct prefix must be present if at all. -- Numeric sign is handled automatically. +- Numeric sign is handled automatically. A sign specifier can be given, but + has no effect. - The thousands separator is handled automatically if the "n" type is used. - The types supported are a slightly different mix to the format() types. Some format() types come directly over: "d", "n", "%", "f", "e", "b", "o" and "x". diff --git a/parse.py b/parse.py index 062a421..e5db401 100644 --- a/parse.py +++ b/parse.py @@ -758,7 +758,7 @@ ALLOWED_TYPES = set(list('nbox%fFegwWdDsSl') + ['t' + c for c in 'ieahgcts']) def extract_format(format, extra_types): - """Pull apart the format [[fill]align][0][width][.precision][type]""" + """Pull apart the format [[fill]align][sign][0][width][.precision][type]""" fill = align = None if format[0] in '<>=^': align = format[0] @@ -768,6 +768,9 @@ def extract_format(format, extra_types): align = format[1] format = format[2:] + if format.startswith(('+', '-', ' ')): + format = format[1:] + zero = False if format and format[0] == '0': zero = True @@ -1261,11 +1264,11 @@ class Parser(object): # align "=" has been handled if align == '<': - s = '%s%s+' % (s, fill) + s = '%s%s*' % (s, fill) elif align == '>': s = '%s*%s' % (fill, s) elif align == '^': - s = '%s*%s%s+' % (fill, s, fill) + s = '%s*%s%s*' % (fill, s, fill) return s
r1chardj0n3s/parse
5bc22a4c6dd1ed0913c73a469a75f328cbd308df
diff --git a/test_parse.py b/test_parse.py index 1752a42..2392686 100755 --- a/test_parse.py +++ b/test_parse.py @@ -205,6 +205,17 @@ class TestParse(unittest.TestCase): r = parse.parse('hello {:w} {:w}', 'hello 12 people') self.assertEqual(r.fixed, ('12', 'people')) + def test_sign(self): + # sign is ignored + r = parse.parse('Pi = {:.7f}', 'Pi = 3.1415926') + self.assertEqual(r.fixed, (3.1415926,)) + r = parse.parse('Pi = {:+.7f}', 'Pi = 3.1415926') + self.assertEqual(r.fixed, (3.1415926,)) + r = parse.parse('Pi = {:-.7f}', 'Pi = 3.1415926') + self.assertEqual(r.fixed, (3.1415926,)) + r = parse.parse('Pi = {: .7f}', 'Pi = 3.1415926') + self.assertEqual(r.fixed, (3.1415926,)) + def test_precision(self): # pull a float out of a string r = parse.parse('Pi = {:.7f}', 'Pi = 3.1415926') @@ -865,17 +876,22 @@ class TestBugs(unittest.TestCase): # prior to the fix, this would raise an AttributeError pickle.dumps(p) - def test_search_centered_bug_112(self): - r = parse.parse("{:^},{:^}", " 12 , 34 ") - self.assertEqual(r[1], "34") - r = parse.search("{:^},{:^}", " 12 , 34 ") - self.assertEqual(r[1], "34") - - def test_search_left_align_bug_112(self): - r = parse.parse("{:<},{:<}", "12 ,34 ") - self.assertEqual(r[1], "34") - r = parse.search("{:<},{:<}", "12 ,34 ") - self.assertEqual(r[1], "34") + def test_unused_centered_alignment_bug(self): + r = parse.parse("{:^2S}", "foo") + self.assertEqual(r[0], "foo") + r = parse.search("{:^2S}", "foo") + self.assertEqual(r[0], "foo") + + # specifically test for the case in issue #118 as well + r = parse.parse("Column {:d}:{:^}", "Column 1: Timestep") + self.assertEqual(r[0], 1) + self.assertEqual(r[1], "Timestep") + + def test_unused_left_alignment_bug(self): + r = parse.parse("{:<2S}", "foo") + self.assertEqual(r[0], "foo") + r = parse.search("{:<2S}", "foo") + self.assertEqual(r[0], "foo") def test_match_trailing_newline(self): r = parse.parse('{}', 'test\n')
seach cut the result with {:^} from parse impor * str = ' 12 , 34 ' # Incorrect with search print(search('{:^},{:^}', a)) <Result ('12', '3') {}> # Correct with parse print(parse('{:^},{:^}', a)) <Result ('12', '34') {}>
0.0
5bc22a4c6dd1ed0913c73a469a75f328cbd308df
[ "test_parse.py::TestParse::test_sign", "test_parse.py::TestBugs::test_unused_centered_alignment_bug", "test_parse.py::TestBugs::test_unused_left_alignment_bug" ]
[ "test_parse.py::TestPattern::test_bird", "test_parse.py::TestPattern::test_braces", "test_parse.py::TestPattern::test_dict_style_fields", "test_parse.py::TestPattern::test_dot_separated_fields", "test_parse.py::TestPattern::test_dot_separated_fields_name_collisions", "test_parse.py::TestPattern::test_fixed", "test_parse.py::TestPattern::test_format_variety", "test_parse.py::TestPattern::test_invalid_groupnames_are_handled_gracefully", "test_parse.py::TestPattern::test_named", "test_parse.py::TestPattern::test_named_typed", "test_parse.py::TestPattern::test_numbered", "test_parse.py::TestResult::test_contains", "test_parse.py::TestResult::test_fixed_access", "test_parse.py::TestResult::test_named_access", "test_parse.py::TestResult::test_slice_access", "test_parse.py::TestParse::test_center", "test_parse.py::TestParse::test_custom_type", "test_parse.py::TestParse::test_datetime_group_count", "test_parse.py::TestParse::test_datetimes", "test_parse.py::TestParse::test_fixed", "test_parse.py::TestParse::test_hexadecimal", "test_parse.py::TestParse::test_left", "test_parse.py::TestParse::test_letters", "test_parse.py::TestParse::test_mixed", "test_parse.py::TestParse::test_mixed_type_variant", "test_parse.py::TestParse::test_mixed_types", "test_parse.py::TestParse::test_multiline", "test_parse.py::TestParse::test_named", "test_parse.py::TestParse::test_named_aligned_typed", "test_parse.py::TestParse::test_named_repeated", "test_parse.py::TestParse::test_named_repeated_fail_value", "test_parse.py::TestParse::test_named_repeated_type", "test_parse.py::TestParse::test_named_repeated_type_fail_value", "test_parse.py::TestParse::test_named_repeated_type_mismatch", "test_parse.py::TestParse::test_named_typed", "test_parse.py::TestParse::test_no_evaluate_result", "test_parse.py::TestParse::test_no_match", "test_parse.py::TestParse::test_nothing", "test_parse.py::TestParse::test_numbers", "test_parse.py::TestParse::test_pipe", "test_parse.py::TestParse::test_precision", "test_parse.py::TestParse::test_question_mark", "test_parse.py::TestParse::test_regular_expression", "test_parse.py::TestParse::test_right", "test_parse.py::TestParse::test_spans", "test_parse.py::TestParse::test_too_many_fields", "test_parse.py::TestParse::test_two_datetimes", "test_parse.py::TestParse::test_typed", "test_parse.py::TestParse::test_typed_fail", "test_parse.py::TestParse::test_unicode", "test_parse.py::TestSearch::test_basic", "test_parse.py::TestSearch::test_multiline", "test_parse.py::TestSearch::test_no_evaluate_result", "test_parse.py::TestSearch::test_pos", "test_parse.py::TestFindall::test_case_sensitivity", "test_parse.py::TestFindall::test_findall", "test_parse.py::TestFindall::test_no_evaluate_result", "test_parse.py::TestBugs::test_dotted_type_conversion_pull_8", "test_parse.py::TestBugs::test_match_trailing_newline", "test_parse.py::TestBugs::test_named_date_issue7", "test_parse.py::TestBugs::test_pickling_bug_110", "test_parse.py::TestBugs::test_pm_handling_issue57", "test_parse.py::TestBugs::test_pm_overflow_issue16", "test_parse.py::TestBugs::test_tz_compare_to_None", "test_parse.py::TestBugs::test_unmatched_brace_doesnt_match", "test_parse.py::TestBugs::test_user_type_with_group_count_issue60", "test_parse.py::TestParseType::test_case_sensitivity", "test_parse.py::TestParseType::test_decimal_value", "test_parse.py::TestParseType::test_int_convert_stateless_base", "test_parse.py::TestParseType::test_pattern_should_be_used", "test_parse.py::TestParseType::test_pattern_should_be_used2", "test_parse.py::TestParseType::test_width_constraints", "test_parse.py::TestParseType::test_width_empty_input", "test_parse.py::TestParseType::test_width_multi_int", "test_parse.py::TestParseType::test_width_str", "test_parse.py::TestParseType::test_with_pattern", "test_parse.py::TestParseType::test_with_pattern_and_regex_group_count", "test_parse.py::TestParseType::test_with_pattern_and_regex_group_count_is_none", "test_parse.py::TestParseType::test_with_pattern_and_wrong_regex_group_count_raises_error" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-01-28 15:47:38+00:00
mit
5,145
r1chardj0n3s__parse-74
diff --git a/LICENSE b/LICENSE index b4d8e28..6c73b16 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2012-2018 Richard Jones <[email protected]> +Copyright (c) 2012-2019 Richard Jones <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.rst b/README.rst index a16654c..5445556 100644 --- a/README.rst +++ b/README.rst @@ -132,8 +132,9 @@ The differences between `parse()` and `format()` are: ===== =========================================== ======== Type Characters Matched Output ===== =========================================== ======== -w Letters and underscore str -W Non-letter and underscore str +l Letters (ASCII) str +w Letters, numbers and underscore str +W Not letters, numbers and underscore str s Whitespace str S Non-whitespace str d Digits (effectively integer numbers) int @@ -342,6 +343,8 @@ the pattern, the actual match represents the shortest successful match for **Version history (in brief)**: +- 1.10.0 Introduce a "letters" matcher, since "w" matches numbers + also. - 1.9.1 Fix deprecation warnings around backslashes in regex strings (thanks Mickaël Schoentgen). Also fix some documentation formatting issues. @@ -403,5 +406,5 @@ the pattern, the actual match represents the shortest successful match for and removed the restriction on mixing fixed-position and named fields - 1.0.0 initial release -This code is copyright 2012-2017 Richard Jones <[email protected]> +This code is copyright 2012-2019 Richard Jones <[email protected]> See the end of the source file for the license of use. diff --git a/parse.py b/parse.py index 3aa4ca4..9da2528 100644 --- a/parse.py +++ b/parse.py @@ -133,8 +133,9 @@ The differences between `parse()` and `format()` are: ===== =========================================== ======== Type Characters Matched Output ===== =========================================== ======== -w Letters and underscore str -W Non-letter and underscore str +l Letters (ASCII) str +w Letters, numbers and underscore str +W Not letters, numbers and underscore str s Whitespace str S Non-whitespace str d Digits (effectively integer numbers) int @@ -343,6 +344,8 @@ the pattern, the actual match represents the shortest successful match for **Version history (in brief)**: +- 1.10.0 Introduce a "letters" matcher, since "w" matches numbers + also. - 1.9.1 Fix deprecation warnings around backslashes in regex strings (thanks Mickaël Schoentgen). Also fix some documentation formatting issues. @@ -404,12 +407,12 @@ the pattern, the actual match represents the shortest successful match for and removed the restriction on mixing fixed-position and named fields - 1.0.0 initial release -This code is copyright 2012-2017 Richard Jones <[email protected]> +This code is copyright 2012-2019 Richard Jones <[email protected]> See the end of the source file for the license of use. ''' from __future__ import absolute_import -__version__ = '1.9.1' +__version__ = '1.10.0' # yes, I now have two problems import re @@ -643,7 +646,7 @@ class RepeatedNameError(ValueError): REGEX_SAFETY = re.compile(r'([?\\\\.[\]()*+\^$!\|])') # allowed field types -ALLOWED_TYPES = set(list('nbox%fFegwWdDsS') + +ALLOWED_TYPES = set(list('nbox%fFegwWdDsSl') + ['t' + c for c in 'ieahgcts']) @@ -1059,7 +1062,8 @@ class Parser(object): self._type_conversions[group] = partial(date_convert, mm=n+1, dd=n+3, hms=n + 5) self._group_index += 5 - + elif type == 'l': + s = r'[A-Za-z]+' elif type: s = r'\%s+' % type elif format.get('precision'): @@ -1299,7 +1303,7 @@ def compile(format, extra_types=None, case_sensitive=False): return Parser(format, extra_types=extra_types) -# Copyright (c) 2012-2013 Richard Jones <[email protected]> +# Copyright (c) 2012-2019 Richard Jones <[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal diff --git a/setup.py b/setup.py index 6fc2090..60136cb 100755 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ setup( description = "parse() is the opposite of format()", long_description = __doc__, author = "Richard Jones", - author_email = "[email protected]", + author_email = "[email protected]", py_modules = ['parse'], url = 'https://github.com/r1chardj0n3s/parse', classifiers = [
r1chardj0n3s/parse
1eebd6808a4f774bdaffc93dbbbee4b2a236bcfa
diff --git a/test_parse.py b/test_parse.py index 8e09a39..f84c05e 100755 --- a/test_parse.py +++ b/test_parse.py @@ -663,6 +663,16 @@ class TestParse(unittest.TestCase): p = parse.compile('{:ti}' * 15) self.assertRaises(parse.TooManyFields, p.parse, '') + def test_letters(self): + res = parse.parse('{:l}', '') + self.assertIsNone(res) + res = parse.parse('{:l}', 'sPaM') + self.assertEqual(res.fixed, ('sPaM', )) + res = parse.parse('{:l}', 'sP4M') + self.assertIsNone(res) + res = parse.parse('{:l}', 'sP_M') + self.assertIsNone(res) + class TestSearch(unittest.TestCase): def test_basic(self): @@ -686,7 +696,6 @@ class TestSearch(unittest.TestCase): self.assertEqual(r.fixed, (42,)) - class TestFindall(unittest.TestCase): def test_findall(self): # basic findall() test
Parsing a continous string I was trying to parse continous string having letters and numbers by the easiest way: >>> parse('{:>w}{:g}{:w}{:g}{:w}', ' G3.80XA5.2M') <Result ('G', 3.8, 'XA', 5.2, 'M') {}> >>> parse('{:>w}{:g}{:w}{:g}{:w}', ' G3.80XA4.2M') <Result ('G', 3.8, 'XA', 4.2, 'M') {}> as far so good, but >>> parse('{:>w}{:g}{:w}{:g}{:w}', ' G3.80XA04.2M') <Result ('G', 3.8, 'XA0', 4.2, 'M') {}> >>> parse('{:>w}{:g}{:w}{:g}{:w}', ' G3.80XA44.2M') <Result ('G', 3.8, 'XA4', 4.2, 'M') {}> >>> parse('{:>w}{:g}{:w}{:g}{:w}', ' G3.80XA40M') <Result ('G', 3.8, 'XA4', 0.0, 'M') {}> changing input string a little bit I was getting bad results. I am missing something? Igor
0.0
1eebd6808a4f774bdaffc93dbbbee4b2a236bcfa
[ "test_parse.py::TestParse::test_letters" ]
[ "test_parse.py::TestPattern::test_beaker", "test_parse.py::TestPattern::test_bird", "test_parse.py::TestPattern::test_braces", "test_parse.py::TestPattern::test_center", "test_parse.py::TestPattern::test_dict_style_fields", "test_parse.py::TestPattern::test_dot_separated_fields", "test_parse.py::TestPattern::test_dot_separated_fields_name_collisions", "test_parse.py::TestPattern::test_fixed", "test_parse.py::TestPattern::test_format_variety", "test_parse.py::TestPattern::test_invalid_groupnames_are_handled_gracefully", "test_parse.py::TestPattern::test_left_fill", "test_parse.py::TestPattern::test_named", "test_parse.py::TestPattern::test_named_typed", "test_parse.py::TestResult::test_fixed_access", "test_parse.py::TestResult::test_named_access", "test_parse.py::TestParse::test_center", "test_parse.py::TestParse::test_custom_type", "test_parse.py::TestParse::test_datetime_group_count", "test_parse.py::TestParse::test_datetimes", "test_parse.py::TestParse::test_fixed", "test_parse.py::TestParse::test_hex_looks_like_binary_issue65", "test_parse.py::TestParse::test_hexadecimal", "test_parse.py::TestParse::test_left", "test_parse.py::TestParse::test_mixed", "test_parse.py::TestParse::test_mixed_type_variant", "test_parse.py::TestParse::test_mixed_types", "test_parse.py::TestParse::test_multiline", "test_parse.py::TestParse::test_named", "test_parse.py::TestParse::test_named_aligned_typed", "test_parse.py::TestParse::test_named_repeated", "test_parse.py::TestParse::test_named_repeated_fail_value", "test_parse.py::TestParse::test_named_repeated_type", "test_parse.py::TestParse::test_named_repeated_type_fail_value", "test_parse.py::TestParse::test_named_repeated_type_mismatch", "test_parse.py::TestParse::test_named_typed", "test_parse.py::TestParse::test_no_evaluate_result", "test_parse.py::TestParse::test_no_match", "test_parse.py::TestParse::test_nothing", "test_parse.py::TestParse::test_numbers", "test_parse.py::TestParse::test_pipe", "test_parse.py::TestParse::test_precision", "test_parse.py::TestParse::test_precision_fail", "test_parse.py::TestParse::test_question_mark", "test_parse.py::TestParse::test_regular_expression", "test_parse.py::TestParse::test_right", "test_parse.py::TestParse::test_spans", "test_parse.py::TestParse::test_too_many_fields", "test_parse.py::TestParse::test_two_datetimes", "test_parse.py::TestParse::test_typed", "test_parse.py::TestParse::test_typed_fail", "test_parse.py::TestParse::test_unicode", "test_parse.py::TestSearch::test_basic", "test_parse.py::TestSearch::test_multiline", "test_parse.py::TestSearch::test_no_evaluate_result", "test_parse.py::TestSearch::test_pos", "test_parse.py::TestFindall::test_findall", "test_parse.py::TestFindall::test_no_evaluate_result", "test_parse.py::TestBugs::test_dotted_type_conversion_pull_8", "test_parse.py::TestBugs::test_named_date_issue7", "test_parse.py::TestBugs::test_pm_handling_issue57", "test_parse.py::TestBugs::test_pm_overflow_issue16", "test_parse.py::TestBugs::test_user_type_with_group_count_issue60", "test_parse.py::TestParseType::test_case_sensitivity", "test_parse.py::TestParseType::test_decimal_value", "test_parse.py::TestParseType::test_pattern_should_be_used", "test_parse.py::TestParseType::test_pattern_should_be_used2", "test_parse.py::TestParseType::test_width_constraints", "test_parse.py::TestParseType::test_width_empty_input", "test_parse.py::TestParseType::test_width_multi_int", "test_parse.py::TestParseType::test_width_str", "test_parse.py::TestParseType::test_with_pattern", "test_parse.py::TestParseType::test_with_pattern_and_regex_group_count", "test_parse.py::TestParseType::test_with_pattern_and_regex_group_count_is_none", "test_parse.py::TestParseType::test_with_pattern_and_wrong_regex_group_count_raises_error" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-01-22 23:02:03+00:00
mit
5,146
r1chardj0n3s__parse-81
diff --git a/README.rst b/README.rst index 59f1018..3665905 100644 --- a/README.rst +++ b/README.rst @@ -345,6 +345,7 @@ the pattern, the actual match represents the shortest successful match for **Version history (in brief)**: +- 1.12.0 Do not assume closing brace when an opening one is found (thanks @mattsep) - 1.11.1 Revert having unicode char in docstring, it breaks Bamboo builds(?!) - 1.11.0 Implement `__contains__` for Result instances. - 1.10.0 Introduce a "letters" matcher, since "w" matches numbers diff --git a/parse.py b/parse.py index b5d543f..bff5f7f 100644 --- a/parse.py +++ b/parse.py @@ -345,6 +345,7 @@ the pattern, the actual match represents the shortest successful match for **Version history (in brief)**: +- 1.12.0 Do not assume closing brace when an opening one is found (thanks @mattsep) - 1.11.1 Revert having unicode char in docstring, it breaks Bamboo builds(?!) - 1.11.0 Implement `__contains__` for Result instances. - 1.10.0 Introduce a "letters" matcher, since "w" matches numbers @@ -415,7 +416,7 @@ See the end of the source file for the license of use. ''' from __future__ import absolute_import -__version__ = '1.11.1' +__version__ = '1.12.0' # yes, I now have two problems import re @@ -885,7 +886,7 @@ class Parser(object): e.append(r'\{') elif part == '}}': e.append(r'\}') - elif part[0] == '{': + elif part[0] == '{' and part[-1] == '}': # this will be a braces-delimited field to handle e.append(self._handle_field(part)) else:
r1chardj0n3s/parse
0d22c3e8ebee09f351938801137aeb6d15ae0ff8
diff --git a/test_parse.py b/test_parse.py index d48159a..7ebe378 100755 --- a/test_parse.py +++ b/test_parse.py @@ -771,6 +771,10 @@ class TestBugs(unittest.TestCase): self.assertEqual(r[0], 'ALICE') self.assertEqual(r[1], 42) + def test_unmatched_brace_doesnt_match(self): + r = parse.parse("{who.txt", "hello") + self.assertIsNone(r) + # ----------------------------------------------------------------------------- # TEST SUPPORT FOR: TestParseType @@ -793,7 +797,6 @@ class TestParseType(unittest.TestCase): result = parser.parse(text) self.assertEqual(result, None) - def test_pattern_should_be_used(self): def parse_number(text): return int(text)
Unmatched brace can still result in a match Certain patterns can still result in a match even when there are unmatched braces. For example: ``` >>> parse("{who.txt", "hello") <Result () {'who.tx': 'hello'}> ``` Even though there is no closing `}`, `parse` assumes the final character is the closing brace and matches the pattern accordingly. In this case, I'd expect `parse` to return `None` since there is no direct match.
0.0
0d22c3e8ebee09f351938801137aeb6d15ae0ff8
[ "test_parse.py::TestBugs::test_unmatched_brace_doesnt_match" ]
[ "test_parse.py::TestPattern::test_beaker", "test_parse.py::TestPattern::test_bird", "test_parse.py::TestPattern::test_braces", "test_parse.py::TestPattern::test_center", "test_parse.py::TestPattern::test_dict_style_fields", "test_parse.py::TestPattern::test_dot_separated_fields", "test_parse.py::TestPattern::test_dot_separated_fields_name_collisions", "test_parse.py::TestPattern::test_fixed", "test_parse.py::TestPattern::test_format_variety", "test_parse.py::TestPattern::test_invalid_groupnames_are_handled_gracefully", "test_parse.py::TestPattern::test_left_fill", "test_parse.py::TestPattern::test_named", "test_parse.py::TestPattern::test_named_typed", "test_parse.py::TestResult::test_contains", "test_parse.py::TestResult::test_fixed_access", "test_parse.py::TestResult::test_named_access", "test_parse.py::TestParse::test_center", "test_parse.py::TestParse::test_custom_type", "test_parse.py::TestParse::test_datetime_group_count", "test_parse.py::TestParse::test_datetimes", "test_parse.py::TestParse::test_fixed", "test_parse.py::TestParse::test_hex_looks_like_binary_issue65", "test_parse.py::TestParse::test_hexadecimal", "test_parse.py::TestParse::test_left", "test_parse.py::TestParse::test_letters", "test_parse.py::TestParse::test_mixed", "test_parse.py::TestParse::test_mixed_type_variant", "test_parse.py::TestParse::test_mixed_types", "test_parse.py::TestParse::test_multiline", "test_parse.py::TestParse::test_named", "test_parse.py::TestParse::test_named_aligned_typed", "test_parse.py::TestParse::test_named_repeated", "test_parse.py::TestParse::test_named_repeated_fail_value", "test_parse.py::TestParse::test_named_repeated_type", "test_parse.py::TestParse::test_named_repeated_type_fail_value", "test_parse.py::TestParse::test_named_repeated_type_mismatch", "test_parse.py::TestParse::test_named_typed", "test_parse.py::TestParse::test_no_evaluate_result", "test_parse.py::TestParse::test_no_match", "test_parse.py::TestParse::test_nothing", "test_parse.py::TestParse::test_numbers", "test_parse.py::TestParse::test_pipe", "test_parse.py::TestParse::test_precision", "test_parse.py::TestParse::test_precision_fail", "test_parse.py::TestParse::test_question_mark", "test_parse.py::TestParse::test_regular_expression", "test_parse.py::TestParse::test_right", "test_parse.py::TestParse::test_spans", "test_parse.py::TestParse::test_too_many_fields", "test_parse.py::TestParse::test_two_datetimes", "test_parse.py::TestParse::test_typed", "test_parse.py::TestParse::test_typed_fail", "test_parse.py::TestParse::test_unicode", "test_parse.py::TestSearch::test_basic", "test_parse.py::TestSearch::test_multiline", "test_parse.py::TestSearch::test_no_evaluate_result", "test_parse.py::TestSearch::test_pos", "test_parse.py::TestFindall::test_findall", "test_parse.py::TestFindall::test_no_evaluate_result", "test_parse.py::TestBugs::test_dotted_type_conversion_pull_8", "test_parse.py::TestBugs::test_named_date_issue7", "test_parse.py::TestBugs::test_pm_handling_issue57", "test_parse.py::TestBugs::test_pm_overflow_issue16", "test_parse.py::TestBugs::test_user_type_with_group_count_issue60", "test_parse.py::TestParseType::test_case_sensitivity", "test_parse.py::TestParseType::test_decimal_value", "test_parse.py::TestParseType::test_pattern_should_be_used", "test_parse.py::TestParseType::test_pattern_should_be_used2", "test_parse.py::TestParseType::test_width_constraints", "test_parse.py::TestParseType::test_width_empty_input", "test_parse.py::TestParseType::test_width_multi_int", "test_parse.py::TestParseType::test_width_str", "test_parse.py::TestParseType::test_with_pattern", "test_parse.py::TestParseType::test_with_pattern_and_regex_group_count", "test_parse.py::TestParseType::test_with_pattern_and_regex_group_count_is_none", "test_parse.py::TestParseType::test_with_pattern_and_wrong_regex_group_count_raises_error" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-04-07 01:10:41+00:00
mit
5,147
raamana__hiwenet-12
diff --git a/hiwenet/__init__.py b/hiwenet/__init__.py index 07c8a69..98bbb16 100644 --- a/hiwenet/__init__.py +++ b/hiwenet/__init__.py @@ -4,16 +4,19 @@ """ +__all__ = ['extract', 'pairwise_dist', 'run_cli', 'more_metrics'] + from sys import version_info if version_info.major==2 and version_info.minor==7: - from hiwenet import extract, run_cli + import more_metrics + from pairwise_dist import extract, run_cli elif version_info.major > 2: - from hiwenet.hiwenet import extract, run_cli + from hiwenet import more_metrics + from hiwenet.pairwise_dist import extract, run_cli else: - raise NotImplementedError('hiwenet supports only 2.7.13 or 3+. Upgrade to Python 3+ is recommended.') + raise NotImplementedError('hiwenet supports only 2.7 or 3+. Upgrade to Python 3+ is recommended.') -__all__ = ['extract', 'hiwenet', 'run_cli'] from ._version import get_versions __version__ = get_versions()['version'] del get_versions diff --git a/hiwenet/__main__.py b/hiwenet/__main__.py index a764b5b..01b6612 100644 --- a/hiwenet/__main__.py +++ b/hiwenet/__main__.py @@ -1,9 +1,9 @@ from sys import version_info if version_info.major==2 and version_info.minor==7: - from hiwenet import run_cli + from pairwise_dist import run_cli elif version_info.major > 2: - from hiwenet.hiwenet import run_cli + from hiwenet.pairwise_dist import run_cli else: raise NotImplementedError('hiwenet supports only 2.7.13 or 3+. Upgrade to Python 3+ is recommended.') diff --git a/hiwenet/more_metrics.py b/hiwenet/more_metrics.py new file mode 100644 index 0000000..4826d5d --- /dev/null +++ b/hiwenet/more_metrics.py @@ -0,0 +1,76 @@ +""" +Module implementing additional metrics for edge weights. + +""" + +__all__ = ['diff_medians', 'diff_medians_abs'] + +import numpy as np + +def check_array(array): + "Converts to flattened numpy arrays and ensures its not empty." + + if len(array) < 1: + raise ValueError('Input array is empty! Must have atleast 1 element.') + + return np.array(array).flatten() + + +def diff_medians(array_one, array_two): + """ + Computes the difference medians between two arrays of values. + + Given arrays will be flattened (to 1D array) regardless of dimension, + and any bon-finite/NaN values will be ignored. + + Parameters + ---------- + array_one, array_two : iterable + Two arrays of values, possibly of different length. + + Returns + ------- + diff_medians : float + scalar measuring the difference in medians, ignoring NaNs/non-finite values. + + Raises + ------ + ValueError + If one or more of the arrays are empty. + + """ + + array_one = check_array(array_one) + array_two = check_array(array_two) + diff_medians = np.median(array_one) - np.median(array_two) + + return diff_medians + + +def diff_medians_abs(array_one, array_two): + """ + Computes the absolute difference (symmetric) medians between two arrays of values. + + Given arrays will be flattened (to 1D array) regardless of dimension, + and any bon-finite/NaN values will be ignored. + + Parameters + ---------- + array_one, array_two : iterable + Two arrays of values, possibly of different length. + + Returns + ------- + diff_medians : float + scalar measuring the difference in medians, ignoring NaNs/non-finite values. + + Raises + ------ + ValueError + If one or more of the arrays are empty. + + """ + + abs_diff_medians = np.abs(diff_medians(array_one, array_two)) + + return abs_diff_medians \ No newline at end of file diff --git a/hiwenet/hiwenet.py b/hiwenet/pairwise_dist.py similarity index 96% rename from hiwenet/hiwenet.py rename to hiwenet/pairwise_dist.py index 39b2518..67aa786 100644 --- a/hiwenet/hiwenet.py +++ b/hiwenet/pairwise_dist.py @@ -10,6 +10,14 @@ import logging import networkx as nx import numpy as np from os.path import join as pjoin, exists as pexists +from sys import version_info + +if version_info.major==2 and version_info.minor==7: + import more_metrics +elif version_info.major > 2: + from hiwenet import more_metrics +else: + raise NotImplementedError('hiwenet supports only 2.7 or 3+. Upgrade to Python 3+ is recommended.') list_medpy_histogram_metrics = np.array([ 'chebyshev', 'chebyshev_neg', 'chi_square', @@ -37,7 +45,7 @@ semi_metric_list = [ 'noelle_1', 'noelle_3', 'correlate_1'] -metrics_on_original_features = ['diff_medians', ] +metrics_on_original_features = ['diff_medians', 'diff_medians_abs'] minimum_num_bins = 5 @@ -318,6 +326,8 @@ def extract(features, groups, print('All exceptions encountered so far:\n {}'.format('\n'.join(exceptions_list))) raise ValueError('Weights for atleast {:.2f}% of edges could not be computed.'.format(error_thresh * 100)) + sys.stdout.write('\n') + if return_networkx_graph: if out_weights_path is not None: graph.write_graphml(out_weights_path) @@ -492,16 +502,23 @@ def check_weight_method(weight_method_spec, raise TypeError('allow_non_symmetric flag must be boolean') if isinstance(weight_method_spec, str): + weight_method_spec = weight_method_spec.lower() + if weight_method_spec in list_medpy_histogram_metrics: from medpy.metric import histogram as medpy_hist_metrics weight_func = getattr(medpy_hist_metrics, weight_method_spec) + if use_orig_distr: + raise ValueError('use_original_distribution must be False when using builtin histogram metrics, ' + 'which expect histograms as input.') + + elif weight_method_spec in metrics_on_original_features: + weight_func = getattr(more_metrics, weight_method_spec) + if not use_orig_distr: + raise ValueError('use_original_distribution must be True when using builtin non-histogram metrics, ' + 'which expect original feature values in ROI/node as input.') else: raise NotImplementedError('Chosen histogram distance/metric not implemented or invalid.') - if use_orig_distr: - raise ValueError('use_original_distribution must be False when using builtin histogram metrics, ' - 'which expect histograms as input.') - elif callable(weight_method_spec): # ensure 1) takes two ndarrays try:
raamana/hiwenet
7cf61bb7d3531408ef9c77fd81e1d15122e1bfa3
diff --git a/hiwenet/test_hiwenet.py b/hiwenet/test_hiwenet.py index e1df71e..afa4ea6 100644 --- a/hiwenet/test_hiwenet.py +++ b/hiwenet/test_hiwenet.py @@ -9,8 +9,8 @@ from os.path import join as pjoin, exists as pexists, abspath from sys import version_info if version_info.major==2 and version_info.minor==7: - from hiwenet import extract as hiwenet - from hiwenet import run_cli as CLI + from pairwise_dist import extract as hiwenet + from pairwise_dist import run_cli as CLI elif version_info.major > 2: from hiwenet import extract as hiwenet from hiwenet import run_cli as CLI @@ -72,6 +72,25 @@ def test_dimensions(): assert len(ew) == num_groups assert ew.shape[0] == num_groups and ew.shape[1] == num_groups +def test_more_metrics(): + ew = hiwenet(features, groups, weight_method='diff_medians', + use_original_distribution=True) + assert len(ew) == num_groups + assert ew.shape[0] == num_groups and ew.shape[1] == num_groups + + ew_abs = hiwenet(features, groups, weight_method='diff_medians_abs', + use_original_distribution=True) + assert np.allclose(np.abs(ew), ew_abs, equal_nan=True) + + with raises(ValueError): + ew = hiwenet(features, groups, weight_method='diff_medians', + use_original_distribution=False) + + with raises(ValueError): + ew = hiwenet(features, groups, + weight_method='manhattan', + use_original_distribution=True) + def test_too_few_groups(): features, groups, group_ids, num_groups = make_features(100, 1) with raises(ValueError): @@ -256,6 +275,8 @@ def test_input_callable_on_orig_data(): use_original_distribution=True) # test_directed_nx() -test_directed_mat() +# test_directed_mat() # test_CLI_output_matches_API() -# test_input_callable() \ No newline at end of file +# test_input_callable() + +test_more_metrics() \ No newline at end of file
Broadening options for weight computation Using the new feature of arbitrary callable, implement more useful weights - [ ] such as difference in medians, - [ ] correlation, thresholding etc - [ ] other of interest
0.0
7cf61bb7d3531408ef9c77fd81e1d15122e1bfa3
[ "hiwenet/test_hiwenet.py::test_more_metrics", "hiwenet/test_hiwenet.py::test_too_few_groups", "hiwenet/test_hiwenet.py::test_too_few_values", "hiwenet/test_hiwenet.py::test_invalid_trim_perc", "hiwenet/test_hiwenet.py::test_invalid_weight_method", "hiwenet/test_hiwenet.py::test_trim_not_too_few_values", "hiwenet/test_hiwenet.py::test_trim_false_too_few_to_calc_range", "hiwenet/test_hiwenet.py::test_not_np_arrays", "hiwenet/test_hiwenet.py::test_CLI_nonexisting_paths", "hiwenet/test_hiwenet.py::test_CLI_invalid_args", "hiwenet/test_hiwenet.py::test_CLI_too_few_args", "hiwenet/test_hiwenet.py::test_input_callable_on_orig_data" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-11-12 04:44:48+00:00
mit
5,148
rabitt__pysox-28
diff --git a/setup.py b/setup.py index eee03d9..d0cd01c 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ if __name__ == "__main__": setup( name='sox', - version='1.2.1', + version='1.2.2', description='Python wrapper around SoX.', diff --git a/sox/core.py b/sox/core.py index 2b14d01..64a70cd 100644 --- a/sox/core.py +++ b/sox/core.py @@ -67,7 +67,6 @@ def sox(args): class SoxError(Exception): '''Exception to be raised when SoX exits with non-zero status. ''' - def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) diff --git a/sox/transform.py b/sox/transform.py index 438a3c3..f4eb248 100644 --- a/sox/transform.py +++ b/sox/transform.py @@ -395,6 +395,11 @@ class Transformer(object): file_info.validate_input_file(input_filepath) file_info.validate_output_file(output_filepath) + if input_filepath == output_filepath: + raise ValueError( + "input_filepath must be different from output_filepath." + ) + args = [] args.extend(self.globals) args.extend(self.input_format)
rabitt/pysox
bba620da31f76adbb4fa6cc524151b2518dc3079
diff --git a/tests/test_transform.py b/tests/test_transform.py index aa357d1..056676c 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -386,6 +386,10 @@ class TestTransformerBuild(unittest.TestCase): with self.assertRaises(IOError): self.tfm.build('blah/asdf.wav', OUTPUT_FILE) + def test_input_output_equal(self): + with self.assertRaises(ValueError): + self.tfm.build(INPUT_FILE, INPUT_FILE) + def test_failed_sox(self): self.tfm.effects = ['channels', '-1'] with self.assertRaises(SoxError):
Support using same file path for input & output Sox doesn't support using the same file as both input and output - doing this will result in an empty, invalid audio file. While this is sox behavior and not pysox, it would be nice if pysox took care of this behind the scenes. Right now the user needs to worry about this logic themselves, e.g. like this: ```python import tempfile import shutil from scaper.util import _close_temp_files audio_infile = '/Users/justin/Downloads/trimtest.wav' audio_outfile = '/Users/justin/Downloads/trimtest.wav' start_time = 2 end_time = 3 tfm = sox.Transformer() tfm.trim(start_time, end_time) if audio_outfile != audio_infile: tfm.build(audio_infile, audio_outfile) else: # must use temp file in order to save to same file tmpfiles = [] with _close_temp_files(tmpfiles): # Create tmp file tmpfiles.append( tempfile.NamedTemporaryFile( suffix='.wav', delete=True)) # Save trimmed result to temp file tfm.build(audio_infile, tmpfiles[-1].name) # Copy result back to original file shutil.copyfile(tmpfiles[-1].name, audio_outfile) ``` Pysox *does* issue a warning when a file is about to be overwritten, which is even more confusing under this scenario since the user (who might be unfamiliar with the quirks of sox) has no reason to think that the overwritten file will be invalid.
0.0
bba620da31f76adbb4fa6cc524151b2518dc3079
[ "tests/test_transform.py::TestTransformerBuild::test_input_output_equal" ]
[ "tests/test_transform.py::TestTransformDefault::test_effects", "tests/test_transform.py::TestTransformDefault::test_effects_log", "tests/test_transform.py::TestTransformDefault::test_globals", "tests/test_transform.py::TestTransformDefault::test_input_format", "tests/test_transform.py::TestTransformDefault::test_output_format", "tests/test_transform.py::TestTransformSetGlobals::test_dither_invalid", "tests/test_transform.py::TestTransformSetGlobals::test_guard_invalid", "tests/test_transform.py::TestTransformSetGlobals::test_multithread_invalid", "tests/test_transform.py::TestTransformSetGlobals::test_replay_gain_invalid", "tests/test_transform.py::TestTransformSetGlobals::test_verbosity_invalid", "tests/test_transform.py::TestTransformSetInputFormat::test_bits_invalid", "tests/test_transform.py::TestTransformSetInputFormat::test_bits_invalid2", "tests/test_transform.py::TestTransformSetInputFormat::test_channels_invalid", "tests/test_transform.py::TestTransformSetInputFormat::test_channels_invalid2", "tests/test_transform.py::TestTransformSetInputFormat::test_encoding_invalid", "tests/test_transform.py::TestTransformSetInputFormat::test_file_type_invalid", "tests/test_transform.py::TestTransformSetInputFormat::test_ignore_length_invalid", "tests/test_transform.py::TestTransformSetInputFormat::test_rate_invalid", "tests/test_transform.py::TestTransformSetInputFormat::test_rate_invalid2", "tests/test_transform.py::TestTransformSetOutputFormat::test_append_comments_invalid", "tests/test_transform.py::TestTransformSetOutputFormat::test_bits_invalid", "tests/test_transform.py::TestTransformSetOutputFormat::test_bits_invalid2", "tests/test_transform.py::TestTransformSetOutputFormat::test_channels_invalid", "tests/test_transform.py::TestTransformSetOutputFormat::test_channels_invalid2", "tests/test_transform.py::TestTransformSetOutputFormat::test_comments_invalid", "tests/test_transform.py::TestTransformSetOutputFormat::test_encoding_invalid", "tests/test_transform.py::TestTransformSetOutputFormat::test_file_type_invalid", "tests/test_transform.py::TestTransformSetOutputFormat::test_rate_invalid", "tests/test_transform.py::TestTransformSetOutputFormat::test_rate_invalid2", "tests/test_transform.py::TestTransformerBuild::test_failed_sox", "tests/test_transform.py::TestTransformerBuild::test_invalid", "tests/test_transform.py::TestTransformerPreview::test_valid", "tests/test_transform.py::TestTransformerAllpass::test_frequency_invalid", "tests/test_transform.py::TestTransformerAllpass::test_width_q_invalid", "tests/test_transform.py::TestTransformerBandpass::test_constant_skirt_invalid", "tests/test_transform.py::TestTransformerBandpass::test_frequency_invalid", "tests/test_transform.py::TestTransformerBandpass::test_width_q_invalid", "tests/test_transform.py::TestTransformerBandreject::test_frequency_invalid", "tests/test_transform.py::TestTransformerBandreject::test_width_q_invalid", "tests/test_transform.py::TestTransformerBass::test_frequency_invalid", "tests/test_transform.py::TestTransformerBass::test_gain_db_invalid", "tests/test_transform.py::TestTransformerBass::test_slope_invalid", "tests/test_transform.py::TestTransformerBend::test_cents_invalid_len", "tests/test_transform.py::TestTransformerBend::test_cents_invalid_nonlist", "tests/test_transform.py::TestTransformerBend::test_cents_invalid_vals", "tests/test_transform.py::TestTransformerBend::test_end_times_invalid_len", "tests/test_transform.py::TestTransformerBend::test_end_times_invalid_nonlist", "tests/test_transform.py::TestTransformerBend::test_end_times_invalid_order", "tests/test_transform.py::TestTransformerBend::test_end_times_invalid_vals", "tests/test_transform.py::TestTransformerBend::test_frame_rate_invalid", "tests/test_transform.py::TestTransformerBend::test_n_bends_invalid", "tests/test_transform.py::TestTransformerBend::test_overlapping_intervals", "tests/test_transform.py::TestTransformerBend::test_oversample_rate_invalid", "tests/test_transform.py::TestTransformerBend::test_start_greater_end", "tests/test_transform.py::TestTransformerBend::test_start_times_invalid_len", "tests/test_transform.py::TestTransformerBend::test_start_times_invalid_nonlist", "tests/test_transform.py::TestTransformerBend::test_start_times_invalid_order", "tests/test_transform.py::TestTransformerBend::test_start_times_invalid_vals", "tests/test_transform.py::TestTransformerBiquad::test_a_non_num", "tests/test_transform.py::TestTransformerBiquad::test_a_nonlist", "tests/test_transform.py::TestTransformerBiquad::test_a_wrong_len", "tests/test_transform.py::TestTransformerBiquad::test_b_non_num", "tests/test_transform.py::TestTransformerBiquad::test_b_nonlist", "tests/test_transform.py::TestTransformerBiquad::test_b_wrong_len", "tests/test_transform.py::TestTransformerChannels::test_invalid_nchannels", "tests/test_transform.py::TestTransformerChorus::test_invalid_decays", "tests/test_transform.py::TestTransformerChorus::test_invalid_decays_vals", "tests/test_transform.py::TestTransformerChorus::test_invalid_decays_wronglen", "tests/test_transform.py::TestTransformerChorus::test_invalid_delays", "tests/test_transform.py::TestTransformerChorus::test_invalid_delays_vals", "tests/test_transform.py::TestTransformerChorus::test_invalid_delays_wronglen", "tests/test_transform.py::TestTransformerChorus::test_invalid_depths", "tests/test_transform.py::TestTransformerChorus::test_invalid_depths_vals", "tests/test_transform.py::TestTransformerChorus::test_invalid_depths_wronglen", "tests/test_transform.py::TestTransformerChorus::test_invalid_gain_in", "tests/test_transform.py::TestTransformerChorus::test_invalid_gain_out", "tests/test_transform.py::TestTransformerChorus::test_invalid_n_voices", "tests/test_transform.py::TestTransformerChorus::test_invalid_shapes", "tests/test_transform.py::TestTransformerChorus::test_invalid_shapes_vals", "tests/test_transform.py::TestTransformerChorus::test_invalid_shapes_wronglen", "tests/test_transform.py::TestTransformerChorus::test_invalid_speeds", "tests/test_transform.py::TestTransformerChorus::test_invalid_speeds_vals", "tests/test_transform.py::TestTransformerChorus::test_invalid_speeds_wronglen", "tests/test_transform.py::TestTransformerContrast::test_invalid_amount_big", "tests/test_transform.py::TestTransformerContrast::test_invalid_amount_neg", "tests/test_transform.py::TestTransformerContrast::test_invalid_amount_nonnum", "tests/test_transform.py::TestTransformerCompand::test_attack_time_invalid_neg", "tests/test_transform.py::TestTransformerCompand::test_attack_time_invalid_nonnum", "tests/test_transform.py::TestTransformerCompand::test_decay_time_invalid_neg", "tests/test_transform.py::TestTransformerCompand::test_decay_time_invalid_nonnum", "tests/test_transform.py::TestTransformerCompand::test_soft_knee_invalid", "tests/test_transform.py::TestTransformerCompand::test_tf_points_empty", "tests/test_transform.py::TestTransformerCompand::test_tf_points_nonlist", "tests/test_transform.py::TestTransformerCompand::test_tf_points_nontuples", "tests/test_transform.py::TestTransformerCompand::test_tf_points_tup_dups", "tests/test_transform.py::TestTransformerCompand::test_tf_points_tup_len", "tests/test_transform.py::TestTransformerCompand::test_tf_points_tup_nonnum", "tests/test_transform.py::TestTransformerCompand::test_tf_points_tup_nonnum2", "tests/test_transform.py::TestTransformerCompand::test_tf_points_tup_positive", "tests/test_transform.py::TestTransformerConvert::test_bitdepth_invalid", "tests/test_transform.py::TestTransformerConvert::test_channels_invalid1", "tests/test_transform.py::TestTransformerConvert::test_channels_invalid2", "tests/test_transform.py::TestTransformerConvert::test_samplerate_invalid", "tests/test_transform.py::TestTransformerDcshift::test_invalid_shift_big", "tests/test_transform.py::TestTransformerDcshift::test_invalid_shift_neg", "tests/test_transform.py::TestTransformerDcshift::test_invalid_shift_nonnum", "tests/test_transform.py::TestTransformerDelay::test_invalid_position_type", "tests/test_transform.py::TestTransformerDelay::test_invalid_position_vals", "tests/test_transform.py::TestTransformerDownsample::test_default", "tests/test_transform.py::TestTransformerDownsample::test_invalid_factor_neg", "tests/test_transform.py::TestTransformerDownsample::test_invalid_factor_nonnum", "tests/test_transform.py::TestTransformerEcho::test_decays_invalid_len", "tests/test_transform.py::TestTransformerEcho::test_decays_invalid_type", "tests/test_transform.py::TestTransformerEcho::test_decays_invalid_vals", "tests/test_transform.py::TestTransformerEcho::test_delays_invalid_len", "tests/test_transform.py::TestTransformerEcho::test_delays_invalid_type", "tests/test_transform.py::TestTransformerEcho::test_delays_invalid_vals", "tests/test_transform.py::TestTransformerEcho::test_gain_in_invalid", "tests/test_transform.py::TestTransformerEcho::test_gain_out_invalid", "tests/test_transform.py::TestTransformerEcho::test_n_echos_invalid", "tests/test_transform.py::TestTransformerEchos::test_decays_invalid_len", "tests/test_transform.py::TestTransformerEchos::test_decays_invalid_type", "tests/test_transform.py::TestTransformerEchos::test_decays_invalid_vals", "tests/test_transform.py::TestTransformerEchos::test_delays_invalid_len", "tests/test_transform.py::TestTransformerEchos::test_delays_invalid_type", "tests/test_transform.py::TestTransformerEchos::test_delays_invalid_vals", "tests/test_transform.py::TestTransformerEchos::test_gain_in_invalid", "tests/test_transform.py::TestTransformerEchos::test_gain_out_invalid", "tests/test_transform.py::TestTransformerEchos::test_n_echos_invalid", "tests/test_transform.py::TestTransformerEqualizer::test_frequency_invalid", "tests/test_transform.py::TestTransformerEqualizer::test_gain_db_invalid", "tests/test_transform.py::TestTransformerEqualizer::test_width_q_invalid", "tests/test_transform.py::TestTransformerFade::test_fade_in_invalid", "tests/test_transform.py::TestTransformerFade::test_fade_out_invalid", "tests/test_transform.py::TestTransformerFade::test_fade_shape_invalid", "tests/test_transform.py::TestTransformerFir::test_invalid_coeffs_nonlist", "tests/test_transform.py::TestTransformerFir::test_invalid_coeffs_vals", "tests/test_transform.py::TestTransformerFlanger::test_flanger_delay_invalid", "tests/test_transform.py::TestTransformerFlanger::test_flanger_depth_invalid", "tests/test_transform.py::TestTransformerFlanger::test_flanger_interp_invalid", "tests/test_transform.py::TestTransformerFlanger::test_flanger_phase_invalid", "tests/test_transform.py::TestTransformerFlanger::test_flanger_regen_invalid", "tests/test_transform.py::TestTransformerFlanger::test_flanger_shape_invalid", "tests/test_transform.py::TestTransformerFlanger::test_flanger_speed_invalid", "tests/test_transform.py::TestTransformerFlanger::test_flanger_width_invalid", "tests/test_transform.py::TestTransformerGain::test_balance_invalid", "tests/test_transform.py::TestTransformerGain::test_gain_db_invalid", "tests/test_transform.py::TestTransformerGain::test_limiter_invalid", "tests/test_transform.py::TestTransformerGain::test_normalize_invalid", "tests/test_transform.py::TestTransformerHighpass::test_frequency_invalid", "tests/test_transform.py::TestTransformerHighpass::test_n_poles_invalid", "tests/test_transform.py::TestTransformerHighpass::test_width_q_invalid", "tests/test_transform.py::TestTransformerHilbert::test_default", "tests/test_transform.py::TestTransformerHilbert::test_num_taps_invalid", "tests/test_transform.py::TestTransformerHilbert::test_num_taps_invalid_even", "tests/test_transform.py::TestTransformerHilbert::test_num_taps_valid", "tests/test_transform.py::TestTransformerLowpass::test_frequency_invalid", "tests/test_transform.py::TestTransformerLowpass::test_n_poles_invalid", "tests/test_transform.py::TestTransformerLowpass::test_width_q_invalid", "tests/test_transform.py::TestTransformerLoudness::test_gain_db_invalid", "tests/test_transform.py::TestTransformerLoudness::test_reference_level_invalid", "tests/test_transform.py::TestTransformerLoudness::test_reference_level_oorange", "tests/test_transform.py::TestTransformerMcompand::test_attack_time_invalid_len", "tests/test_transform.py::TestTransformerMcompand::test_attack_time_invalid_neg", "tests/test_transform.py::TestTransformerMcompand::test_attack_time_invalid_nonnum", "tests/test_transform.py::TestTransformerMcompand::test_attack_time_invalid_type", "tests/test_transform.py::TestTransformerMcompand::test_crossover_frequencies_invalid", "tests/test_transform.py::TestTransformerMcompand::test_crossover_frequencies_invalid_vals", "tests/test_transform.py::TestTransformerMcompand::test_decay_time_invalid_len", "tests/test_transform.py::TestTransformerMcompand::test_decay_time_invalid_neg", "tests/test_transform.py::TestTransformerMcompand::test_decay_time_invalid_nonnum", "tests/test_transform.py::TestTransformerMcompand::test_decay_time_invalid_type", "tests/test_transform.py::TestTransformerMcompand::test_n_bands_invalid", "tests/test_transform.py::TestTransformerMcompand::test_soft_knee_db_invalid_len", "tests/test_transform.py::TestTransformerMcompand::test_soft_knee_db_invalid_type", "tests/test_transform.py::TestTransformerMcompand::test_soft_knee_invalid", "tests/test_transform.py::TestTransformerMcompand::test_tf_points_elt_empty", "tests/test_transform.py::TestTransformerMcompand::test_tf_points_elt_nonlist", "tests/test_transform.py::TestTransformerMcompand::test_tf_points_elt_nontuples", "tests/test_transform.py::TestTransformerMcompand::test_tf_points_elt_tup_len", "tests/test_transform.py::TestTransformerMcompand::test_tf_points_elt_tup_nonnum", "tests/test_transform.py::TestTransformerMcompand::test_tf_points_tup_dups", "tests/test_transform.py::TestTransformerMcompand::test_tf_points_tup_nonnum2", "tests/test_transform.py::TestTransformerMcompand::test_tf_points_tup_positive", "tests/test_transform.py::TestTransformerMcompand::test_tf_points_wrong_len", "tests/test_transform.py::TestTransformerNorm::test_db_level_invalid", "tests/test_transform.py::TestTransformerOverdrive::test_colour_invalid", "tests/test_transform.py::TestTransformerOverdrive::test_gain_db_invalid", "tests/test_transform.py::TestTransformerPad::test_end_duration_invalid", "tests/test_transform.py::TestTransformerPad::test_start_duration_invalid", "tests/test_transform.py::TestTransformerPhaser::test_decay_invalid", "tests/test_transform.py::TestTransformerPhaser::test_delay_invalid", "tests/test_transform.py::TestTransformerPhaser::test_gain_in_invalid", "tests/test_transform.py::TestTransformerPhaser::test_gain_out_invalid", "tests/test_transform.py::TestTransformerPhaser::test_modulation_shape_invalid", "tests/test_transform.py::TestTransformerPhaser::test_speed_invalid", "tests/test_transform.py::TestTransformerPitch::test_n_semitones_invalid", "tests/test_transform.py::TestTransformerPitch::test_quick_invalid", "tests/test_transform.py::TestTransformerRate::test_quality_invalid", "tests/test_transform.py::TestTransformerRate::test_samplerate_invalid", "tests/test_transform.py::TestTransformerRepeat::test_count_invalid", "tests/test_transform.py::TestTransformerRepeat::test_count_invalid_fmt", "tests/test_transform.py::TestTransformerReverb::test_high_freq_damping_invalid", "tests/test_transform.py::TestTransformerReverb::test_pre_delay_invalid", "tests/test_transform.py::TestTransformerReverb::test_reverberance_invalid", "tests/test_transform.py::TestTransformerReverb::test_room_scale_invalid", "tests/test_transform.py::TestTransformerReverb::test_stereo_depth_invalid", "tests/test_transform.py::TestTransformerReverb::test_wet_gain_invalid", "tests/test_transform.py::TestTransformerReverb::test_wet_only_invalid", "tests/test_transform.py::TestTransformerSilence::test_buffer_around_silence_invalid", "tests/test_transform.py::TestTransformerSilence::test_location_invalid", "tests/test_transform.py::TestTransformerSilence::test_min_silence_duration_invalid", "tests/test_transform.py::TestTransformerSilence::test_silence_threshold_invalid", "tests/test_transform.py::TestTransformerSilence::test_silence_threshold_invalid2", "tests/test_transform.py::TestTransformerSinc::test_cutoff_freq_invalid", "tests/test_transform.py::TestTransformerSinc::test_cutoff_freq_invalid_high", "tests/test_transform.py::TestTransformerSinc::test_cutoff_freq_invalid_list", "tests/test_transform.py::TestTransformerSinc::test_cutoff_freq_invalid_list_len", "tests/test_transform.py::TestTransformerSinc::test_cutoff_freq_invalid_number", "tests/test_transform.py::TestTransformerSinc::test_cutoff_freq_invalid_reject", "tests/test_transform.py::TestTransformerSinc::test_filter_type_invalid", "tests/test_transform.py::TestTransformerSinc::test_phase_response_invalid", "tests/test_transform.py::TestTransformerSinc::test_phase_response_invalid_large", "tests/test_transform.py::TestTransformerSinc::test_phase_response_invalid_small", "tests/test_transform.py::TestTransformerSinc::test_stop_band_attenuation_invalid", "tests/test_transform.py::TestTransformerSinc::test_transition_bw_invalid", "tests/test_transform.py::TestTransformerSinc::test_transition_bw_invalid_float", "tests/test_transform.py::TestTransformerSinc::test_transition_bw_invalid_list_elt", "tests/test_transform.py::TestTransformerSinc::test_transition_bw_invalid_low", "tests/test_transform.py::TestTransformerSinc::test_transition_bw_linvalid_list_len", "tests/test_transform.py::TestTransformerSpeed::test_factor_invalid", "tests/test_transform.py::TestTransformerStretch::test_factor_invalid", "tests/test_transform.py::TestTransformerStretch::test_window_invalid", "tests/test_transform.py::TestTransformerTempo::test_audio_type_invalid", "tests/test_transform.py::TestTransformerTempo::test_factor_invalid", "tests/test_transform.py::TestTransformerTempo::test_quick_invalid", "tests/test_transform.py::TestTransformerTreble::test_frequency_invalid", "tests/test_transform.py::TestTransformerTreble::test_gain_db_invalid", "tests/test_transform.py::TestTransformerTreble::test_slope_invalid", "tests/test_transform.py::TestTransformerTremolo::test_depth_invalid", "tests/test_transform.py::TestTransformerTremolo::test_speed_invalid", "tests/test_transform.py::TestTransformerTrim::test_invalid_end_time", "tests/test_transform.py::TestTransformerTrim::test_invalid_start_time", "tests/test_transform.py::TestTransformerTrim::test_invalid_time_pair", "tests/test_transform.py::TestTransformerUpsample::test_default", "tests/test_transform.py::TestTransformerUpsample::test_invalid_factor_decimal", "tests/test_transform.py::TestTransformerUpsample::test_invalid_factor_neg", "tests/test_transform.py::TestTransformerUpsample::test_invalid_factor_nonnum", "tests/test_transform.py::TestTransformerVad::test_invalid_activity_threshold", "tests/test_transform.py::TestTransformerVad::test_invalid_initial_pad", "tests/test_transform.py::TestTransformerVad::test_invalid_initial_search_buffer", "tests/test_transform.py::TestTransformerVad::test_invalid_location", "tests/test_transform.py::TestTransformerVad::test_invalid_max_gap", "tests/test_transform.py::TestTransformerVad::test_invalid_min_activity_duration", "tests/test_transform.py::TestTransformerVad::test_invalid_normalize" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2016-10-27 22:35:19+00:00
bsd-3-clause
5,149
rabitt__pysox-55
diff --git a/docs/changes.rst b/docs/changes.rst index 920d6fc..34e354e 100644 --- a/docs/changes.rst +++ b/docs/changes.rst @@ -8,4 +8,19 @@ v0.1 v1.1.8 ~~~~~~ -- Move specification of input/output file arguments from __init__ to .build() \ No newline at end of file +- Move specification of input/output file arguments from __init__ to .build() + +v1.3.0 +~~~~~~ +- patched core sox call to work on Windows +- added remix +- added gain to mcompand +- fixed scientific notation format bug +- allow null output filepaths in `build` +- added ability to capture `build` outputs to stdout and stderr +- added `power_spectrum` +- added `stat` +- added `clear` method +- added `noiseprof` and `noisered` effects +- added `vol` effect +- fixed `Combiner.preview()` \ No newline at end of file diff --git a/sox/combine.py b/sox/combine.py index 1a50272..2103bb7 100644 --- a/sox/combine.py +++ b/sox/combine.py @@ -15,6 +15,7 @@ from .core import ENCODING_VALS from .core import enquote_filepath from .core import is_number from .core import sox +from .core import play from .core import SoxError from .core import SoxiError from .core import VALID_FORMATS @@ -110,6 +111,45 @@ class Combiner(Transformer): logging.info("[SoX] {}".format(out)) return True + def preview(self, input_filepath_list, combine_type, input_volumes=None): + '''Play a preview of the output with the current set of effects + + Parameters + ---------- + input_filepath_list : list of str + List of paths to input audio files. + combine_type : str + Input file combining method. One of the following values: + * concatenate : combine input files by concatenating in the + order given. + * merge : combine input files by stacking each input file into + a new channel of the output file. + * mix : combine input files by summing samples in corresponding + channels. + * mix-power : combine input files with volume adjustments such + that the output volume is roughly equivlent to one of the + input signals. + * multiply : combine input files by multiplying samples in + corresponding samples. + input_volumes : list of float, default=None + List of volumes to be applied upon combining input files. Volumes + are applied to the input files in order. + If None, input files will be combined at their original volumes. + + ''' + args = ["play", "--no-show-progress"] + args.extend(self.globals) + args.extend(['--combine', combine_type]) + + input_format_list = _build_input_format_list( + input_filepath_list, input_volumes, self.input_format + ) + input_args = _build_input_args(input_filepath_list, input_format_list) + args.extend(input_args) + args.extend(self.effects) + + play(args) + def set_input_format(self, file_type=None, rate=None, bits=None, channels=None, encoding=None, ignore_length=None): '''Sets input file format arguments. This is primarily useful when diff --git a/sox/transform.py b/sox/transform.py index 74be29a..09e943e 100644 --- a/sox/transform.py +++ b/sox/transform.py @@ -458,6 +458,12 @@ class Transformer(object): def preview(self, input_filepath): '''Play a preview of the output with the current set of effects + + Parameters + ---------- + input_filepath : str + Path to input audio file. + ''' args = ["play", "--no-show-progress"] args.extend(self.globals) diff --git a/sox/version.py b/sox/version.py index 6d16084..83db3e9 100644 --- a/sox/version.py +++ b/sox/version.py @@ -2,5 +2,5 @@ # -*- coding: utf-8 -*- """Version info""" -short_version = '1.2' -version = '1.2.9' +short_version = '1.3' +version = '1.3.0'
rabitt/pysox
6347273c53907075fa0d2ed5891ac9364d7a2b0e
diff --git a/tests/test_combine.py b/tests/test_combine.py index 36985bf..c0fdea6 100644 --- a/tests/test_combine.py +++ b/tests/test_combine.py @@ -379,6 +379,22 @@ class TestBuildInputFormatList(unittest.TestCase): self.assertEqual(expected, actual) +class TestCombinePreview(unittest.TestCase): + def setUp(self): + self.cbn = new_combiner() + self.cbn.trim(0, 0.1) + + def test_valid(self): + expected = None + actual = self.cbn.preview([INPUT_WAV, INPUT_WAV], 'mix') + self.assertEqual(expected, actual) + + def test_valid_vol(self): + expected = None + actual = self.cbn.preview([INPUT_WAV, INPUT_WAV], 'mix', [1.0, 0.5]) + self.assertEqual(expected, actual) + + class TestBuildInputArgs(unittest.TestCase): def test_unequal_length(self):
Combiner.preview() fails `Combiner` inherits `preview` from `Transformer` but it needs to be overwritten because the base call is different for multiple inputs.
0.0
6347273c53907075fa0d2ed5891ac9364d7a2b0e
[ "tests/test_combine.py::TestCombinePreview::test_valid", "tests/test_combine.py::TestCombinePreview::test_valid_vol" ]
[ "tests/test_combine.py::TestCombineDefault::test_effects", "tests/test_combine.py::TestCombineDefault::test_effects_log", "tests/test_combine.py::TestCombineDefault::test_failed_build", "tests/test_combine.py::TestCombineDefault::test_globals", "tests/test_combine.py::TestCombineDefault::test_output_format", "tests/test_combine.py::TestSetInputFormat::test_bits", "tests/test_combine.py::TestSetInputFormat::test_channels", "tests/test_combine.py::TestSetInputFormat::test_encoding", "tests/test_combine.py::TestSetInputFormat::test_ignore_length", "tests/test_combine.py::TestSetInputFormat::test_invalid_bits", "tests/test_combine.py::TestSetInputFormat::test_invalid_bits_val", "tests/test_combine.py::TestSetInputFormat::test_invalid_channels", "tests/test_combine.py::TestSetInputFormat::test_invalid_channels_val", "tests/test_combine.py::TestSetInputFormat::test_invalid_encoding", "tests/test_combine.py::TestSetInputFormat::test_invalid_encoding_val", "tests/test_combine.py::TestSetInputFormat::test_invalid_file_type", "tests/test_combine.py::TestSetInputFormat::test_invalid_file_type_val", "tests/test_combine.py::TestSetInputFormat::test_invalid_ignore_length", "tests/test_combine.py::TestSetInputFormat::test_invalid_ignore_length_val", "tests/test_combine.py::TestSetInputFormat::test_invalid_rate", "tests/test_combine.py::TestSetInputFormat::test_invalid_rate_val", "tests/test_combine.py::TestSetInputFormat::test_multiple_different_len", "tests/test_combine.py::TestSetInputFormat::test_multiple_same_len", "tests/test_combine.py::TestSetInputFormat::test_none", "tests/test_combine.py::TestSetInputFormat::test_rate", "tests/test_combine.py::TestBuildInputFormatList::test_equal_num_fmt", "tests/test_combine.py::TestBuildInputFormatList::test_equal_num_vol", "tests/test_combine.py::TestBuildInputFormatList::test_greater_num_fmt", "tests/test_combine.py::TestBuildInputFormatList::test_greater_num_vol", "tests/test_combine.py::TestBuildInputFormatList::test_lesser_num_fmt", "tests/test_combine.py::TestBuildInputFormatList::test_lesser_num_vol", "tests/test_combine.py::TestBuildInputFormatList::test_none", "tests/test_combine.py::TestBuildInputArgs::test_basic", "tests/test_combine.py::TestBuildInputArgs::test_unequal_length", "tests/test_combine.py::TestValidateCombineType::test_invalid", "tests/test_combine.py::TestValidateCombineType::test_valid", "tests/test_combine.py::TestValidateVolumes::test_invalid_type", "tests/test_combine.py::TestValidateVolumes::test_invalid_vol", "tests/test_combine.py::TestValidateVolumes::test_valid_list", "tests/test_combine.py::TestValidateVolumes::test_valid_none" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-05-29 17:55:46+00:00
bsd-3-clause
5,150
rachmadaniHaryono__we-get-11
diff --git a/README.rst b/README.rst index 3f7125f..050d69a 100644 --- a/README.rst +++ b/README.rst @@ -66,13 +66,13 @@ Options ===================== ===================================================== -s --search=<text> Search for a torrent. -l --list List top torrents from modules. --t --target=<target> Select module to use or 'all'. +-t --target=<target> Select module to use or 'all' [default: all]. -L --links Output results as links. -J --json Output results in JSON format. -G --get-list List targets (supported web-sites). -f --filter=<str> Match text or regular expression in the torrent name. -n --results=<n> Number of results to retrieve. --S --sort-type=<type> Sort torrents by name/seeds (default: seeds). +-S --sort-type=<type> Sort torrents by name/seeds [default: seeds]. ===================== ===================================================== Video options diff --git a/changelog.rst b/changelog.rst index 8af0274..9f65658 100644 --- a/changelog.rst +++ b/changelog.rst @@ -14,6 +14,12 @@ New - user status for pirate bay - argv for arguments +Changes +~~~~~~~ + +- target parameter default to all + + 1.1.0 - 2018-07-08 ------------------ diff --git a/we_get/core/we_get.py b/we_get/core/we_get.py index 4dddbc4..a4da5a0 100644 --- a/we_get/core/we_get.py +++ b/we_get/core/we_get.py @@ -28,13 +28,13 @@ __doc__ = """Usage: we-get [options]... Options: -s --search=<text> Search for a torrent. -l --list List top torrents from modules. - -t --target=<target> Select module to use or \'all\'. + -t --target=<target> Select module to use or 'all' [default: all]. -L --links Output results as links. -J --json Output results in JSON format. -G --get-list List targets (supported web-sites). -f --filter=<str> Match text or regular expression in the torrent name. -n --results=<n> Number of results to retrieve. - -S --sort-type=<type> Sort torrents by name/seeds (default: seeds). + -S --sort-type=<type> Sort torrents by name/seeds [default: seeds]. Video options: -q --quality=<q> Try to match quality for the torrent (720p,1080p, ...).
rachmadaniHaryono/we-get
ed496f3fed81a2d87d876b6cd3b83960a8e9125b
diff --git a/tests/test_core_we_get.py b/tests/test_core_we_get.py new file mode 100644 index 0000000..5d30afc --- /dev/null +++ b/tests/test_core_we_get.py @@ -0,0 +1,61 @@ +import pytest +from docopt import docopt, DocoptExit + +from we_get.core.we_get import WG +from we_get.core import we_get + + [email protected]( + 'argv, exp_res', + [ + [None, {'arguments': None, 'parguments': {}, 'we_get_run': 0}], + [['--search', 'ubuntu'], { + 'arguments': { + '--filter': [], + '--genre': [], + '--get-list': 0, + '--help': 0, + '--json': 0, + '--links': 0, + '--list': 0, + '--quality': [], + '--results': [], + '--search': ['ubuntu'], + '--sort-type': [], + '--target': ['all'], + '--version': 0 + }, + 'parguments': { + '--search': ['ubuntu'], '--target': ['all']}, 'we_get_run': 1 + }], + ] +) +def test_parse_arguments(argv, exp_res): + wg = WG() + if argv is None: + with pytest.raises(DocoptExit): + wg.parse_arguments() + assert vars(wg) == exp_res + with pytest.raises(DocoptExit): + wg.parse_arguments(argv) + assert vars(wg) == exp_res + else: + wg.parse_arguments(argv) + assert vars(wg) == exp_res + + [email protected]( + 'argv, exp_res', + [ + [ + [], + { + '--filter': [], '--genre': [], '--get-list': 0, '--help': 0, '--json': 0, + '--links': 0, '--list': 0, '--quality': [], '--results': [], '--search': [], + '--sort-type': [], '--target': ['all'], '--version': 0} + ], + ], +) +def test_we_get_docopt(argv, exp_res): + res = docopt(we_get.__doc__, argv=argv) + assert exp_res == res diff --git a/tests/test_doc.py b/tests/test_doc.py new file mode 100644 index 0000000..aa689ed --- /dev/null +++ b/tests/test_doc.py @@ -0,0 +1,27 @@ +from datetime import datetime + + +def test_arg_option_doc(): + with open('README.rst') as f: + content = f.read() + option_parts = content.split('Options\n-------')[1].split('Video options\n')[0].strip() + option_parts = option_parts.splitlines()[1:-1] + option_parts = [x.split(' ', 2) for x in option_parts] + for idx, x in enumerate(option_parts): + option_parts[idx][2] = x[2].strip() + with open('we_get/core/we_get.py') as f: + m_content = f.read() + m_option_parts = m_content.split('Options:')[1].split('Video options')[0].strip().splitlines() + m_option_parts = [x.strip().split(' ', 2) for x in m_option_parts] + for idx, x in enumerate(m_option_parts): + m_option_parts[idx][2] = x[2].strip() + assert option_parts == m_option_parts + + +def test_year(): + current_year = datetime.now().year + with open('we_get/core/we_get.py') as f: + m_content = f.read() + m_content.splitlines()[1] + year = m_content.split('Copyright (c) 2016-')[1].split(' ')[0] + assert year == str(current_year)
Default -t to all I was wondering if it would make sense to default the target parameter to all if it isn't specified. Currently no search will take place if the parameter is omitted. That way you get the most results by default and only narrow them down **if** you want them to be.
0.0
ed496f3fed81a2d87d876b6cd3b83960a8e9125b
[ "tests/test_core_we_get.py::test_parse_arguments[argv1-exp_res1]", "tests/test_core_we_get.py::test_we_get_docopt[argv0-exp_res0]", "tests/test_doc.py::test_arg_option_doc" ]
[ "tests/test_core_we_get.py::test_parse_arguments[None-exp_res0]" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-06-10 20:59:52+00:00
mit
5,151
radiasoft__pykern-126
diff --git a/pykern/pkio.py b/pykern/pkio.py index 4eea5f8..4d878dc 100644 --- a/pykern/pkio.py +++ b/pykern/pkio.py @@ -285,19 +285,22 @@ def walk_tree(dirname, file_re=None): Yields: py.path.local: paths in sorted order """ - fr = file_re - if fr and not hasattr(fr, 'search'): - fr = re.compile(fr) - dirname = py_path(dirname).realpath() - dn = str(dirname) + def _walk(dir_path): + for r, _, files in os.walk(str(dir_path), topdown=True, onerror=None, followlinks=False): + r = py_path(r) + for f in files: + yield r.join(f) + res = [] - for r, d, files in os.walk(dn, topdown=True, onerror=None, followlinks=False): - for f in files: - p = py_path(r).join(f) - if fr and not fr.search(dirname.bestrelpath(p)): - continue - res.append(p) - # Not an iterator, but works as one. Don't assume always will return list + d = py_path(dirname) + if not file_re: + res = list(_walk(d)) + else: + if not hasattr(file_re, 'search'): + file_re = re.compile(file_re) + for p in _walk(d): + if file_re.search(d.bestrelpath(p)): + res.append(p) return sorted(res)
radiasoft/pykern
753082c2a08a5776b30ddab5b28533cdb85b7f3c
diff --git a/tests/pkio_test.py b/tests/pkio_test.py index d17b4fb..2b7e78f 100644 --- a/tests/pkio_test.py +++ b/tests/pkio_test.py @@ -102,6 +102,7 @@ def test_walk_tree_and_sorted_glob(): """Looks in work_dir""" from pykern import pkunit from pykern import pkio + import re with pkunit.save_chdir_work() as pwd: for f in ('d1/d7', 'd2/d3', 'd4/d5/d6'): @@ -116,6 +117,8 @@ def test_walk_tree_and_sorted_glob(): 'When walking tree with file_re, should only return matching files' assert [expect[0]] == list(pkio.walk_tree('.', '^d1')), \ 'When walking tree with file_re, file to match does not include dir being searched' + assert [expect[0]] == list(pkio.walk_tree('.', re.compile('^d1'))), \ + 'When walking tree with file_re, file to match does not include dir being searched' assert pkio.sorted_glob('*/*/f*', key='basename') == expect
refactor pkio.walk_tree This is an example refactoring about local variables.
0.0
753082c2a08a5776b30ddab5b28533cdb85b7f3c
[ "tests/pkio_test.py::test_unchecked_remove", "tests/pkio_test.py::test_has_file_extension", "tests/pkio_test.py::test_py_path", "tests/pkio_test.py::test_save_chdir", "tests/pkio_test.py::test_write_binary", "tests/pkio_test.py::test_walk_tree_and_sorted_glob", "tests/pkio_test.py::test_write_text", "tests/pkio_test.py::test_atomic_write" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2022-02-22 20:34:30+00:00
apache-2.0
5,152
radiasoft__pykern-158
diff --git a/pykern/pkunit.py b/pykern/pkunit.py index c76ac2a..fc72b1b 100644 --- a/pykern/pkunit.py +++ b/pykern/pkunit.py @@ -239,12 +239,17 @@ def file_eq(expect_path, *args, **kwargs): actual_path = b if not isinstance(actual_path, pykern.pkconst.PY_PATH_LOCAL_TYPE): actual_path = work_dir().join(actual_path) - actual = kwargs['actual'] if a else pkio.read_text(actual_path) + if a: + actual = kwargs['actual'] + if actual_path.exists(): + pkfail('actual={} and actual_path={} both exist', actual, actual_path) + else: + actual = pkio.read_text(actual_path) if expect_path.ext == '.json' and not actual_path.exists(): - e = pykern.pkjson.load_any(expect_path) + e = pkio.read_text(expect_path) if a: pkio.mkdir_parent_only(actual_path) - pykern.pkjson.dump_pretty(actual, filename=actual_path) + actual = pykern.pkjson.dump_pretty(actual, filename=actual_path) else: if j: import pykern.pkjinja
radiasoft/pykern
253ff7fa844d592cd544e2961036d27f51f05faa
diff --git a/tests/pkunit_data/file_eq1.json b/tests/pkunit_data/file_eq1.json new file mode 100644 index 0000000..7326da5 --- /dev/null +++ b/tests/pkunit_data/file_eq1.json @@ -0,0 +1,1 @@ +"array('d', [1.0])" diff --git a/tests/pkunit_data/file_eq2.txt b/tests/pkunit_data/file_eq2.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/pkunit_data/file_eq3.txt b/tests/pkunit_data/file_eq3.txt new file mode 100644 index 0000000..339f0be --- /dev/null +++ b/tests/pkunit_data/file_eq3.txt @@ -0,0 +1,1 @@ +something else \ No newline at end of file diff --git a/tests/pkunit_test.py b/tests/pkunit_test.py index 31acebb..40b0b6e 100644 --- a/tests/pkunit_test.py +++ b/tests/pkunit_test.py @@ -5,6 +5,9 @@ u"""PyTest for :mod:`pykern.pkunit` :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function +import pkgutil + +import py import pytest def test_assert_object_with_json(): @@ -55,6 +58,22 @@ def test_empty_work_dir(): 'Ensure directory was created' +def test_file_eq(): + import array + import pykern.pkunit + import pykern.pkio + + a = array.ArrayType('d', [1]) + pykern.pkunit.file_eq('file_eq1.json', actual=a) + + with pykern.pkunit.pkexcept(TypeError): + pykern.pkunit.file_eq('file_eq2.txt', actual=dict()) + d = pykern.pkunit.empty_work_dir() + pykern.pkio.write_text(d.join('file_eq3.txt'), 'something') + with pykern.pkunit.pkexcept('both exist'): + pykern.pkunit.file_eq('file_eq3.txt', actual='something else') + + def test_import_module_from_data_dir(monkeypatch): from pykern import pkunit
pkunit.file_eq always should compare files Almost always compares objects instead
0.0
253ff7fa844d592cd544e2961036d27f51f05faa
[ "tests/pkunit_test.py::test_file_eq" ]
[ "tests/pkunit_test.py::test_assert_object_with_json", "tests/pkunit_test.py::test_data_dir", "tests/pkunit_test.py::test_data_yaml", "tests/pkunit_test.py::test_empty_work_dir", "tests/pkunit_test.py::test_import_module_from_data_dir", "tests/pkunit_test.py::test_pkexcept", "tests/pkunit_test.py::test_pkok", "tests/pkunit_test.py::test_pkre_convert" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2022-04-07 20:43:22+00:00
apache-2.0
5,153
radiasoft__pykern-160
diff --git a/pykern/pkcli/__init__.py b/pykern/pkcli/__init__.py index cb8bd7e..27cbf90 100644 --- a/pykern/pkcli/__init__.py +++ b/pykern/pkcli/__init__.py @@ -66,6 +66,42 @@ def command_error(fmt, *args, **kwargs): raise CommandError(fmt.format(*args, **kwargs)) +class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, + argparse.RawDescriptionHelpFormatter): + def _expand_help(self, action): + return super()._expand_help(action).split('\n')[0] + +class CustomParser(argparse.ArgumentParser): + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.program = kwargs.copy() + self.options = [] + + def format_help(self): + f = argh.PARSER_FORMATTER(prog=self.prog) + if not self.description: + f = CustomFormatter(prog=self.prog) + f.add_usage( + self.usage, + self._actions, + self._mutually_exclusive_groups + ) + f.add_text(self.description) + for a in self._action_groups: + f.start_section(a.title) + f.add_text(a.description) + f.add_arguments(a._group_actions) + f.end_section() + f.add_text(self.epilog) + if not self.description: + return f.format_help().replace('positional arguments', 'commands') + return f.format_help() + + def print_help(self): + print(self.format_help()) + + def main(root_pkg, argv=None): """Invokes module functions in :mod:`pykern.pkcli` @@ -90,8 +126,7 @@ def main(root_pkg, argv=None): if not cli: return 1 prog = prog + ' ' + module_name - parser = argparse.ArgumentParser( - prog=prog, formatter_class=argh.PARSER_FORMATTER) + parser = CustomParser(prog) cmds = _commands(cli) dc = _default_command(cmds, argv) if dc:
radiasoft/pykern
814541baf45bb9221a6c03aa766bd28fbd523ec5
diff --git a/tests/pkcli_data/p1/pkcli/conf1.py b/tests/pkcli_data/p1/pkcli/conf1.py index 3feccce..057bb50 100644 --- a/tests/pkcli_data/p1/pkcli/conf1.py +++ b/tests/pkcli_data/p1/pkcli/conf1.py @@ -5,11 +5,21 @@ last_cmd = None from pykern.pkdebug import pkdp def cmd1(arg1): + """Subject line for cmd1 + + Args: + arg1 + """ global last_cmd last_cmd = cmd1 return def cmd2(): + """Subject line for cmd2 + + Args: + - + """ global last_cmd last_cmd = cmd2 return diff --git a/tests/pkcli_test.py b/tests/pkcli_test.py index fcaeb56..09d6087 100644 --- a/tests/pkcli_test.py +++ b/tests/pkcli_test.py @@ -42,7 +42,7 @@ def test_main2(capsys): _dev(rp, [], None, all_modules, capsys) _dev(rp, ['--help'], None, all_modules, capsys) _dev(rp, ['conf1'], SystemExit, r'cmd1,cmd2.*too few', capsys) - _dev(rp, ['conf1', '-h'], SystemExit, r'\{cmd1,cmd2\}.*positional arguments', capsys) + _dev(rp, ['conf1', '-h'], SystemExit, r'\{cmd1,cmd2\}.*commands', capsys) if six.PY2: _dev(rp, ['not_found'], None, r'no module', capsys) else: @@ -91,8 +91,9 @@ def _dev(root_pkg, argv, exc, expect, capsys): out, err = capsys.readouterr() if not err: err = out - assert re.search(expect, err, flags=re.IGNORECASE+re.DOTALL) is not None, \ - 'Looking for {} in err={}'.format(expect, err) + assert re.search('Args.*arg1', err, flags=re.DOTALL) is None, \ + 'failure to ignore arguments and only print subject. out: {}'.format(err) + pkunit.pkre(expect, err) def _main(root_pkg, argv):
pkcli docstring printing too greedy When using the `pkcli` interaction with the middl project, I'm finding that the help printing seems a bit too greedy, printing the entire docstring instead of just the function summary. The command is below: ```bash (middl) [joshec@roentgen middl]$ middlsoft train -h usage: middlsoft train [-h] {regressor,vrae} ... positional arguments: {regressor,vrae} regressor Train and run regressor to map latent space back to data Args: configuration (str): path to configuration file in model directory no_cuda (bool): whether or not to use CUDA. Defaults to False. cuda_device (int): CUDA device index. Defaults to -1 (all). do_write (bool): write regressor output to file. Defaults to False. use_sklearn (bool): use scikit-learn MLPRegressor vs pytorch. Defaults to False. datadir (str): alternative directory to find data in. Defaults to None. profile (bool): perform simple profiling of pytorch model. Defaults to False. Returns: None vrae optional arguments: -h, --help show this help message and exit ``` This printing occurs on the disvae_losses branch of the middl project: [middl/middlsoft/pkcli/train.py](https://github.com/radiasoft/middl/blob/d8ebd67e8dff4ff563fc7be78220f785c1fb5ad3/middlsoft/pkcli/train.py#L253-L274)
0.0
814541baf45bb9221a6c03aa766bd28fbd523ec5
[ "tests/pkcli_test.py::test_main2" ]
[ "tests/pkcli_test.py::test_command_error", "tests/pkcli_test.py::test_main1", "tests/pkcli_test.py::test_main3" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-04-14 23:01:09+00:00
apache-2.0
5,154
radiasoft__pykern-282
diff --git a/pykern/pkunit.py b/pykern/pkunit.py index 4c758b8..5b26817 100644 --- a/pykern/pkunit.py +++ b/pykern/pkunit.py @@ -168,9 +168,11 @@ def case_dirs(group_prefix="", ignore_lines=None): file_eq(expect_path=e, actual_path=a, ignore_lines=ignore_lines) d = work_dir() + n = 0 for i in pkio.sorted_glob(data_dir().join(group_prefix + "*.in")): w = d.join(i.purebasename) shutil.copytree(str(i), str(w)) + n += 1 with pkio.save_chdir(w): yield w try: @@ -188,6 +190,8 @@ def case_dirs(group_prefix="", ignore_lines=None): _pkdlog("Exception in case_dir={}\n{}", w, f.read()) # This avoids confusing "during handling of above exception" pkfail("See stack above") + if n == 0: + pkfail(f"No files found for group_prefix={group_prefix}") def data_dir():
radiasoft/pykern
d4428c272971980d3d03784c19c6fb1196c46336
diff --git a/tests/pkunit1_test.py b/tests/pkunit1_test.py index 417a0f4..8386381 100644 --- a/tests/pkunit1_test.py +++ b/tests/pkunit1_test.py @@ -33,3 +33,11 @@ def test_case_dirs_curly_brackets(): with pkunit.pkexcept("1c1\n< expected\n---\n> {unexpected}"): for d in pkunit.case_dirs(group_prefix="curly_brackets"): pass + + +def test_no_files(): + from pykern import pkunit + + with pkunit.pkexcept("no files found"): + for d in pkunit.case_dirs(group_prefix="no_files"): + continue
pkunit.case_dirs should detect no files and fail If case_dirs doesn't generate any files, it should pkfail with a message about the prefix not generating any files. There should be at least one output file, too.
0.0
d4428c272971980d3d03784c19c6fb1196c46336
[ "tests/pkunit1_test.py::test_no_files" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2022-09-30 18:01:09+00:00
apache-2.0
5,155
radiasoft__pykern-349
diff --git a/pykern/pksetup.py b/pykern/pksetup.py index 9a32644..f86a1a0 100644 --- a/pykern/pksetup.py +++ b/pykern/pksetup.py @@ -66,6 +66,8 @@ TESTS_DIR = "tests" _VERSION_RE = r"(\d{8}\.\d+)" +_cfg = None + class NullCommand(distutils.cmd.Command, object): """Use to eliminate a ``cmdclass``. @@ -689,6 +691,14 @@ def _version(base): str: Chronological version "yyyymmdd.hhmmss" str: git sha if available """ + from pykern import pkconfig + + global _cfg + + if not _cfg: + _cfg = pkconfig.init(no_version=(False, bool, "use utcnow as version")) + if _cfg.no_version: + return _version_from_datetime(), None v1 = _version_from_pkg_info(base) v2, sha = _version_from_git(base) if v1: @@ -706,6 +716,15 @@ def _version_float(value): return m.group(1)[: -len(m.group(2))] if m.group(2) else m.group(1) +def _version_from_datetime(value=None): + # Avoid 'UserWarning: Normalizing' by setuptools + return str( + pkg_resources.parse_version( + (value or datetime.datetime.utcnow()).strftime("%Y%m%d.%H%M%S"), + ), + ) + + def _version_from_git(base): """Chronological version string for most recent commit or time of newer file. @@ -726,15 +745,13 @@ def _version_from_git(base): # Under development? sha = None if len(_git_ls_files(["--modified", "--deleted"])): - vt = datetime.datetime.utcnow() + vt = None else: branch = _check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).rstrip() vt = _check_output(["git", "log", "-1", "--format=%ct", branch]).rstrip() vt = datetime.datetime.fromtimestamp(float(vt)) sha = _check_output(["git", "rev-parse", "HEAD"]).rstrip() - v = vt.strftime("%Y%m%d.%H%M%S") - # Avoid 'UserWarning: Normalizing' by setuptools - return str(pkg_resources.parse_version(v)), sha + return _version_from_datetime(vt), sha def _version_from_pkg_info(base):
radiasoft/pykern
45722dbf5ef7962a123b3c6d93745151acd1e294
diff --git a/tests/pksetup_test.py b/tests/pksetup_test.py index feb51af..7e5339c 100644 --- a/tests/pksetup_test.py +++ b/tests/pksetup_test.py @@ -5,7 +5,7 @@ :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function -from subprocess import check_call, call +import subprocess import contextlib import glob import os @@ -27,26 +27,26 @@ def test_build_clean(): from pykern import pkunit with _project_dir("pksetupunit1") as d: - check_call(["python", "setup.py", "sdist", "--formats=zip"]) + subprocess.check_call(["python", "setup.py", "sdist", "--formats=zip"]) archive = _assert_members( ["pksetupunit1", "package_data", "data1"], ["scripts", "script1"], ["examples", "example1.txt"], ["tests", "mod2_test.py"], ) - check_call(["python", "setup.py", "build"]) + subprocess.check_call(["python", "setup.py", "build"]) dat = os.path.join("build", "lib", "pksetupunit1", "package_data", "data1") assert os.path.exists( dat ), "When building, package_data should be installed in lib" bin_dir = "scripts-{}.{}".format(*(sys.version_info[0:2])) - check_call(["python", "setup.py", "test"]) + subprocess.check_call(["python", "setup.py", "test"]) assert os.path.exists("tests/mod2_test.py") - check_call(["git", "clean", "-dfx"]) + subprocess.check_call(["git", "clean", "-dfx"]) assert not os.path.exists( "build" ), "When git clean runs, build directory should not exist" - check_call(["python", "setup.py", "sdist"]) + subprocess.check_call(["python", "setup.py", "sdist"]) pkio.unchecked_remove(archive) _assert_members( ["!", "tests", "mod2_work", "do_not_include_in_sdist.py"], @@ -54,10 +54,10 @@ def test_build_clean(): ) # TODO(robnagler) need another sentinel here if os.environ.get("PKSETUP_PKDEPLOY_IS_DEV", False): - check_call(["python", "setup.py", "pkdeploy"]) + subprocess.check_call(["python", "setup.py", "pkdeploy"]) -def not_a_test_optional_args(): +def test_optional_args(): """Create a normal distribution Installs into the global environment, which messes up pykern's install. @@ -66,12 +66,46 @@ def not_a_test_optional_args(): from pykern import pkio from pykern import pksetup from pykern import pkunit + from pykern import pkdebug + + def _results(pwd, expect): + x = d.dirpath().listdir(fil=lambda x: x.basename != d.basename) + pkunit.pkeq(1, len(x)) + a = list(pkio.walk_tree(x[0], "/(civicjson.py|adhan.py|pksetup.*METADATA)$")) + pkunit.pkeq(expect, len(a)) + for f in a: + if f.basename == "METADATA": + return x[0], f + pkunit.pkfail("METADATA not found in files={}", a) with _project_dir("pksetupunit2") as d: - call(["pip", "uninstall", "-y", "shijian"]) - call(["pip", "uninstall", "-y", "adhan"]) - check_call(["pip", "install", "-e", ".[all]"]) - check_call(["python", "setup.py", "test"]) + # clean the work dir then run afind + subprocess.check_call( + [ + "pip", + "install", + "--root", + pkunit.work_dir(), + # No -e or it will modify global environment + ".[all]", + ], + ) + x, m1 = _results(d, 3) + pkio.unchecked_remove(x, ".git") + e = os.environ.copy() + e["PYKERN_PKSETUP_NO_VERSION"] = "1" + subprocess.check_call( + [ + "pip", + "install", + "--root", + pkunit.work_dir(), + ".", + ], + env=e, + ) + _, m2 = _results(d, 1) + pkunit.pkne(m1, m2) @contextlib.contextmanager @@ -92,12 +126,12 @@ def _project_dir(project): d = pkunit.empty_work_dir().join(project) pkunit.data_dir().join(d.basename).copy(d) with pkio.save_chdir(d): - check_call(["git", "init", "."]) - check_call(["git", "config", "user.email", "[email protected]"]) - check_call(["git", "config", "user.name", "pykern"]) - check_call(["git", "add", "."]) + subprocess.check_call(["git", "init", "."]) + subprocess.check_call(["git", "config", "user.email", "[email protected]"]) + subprocess.check_call(["git", "config", "user.name", "pykern"]) + subprocess.check_call(["git", "add", "."]) # Need a commit - check_call(["git", "commit", "-m", "n/a"]) + subprocess.check_call(["git", "commit", "-m", "n/a"]) yield d
Add PYKERN_PKSETUP_NO_VERSION=1 In order to install a repo directly from a GitHub repo download zip (no .git or egg-info), need to override version.
0.0
45722dbf5ef7962a123b3c6d93745151acd1e294
[ "tests/pksetup_test.py::test_optional_args" ]
[ "tests/pksetup_test.py::test_build_clean" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-03-31 20:32:53+00:00
apache-2.0
5,156
radish-bdd__radish-307
diff --git a/docs/commandline.rst b/docs/commandline.rst index beb974c..5f50396 100644 --- a/docs/commandline.rst +++ b/docs/commandline.rst @@ -40,6 +40,10 @@ containing steps and terrain functions from multiple locations: Since version v0.7.0 you can use multiple basedirs within one ``-b`` flag split by a colon (:). Similar to the possibilities you've got with ``$PATH``. +On Windows it is not possbile to use a colon (:) because it is used +in almost any absolute path, e.g. ``C:\foo\bar``. +Since version v0.11.2 you can use a semicolon (;) on Windows for +multiple basedirs. Run - Early exit diff --git a/radish/utils.py b/radish/utils.py index afee180..5a35cd1 100644 --- a/radish/utils.py +++ b/radish/utils.py @@ -190,4 +190,5 @@ def flattened_basedirs(basedirs): Multiple basedirs can be specified within a single element split by a colon. """ - return list(x for x in itertools.chain(*(x.split(":") for x in basedirs)) if x) + separator = ";" if os.name == "nt" else ":" + return list(x for x in itertools.chain(*(x.split(separator) for x in basedirs)) if x)
radish-bdd/radish
ab7e7a6179e2553232661aece213087a68d75d55
diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 5aad50f..21ffb72 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -18,22 +18,26 @@ import radish.utils as utils @pytest.mark.parametrize( - "basedirs, expected_basedirs", + "basedirs, expected_basedirs, os_name", [ - (["foo", "bar"], ["foo", "bar"]), - (["foo:bar", "foobar"], ["foo", "bar", "foobar"]), + (["foo", "bar"], ["foo", "bar"], "posix"), + (["foo:bar", "foobar"], ["foo", "bar", "foobar"], "posix"), ( ["foo:bar", "foobar", "one:two:three"], ["foo", "bar", "foobar", "one", "two", "three"], + "posix" ), - (["foo:", ":bar"], ["foo", "bar"]), + (["foo:", ":bar"], ["foo", "bar"], "posix"), + (["C:\\windows\\radish"], ["C:\\windows\\radish"], "nt"), + (["C:\\windows;radish"], ["C:\\windows", "radish"], "nt"), ], ) -def test_flattened_basedirs(basedirs, expected_basedirs): +def test_flattened_basedirs(mocker, basedirs, expected_basedirs, os_name): """ Test flatten basedirs """ # given & when + mocker.patch("os.name", os_name) actual_basedirs = utils.flattened_basedirs(basedirs) # then
"Error: Location '$PWD/radish' to load modules does not exist" on Windows during running features Following the instruction from: http://radish.readthedocs.io/en/latest/installation.html and http://radish.readthedocs.io/en/latest/quickstart.html instead of running the tests with command `radish features/` an error occurs: ``` Error: Location '$PWD/radish' to load modules does not exist Traceback (most recent call last): File "d:\workspace\radishSample\venv\lib\site-packages\radish\errororacle.py", line 52, in _decorator return func(*args, **kwargs) File "d:\workspace\radishSample\venv\lib\site-packages\radish\main.py", line 206, in main return method(core) File "d:\workspace\radishSample\venv\lib\site-packages\radish\main.py", line 65, in run_features load_modules(basedir) File "d:\workspace\radishSample\venv\lib\site-packages\radish\loader.py", line 20, in load_modules raise OSError("Location '{0}' to load modules does not exist".format(location)) OSError: Location '$PWD/radish' to load modules does not exist ``` According to https://github.com/radish-bdd/radish - it should be possible to run it on Windows without any modifications. Tested with following versions: ``` radish-bdd (0.8.3) radish-parse-type (0.3.5) ``` OS: ``` OS Name Microsoft Windows 10 Pro, 64-bit Version 10.0.16299 Build 16299 ``` Python: `Python 3.6.4, 32-bit`
0.0
ab7e7a6179e2553232661aece213087a68d75d55
[ "tests/unit/test_utils.py::test_flattened_basedirs[basedirs0-expected_basedirs0-posix]", "tests/unit/test_utils.py::test_make_unique_obj_list", "tests/unit/test_utils.py::test_flattened_basedirs[basedirs2-expected_basedirs2-posix]", "tests/unit/test_utils.py::test_flattened_basedirs[basedirs5-expected_basedirs5-nt]", "tests/unit/test_utils.py::test_flattened_basedirs[basedirs4-expected_basedirs4-nt]", "tests/unit/test_utils.py::test_flattened_basedirs[basedirs3-expected_basedirs3-posix]", "tests/unit/test_utils.py::test_flattened_basedirs[basedirs1-expected_basedirs1-posix]" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-02-08 21:28:01+00:00
mit
5,157
radomirbosak__duden-195
diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ca37bc..2d88e2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Breaking: New features: * Add `pronunciation_audio_url` property #183 by @mundanevision20 +* Synonyms are now properly split #195 Bugfixes: diff --git a/docs/usage.md b/docs/usage.md index ab71b64..a897ebc 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -36,7 +36,7 @@ This example showcases the most useful functions of the `DudenWord` class. 'barmherziges Wesen, Verhalten' > w.synonyms -'[Engels]güte, Milde, Nachsicht, Nachsichtigkeit; (gehoben) Herzensgüte, Mildtätigkeit, Seelengüte; (bildungssprachlich) Humanität, Indulgenz; (veraltend) Wohltätigkeit; (Religion) Gnade' +['[Engels]güte', 'Milde', 'Nachsicht', 'Nachsichtigkeit'] > w.origin 'mittelhochdeutsch barmherzekeit, barmherze, althochdeutsch armherzi, nach (kirchen)lateinisch misericordia' diff --git a/duden/word.py b/duden/word.py index 60fecc6..c8d58bf 100644 --- a/duden/word.py +++ b/duden/word.py @@ -239,16 +239,17 @@ class DudenWord: """ Return the structure with word synonyms """ - try: - section = self.soup.find("div", id="synonyme") - section = copy.copy(section) - if section.header: - section.header.extract() - return recursively_extract( - section, maxdepth=2, exfun=lambda x: x.text.strip() - ) - except AttributeError: + section = self.soup.find("div", id="synonyme") + if section is None: return None + section = copy.copy(section) + if section.header: + section.header.extract() + more_nav = section.find("nav", class_="more") + if more_nav: + more_nav.extract() + + return split_synonyms(section.text.strip()) @property def origin(self): @@ -430,3 +431,34 @@ class DudenWord: return None return [spelling.get_text() for spelling in alternative_spellings] + + +def split_synonyms(text): + """ + Properly split strings like + + meaning1, (commonly) meaning2; (formal, distant) meaning3 + """ + # split by ',' and ';' + comma_splits = text.split(",") + fine_splits = [] + for split in comma_splits: + fine_splits.extend(split.split(";")) + + # now join back parts which are inside of parentheses + final_splits = [] + inside_parens = False + for split in fine_splits: + if inside_parens: + final_splits[-1] = final_splits[-1] + "," + split + else: + final_splits.append(split) + + if "(" in split and ")" in split: + inside_parens = split.index("(") > split.index("(") + elif "(" in split: + inside_parens = True + elif ")" in split: + inside_parens = False + + return [split.strip() for split in final_splits]
radomirbosak/duden
eef0256225fe58c9fc715fe020ded537ba75716f
diff --git a/tests/test_data/Barmherzigkeit.yaml b/tests/test_data/Barmherzigkeit.yaml index 50f69b7..92b1105 100644 --- a/tests/test_data/Barmherzigkeit.yaml +++ b/tests/test_data/Barmherzigkeit.yaml @@ -16,7 +16,10 @@ origin: mittelhochdeutsch barmherzekeit, barmherze, althochdeutsch armherzi, nac grammar_overview: 'die Barmherzigkeit; Genitiv: der Barmherzigkeit' compounds: null synonyms: -- '[Engels]güte, Milde, Nachsicht, Nachsichtigkeit' +- '[Engels]güte' +- Milde +- Nachsicht +- Nachsichtigkeit words_before: - barmen - Barmen diff --git a/tests/test_data/Feiertag.yaml b/tests/test_data/Feiertag.yaml index 9ae6488..5edeb22 100644 --- a/tests/test_data/Feiertag.yaml +++ b/tests/test_data/Feiertag.yaml @@ -43,7 +43,9 @@ compounds: - verbringen - öffnen synonyms: -- Festtag, Gedenktag, Ehrentag +- Festtag +- Gedenktag +- Ehrentag words_before: - Feierlichkeit - Feiermodus diff --git a/tests/test_data/Kragen.yaml b/tests/test_data/Kragen.yaml index 1bcc139..8be889a 100644 --- a/tests/test_data/Kragen.yaml +++ b/tests/test_data/Kragen.yaml @@ -21,7 +21,8 @@ grammar_overview: 'der Kragen; Genitiv: des Kragens, Plural: die Kragen, süddeu österreichisch, schweizerisch: Krägen' compounds: null synonyms: -- Gurgel, Kehle +- Gurgel +- Kehle words_before: - Kraftwerksbetreiberin - Kraftwort diff --git a/tests/test_data/Petersilie.yaml b/tests/test_data/Petersilie.yaml index fd0bff0..12ccd60 100644 --- a/tests/test_data/Petersilie.yaml +++ b/tests/test_data/Petersilie.yaml @@ -17,8 +17,9 @@ origin: mittelhochdeutsch pētersil(je), althochdeutsch petersilie, petrasile < grammar_overview: 'die Petersilie; Genitiv: der Petersilie, Plural: die Petersilien' compounds: null synonyms: -- (schweizerisch) Peterli; (bayrisch, österreichisch umgangssprachlich) Petersil; - (südwestdeutsch und schweizerisch mundartlich) Peterle +- (schweizerisch) Peterli +- (bayrisch, österreichisch umgangssprachlich) Petersil +- (südwestdeutsch und schweizerisch mundartlich) Peterle words_before: - Peter-Paul-Kirche - Petersburg diff --git a/tests/test_data/einfach.yaml b/tests/test_data/einfach.yaml index 87d6e2d..df22e24 100644 --- a/tests/test_data/einfach.yaml +++ b/tests/test_data/einfach.yaml @@ -45,7 +45,10 @@ compounds: - stimmen - werden synonyms: -- einmal, nicht doppelt, nicht mehrfach, bequem +- einmal +- nicht doppelt +- nicht mehrfach +- bequem words_before: - Eineuromünze - Eineurostück diff --git a/tests/test_data/laufen.yaml b/tests/test_data/laufen.yaml index c931c1b..7afcbf9 100644 --- a/tests/test_data/laufen.yaml +++ b/tests/test_data/laufen.yaml @@ -63,7 +63,10 @@ compounds: - Vertrag - Vorbereitung synonyms: -- eilen, fegen, hetzen, jagen +- eilen +- fegen +- hetzen +- jagen words_before: - Laufbekleidung - Laufbrett diff --git a/tests/test_word.py b/tests/test_word.py new file mode 100644 index 0000000..0d0af5a --- /dev/null +++ b/tests/test_word.py @@ -0,0 +1,12 @@ +"""Test word functions""" + +from duden.word import split_synonyms + + +def test_split_synonyms(): + """Test one-line list splitting""" + assert split_synonyms("") == [""] + assert split_synonyms("a, b ,c") == ["a", "b", "c"] + + expected = ["a", "b (b, c)", "d (d, e, f) g", "h"] + assert split_synonyms("a, b (b, c); d (d; e, f) g, h") == expected
Documentation of synonyms doesn't match code In the usage document it looks like `DudenWord.synonyms` is just a single string but the code actually returns a list with strings. Or always just *one* string, as the fix to #115 suggests.
0.0
eef0256225fe58c9fc715fe020ded537ba75716f
[ "tests/test_word.py::test_split_synonyms" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-02-25 10:06:39+00:00
mit
5,158
raimon49__pip-licenses-150
diff --git a/README.md b/README.md index eeeb287..7517b50 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Dump the software license list of Python packages installed with pip. * [Usage](#usage) * [Command\-Line Options](#command-line-options) * [Common options](#common-options) + * [Option: python](#option-python) * [Option: from](#option-from) * [Option: order](#option-order) * [Option: format](#option-format) @@ -97,6 +98,21 @@ Execute the command with your venv (or virtualenv) environment. ### Common options +#### Option: python + +By default, this tools finds the packages from the environment pip-licenses is launched from, by searching in current python's `sys.path` folders. In the case you want to search for packages in an other environment (e.g. if you want to run pip-licenses from its own isolated environment), you can specify a path to a python executable. The packages will be searched for in the given python's `sys.path`, free of pip-licenses dependencies. + +```bash +(venv) $ pip-licenses --with-system | grep pip + pip 22.3.1 MIT License + pip-licenses 4.1.0 MIT License +``` + +```bash +(venv) $ pip-licenses --python=</path/to/other/env>/bin/python --with-system | grep pip + pip 23.0.1 MIT License +``` + #### Option: from By default, this tool finds the license from [Trove Classifiers](https://pypi.org/classifiers/) or package Metadata. Some Python packages declare their license only in Trove Classifiers. diff --git a/piplicenses.py b/piplicenses.py index 3bac56e..488c338 100644 --- a/piplicenses.py +++ b/piplicenses.py @@ -30,7 +30,9 @@ from __future__ import annotations import argparse import codecs +import os import re +import subprocess import sys from collections import Counter from enum import Enum, auto @@ -194,7 +196,21 @@ def get_packages( return pkg_info - pkgs = importlib_metadata.distributions() + def get_python_sys_path(executable: str) -> list[str]: + script = "import sys; print(' '.join(filter(bool, sys.path)))" + output = subprocess.run( + [executable, "-c", script], + capture_output=True, + env={**os.environ, "PYTHONPATH": "", "VIRTUAL_ENV": ""}, + ) + return output.stdout.decode().strip().split() + + if args.python == sys.executable: + search_paths = sys.path + else: + search_paths = get_python_sys_path(args.python) + + pkgs = importlib_metadata.distributions(path=search_paths) ignore_pkgs_as_lower = [pkg.lower() for pkg in args.ignore_packages] pkgs_as_lower = [pkg.lower() for pkg in args.packages] @@ -785,6 +801,17 @@ def create_parser() -> CompatibleArgumentParser: "-v", "--version", action="version", version="%(prog)s " + __version__ ) + common_options.add_argument( + "--python", + type=str, + default=sys.executable, + metavar="PYTHON_EXEC", + help="R| path to python executable to search distributions from\n" + "Package will be searched in the selected python's sys.path\n" + "By default, will search packages for current env executable\n" + "(default: sys.executable)", + ) + common_options.add_argument( "--from", dest="from_",
raimon49/pip-licenses
bd213a57b824bd404436dfb261af1383824b5465
diff --git a/test_piplicenses.py b/test_piplicenses.py index f470377..426f31a 100644 --- a/test_piplicenses.py +++ b/test_piplicenses.py @@ -4,11 +4,14 @@ from __future__ import annotations import copy import email +import json import re import sys import unittest +import venv from enum import Enum, auto from importlib.metadata import Distribution +from types import SimpleNamespace from typing import TYPE_CHECKING, Any, List import docutils.frontend @@ -39,6 +42,7 @@ from piplicenses import ( factory_styled_table_with_args, find_license_from_classifier, get_output_fields, + get_packages, get_sortby, output_colored, save_if_needs, @@ -780,6 +784,26 @@ def test_allow_only(monkeypatch) -> None: ) +def test_different_python() -> None: + import tempfile + + class TempEnvBuild(venv.EnvBuilder): + def post_setup(self, context: SimpleNamespace) -> None: + self.context = context + + with tempfile.TemporaryDirectory() as target_dir_path: + venv_builder = TempEnvBuild(with_pip=True) + venv_builder.create(str(target_dir_path)) + python_exec = venv_builder.context.env_exe + python_arg = f"--python={python_exec}" + args = create_parser().parse_args([python_arg, "-s", "-f=json"]) + pkgs = get_packages(args) + package_names = sorted(p["name"] for p in pkgs) + print(package_names) + + assert package_names == ["pip", "setuptools"] + + def test_fail_on(monkeypatch) -> None: licenses = ("MIT license",) allow_only_args = ["--fail-on={}".format(";".join(licenses))]
Retrieve licenses from other environment Somehow related to #107 Currently, we can only get packages from the environments we are running pip-licenses on. This is a problem for two reasons - As said in mentioned issue, we cannot use it as a pre-commit hook easily. There is the possibility to use a hook within the activated environment, but it's clearly not following its guidelines - Using this libraries implies installing it in your venv, and thus contaminating it by installing packages you wouldn't need otherwise. It's no great given the purpose of this lib is to identify licenses of installed packages I think there is a simple fix to this. Indeed, thepckages are discovered via `importlib` `distributions()` function. As it can be seen here : https://github.com/raimon49/pip-licenses/blob/master/piplicenses.py#L193 By looking at the documentation and code of importlib, it seems to me that `distributions` should accept a `path` argument with a list of folders to search into. See https://importlib-metadata.readthedocs.io/en/latest/api.html#importlib_metadata.distributions and https://github.com/python/importlib_metadata/blob/700f2c7d74543e3695163d5487155b92e6f04d65/importlib_metadata/__init__.py#L809 `distributions(**kwargs)` calls `Distribution.discover(**kwargs)` which expects either a `Context` object or its args for creating one (see https://github.com/python/importlib_metadata/blob/700f2c7d74543e3695163d5487155b92e6f04d65/importlib_metadata/__init__.py#L387 ) All in all, calling `distributions([folder_path])` will retrieve all packages metadata in the given `folder_path` which could be a CLI parameter. What do you think ?
0.0
bd213a57b824bd404436dfb261af1383824b5465
[ "test_piplicenses.py::test_different_python" ]
[ "test_piplicenses.py::PYCODESTYLE", "test_piplicenses.py::TestGetLicenses::test_case_insensitive_set_diff", "test_piplicenses.py::TestGetLicenses::test_case_insensitive_set_intersect", "test_piplicenses.py::TestGetLicenses::test_display_multiple_license_from_classifier", "test_piplicenses.py::TestGetLicenses::test_find_license_from_classifier", "test_piplicenses.py::TestGetLicenses::test_format_confluence", "test_piplicenses.py::TestGetLicenses::test_format_csv", "test_piplicenses.py::TestGetLicenses::test_format_json", "test_piplicenses.py::TestGetLicenses::test_format_json_license_manager", "test_piplicenses.py::TestGetLicenses::test_format_markdown", "test_piplicenses.py::TestGetLicenses::test_format_plain", "test_piplicenses.py::TestGetLicenses::test_format_plain_vertical", "test_piplicenses.py::TestGetLicenses::test_format_rst_default_filter", "test_piplicenses.py::TestGetLicenses::test_from_classifier", "test_piplicenses.py::TestGetLicenses::test_from_meta", "test_piplicenses.py::TestGetLicenses::test_from_mixed", "test_piplicenses.py::TestGetLicenses::test_if_no_classifiers_then_no_licences_found", "test_piplicenses.py::TestGetLicenses::test_ignore_packages", "test_piplicenses.py::TestGetLicenses::test_order_author", "test_piplicenses.py::TestGetLicenses::test_order_license", "test_piplicenses.py::TestGetLicenses::test_order_name", "test_piplicenses.py::TestGetLicenses::test_order_url", "test_piplicenses.py::TestGetLicenses::test_order_url_no_effect", "test_piplicenses.py::TestGetLicenses::test_output_colored_bold", "test_piplicenses.py::TestGetLicenses::test_output_colored_normal", "test_piplicenses.py::TestGetLicenses::test_select_license_by_source", "test_piplicenses.py::TestGetLicenses::test_summary", "test_piplicenses.py::TestGetLicenses::test_summary_sort_by_count", "test_piplicenses.py::TestGetLicenses::test_summary_sort_by_name", "test_piplicenses.py::TestGetLicenses::test_summary_warning", "test_piplicenses.py::TestGetLicenses::test_with_authors", "test_piplicenses.py::TestGetLicenses::test_with_default_filter", "test_piplicenses.py::TestGetLicenses::test_with_description", "test_piplicenses.py::TestGetLicenses::test_with_empty_args", "test_piplicenses.py::TestGetLicenses::test_with_license_file", "test_piplicenses.py::TestGetLicenses::test_with_license_file_no_path", "test_piplicenses.py::TestGetLicenses::test_with_license_file_warning", "test_piplicenses.py::TestGetLicenses::test_with_notice_file", "test_piplicenses.py::TestGetLicenses::test_with_packages", "test_piplicenses.py::TestGetLicenses::test_with_packages_with_system", "test_piplicenses.py::TestGetLicenses::test_with_specified_filter", "test_piplicenses.py::TestGetLicenses::test_with_system", "test_piplicenses.py::TestGetLicenses::test_with_urls", "test_piplicenses.py::TestGetLicenses::test_without_filter", "test_piplicenses.py::test_output_file_success", "test_piplicenses.py::test_output_file_error", "test_piplicenses.py::test_output_file_none", "test_piplicenses.py::test_allow_only", "test_piplicenses.py::test_fail_on", "test_piplicenses.py::test_enums", "test_piplicenses.py::test_verify_args" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-03-21 21:15:37+00:00
mit
5,159
raimon49__pip-licenses-154
diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e60480..1c71659 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ ## CHANGELOG +### 4.2.0 + +* Implement new option `--with-maintainers` +* Implement new option `--python` +* Allow version spec in `--ignore-packages` parameters +* When the `Author` field is `UNKNOWN`, the output is automatically completed from `Author-email` +* When the `home-page` field is `UNKNOWN`, the output is automatically completed from `Project-URL` + ### 4.1.0 * Support case-insensitive license name matching around `--fail-on` and `--allow-only` parameters diff --git a/README.md b/README.md index 7517b50..76855da 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ Dump the software license list of Python packages installed with pip. * [Format options](#format-options) * [Option: with\-system](#option-with-system) * [Option: with\-authors](#option-with-authors) + * [Option: with\-maintainers](#option-with-maintainers) * [Option: with\-urls](#option-with-urls) * [Option: with\-description](#option-with-description) * [Option: with\-license\-file](#option-with-license-file) @@ -429,6 +430,12 @@ When executed with the `--with-authors` option, output with author of the packag pytz 2017.3 MIT Stuart Bishop ``` +#### Option: with-maintainers + +When executed with the `--with-maintainers` option, output with maintainer of the package. + +**Note:** This option is available for users who want information about the maintainer as well as the author. See [#144](https://github.com/raimon49/pip-licenses/issues/144) + #### Option: with-urls For packages without Metadata, the license is output as `UNKNOWN`. To get more package information, use the `--with-urls` option. diff --git a/piplicenses.py b/piplicenses.py index 488c338..90da0b7 100644 --- a/piplicenses.py +++ b/piplicenses.py @@ -49,13 +49,14 @@ from prettytable import NONE as RULE_NONE from prettytable import PrettyTable if TYPE_CHECKING: - from typing import Iterator, Optional, Sequence + from email.message import Message + from typing import Callable, Dict, Iterator, Optional, Sequence open = open # allow monkey patching __pkgname__ = "pip-licenses" -__version__ = "4.1.0" +__version__ = "4.2.0" __author__ = "raimon" __license__ = "MIT" __summary__ = ( @@ -73,6 +74,7 @@ FIELD_NAMES = ( "NoticeFile", "NoticeText", "Author", + "Maintainer", "Description", "URL", ) @@ -95,11 +97,50 @@ SUMMARY_OUTPUT_FIELDS = ( "License", ) -METADATA_KEYS = { - "home-page": ["home-page"], - "author": ["author", "author-email"], - "license": ["license"], - "summary": ["summary"], + +def extract_homepage(metadata: Message) -> Optional[str]: + """Extracts the homepage attribute from the package metadata. + + Not all python packages have defined a home-page attribute. + As a fallback, the `Project-URL` metadata can be used. + The python core metadata supports multiple (free text) values for + the `Project-URL` field that are comma separated. + + Args: + metadata: The package metadata to extract the homepage from. + + Returns: + The home page if applicable, None otherwise. + """ + homepage = metadata.get("home-page", None) + if homepage is not None: + return homepage + + candidates: Dict[str, str] = {} + + for entry in metadata.get_all("Project-URL", []): + key, value = entry.split(",", 1) + candidates[key.strip()] = value.strip() + + for priority_key in ["Homepage", "Source", "Changelog", "Bug Tracker"]: + if priority_key in candidates: + return candidates[priority_key] + + return None + + +METADATA_KEYS: Dict[str, List[Callable[[Message], Optional[str]]]] = { + "home-page": [extract_homepage], + "author": [ + lambda metadata: metadata.get("author"), + lambda metadata: metadata.get("author-email"), + ], + "maintainer": [ + lambda metadata: metadata.get("maintainer"), + lambda metadata: metadata.get("maintainer-email"), + ], + "license": [lambda metadata: metadata.get("license")], + "summary": [lambda metadata: metadata.get("summary")], } # Mapping of FIELD_NAMES to METADATA_KEYS where they differ by more than case @@ -168,10 +209,12 @@ def get_packages( "noticetext": notice_text, } metadata = pkg.metadata - for field_name, field_selectors in METADATA_KEYS.items(): + for field_name, field_selector_fns in METADATA_KEYS.items(): value = None - for selector in field_selectors: - value = metadata.get(selector, None) # type: ignore[attr-defined] # noqa: E501 + for field_selector_fn in field_selector_fns: + # Type hint of `Distribution.metadata` states `PackageMetadata` + # but it's actually of type `email.Message` + value = field_selector_fn(metadata) # type: ignore if value: break pkg_info[field_name] = value or LICENSE_UNKNOWN @@ -542,6 +585,9 @@ def get_output_fields(args: CustomNamespace) -> list[str]: if args.with_authors: output_fields.append("Author") + if args.with_maintainers: + output_fields.append("Maintainer") + if args.with_urls: output_fields.append("URL") @@ -571,6 +617,8 @@ def get_sortby(args: CustomNamespace) -> str: return "Name" elif args.order == OrderArg.AUTHOR and args.with_authors: return "Author" + elif args.order == OrderArg.MAINTAINER and args.with_maintainers: + return "Maintainer" elif args.order == OrderArg.URL and args.with_urls: return "URL" @@ -739,6 +787,7 @@ class OrderArg(NoValueEnum): LICENSE = L = auto() NAME = N = auto() AUTHOR = A = auto() + MAINTAINER = M = auto() URL = U = auto() @@ -897,6 +946,12 @@ def create_parser() -> CompatibleArgumentParser: default=False, help="dump with package authors", ) + format_options.add_argument( + "--with-maintainers", + action="store_true", + default=False, + help="dump with package maintainers", + ) format_options.add_argument( "-u", "--with-urls",
raimon49/pip-licenses
8b38914671b783c214b8c7539af8c4531f861fc0
diff --git a/test_piplicenses.py b/test_piplicenses.py index 426f31a..674cf83 100644 --- a/test_piplicenses.py +++ b/test_piplicenses.py @@ -13,6 +13,7 @@ from enum import Enum, auto from importlib.metadata import Distribution from types import SimpleNamespace from typing import TYPE_CHECKING, Any, List +from unittest.mock import MagicMock import docutils.frontend import docutils.parsers.rst @@ -39,6 +40,7 @@ from piplicenses import ( create_parser, create_warn_string, enum_key_to_value, + extract_homepage, factory_styled_table_with_args, find_license_from_classifier, get_output_fields, @@ -309,6 +311,17 @@ class TestGetLicenses(CommandLineTestCase): output_string = create_output_string(args) self.assertIn("Author", output_string) + def test_with_maintainers(self) -> None: + with_maintainers_args = ["--with-maintainers"] + args = self.parser.parse_args(with_maintainers_args) + + output_fields = get_output_fields(args) + self.assertNotEqual(output_fields, list(DEFAULT_OUTPUT_FIELDS)) + self.assertIn("Maintainer", output_fields) + + output_string = create_output_string(args) + self.assertIn("Maintainer", output_string) + def test_with_urls(self) -> None: with_urls_args = ["--with-urls"] args = self.parser.parse_args(with_urls_args) @@ -394,17 +407,32 @@ class TestGetLicenses(CommandLineTestCase): self.assertIn("best paired with --format=json", warn_string) def test_ignore_packages(self) -> None: - if "PTable" in SYSTEM_PACKAGES: - ignore_pkg_name = "PTable" - else: - ignore_pkg_name = "prettytable" - ignore_packages_args = ["--ignore-package=" + ignore_pkg_name] + ignore_pkg_name = "prettytable" + ignore_packages_args = [ + "--ignore-package=" + ignore_pkg_name, + "--with-system", + ] args = self.parser.parse_args(ignore_packages_args) table = create_licenses_table(args) pkg_name_columns = self._create_pkg_name_columns(table) self.assertNotIn(ignore_pkg_name, pkg_name_columns) + def test_ignore_packages_and_version(self) -> None: + # Fictitious version that does not exist + ignore_pkg_name = "prettytable" + ignore_pkg_spec = ignore_pkg_name + ":1.99.99" + ignore_packages_args = [ + "--ignore-package=" + ignore_pkg_spec, + "--with-system", + ] + args = self.parser.parse_args(ignore_packages_args) + table = create_licenses_table(args) + + pkg_name_columns = self._create_pkg_name_columns(table) + # It is expected that prettytable will include + self.assertIn(ignore_pkg_name, pkg_name_columns) + def test_with_packages(self) -> None: pkg_name = "py" only_packages_args = ["--packages=" + pkg_name] @@ -415,10 +443,7 @@ class TestGetLicenses(CommandLineTestCase): self.assertListEqual([pkg_name], pkg_name_columns) def test_with_packages_with_system(self) -> None: - if "PTable" in SYSTEM_PACKAGES: - pkg_name = "PTable" - else: - pkg_name = "prettytable" + pkg_name = "prettytable" only_packages_args = ["--packages=" + pkg_name, "--with-system"] args = self.parser.parse_args(only_packages_args) table = create_licenses_table(args) @@ -447,6 +472,13 @@ class TestGetLicenses(CommandLineTestCase): sortby = get_sortby(args) self.assertEqual("Author", sortby) + def test_order_maintainer(self) -> None: + order_maintainer_args = ["--order=maintainer", "--with-maintainers"] + args = self.parser.parse_args(order_maintainer_args) + + sortby = get_sortby(args) + self.assertEqual("Maintainer", sortby) + def test_order_url(self) -> None: order_url_args = ["--order=url", "--with-urls"] args = self.parser.parse_args(order_url_args) @@ -875,3 +907,56 @@ def test_verify_args( capture = capsys.readouterr().err for arg in ("invalid code", "--filter-code-page"): assert arg in capture + + +def test_extract_homepage_home_page_set() -> None: + metadata = MagicMock() + metadata.get.return_value = "Foobar" + + assert "Foobar" == extract_homepage(metadata=metadata) # type: ignore + + metadata.get.assert_called_once_with("home-page", None) + + +def test_extract_homepage_project_url_fallback() -> None: + metadata = MagicMock() + metadata.get.return_value = None + + # `Homepage` is prioritized higher than `Source` + metadata.get_all.return_value = [ + "Source, source", + "Homepage, homepage", + ] + + assert "homepage" == extract_homepage(metadata=metadata) # type: ignore + + metadata.get_all.assert_called_once_with("Project-URL", []) + + +def test_extract_homepage_project_url_fallback_multiple_parts() -> None: + metadata = MagicMock() + metadata.get.return_value = None + + # `Homepage` is prioritized higher than `Source` + metadata.get_all.return_value = [ + "Source, source", + "Homepage, homepage, foo, bar", + ] + + assert "homepage, foo, bar" == extract_homepage( + metadata=metadata # type: ignore + ) + + metadata.get_all.assert_called_once_with("Project-URL", []) + + +def test_extract_homepage_empty() -> None: + metadata = MagicMock() + + metadata.get.return_value = None + metadata.get_all.return_value = [] + + assert None is extract_homepage(metadata=metadata) # type: ignore + + metadata.get.assert_called_once_with("home-page", None) + metadata.get_all.assert_called_once_with("Project-URL", [])
Expose maintainers Some packages do not have the `author` field set, but the `maintainer` one (example: https://github.com/opencv/opencv-python/blob/b776e5ce9f164600a1bd05178a058272122bf02a/setup.py#L272). Exposing the maintainer as well would allow users to work with the maintainer value if the author value would be empty otherwise.
0.0
8b38914671b783c214b8c7539af8c4531f861fc0
[ "test_piplicenses.py::PYCODESTYLE", "test_piplicenses.py::TestGetLicenses::test_case_insensitive_set_diff", "test_piplicenses.py::TestGetLicenses::test_case_insensitive_set_intersect", "test_piplicenses.py::TestGetLicenses::test_display_multiple_license_from_classifier", "test_piplicenses.py::TestGetLicenses::test_find_license_from_classifier", "test_piplicenses.py::TestGetLicenses::test_format_confluence", "test_piplicenses.py::TestGetLicenses::test_format_csv", "test_piplicenses.py::TestGetLicenses::test_format_json", "test_piplicenses.py::TestGetLicenses::test_format_json_license_manager", "test_piplicenses.py::TestGetLicenses::test_format_markdown", "test_piplicenses.py::TestGetLicenses::test_format_plain", "test_piplicenses.py::TestGetLicenses::test_format_plain_vertical", "test_piplicenses.py::TestGetLicenses::test_format_rst_default_filter", "test_piplicenses.py::TestGetLicenses::test_from_classifier", "test_piplicenses.py::TestGetLicenses::test_from_meta", "test_piplicenses.py::TestGetLicenses::test_from_mixed", "test_piplicenses.py::TestGetLicenses::test_if_no_classifiers_then_no_licences_found", "test_piplicenses.py::TestGetLicenses::test_ignore_packages", "test_piplicenses.py::TestGetLicenses::test_ignore_packages_and_version", "test_piplicenses.py::TestGetLicenses::test_order_author", "test_piplicenses.py::TestGetLicenses::test_order_license", "test_piplicenses.py::TestGetLicenses::test_order_maintainer", "test_piplicenses.py::TestGetLicenses::test_order_name", "test_piplicenses.py::TestGetLicenses::test_order_url", "test_piplicenses.py::TestGetLicenses::test_order_url_no_effect", "test_piplicenses.py::TestGetLicenses::test_output_colored_bold", "test_piplicenses.py::TestGetLicenses::test_output_colored_normal", "test_piplicenses.py::TestGetLicenses::test_select_license_by_source", "test_piplicenses.py::TestGetLicenses::test_summary", "test_piplicenses.py::TestGetLicenses::test_summary_sort_by_count", "test_piplicenses.py::TestGetLicenses::test_summary_sort_by_name", "test_piplicenses.py::TestGetLicenses::test_summary_warning", "test_piplicenses.py::TestGetLicenses::test_with_authors", "test_piplicenses.py::TestGetLicenses::test_with_default_filter", "test_piplicenses.py::TestGetLicenses::test_with_description", "test_piplicenses.py::TestGetLicenses::test_with_empty_args", "test_piplicenses.py::TestGetLicenses::test_with_license_file", "test_piplicenses.py::TestGetLicenses::test_with_license_file_no_path", "test_piplicenses.py::TestGetLicenses::test_with_license_file_warning", "test_piplicenses.py::TestGetLicenses::test_with_maintainers", "test_piplicenses.py::TestGetLicenses::test_with_notice_file", "test_piplicenses.py::TestGetLicenses::test_with_packages", "test_piplicenses.py::TestGetLicenses::test_with_packages_with_system", "test_piplicenses.py::TestGetLicenses::test_with_specified_filter", "test_piplicenses.py::TestGetLicenses::test_with_system", "test_piplicenses.py::TestGetLicenses::test_with_urls", "test_piplicenses.py::TestGetLicenses::test_without_filter", "test_piplicenses.py::test_output_file_success", "test_piplicenses.py::test_output_file_error", "test_piplicenses.py::test_output_file_none", "test_piplicenses.py::test_allow_only", "test_piplicenses.py::test_different_python", "test_piplicenses.py::test_fail_on", "test_piplicenses.py::test_enums", "test_piplicenses.py::test_verify_args", "test_piplicenses.py::test_extract_homepage_home_page_set", "test_piplicenses.py::test_extract_homepage_project_url_fallback", "test_piplicenses.py::test_extract_homepage_project_url_fallback_multiple_parts", "test_piplicenses.py::test_extract_homepage_empty" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-04-02 00:43:54+00:00
mit
5,160
raimon49__pip-licenses-161
diff --git a/CHANGELOG.md b/CHANGELOG.md index b68843f..787f72f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## CHANGELOG +### 4.3.1 + +* Fix to treat package names as normalized as in [PEP 503](https://peps.python.org/pep-0503/) with `--packages` and `--ignore-packages` option + ### 4.3.0 * Implement new option `--no-version` diff --git a/piplicenses.py b/piplicenses.py index 44e8798..ed028b1 100644 --- a/piplicenses.py +++ b/piplicenses.py @@ -56,7 +56,7 @@ if TYPE_CHECKING: open = open # allow monkey patching __pkgname__ = "pip-licenses" -__version__ = "4.3.0" +__version__ = "4.3.1" __author__ = "raimon" __license__ = "MIT" __summary__ = ( @@ -129,6 +129,24 @@ def extract_homepage(metadata: Message) -> Optional[str]: return None +PATTERN_DELIMITER = re.compile(r"[-_.]+") + + +def normalize_pkg_name(pkg_name: str) -> str: + """Return normalized name according to PEP specification + + See here: https://peps.python.org/pep-0503/#normalized-names + + Args: + pkg_name: Package name it is extracted from the package metadata + or specified in the CLI + + Returns: + normalized packege name + """ + return PATTERN_DELIMITER.sub("-", pkg_name).lower() + + METADATA_KEYS: Dict[str, List[Callable[[Message], Optional[str]]]] = { "home-page": [extract_homepage], "author": [ @@ -254,8 +272,10 @@ def get_packages( search_paths = get_python_sys_path(args.python) pkgs = importlib_metadata.distributions(path=search_paths) - ignore_pkgs_as_lower = [pkg.lower() for pkg in args.ignore_packages] - pkgs_as_lower = [pkg.lower() for pkg in args.packages] + ignore_pkgs_as_normalize = [ + normalize_pkg_name(pkg) for pkg in args.ignore_packages + ] + pkgs_as_normalize = [normalize_pkg_name(pkg) for pkg in args.packages] fail_on_licenses = set() if args.fail_on: @@ -266,16 +286,16 @@ def get_packages( allow_only_licenses = set(map(str.strip, args.allow_only.split(";"))) for pkg in pkgs: - pkg_name = pkg.metadata["name"] + pkg_name = normalize_pkg_name(pkg.metadata["name"]) pkg_name_and_version = pkg_name + ":" + pkg.metadata["version"] if ( - pkg_name.lower() in ignore_pkgs_as_lower - or pkg_name_and_version.lower() in ignore_pkgs_as_lower + pkg_name.lower() in ignore_pkgs_as_normalize + or pkg_name_and_version.lower() in ignore_pkgs_as_normalize ): continue - if pkgs_as_lower and pkg_name.lower() not in pkgs_as_lower: + if pkgs_as_normalize and pkg_name.lower() not in pkgs_as_normalize: continue if not args.with_system and pkg_name in SYSTEM_PACKAGES:
raimon49/pip-licenses
925933da61c810b935ef143ecea881e94657dd16
diff --git a/test_piplicenses.py b/test_piplicenses.py index 0ac2394..f8cba9b 100644 --- a/test_piplicenses.py +++ b/test_piplicenses.py @@ -46,6 +46,7 @@ from piplicenses import ( get_output_fields, get_packages, get_sortby, + normalize_pkg_name, output_colored, save_if_needs, select_license_by_source, @@ -429,6 +430,18 @@ class TestGetLicenses(CommandLineTestCase): pkg_name_columns = self._create_pkg_name_columns(table) self.assertNotIn(ignore_pkg_name, pkg_name_columns) + def test_ignore_normalized_packages(self) -> None: + ignore_pkg_name = "pip-licenses" + ignore_packages_args = [ + "--ignore-package=pip_licenses", + "--with-system", + ] + args = self.parser.parse_args(ignore_packages_args) + table = create_licenses_table(args) + + pkg_name_columns = self._create_pkg_name_columns(table) + self.assertNotIn(ignore_pkg_name, pkg_name_columns) + def test_ignore_packages_and_version(self) -> None: # Fictitious version that does not exist ignore_pkg_name = "prettytable" @@ -453,6 +466,18 @@ class TestGetLicenses(CommandLineTestCase): pkg_name_columns = self._create_pkg_name_columns(table) self.assertListEqual([pkg_name], pkg_name_columns) + def test_with_normalized_packages(self) -> None: + pkg_name = "typing_extensions" + only_packages_args = [ + "--package=typing-extensions", + "--with-system", + ] + args = self.parser.parse_args(only_packages_args) + table = create_licenses_table(args) + + pkg_name_columns = self._create_pkg_name_columns(table) + self.assertListEqual([pkg_name], pkg_name_columns) + def test_with_packages_with_system(self) -> None: pkg_name = "prettytable" only_packages_args = ["--packages=" + pkg_name, "--with-system"] @@ -920,6 +945,14 @@ def test_verify_args( assert arg in capture +def test_normalize_pkg_name() -> None: + expected_normalized_name = "pip-licenses" + + assert normalize_pkg_name("pip_licenses") == expected_normalized_name + assert normalize_pkg_name("pip.licenses") == expected_normalized_name + assert normalize_pkg_name("Pip-Licenses") == expected_normalized_name + + def test_extract_homepage_home_page_set() -> None: metadata = MagicMock() metadata.get.return_value = "Foobar"
Treat `-` and `_` as equivalent in package names `pip` treats `-` and `_` as equivalent, but `pip-licenses` differentiates between the two when using the `-p` flag. Having `pip-licenses` also treat `-` and `_` as equivalent makes it easier to work with. In my particular use case, I have a venv that contains packages from a `requirements.txt` and also additional packages that I don't want licenses of. I then passed the packages in the `requirements.txt` to `pip-licenses -p` and was surprised when the license for `typing-extensions` wasn't found. However, passing `typing_extensions` instead to `pip-licenses` works. `requirements.txt` in this form can be created from, e.g. `pipenv requirements`.
0.0
925933da61c810b935ef143ecea881e94657dd16
[ "test_piplicenses.py::PYCODESTYLE", "test_piplicenses.py::TestGetLicenses::test_case_insensitive_set_diff", "test_piplicenses.py::TestGetLicenses::test_case_insensitive_set_intersect", "test_piplicenses.py::TestGetLicenses::test_display_multiple_license_from_classifier", "test_piplicenses.py::TestGetLicenses::test_find_license_from_classifier", "test_piplicenses.py::TestGetLicenses::test_format_confluence", "test_piplicenses.py::TestGetLicenses::test_format_csv", "test_piplicenses.py::TestGetLicenses::test_format_json", "test_piplicenses.py::TestGetLicenses::test_format_json_license_manager", "test_piplicenses.py::TestGetLicenses::test_format_markdown", "test_piplicenses.py::TestGetLicenses::test_format_plain", "test_piplicenses.py::TestGetLicenses::test_format_plain_vertical", "test_piplicenses.py::TestGetLicenses::test_format_rst_default_filter", "test_piplicenses.py::TestGetLicenses::test_from_classifier", "test_piplicenses.py::TestGetLicenses::test_from_meta", "test_piplicenses.py::TestGetLicenses::test_from_mixed", "test_piplicenses.py::TestGetLicenses::test_if_no_classifiers_then_no_licences_found", "test_piplicenses.py::TestGetLicenses::test_ignore_normalized_packages", "test_piplicenses.py::TestGetLicenses::test_ignore_packages", "test_piplicenses.py::TestGetLicenses::test_ignore_packages_and_version", "test_piplicenses.py::TestGetLicenses::test_order_author", "test_piplicenses.py::TestGetLicenses::test_order_license", "test_piplicenses.py::TestGetLicenses::test_order_maintainer", "test_piplicenses.py::TestGetLicenses::test_order_name", "test_piplicenses.py::TestGetLicenses::test_order_url", "test_piplicenses.py::TestGetLicenses::test_order_url_no_effect", "test_piplicenses.py::TestGetLicenses::test_output_colored_bold", "test_piplicenses.py::TestGetLicenses::test_output_colored_normal", "test_piplicenses.py::TestGetLicenses::test_select_license_by_source", "test_piplicenses.py::TestGetLicenses::test_summary", "test_piplicenses.py::TestGetLicenses::test_summary_sort_by_count", "test_piplicenses.py::TestGetLicenses::test_summary_sort_by_name", "test_piplicenses.py::TestGetLicenses::test_summary_warning", "test_piplicenses.py::TestGetLicenses::test_with_authors", "test_piplicenses.py::TestGetLicenses::test_with_default_filter", "test_piplicenses.py::TestGetLicenses::test_with_description", "test_piplicenses.py::TestGetLicenses::test_with_empty_args", "test_piplicenses.py::TestGetLicenses::test_with_license_file", "test_piplicenses.py::TestGetLicenses::test_with_license_file_no_path", "test_piplicenses.py::TestGetLicenses::test_with_license_file_warning", "test_piplicenses.py::TestGetLicenses::test_with_maintainers", "test_piplicenses.py::TestGetLicenses::test_with_normalized_packages", "test_piplicenses.py::TestGetLicenses::test_with_notice_file", "test_piplicenses.py::TestGetLicenses::test_with_packages", "test_piplicenses.py::TestGetLicenses::test_with_packages_with_system", "test_piplicenses.py::TestGetLicenses::test_with_specified_filter", "test_piplicenses.py::TestGetLicenses::test_with_system", "test_piplicenses.py::TestGetLicenses::test_with_urls", "test_piplicenses.py::TestGetLicenses::test_without_filter", "test_piplicenses.py::TestGetLicenses::test_without_version", "test_piplicenses.py::test_output_file_success", "test_piplicenses.py::test_output_file_error", "test_piplicenses.py::test_output_file_none", "test_piplicenses.py::test_allow_only", "test_piplicenses.py::test_different_python", "test_piplicenses.py::test_fail_on", "test_piplicenses.py::test_enums", "test_piplicenses.py::test_verify_args", "test_piplicenses.py::test_normalize_pkg_name", "test_piplicenses.py::test_extract_homepage_home_page_set", "test_piplicenses.py::test_extract_homepage_project_url_fallback", "test_piplicenses.py::test_extract_homepage_project_url_fallback_multiple_parts", "test_piplicenses.py::test_extract_homepage_empty" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-04 02:26:08+00:00
mit
5,161
raimon49__pip-licenses-186
diff --git a/README.md b/README.md index 1d03eae..0c5a795 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ Dump the software license list of Python packages installed with pip. * [Verify options](#verify-options) * [Option: fail\-on](#option-fail-on) * [Option: allow\-only](#option-allow-only) + * [Option: partial\-match](#option-partial-match) * [More Information](#more-information) * [Dockerfile](#dockerfile) * [About UnicodeEncodeError](#about-unicodeencodeerror) @@ -545,6 +546,49 @@ $ echo $? 1 ``` +#### Option: partial\-match + +If set, enables partial (substring) matching for `--fail-on` or `--allow-only`. Default is unset (False). + +Usage: + +```bash +(venv) $ pip-licenses --partial-match --allow-only="MIT License;BSD License" +(venv) $ pip-licenses --partial-match --fail-on="MIT License;BSD License" + +``` + +**Note:** Semantics are the same as with `--fail-on` or `--allow-only`. This only enables substring matching. +``` +# keyring library has 2 licenses +$ pip-licenses --package keyring + Name Version License + keyring 23.0.1 MIT License; Python Software Foundation License + +# One or both licenses must be specified (order and case does not matter). Following checks will pass: +$ pip-licenses --package keyring --allow-only="MIT License" +$ pip-licenses --package keyring --allow-only="mit License" +$ pip-licenses --package keyring --allow-only="BSD License;MIT License" +$ pip-licenses --package keyring --allow-only="Python Software Foundation License" +$ pip-licenses --package keyring --allow-only="Python Software Foundation License;MIT License" + +# These won't pass, as they're not a full match against one of the licenses +$ pip-licenses --package keyring --allow-only="MIT" +$ echo $? +1 +$ pip-licenses --package keyring --allow-only="mit" +$ echo $? +1 + +# with --partial-match, they pass +$ pip-licenses --package keyring --partial-match --allow-only="MIT" +$ echo $? +0 +$ pip-licenses --package keyring --partial-match --allow-only="mit" +$ echo $? +0 +``` + ### More Information diff --git a/piplicenses.py b/piplicenses.py old mode 100644 new mode 100755 index b8def73..65c5779 --- a/piplicenses.py +++ b/piplicenses.py @@ -316,9 +316,15 @@ def get_packages( ) if fail_on_licenses: - failed_licenses = case_insensitive_set_intersect( - license_names, fail_on_licenses - ) + failed_licenses = set() + if not args.partial_match: + failed_licenses = case_insensitive_set_intersect( + license_names, fail_on_licenses + ) + else: + failed_licenses = case_insensitive_partial_match_set_intersect( + license_names, fail_on_licenses + ) if failed_licenses: sys.stderr.write( "fail-on license {} was found for package " @@ -331,9 +337,16 @@ def get_packages( sys.exit(1) if allow_only_licenses: - uncommon_licenses = case_insensitive_set_diff( - license_names, allow_only_licenses - ) + uncommon_licenses = set() + if not args.partial_match: + uncommon_licenses = case_insensitive_set_diff( + license_names, allow_only_licenses + ) + else: + uncommon_licenses = case_insensitive_partial_match_set_diff( + license_names, allow_only_licenses + ) + if len(uncommon_licenses) == len(license_names): sys.stderr.write( "license {} not in allow-only licenses was found" @@ -409,6 +422,24 @@ def case_insensitive_set_intersect(set_a, set_b): return common_items +def case_insensitive_partial_match_set_intersect(set_a, set_b): + common_items = set() + for item_a in set_a: + for item_b in set_b: + if item_b.lower() in item_a.lower(): + common_items.add(item_a) + return common_items + + +def case_insensitive_partial_match_set_diff(set_a, set_b): + uncommon_items = set_a.copy() + for item_a in set_a: + for item_b in set_b: + if item_b.lower() in item_a.lower(): + uncommon_items.remove(item_a) + return uncommon_items + + def case_insensitive_set_diff(set_a, set_b): """Same as set.difference() but case-insensitive""" uncommon_items = set() @@ -761,6 +792,7 @@ class CustomNamespace(argparse.Namespace): with_notice_file: bool filter_strings: bool filter_code_page: str + partial_match: bool fail_on: Optional[str] allow_only: Optional[str] @@ -1055,6 +1087,12 @@ def create_parser() -> CompatibleArgumentParser: help="fail (exit with code 1) on the first occurrence " "of the licenses not in the semicolon-separated list", ) + verify_options.add_argument( + "--partial-match", + action="store_true", + default=False, + help="enables partial matching for --allow-only/--fail-on", + ) return parser
raimon49/pip-licenses
6ab64cd48d642df313e37728681646f5fc0242d1
diff --git a/test_piplicenses.py b/test_piplicenses.py index 5a704b1..34ff75f 100644 --- a/test_piplicenses.py +++ b/test_piplicenses.py @@ -33,6 +33,8 @@ from piplicenses import ( CompatibleArgumentParser, FromArg, __pkgname__, + case_insensitive_partial_match_set_diff, + case_insensitive_partial_match_set_intersect, case_insensitive_set_diff, case_insensitive_set_intersect, create_licenses_table, @@ -769,6 +771,42 @@ class TestGetLicenses(CommandLineTestCase): self.assertTrue({"revised BSD"} == b_intersect_c) self.assertTrue(len(a_intersect_empty) == 0) + def test_case_insensitive_partial_match_set_diff(self) -> None: + set_a = {"MIT License"} + set_b = {"Mit", "BSD License"} + set_c = {"mit license"} + a_diff_b = case_insensitive_partial_match_set_diff(set_a, set_b) + a_diff_c = case_insensitive_partial_match_set_diff(set_a, set_c) + b_diff_c = case_insensitive_partial_match_set_diff(set_b, set_c) + a_diff_empty = case_insensitive_partial_match_set_diff(set_a, set()) + + self.assertTrue(len(a_diff_b) == 0) + self.assertTrue(len(a_diff_c) == 0) + self.assertIn("BSD License", b_diff_c) + self.assertIn("MIT License", a_diff_empty) + + def test_case_insensitive_partial_match_set_intersect(self) -> None: + set_a = {"Revised BSD"} + set_b = {"Apache License", "revised BSD"} + set_c = {"bsd"} + a_intersect_b = case_insensitive_partial_match_set_intersect( + set_a, set_b + ) + a_intersect_c = case_insensitive_partial_match_set_intersect( + set_a, set_c + ) + b_intersect_c = case_insensitive_partial_match_set_intersect( + set_b, set_c + ) + a_intersect_empty = case_insensitive_partial_match_set_intersect( + set_a, set() + ) + + self.assertTrue(set_a == a_intersect_b) + self.assertTrue(set_a == a_intersect_c) + self.assertTrue({"revised BSD"} == b_intersect_c) + self.assertTrue(len(a_intersect_empty) == 0) + class MockStdStream(object): def __init__(self) -> None: @@ -850,6 +888,35 @@ def test_allow_only(monkeypatch) -> None: ) +def test_allow_only_partial(monkeypatch) -> None: + licenses = ( + "Bsd", + "Apache", + "Mozilla Public License 2.0 (MPL 2.0)", + "Python Software Foundation License", + "Public Domain", + "GNU General Public License (GPL)", + "GNU Library or Lesser General Public License (LGPL)", + ) + allow_only_args = [ + "--partial-match", + "--allow-only={}".format(";".join(licenses)), + ] + mocked_stdout = MockStdStream() + mocked_stderr = MockStdStream() + monkeypatch.setattr(sys.stdout, "write", mocked_stdout.write) + monkeypatch.setattr(sys.stderr, "write", mocked_stderr.write) + monkeypatch.setattr(sys, "exit", lambda n: None) + args = create_parser().parse_args(allow_only_args) + create_licenses_table(args) + + assert "" == mocked_stdout.printed + assert ( + "license MIT License not in allow-only licenses was found for " + "package" in mocked_stderr.printed + ) + + def test_different_python() -> None: import tempfile @@ -891,6 +958,27 @@ def test_fail_on(monkeypatch) -> None: ) +def test_fail_on_partial_match(monkeypatch) -> None: + licenses = ("MIT",) + allow_only_args = [ + "--partial-match", + "--fail-on={}".format(";".join(licenses)), + ] + mocked_stdout = MockStdStream() + mocked_stderr = MockStdStream() + monkeypatch.setattr(sys.stdout, "write", mocked_stdout.write) + monkeypatch.setattr(sys.stderr, "write", mocked_stderr.write) + monkeypatch.setattr(sys, "exit", lambda n: None) + args = create_parser().parse_args(allow_only_args) + create_licenses_table(args) + + assert "" == mocked_stdout.printed + assert ( + "fail-on license MIT License was found for " + "package" in mocked_stderr.printed + ) + + def test_enums() -> None: class TestEnum(Enum): PLAIN = P = auto()
Consider enabling partial matching for licenses Hello, there are use cases, where partial matching on license name could be beneficial, such as when one would like to match all versions of a license - say BSD or GPL or GPLv3 vs GPLv3+. Consider adding a way to enable partial matching against licenses, as a non-default option, to ease maintenance of long licenses allow/block lists. Thanks!
0.0
6ab64cd48d642df313e37728681646f5fc0242d1
[ "test_piplicenses.py::PYCODESTYLE", "test_piplicenses.py::TestGetLicenses::test_case_insensitive_partial_match_set_diff", "test_piplicenses.py::TestGetLicenses::test_case_insensitive_partial_match_set_intersect", "test_piplicenses.py::TestGetLicenses::test_case_insensitive_set_diff", "test_piplicenses.py::TestGetLicenses::test_case_insensitive_set_intersect", "test_piplicenses.py::TestGetLicenses::test_display_multiple_license_from_classifier", "test_piplicenses.py::TestGetLicenses::test_find_license_from_classifier", "test_piplicenses.py::TestGetLicenses::test_format_confluence", "test_piplicenses.py::TestGetLicenses::test_format_csv", "test_piplicenses.py::TestGetLicenses::test_format_json", "test_piplicenses.py::TestGetLicenses::test_format_json_license_manager", "test_piplicenses.py::TestGetLicenses::test_format_markdown", "test_piplicenses.py::TestGetLicenses::test_format_plain", "test_piplicenses.py::TestGetLicenses::test_format_plain_vertical", "test_piplicenses.py::TestGetLicenses::test_format_rst_default_filter", "test_piplicenses.py::TestGetLicenses::test_format_rst_without_filter", "test_piplicenses.py::TestGetLicenses::test_from_classifier", "test_piplicenses.py::TestGetLicenses::test_from_meta", "test_piplicenses.py::TestGetLicenses::test_from_mixed", "test_piplicenses.py::TestGetLicenses::test_if_no_classifiers_then_no_licences_found", "test_piplicenses.py::TestGetLicenses::test_ignore_normalized_packages", "test_piplicenses.py::TestGetLicenses::test_ignore_packages", "test_piplicenses.py::TestGetLicenses::test_ignore_packages_and_version", "test_piplicenses.py::TestGetLicenses::test_order_author", "test_piplicenses.py::TestGetLicenses::test_order_license", "test_piplicenses.py::TestGetLicenses::test_order_maintainer", "test_piplicenses.py::TestGetLicenses::test_order_name", "test_piplicenses.py::TestGetLicenses::test_order_url", "test_piplicenses.py::TestGetLicenses::test_order_url_no_effect", "test_piplicenses.py::TestGetLicenses::test_output_colored_bold", "test_piplicenses.py::TestGetLicenses::test_output_colored_normal", "test_piplicenses.py::TestGetLicenses::test_select_license_by_source", "test_piplicenses.py::TestGetLicenses::test_summary", "test_piplicenses.py::TestGetLicenses::test_summary_sort_by_count", "test_piplicenses.py::TestGetLicenses::test_summary_sort_by_name", "test_piplicenses.py::TestGetLicenses::test_summary_warning", "test_piplicenses.py::TestGetLicenses::test_with_authors", "test_piplicenses.py::TestGetLicenses::test_with_default_filter", "test_piplicenses.py::TestGetLicenses::test_with_description", "test_piplicenses.py::TestGetLicenses::test_with_empty_args", "test_piplicenses.py::TestGetLicenses::test_with_license_file", "test_piplicenses.py::TestGetLicenses::test_with_license_file_no_path", "test_piplicenses.py::TestGetLicenses::test_with_license_file_warning", "test_piplicenses.py::TestGetLicenses::test_with_maintainers", "test_piplicenses.py::TestGetLicenses::test_with_normalized_packages", "test_piplicenses.py::TestGetLicenses::test_with_notice_file", "test_piplicenses.py::TestGetLicenses::test_with_packages", "test_piplicenses.py::TestGetLicenses::test_with_packages_with_system", "test_piplicenses.py::TestGetLicenses::test_with_specified_filter", "test_piplicenses.py::TestGetLicenses::test_with_system", "test_piplicenses.py::TestGetLicenses::test_with_urls", "test_piplicenses.py::TestGetLicenses::test_without_filter", "test_piplicenses.py::TestGetLicenses::test_without_version", "test_piplicenses.py::test_output_file_success", "test_piplicenses.py::test_output_file_error", "test_piplicenses.py::test_output_file_none", "test_piplicenses.py::test_allow_only", "test_piplicenses.py::test_allow_only_partial", "test_piplicenses.py::test_different_python", "test_piplicenses.py::test_fail_on", "test_piplicenses.py::test_fail_on_partial_match", "test_piplicenses.py::test_enums", "test_piplicenses.py::test_verify_args", "test_piplicenses.py::test_normalize_pkg_name", "test_piplicenses.py::test_extract_homepage_home_page_set", "test_piplicenses.py::test_extract_homepage_project_url_fallback", "test_piplicenses.py::test_extract_homepage_project_url_fallback_multiple_parts", "test_piplicenses.py::test_extract_homepage_empty", "test_piplicenses.py::test_extract_homepage_project_uprl_fallback_capitalisation" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-03-26 22:28:40+00:00
mit
5,162
ramonhagenaars__barentsz-4
diff --git a/barentsz/_discover.py b/barentsz/_discover.py index c3e915e..4671539 100644 --- a/barentsz/_discover.py +++ b/barentsz/_discover.py @@ -25,6 +25,7 @@ from typish import ( ) from barentsz._attribute import Attribute +from barentsz._typings import exclude_pred from barentsz._here import here @@ -165,7 +166,7 @@ def discover_classes( include_privates: bool = False, in_private_modules: bool = False, raise_on_fail: bool = False, - exclude: Union[Iterable[type], type] = None + exclude: Union[type, exclude_pred, Iterable[Union[type, exclude_pred]]] = None ) -> List[type]: """ Discover any classes within the given source and according to the given @@ -178,8 +179,8 @@ def discover_classes( in_private_modules: if True, private modules are explored as well. raise_on_fail: if True, raises an ImportError upon the first import failure. - exclude: a type or multiple types that are to be excluded from the - result. + exclude: one or more types or predicates that are to be excluded + from the result. Returns: a list of all discovered classes (types). @@ -190,6 +191,9 @@ def discover_classes( result = list({cls for cls in elements if (signature is Any or subclass_of(cls, signature)) and cls not in exclude_}) + exclude_predicates = [e for e in exclude_ if inspect.isfunction(e)] + for pred in exclude_predicates: + result = [cls for cls in result if not pred(cls)] result.sort(key=lambda cls: cls.__name__) return result diff --git a/barentsz/_typings.py b/barentsz/_typings.py new file mode 100644 index 0000000..454d94b --- /dev/null +++ b/barentsz/_typings.py @@ -0,0 +1,3 @@ +from typing import Callable + +exclude_pred = Callable[[type], bool]
ramonhagenaars/barentsz
5591825299b4a1c2176f5af28feec89b5e21ad64
diff --git a/tests/test_discover_classes.py b/tests/test_discover_classes.py index c2fc32a..86bf9bc 100644 --- a/tests/test_discover_classes.py +++ b/tests/test_discover_classes.py @@ -80,7 +80,7 @@ class TestDiscoverClasses(TestCase): with self.assertRaises(ValueError): discover_classes(123) - def test_discover_classes_with_exclusions(self): + def test_discover_classes_with_type_exclusions(self): # SETUP path_to_resources = (Path(__file__).parent.parent / 'test_resources' / 'examples_for_tests') @@ -94,3 +94,19 @@ class TestDiscoverClasses(TestCase): self.assertIn(Class1_level2, classes1) self.assertEqual(1, len(classes2)) self.assertIn(Class1_level2, classes2) + + def test_discover_classes_with_predicate_exclusions(self): + # SETUP + path_to_resources = (Path(__file__).parent.parent / 'test_resources' + / 'examples_for_tests') + + def _name_is_class1(cls: type) -> bool: + return cls.__name__.lower() == 'class1' + + # EXECUTE + classes1 = discover_classes(path_to_resources, exclude=_name_is_class1) + classes2 = discover_classes(path_to_resources, exclude=[_name_is_class1]) + + # VERIFY + self.assertEqual(0, len(classes1)) + self.assertEqual(0, len(classes2))
Feature request: filtering out abstract classes While developing a certain machine learning game, I "discovered" ;) that it would be very useful to have the option to automatically filter out abstract classes when using `discover_classes`. I would imagine a parameter `exclude_abstract` with default value `False`. I might just write a PR for this myself :)
0.0
5591825299b4a1c2176f5af28feec89b5e21ad64
[ "tests/test_discover_classes.py::TestDiscoverClasses::test_discover_classes_with_predicate_exclusions" ]
[ "tests/test_discover_classes.py::TestDiscoverClasses::test_discover_classes_in_module", "tests/test_discover_classes.py::TestDiscoverClasses::test_discover_classes_in_path", "tests/test_discover_classes.py::TestDiscoverClasses::test_discover_classes_in_private_modules", "tests/test_discover_classes.py::TestDiscoverClasses::test_discover_classes_with_signature", "tests/test_discover_classes.py::TestDiscoverClasses::test_discover_classes_with_type_exclusions", "tests/test_discover_classes.py::TestDiscoverClasses::test_discover_classes_with_wrong_argument", "tests/test_discover_classes.py::TestDiscoverClasses::test_discover_private_classes" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-09-07 18:34:43+00:00
mit
5,163
ramonhagenaars__jsons-108
diff --git a/jsons/__init__.py b/jsons/__init__.py index 188961e..14168e8 100644 --- a/jsons/__init__.py +++ b/jsons/__init__.py @@ -91,6 +91,7 @@ from enum import Enum from typing import Union, List, Tuple, Iterable from uuid import UUID from decimal import Decimal +from pathlib import PurePath from jsons._common_impl import NoneType from jsons._key_transformers import snakecase, camelcase, pascalcase, lispcase from jsons import ( @@ -160,6 +161,7 @@ default_object_serializer = serializers.default_object_serializer default_decimal_serializer = serializers.default_decimal_serializer default_uuid_serializer = serializers.default_uuid_serializer default_union_serializer = serializers.default_union_serializer +default_path_serializer = serializers.default_path_serializer default_list_deserializer = deserializers.default_list_deserializer default_tuple_deserializer = deserializers.default_tuple_deserializer @@ -180,6 +182,7 @@ default_iterable_deserializer = deserializers.default_iterable_deserializer default_object_deserializer = deserializers.default_object_deserializer default_uuid_deserializer = deserializers.default_uuid_deserializer default_decimal_deserializer = deserializers.default_decimal_deserializer +default_path_deserializer = deserializers.default_path_deserializer # Set the serializers: set_serializer(default_tuple_serializer, (tuple, Tuple)) @@ -197,6 +200,7 @@ set_serializer(default_object_serializer, object, False) set_serializer(default_uuid_serializer, UUID) set_serializer(default_decimal_serializer, Decimal) set_serializer(default_union_serializer, Union) +set_serializer(default_path_serializer, PurePath) # Set the deserializers: set_deserializer(default_list_deserializer, (list, List)) @@ -217,3 +221,4 @@ set_deserializer(default_object_deserializer, object, False) set_deserializer(default_uuid_deserializer, UUID) set_deserializer(default_complex_deserializer, complex) set_deserializer(default_decimal_deserializer, Decimal) +set_deserializer(default_path_deserializer, PurePath) diff --git a/jsons/deserializers/__init__.py b/jsons/deserializers/__init__.py index 557e7a7..e5a78a8 100644 --- a/jsons/deserializers/__init__.py +++ b/jsons/deserializers/__init__.py @@ -29,6 +29,7 @@ from jsons.deserializers.default_tuple import ( default_namedtuple_deserializer ) from jsons.deserializers.default_decimal import default_decimal_deserializer +from jsons.deserializers.default_path import default_path_deserializer KEY_TRANSFORMER_SNAKECASE = snakecase diff --git a/jsons/deserializers/default_path.py b/jsons/deserializers/default_path.py new file mode 100644 index 0000000..76db0df --- /dev/null +++ b/jsons/deserializers/default_path.py @@ -0,0 +1,12 @@ +from pathlib import PurePath + + +def default_path_deserializer(obj: str, cls: type = PurePath, **kwargs) -> PurePath: + """ + Deserialize a string to a `pathlib.PurePath` object. Since ``pathlib`` + implements ``PurePath``, no filename or existence checks are performed. + :param obj: the string to deserialize. + :param kwargs: not used. + :return: a ``str``. + """ + return cls(obj) diff --git a/jsons/serializers/__init__.py b/jsons/serializers/__init__.py index 64433c6..6aa3500 100644 --- a/jsons/serializers/__init__.py +++ b/jsons/serializers/__init__.py @@ -20,6 +20,7 @@ from jsons.serializers.default_tuple import default_tuple_serializer from jsons.serializers.default_uuid import default_uuid_serializer from jsons.serializers.default_decimal import default_decimal_serializer from jsons.serializers.default_union import default_union_serializer +from jsons.serializers.default_path import default_path_serializer KEY_TRANSFORMER_SNAKECASE = snakecase diff --git a/jsons/serializers/default_path.py b/jsons/serializers/default_path.py new file mode 100644 index 0000000..205d55d --- /dev/null +++ b/jsons/serializers/default_path.py @@ -0,0 +1,15 @@ +from pathlib import PurePath + + +def default_path_serializer(obj: PurePath, **kwargs) -> str: + """ + Serialize a ``pathlib.PurePath`` object to a ``str``, Posix-style. + + Posix-style strings are used as they can be used to create ``pathlib.Path`` + objects on both Posix and Windows systems, but Windows-style strings can + only be used to create valid ``pathlib.Path`` objects on Windows. + :param obj: the path to serialize. + :param kwargs: not used. + :return: a ``str``. + """ + return obj.as_posix()
ramonhagenaars/jsons
b895fa654e2df5d18ef265cbce4937ba3cbc151b
diff --git a/tests/test_path.py b/tests/test_path.py new file mode 100644 index 0000000..204235a --- /dev/null +++ b/tests/test_path.py @@ -0,0 +1,273 @@ +import os.path +from pathlib import Path, PureWindowsPath, PurePosixPath +from unittest import TestCase + +import jsons + + +class TestPath(TestCase): + + def test_dump_singlepart_relative_path(self): + self.assertEqual('abc', jsons.dump(Path('abc'))) + + def test_dump_singlepart_pure_windows_path(self): + self.assertEqual('abc', jsons.dump(PureWindowsPath('abc'))) + + def test_dump_singlepart_pure_posix_path(self): + self.assertEqual('abc', jsons.dump(PurePosixPath('abc'))) + + def test_dump_multipart_relative_path(self): + self.assertEqual( + 'abc/def/ghi', + jsons.dump(Path('abc', 'def', 'ghi')) + ) + self.assertEqual( + 'abc/def/ghi', + jsons.dump(Path('abc/def/ghi')) + ) + + def test_dump_multipart_pure_windows_path(self): + self.assertEqual( + 'abc/def/ghi', + jsons.dump(PureWindowsPath('abc', 'def', 'ghi')) + ) + self.assertEqual( + 'abc/def/ghi', + jsons.dump(PureWindowsPath('abc/def/ghi')) + ) + self.assertEqual( + 'abc/def/ghi', + jsons.dump(PureWindowsPath('abc\\def\\ghi')) + ) + + def test_dump_multipart_pure_posix_path(self): + self.assertEqual( + 'abc/def/ghi', + jsons.dump(PurePosixPath('abc', 'def', 'ghi')) + ) + self.assertEqual( + 'abc/def/ghi', + jsons.dump(PurePosixPath('abc/def/ghi')) + ) + self.assertEqual( + 'abc\\def\\ghi', + jsons.dump(PurePosixPath('abc\\def\\ghi')) + ) + + def test_dump_multipart_drived_pure_windows_path(self): + self.assertEqual( + 'Z:/abc/def/ghi', + jsons.dump(PureWindowsPath('Z:\\', 'abc', 'def', 'ghi')) + ) + self.assertEqual( + 'Z:/abc/def/ghi', + jsons.dump(PureWindowsPath('Z:/abc/def/ghi')) + ) + self.assertEqual( + 'Z:/abc/def/ghi', + jsons.dump(PureWindowsPath('Z:\\abc\\def\\ghi')) + ) + + def test_dump_multipart_drived_pure_posix_path(self): + self.assertEqual( + 'Z:/abc/def/ghi', + jsons.dump(PurePosixPath('Z:', 'abc', 'def', 'ghi')) + ) + self.assertEqual( + 'Z:/abc/def/ghi', + jsons.dump(PurePosixPath('Z:/abc/def/ghi')) + ) + self.assertEqual( + 'Z:\\abc\\def\\ghi', + jsons.dump(PurePosixPath('Z:\\abc\\def\\ghi')) + ) + + ################# + + def test_load_singlepart_relative_path(self): + self.assertEqual( + Path('abc'), + jsons.load('abc', Path) + ) + + def test_load_singlepart_pure_windows_path(self): + self.assertEqual( + PureWindowsPath('abc'), + jsons.load('abc', PureWindowsPath) + ) + + def test_load_singlepart_pure_posix_path(self): + self.assertEqual( + PurePosixPath('abc'), + jsons.load('abc', PurePosixPath) + ) + + def test_load_multipart_relative_path(self): + self.assertEqual( + Path('abc', 'def', 'ghi'), + jsons.load('abc/def/ghi', Path) + ) + self.assertEqual( + Path('abc/def/ghi'), + jsons.load('abc/def/ghi', Path) + ) + + def test_load_multipart_pure_windows_path(self): + # We should be able to load Posix-style paths on Windows. + self.assertEqual( + PureWindowsPath('abc', 'def', 'ghi'), + jsons.load('abc/def/ghi', PureWindowsPath) + ) + self.assertEqual( + PureWindowsPath('abc/def/ghi'), + jsons.load('abc/def/ghi', PureWindowsPath) + ) + self.assertEqual( + PureWindowsPath('abc\\def\\ghi'), + jsons.load('abc/def/ghi', PureWindowsPath) + ) + # We should be able to load Windows-style paths on Windows. + self.assertEqual( + PureWindowsPath('abc', 'def', 'ghi'), + jsons.load('abc\\def\\ghi', PureWindowsPath) + ) + self.assertEqual( + PureWindowsPath('abc/def/ghi'), + jsons.load('abc\\def\\ghi', PureWindowsPath) + ) + self.assertEqual( + PureWindowsPath('abc\\def\\ghi'), + jsons.load('abc\\def\\ghi', PureWindowsPath) + ) + + def test_load_multipart_pure_posix_path(self): + # We should be able to load Posix-style paths on Posix systems. + self.assertEqual( + PurePosixPath('abc', 'def', 'ghi'), + jsons.load('abc/def/ghi', PurePosixPath) + ) + self.assertEqual( + PurePosixPath('abc/def/ghi'), + jsons.load('abc/def/ghi', PurePosixPath) + ) + self.assertNotEqual( + PurePosixPath('abc\\def\\ghi'), + jsons.load('abc/def/ghi', PurePosixPath) + ) + # Backslashes on Posix systems should be interpreted as escapes. + self.assertNotEqual( + PurePosixPath('abc', 'def', 'ghi'), + jsons.load('abc\\def\\ghi', PurePosixPath) + ) + self.assertNotEqual( + PurePosixPath('abc/def/ghi'), + jsons.load('abc\\def\\ghi', PurePosixPath) + ) + self.assertEqual( + PurePosixPath('abc\\def\\ghi'), + jsons.load('abc\\def\\ghi', PurePosixPath) + ) + + def test_load_multipart_drived_pure_windows_path(self): + # We should be able to load Posix-style paths on Windows. + self.assertEqual( + PureWindowsPath('Z:\\', 'abc', 'def', 'ghi'), + jsons.load('Z:/abc/def/ghi', PureWindowsPath) + ) + self.assertEqual( + PureWindowsPath('Z:/abc/def/ghi'), + jsons.load('Z:/abc/def/ghi', PureWindowsPath) + ) + self.assertEqual( + PureWindowsPath('Z:\\abc\\def\\ghi'), + jsons.load('Z:/abc/def/ghi', PureWindowsPath) + ) + # We should be able to load Windows-style paths on Windows. + self.assertEqual( + PureWindowsPath('Z:\\', 'abc', 'def', 'ghi'), + jsons.load('Z:\\abc\\def\\ghi', PureWindowsPath) + ) + self.assertEqual( + PureWindowsPath('Z:/abc/def/ghi'), + jsons.load('Z:\\abc\\def\\ghi', PureWindowsPath) + ) + self.assertEqual( + PureWindowsPath('Z:\\abc\\def\\ghi'), + jsons.load('Z:\\abc\\def\\ghi', PureWindowsPath) + ) + + def test_load_multipart_drived_pure_posix_path(self): + # We should be able to load Posix-style paths on Windows. + self.assertEqual( + PurePosixPath('Z:', 'abc', 'def', 'ghi'), + jsons.load('Z:/abc/def/ghi', PurePosixPath) + ) + self.assertEqual( + PurePosixPath('Z:/abc/def/ghi'), + jsons.load('Z:/abc/def/ghi', PurePosixPath) + ) + self.assertNotEqual( + PurePosixPath('Z:\\abc\\def\\ghi'), + jsons.load('Z:/abc/def/ghi', PurePosixPath) + ) + # Backslashes on Posix systems should be interpreted as escapes. + self.assertNotEqual( + PurePosixPath('Z:', 'abc', 'def', 'ghi'), + jsons.load('Z:\\abc\\def\\ghi', PurePosixPath) + ) + self.assertNotEqual( + PurePosixPath('Z:/abc/def/ghi'), + jsons.load('Z:\\abc\\def\\ghi', PurePosixPath) + ) + self.assertEqual( + PurePosixPath('Z:\\abc\\def\\ghi'), + jsons.load('Z:\\abc\\def\\ghi', PurePosixPath) + ) + + def test_dump_posix_load_windows(self): + dump_result = jsons.dump(PurePosixPath('abc', 'def', 'ghi')) + self.assertEqual( + 'abc/def/ghi', + dump_result + ) + load_result = jsons.load(dump_result, PureWindowsPath) + self.assertEqual( + PureWindowsPath('abc', 'def', 'ghi'), + load_result + ) + + def test_dump_windows_load_posix(self): + dump_result = jsons.dump(PureWindowsPath('abc', 'def', 'ghi')) + self.assertEqual( + 'abc/def/ghi', + dump_result + ) + load_result = jsons.load(dump_result, PurePosixPath) + self.assertEqual( + PurePosixPath('abc', 'def', 'ghi'), + load_result + ) + + def test_dump_posix_load_posix(self): + dump_result = jsons.dump(PurePosixPath('abc', 'def', 'ghi')) + self.assertEqual( + 'abc/def/ghi', + dump_result + ) + load_result = jsons.load(dump_result, PurePosixPath) + self.assertEqual( + PurePosixPath('abc', 'def', 'ghi'), + load_result + ) + + def test_dump_windows_load_windows(self): + dump_result = jsons.dump(PureWindowsPath('abc', 'def', 'ghi')) + self.assertEqual( + 'abc/def/ghi', + dump_result + ) + load_result = jsons.load(dump_result, PureWindowsPath) + self.assertEqual( + PureWindowsPath('abc', 'def', 'ghi'), + load_result + )
Add support for pathlib.Path objects The current `default_object_deserializer` does not support `pathlib.Path` objects. When trying to deserialise the string `data/gqa` to a `pathlib.Path` object, the default `default_object_deserializer` tries to access attributes of the string `data/gqa`, lesding to the following error in a dictionary comprehension: ``` Traceback (most recent call last): File "/home/alex/.virtualenvs/python-standard/lib/python3.8/site-packages/jsons/_load_impl.py", line 110, in _do_load result = deserializer(json_obj, cls, **kwargs) File "/home/alex/.virtualenvs/python-standard/lib/python3.8/site-packages/jsons/deserializers/default_object.py", line 40, in default_object_deserializer remaining_attrs = _get_remaining_args(obj, cls, constructor_args, File "/home/alex/.virtualenvs/python-standard/lib/python3.8/site-packages/jsons/deserializers/default_object.py", line 174, in _get_remaining_args remaining_attrs = {attr_name: obj[attr_name] for attr_name in obj File "/home/alex/.virtualenvs/python-standard/lib/python3.8/site-packages/jsons/deserializers/default_object.py", line 174, in <dictcomp> remaining_attrs = {attr_name: obj[attr_name] for attr_name in obj TypeError: string indices must be integers ``` I would like to propose a default serialiser and deserialiser for `pathlib.Path` objects that allows for conversion between `str` and `pathlib.Path`. Whether to support a list of path segments like `["data", "gqa"]` is up for discussion.
0.0
b895fa654e2df5d18ef265cbce4937ba3cbc151b
[ "tests/test_path.py::TestPath::test_dump_multipart_drived_pure_posix_path", "tests/test_path.py::TestPath::test_dump_multipart_drived_pure_windows_path", "tests/test_path.py::TestPath::test_dump_multipart_pure_posix_path", "tests/test_path.py::TestPath::test_dump_multipart_pure_windows_path", "tests/test_path.py::TestPath::test_dump_multipart_relative_path", "tests/test_path.py::TestPath::test_dump_posix_load_posix", "tests/test_path.py::TestPath::test_dump_posix_load_windows", "tests/test_path.py::TestPath::test_dump_singlepart_pure_posix_path", "tests/test_path.py::TestPath::test_dump_singlepart_pure_windows_path", "tests/test_path.py::TestPath::test_dump_singlepart_relative_path", "tests/test_path.py::TestPath::test_dump_windows_load_posix", "tests/test_path.py::TestPath::test_dump_windows_load_windows", "tests/test_path.py::TestPath::test_load_multipart_drived_pure_posix_path", "tests/test_path.py::TestPath::test_load_multipart_drived_pure_windows_path", "tests/test_path.py::TestPath::test_load_multipart_pure_posix_path", "tests/test_path.py::TestPath::test_load_multipart_pure_windows_path", "tests/test_path.py::TestPath::test_load_multipart_relative_path", "tests/test_path.py::TestPath::test_load_singlepart_pure_posix_path", "tests/test_path.py::TestPath::test_load_singlepart_pure_windows_path", "tests/test_path.py::TestPath::test_load_singlepart_relative_path" ]
[]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-02 13:58:13+00:00
mit
5,164
ramonhagenaars__jsons-143
diff --git a/README.md b/README.md index 70892fd..15af1d1 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,10 @@ list_of_tuples = jsons.load(some_dict, List[Tuple[AClass, AnotherClass]]) ## Recent updates +### 1.5.1 + +- Bugfix: `ZoneInfo` failed to dump if attached to a `datetime`. + ### 1.5.0 - Feature: Support for `ZoneInfo` on Python3.9+. diff --git a/jsons/_datetime_impl.py b/jsons/_datetime_impl.py index 6b0d734..575d9a6 100644 --- a/jsons/_datetime_impl.py +++ b/jsons/_datetime_impl.py @@ -73,7 +73,8 @@ def _datetime_offset_str(obj: datetime, fork_inst: type) -> str: return '+00:00' offset = 'Z' if tzone.tzname(None) not in ('UTC', 'UTC+00:00'): - tdelta = tzone.utcoffset(None) or tzone.adjusted_offset + tdelta = tzone.utcoffset(None) or \ + getattr(tzone, 'adjusted_offset', tzone.utcoffset(obj)) offset = _timedelta_offset_str(tdelta) return offset diff --git a/jsons/_meta.py b/jsons/_meta.py index fe65e9f..8c60d77 100644 --- a/jsons/_meta.py +++ b/jsons/_meta.py @@ -1,5 +1,5 @@ __title__ = 'jsons' -__version__ = '1.5.0' +__version__ = '1.5.1' __author__ = 'Ramon Hagenaars' __author_email__ = '[email protected]' __description__ = 'For serializing Python objects to JSON (dicts) and back'
ramonhagenaars/jsons
df9b587b30984720d0b7c7c843a67f83f1b8d3a5
diff --git a/tests/test_specific_versions.py b/tests/test_specific_versions.py index 341df74..6a699ee 100644 --- a/tests/test_specific_versions.py +++ b/tests/test_specific_versions.py @@ -1,5 +1,6 @@ import sys import uuid +from datetime import datetime from pathlib import Path from unittest import TestCase, skipUnless @@ -146,7 +147,7 @@ class TestSpecificVersions(TestCase): self.assertDictEqual(expected2, dumped2) @only_version_3(9, and_above=True) - def test_postponed_annoation_dataclass(self): + def test_zoneinfo(self): # On Python 3.9 ZoneInfo should be available. from zoneinfo import ZoneInfo @@ -154,9 +155,13 @@ class TestSpecificVersions(TestCase): info = ZoneInfo(key='America/Los_Angeles') dumped_info = jsons.dump(info) loaded_info = jsons.load(dumped_info, ZoneInfo) - self.assertEqual(info, loaded_info) + dt = datetime(2021, 8, 31, tzinfo=ZoneInfo("America/Los_Angeles")) + dumped_dt = jsons.dump(dt) + loaded_dt = jsons.load(dumped_dt, datetime) + self.assertEqual(dt, loaded_dt) + @only_version_3(9, and_above=True) def test_dump_load_parameterized_collections(self): import version_39
zoneinfo support incomplete As the following REPL session seems to show, `zoneinfo` support in version `1.5.0` is incomplete. The standalone `dump` of `ZoneInfo` works, but when constructing a `datetime` with `tzinfo` , the nested dump doesn't work. ``` >>> import jsons >>> from zoneinfo import ZoneInfo >>> info = ZoneInfo(key='America/Los_Angeles') >>> di = jsons.dump(info) >>> di {'key': 'America/Los_Angeles'} >>> from datetime import datetime, timedelta >>> dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles")) >>> jdt = jsons.dump(dt) Traceback (most recent call last): File "C:\Users\jeff1\Documents\projects\git\cdk\r53\.venv\lib\site-packages\jsons\_dump_impl.py", line 60, in _do_dump result = serializer(obj, cls=cls, **kwargs) File "C:\Users\jeff1\Documents\projects\git\cdk\r53\.venv\lib\site-packages\jsons\serializers\default_datetime.py", line 21, in default_datetime_serializer return to_str(obj, strip_microseconds, kwargs['fork_inst'], File "C:\Users\jeff1\Documents\projects\git\cdk\r53\.venv\lib\site-packages\jsons\_datetime_impl.py", line 20, in to_str offset = get_offset_str(dt, fork_inst) File "C:\Users\jeff1\Documents\projects\git\cdk\r53\.venv\lib\site-packages\jsons\_datetime_impl.py", line 37, in get_offset_str result = _datetime_offset_str(obj, fork_inst) File "C:\Users\jeff1\Documents\projects\git\cdk\r53\.venv\lib\site-packages\jsons\_datetime_impl.py", line 76, in _datetime_offset_str tdelta = tzone.utcoffset(None) or tzone.adjusted_offset AttributeError: 'zoneinfo.ZoneInfo' object has no attribute 'adjusted_offset' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\jeff1\Documents\projects\git\cdk\r53\.venv\lib\site-packages\jsons\_dump_impl.py", line 55, in dump return _do_dump(obj, serializer, cls, initial, kwargs_) File "C:\Users\jeff1\Documents\projects\git\cdk\r53\.venv\lib\site-packages\jsons\_dump_impl.py", line 66, in _do_dump raise SerializationError(str(err)) from err jsons.exceptions.SerializationError: 'zoneinfo.ZoneInfo' object has no attribute 'adjusted_offset' ```
0.0
df9b587b30984720d0b7c7c843a67f83f1b8d3a5
[ "tests/test_specific_versions.py::TestSpecificVersions::test_zoneinfo" ]
[ "tests/test_specific_versions.py::TestSpecificVersions::test_dump_dataclass_with_optional", "tests/test_specific_versions.py::TestSpecificVersions::test_dump_load_parameterized_collections", "tests/test_specific_versions.py::TestSpecificVersions::test_dump_parent_dataclass", "tests/test_specific_versions.py::TestSpecificVersions::test_hint_with_jsonserializable", "tests/test_specific_versions.py::TestSpecificVersions::test_namedtuple_with_optional", "tests/test_specific_versions.py::TestSpecificVersions::test_postponed_annotation_dataclass", "tests/test_specific_versions.py::TestSpecificVersions::test_simple_dump_and_load_dataclass", "tests/test_specific_versions.py::TestSpecificVersions::test_simple_dump_and_load_dataclass_with_future_import", "tests/test_specific_versions.py::TestSpecificVersions::test_uuid_serialization" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-08-31 19:22:51+00:00
mit
5,165
ramonhagenaars__jsons-161
diff --git a/.github/workflows/pythonapp.yml b/.github/workflows/pythonapp.yml index 5aadfc3..c0ee5c0 100644 --- a/.github/workflows/pythonapp.yml +++ b/.github/workflows/pythonapp.yml @@ -17,14 +17,14 @@ jobs: ] os: [ ubuntu-latest, -# macOS-latest, FIXME: seems to not work at the moment. + macOS-latest, windows-latest ] name: Python ${{ matrix.python-version }} on ${{ matrix.os }} steps: - uses: actions/checkout@master - name: Setup python - uses: actions/setup-python@v1 + uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} architecture: x64 diff --git a/docs/_templates/sidebarintro.html b/docs/_templates/sidebarintro.html index 155b876..b78a06e 100644 --- a/docs/_templates/sidebarintro.html +++ b/docs/_templates/sidebarintro.html @@ -14,7 +14,7 @@ <h3>Links</h3> <ul> <li> - <a href="https://ghbtns.com/github-btn.html?user=ramonhagenaars&repo=jsons&type=watch&count=true&size=large" allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px">jsons - Github</a> + <a href="https://github.com/ramonhagenaars/jsons/" allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px">jsons - Github</a> </li> <li> <a href="https://pypi.org/project/jsons/">jsons - PyPi</a> diff --git a/jsons/deserializers/default_list.py b/jsons/deserializers/default_list.py index f64aeda..6f3a880 100644 --- a/jsons/deserializers/default_list.py +++ b/jsons/deserializers/default_list.py @@ -56,7 +56,7 @@ def _do_load( result = [] for index, elem in enumerate(obj): try: - result.append(load(elem, cls=cls, tasks=1, **kwargs)) + result.append(load(elem, cls=cls, tasks=1, fork_inst=fork_inst, **kwargs)) except DeserializationError as err: new_msg = ('Could not deserialize element at index %s. %s' % (index, err.message))
ramonhagenaars/jsons
a5150cdd2704e83fe5f8798822a1c901b54dcb1c
diff --git a/tests/test_list.py b/tests/test_list.py index a5a7286..4dcceb3 100644 --- a/tests/test_list.py +++ b/tests/test_list.py @@ -184,3 +184,17 @@ class TestList(TestCase): self.assertIn('500', warn_msg) self.assertEqual(999, len(loaded)) + + def test_propagation_of_fork_inst(self): + class C: + def __init__(self, x: int): + self.x = x + + def c_deserializer(obj, *_, **__) -> C: + return C(obj['x'] * 2) + + fork = jsons.fork(name='fork_inst_propagation') + jsons.set_deserializer(c_deserializer, C, fork_inst=fork) + cs = jsons.loads('[{"x":2},{"x":3}]', List[C], fork_inst=fork) + self.assertEqual(4, cs[0].x) + self.assertEqual(6, cs[1].x)
fork_inst not being passed along to element deserializer in default list deserializer https://github.com/ramonhagenaars/jsons/blob/a5150cdd2704e83fe5f8798822a1c901b54dcb1c/jsons/deserializers/default_list.py#L59 I'm not sure if this is intentional or not. I've registered my deserializers in a fork_inst, but they are not called in certain circumstances. I tracked the issue down to the linked line in the default_list_deserializer. My guess is that the kwargs argument should be extended with the fork_inst parameter, before calling the element deserializer. For now I will check if my issue can be solved, bei either overwriting default_list_deserializer or by not using a fork_inst at all.
0.0
a5150cdd2704e83fe5f8798822a1c901b54dcb1c
[ "tests/test_list.py::TestList::test_propagation_of_fork_inst" ]
[ "tests/test_list.py::TestList::test_dump_list", "tests/test_list.py::TestList::test_dump_list_multiprocess", "tests/test_list.py::TestList::test_dump_list_strict_no_cls", "tests/test_list.py::TestList::test_dump_load_list_verbose", "tests/test_list.py::TestList::test_load_error_points_at_index", "tests/test_list.py::TestList::test_load_list", "tests/test_list.py::TestList::test_load_list2", "tests/test_list.py::TestList::test_load_list_multiprocess", "tests/test_list.py::TestList::test_load_list_multithreaded", "tests/test_list.py::TestList::test_load_list_typing", "tests/test_list.py::TestList::test_load_list_with_generic", "tests/test_list.py::TestList::test_warn_on_fail" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-04-19 18:47:10+00:00
mit
5,166
ramonhagenaars__jsons-171
diff --git a/README.md b/README.md index bea7f72..6321d77 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,10 @@ list_of_tuples = jsons.load(some_dict, List[Tuple[AClass, AnotherClass]]) ## Recent updates +### 1.6.3 + +- Bugfix: a string was sometimes unintentionally parsed into a datetime. + ### 1.6.2 - Bugfix: `fork_inst`s were not propagated in `default_list_deserializer` (thanks to patrickguenther). diff --git a/jsons/_load_impl.py b/jsons/_load_impl.py index 2d2d322..724cdf2 100644 --- a/jsons/_load_impl.py +++ b/jsons/_load_impl.py @@ -79,6 +79,7 @@ def load( return json_obj if isinstance(cls, str): cls = get_cls_from_str(cls, json_obj, fork_inst) + original_cls = cls cls, meta_hints = _check_and_get_cls_and_meta_hints( json_obj, cls, fork_inst, kwargs.get('_inferred_cls', False)) @@ -88,12 +89,13 @@ def load( initial = kwargs.get('_initial', True) kwargs_ = { + 'meta_hints': meta_hints, # Overridable by kwargs. + **kwargs, 'strict': strict, 'fork_inst': fork_inst, 'attr_getters': attr_getters, - 'meta_hints': meta_hints, '_initial': False, - **kwargs + '_inferred_cls': cls is not original_cls, } return _do_load(json_obj, deserializer, cls, initial, **kwargs_) diff --git a/jsons/_package_info.py b/jsons/_package_info.py index bc37be5..f4781c8 100644 --- a/jsons/_package_info.py +++ b/jsons/_package_info.py @@ -1,5 +1,5 @@ __title__ = 'jsons' -__version__ = '1.6.2' +__version__ = '1.6.3' __author__ = 'Ramon Hagenaars' __author_email__ = '[email protected]' __description__ = 'For serializing Python objects to JSON (dicts) and back' diff --git a/jsons/deserializers/default_string.py b/jsons/deserializers/default_string.py index 5024198..b20733e 100644 --- a/jsons/deserializers/default_string.py +++ b/jsons/deserializers/default_string.py @@ -17,6 +17,9 @@ def default_string_deserializer(obj: str, :param kwargs: any keyword arguments. :return: the deserialized obj. """ + target_is_str = cls is str and not kwargs.get('_inferred_cls') + if target_is_str: + return str(obj) try: result = load(obj, datetime, **kwargs) except DeserializationError:
ramonhagenaars/jsons
0b4b777de2734ed1d53a0571528cf28d0c11ee9b
diff --git a/tests/test_str.py b/tests/test_str.py new file mode 100644 index 0000000..2ec5a35 --- /dev/null +++ b/tests/test_str.py @@ -0,0 +1,33 @@ +from datetime import datetime +from unittest import TestCase + +import jsons + + +class TestStr(TestCase): + def test_string_is_loaded_as_string(self): + + class C: + def __init__(self, x: str): + self.x = x + + fork = jsons.fork() + jsons.set_deserializer(lambda obj, _, **kwargs: datetime.strptime(obj, '%Y'), datetime, fork_inst=fork) + loaded = jsons.load({'x': '1025'}, C, strict=True, fork_inst=fork) + + self.assertIsInstance(loaded.x, str) + + def test_string_is_loaded_as_datetime(self): + + class C: + def __init__(self, x): + # x has no hint, so the type will be inferred. Since x is not + # explicitly targeted as str, it may get parsed as a datetime. + # And in this test, it should. + self.x = x + + fork = jsons.fork() + jsons.set_deserializer(lambda obj, _, **kwargs: datetime.strptime(obj, '%Y'), datetime, fork_inst=fork) + loaded = jsons.load({'x': '1025'}, C, strict=True, fork_inst=fork) + + self.assertIsInstance(loaded.x, datetime)
String deserialized as datetime despite target type annotation This code: ```python @dataclass class Sample: prop: str def unrelated_date_deserializer(obj: str, cls: type = datetime, **kwargs) -> datetime: return datetime.strptime(obj, '%Y') jsons.set_deserializer(unrelated_date_deserializer, datetime) json = {'prop': '1025'} print(jsons.load(json, Sample, strict=True)) ``` Outputs: ```python Sample(prop=datetime.datetime(1025, 1, 1, 0, 0)) ``` Shouldn't the `str` type annotation be used to decide whether to employ the deserializer or not?
0.0
0b4b777de2734ed1d53a0571528cf28d0c11ee9b
[ "tests/test_str.py::TestStr::test_string_is_loaded_as_string" ]
[ "tests/test_str.py::TestStr::test_string_is_loaded_as_datetime" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-06-09 19:18:09+00:00
mit
5,167
ramonhagenaars__jsons-79
diff --git a/jsons/_load_impl.py b/jsons/_load_impl.py index 4cc1ffd..b8055b4 100644 --- a/jsons/_load_impl.py +++ b/jsons/_load_impl.py @@ -103,6 +103,9 @@ def _do_load(json_obj: object, cls: type, initial: bool, **kwargs): + cls_name = get_class_name(cls, fully_qualified=True) + if deserializer is None: + raise DeserializationError('No deserializer for type "{}"'.format(cls_name), json_obj, cls) try: result = deserializer(json_obj, cls, **kwargs) validate(result, cls, kwargs['fork_inst']) @@ -110,7 +113,8 @@ def _do_load(json_obj: object, clear() if isinstance(err, JsonsError): raise - raise DeserializationError(str(err), json_obj, cls) + message = 'Could not deserialize value "{}" into "{}". {}'.format(json_obj, cls_name, err) + raise DeserializationError(message, json_obj, cls) else: if initial: # Clear all lru caches right before returning the initial call. diff --git a/jsons/deserializers/default_primitive.py b/jsons/deserializers/default_primitive.py index 3110904..2223957 100644 --- a/jsons/deserializers/default_primitive.py +++ b/jsons/deserializers/default_primitive.py @@ -17,6 +17,6 @@ def default_primitive_deserializer(obj: object, try: result = cls(obj) except ValueError: - raise DeserializationError('Could not cast {} into {}' + raise DeserializationError('Could not cast "{}" into "{}"' .format(obj, cls.__name__), obj, cls) return result diff --git a/jsons/serializers/default_primitive.py b/jsons/serializers/default_primitive.py index ee24f9c..6fa0a59 100644 --- a/jsons/serializers/default_primitive.py +++ b/jsons/serializers/default_primitive.py @@ -17,6 +17,6 @@ def default_primitive_serializer(obj: object, try: result = cls(obj) except ValueError: - raise SerializationError('Could not cast {} into {}' + raise SerializationError('Could not cast "{}" into "{}"' .format(obj, cls.__name__)) return result
ramonhagenaars/jsons
600917c62cf9a6a261752e31e761678ad7fc2b8d
diff --git a/tests/test_type_error.py b/tests/test_type_error.py new file mode 100644 index 0000000..2e12564 --- /dev/null +++ b/tests/test_type_error.py @@ -0,0 +1,43 @@ +import datetime +from dataclasses import dataclass +from unittest import TestCase +import jsons +from jsons import DeserializationError + + +@dataclass +class WrongUser: + id: int + birthday: datetime # intentionally wrong + + +@dataclass +class CorrectUser: + id: int + birthday: datetime.datetime + + +class TestTypeError(TestCase): + def test_undefined_deserializer(self): + dumped = {'id': 12, 'birthday': '1879-03-14T11:30:00+01:00'} + with self.assertRaises(DeserializationError) as errorContext: + jsons.load(dumped, WrongUser) + error: DeserializationError = errorContext.exception + self.assertEqual('No deserializer for type "datetime"', error.message) + self.assertEqual(datetime, error.target) + + def test_wrong_primitive_type(self): + dumped = {'id': 'Albert', 'birthday': '1879-03-14T11:30:00+01:00'} + with self.assertRaises(DeserializationError) as errorContext: + jsons.load(dumped, WrongUser) + error: DeserializationError = errorContext.exception + self.assertEqual('Could not cast "Albert" into "int"', error.message) + self.assertEqual(int, error.target) + + def test_wrong_type(self): + dumped = {'id': 12, 'birthday': 'every day'} + with self.assertRaises(DeserializationError) as errorContext: + jsons.load(dumped, CorrectUser) + error: DeserializationError = errorContext.exception + self.assertTrue(error.message.startswith('Could not deserialize value "every day" into "datetime.datetime".')) + self.assertEqual(datetime.datetime, error.target)
Invalid type hints result in cryptic error messages When a class has an invalid type hint, deserializing into that class may cause a ``DeserializationError`` that does not help solving the issue. The error should be more descriptive. Example: ```python import datetime # <-- Note that the module is imported, not the class. from dataclasses import dataclass import jsons @dataclass class User: name: str birthday: datetime dumped = { 'name': 'Albert', 'birthday': '1879-03-14T11:30:00+01:00' } jsons.load(dumped, User) ``` This causes: ```python Traceback (most recent call last): File "C:\Projects\Personal\jsons\jsons\_main_impl.py", line 128, in load return deserializer(json_obj, cls, **kwargs_) File "C:\Projects\Personal\jsons\jsons\deserializers\default_object.py", line 31, in default_object_deserializer constructor_args = _get_constructor_args(obj, cls, **kwargs) File "C:\Projects\Personal\jsons\jsons\deserializers\default_object.py", line 58, in _get_constructor_args constructor_args_in_obj = {key: value for key, value in args_gen if key} File "C:\Projects\Personal\jsons\jsons\deserializers\default_object.py", line 58, in <dictcomp> constructor_args_in_obj = {key: value for key, value in args_gen if key} File "C:\Projects\Personal\jsons\jsons\deserializers\default_object.py", line 57, in <genexpr> in signature_parameters.items() if sig_key != 'self') File "C:\Projects\Personal\jsons\jsons\deserializers\default_object.py", line 75, in _get_value_for_attr meta_hints, **kwargs) File "C:\Projects\Personal\jsons\jsons\deserializers\default_object.py", line 109, in _get_value_from_obj value = load(obj[sig_key], arg_cls, meta_hints=new_hints, **kwargs) File "C:\Projects\Personal\jsons\jsons\_main_impl.py", line 119, in load deserializer = _get_deserializer(cls, fork_inst) File "C:\Projects\Personal\jsons\jsons\_main_impl.py", line 145, in _get_deserializer fork_inst._classes_deserializers, fork_inst) File "C:\Projects\Personal\jsons\jsons\_main_impl.py", line 153, in _get_lizer cls_name = get_class_name(cls, str.lower, fork_inst=fork_inst) File "C:\Projects\Personal\jsons\jsons\_common_impl.py", line 51, in get_class_name module = _get_module(cls) File "C:\Projects\Personal\jsons\jsons\_common_impl.py", line 104, in _get_module module = cls.__module__ AttributeError: module 'datetime' has no attribute '__module__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Projects/Personal/jsons/effe.py", line 14, in <module> jsons.load(dumped, User) File "C:\Projects\Personal\jsons\jsons\_main_impl.py", line 132, in load raise DeserializationError(str(err), json_obj, cls) jsons.exceptions.DeserializationError: module 'datetime' has no attribute '__module__' ```
0.0
600917c62cf9a6a261752e31e761678ad7fc2b8d
[ "tests/test_type_error.py::TestTypeError::test_undefined_deserializer", "tests/test_type_error.py::TestTypeError::test_wrong_primitive_type", "tests/test_type_error.py::TestTypeError::test_wrong_type" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2019-12-07 17:26:10+00:00
mit
5,168
ramonhagenaars__jsons-86
diff --git a/README.md b/README.md index ac05a16..17f98b9 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,10 @@ list_of_tuples = jsons.load(some_dict, List[Tuple[AClass, AnotherClass]]) ## Recent updates +### 1.1.2 + +- Bugfix: Dumping a tuple with ellipsis failed in strict mode. + ### 1.1.1 - Feature: Added a serializer for ``Union`` types. @@ -120,11 +124,7 @@ list_of_tuples = jsons.load(some_dict, List[Tuple[AClass, AnotherClass]]) ### 0.10.2 - - Bugfix: Loading `Dict[K, V]` did not parse `K`. - -### 0.10.1 - - - Change: Correction of the type hints of `load`, `loads`, `loadb`. + - Bugfix: Loading `Dict[K, V]` did not parse `K ## Contributors diff --git a/docs/index.rst b/docs/index.rst index 2f6ceb0..37ddfe1 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -57,7 +57,7 @@ And to deserialize, just do: .. code:: python - instance = jsons.load(loaded, Car) + instance = jsons.load(dumped, Car) Type hints for the win! diff --git a/jsons/serializers/default_iterable.py b/jsons/serializers/default_iterable.py index 9e26962..7032a80 100644 --- a/jsons/serializers/default_iterable.py +++ b/jsons/serializers/default_iterable.py @@ -35,7 +35,6 @@ def default_iterable_serializer( kwargs_.pop('_store_cls', None) if strict: cls_ = determine_cls(obj, cls) - # cls_ = cls or get_type(obj) # Get the List[T] type from the instance. subclasses = _get_subclasses(obj, cls_) else: subclasses = _get_subclasses(obj, None) diff --git a/jsons/serializers/default_primitive.py b/jsons/serializers/default_primitive.py index 6fa0a59..074d30c 100644 --- a/jsons/serializers/default_primitive.py +++ b/jsons/serializers/default_primitive.py @@ -9,7 +9,7 @@ def default_primitive_serializer(obj: object, """ Serialize a primitive; simply return the given ``obj``. :param obj: the primitive. - :param _: not used. + :param cls: the type of ``obj``. :return: ``obj``. """ result = obj diff --git a/jsons/serializers/default_tuple.py b/jsons/serializers/default_tuple.py index aef627b..5b12961 100644 --- a/jsons/serializers/default_tuple.py +++ b/jsons/serializers/default_tuple.py @@ -1,19 +1,31 @@ -from typing import Union +from typing import Union, Optional, Tuple + +from typish import get_args + +from jsons._compatibility_impl import tuple_with_ellipsis from jsons._dump_impl import dump from jsons.serializers.default_iterable import default_iterable_serializer -def default_tuple_serializer(obj: tuple, **kwargs) -> Union[list, dict]: +def default_tuple_serializer(obj: tuple, + cls: Optional[type] = None, + **kwargs) -> Union[list, dict]: """ Serialize the given ``obj`` to a list of serialized objects. :param obj: the tuple that is to be serialized. + :param cls: the type of the ``obj``. :param kwargs: any keyword arguments that may be given to the serialization process. :return: a list of which all elements are serialized. """ if hasattr(obj, '_fields'): return default_namedtuple_serializer(obj, **kwargs) - return default_iterable_serializer(obj, **kwargs) + + cls_ = cls + if cls and tuple_with_ellipsis(cls): + cls_ = Tuple[(get_args(cls)[0],) * len(obj)] + + return default_iterable_serializer(obj, cls_, **kwargs) def default_namedtuple_serializer(obj: tuple, **kwargs) -> dict:
ramonhagenaars/jsons
aa565f530b3e72c5854cf11b10b1d90daa85f047
diff --git a/tests/test_tuple.py b/tests/test_tuple.py index f25bf8f..51ccc2e 100644 --- a/tests/test_tuple.py +++ b/tests/test_tuple.py @@ -14,6 +14,21 @@ class TestTuple(TestCase): self.assertEqual([1, 2, 3, [4, 5, ['2018-07-08T21:34:00Z']]], jsons.dump(tup)) + def test_dump_tuple_with_ellipsis(self): + class A: + def __init__(self, x: Tuple[str, ...]): + self.x = x + + expected = { + 'x': ['abc', 'def'] + } + + dumped1 = jsons.dump(A(('abc', 'def')), strict=True) + dumped2 = jsons.dump(A(('abc', 'def')), strict=False) + + self.assertDictEqual(expected, dumped1) + self.assertDictEqual(expected, dumped2) + def test_dump_namedtuple(self): T = namedtuple('T', ['x', 'y']) t = T(1, 2)
Serialization of unspecified length of Tuple fails The following serialization fails when I use `strict=True`, I am not sure whether this is expected behavior or not. ``` >>> from typing import Tuple >>> from dataclasses import dataclass >>> import jsons >>> @dataclass(frozen=True) ... class A: ... x: Tuple[str, ...] ... >>> jsons.dumps(A('abc'), strict=True) ``` Error: ``` Traceback (most recent call last): File "~/.pyenv/versions/forms/lib/python3.7/site-packages/jsons/_dump_impl.py", line 62, in _do_dump result = serializer(obj, cls=cls, **kwargs) File "~/.pyenv/versions/forms/lib/python3.7/site-packages/jsons/serializers/default_object.py", line 92, in default_object_serializer fork_inst=fork_inst) File "~/.pyenv/versions/forms/lib/python3.7/site-packages/jsons/serializers/default_object.py", line 126, in _do_serialize **kwargs) File "~/.pyenv/versions/forms/lib/python3.7/site-packages/jsons/_dump_impl.py", line 57, in dump return _do_dump(obj, serializer, cls, initial, kwargs_) File "~/.pyenv/versions/forms/lib/python3.7/site-packages/jsons/_dump_impl.py", line 68, in _do_dump raise SerializationError(str(err)) jsons.exceptions.SerializationError: Not enough generic types (2) in typing.Tuple[str, ...], expected 3 to match the iterable of length 3 ```
0.0
aa565f530b3e72c5854cf11b10b1d90daa85f047
[ "tests/test_tuple.py::TestTuple::test_dump_tuple_with_ellipsis" ]
[ "tests/test_tuple.py::TestTuple::test_dump_namedtuple", "tests/test_tuple.py::TestTuple::test_dump_namedtuple_with_types", "tests/test_tuple.py::TestTuple::test_dump_tuple", "tests/test_tuple.py::TestTuple::test_load_namedtuple_with_empty", "tests/test_tuple.py::TestTuple::test_load_namedtuple_without_types", "tests/test_tuple.py::TestTuple::test_load_tuple", "tests/test_tuple.py::TestTuple::test_load_tuple_typing", "tests/test_tuple.py::TestTuple::test_load_tuple_with_n_length" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-01-22 20:27:13+00:00
mit
5,169
ramonhagenaars__nptyping-85
diff --git a/HISTORY.md b/HISTORY.md index 113df46..40c00c1 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,9 @@ # History +## 2.2.0 (2022-06-26) + +- Added support for expressing "at least N dimensions". + ## 2.1.3 (2022-06-19) - Fixed typing issue with Pyright/Pylance that caused the message: "Literal" is not a class diff --git a/USERDOCS.md b/USERDOCS.md index 639ee19..b4b4935 100644 --- a/USERDOCS.md +++ b/USERDOCS.md @@ -110,7 +110,7 @@ labels, wildcards and dimension breakdowns, they are described in the following The syntax of a shape expression can be formalized in BNF. Extra whitespacing is allowed (e.g. around commas), but this is not included in the schema below (to avoid extra complexity). ``` -shape-expression = <dimensions>|<dimension>","<ellipsis> +shape-expression = <dimensions>|<dimensions>","<ellipsis> dimensions = <dimension>|<dimension>","<dimensions> dimension = <unlabeled-dimension>|<labeled-dimension> labeled-dimension = <unlabeled-dimension>" "<label> @@ -201,6 +201,19 @@ True ``` The shape in the above example can be replaced with `typing.Any` to have the same effect. +You can also express "at least N dimensions": +```python +>>> isinstance(random.randn(2, 2), NDArray[Shape["2, 2, ..."], Any]) +True +>>> isinstance(random.randn(2, 2, 2, 2), NDArray[Shape["2, 2, ..."], Any]) +True +>>> isinstance(random.randn(2), NDArray[Shape["2, 2, ..."], Any]) +False + +``` + + + #### Dimension breakdowns A dimension can be broken down into more detail. We call this a **dimension breakdown**. This can be useful to clearly describe what a dimension means. Example: diff --git a/nptyping/package_info.py b/nptyping/package_info.py index b3da4c0..a2a4f23 100644 --- a/nptyping/package_info.py +++ b/nptyping/package_info.py @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ __title__ = "nptyping" -__version__ = "2.1.3" +__version__ = "2.2.0" __author__ = "Ramon Hagenaars" __author_email__ = "[email protected]" __description__ = "Type hints for NumPy." diff --git a/nptyping/shape_expression.py b/nptyping/shape_expression.py index 402b272..44095eb 100644 --- a/nptyping/shape_expression.py +++ b/nptyping/shape_expression.py @@ -47,8 +47,8 @@ def check_shape(shape: ShapeTuple, target: "Shape") -> bool: :param target: the shape expression to which shape is tested. :return: True if the given shape corresponds to shape_expression. """ - dim_strings = _handle_ellipsis(target.prepared_args, shape) - return _check_dimensions_against_shape(dim_strings, shape) + target_shape = _handle_ellipsis(shape, target.prepared_args) + return _check_dimensions_against_shape(shape, target_shape) def validate_shape_expression(shape_expression: Union[ShapeExpression, Any]) -> None: @@ -113,37 +113,41 @@ def remove_labels(dimensions: List[str]) -> List[str]: :param dimensions: a list of dimensions. :return: a copy of the given list without labels. """ - return [re.sub(r"\b[a-z]\w*", "", dim) for dim in dimensions] + return [re.sub(r"\b[a-z]\w*", "", dim).strip() for dim in dimensions] -def _check_dimensions_against_shape(dimensions: List[str], shape: ShapeTuple) -> bool: - # Walk through the dimensions and test them against the given shape, +def _check_dimensions_against_shape(shape: ShapeTuple, target: List[str]) -> bool: + # Walk through the shape and test them against the given target, # taking into consideration variables, wildcards, etc. - if len(shape) != len(dimensions): + + if len(shape) != len(target): return False - assigned_variables: Dict[str, str] = {} - for inst_dim, cls_dim in zip(shape, dimensions): - cls_dim_ = cls_dim.strip() - inst_dim_ = str(inst_dim) - if _is_variable(cls_dim_): - # Since cls_dim_ is a variable, try to assign it with - # inst_dim_. This always succeeds if a variable with the same - # name hasn't been assigned already. - if ( - cls_dim_ in assigned_variables - and assigned_variables[cls_dim_] != inst_dim_ - ): - result = False - break - assigned_variables[cls_dim_] = inst_dim_ - elif inst_dim_ != cls_dim_ and not _is_wildcard(cls_dim_): - # Identical dimension sizes or wildcards are fine. - result = False - break - else: - # All is well, no errors have been encountered. - result = True - return result + shape_as_strings = (str(dim) for dim in shape) + variables: Dict[str, str] = {} + for dim, target_dim in zip(shape_as_strings, target): + if _is_wildcard(target_dim) or _is_assignable_var(dim, target_dim, variables): + continue + if dim != target_dim: + return False + return True + + +def _handle_ellipsis(shape: ShapeTuple, target: List[str]) -> List[str]: + # Let the ellipsis allows for any number of dimensions by replacing the + # ellipsis with the dimension size repeated the number of times that + # corresponds to the shape of the instance. + if target[-1] == "...": + dim_to_repeat = target[-2] + target = target[0:-1] + if len(shape) > len(target): + difference = len(shape) - len(target) + target += difference * [dim_to_repeat] + return target + + +def _is_assignable_var(dim: str, target_dim: str, variables: Dict[str, str]) -> bool: + # Return whether target_dim is a variable and can be assigned with dim. + return _is_variable(target_dim) and _can_assign_variable(dim, target_dim, variables) def _is_variable(dim: str) -> bool: @@ -151,22 +155,19 @@ def _is_variable(dim: str) -> bool: return dim[0] in string.ascii_uppercase +def _can_assign_variable(dim: str, target_dim: str, variables: Dict[str, str]) -> bool: + # Check and assign a variable. + assignable = variables.get(target_dim) in (None, dim) + variables[target_dim] = dim + return assignable + + def _is_wildcard(dim: str) -> bool: # Return whether dim is a wildcard (i.e. the character that takes any # dimension size). return dim == "*" -def _handle_ellipsis(dimensions: List[str], shape: ShapeTuple) -> List[str]: - # Let the ellipsis allows for any number of dimensions by replacing the - # ellipsis with the dimension size repeated the number of times that - # corresponds to the shape of the instance. - result = dimensions - if len(dimensions) == 2 and dimensions[1].strip() == "...": - result = dimensions[0:1] * len(shape) - return result - - _REGEX_SEPARATOR = r"(\s*,\s*)" _REGEX_DIMENSION_SIZE = r"(\s*[0-9]+\s*)" _REGEX_VARIABLE = r"(\s*\b[A-Z]\w*\s*)" @@ -184,7 +185,5 @@ _REGEX_DIMENSION_WITH_LABEL = rf"({_REGEX_DIMENSION}(\s+{_REGEX_LABEL})*)" _REGEX_DIMENSIONS = ( rf"{_REGEX_DIMENSION_WITH_LABEL}({_REGEX_SEPARATOR}{_REGEX_DIMENSION_WITH_LABEL})*" ) -_REGEX_DIMENSION_ELLIPSIS = ( - rf"({_REGEX_DIMENSION_WITH_LABEL}{_REGEX_SEPARATOR}\.\.\.\s*)" -) -_REGEX_SHAPE_EXPRESSION = rf"^({_REGEX_DIMENSIONS}|{_REGEX_DIMENSION_ELLIPSIS})$" +_REGEX_DIMENSIONS_ELLIPSIS = rf"({_REGEX_DIMENSIONS}{_REGEX_SEPARATOR}\.\.\.\s*)" +_REGEX_SHAPE_EXPRESSION = rf"^({_REGEX_DIMENSIONS}|{_REGEX_DIMENSIONS_ELLIPSIS})$"
ramonhagenaars/nptyping
0e37975a962e06fa3bcbb516d6ba33b17a7a86e7
diff --git a/tests/test_ndarray.py b/tests/test_ndarray.py index bbf647f..e4929b4 100644 --- a/tests/test_ndarray.py +++ b/tests/test_ndarray.py @@ -105,6 +105,20 @@ class NDArrayTest(TestCase): NDArray[Shape["*, ..."], Any], "This should match with an array of any dimensions of any size.", ) + self.assertIsInstance( + np.array([[0]]), + NDArray[Shape["1, 1, ..."], Any], + "This should match with an array of shape (1, 1).", + ) + self.assertIsInstance( + np.array([[[[0]]]]), + NDArray[Shape["1, 1, ..."], Any], + "This should match with an array of shape (1, 1, 1, 1).", + ) + self.assertIsInstance( + np.array([[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]), + NDArray[Shape["1, 2, ..."], Any], + ) def test_isinstance_fails_with_ellipsis(self): self.assertNotIsInstance( @@ -112,6 +126,10 @@ class NDArrayTest(TestCase): NDArray[Shape["1, ..."], Any], "This should match with an array of any dimensions of size 1.", ) + self.assertNotIsInstance( + np.array([[[[[0], [0]], [[0], [0]]], [[[0], [0]], [[0], [0]]]]]), + NDArray[Shape["1, 2, ..."], Any], + ) def test_isinstance_succeeds_with_dim_breakdown(self): self.assertIsInstance( diff --git a/tests/test_shape_expression.py b/tests/test_shape_expression.py index 7dd5453..5e2b571 100644 --- a/tests/test_shape_expression.py +++ b/tests/test_shape_expression.py @@ -14,8 +14,10 @@ class ShapeExpressionTest(TestCase): validate_shape_expression("1, 2, 3") validate_shape_expression("1, ...") validate_shape_expression("*, ...") + validate_shape_expression("*, *, ...") validate_shape_expression("VaRiAbLe123, ...") validate_shape_expression("[a, b], ...") + validate_shape_expression("2, 3, ...") validate_shape_expression("*, *, *") validate_shape_expression("VaRiAbLe123, VaRiAbLe123, VaRiAbLe123") validate_shape_expression("[a]")
Express constraints for the first few channels and then specify ellipses? Unless I'm missing something there seems to be no way to encode the idea that an array has at least 2 dimensions with some size constraint, but then it may also contain any other trailing dimensions. For instance, I would have thought that I would say that I could have an array with at least 2 dimensions like this: `Shape['*,*,...']` but that seems to return an InvalidShapeError. Looking at the grammar, this seems to make sense, the line `shape_expression : dimensions | dimension "," ellipsis` indicates that an ellipsis is only valid when there is one dimension. If we modify the grammar such that we are using `shape_expression : dimensions | dimensions "," ellipsis`, it _should_ be possible to express what I'm looking for, however in my prototyping I couldn't parse the expression with an LALR parser, I had to use Earley instead. Here is my prototype I made with Lark: ```python import lark SHAPE_GRAMMAR = ( ''' // https://github.com/ramonhagenaars/nptyping/blob/master/USERDOCS.md#Shape-expressions ?start: shape_expression shape_expression : dimensions | dimensions "," ellipsis dimensions : dimension | dimension "," dimensions dimension : unlabeled_dimension | labeled_dimension labeled_dimension : unlabeled_dimension " " label unlabeled_dimension : number | variable | wildcard | dimension_breakdown wildcard : "*" dimension_breakdown : "[" labels "]" labels : label | label "," labels label : lletter | lletter word variable : uletter | uletter word word : letter | word underscore | word number letter : lletter | uletter uletter : "A"|"B"|"C"|"D"|"E"|"F"|"G"|"H"|"I"|"J"|"K"|"L"|"M"|"N"|"O"|"P"|"Q"|"R"|"S"|"T"|"U"|"V"|"W"|"X"|"Y"|"Z" lletter : "a"|"b"|"c"|"d"|"e"|"f"|"g"|"h"|"i"|"j"|"k"|"l"|"m"|"n"|"o"|"p"|"q"|"r"|"s"|"t"|"u"|"v"|"w"|"x"|"y"|"z" number : digit | number digit digit : "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9" underscore : "_" ellipsis : "..." ''') # shape_parser = lark.Lark(SHAPE_GRAMMAR, start='start', parser='lalr') shape_parser = lark.Lark(SHAPE_GRAMMAR, start='start', parser='earley') print(shape_parser.parse('3').pretty()) print(shape_parser.parse('N,M').pretty()) print(shape_parser.parse('N,3').pretty()) print(shape_parser.parse('*,*').pretty()) print(shape_parser.parse('2,...').pretty()) print(shape_parser.parse('*,...').pretty()) print(shape_parser.parse('1,3,4,5,...').pretty()) print(shape_parser.parse('*,*,...').pretty()) ```
0.0
0e37975a962e06fa3bcbb516d6ba33b17a7a86e7
[ "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_with_ellipsis", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_with_ellipsis", "tests/test_shape_expression.py::ShapeExpressionTest::test_validate_shape_expression_success" ]
[ "tests/test_ndarray.py::NDArrayTest::test_changing_attributes_is_forbidden", "tests/test_ndarray.py::NDArrayTest::test_instantiation_is_forbidden", "tests/test_ndarray.py::NDArrayTest::test_invalid_arguments_raise_errors", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_if_nr_of_shapes_dont_match", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_if_shape_size_dont_match", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_if_structure_contains_invalid_types", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_if_structure_doesnt_match", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_if_variables_cannot_be_assigned", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_with_dim_breakdown", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_if_shapes_match_exactly", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_if_structure_match_exactly", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_if_variables_can_be_assigned", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_with_0d_arrays", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_with_dim_breakdown", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_with_labels", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_with_wildcards", "tests/test_ndarray.py::NDArrayTest::test_ndarray_is_hashable", "tests/test_ndarray.py::NDArrayTest::test_recursive_structure_is_forbidden", "tests/test_ndarray.py::NDArrayTest::test_str", "tests/test_ndarray.py::NDArrayTest::test_subclassing_is_forbidden", "tests/test_ndarray.py::NDArrayTest::test_types_with_nptyping_aliases", "tests/test_ndarray.py::NDArrayTest::test_types_with_numpy_dtypes", "tests/test_ndarray.py::NDArrayTest::test_valid_arguments_should_not_raise", "tests/test_shape_expression.py::ShapeExpressionTest::test_normalize_shape_expression", "tests/test_shape_expression.py::ShapeExpressionTest::test_validate_shape_expression_fail" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-06-26 14:14:08+00:00
mit
5,170
ramonhagenaars__nptyping-86
diff --git a/HISTORY.md b/HISTORY.md index 40c00c1..5409690 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,10 @@ # History +## 2.3.0 (2022-08-28) + +- Added support for subarrays with shape expressions inside structure expressions. +- Added support for wildcards in structure expressions. + ## 2.2.0 (2022-06-26) - Added support for expressing "at least N dimensions". diff --git a/README.md b/README.md index b64c1c4..f9bf3c1 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,13 @@ True ``` +Subarrays can be expressed with a shape expression between square brackets: +```python +>>> Structure["name: Int[3, 3]"] +Structure['name: Int[3, 3]'] + +``` + ### Record arrays The recarray is a specialization of a structured array. You can use `RecArray` to express them. diff --git a/USERDOCS.md b/USERDOCS.md index b4b4935..203a8fc 100644 --- a/USERDOCS.md +++ b/USERDOCS.md @@ -19,6 +19,7 @@ * [DTypes](#DTypes) * [Structure expressions](#Structure-expressions) * [Syntax](#Syntax-structure-expressions) + * [Subarrays](#Subarrays) * [RecArray](#RecArray) * [Examples](#Examples) * [Similar projects](#Similar-projects) @@ -212,8 +213,6 @@ False ``` - - #### Dimension breakdowns A dimension can be broken down into more detail. We call this a **dimension breakdown**. This can be useful to clearly describe what a dimension means. Example: @@ -328,7 +327,6 @@ NDArray[Any, Floating] ``` - ### Structure expressions You can denote the structure of a structured array using what we call a **structure expression**. This expression - again a string - can be put into `Structure` and can then be used in an `NDArray`. @@ -391,10 +389,12 @@ colons), but this is not included in the schema below. ``` structure-expression = <fields> fields = <field>|<field>","<fields> -field = <field_name>":"<field_type>|"["<combined_field_names>"]:"<field_type> -combined_field_names = <field_name>","<field_name>|<field_name>","<combined_field_names> -field_type = <word> -field_name = <word> +field = <field-name>":"<field-type>|"["<combined-field-names>"]:"<field-type> +combined-field-names = <field-name>","<field-name>|<field-name>","<combined-field-names> +field-type = <word>|<word><field-subarray-shape>|<wildcard> +wildcard = "*" +field-subarray-shape = "["<shape-expression>"]" +field-name = <word> word = <letter>|<word><underscore>|<word><number> letter = <lletter>|<uletter> uletter = "A"|"B"|"C"|"D"|"E"|"F"|"G"|"H"|"I"|"J"|"K"|"L"|"M"|"N"|"O"|"P"|"Q"|"R"|"S"|"T"|"U"|"V"|"W"|"X"|"Y"|"Z" @@ -404,6 +404,20 @@ digit = "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9" underscore = "_" ``` +#### Subarrays +You can express the shape of a subarray using brackets after a type. You can use the full power of shape expressions. + +```python +>>> from typing import Any +>>> import numpy as np +>>> from nptyping import NDArray, Structure + +>>> arr = np.array([("x")], np.dtype([("x", "U10", (2, 2))])) +>>> isinstance(arr, NDArray[Any, Structure["x: Str[2, 2]"]]) +True + +``` + ### RecArray The `RecArray` corresponds to [numpy.recarray](https://numpy.org/doc/stable/reference/generated/numpy.recarray.html). It is an extension of `NDArray` and behaves similarly. A key difference is that with `RecArray`, the `Structure` OR diff --git a/nptyping/package_info.py b/nptyping/package_info.py index a2a4f23..4909726 100644 --- a/nptyping/package_info.py +++ b/nptyping/package_info.py @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ __title__ = "nptyping" -__version__ = "2.2.0" +__version__ = "2.3.0" __author__ = "Ramon Hagenaars" __author_email__ = "[email protected]" __description__ = "Type hints for NumPy." diff --git a/nptyping/structure_expression.py b/nptyping/structure_expression.py index 63f61d1..119726c 100644 --- a/nptyping/structure_expression.py +++ b/nptyping/structure_expression.py @@ -30,12 +30,19 @@ from typing import ( Dict, List, Mapping, + Type, Union, ) import numpy as np -from nptyping.error import InvalidStructureError +from nptyping.error import InvalidShapeError, InvalidStructureError +from nptyping.shape import Shape +from nptyping.shape_expression import ( + check_shape, + normalize_shape_expression, + validate_shape_expression, +) from nptyping.typing_ import StructureExpression if TYPE_CHECKING: @@ -59,6 +66,7 @@ def validate_structure_expression( _validate_structure_expression_contains_no_multiple_field_names( structure_expression ) + _validate_sub_array_expressions(structure_expression) def check_structure( @@ -77,17 +85,38 @@ def check_structure( :return: True if the given dtype is valid with the given target. """ fields: Mapping[str, Any] = structured_dtype.fields or {} # type: ignore[assignment] + + # Add the wildcard to the lexicon. We want to do this here to keep + # knowledge on wildcards in one place (this module). + type_per_name_with_wildcard = {**type_per_name, "*": object} # type: ignore[arg-type] + for name, dtype_tuple in fields.items(): dtype = dtype_tuple[0] target_type_name = target.get_type(name) - check_type_name(target_type_name, type_per_name) - target_type = type_per_name[target_type_name] - if not issubclass(dtype.type, target_type): + target_type_shape_match = re.search(_REGEX_FIELD_SHAPE, target_type_name) + actual_type = dtype.type + if target_type_shape_match: + if not dtype.subdtype: + # the dtype does not contain a shape. + return False + actual_type = dtype.subdtype[0].type + target_type_shape = target_type_shape_match.group(1) + shape_corresponds = check_shape(dtype.shape, Shape[target_type_shape]) + if not shape_corresponds: + return False + target_type_name = target_type_name.replace( + target_type_shape_match.group(0), "" + ) + check_type_name(target_type_name, type_per_name_with_wildcard) + target_type = type_per_name_with_wildcard[target_type_name] + if not issubclass(actual_type, target_type): return False return True -def check_type_names(structure: "Structure", type_per_name: Dict[str, type]) -> None: +def check_type_names( + structure: "Structure", type_per_name: Dict[str, Type[object]] +) -> None: """ Check the given structure for any invalid type names in the given context of type_per_name. Raises an InvalidStructureError if a type name is @@ -100,7 +129,7 @@ def check_type_names(structure: "Structure", type_per_name: Dict[str, type]) -> check_type_name(type_, type_per_name) -def check_type_name(type_name: str, type_per_name: Dict[str, type]) -> None: +def check_type_name(type_name: str, type_per_name: Dict[str, Type[object]]) -> None: """ Check if the given type_name is in type_per_name and raise a meaningful error if not. @@ -108,6 +137,8 @@ def check_type_name(type_name: str, type_per_name: Dict[str, type]) -> None: :param type_per_name: a dict that is looked in for type_name. :return: None. """ + # Remove any subarray stuff here. + type_name = type_name.split("[")[0] if type_name not in type_per_name: close_matches = get_close_matches( type_name, type_per_name.keys(), 3, cutoff=0.4 @@ -135,7 +166,7 @@ def normalize_structure_expression( structure_expression = re.sub(r"\s*", "", structure_expression) type_to_names_dict = _create_type_to_names_dict(structure_expression) normalized_structure_expression = _type_to_names_dict_to_str(type_to_names_dict) - return normalized_structure_expression.replace(",", ", ") + return normalized_structure_expression.replace(",", ", ").replace(" ", " ") def create_name_to_type_dict( @@ -188,6 +219,23 @@ def _validate_structure_expression_contains_no_multiple_field_names( ) +def _validate_sub_array_expressions(structure_expression: str) -> None: + # Validate that the given structure expression does not contain any shape + # expressions for sub arrays that are invalid. + for field_match in re.findall(_REGEX_FIELD, structure_expression): + field_type = field_match[0].split(_FIELD_TYPE_POINTER)[1] + type_shape_match = re.search(_REGEX_FIELD_SHAPE, field_type) + if type_shape_match: + type_shape = type_shape_match[1] + try: + validate_shape_expression(type_shape) + except InvalidShapeError as err: + raise InvalidStructureError( + f"'{structure_expression}' is not a valid structure" + f" expression; {str(err)}" + ) from err + + def _create_type_to_names_dict( structure_expression: StructureExpression, ) -> Dict[str, List[str]]: @@ -199,10 +247,17 @@ def _create_type_to_names_dict( field_name_combination_match = re.match( _REGEX_FIELD_NAMES_COMBINATION, field_name_combination ) + field_type_shape_match = re.search(_REGEX_FIELD_SHAPE, field_type) if field_name_combination_match: field_names = field_name_combination_match.group(2).split(_SEPARATOR) else: field_names = [field_name_combination] + if field_type_shape_match: + type_shape = field_type_shape_match.group(1) + normalized_type_shape = normalize_shape_expression(type_shape) + field_type = field_type.replace( + field_type_shape_match.group(0), f"[{normalized_type_shape}]" + ) names_per_type[field_type] += field_names return { field_type: sorted(names_per_type[field_type]) @@ -230,7 +285,11 @@ _REGEX_FIELD_NAMES_COMBINATION = rf"(\s*\[{_REGEX_FIELD_NAMES}\]\s*)" _REGEX_FIELD_LEFT = rf"({_REGEX_FIELD_NAME}|{_REGEX_FIELD_NAMES_COMBINATION})" _REGEX_FIELD_TYPE = r"(\s*[a-zA-Z]\w*\s*)" _REGEX_FIELD_TYPE_WILDCARD = r"(\s*\*\s*)" -_REGEX_FIELD_RIGHT = rf"({_REGEX_FIELD_TYPE}|{_REGEX_FIELD_TYPE_WILDCARD})" +_REGEX_FIELD_SHAPE = r"\[([^\]]+)\]" +_REGEX_FIELD_SHAPE_MAYBE = rf"\s*({_REGEX_FIELD_SHAPE})?\s*" +_REGEX_FIELD_RIGHT = ( + rf"({_REGEX_FIELD_TYPE}|{_REGEX_FIELD_TYPE_WILDCARD}){_REGEX_FIELD_SHAPE_MAYBE}" +) _REGEX_FIELD_TYPE_POINTER = rf"(\s*{_FIELD_TYPE_POINTER}\s*)" _REGEX_FIELD = ( rf"(\s*{_REGEX_FIELD_LEFT}{_REGEX_FIELD_TYPE_POINTER}{_REGEX_FIELD_RIGHT}\s*)"
ramonhagenaars/nptyping
260da2696fbf9172658d3c4363bfb50478b9068b
diff --git a/tests/test_ndarray.py b/tests/test_ndarray.py index e4929b4..f4f7676 100644 --- a/tests/test_ndarray.py +++ b/tests/test_ndarray.py @@ -187,6 +187,10 @@ class NDArrayTest(TestCase): NDArray[Any, Structure["[name, age]: Str"]], ) + def test_isinstance_succeeds_if_structure_subarray_matches(self): + arr = np.array([("x")], np.dtype([("x", "U10", (2, 2))])) + self.assertIsInstance(arr, NDArray[Any, Structure["x: Str[2, 2]"]]) + def test_isinstance_fails_if_structure_contains_invalid_types(self): with self.assertRaises(InvalidStructureError) as err: NDArray[Any, Structure["name: Str, age: Float, address: Address"]] diff --git a/tests/test_structure_expression.py b/tests/test_structure_expression.py index 3c77c9d..fc52930 100644 --- a/tests/test_structure_expression.py +++ b/tests/test_structure_expression.py @@ -23,6 +23,44 @@ class StructureExpressionTest(TestCase): structure2 = Structure["[a, b, c]: Integer"] self.assertTrue(check_structure(dtype2, structure2, dtype_per_name)) + dtype3 = np.dtype([("name", "U10")]) + structure3 = Structure["name: *"] + self.assertTrue(check_structure(dtype3, structure3, dtype_per_name)) + + def test_check_structure_with_sub_array(self): + dtype = np.dtype([("x", "U10", (2, 2))]) + structure = Structure["x: Str[2, 2]"] + self.assertTrue(check_structure(dtype, structure, dtype_per_name)) + + dtype2 = np.dtype([("x", "U10", (2, 2))]) + structure2 = Structure["x: Int[2, 2]"] + self.assertFalse( + check_structure(dtype2, structure2, dtype_per_name), + "It should fail because of the type.", + ) + + dtype3 = np.dtype([("x", "U10", (3, 3))]) + structure3 = Structure["x: Str[2, 2]"] + self.assertFalse( + check_structure(dtype3, structure3, dtype_per_name), + "It should fail because of the shape.", + ) + + dtype4 = np.dtype([("x", "U10", (2, 2)), ("y", "U10", (2, 2))]) + structure4 = Structure["x: Str[2, 2], y: Str[2, 2]"] + self.assertTrue(check_structure(dtype4, structure4, dtype_per_name)) + + dtype5 = np.dtype([("x", "U10", (2, 2)), ("y", "U10", (2, 2))]) + structure5 = Structure["[x, y]: Str[2, 2]"] + self.assertTrue(check_structure(dtype5, structure5, dtype_per_name)) + + dtype6 = np.dtype([("x", "U10")]) + structure6 = Structure["x: Str[2, 2]"] + self.assertFalse( + check_structure(dtype6, structure6, dtype_per_name), + "It should fail because it doesn't contain a sub array at all.", + ) + def test_check_structure_false(self): dtype = np.dtype([("name", "U10"), ("age", "i4")]) structure = Structure["name: Str, age: UInt"] @@ -66,8 +104,12 @@ class StructureExpressionTest(TestCase): validate_structure_expression("a_123: t") validate_structure_expression("abc: type") validate_structure_expression("abc: *") + validate_structure_expression("abc: type[2, 2]") + validate_structure_expression("abc: type [*, ...]") validate_structure_expression("abc: type, def: type") + validate_structure_expression("abc: type[*, 2, ...], def: type[2 ]") validate_structure_expression("[abc, def]: type") + validate_structure_expression("[abc, def]: type[*, ...]") validate_structure_expression("[abc, def]: type1, ghi: type2") validate_structure_expression("[abc, def]: type1, [ghi, jkl]: type2") validate_structure_expression( @@ -104,6 +146,15 @@ class StructureExpressionTest(TestCase): validate_structure_expression("[a,b,]: type") with self.assertRaises(InvalidStructureError): validate_structure_expression("[,a,b]: type") + with self.assertRaises(InvalidStructureError): + validate_structure_expression("abc: type []") + with self.assertRaises(InvalidStructureError): + validate_structure_expression("a: t[]") + with self.assertRaises(InvalidStructureError) as err: + validate_structure_expression( + "a: t[*, 2, ...], b: t[not-a-valid-shape-expression]" + ) + self.assertIn("not-a-valid-shape-expression", str(err.exception)) with self.assertRaises(InvalidStructureError) as err: validate_structure_expression("a: t1, b: t2, c: t3, a: t4") self.assertEqual( @@ -138,6 +189,9 @@ class StructureExpressionTest(TestCase): "[a, b, d, e]: t1, c: t2", normalize_structure_expression("[b, a]: t1, c: t2, [d, e]: t1"), ) + self.assertEqual( + "a: t[*, ...]", normalize_structure_expression(" a : t [ * , ... ]") + ) def test_create_name_to_type_dict(self): output = create_name_to_type_dict("a: t1, b: t2, c: t1")
Nested dtype support How would you be able to use `nptyping` to define the type of a structured array with the following `dtype`: ```python dtype = numpy.dtype([('index', numpy.uint64), ('measurements', numpy.float64, (2,))]) ``` I tried variations of ```python NDArray[Shape["*"], Structure["index: UInt64, measurements: Float64"]]) ``` but this doesn't work (`assert_isinstance` fails), and I couldn't define anything in the docs that would allow for specifying the shape `(2,)` of the `measurements` sub-array. Would it be possible to directly use `dtype` objects for type specs?
0.0
260da2696fbf9172658d3c4363bfb50478b9068b
[ "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_if_structure_subarray_matches", "tests/test_structure_expression.py::StructureExpressionTest::test_check_structure_true", "tests/test_structure_expression.py::StructureExpressionTest::test_check_structure_with_sub_array", "tests/test_structure_expression.py::StructureExpressionTest::test_normalize_structure_expression", "tests/test_structure_expression.py::StructureExpressionTest::test_validate_structure_expression_success" ]
[ "tests/test_ndarray.py::NDArrayTest::test_changing_attributes_is_forbidden", "tests/test_ndarray.py::NDArrayTest::test_instantiation_is_forbidden", "tests/test_ndarray.py::NDArrayTest::test_invalid_arguments_raise_errors", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_if_nr_of_shapes_dont_match", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_if_shape_size_dont_match", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_if_structure_contains_invalid_types", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_if_structure_doesnt_match", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_if_variables_cannot_be_assigned", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_with_dim_breakdown", "tests/test_ndarray.py::NDArrayTest::test_isinstance_fails_with_ellipsis", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_if_shapes_match_exactly", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_if_structure_match_exactly", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_if_variables_can_be_assigned", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_with_0d_arrays", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_with_dim_breakdown", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_with_ellipsis", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_with_labels", "tests/test_ndarray.py::NDArrayTest::test_isinstance_succeeds_with_wildcards", "tests/test_ndarray.py::NDArrayTest::test_ndarray_is_hashable", "tests/test_ndarray.py::NDArrayTest::test_recursive_structure_is_forbidden", "tests/test_ndarray.py::NDArrayTest::test_str", "tests/test_ndarray.py::NDArrayTest::test_subclassing_is_forbidden", "tests/test_ndarray.py::NDArrayTest::test_types_with_nptyping_aliases", "tests/test_ndarray.py::NDArrayTest::test_types_with_numpy_dtypes", "tests/test_ndarray.py::NDArrayTest::test_valid_arguments_should_not_raise", "tests/test_structure_expression.py::StructureExpressionTest::test_check_structure_false", "tests/test_structure_expression.py::StructureExpressionTest::test_check_structure_invalid_type", "tests/test_structure_expression.py::StructureExpressionTest::test_create_name_to_type_dict", "tests/test_structure_expression.py::StructureExpressionTest::test_validate_structure_expression_fail" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2022-06-26 19:15:03+00:00
mit
5,171
ramonsaraiva__pubg-python-87
diff --git a/pubg_python/clients.py b/pubg_python/clients.py index dcf7edf..04f3a21 100644 --- a/pubg_python/clients.py +++ b/pubg_python/clients.py @@ -13,6 +13,7 @@ class Client: API_OK = 200 API_ERRORS_MAPPING = { 401: exceptions.UnauthorizedError, + 403: exceptions.OldTelemetryError, 404: exceptions.NotFoundError, 415: exceptions.InvalidContentTypeError, 429: exceptions.RateLimitError, @@ -45,4 +46,12 @@ class APIClient(Client): class TelemetryClient(Client): - pass + + TELEMETRY_HOSTS = [ + 'telemetry-cdn.playbattlegrounds.com' + ] + + def request(self, endpoint): + if furl.furl(endpoint).host not in self.TELEMETRY_HOSTS: + raise exceptions.TelemetryURLError + return super().request(endpoint) diff --git a/pubg_python/exceptions.py b/pubg_python/exceptions.py index 9a96ba8..aebfc2b 100644 --- a/pubg_python/exceptions.py +++ b/pubg_python/exceptions.py @@ -51,3 +51,15 @@ class RateLimitError(APIError): int(self.response_headers.get('X-Ratelimit-Reset'))) super().__init__('Too many requests. Limit: {} Reset: {}'.format( self.rl_limit, self.rl_reset)) + + +class OldTelemetryError(APIError): + + def __init__(self, *args, **kwargs): + super().__init__('Telemetry was not found or no longer available') + + +class TelemetryURLError(APIError): + + def __init__(self, *args, **kwargs): + super().__init__('Telemetry host differs from official')
ramonsaraiva/pubg-python
06444796f8d9156ca3b41c9ec104489a233f2c95
diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 68ff363..73effb6 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -9,7 +9,9 @@ from pubg_python.exceptions import ( UnauthorizedError, NotFoundError, InvalidContentTypeError, - RateLimitError + RateLimitError, + OldTelemetryError, + TelemetryURLError ) api = PUBG('apikey', Shard.STEAM) BASE_URL = APIClient.BASE_URL @@ -90,3 +92,23 @@ def test_client_ratelimit_error(mock): assert False except RateLimitError: assert True + + +def test_old_telemetry_error(mock): + url = 'https://telemetry-cdn.playbattlegrounds.com/missed_path.json' + mock.get(url, status_code=403) + try: + api.telemetry(url) + assert False + except OldTelemetryError: + assert True + + +def test_telemetry_url_error(mock): + url = 'https://different-host.com/telemetry.json' + mock.get(url, status_code=200) + try: + api.telemetry(url) + assert False + except TelemetryURLError: + assert True diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index 4c63489..40929c0 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -6,7 +6,7 @@ from pubg_python.domain.telemetry.events import LogMatchDefinition api = PUBG('apikey', Shard.STEAM) BASE_URL = APIClient.BASE_URL -TELEMETRY_URL = 'http://telemetry.pubg' +TELEMETRY_URL = 'http://telemetry-cdn.playbattlegrounds.com/telemetry.json' TELEMETRY_JSON = json.load(open('tests/telemetry_response.json'))
New telemetry exceptions @ramonsaraiva In official PUBG API discord server i've found that there is undocumented 403 status code if telemetry was not found on servers or no longer available. Should i make a new exception (ex. `OldTelemetryError`) or just return `NotFoundError` for 403 status code? Examples: https://telemetry-cdn.playbattlegrounds.com/bluehole-pubg/steam/2019/08/28/21/18/5a9cc5e2-c9d9-11e9-8db7-0a586468ab66-telemetry.json https://telemetry-cdn.playbattlegrounds.com/bluehole-pubg/steam/2019/08/30/18/00/0fb4b2b6-cb50-11e9-a981-0a5864687231-telemetry.json P.S. Should we limit telemetry URL only for official PUBG host `telemetry-cdn.playbattlegrounds.com` otherwise `TelemetryURLError`?
0.0
06444796f8d9156ca3b41c9ec104489a233f2c95
[ "tests/test_exceptions.py::test_client_ratelimit_error", "tests/test_exceptions.py::test_api_error", "tests/test_exceptions.py::test_client_invalid_content_type_error", "tests/test_exceptions.py::test_telemetry_url_error", "tests/test_exceptions.py::test_invalid_shard_error", "tests/test_exceptions.py::test_required_filter_error", "tests/test_exceptions.py::test_client_notfound_error", "tests/test_exceptions.py::test_old_telemetry_error", "tests/test_exceptions.py::test_invalid_filter_error", "tests/test_exceptions.py::test_client_unauthorized_error", "tests/test_telemetry.py::test_events_from_type", "tests/test_telemetry.py::test_telemetry_from_json", "tests/test_telemetry.py::test_telemetry_instance" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-09-17 15:56:20+00:00
mit
5,172
randsleadershipslack__destalinator-169
diff --git a/README.md b/README.md index f5f8da1..90af60d 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ These channels need to be manually created by you in your Slack. ### Environment variables -All configs in `configuration.yaml` are overrideable through environment variables with the same name prefixed by `DESTALINATOR_` (e.g. `activated` -> `DESTALINATOR_ACTIVATED`). Set array environment variables (e.g. `DESTALINATOR_IGNORE_CHANNELS`) by comma delimiting items +All configs in `configuration.yaml` are overrideable through environment variables with the same name prefixed by `DESTALINATOR_` (e.g. `activated` -> `DESTALINATOR_ACTIVATED`). Set array environment variables (e.g. `DESTALINATOR_IGNORE_CHANNELS`) by comma delimiting items. If you only have one value for an array type environment variable add a training comma to denote the variable as a list. #### `DESTALINATOR_SB_TOKEN` (Required) diff --git a/config.py b/config.py index 364b3f6..d65d811 100644 --- a/config.py +++ b/config.py @@ -25,7 +25,7 @@ class Config(WithLogger): else: envvar = os.getenv('DESTALINATOR_' + upper_attrname) if envvar is not None: - return envvar.split(',') if ',' in envvar else envvar + return [x for x in envvar.split(',') if x] if ',' in envvar else envvar return self.config.get(attrname, '')
randsleadershipslack/destalinator
25cacb4a688f2501ef198ac2a86a0909bb6bdbb0
diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..e9c88c0 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,14 @@ +import os +import unittest + +from config import get_config + + +class ConfigTest(unittest.TestCase): + def setUp(self): + os.environ['DESTALINATOR_STRING_VARIABLE'] = 'test' + os.environ['DESTALINATOR_LIST_VARIABLE'] = 'test,' + + def test_environment_variable_configs(self): + self.assertEqual(get_config().string_variable, 'test') + self.assertListEqual(get_config().list_variable, ['test'])
List Configs Don't Work When Using Environment Variables Using a config like `ignore_channel_patterns` through the environment variable `DESTALINATOR_IGNORE_CHANNEL_PATTERNS=^auto-` causes everything to be ignored. The string pattern is not casted into a list properly and causes unexpected behavior. If there's a better env var syntax for this to work out of the box we should update docs, otherwise we'll need to code in a solution or not support env vars for list properties.
0.0
25cacb4a688f2501ef198ac2a86a0909bb6bdbb0
[ "tests/test_config.py::ConfigTest::test_environment_variable_configs" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-12-14 11:36:15+00:00
apache-2.0
5,173
raphaelm__defusedcsv-6
diff --git a/defusedcsv/csv.py b/defusedcsv/csv.py index 2656c96..a027b85 100644 --- a/defusedcsv/csv.py +++ b/defusedcsv/csv.py @@ -1,20 +1,28 @@ import re from csv import ( QUOTE_ALL, QUOTE_MINIMAL, QUOTE_NONE, QUOTE_NONNUMERIC, Dialect, - DictReader, DictWriter as BaseDictWriter, Error, Sniffer, excel, excel_tab, + DictReader, DictWriter as _BaseDictWriter, Error, Sniffer, excel, excel_tab, field_size_limit, get_dialect, list_dialects, reader, register_dialect, - unix_dialect, unregister_dialect, writer as basewriter, + unix_dialect, unregister_dialect, writer as _basewriter, + __doc__, ) +from numbers import Number + +from . import version as __version__ __all__ = ["QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE", - "Error", "Dialect", "excel", "excel_tab", "field_size_limit", "reader", "writer", + "Error", "Dialect", "__doc__", "excel", "excel_tab", + "field_size_limit", "reader", "writer", "register_dialect", "get_dialect", "list_dialects", "Sniffer", - "unregister_dialect", "DictReader", "DictWriter", "unix_dialect"] + "unregister_dialect", "__version__", "DictReader", "DictWriter", + "unix_dialect"] -def escape(payload): +def _escape(payload): if payload is None: return '' + if isinstance(payload, Number): + return payload payload = str(payload) if payload and payload[0] in ('@', '+', '-', '=', '|', '%') and not re.match("^-?[0-9,\\.]+$", payload): @@ -23,25 +31,30 @@ def escape(payload): return payload -class ProxyWriter: +class _ProxyWriter: def __init__(self, writer): self.writer = writer def writerow(self, row): - self.writer.writerow([escape(field) for field in row]) + try: + iter(row) + except TypeError as err: + msg = "iterable expected, not %s" % type(row).__name__ + raise Error(msg) from err + return self.writer.writerow([_escape(field) for field in row]) def writerows(self, rows): - self.writer.writerows([[escape(field) for field in row] for row in rows]) + return self.writer.writerows([[_escape(field) for field in row] for row in rows]) def __getattr__(self, item): return getattr(self.writer, item) def writer(csvfile, dialect='excel', **fmtparams): - return ProxyWriter(basewriter(csvfile, dialect, **fmtparams)) + return _ProxyWriter(_basewriter(csvfile, dialect, **fmtparams)) -class DictWriter(BaseDictWriter): +class DictWriter(_BaseDictWriter): def __init__(self, f, fieldnames, restval="", extrasaction="raise", dialect="excel", *args, **kwds): super().__init__(f, fieldnames, restval, extrasaction, dialect, *args, **kwds)
raphaelm/defusedcsv
26062bce682fa1ff99d43bde8332fb6e6ac970c0
diff --git a/tests/test_escape.py b/tests/test_escape.py index fa14347..93e2a50 100644 --- a/tests/test_escape.py +++ b/tests/test_escape.py @@ -1,5 +1,5 @@ import pytest -from defusedcsv.csv import escape +from defusedcsv.csv import _escape as escape @pytest.mark.parametrize("input,expected", [ @@ -44,9 +44,14 @@ def test_dangerous_sample_payloads(input, expected): "Test | Foo", "", None, +]) +def test_safe_sample_payloads(input): + assert escape(input) == (str(input) if input is not None else '') + [email protected]("input", [ 1, 2, True ]) -def test_safe_sample_payloads(input): - assert escape(input) == (str(input) if input is not None else '') +def test_safe_nonstr_sample_payloads(input): + assert escape(input) == input diff --git a/tests/test_unmodified.py b/tests/test_unmodified.py index e1d1326..e2548c3 100644 --- a/tests/test_unmodified.py +++ b/tests/test_unmodified.py @@ -32,6 +32,9 @@ def test_has_attributes(): assert hasattr(csv, 'QUOTE_NONNUMERIC') assert hasattr(csv, 'QUOTE_NONE') assert hasattr(csv, 'Error') + assert hasattr(csv, 'writer') + assert hasattr(csv, '__doc__') + assert hasattr(csv, '__version__') def test_dialect_registry():
writer.writerow() does not return anything The stdlib python csv writer will return the row (as string) when calling `writer.writerow(row)`. The `defusedcsv` proxy is not handing the value along though. ``` from defusedcsv import csv class EchoWriter: def write(self, value): return value pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) value = writer.writerow(["foo", "bar""]) ``` That returns `None`. When using stock `csv`, it'll return `"foo,bar"`. I admit, the above example may be a bit convoluted and there may be better ways to do this. However for maximum compatibility with the stdlib csv library it might make sense to mimic this behaviour.
0.0
26062bce682fa1ff99d43bde8332fb6e6ac970c0
[ "tests/test_escape.py::test_dangerous_sample_payloads[=1+1-'=1+1_0]", "tests/test_escape.py::test_dangerous_sample_payloads[-1+1-'-1+1]", "tests/test_escape.py::test_dangerous_sample_payloads[+1+1-'+1+1]", "tests/test_escape.py::test_dangerous_sample_payloads[=1+1-'=1+1_1]", "tests/test_escape.py::test_dangerous_sample_payloads[@A3-'@A3]", "tests/test_escape.py::test_dangerous_sample_payloads[%1-'%1]", "tests/test_escape.py::test_dangerous_sample_payloads[|1+1-'\\\\|1+1]", "tests/test_escape.py::test_dangerous_sample_payloads[=1|2-'=1\\\\|2]", "tests/test_escape.py::test_dangerous_sample_payloads[=cmd|'", "tests/test_escape.py::test_dangerous_sample_payloads[@SUM(1+1)*cmd|'", "tests/test_escape.py::test_dangerous_sample_payloads[-2+3+cmd|'", "tests/test_escape.py::test_dangerous_sample_payloads[=HYPERLINK(\"http://contextis.co.uk?leak=\"&A1&A2,\"Error:", "tests/test_escape.py::test_safe_sample_payloads[1+2]", "tests/test_escape.py::test_safe_sample_payloads[1]", "tests/test_escape.py::test_safe_sample_payloads[Foo]", "tests/test_escape.py::test_safe_sample_payloads[1.3]", "tests/test_escape.py::test_safe_sample_payloads[1,2]", "tests/test_escape.py::test_safe_sample_payloads[-1.3]", "tests/test_escape.py::test_safe_sample_payloads[-1,2]", "tests/test_escape.py::test_safe_sample_payloads[Foo", "tests/test_escape.py::test_safe_sample_payloads[1-2]", "tests/test_escape.py::test_safe_sample_payloads[1=3]", "tests/test_escape.py::test_safe_sample_payloads[[email protected]]", "tests/test_escape.py::test_safe_sample_payloads[19.00", "tests/test_escape.py::test_safe_sample_payloads[Test", "tests/test_escape.py::test_safe_sample_payloads[]", "tests/test_escape.py::test_safe_sample_payloads[None]", "tests/test_escape.py::test_safe_nonstr_sample_payloads[1]", "tests/test_escape.py::test_safe_nonstr_sample_payloads[2]", "tests/test_escape.py::test_safe_nonstr_sample_payloads[True]", "tests/test_unmodified.py::test_read", "tests/test_unmodified.py::test_has_attributes", "tests/test_unmodified.py::test_dialect_registry" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-04-08 12:22:53+00:00
apache-2.0
5,174
rapidpro__rapidpro-python-38
diff --git a/temba_client/utils.py b/temba_client/utils.py index 39a3a2a..2489884 100644 --- a/temba_client/utils.py +++ b/temba_client/utils.py @@ -33,8 +33,11 @@ def parse_iso8601(value): def format_iso8601(value): """ - Formats a datetime as a UTC ISO8601 date + Formats a datetime as a UTC ISO8601 date or returns None if value is None """ + if value is None: + return None + _format = ISO8601_DATETIME_FORMAT + '.%f' return six.text_type(value.astimezone(pytz.UTC).strftime(_format))
rapidpro/rapidpro-python
3c9417903b2426c57d1b355cdf24ca9f26660c7c
diff --git a/temba_client/tests.py b/temba_client/tests.py index d8386f7..e24f86a 100644 --- a/temba_client/tests.py +++ b/temba_client/tests.py @@ -72,6 +72,9 @@ class UtilsTest(TembaTest): d = datetime.datetime(2014, 1, 2, 3, 4, 5, 6, UtilsTest.TestTZ()) self.assertEqual(format_iso8601(d), '2014-01-02T08:04:05.000006') + def test_format_iso8601_should_return_none_when_no_datetime_given(self): + self.assertIs(format_iso8601(None), None) + def test_parse_iso8601(self): dt = datetime.datetime(2014, 1, 2, 3, 4, 5, 0, pytz.UTC) self.assertEqual(parse_iso8601('2014-01-02T03:04:05.000000Z'), dt)
Null DatetimeField raises an exception upon serialisation request Objects with DatetimeField attributes cannot be properly serialised when any of their DatetimeField attributes is not set (i.e. set to null in the JSON response). This makes the following scenario possible: 1. fetch data from the server (e.g. TembaClient(...).get_runs()) - the data is internally deserialised by rapidpro-python 2. fed the result of this deserialisation process back to rapidpro-python to have it (re)serialised 3. error (please see the example traceback below) ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ego/.virtualenvs/rapidpro-python/local/lib/python2.7/site-packages/temba_client/serialization.py", line 63, in serialize field_value = field.serialize(attr_value) File "/home/ego/.virtualenvs/rapidpro-python/local/lib/python2.7/site-packages/temba_client/serialization.py", line 148, in serialize return [self.item_class.serialize(item) for item in value] File "/home/ego/.virtualenvs/rapidpro-python/local/lib/python2.7/site-packages/temba_client/serialization.py", line 63, in serialize field_value = field.serialize(attr_value) File "/home/ego/.virtualenvs/rapidpro-python/local/lib/python2.7/site-packages/temba_client/serialization.py", line 122, in serialize return format_iso8601(value) File "/home/ego/.virtualenvs/rapidpro-python/local/lib/python2.7/site-packages/temba_client/utils.py", line 40, in format_iso8601 return six.text_type(value.astimezone(pytz.UTC).strftime(_format)) AttributeError: 'NoneType' object has no attribute 'astimezone' ```
0.0
3c9417903b2426c57d1b355cdf24ca9f26660c7c
[ "temba_client/tests.py::UtilsTest::test_format_iso8601_should_return_none_when_no_datetime_given" ]
[ "temba_client/tests.py::UtilsTest::test_format_iso8601", "temba_client/tests.py::UtilsTest::test_parse_iso8601", "temba_client/tests.py::FieldsTest::test_boolean", "temba_client/tests.py::FieldsTest::test_integer", "temba_client/tests.py::FieldsTest::test_object_list", "temba_client/tests.py::TembaObjectTest::test_create", "temba_client/tests.py::TembaObjectTest::test_deserialize", "temba_client/tests.py::TembaObjectTest::test_serialize", "temba_client/tests.py::BaseClientTest::test_init" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2016-10-05 17:59:48+00:00
bsd-3-clause
5,175
rapidpro__rapidpro-python-66
diff --git a/temba_client/exceptions.py b/temba_client/exceptions.py index 253903c..95594ba 100644 --- a/temba_client/exceptions.py +++ b/temba_client/exceptions.py @@ -56,7 +56,8 @@ class TembaHttpError(TembaException): class TembaSerializationException(TembaException): - pass + def __init__(self, message): + self.message = message class TembaMultipleResultsError(TembaException):
rapidpro/rapidpro-python
5872006fa0f407bd2a859b07b1cb6d8d9bb11768
diff --git a/temba_client/tests.py b/temba_client/tests.py index 35578a2..1da8715 100644 --- a/temba_client/tests.py +++ b/temba_client/tests.py @@ -106,6 +106,12 @@ class TestType(TembaObject): meh = ObjectDictField(item_class=TestSubType) +class TembaSerializationExceptionTest(TembaTest): + def test_str_works(self): + err = TembaSerializationException("boop") + self.assertEqual(str(err), "boop") + + class FieldsTest(TembaTest): def test_boolean(self): field = BooleanField()
TembaSerializationException always has the message <exception str() failed> Hello, I was using the `TembaObject.deserialize()` method to deserialize archived `Run` objects in my project (https://github.com/JustFixNYC/tenants2/pull/902) and noticed that an unusual exception was occurring. It's easily reproducible in the REPL: ``` >>> from temba_client.serialization import TembaSerializationException >>> >>> raise TembaSerializationException('boop') Traceback (most recent call last): File "<stdin>", line 1, in <module> temba_client.exceptions.TembaSerializationException: <exception str() failed> ``` The actual cause of `str()` failing can be found via: ``` >>> str(TembaSerializationException('boop')) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/venv/lib/python3.8/site-packages/temba_client/exceptions.py", line 3, in __str__ return self.message AttributeError: 'TembaSerializationException' object has no attribute 'message' ``` So it looks like `.message` isn't being set in the constructor for `TembaSerializationException`? For now I'm just catching the exceptions and logging their `args[0]` attribute, but fixing these so they have meaningful error messages would be helpful.
0.0
5872006fa0f407bd2a859b07b1cb6d8d9bb11768
[ "temba_client/tests.py::TembaSerializationExceptionTest::test_str_works" ]
[ "temba_client/tests.py::UtilsTest::test_format_iso8601", "temba_client/tests.py::UtilsTest::test_parse_iso8601", "temba_client/tests.py::FieldsTest::test_boolean", "temba_client/tests.py::FieldsTest::test_integer", "temba_client/tests.py::FieldsTest::test_object_dict", "temba_client/tests.py::FieldsTest::test_object_list", "temba_client/tests.py::TembaObjectTest::test_create", "temba_client/tests.py::TembaObjectTest::test_deserialize", "temba_client/tests.py::TembaObjectTest::test_serialize", "temba_client/tests.py::BaseClientTest::test_init" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-11-06 22:02:11+00:00
bsd-3-clause
5,176
readthedocs__sphinx-hoverxref-195
diff --git a/hoverxref/extension.py b/hoverxref/extension.py index 7c56d4b..0dc27af 100644 --- a/hoverxref/extension.py +++ b/hoverxref/extension.py @@ -197,7 +197,7 @@ def missing_reference(app, env, node, contnode): See https://github.com/sphinx-doc/sphinx/blob/4d90277c/sphinx/ext/intersphinx.py#L244-L250 """ - if not app.config.hoverxref_intersphinx: + if not app.config.hoverxref_intersphinx or 'sphinx.ext.intersphinx' not in app.config.extensions: # Do nothing if the user doesn't have hoverxref intersphinx enabled return @@ -239,7 +239,13 @@ def missing_reference(app, env, node, contnode): inventory = inventories.named_inventory.get(inventory_name, {}) # Logic of `.objtypes_for_role` stolen from # https://github.com/sphinx-doc/sphinx/blob/b8789b4c/sphinx/ext/intersphinx.py#L397 - for objtype in env.get_domain(domain).objtypes_for_role(reftype): + objtypes_for_role = env.get_domain(domain).objtypes_for_role(reftype) + + # If the reftype is not defined on the domain, we skip it + if not objtypes_for_role: + continue + + for objtype in objtypes_for_role: inventory_member = inventory.get(f'{domain}:{objtype}') if inventory_member and inventory_member.get(target) is not None:
readthedocs/sphinx-hoverxref
a1255c50ff9bab5ce4a0561ce53dd5ba6c878a93
diff --git a/tests/examples/python-domain/index.rst b/tests/examples/python-domain/index.rst index 89dc610..cadfa74 100644 --- a/tests/examples/python-domain/index.rst +++ b/tests/examples/python-domain/index.rst @@ -8,3 +8,6 @@ This is an example page with a Python Domain role usage. :py:mod:`hoverxref.extension` :py:func:`hoverxref.extension.setup` + +Note that ``:py:const:`` does not exist in the Python domain, but it shouldn't make the build to fail. +"Constant" should be rendered in the same way as the other Python objects: :py:const:`Constant` diff --git a/tests/test_htmltag.py b/tests/test_htmltag.py index f194e15..9097041 100644 --- a/tests/test_htmltag.py +++ b/tests/test_htmltag.py @@ -118,6 +118,38 @@ def test_python_domain(app, status, warning): '<a class="hoverxref tooltip reference internal" href="api.html#hoverxref.extension.HoverXRefStandardDomainMixin" title="hoverxref.extension.HoverXRefStandardDomainMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">This</span> <span class="pre">is</span> <span class="pre">a</span> <span class="pre">:py:class:</span> <span class="pre">role</span> <span class="pre">to</span> <span class="pre">a</span> <span class="pre">Python</span> <span class="pre">object</span></code></a>', '<a class="hoverxref tooltip reference internal" href="api.html#module-hoverxref.extension" title="hoverxref.extension"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hoverxref.extension</span></code></a>', '<a class="hoverxref tooltip reference internal" href="api.html#hoverxref.extension.setup" title="hoverxref.extension.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">hoverxref.extension.setup()</span></code></a>', + '<code class="xref py py-const docutils literal notranslate"><span class="pre">Constant</span></code>', + ] + + for chunk in chunks: + assert chunk in content + + [email protected]( + srcdir=pythondomainsrcdir, + confoverrides={ + 'hoverxref_domains': ['py'], + 'hoverxref_intersphinx': ['python'], + 'hoverxref_auto_ref': True, + 'extensions': [ + 'sphinx.ext.autodoc', + 'sphinx.ext.autosectionlabel', + 'sphinx.ext.intersphinx', + 'hoverxref.extension', + ], + }, +) +def test_python_domain_intersphinx(app, status, warning): + app.build() + path = app.outdir / 'index.html' + assert path.exists() is True + content = open(path).read() + + chunks = [ + '<a class="hoverxref tooltip reference internal" href="api.html#hoverxref.extension.HoverXRefStandardDomainMixin" title="hoverxref.extension.HoverXRefStandardDomainMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">This</span> <span class="pre">is</span> <span class="pre">a</span> <span class="pre">:py:class:</span> <span class="pre">role</span> <span class="pre">to</span> <span class="pre">a</span> <span class="pre">Python</span> <span class="pre">object</span></code></a>', + '<a class="hoverxref tooltip reference internal" href="api.html#module-hoverxref.extension" title="hoverxref.extension"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hoverxref.extension</span></code></a>', + '<a class="hoverxref tooltip reference internal" href="api.html#hoverxref.extension.setup" title="hoverxref.extension.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">hoverxref.extension.setup()</span></code></a>', + '<code class="xref py py-const docutils literal notranslate"><span class="pre">Constant</span></code>', ] for chunk in chunks:
TypeError: 'NoneType' object is not iterable No idea what causes it. https://readthedocs.org/projects/pyunity/builds/17067435/
0.0
a1255c50ff9bab5ce4a0561ce53dd5ba6c878a93
[ "tests/test_htmltag.py::test_python_domain_intersphinx" ]
[ "tests/test_htmltag.py::test_default_settings", "tests/test_htmltag.py::test_js_render", "tests/test_htmltag.py::test_autosectionlabel_project_version_settings", "tests/test_htmltag.py::test_custom_object", "tests/test_htmltag.py::test_python_domain", "tests/test_htmltag.py::test_glossary_term_domain", "tests/test_htmltag.py::test_default_type", "tests/test_htmltag.py::test_ignore_refs", "tests/test_htmltag.py::test_intersphinx_default_configs", "tests/test_htmltag.py::test_intersphinx_python_mapping", "tests/test_htmltag.py::test_intersphinx_all_mappings" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-06-07 11:35:52+00:00
mit
5,177
reata__sqllineage-107
diff --git a/sqllineage/core.py b/sqllineage/core.py index f46ba1d..5d34b6b 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -20,7 +20,7 @@ SOURCE_TABLE_TOKENS = ( # inspired by https://github.com/andialbrecht/sqlparse/blob/master/sqlparse/keywords.py r"((LEFT\s+|RIGHT\s+|FULL\s+)?(INNER\s+|OUTER\s+|STRAIGHT\s+)?|(CROSS\s+|NATURAL\s+)?)?JOIN", ) -TARGET_TABLE_TOKENS = ("INTO", "OVERWRITE", "TABLE", "VIEW") +TARGET_TABLE_TOKENS = ("INTO", "OVERWRITE", "TABLE", "VIEW", "UPDATE") TEMP_TABLE_TOKENS = ("WITH",)
reata/sqllineage
d94ca2c74c927ece4a5bfbc64b613b6c70ca5c63
diff --git a/tests/test_others.py b/tests/test_others.py index afe8852..93233dc 100644 --- a/tests/test_others.py +++ b/tests/test_others.py @@ -45,6 +45,18 @@ def test_create_after_drop(): ) +def test_update(): + helper("UPDATE tab1 SET col1='val1' WHERE col2='val2'", None, {"tab1"}) + + +def test_update_with_join(): + helper( + "UPDATE tab1 a INNER JOIN tab2 b ON a.col1=b.col1 SET a.col2=b.col2", + {"tab2"}, + {"tab1"}, + ) + + def test_drop(): helper("DROP TABLE IF EXISTS tab1", None, None)
Incorrect Result for UPDATE statement hello reata.when i using sqllineage to analyze the follow SQL .I got a bug. `UPDATE tablea a INNER JOIN ( SELECT col2 FROM tableb GROUP BY col ) b ON b.col = a.col SET a.col1 = a.col2 * b.col2 ` that SQL update tablea`s col1 using tableb`s col2 . when i running the SQLLINGAGE it returns tableb as source table but null as target table .in my view the source table should be tableb and the target table should be tablea but not null
0.0
d94ca2c74c927ece4a5bfbc64b613b6c70ca5c63
[ "tests/test_others.py::test_update", "tests/test_others.py::test_update_with_join" ]
[ "tests/test_others.py::test_use", "tests/test_others.py::test_table_name_case", "tests/test_others.py::test_create", "tests/test_others.py::test_create_if_not_exist", "tests/test_others.py::test_create_as", "tests/test_others.py::test_create_like", "tests/test_others.py::test_create_select", "tests/test_others.py::test_create_after_drop", "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_with_comment", "tests/test_others.py::test_drop_after_create", "tests/test_others.py::test_drop_tmp_tab_after_create", "tests/test_others.py::test_new_create_tab_as_tmp_table", "tests/test_others.py::test_alter_table_rename", "tests/test_others.py::test_alter_target_table_name", "tests/test_others.py::test_refresh_table", "tests/test_others.py::test_cache_table", "tests/test_others.py::test_truncate_table", "tests/test_others.py::test_delete_from_table", "tests/test_others.py::test_split_statements", "tests/test_others.py::test_split_statements_with_heading_and_ending_new_line", "tests/test_others.py::test_split_statements_with_comment", "tests/test_others.py::test_statements_trim_comment", "tests/test_others.py::test_split_statements_with_show_create_table", "tests/test_others.py::test_split_statements_with_desc" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-12-20 04:34:32+00:00
mit
5,178
reata__sqllineage-17
diff --git a/sqllineage/core.py b/sqllineage/core.py index 301c818..2f5e0b6 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -3,7 +3,7 @@ import sys from typing import List, Set import sqlparse -from sqlparse.sql import Function, Identifier, IdentifierList, Statement, TokenList +from sqlparse.sql import Function, Identifier, Parenthesis, Statement, TokenList from sqlparse.tokens import Keyword, Token, Whitespace SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN', @@ -51,11 +51,9 @@ Target Tables: return self._target_tables def _extract_from_token(self, token: Token): - if not isinstance(token, TokenList): - return source_table_token_flag = target_table_token_flag = temp_table_token_flag = False for sub_token in token.tokens: - if isinstance(token, TokenList) and not isinstance(sub_token, (Identifier, IdentifierList)): + if isinstance(sub_token, TokenList): self._extract_from_token(sub_token) if sub_token.ttype in Keyword: if sub_token.normalized in SOURCE_TABLE_TOKENS: @@ -75,7 +73,13 @@ Target Tables: continue else: assert isinstance(sub_token, Identifier) - self._source_tables.add(sub_token.get_real_name()) + if isinstance(sub_token.token_first(), Parenthesis): + # SELECT col1 FROM (SELECT col2 FROM tab1) dt, the subquery will be parsed as Identifier + # and this Identifier's get_real_name method would return alias name dt + # referring https://github.com/andialbrecht/sqlparse/issues/218 for further information + pass + else: + self._source_tables.add(sub_token.get_real_name()) source_table_token_flag = False elif target_table_token_flag: if sub_token.ttype == Whitespace:
reata/sqllineage
b613ec49de0b613cfaa74b37282f410659dcbc06
diff --git a/tests/test_select.py b/tests/test_select.py index cea96ef..49fe323 100644 --- a/tests/test_select.py +++ b/tests/test_select.py @@ -40,6 +40,10 @@ def test_select_count(): helper("SELECT COUNT(*) FROM tab1", {"tab1"}) +def test_select_subquery(): + helper("SELECT col1 FROM (SELECT col2 FROM tab1) dt", {"tab1"}) + + def test_select_inner_join(): helper("SELECT * FROM tab1 INNER JOIN tab2", {"tab1", "tab2"})
subquery mistake alias as table name ``` $ python -m sqllineage.core -e "SELECT col1 FROM (SELECT col2 from tab1) dt" Statements(#): 1 Source Tables: dt Target Tables: ``` expect source table as tab1
0.0
b613ec49de0b613cfaa74b37282f410659dcbc06
[ "tests/test_select.py::test_select_subquery" ]
[ "tests/test_select.py::test_select", "tests/test_select.py::test_select_asterisk", "tests/test_select.py::test_select_value", "tests/test_select.py::test_select_function", "tests/test_select.py::test_select_with_where", "tests/test_select.py::test_select_with_comment", "tests/test_select.py::test_select_keyword_as_column_alias", "tests/test_select.py::test_select_with_table_alias", "tests/test_select.py::test_select_count", "tests/test_select.py::test_select_inner_join", "tests/test_select.py::test_select_join", "tests/test_select.py::test_select_left_join", "tests/test_select.py::test_select_left_semi_join", "tests/test_select.py::test_select_left_semi_join_with_on", "tests/test_select.py::test_select_right_join", "tests/test_select.py::test_select_full_outer_join", "tests/test_select.py::test_select_full_outer_join_with_full_as_alias", "tests/test_select.py::test_select_cross_join", "tests/test_select.py::test_select_cross_join_with_on", "tests/test_select.py::test_select_join_with_subquery", "tests/test_select.py::test_with_select" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-08-11 07:52:41+00:00
mit
5,179
reata__sqllineage-19
diff --git a/sqllineage/core.py b/sqllineage/core.py index 2f5e0b6..fbf17f2 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -4,7 +4,7 @@ from typing import List, Set import sqlparse from sqlparse.sql import Function, Identifier, Parenthesis, Statement, TokenList -from sqlparse.tokens import Keyword, Token, Whitespace +from sqlparse.tokens import Keyword, Token SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN', 'FULL OUTER JOIN', 'CROSS JOIN') @@ -69,7 +69,7 @@ Target Tables: self._target_tables.add(sub_token.get_alias()) continue if source_table_token_flag: - if sub_token.ttype == Whitespace: + if sub_token.is_whitespace: continue else: assert isinstance(sub_token, Identifier) @@ -82,7 +82,7 @@ Target Tables: self._source_tables.add(sub_token.get_real_name()) source_table_token_flag = False elif target_table_token_flag: - if sub_token.ttype == Whitespace: + if sub_token.is_whitespace: continue elif isinstance(sub_token, Function): # insert into tab (col1, col2), tab (col1, col2) will be parsed as Function @@ -95,7 +95,7 @@ Target Tables: self._target_tables.add(sub_token.get_real_name()) target_table_token_flag = False elif temp_table_token_flag: - if sub_token.ttype == Whitespace: + if sub_token.is_whitespace: continue else: assert isinstance(sub_token, Identifier)
reata/sqllineage
2901dd193c45e4ae0aab792ac0aaa11a04a2de1b
diff --git a/tests/test_select.py b/tests/test_select.py index 49fe323..8837091 100644 --- a/tests/test_select.py +++ b/tests/test_select.py @@ -5,6 +5,11 @@ def test_select(): helper("SELECT col1 FROM tab1", {"tab1"}) +def test_select_multi_line(): + helper("""SELECT col1 FROM +tab1""", {"tab1"}) + + def test_select_asterisk(): helper("SELECT * FROM tab1", {"tab1"})
multi-line sql causes AssertionError ```sql SELECT * FROM tab1 ``` causes following exception Traceback (most recent call last): File "/home/admin/.pyenv/versions/3.6.8/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/home/admin/.pyenv/versions/3.6.8/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/admin/repos/sqllineage/sqllineage/core.py", line 131, in <module> main() File "/home/admin/repos/sqllineage/sqllineage/core.py", line 119, in main print(LineageParser(sql)) File "/home/admin/repos/sqllineage/sqllineage/core.py", line 23, in __init__ self._extract_from_token(stmt) File "/home/admin/repos/sqllineage/sqllineage/core.py", line 75, in _extract_from_token assert isinstance(sub_token, Identifier) AssertionError
0.0
2901dd193c45e4ae0aab792ac0aaa11a04a2de1b
[ "tests/test_select.py::test_select_multi_line" ]
[ "tests/test_select.py::test_select", "tests/test_select.py::test_select_asterisk", "tests/test_select.py::test_select_value", "tests/test_select.py::test_select_function", "tests/test_select.py::test_select_with_where", "tests/test_select.py::test_select_with_comment", "tests/test_select.py::test_select_keyword_as_column_alias", "tests/test_select.py::test_select_with_table_alias", "tests/test_select.py::test_select_count", "tests/test_select.py::test_select_subquery", "tests/test_select.py::test_select_inner_join", "tests/test_select.py::test_select_join", "tests/test_select.py::test_select_left_join", "tests/test_select.py::test_select_left_semi_join", "tests/test_select.py::test_select_left_semi_join_with_on", "tests/test_select.py::test_select_right_join", "tests/test_select.py::test_select_full_outer_join", "tests/test_select.py::test_select_full_outer_join_with_full_as_alias", "tests/test_select.py::test_select_cross_join", "tests/test_select.py::test_select_cross_join_with_on", "tests/test_select.py::test_select_join_with_subquery", "tests/test_select.py::test_with_select" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-08-11 08:31:46+00:00
mit
5,180
reata__sqllineage-22
diff --git a/sqllineage/core.py b/sqllineage/core.py index fbf17f2..74c178d 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -4,7 +4,7 @@ from typing import List, Set import sqlparse from sqlparse.sql import Function, Identifier, Parenthesis, Statement, TokenList -from sqlparse.tokens import Keyword, Token +from sqlparse.tokens import DDL, Keyword, Token SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN', 'FULL OUTER JOIN', 'CROSS JOIN') @@ -20,7 +20,10 @@ class LineageParser(object): self._target_tables = set() self._stmt = sqlparse.parse(sql, self._encoding) for stmt in self._stmt: - self._extract_from_token(stmt) + if stmt.token_first().ttype == DDL and stmt.token_first().normalized == "DROP": + self._target_tables -= {t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier)} + else: + self._extract_from_token(stmt) self._tmp_tables = self._source_tables.intersection(self._target_tables) self._source_tables -= self._tmp_tables self._target_tables -= self._tmp_tables
reata/sqllineage
95cc52fb0e425a8aa68ba6f4297f4a9490583cac
diff --git a/tests/test_others.py b/tests/test_others.py index a6f8472..6fc57c9 100644 --- a/tests/test_others.py +++ b/tests/test_others.py @@ -6,6 +6,26 @@ def test_use(): helper("USE db1") +def test_create(): + helper("CREATE TABLE tab1 (col1 STRING)", None, {"tab1"}) + + +def test_create_if_not_exist(): + helper("CREATE TABLE IF NOT EXISTS tab1 (col1 STRING)", None, {"tab1"}) + + +def test_create_after_drop(): + helper("DROP TABLE IF EXISTS tab1; CREATE TABLE IF NOT EXISTS tab1 (col1 STRING)", None, {"tab1"}) + + +def test_drop(): + helper("DROP TABLE IF EXISTS tab1", None, None) + + +def test_drop_after_create(): + helper("CREATE TABLE IF NOT EXISTS tab1 (col1 STRING);DROP TABLE IF EXISTS tab1", None, None) + + def test_create_select(): helper("CREATE TABLE tab1 SELECT * FROM tab2", {"tab2"}, {"tab1"})
drop table parsed as target table ``` $ sqllineage -e "DROP TABLE IF EXISTS tab1" Statements(#): 1 Source Tables: Target Tables: tab1 ``` expect: When a table is in target_tables, dropping table result in a removal from target_tables. Otherwise the DROP DML doesn't affect the result.
0.0
95cc52fb0e425a8aa68ba6f4297f4a9490583cac
[ "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_after_create" ]
[ "tests/test_others.py::test_use", "tests/test_others.py::test_create", "tests/test_others.py::test_create_if_not_exist", "tests/test_others.py::test_create_after_drop", "tests/test_others.py::test_create_select", "tests/test_others.py::test_split_statements" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-08-11 10:15:27+00:00
mit
5,181
reata__sqllineage-24
diff --git a/sqllineage/core.py b/sqllineage/core.py index 74c178d..2faa914 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -4,7 +4,7 @@ from typing import List, Set import sqlparse from sqlparse.sql import Function, Identifier, Parenthesis, Statement, TokenList -from sqlparse.tokens import DDL, Keyword, Token +from sqlparse.tokens import Keyword, Token SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN', 'FULL OUTER JOIN', 'CROSS JOIN') @@ -18,9 +18,9 @@ class LineageParser(object): self._encoding = encoding self._source_tables = set() self._target_tables = set() - self._stmt = sqlparse.parse(sql, self._encoding) + self._stmt = sqlparse.parse(sql.strip(), self._encoding) for stmt in self._stmt: - if stmt.token_first().ttype == DDL and stmt.token_first().normalized == "DROP": + if stmt.get_type() == "DROP": self._target_tables -= {t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier)} else: self._extract_from_token(stmt) @@ -76,7 +76,7 @@ Target Tables: continue else: assert isinstance(sub_token, Identifier) - if isinstance(sub_token.token_first(), Parenthesis): + if isinstance(sub_token.token_first(skip_cm=True), Parenthesis): # SELECT col1 FROM (SELECT col2 FROM tab1) dt, the subquery will be parsed as Identifier # and this Identifier's get_real_name method would return alias name dt # referring https://github.com/andialbrecht/sqlparse/issues/218 for further information @@ -90,8 +90,8 @@ Target Tables: elif isinstance(sub_token, Function): # insert into tab (col1, col2), tab (col1, col2) will be parsed as Function # referring https://github.com/andialbrecht/sqlparse/issues/483 for further information - assert isinstance(sub_token.token_first(), Identifier) - self._target_tables.add(sub_token.token_first().get_real_name()) + assert isinstance(sub_token.token_first(skip_cm=True), Identifier) + self._target_tables.add(sub_token.token_first(skip_cm=True).get_real_name()) target_table_token_flag = False else: assert isinstance(sub_token, Identifier)
reata/sqllineage
245a83548482fbf78f90a26cea97a534c61be2e5
diff --git a/tests/test_others.py b/tests/test_others.py index 6fc57c9..7e0a287 100644 --- a/tests/test_others.py +++ b/tests/test_others.py @@ -22,6 +22,11 @@ def test_drop(): helper("DROP TABLE IF EXISTS tab1", None, None) +def test_drop_with_comment(): + helper("""--comment +DROP TABLE IF EXISTS tab1""", None, None) + + def test_drop_after_create(): helper("CREATE TABLE IF NOT EXISTS tab1 (col1 STRING);DROP TABLE IF EXISTS tab1", None, None) @@ -33,3 +38,8 @@ def test_create_select(): def test_split_statements(): sql = "SELECT * FROM tab1; SELECT * FROM tab2;" assert len(LineageParser(sql).statements) == 2 + + +def test_split_statements_with_heading_and_ending_new_line(): + sql = "\nSELECT * FROM tab1;\nSELECT * FROM tab2;\n" + assert len(LineageParser(sql).statements) == 2
drop table parsed as target table ``` $ sqllineage -e "DROP TABLE IF EXISTS tab1" Statements(#): 1 Source Tables: Target Tables: tab1 ``` expect: When a table is in target_tables, dropping table result in a removal from target_tables. Otherwise the DROP DML doesn't affect the result.
0.0
245a83548482fbf78f90a26cea97a534c61be2e5
[ "tests/test_others.py::test_drop_with_comment", "tests/test_others.py::test_split_statements_with_heading_and_ending_new_line" ]
[ "tests/test_others.py::test_use", "tests/test_others.py::test_create", "tests/test_others.py::test_create_if_not_exist", "tests/test_others.py::test_create_after_drop", "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_after_create", "tests/test_others.py::test_create_select", "tests/test_others.py::test_split_statements" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-08-11 12:01:06+00:00
mit
5,182
reata__sqllineage-26
diff --git a/sqllineage/core.py b/sqllineage/core.py index 2faa914..fbfff54 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -18,7 +18,7 @@ class LineageParser(object): self._encoding = encoding self._source_tables = set() self._target_tables = set() - self._stmt = sqlparse.parse(sql.strip(), self._encoding) + self._stmt = [s for s in sqlparse.parse(sql.strip(), self._encoding) if s.get_type() != "UNKNOWN"] for stmt in self._stmt: if stmt.get_type() == "DROP": self._target_tables -= {t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier)}
reata/sqllineage
c7ea5d861359fe49692e2036b9e382af73ba8069
diff --git a/tests/test_others.py b/tests/test_others.py index 7e0a287..9a0b89f 100644 --- a/tests/test_others.py +++ b/tests/test_others.py @@ -43,3 +43,10 @@ def test_split_statements(): def test_split_statements_with_heading_and_ending_new_line(): sql = "\nSELECT * FROM tab1;\nSELECT * FROM tab2;\n" assert len(LineageParser(sql).statements) == 2 + + +def test_split_statements_with_comment(): + sql = """SELECT 1; + +-- SELECT 2;""" + assert len(LineageParser(sql).statements) == 1
Empty Statement return take the following sql as example ```sql SELECT 1; -- SELECT 2; ``` the parsing result says that it contains two statements, instead of one.
0.0
c7ea5d861359fe49692e2036b9e382af73ba8069
[ "tests/test_others.py::test_split_statements_with_comment" ]
[ "tests/test_others.py::test_use", "tests/test_others.py::test_create", "tests/test_others.py::test_create_if_not_exist", "tests/test_others.py::test_create_after_drop", "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_with_comment", "tests/test_others.py::test_drop_after_create", "tests/test_others.py::test_create_select", "tests/test_others.py::test_split_statements", "tests/test_others.py::test_split_statements_with_heading_and_ending_new_line" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-08-11 12:23:51+00:00
mit
5,183
reata__sqllineage-27
diff --git a/sqllineage/core.py b/sqllineage/core.py index fbfff54..231aa26 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -18,7 +18,7 @@ class LineageParser(object): self._encoding = encoding self._source_tables = set() self._target_tables = set() - self._stmt = [s for s in sqlparse.parse(sql.strip(), self._encoding) if s.get_type() != "UNKNOWN"] + self._stmt = [s for s in sqlparse.parse(sql.strip(), self._encoding) if s.token_first(skip_cm=True)] for stmt in self._stmt: if stmt.get_type() == "DROP": self._target_tables -= {t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier)}
reata/sqllineage
d0c47ddbb0b73eea2700e6934fdc89159ac7b22e
diff --git a/tests/test_others.py b/tests/test_others.py index 9a0b89f..ddc0c30 100644 --- a/tests/test_others.py +++ b/tests/test_others.py @@ -50,3 +50,17 @@ def test_split_statements_with_comment(): -- SELECT 2;""" assert len(LineageParser(sql).statements) == 1 + + +def test_split_statements_with_show_create_table(): + sql = """SELECT 1; + +SHOW CREATE TABLE tab1;""" + assert len(LineageParser(sql).statements) == 2 + + +def test_split_statements_with_desc(): + sql = """SELECT 1; + +DESC tab1;""" + assert len(LineageParser(sql).statements) == 2
Empty Statement return take the following sql as example ```sql SELECT 1; -- SELECT 2; ``` the parsing result says that it contains two statements, instead of one.
0.0
d0c47ddbb0b73eea2700e6934fdc89159ac7b22e
[ "tests/test_others.py::test_split_statements_with_show_create_table", "tests/test_others.py::test_split_statements_with_desc" ]
[ "tests/test_others.py::test_use", "tests/test_others.py::test_create", "tests/test_others.py::test_create_if_not_exist", "tests/test_others.py::test_create_after_drop", "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_with_comment", "tests/test_others.py::test_drop_after_create", "tests/test_others.py::test_create_select", "tests/test_others.py::test_split_statements", "tests/test_others.py::test_split_statements_with_heading_and_ending_new_line", "tests/test_others.py::test_split_statements_with_comment" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-08-12 14:16:19+00:00
mit
5,184
reata__sqllineage-38
diff --git a/sqllineage/core.py b/sqllineage/core.py index 231aa26..5b010e2 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -3,13 +3,13 @@ import sys from typing import List, Set import sqlparse -from sqlparse.sql import Function, Identifier, Parenthesis, Statement, TokenList +from sqlparse.sql import Comment, Function, Identifier, Parenthesis, Statement, TokenList from sqlparse.tokens import Keyword, Token SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN', 'FULL OUTER JOIN', 'CROSS JOIN') TARGET_TABLE_TOKENS = ('INTO', 'OVERWRITE', 'TABLE') -TEMP_TABLE_TOKENS = ('WITH', ) +TEMP_TABLE_TOKENS = ('WITH',) class LineageParser(object): @@ -53,7 +53,7 @@ Target Tables: def target_tables(self) -> Set[str]: return self._target_tables - def _extract_from_token(self, token: Token): + def _extract_from_token(self, token: Token) -> None: source_table_token_flag = target_table_token_flag = temp_table_token_flag = False for sub_token in token.tokens: if isinstance(sub_token, TokenList): @@ -72,7 +72,7 @@ Target Tables: self._target_tables.add(sub_token.get_alias()) continue if source_table_token_flag: - if sub_token.is_whitespace: + if self.__token_negligible_before_tablename(sub_token): continue else: assert isinstance(sub_token, Identifier) @@ -85,7 +85,7 @@ Target Tables: self._source_tables.add(sub_token.get_real_name()) source_table_token_flag = False elif target_table_token_flag: - if sub_token.is_whitespace: + if self.__token_negligible_before_tablename(sub_token): continue elif isinstance(sub_token, Function): # insert into tab (col1, col2), tab (col1, col2) will be parsed as Function @@ -98,7 +98,7 @@ Target Tables: self._target_tables.add(sub_token.get_real_name()) target_table_token_flag = False elif temp_table_token_flag: - if sub_token.is_whitespace: + if self.__token_negligible_before_tablename(sub_token): continue else: assert isinstance(sub_token, Identifier) @@ -107,6 +107,10 @@ Target Tables: self._extract_from_token(sub_token) temp_table_token_flag = False + @classmethod + def __token_negligible_before_tablename(cls, token: Token) -> bool: + return token.is_whitespace or isinstance(token, Comment) + def main(): parser = argparse.ArgumentParser(prog='sqllineage', description='SQL Lineage Parser.')
reata/sqllineage
d79057f068fa8d2e3c8c121355eb9af2a026d899
diff --git a/tests/test_select.py b/tests/test_select.py index 8837091..69b6133 100644 --- a/tests/test_select.py +++ b/tests/test_select.py @@ -30,6 +30,14 @@ def test_select_with_comment(): helper("SELECT -- comment1\n col1 FROM tab1", {"tab1"}) +def test_select_with_comment_after_from(): + helper("SELECT col1\nFROM -- comment\ntab1", {"tab1"}) + + +def test_select_with_comment_after_join(): + helper("select * from tab1 join --comment\ntab2 on tab1.x = tab2.x", {"tab1", "tab2"}) + + def test_select_keyword_as_column_alias(): # here `as` is the column alias helper("SELECT 1 `as` FROM tab1", {"tab1"})
comment in line raise AssertionError ```sql select * from -- comment tab_a ``` This will raise AssertionError
0.0
d79057f068fa8d2e3c8c121355eb9af2a026d899
[ "tests/test_select.py::test_select_with_comment_after_from", "tests/test_select.py::test_select_with_comment_after_join" ]
[ "tests/test_select.py::test_select", "tests/test_select.py::test_select_multi_line", "tests/test_select.py::test_select_asterisk", "tests/test_select.py::test_select_value", "tests/test_select.py::test_select_function", "tests/test_select.py::test_select_with_where", "tests/test_select.py::test_select_with_comment", "tests/test_select.py::test_select_keyword_as_column_alias", "tests/test_select.py::test_select_with_table_alias", "tests/test_select.py::test_select_count", "tests/test_select.py::test_select_subquery", "tests/test_select.py::test_select_inner_join", "tests/test_select.py::test_select_join", "tests/test_select.py::test_select_left_join", "tests/test_select.py::test_select_left_semi_join", "tests/test_select.py::test_select_left_semi_join_with_on", "tests/test_select.py::test_select_right_join", "tests/test_select.py::test_select_full_outer_join", "tests/test_select.py::test_select_full_outer_join_with_full_as_alias", "tests/test_select.py::test_select_cross_join", "tests/test_select.py::test_select_cross_join_with_on", "tests/test_select.py::test_select_join_with_subquery", "tests/test_select.py::test_with_select" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-03-23 13:20:36+00:00
mit
5,185
reata__sqllineage-40
diff --git a/sqllineage/core.py b/sqllineage/core.py index 5b010e2..0d7c505 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -1,4 +1,5 @@ import argparse +import re import sys from typing import List, Set @@ -6,8 +7,9 @@ import sqlparse from sqlparse.sql import Comment, Function, Identifier, Parenthesis, Statement, TokenList from sqlparse.tokens import Keyword, Token -SOURCE_TABLE_TOKENS = ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'LEFT OUTER JOIN', 'RIGHT OUTER JOIN', - 'FULL OUTER JOIN', 'CROSS JOIN') +SOURCE_TABLE_TOKENS = (r'FROM', + # inspired by https://github.com/andialbrecht/sqlparse/blob/master/sqlparse/keywords.py + r'((LEFT\s+|RIGHT\s+|FULL\s+)?(INNER\s+|OUTER\s+|STRAIGHT\s+)?|(CROSS\s+|NATURAL\s+)?)?JOIN') TARGET_TABLE_TOKENS = ('INTO', 'OVERWRITE', 'TABLE') TEMP_TABLE_TOKENS = ('WITH',) @@ -59,7 +61,7 @@ Target Tables: if isinstance(sub_token, TokenList): self._extract_from_token(sub_token) if sub_token.ttype in Keyword: - if sub_token.normalized in SOURCE_TABLE_TOKENS: + if any(re.match(regex, sub_token.normalized) for regex in SOURCE_TABLE_TOKENS): source_table_token_flag = True elif sub_token.normalized in TARGET_TABLE_TOKENS: target_table_token_flag = True
reata/sqllineage
d80f93bcdcdd4d4b9120ba8c6a0159b7e0e8ba26
diff --git a/tests/test_select.py b/tests/test_select.py index 69b6133..8f31412 100644 --- a/tests/test_select.py +++ b/tests/test_select.py @@ -69,6 +69,10 @@ def test_select_left_join(): helper("SELECT * FROM tab1 LEFT JOIN tab2", {"tab1", "tab2"}) +def test_select_left_join_with_extra_space_in_middle(): + helper("SELECT * FROM tab1 LEFT JOIN tab2", {"tab1", "tab2"}) + + def test_select_left_semi_join(): helper("SELECT * FROM tab1 LEFT SEMI JOIN tab2", {"tab1", "tab2"})
white space in left join ```sql select * from tab_a left join tab_b on tab_a.x = tab_b.x ``` an extra whitespace in "left join" make tab_b undetectable.
0.0
d80f93bcdcdd4d4b9120ba8c6a0159b7e0e8ba26
[ "tests/test_select.py::test_select_left_join_with_extra_space_in_middle" ]
[ "tests/test_select.py::test_select", "tests/test_select.py::test_select_multi_line", "tests/test_select.py::test_select_asterisk", "tests/test_select.py::test_select_value", "tests/test_select.py::test_select_function", "tests/test_select.py::test_select_with_where", "tests/test_select.py::test_select_with_comment", "tests/test_select.py::test_select_with_comment_after_from", "tests/test_select.py::test_select_with_comment_after_join", "tests/test_select.py::test_select_keyword_as_column_alias", "tests/test_select.py::test_select_with_table_alias", "tests/test_select.py::test_select_count", "tests/test_select.py::test_select_subquery", "tests/test_select.py::test_select_inner_join", "tests/test_select.py::test_select_join", "tests/test_select.py::test_select_left_join", "tests/test_select.py::test_select_left_semi_join", "tests/test_select.py::test_select_left_semi_join_with_on", "tests/test_select.py::test_select_right_join", "tests/test_select.py::test_select_full_outer_join", "tests/test_select.py::test_select_full_outer_join_with_full_as_alias", "tests/test_select.py::test_select_cross_join", "tests/test_select.py::test_select_cross_join_with_on", "tests/test_select.py::test_select_join_with_subquery", "tests/test_select.py::test_with_select" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-04-07 13:19:46+00:00
mit
5,186
reata__sqllineage-42
diff --git a/sqllineage/core.py b/sqllineage/core.py index a46e388..1d9a021 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -4,7 +4,7 @@ import sys from typing import List, Set import sqlparse -from sqlparse.sql import Comment, Function, Identifier, Parenthesis, Statement, TokenList +from sqlparse.sql import Comment, Comparison, Function, Identifier, Parenthesis, Statement, TokenList from sqlparse.tokens import Keyword, Token SOURCE_TABLE_TOKENS = (r'FROM', @@ -95,11 +95,17 @@ Target Tables: # referring https://github.com/andialbrecht/sqlparse/issues/483 for further information assert isinstance(sub_token.token_first(skip_cm=True), Identifier) self._target_tables.add(sub_token.token_first(skip_cm=True).get_real_name()) - target_table_token_flag = False + elif isinstance(sub_token, Comparison): + # create table tab1 like tab2, tab1 like tab2 will be parsed as Comparison + # referring https://github.com/andialbrecht/sqlparse/issues/543 for further information + assert isinstance(sub_token.left, Identifier) + assert isinstance(sub_token.right, Identifier) + self._target_tables.add(sub_token.left.get_real_name()) + self._source_tables.add(sub_token.right.get_real_name()) else: assert isinstance(sub_token, Identifier) self._target_tables.add(sub_token.get_real_name()) - target_table_token_flag = False + target_table_token_flag = False elif temp_table_token_flag: if self.__token_negligible_before_tablename(sub_token): continue
reata/sqllineage
b8eaecc85b279dc18f9464b9e2bf6b2164b63211
diff --git a/tests/test_others.py b/tests/test_others.py index eabb6d4..a9405c8 100644 --- a/tests/test_others.py +++ b/tests/test_others.py @@ -14,6 +14,14 @@ def test_create_if_not_exist(): helper("CREATE TABLE IF NOT EXISTS tab1 (col1 STRING)", None, {"tab1"}) +def test_create_as(): + helper("CREATE TABLE tab1 AS SELECT * FROM tab2", {"tab2"}, {"tab1"}) + + +def test_create_like(): + helper("CREATE TABLE tab1 LIKE tab2", {"tab2"}, {"tab1"}) + + def test_create_after_drop(): helper("DROP TABLE IF EXISTS tab1; CREATE TABLE IF NOT EXISTS tab1 (col1 STRING)", None, {"tab1"})
Support Create Table Like Statement ``` drop table if exists tab_a; create table if not exists tab_a like tab_b; ``` drop before create, the result is tab_a exists after the above statements; If we switch the order: ``` create table if not exists tab_a like tab_b; drop table if exists tab_a; ``` Although the above statements make no sense, still, we should output result as tab_a does not exist. Under current circumstances, both cases will be that tab_a does not exists since tab_a is identified as temp table. This is related to #23
0.0
b8eaecc85b279dc18f9464b9e2bf6b2164b63211
[ "tests/test_others.py::test_create_like" ]
[ "tests/test_others.py::test_use", "tests/test_others.py::test_create", "tests/test_others.py::test_create_if_not_exist", "tests/test_others.py::test_create_as", "tests/test_others.py::test_create_after_drop", "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_with_comment", "tests/test_others.py::test_drop_after_create", "tests/test_others.py::test_drop_tmp_tab_after_create", "tests/test_others.py::test_create_select", "tests/test_others.py::test_split_statements", "tests/test_others.py::test_split_statements_with_heading_and_ending_new_line", "tests/test_others.py::test_split_statements_with_comment", "tests/test_others.py::test_split_statements_with_show_create_table", "tests/test_others.py::test_split_statements_with_desc" ]
{ "failed_lite_validators": [ "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2020-04-11 06:34:07+00:00
mit
5,187
reata__sqllineage-45
diff --git a/sqllineage/core.py b/sqllineage/core.py index 059f40e..5ba4481 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -54,11 +54,11 @@ Target Tables: @property def source_tables(self) -> Set[str]: - return self._source_tables + return {t.lower() for t in self._source_tables} @property def target_tables(self) -> Set[str]: - return self._target_tables + return {t.lower() for t in self._target_tables} def _extract_from_DML(self, token: Token) -> None: source_table_token_flag = target_table_token_flag = temp_table_token_flag = False
reata/sqllineage
27346e0d6488cd5b3f9205543da78b973ce5d274
diff --git a/tests/test_others.py b/tests/test_others.py index 38956f1..f5f71f6 100644 --- a/tests/test_others.py +++ b/tests/test_others.py @@ -6,6 +6,13 @@ def test_use(): helper("USE db1") +def test_table_name_case(): + helper("""insert overwrite table tab_a +select * from tab_b +union all +select * from TAB_B""", {"tab_b"}, {"tab_a"}) + + def test_create(): helper("CREATE TABLE tab1 (col1 STRING)", None, {"tab1"})
case-sensitive parsing ``` insert overwrite table tab_a select * from tab_b union all select * from TAB_B ``` here tab_b and TAB_B will be parsed as two different tables.
0.0
27346e0d6488cd5b3f9205543da78b973ce5d274
[ "tests/test_others.py::test_table_name_case" ]
[ "tests/test_others.py::test_use", "tests/test_others.py::test_create", "tests/test_others.py::test_create_if_not_exist", "tests/test_others.py::test_create_as", "tests/test_others.py::test_create_like", "tests/test_others.py::test_create_select", "tests/test_others.py::test_create_after_drop", "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_with_comment", "tests/test_others.py::test_drop_after_create", "tests/test_others.py::test_drop_tmp_tab_after_create", "tests/test_others.py::test_alter_table_rename", "tests/test_others.py::test_alter_target_table_name", "tests/test_others.py::test_truncate_table", "tests/test_others.py::test_delete_from_table", "tests/test_others.py::test_split_statements", "tests/test_others.py::test_split_statements_with_heading_and_ending_new_line", "tests/test_others.py::test_split_statements_with_comment", "tests/test_others.py::test_split_statements_with_show_create_table", "tests/test_others.py::test_split_statements_with_desc" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-04-11 09:40:56+00:00
mit
5,188
reata__sqllineage-52
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d0900fd..0c32adf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,3 @@ repos: hooks: - id: black language_version: python3.6 - - repo: https://github.com/PyCQA/bandit - rev: master - hooks: - - id: bandit diff --git a/sqllineage/core.py b/sqllineage/core.py index 47077d4..2b1b77b 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -16,6 +16,7 @@ from sqlparse.sql import ( from sqlparse.tokens import Keyword, Token from sqllineage.exceptions import SQLLineageException +from sqllineage.models import Table SOURCE_TABLE_TOKENS = ( r"FROM", @@ -29,8 +30,8 @@ TEMP_TABLE_TOKENS = ("WITH",) class LineageParser(object): def __init__(self, sql: str, encoding=None): self._encoding = encoding - self._source_tables = set() # type: Set[str] - self._target_tables = set() # type: Set[str] + self._source_tables = set() # type: Set[Table] + self._target_tables = set() # type: Set[Table] self._stmt = [ s for s in sqlparse.parse(sql.strip(), self._encoding) @@ -61,8 +62,8 @@ Target Tables: {target_tables} """.format( stmt_cnt=len(self.statements), - source_tables="\n ".join(self.source_tables), - target_tables="\n ".join(self.target_tables), + source_tables="\n ".join(str(t) for t in self.source_tables), + target_tables="\n ".join(str(t) for t in self.target_tables), ) @property @@ -74,12 +75,12 @@ Target Tables: return [sqlparse.format(s.value) for s in self.statements_parsed] @property - def source_tables(self) -> Set[str]: - return {t.lower() for t in self._source_tables} + def source_tables(self) -> Set[Table]: + return {t for t in self._source_tables} @property - def target_tables(self) -> Set[str]: - return {t.lower() for t in self._target_tables} + def target_tables(self) -> Set[Table]: + return {t for t in self._target_tables} def _extract_from_DML(self, token: Token) -> None: source_table_token_flag = ( @@ -105,7 +106,7 @@ Target Tables: and sub_token.get_alias() is not None ): # overwrite can't be parsed as Keyword, manual walk around - self._target_tables.add(sub_token.get_alias()) + self._target_tables.add(Table(sub_token.get_alias())) continue if source_table_token_flag: if self.__token_negligible_before_tablename(sub_token): @@ -119,7 +120,7 @@ Target Tables: # referring https://github.com/andialbrecht/sqlparse/issues/218 for further information pass else: - self._source_tables.add(sub_token.get_real_name()) + self._source_tables.add(Table(sub_token.get_real_name())) source_table_token_flag = False elif target_table_token_flag: if self.__token_negligible_before_tablename(sub_token): @@ -130,7 +131,7 @@ Target Tables: if not isinstance(sub_token.token_first(skip_cm=True), Identifier): raise SQLLineageException("An Identifier is expected") self._target_tables.add( - sub_token.token_first(skip_cm=True).get_real_name() + Table(sub_token.token_first(skip_cm=True).get_real_name()) ) elif isinstance(sub_token, Comparison): # create table tab1 like tab2, tab1 like tab2 will be parsed as Comparison @@ -140,12 +141,12 @@ Target Tables: and isinstance(sub_token.right, Identifier) ): raise SQLLineageException("An Identifier is expected") - self._target_tables.add(sub_token.left.get_real_name()) - self._source_tables.add(sub_token.right.get_real_name()) + self._target_tables.add(Table(sub_token.left.get_real_name())) + self._source_tables.add(Table(sub_token.right.get_real_name())) else: if not isinstance(sub_token, Identifier): raise SQLLineageException("An Identifier is expected") - self._target_tables.add(sub_token.get_real_name()) + self._target_tables.add(Table(sub_token.get_real_name())) target_table_token_flag = False elif temp_table_token_flag: if self.__token_negligible_before_tablename(sub_token): @@ -153,19 +154,23 @@ Target Tables: else: if not isinstance(sub_token, Identifier): raise SQLLineageException("An Identifier is expected") - self._source_tables.add(sub_token.get_real_name()) - self._target_tables.add(sub_token.get_real_name()) + self._source_tables.add(Table(sub_token.get_real_name())) + self._target_tables.add(Table(sub_token.get_real_name())) self._extract_from_DML(sub_token) temp_table_token_flag = False def _extract_from_DDL_DROP(self, stmt: Statement) -> None: for st_tables in (self._source_tables, self._target_tables): st_tables -= { - t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier) + Table(t.get_real_name()) + for t in stmt.tokens + if isinstance(t, Identifier) } def _extract_from_DDL_ALTER(self, stmt: Statement) -> None: - tables = [t.get_real_name() for t in stmt.tokens if isinstance(t, Identifier)] + tables = [ + Table(t.get_real_name()) for t in stmt.tokens if isinstance(t, Identifier) + ] keywords = [t for t in stmt.tokens if t.ttype is Keyword] if any(k.normalized == "RENAME" for k in keywords) and len(tables) == 2: for st_tables in (self._source_tables, self._target_tables): diff --git a/sqllineage/models.py b/sqllineage/models.py new file mode 100644 index 0000000..6ec1349 --- /dev/null +++ b/sqllineage/models.py @@ -0,0 +1,44 @@ +from typing import Optional + + +class Database: + def __init__(self, name: Optional[str] = "<unknown>"): + self.raw_name = name + + def __str__(self): + return self.raw_name.lower() + + def __repr__(self): + return "Database: " + str(self) + + def __eq__(self, other): + return type(self) is type(other) and str(self) == str(other) + + def __hash__(self): + return hash(str(self)) + + +class Table: + def __init__(self, name: str, database: Optional[Database] = Database()): + self.database = database + self.raw_name = name + + def __str__(self): + return "{}.{}".format(self.database, self.raw_name.lower()) + + def __repr__(self): + return "Table: " + str(self) + + def __eq__(self, other): + return type(self) is type(other) and str(self) == str(other) + + def __hash__(self): + return hash(str(self)) + + +class Partition: + pass + + +class Column: + pass
reata/sqllineage
443ae3926f9de92773da57b51d0b61034d96bb80
diff --git a/tests/helpers.py b/tests/helpers.py index cf9775f..8ea1990 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -1,7 +1,12 @@ from sqllineage.core import LineageParser +from sqllineage.models import Table def helper(sql, source_tables=None, target_tables=None): lp = LineageParser(sql) - assert lp.source_tables == (source_tables or set()) - assert lp.target_tables == (target_tables or set()) + assert lp.source_tables == ( + set() if source_tables is None else {Table(t) for t in source_tables} + ) + assert lp.target_tables == ( + set() if target_tables is None else {Table(t) for t in target_tables} + ) diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 0000000..147bfe6 --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,13 @@ +from sqllineage.models import Database, Table + + +def test_repr_dummy(): + assert repr(Database()) + assert repr(Table("")) + + +def test_hash_eq(): + assert Database("a") == Database("a") + assert len({Database("a"), Database("a")}) == 1 + assert Table("a") == Table("a") + assert len({Table("a"), Table("a")}) == 1
dedicated Table/Partition/Column Class for things such as database info, alias name, etc
0.0
443ae3926f9de92773da57b51d0b61034d96bb80
[ "tests/test_models.py::test_repr_dummy", "tests/test_models.py::test_hash_eq" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-04-18 09:29:37+00:00
mit
5,189
reata__sqllineage-53
diff --git a/sqllineage/core.py b/sqllineage/core.py index 2b1b77b..3ebe4dc 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -120,7 +120,7 @@ Target Tables: # referring https://github.com/andialbrecht/sqlparse/issues/218 for further information pass else: - self._source_tables.add(Table(sub_token.get_real_name())) + self._source_tables.add(Table.create(sub_token)) source_table_token_flag = False elif target_table_token_flag: if self.__token_negligible_before_tablename(sub_token): @@ -131,7 +131,7 @@ Target Tables: if not isinstance(sub_token.token_first(skip_cm=True), Identifier): raise SQLLineageException("An Identifier is expected") self._target_tables.add( - Table(sub_token.token_first(skip_cm=True).get_real_name()) + Table.create(sub_token.token_first(skip_cm=True)) ) elif isinstance(sub_token, Comparison): # create table tab1 like tab2, tab1 like tab2 will be parsed as Comparison @@ -141,12 +141,12 @@ Target Tables: and isinstance(sub_token.right, Identifier) ): raise SQLLineageException("An Identifier is expected") - self._target_tables.add(Table(sub_token.left.get_real_name())) - self._source_tables.add(Table(sub_token.right.get_real_name())) + self._target_tables.add(Table.create(sub_token.left)) + self._source_tables.add(Table.create(sub_token.right)) else: if not isinstance(sub_token, Identifier): raise SQLLineageException("An Identifier is expected") - self._target_tables.add(Table(sub_token.get_real_name())) + self._target_tables.add(Table.create(sub_token)) target_table_token_flag = False elif temp_table_token_flag: if self.__token_negligible_before_tablename(sub_token): @@ -154,23 +154,19 @@ Target Tables: else: if not isinstance(sub_token, Identifier): raise SQLLineageException("An Identifier is expected") - self._source_tables.add(Table(sub_token.get_real_name())) - self._target_tables.add(Table(sub_token.get_real_name())) + self._source_tables.add(Table.create(sub_token)) + self._target_tables.add(Table.create(sub_token)) self._extract_from_DML(sub_token) temp_table_token_flag = False def _extract_from_DDL_DROP(self, stmt: Statement) -> None: for st_tables in (self._source_tables, self._target_tables): st_tables -= { - Table(t.get_real_name()) - for t in stmt.tokens - if isinstance(t, Identifier) + Table.create(t) for t in stmt.tokens if isinstance(t, Identifier) } def _extract_from_DDL_ALTER(self, stmt: Statement) -> None: - tables = [ - Table(t.get_real_name()) for t in stmt.tokens if isinstance(t, Identifier) - ] + tables = [Table.create(t) for t in stmt.tokens if isinstance(t, Identifier)] keywords = [t for t in stmt.tokens if t.ttype is Keyword] if any(k.normalized == "RENAME" for k in keywords) and len(tables) == 2: for st_tables in (self._source_tables, self._target_tables): diff --git a/sqllineage/models.py b/sqllineage/models.py index 6ec1349..25bbdef 100644 --- a/sqllineage/models.py +++ b/sqllineage/models.py @@ -1,8 +1,14 @@ -from typing import Optional +import warnings +from sqlparse.sql import Identifier -class Database: - def __init__(self, name: Optional[str] = "<unknown>"): +from sqllineage.exceptions import SQLLineageException + + +class Schema: + unknown = "<unknown>" + + def __init__(self, name: str = unknown): self.raw_name = name def __str__(self): @@ -17,14 +23,26 @@ class Database: def __hash__(self): return hash(str(self)) + def __bool__(self): + return str(self) != self.unknown + class Table: - def __init__(self, name: str, database: Optional[Database] = Database()): - self.database = database - self.raw_name = name + def __init__(self, name: str, schema: Schema = Schema()): + if len(name.split(".")) == 2: + schema_name, table_name = name.split(".") + self.schema = Schema(schema_name) + self.raw_name = table_name + if schema: + warnings.warn("Name is in schema.table format, schema param is ignored") + elif "." not in name: + self.schema = schema + self.raw_name = name + else: + raise SQLLineageException("Invalid format for table name: %s", name) def __str__(self): - return "{}.{}".format(self.database, self.raw_name.lower()) + return "{}.{}".format(self.schema, self.raw_name.lower()) def __repr__(self): return "Table: " + str(self) @@ -35,6 +53,15 @@ class Table: def __hash__(self): return hash(str(self)) + @staticmethod + def create(identifier: Identifier): + schema = ( + Schema(identifier.get_parent_name()) + if identifier.get_parent_name() is not None + else Schema() + ) + return Table(identifier.get_real_name(), schema) + class Partition: pass
reata/sqllineage
4c76a67fde9dbfabb8528fe552bffd0e1672b5e0
diff --git a/tests/test_models.py b/tests/test_models.py index 147bfe6..47f09bc 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,13 +1,13 @@ -from sqllineage.models import Database, Table +from sqllineage.models import Schema, Table def test_repr_dummy(): - assert repr(Database()) + assert repr(Schema()) assert repr(Table("")) def test_hash_eq(): - assert Database("a") == Database("a") - assert len({Database("a"), Database("a")}) == 1 + assert Schema("a") == Schema("a") + assert len({Schema("a"), Schema("a")}) == 1 assert Table("a") == Table("a") assert len({Table("a"), Table("a")}) == 1 diff --git a/tests/test_select.py b/tests/test_select.py index 4f53d07..30d8ee3 100644 --- a/tests/test_select.py +++ b/tests/test_select.py @@ -5,6 +5,10 @@ def test_select(): helper("SELECT col1 FROM tab1", {"tab1"}) +def test_select_with_schema(): + helper("SELECT col1 FROM schema1.tab1", {"schema1.tab1"}) + + def test_select_multi_line(): helper( """SELECT col1 FROM
missing database/schema in lineage result
0.0
4c76a67fde9dbfabb8528fe552bffd0e1672b5e0
[ "tests/test_models.py::test_repr_dummy", "tests/test_models.py::test_hash_eq", "tests/test_select.py::test_select", "tests/test_select.py::test_select_with_schema", "tests/test_select.py::test_select_multi_line", "tests/test_select.py::test_select_asterisk", "tests/test_select.py::test_select_value", "tests/test_select.py::test_select_function", "tests/test_select.py::test_select_with_where", "tests/test_select.py::test_select_with_comment", "tests/test_select.py::test_select_with_comment_after_from", "tests/test_select.py::test_select_with_comment_after_join", "tests/test_select.py::test_select_keyword_as_column_alias", "tests/test_select.py::test_select_with_table_alias", "tests/test_select.py::test_select_count", "tests/test_select.py::test_select_subquery", "tests/test_select.py::test_select_inner_join", "tests/test_select.py::test_select_join", "tests/test_select.py::test_select_left_join", "tests/test_select.py::test_select_left_join_with_extra_space_in_middle", "tests/test_select.py::test_select_left_semi_join", "tests/test_select.py::test_select_left_semi_join_with_on", "tests/test_select.py::test_select_right_join", "tests/test_select.py::test_select_full_outer_join", "tests/test_select.py::test_select_full_outer_join_with_full_as_alias", "tests/test_select.py::test_select_cross_join", "tests/test_select.py::test_select_cross_join_with_on", "tests/test_select.py::test_select_join_with_subquery", "tests/test_select.py::test_with_select" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-07 08:13:47+00:00
mit
5,190
reata__sqllineage-56
diff --git a/sqllineage/combiners.py b/sqllineage/combiners.py index a652340..2887748 100644 --- a/sqllineage/combiners.py +++ b/sqllineage/combiners.py @@ -1,7 +1,9 @@ from functools import reduce -from operator import add +from operator import add, or_ +from typing import Set from sqllineage.core import LineageResult +from sqllineage.models import Table class LineageCombiner: @@ -30,10 +32,22 @@ class DefaultLineageCombiner(LineageCombiner): if table_old in st_tables: st_tables.remove(table_old) st_tables.add(table_new) + elif lineage_result.with_: + combined_result.read |= lineage_result.read - lineage_result.with_ + combined_result.write |= lineage_result.write else: combined_result.read |= lineage_result.read combined_result.write |= lineage_result.write tmp_tables = combined_result.read.intersection(combined_result.write) + self_depend_tables = reduce( + or_, + ( + lineage_result.read.intersection(lineage_result.write) + for lineage_result in args + ), + set(), + ) # type: Set[Table] + tmp_tables -= self_depend_tables combined_result.read -= tmp_tables combined_result.write -= tmp_tables return combined_result diff --git a/sqllineage/core.py b/sqllineage/core.py index 47d3265..3657362 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -27,12 +27,10 @@ TEMP_TABLE_TOKENS = ("WITH",) class LineageResult: """Statement(s) Level Lineage Result.""" - __slots__ = ["read", "write", "rename", "drop"] + __slots__ = ["read", "write", "rename", "drop", "with_"] if TYPE_CHECKING: - read = None # type: Set[Table] - write = None # type: Set[Table] - rename = None # type: Set[Tuple[Table, Table]] - drop = None # type: Set[Table] + read = write = drop = with_ = set() # type: Set[Table] + rename = set() # type: Set[Tuple[Table, Table]] def __init__(self) -> None: for attr in self.__slots__: @@ -54,6 +52,9 @@ class LineageResult: for attr in self.__slots__ ) + def __repr__(self): + return str(self) + class LineageAnalyzer: """SQL Statement Level Lineage Analyzer.""" @@ -160,8 +161,7 @@ class LineageAnalyzer: else: if not isinstance(sub_token, Identifier): raise SQLLineageException("An Identifier is expected") - self._lineage_result.read.add(Table.create(sub_token)) - self._lineage_result.write.add(Table.create(sub_token)) + self._lineage_result.with_.add(Table.create(sub_token)) self._extract_from_DML(sub_token) temp_table_token_flag = False
reata/sqllineage
3ca9308e30c3837095a2a3ac85adb26fa4b6ef7a
diff --git a/tests/test_core.py b/tests/test_core.py index a91e485..58702e9 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -2,5 +2,5 @@ from sqllineage.core import LineageResult def test_dummy(): - assert str(LineageResult()) + assert str(LineageResult()) == repr(LineageResult()) assert LineageResult() + LineageResult() is not None diff --git a/tests/test_insert.py b/tests/test_insert.py index f0b1c6c..b206926 100644 --- a/tests/test_insert.py +++ b/tests/test_insert.py @@ -47,6 +47,17 @@ def test_insert_overwrite_values(): ) +def test_insert_overwrite_from_self(): + helper( + """INSERT OVERWRITE TABLE tab_1 +SELECT tab2.col_a from tab_2 +JOIN tab_1 +ON tab_1.col_a = tab_2.cola""", + {"tab_1", "tab_2"}, + {"tab_1"}, + ) + + def test_with_insert(): helper( "WITH tab1 AS (SELECT * FROM tab2) INSERT INTO tab3 SELECT * FROM tab1", diff --git a/tests/test_models.py b/tests/test_models.py index 47f09bc..9bc2294 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,9 +1,16 @@ +import pytest + +from sqllineage.exceptions import SQLLineageException from sqllineage.models import Schema, Table def test_repr_dummy(): assert repr(Schema()) assert repr(Table("")) + with pytest.raises(SQLLineageException): + Table("a.b.c") + with pytest.warns(Warning): + Table("a.b", Schema("c")) def test_hash_eq(): diff --git a/tests/test_others.py b/tests/test_others.py index 946bf4c..863e1d0 100644 --- a/tests/test_others.py +++ b/tests/test_others.py @@ -73,6 +73,12 @@ drop table tab_a;""" helper(sql, {"tab_b"}, {"tab_c"}) +def test_new_create_tab_as_tmp_table(): + sql = """create table tab_a as select * from tab_b; +create table tab_c as select * from tab_a;""" + helper(sql, {"tab_b"}, {"tab_c"}) + + def test_alter_table_rename(): helper("alter table tab1 rename to tab2;", None, None)
let user choose whether to filter temp table or not Currently, If a table is both source table and target table. sqllineage will identify this table as temp table and hide it from user. We should give use control over the display of temp table
0.0
3ca9308e30c3837095a2a3ac85adb26fa4b6ef7a
[ "tests/test_core.py::test_dummy", "tests/test_insert.py::test_insert_overwrite_from_self" ]
[ "tests/test_insert.py::test_insert_into", "tests/test_insert.py::test_insert_into_with_keyword_table", "tests/test_insert.py::test_insert_into_with_columns", "tests/test_insert.py::test_insert_into_with_columns_and_select", "tests/test_insert.py::test_insert_into_with_columns_and_select_union", "tests/test_insert.py::test_insert_into_partitions", "tests/test_insert.py::test_insert_overwrite", "tests/test_insert.py::test_insert_overwrite_with_keyword_table", "tests/test_insert.py::test_insert_overwrite_values", "tests/test_insert.py::test_with_insert", "tests/test_insert.py::test_with_insert_overwrite", "tests/test_insert.py::test_with_insert_plus_keyword_table", "tests/test_insert.py::test_with_insert_overwrite_plus_keyword_table", "tests/test_models.py::test_repr_dummy", "tests/test_models.py::test_hash_eq", "tests/test_others.py::test_use", "tests/test_others.py::test_table_name_case", "tests/test_others.py::test_create", "tests/test_others.py::test_create_if_not_exist", "tests/test_others.py::test_create_as", "tests/test_others.py::test_create_like", "tests/test_others.py::test_create_select", "tests/test_others.py::test_create_after_drop", "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_with_comment", "tests/test_others.py::test_drop_after_create", "tests/test_others.py::test_drop_tmp_tab_after_create", "tests/test_others.py::test_new_create_tab_as_tmp_table", "tests/test_others.py::test_alter_table_rename", "tests/test_others.py::test_alter_target_table_name", "tests/test_others.py::test_truncate_table", "tests/test_others.py::test_delete_from_table", "tests/test_others.py::test_split_statements", "tests/test_others.py::test_split_statements_with_heading_and_ending_new_line", "tests/test_others.py::test_split_statements_with_comment", "tests/test_others.py::test_split_statements_with_show_create_table", "tests/test_others.py::test_split_statements_with_desc" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-07-18 07:02:16+00:00
mit
5,191
reata__sqllineage-58
diff --git a/sqllineage/runner.py b/sqllineage/runner.py index 643bfc4..20705f7 100644 --- a/sqllineage/runner.py +++ b/sqllineage/runner.py @@ -29,7 +29,7 @@ class LineageRunner(object): self._verbose = verbose def __str__(self): - statements = self.statements + statements = self.statements(strip_comments=True) combined = """Statements(#): {stmt_cnt} Source Tables: {source_tables} @@ -58,9 +58,8 @@ Target Tables: def statements_parsed(self) -> List[Statement]: return self._stmt - @property - def statements(self) -> List[str]: - return [sqlparse.format(s.value) for s in self.statements_parsed] + def statements(self, **kwargs) -> List[str]: + return [sqlparse.format(s.value, **kwargs) for s in self.statements_parsed] @property def source_tables(self) -> Set[Table]:
reata/sqllineage
6d7cbecc817db5145df0d0082cdd646ef2bdd495
diff --git a/tests/test_others.py b/tests/test_others.py index 863e1d0..2468ef5 100644 --- a/tests/test_others.py +++ b/tests/test_others.py @@ -101,30 +101,36 @@ def test_delete_from_table(): def test_split_statements(): sql = "SELECT * FROM tab1; SELECT * FROM tab2;" - assert len(LineageRunner(sql).statements) == 2 + assert len(LineageRunner(sql).statements()) == 2 def test_split_statements_with_heading_and_ending_new_line(): sql = "\nSELECT * FROM tab1;\nSELECT * FROM tab2;\n" - assert len(LineageRunner(sql).statements) == 2 + assert len(LineageRunner(sql).statements()) == 2 def test_split_statements_with_comment(): sql = """SELECT 1; -- SELECT 2;""" - assert len(LineageRunner(sql).statements) == 1 + assert len(LineageRunner(sql).statements()) == 1 + + +def test_statements_trim_comment(): + comment = "------------------\n" + sql = "select * from dual;" + assert LineageRunner(comment + sql).statements(strip_comments=True)[0] == sql def test_split_statements_with_show_create_table(): sql = """SELECT 1; SHOW CREATE TABLE tab1;""" - assert len(LineageRunner(sql).statements) == 2 + assert len(LineageRunner(sql).statements()) == 2 def test_split_statements_with_desc(): sql = """SELECT 1; DESC tab1;""" - assert len(LineageRunner(sql).statements) == 2 + assert len(LineageRunner(sql).statements()) == 2
Trim Leading Comment for Statement in Verbose Output ``` sqllineage -v -e "------------------------ dquote> select * from dual" Statement #1: ------------------------select * from dual table read: {Table: <unknown>.dual} table write: {} table rename: {} table drop: {} table with_: {} ========== Summary: Statements(#): 1 Source Tables: <unknown>.dual Target Tables: ``` We should trim the leading comment line when showing statement.
0.0
6d7cbecc817db5145df0d0082cdd646ef2bdd495
[ "tests/test_others.py::test_split_statements", "tests/test_others.py::test_split_statements_with_heading_and_ending_new_line", "tests/test_others.py::test_split_statements_with_comment", "tests/test_others.py::test_statements_trim_comment", "tests/test_others.py::test_split_statements_with_show_create_table", "tests/test_others.py::test_split_statements_with_desc" ]
[ "tests/test_others.py::test_use", "tests/test_others.py::test_table_name_case", "tests/test_others.py::test_create", "tests/test_others.py::test_create_if_not_exist", "tests/test_others.py::test_create_as", "tests/test_others.py::test_create_like", "tests/test_others.py::test_create_select", "tests/test_others.py::test_create_after_drop", "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_with_comment", "tests/test_others.py::test_drop_after_create", "tests/test_others.py::test_drop_tmp_tab_after_create", "tests/test_others.py::test_new_create_tab_as_tmp_table", "tests/test_others.py::test_alter_table_rename", "tests/test_others.py::test_alter_target_table_name", "tests/test_others.py::test_truncate_table", "tests/test_others.py::test_delete_from_table" ]
{ "failed_lite_validators": [ "has_issue_reference" ], "has_test_patch": true, "is_lite": false }
2020-07-18 08:46:37+00:00
mit
5,192
reata__sqllineage-60
diff --git a/sqllineage/core.py b/sqllineage/core.py index 3657362..25f6751 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -70,6 +70,8 @@ class LineageAnalyzer: elif ( stmt.get_type() == "DELETE" or stmt.token_first(skip_cm=True).normalized == "TRUNCATE" + or stmt.token_first(skip_cm=True).normalized.upper() == "REFRESH" + or stmt.token_first(skip_cm=True).normalized == "CACHE" ): pass else:
reata/sqllineage
5d8751d38c6b953d0d3b8cae2a1823432d3442d1
diff --git a/tests/test_others.py b/tests/test_others.py index 2468ef5..afe8852 100644 --- a/tests/test_others.py +++ b/tests/test_others.py @@ -91,6 +91,14 @@ def test_alter_target_table_name(): ) +def test_refresh_table(): + helper("refresh table tab1", None, None) + + +def test_cache_table(): + helper("cache table tab1", None, None) + + def test_truncate_table(): helper("truncate table tab1", None, None)
Refresh Table and Cache Table Should Not Count as Target Table ``` sqllineage -e "refresh table dual;" Statements(#): 1 Source Tables: Target Tables: <unknown>.dual ```
0.0
5d8751d38c6b953d0d3b8cae2a1823432d3442d1
[ "tests/test_others.py::test_refresh_table", "tests/test_others.py::test_cache_table" ]
[ "tests/test_others.py::test_use", "tests/test_others.py::test_table_name_case", "tests/test_others.py::test_create", "tests/test_others.py::test_create_if_not_exist", "tests/test_others.py::test_create_as", "tests/test_others.py::test_create_like", "tests/test_others.py::test_create_select", "tests/test_others.py::test_create_after_drop", "tests/test_others.py::test_drop", "tests/test_others.py::test_drop_with_comment", "tests/test_others.py::test_drop_after_create", "tests/test_others.py::test_drop_tmp_tab_after_create", "tests/test_others.py::test_new_create_tab_as_tmp_table", "tests/test_others.py::test_alter_table_rename", "tests/test_others.py::test_alter_target_table_name", "tests/test_others.py::test_truncate_table", "tests/test_others.py::test_delete_from_table", "tests/test_others.py::test_split_statements", "tests/test_others.py::test_split_statements_with_heading_and_ending_new_line", "tests/test_others.py::test_split_statements_with_comment", "tests/test_others.py::test_statements_trim_comment", "tests/test_others.py::test_split_statements_with_show_create_table", "tests/test_others.py::test_split_statements_with_desc" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-07-18 08:59:10+00:00
mit
5,193
reata__sqllineage-63
diff --git a/sqllineage/core.py b/sqllineage/core.py index 11ee47e..6c6c494 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -113,18 +113,23 @@ class LineageAnalyzer: if self.__token_negligible_before_tablename(sub_token): continue else: - if not isinstance(sub_token, Identifier): + if isinstance(sub_token, Identifier): + if isinstance(sub_token.token_first(skip_cm=True), Parenthesis): + # SELECT col1 FROM (SELECT col2 FROM tab1) dt, the subquery will be parsed as Identifier + # and this Identifier's get_real_name method would return alias name dt + # referring https://github.com/andialbrecht/sqlparse/issues/218 for further information + pass + else: + self._lineage_result.read.add(Table.create(sub_token)) + elif isinstance(sub_token, Parenthesis): + # SELECT col1 FROM (SELECT col2 FROM tab1), the subquery will be parsed as Parenthesis + # This syntax without alias for subquery is invalid in MySQL, while valid for SparkSQL + pass + else: raise SQLLineageException( "An Identifier is expected, got %s[value: %s] instead" % (type(sub_token).__name__, sub_token) ) - if isinstance(sub_token.token_first(skip_cm=True), Parenthesis): - # SELECT col1 FROM (SELECT col2 FROM tab1) dt, the subquery will be parsed as Identifier - # and this Identifier's get_real_name method would return alias name dt - # referring https://github.com/andialbrecht/sqlparse/issues/218 for further information - pass - else: - self._lineage_result.read.add(Table.create(sub_token)) source_table_token_flag = False elif target_table_token_flag: if self.__token_negligible_before_tablename(sub_token):
reata/sqllineage
54ae4fe7ed6ebae497e45f7c6afde6feb68ca4d9
diff --git a/tests/test_select.py b/tests/test_select.py index 30d8ee3..bfbf552 100644 --- a/tests/test_select.py +++ b/tests/test_select.py @@ -63,7 +63,12 @@ def test_select_count(): def test_select_subquery(): - helper("SELECT col1 FROM (SELECT col2 FROM tab1) dt", {"tab1"}) + helper("SELECT col1 FROM (SELECT col1 FROM tab1) dt", {"tab1"}) + + +def test_select_subquery_without_alias(): + """this syntax is valid in SparkSQL, not for MySQL""" + helper("SELECT col1 FROM (SELECT col1 FROM tab1)", {"tab1"}) def test_select_inner_join():
subquery without alias raises exception ``` SELECT col1 FROM (SELECT col1 FROM tab1) ``` Subquery without alias name is valid syntax in SparkSQL. And this parsing result says: "An Identifier is expected, got Parenthesis[value: (select col1 from tab1)] instead". Since we're not assuming any specific SQL dialect, we should support this.
0.0
54ae4fe7ed6ebae497e45f7c6afde6feb68ca4d9
[ "tests/test_select.py::test_select_subquery_without_alias" ]
[ "tests/test_select.py::test_select", "tests/test_select.py::test_select_with_schema", "tests/test_select.py::test_select_multi_line", "tests/test_select.py::test_select_asterisk", "tests/test_select.py::test_select_value", "tests/test_select.py::test_select_function", "tests/test_select.py::test_select_with_where", "tests/test_select.py::test_select_with_comment", "tests/test_select.py::test_select_with_comment_after_from", "tests/test_select.py::test_select_with_comment_after_join", "tests/test_select.py::test_select_keyword_as_column_alias", "tests/test_select.py::test_select_with_table_alias", "tests/test_select.py::test_select_count", "tests/test_select.py::test_select_subquery", "tests/test_select.py::test_select_inner_join", "tests/test_select.py::test_select_join", "tests/test_select.py::test_select_left_join", "tests/test_select.py::test_select_left_join_with_extra_space_in_middle", "tests/test_select.py::test_select_left_semi_join", "tests/test_select.py::test_select_left_semi_join_with_on", "tests/test_select.py::test_select_right_join", "tests/test_select.py::test_select_full_outer_join", "tests/test_select.py::test_select_full_outer_join_with_full_as_alias", "tests/test_select.py::test_select_cross_join", "tests/test_select.py::test_select_cross_join_with_on", "tests/test_select.py::test_select_join_with_subquery", "tests/test_select.py::test_with_select" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-07-18 11:49:48+00:00
mit
5,194
reata__sqllineage-90
diff --git a/sqllineage/core.py b/sqllineage/core.py index a4f627f..2df62d7 100644 --- a/sqllineage/core.py +++ b/sqllineage/core.py @@ -6,6 +6,7 @@ from sqlparse.sql import ( Comparison, Function, Identifier, + IdentifierList, Parenthesis, Statement, TokenList, @@ -135,6 +136,11 @@ class LineageAnalyzer: pass else: self._lineage_result.read.add(Table.create(sub_token)) + elif isinstance(sub_token, IdentifierList): + # This is to support join in ANSI-89 syntax + for token in sub_token.tokens: + if isinstance(token, Identifier): + self._lineage_result.read.add(Table.create(token)) elif isinstance(sub_token, Parenthesis): # SELECT col1 FROM (SELECT col2 FROM tab1), the subquery will be parsed as Parenthesis # This syntax without alias for subquery is invalid in MySQL, while valid for SparkSQL
reata/sqllineage
46b98fbe548b61e5d63bef8afcb3063c026c4193
diff --git a/tests/test_select.py b/tests/test_select.py index bfbf552..944f1f8 100644 --- a/tests/test_select.py +++ b/tests/test_select.py @@ -128,5 +128,9 @@ def test_select_join_with_subquery(): ) +def test_select_join_in_ansi89_syntax(): + helper("SELECT * FROM tab1 a, tab2 b", {"tab1", "tab2"}) + + def test_with_select(): helper("WITH tab1 AS (SELECT 1) SELECT * FROM tab1")
Cartesian product exception with ANSI-89 Syntax when i use LineageRunner to analyze a sql string like "select a.* from table a,table b " it throws a SQLLineageException: SQLLineageException: An Identifier is expected, got IdentifierList[value: a, table] instead So how can i deal with that exception? `from sqllineage.runner import * LineageRunner("select a.* from table1 a, table2 b").target_tables` `--------------------------------------------------------------------------- SQLLineageException Traceback (most recent call last) <ipython-input-102-0715be0fec21> in <module>() ----> 1 LineageRunner("select a.* from table1 a, table2 b").target_tables ~/anaconda3/lib/python3.6/site-packages/sqllineage/runner.py in __init__(self, sql, encoding, verbose) 31 if s.token_first(skip_cm=True) 32 ] ---> 33 self._lineage_results = [LineageAnalyzer().analyze(stmt) for stmt in self._stmt] 34 self._combined_lineage_result = combine(*self._lineage_results) 35 self._verbose = verbose ~/anaconda3/lib/python3.6/site-packages/sqllineage/runner.py in <listcomp>(.0) 31 if s.token_first(skip_cm=True) 32 ] ---> 33 self._lineage_results = [LineageAnalyzer().analyze(stmt) for stmt in self._stmt] 34 self._combined_lineage_result = combine(*self._lineage_results) 35 self._verbose = verbose ~/anaconda3/lib/python3.6/site-packages/sqllineage/core.py in analyze(self, stmt) 91 else: 92 # DML parsing logic also applies to CREATE DDL ---> 93 self._extract_from_DML(stmt) 94 return self._lineage_result 95 ~/anaconda3/lib/python3.6/site-packages/sqllineage/core.py in _extract_from_DML(self, token) 143 raise SQLLineageException( 144 "An Identifier is expected, got %s[value: %s] instead" --> 145 % (type(sub_token).__name__, sub_token) 146 ) 147 source_table_token_flag = False SQLLineageException: An Identifier is expected, got IdentifierList[value: table1 a, table2 b] instead`
0.0
46b98fbe548b61e5d63bef8afcb3063c026c4193
[ "tests/test_select.py::test_select_join_in_ansi89_syntax" ]
[ "tests/test_select.py::test_select", "tests/test_select.py::test_select_with_schema", "tests/test_select.py::test_select_multi_line", "tests/test_select.py::test_select_asterisk", "tests/test_select.py::test_select_value", "tests/test_select.py::test_select_function", "tests/test_select.py::test_select_with_where", "tests/test_select.py::test_select_with_comment", "tests/test_select.py::test_select_with_comment_after_from", "tests/test_select.py::test_select_with_comment_after_join", "tests/test_select.py::test_select_keyword_as_column_alias", "tests/test_select.py::test_select_with_table_alias", "tests/test_select.py::test_select_count", "tests/test_select.py::test_select_subquery", "tests/test_select.py::test_select_subquery_without_alias", "tests/test_select.py::test_select_inner_join", "tests/test_select.py::test_select_join", "tests/test_select.py::test_select_left_join", "tests/test_select.py::test_select_left_join_with_extra_space_in_middle", "tests/test_select.py::test_select_left_semi_join", "tests/test_select.py::test_select_left_semi_join_with_on", "tests/test_select.py::test_select_right_join", "tests/test_select.py::test_select_full_outer_join", "tests/test_select.py::test_select_full_outer_join_with_full_as_alias", "tests/test_select.py::test_select_cross_join", "tests/test_select.py::test_select_cross_join_with_on", "tests/test_select.py::test_select_join_with_subquery", "tests/test_select.py::test_with_select" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-11-06 13:20:21+00:00
mit
5,195
recurly__recurly-client-python-372
diff --git a/recurly/resource.py b/recurly/resource.py index a3b671c..8677ab4 100644 --- a/recurly/resource.py +++ b/recurly/resource.py @@ -42,9 +42,13 @@ class Resource: if not class_name.endswith("Error"): class_name += "Error" klass = locate("recurly.errors.%s" % class_name) - return klass( - error.message + ". Recurly Request Id: " + response.request_id, error - ) + msg = error.message + ". Recurly Request Id: " + response.request_id + # Use a specific error class if we can find one, else + # fall back to a generic ApiError + if klass: + return klass(msg, error) + else: + return recurly.ApiError(msg, error) @classmethod def cast_json(cls, properties, class_name=None, response=None):
recurly/recurly-client-python
5d3a1faa9792daef003385f4aae57177d48c0358
diff --git a/tests/test_resource.py b/tests/test_resource.py index 9bca2bf..882d4bc 100644 --- a/tests/test_resource.py +++ b/tests/test_resource.py @@ -1,6 +1,7 @@ import unittest import recurly import platform +import json from datetime import datetime from datetime import timezone from recurly import Resource, Response, Request @@ -15,6 +16,10 @@ def cast(obj, class_name=None, resp=None): return Resource.cast_json(obj, class_name, resp) +def cast_error(obj, resp=None): + return Resource.cast_error(obj) + + class TestResource(unittest.TestCase): def test_cast_object_unknown_class(self): # should return the original dict @@ -83,6 +88,29 @@ class TestResource(unittest.TestCase): self.assertEqual(type(page.data[0]), MyResource) self.assertEqual(page.data[0].my_string, "kmxu3f3qof17") + def test_cast_unknown_error(self): + resp = MagicMock() + resp.request_id = "1234" + resp.body = json.dumps( + {"error": {"type": "unknown", "message": "Error Message"}} + ).encode("UTF-8") + err = cast_error(resp) + + # When the error class is unknown, it should fallback to ApiError + self.assertEqual(type(err), recurly.ApiError) + self.assertEqual(str(err), "Error Message. Recurly Request Id: 1234") + + def test_cast_error(self): + resp = MagicMock() + resp.request_id = "1234" + resp.body = json.dumps( + {"error": {"type": "validation", "message": "Invalid"}} + ).encode("UTF-8") + err = cast_error(resp) + + self.assertEqual(type(err), recurly.errors.ValidationError) + self.assertEqual(str(err), "Invalid. Recurly Request Id: 1234") + def test_cast(self): obj = cast( {
Error trying to cast error response **Describe the bug** Seems there is an error while trying to cast an error response due to a missing error class. **To Reproduce** I'm doing a preview request with a wrong zip code (we are using avalara here) and the raw response from the api is the following: ``` {"error":{"type":"service_not_available","message":"Tax service currently not available, please try again later."}} ``` The exception I'm having with the python client is the following: ``` File ".../lib/python3.8/site-packages/recurly/client.py", line 2718, in preview_purchase return self._make_request("POST", path, body, None) File ".../lib/python3.8/site-packages/recurly/base_client.py", line 45, in _make_request raise Resource.cast_error(resp) File .../lib/python3.8/site-packages/recurly/resource.py", line 52, in cast_error return klass( TypeError: 'NoneType' object is not callable ``` Seems code around https://github.com/recurly/recurly-client-python/blob/master/recurly/resource.py#L33 tries to build a class with the name `ServiceNotAvailableError` (matching the returned error type in the json response) but that doesn't exist. **Expected behavior** Error response is parsed and a `recurly.ApiError` is raised. **Your Environment** - Which version of this library are you using? 3.4.1 - Which version of the language are you using? 3.8
0.0
5d3a1faa9792daef003385f4aae57177d48c0358
[ "tests/test_resource.py::TestResource::test_cast_unknown_error" ]
[ "tests/test_resource.py::TestResource::test_cast", "tests/test_resource.py::TestResource::test_cast_error", "tests/test_resource.py::TestResource::test_cast_page", "tests/test_resource.py::TestResource::test_repr_str" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-03-18 19:43:19+00:00
mit
5,196
recurly__recurly-client-python-389
diff --git a/recurly/pager.py b/recurly/pager.py index 1102023..02d6d8b 100644 --- a/recurly/pager.py +++ b/recurly/pager.py @@ -82,7 +82,7 @@ class Pager: """Makes a HEAD request to the API to determine how many total records exist. """ resource = self.__client._make_request("HEAD", self.__path, None, self.__params) - return int(resource.get_response().total_records) + return resource.get_response().total_records def __map_array_params(self, params): """Converts array parameters to CSV strings to maintain consistency with diff --git a/recurly/response.py b/recurly/response.py index a850c51..c42ee80 100644 --- a/recurly/response.py +++ b/recurly/response.py @@ -1,7 +1,28 @@ -import sys, traceback from datetime import datetime import recurly -import json + + +def parse_int_header(dictionary, key): + """Defensively parse an int header""" + val = dictionary.get(key) + + if val is None or not isinstance(val, str): + return None + + if not val.isdigit(): + return None + + return int(val) + + +def parse_datetime_header(dictionary, key): + """Defensively parse datetime header""" + + int_val = parse_int_header(dictionary, key) + if int_val is None: + return None + + return datetime.utcfromtimestamp(int_val) class Response: @@ -12,29 +33,26 @@ class Response: self.status = response.status http_body = response.read() self.body = None + self.__headers = response.headers + + self.request_id = self.__headers.get("X-Request-Id") + self.date = self.__headers.get("Date") + + self.rate_limit = parse_int_header(self.__headers, "X-RateLimit-Limit") + self.rate_limit_remaining = parse_int_header( + self.__headers, "X-RateLimit-Remaining" + ) + self.rate_limit_reset = parse_datetime_header( + self.__headers, "X-RateLimit-Reset" + ) + self.content_type = self.__headers.get("Content-Type", "").split(";")[0] + + self.proxy_metadata = { + "server": self.__headers.get("Server"), + "cf-ray": self.__headers.get("CF-RAY"), + } + + self.total_records = parse_int_header(self.__headers, "Recurly-Total-Records") - try: - self.__headers = response.headers - self.request_id = self.__headers.get("X-Request-Id") - self.rate_limit = int(self.__headers.get("X-RateLimit-Limit")) - self.rate_limit_remaining = int(self.__headers.get("X-RateLimit-Remaining")) - self.rate_limit_reset = datetime.utcfromtimestamp( - int(self.__headers.get("X-RateLimit-Reset")) - ) - self.date = self.__headers.get("Date") - self.content_type = self.__headers.get("Content-Type", "").split(";")[0] - self.proxy_metadata = { - "server": self.__headers.get("Server"), - "cf-ray": self.__headers.get("CF-RAY"), - } - self.total_records = self.__headers.get("recurly-total-records") - if http_body and len(http_body) > 0: - self.body = http_body - except: - # Re-raise the exception in strict-mode - if recurly.STRICT_MODE: - raise - # Log and ignore it in production, we don't want this to kill the whole request - else: - print("[WARNING][Recurly] Unexpected error parsing response metadata") - traceback.print_exc(file=sys.stdout) + if http_body and len(http_body) > 0: + self.body = http_body
recurly/recurly-client-python
69a07d89a68d3d72ad2757c91c23d81034c921c7
diff --git a/tests/test_resource.py b/tests/test_resource.py index 882d4bc..3abaa88 100644 --- a/tests/test_resource.py +++ b/tests/test_resource.py @@ -28,46 +28,6 @@ class TestResource(unittest.TestCase): with self.assertRaises(ValueError): self.assertEqual(cast(obj), obj) - def test_cast_from_response(self): - resp = MagicMock() - resp.headers = { - "X-Request-Id": "0av50sm5l2n2gkf88ehg", - "X-RateLimit-Limit": "2000", - "X-RateLimit-Remaining": "1985", - "X-RateLimit-Reset": "1564624560", - "Date": "Thu, 01 Aug 2019 01:26:44 GMT", - "Server": "cloudflare", - "CF-RAY": "4ff4b71268424738-EWR", - } - - request = Request("GET", "/sites", {}) - empty = cast({}, "Empty", Response(resp, request)) - response = empty.get_response() - - self.assertEqual(type(response), Response) - self.assertEqual(response.request_id, "0av50sm5l2n2gkf88ehg") - self.assertEqual(response.rate_limit, 2000) - self.assertEqual(response.rate_limit_remaining, 1985) - self.assertEqual(response.rate_limit_reset, datetime(2019, 8, 1, 1, 56)) - self.assertEqual(response.date, "Thu, 01 Aug 2019 01:26:44 GMT") - self.assertEqual(response.proxy_metadata["server"], "cloudflare") - self.assertEqual(response.proxy_metadata["cf-ray"], "4ff4b71268424738-EWR") - self.assertEqual(response.request.method, "GET") - self.assertEqual(response.request.path, "/sites") - self.assertEqual(response.request.body, {}) - - resp = MagicMock() - resp.headers = { - "X-Request-Id": "abcd123", - "X-RateLimit-Limit": "invalid2000", - "X-RateLimit-Remaining": "1985", - "X-RateLimit-Reset": "1564624560", - "Date": "Thu, 01 Aug 2019 01:26:44 GMT", - } - - with self.assertRaises(ValueError): - cast({}, "Empty", Response(resp, request)) - def test_cast_page(self): # should return a page of cast data page = cast( diff --git a/tests/test_response.py b/tests/test_response.py new file mode 100644 index 0000000..6b83b1d --- /dev/null +++ b/tests/test_response.py @@ -0,0 +1,79 @@ +import unittest +import recurly +from datetime import datetime +from recurly import Response, Request +from unittest.mock import Mock, MagicMock + + +class TestResponse(unittest.TestCase): + def test_init(self): + resp = MagicMock() + resp.headers = { + "X-Request-Id": "0av50sm5l2n2gkf88ehg", + "X-RateLimit-Limit": "2000", + "X-RateLimit-Remaining": "1985", + "X-RateLimit-Reset": "1564624560", + "Recurly-Total-Records": "100", + "Date": "Thu, 01 Aug 2019 01:26:44 GMT", + "Server": "cloudflare", + "CF-RAY": "4ff4b71268424738-EWR", + } + + req = Request("GET", "/sites", {}) + response = Response(resp, req) + + self.assertEqual(type(response), Response) + self.assertEqual(response.request_id, "0av50sm5l2n2gkf88ehg") + self.assertEqual(response.rate_limit, 2000) + self.assertEqual(response.rate_limit_remaining, 1985) + self.assertEqual(response.rate_limit_reset, datetime(2019, 8, 1, 1, 56)) + self.assertEqual(response.total_records, 100) + self.assertEqual(response.date, "Thu, 01 Aug 2019 01:26:44 GMT") + self.assertEqual(response.proxy_metadata["server"], "cloudflare") + self.assertEqual(response.proxy_metadata["cf-ray"], "4ff4b71268424738-EWR") + self.assertEqual(response.request.method, "GET") + self.assertEqual(response.request.path, "/sites") + self.assertEqual(response.request.body, {}) + + def test_init_with_invalid_headers(self): + resp = MagicMock() + resp.headers = { + "X-Request-Id": "0av50sm5l2n2gkf88ehg", + "X-RateLimit-Limit": "notanum", + "X-RateLimit-Remaining": "notanum", + "X-RateLimit-Reset": "notanum", + "recurly-total-records": "notanum", + "Date": "Thu, 01 Aug 2019 01:26:44 GMT", + "Server": "cloudflare", + "CF-RAY": "4ff4b71268424738-EWR", + } + + req = Request("GET", "/sites", {}) + response = Response(resp, req) + + self.assertEqual(type(response), Response) + self.assertEqual(response.request_id, "0av50sm5l2n2gkf88ehg") + self.assertEqual(response.rate_limit, None) + self.assertEqual(response.rate_limit_remaining, None) + self.assertEqual(response.rate_limit_reset, None) + self.assertEqual(response.total_records, None) + self.assertEqual(response.date, "Thu, 01 Aug 2019 01:26:44 GMT") + self.assertEqual(response.proxy_metadata["server"], "cloudflare") + self.assertEqual(response.proxy_metadata["cf-ray"], "4ff4b71268424738-EWR") + + def test_init_with_missing_headers(self): + resp = MagicMock() + resp.headers = {} + + req = Request("GET", "/sites", {}) + response = Response(resp, req) + + self.assertEqual(type(response), Response) + self.assertEqual(response.request_id, None) + self.assertEqual(response.rate_limit, None) + self.assertEqual(response.rate_limit_remaining, None) + self.assertEqual(response.rate_limit_reset, None) + self.assertEqual(response.total_records, None) + self.assertEqual(response.date, None) + self.assertEqual(response.proxy_metadata["server"], None) + self.assertEqual(response.proxy_metadata["cf-ray"], None)
RateLimiter Exception When I reach the rate-limit I get a no-explicit error message. The error that I get is the following: ` self.rate_limit = int(self.__headers.get("X-RateLimit-Limit")) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' ` **Your Environment** - 3.4.2 - python3.8
0.0
69a07d89a68d3d72ad2757c91c23d81034c921c7
[ "tests/test_response.py::TestResponse::test_init", "tests/test_response.py::TestResponse::test_init_with_invalid_headers", "tests/test_response.py::TestResponse::test_init_with_missing_headers" ]
[ "tests/test_resource.py::TestResource::test_cast", "tests/test_resource.py::TestResource::test_cast_error", "tests/test_resource.py::TestResource::test_cast_page", "tests/test_resource.py::TestResource::test_cast_unknown_error", "tests/test_resource.py::TestResource::test_repr_str" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2020-04-24 17:30:19+00:00
mit
5,197
red-coracle__flask-argon2-10
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..2fa020d --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,27 @@ +name: pytest + +on: [push, pull_request] + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ['3.7', '3.8', '3.9', '3.10'] + + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 1 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v3 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + - name: Test with pytest + run: | + pip install pytest + pytest test_flask_argon2.py diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index f70bf5c..0000000 --- a/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -sudo: required -language: python -dist: focal -python: - - 2.7 - - 3.5 - - 3.6 - - 3.7 - - 3.8 - - "nightly" - - "pypy" - - "pypy3" - -matrix: - allow_failures: - - python: "nightly" - - python: pypy - - python: pypy3 - -install: - - pip install . - - pip install flask - -script: - - python setup.py test - -notifications: - email: false diff --git a/flask_argon2.py b/flask_argon2.py index 2f75d97..0177963 100644 --- a/flask_argon2.py +++ b/flask_argon2.py @@ -4,13 +4,10 @@ A Flask extension providing argon2 hashing and comparison. - :copyright: (c) 2019 by DominusTemporis. + :copyright: (c) 2022 by red-coracle. :license: MIT, see LICENSE for more details. """ -from __future__ import absolute_import -from __future__ import print_function -# from sys import version_info __version_info__ = ('0', '2', '0', '0') __version__ = '.'.join(__version_info__) @@ -26,8 +23,6 @@ except ImportError as e: print('argon2_cffi is required to use Flask-Argon2') raise e -# PY3 = version_info[0] >= 3 - def generate_password_hash(password): ''' @@ -110,35 +105,41 @@ class Argon2(object): def __init__(self, app=None, - time_cost=_time_cost, - memory_cost=_memory_cost, - parallelism=_parallelism, - hash_len=_hash_len, - salt_len=_salt_len, - encoding=_encoding): + time_cost: int = None, + memory_cost: int = None, + parallelism: int = None, + hash_len: int = None, + salt_len: int = None, + encoding: str = None): + # Keep for backwards compatibility self.time_cost = time_cost self.memory_cost = memory_cost self.parallelism = parallelism self.hash_len = hash_len self.salt_len = salt_len self.encoding = encoding - self.ph = argon2.PasswordHasher(self.time_cost, - self.memory_cost, - self.parallelism, - self.hash_len, - self.salt_len, - self.encoding) - + self.init_app(app) + def init_app(self, app): '''Initalizes the application with the extension. :param app: The Flask application object. ''' - self.time_cost = app.config.get('ARGON2_TIME_COST', self._time_cost) - self.memory_cost = app.config.get('ARGON2_MEMORY_COST', self._memory_cost) - self.parallelism = app.config.get('ARGON2_PARALLELISM', self._parallelism) - self.hash_len = app.config.get('ARGON2_HASH_LENGTH', self._hash_len) - self.salt_len = app.config.get('ARGON2_SALT_LENGTH', self._salt_len) - self.encoding = app.config.get('ARGON2_ENCODING', self._encoding) + + self.time_cost = self.time_cost or self._time_cost + self.memory_cost = self.memory_cost or self._memory_cost + self.parallelism = self.parallelism or self._parallelism + self.hash_len = self.hash_len or self._hash_len + self.salt_len = self.salt_len or self._salt_len + self.encoding = self.encoding or self._encoding + + if app is not None: + self.time_cost = app.config.get('ARGON2_TIME_COST', self.time_cost) + self.memory_cost = app.config.get('ARGON2_MEMORY_COST', self.memory_cost) + self.parallelism = app.config.get('ARGON2_PARALLELISM', self.parallelism) + self.hash_len = app.config.get('ARGON2_HASH_LENGTH', self.hash_len) + self.salt_len = app.config.get('ARGON2_SALT_LENGTH', self.salt_len) + self.encoding = app.config.get('ARGON2_ENCODING', self.encoding) + self.ph = argon2.PasswordHasher(self.time_cost, self.memory_cost, self.parallelism, @@ -146,7 +147,6 @@ class Argon2(object): self.salt_len, self.encoding) - def generate_password_hash(self, password): '''Generates a password hash using argon2. Example usage of :class:`generate_password_hash` might look something @@ -158,13 +158,6 @@ class Argon2(object): if not password: raise ValueError('Password must be non-empty.') - # if PY3: - # if isinstance(password, str): - # password = bytes(password, 'utf-8') - # else: - # if isinstance(password, unicode): - # password = password.encode('utf-8') - return self.ph.hash(password) def check_password_hash(self, pw_hash, password): diff --git a/requirements.txt b/requirements.txt index ca76291..8dce1a2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ -argon2_cffi>=20.1.0 -Flask>=1.* +argon2_cffi>=21.0.0 +Flask>=2.*
red-coracle/flask-argon2
2dec14c557ecf31e986afbfbd3363392a660f050
diff --git a/test_flask_argon2.py b/test_flask_argon2.py index c3547d4..e47a314 100644 --- a/test_flask_argon2.py +++ b/test_flask_argon2.py @@ -1,48 +1,67 @@ -# coding:utf-8 - -import unittest import flask -from flask_argon2 import (Argon2, check_password_hash, generate_password_hash) +import pytest +from argon2.profiles import CHEAPEST + +from flask_argon2 import Argon2, check_password_hash, generate_password_hash + + [email protected](scope='module') +def _argon2(): + app = flask.Flask(__name__) + return Argon2(app) + + +def test_check_hash(_argon2): + pw_hash = _argon2.generate_password_hash('secret') + assert check_password_hash(pw_hash, 'secret') is True + pw_hash = _argon2.generate_password_hash(u'\u2603') + assert _argon2.check_password_hash(pw_hash, u'\u2603') is True + pw_hash = generate_password_hash('hunter2') + assert check_password_hash(pw_hash, 'hunter2') is True + + +def test_unicode_hash(_argon2): + password = u'東京' + pw_hash = _argon2.generate_password_hash(password) + assert _argon2.check_password_hash(pw_hash, password) is True + +def test_hash_error(_argon2): + pw_hash = _argon2.generate_password_hash('secret') + assert _argon2.check_password_hash(pw_hash, 'hunter2') is False -class BasicTestCase(unittest.TestCase): - def setUp(self): - app = flask.Flask(__name__) - self.argon2 = Argon2(app) +def test_invalid_hash(_argon2): + assert _argon2.check_password_hash('secret', 'hunter2') is False - def test_check_hash(self): - pw_hash = self.argon2.generate_password_hash('secret') - self.assertTrue(self.argon2.check_password_hash(pw_hash, 'secret')) - pw_hash = self.argon2.generate_password_hash(u'\u2603') - self.assertTrue(self.argon2.check_password_hash(pw_hash, u'\u2603')) - pw_hash = generate_password_hash('hunter2') - self.assertTrue(check_password_hash(pw_hash, 'hunter2')) - def test_unicode_hash(self): - password = u'東京' - pw_hash = generate_password_hash(password) - self.assertTrue(check_password_hash(pw_hash, password)) +def test_init_override(): + app = flask.Flask(__name__) + _argon2 = Argon2(app, parallelism=3) + pw_hash = _argon2.generate_password_hash('secret') + assert _argon2.parallelism == 3 + assert _argon2.check_password_hash(pw_hash, 'secret') is True - def test_hash_error(self): - pw_hash = self.argon2.generate_password_hash('secret') - self.assertFalse(self.argon2.check_password_hash(pw_hash, 'hunter2')) - - def test_hash_invalid_hash(self): - """ Check that an InvalidHash is raised when an unhased password is used. """ - self.assertFalse(self.argon2.check_password_hash('secret', 'hunter2')) +def test_app_config_override(): + app = flask.Flask(__name__) + app.config['ARGON2_MEMORY_COST'] = CHEAPEST.memory_cost + _argon2 = Argon2(app) + assert _argon2.memory_cost == CHEAPEST.memory_cost + assert _argon2.ph.memory_cost == CHEAPEST.memory_cost -class OverridesTestCase(unittest.TestCase): - def setUp(self): - app = flask.Flask(__name__) - self.argon2 = Argon2(app, parallelism=3) +def test_multiple_overrides(): + app = flask.Flask(__name__) + app.config['ARGON2_PARALLELISM'] = CHEAPEST.parallelism + _argon2 = Argon2(app, hash_len=16) + assert _argon2.parallelism == CHEAPEST.parallelism + assert _argon2.hash_len == 16 - def test_changed_parallelism(self): - pw_hash = self.argon2.generate_password_hash('secret') - self.assertTrue(self.argon2.parallelism == 3) - self.assertTrue(self.argon2.check_password_hash(pw_hash, 'secret')) -if __name__ == '__main__': - unittest.main() +def test_multiple_override_same_parameter(): + app = flask.Flask(__name__) + app.config['ARGON2_PARALLELISM'] = CHEAPEST.parallelism + _argon2 = Argon2(app, parallelism=8) + assert _argon2.parallelism == CHEAPEST.parallelism + assert _argon2.ph.parallelism == CHEAPEST.parallelism
default settings Hello, Seems it's not possible to change default argon2 settings, at least I didn't figure out the way to set them via typical app.config: ``` # example code (custom flask script) from flask_argon2 import Argon2 from flask import Flask app = Flask(__name__) # example trying to change only memory cost value app.config['ARGON2_MEMORY_COST'] = 131072 app.config['DEFAULT_MEMORY_COST'] = 131072 crypt_argon2 = Argon2(app) ``` looks like the Argon2 module is taking pre-set default values from argon2 module (password_hasher.py), and ignores any values passed in via app.config. And unless changing the argon2 module code, I can't find other way to set custom values. ``` # argon2/password_hasher.py from .profiles import RFC_9106_LOW_MEMORY DEFAULT_RANDOM_SALT_LENGTH = RFC_9106_LOW_MEMORY.salt_len DEFAULT_HASH_LENGTH = RFC_9106_LOW_MEMORY.hash_len DEFAULT_TIME_COST = RFC_9106_LOW_MEMORY.time_cost DEFAULT_MEMORY_COST = RFC_9106_LOW_MEMORY.memory_cost DEFAULT_PARALLELISM = RFC_9106_LOW_MEMORY.parallelism ``` Values passed to argon2 hash function: ``` # argon2/profiles.py # SECOND RECOMMENDED option per RFC 9106. RFC_9106_LOW_MEMORY = Parameters( type=Type.ID, version=19, salt_len=16, hash_len=32, time_cost=3, memory_cost=65536, # 64 MiB parallelism=4, ) ``` Is this intended, or I am doing something wrong?
0.0
2dec14c557ecf31e986afbfbd3363392a660f050
[ "test_flask_argon2.py::test_app_config_override", "test_flask_argon2.py::test_multiple_overrides", "test_flask_argon2.py::test_multiple_override_same_parameter" ]
[ "test_flask_argon2.py::test_check_hash", "test_flask_argon2.py::test_unicode_hash", "test_flask_argon2.py::test_hash_error", "test_flask_argon2.py::test_invalid_hash", "test_flask_argon2.py::test_init_override" ]
{ "failed_lite_validators": [ "has_added_files", "has_removed_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-06-04 12:21:18+00:00
mit
5,198
red-hat-storage__rhcephpkg-91
diff --git a/rhcephpkg/merge_patches.py b/rhcephpkg/merge_patches.py index 9db15c2..6cb48d1 100644 --- a/rhcephpkg/merge_patches.py +++ b/rhcephpkg/merge_patches.py @@ -14,23 +14,30 @@ that into our local patch-queue branch, so that both branches align. This command helps to align the patch series between our RHEL packages and our Ubuntu packages. +Options: +--force Do a hard reset, rather than restricting to fast-forward merges + only. Use this option if the RHEL patches branch was amended or + rebased for some reason. """ name = 'merge-patches' def __init__(self, argv): self.argv = argv - self.options = [] + self.options = ['--force', '--hard-reset'] def main(self): self.parser = Transport(self.argv, options=self.options) self.parser.catch_help = self.help() self.parser.parse_args() - self._run() + force = False + if self.parser.has(['--force', '--hard-reset']): + force = True + self._run(force) def help(self): return self._help - def _run(self): + def _run(self, force=False): # Determine the names of the relevant branches current_branch = util.current_branch() debian_branch = util.current_debian_branch() @@ -43,6 +50,10 @@ Ubuntu packages. # For example: "git pull --ff-only patches/ceph-2-rhel-patches" cmd = ['git', 'pull', '--ff-only', 'patches/' + rhel_patches_branch] + if force: + # Do a hard reset on HEAD instead. + cmd = ['git', 'reset', '--hard', + 'patches/' + rhel_patches_branch] else: # HEAD is our debian branch. Use "git fetch" to update the # patch-queue ref. For example: @@ -50,6 +61,10 @@ Ubuntu packages. # patches/ceph-2-rhel-patches:patch-queue/ceph-2-ubuntu" cmd = ['git', 'fetch', '.', 'patches/%s:%s' % (rhel_patches_branch, patches_branch)] + if force: + # Do a hard push (with "+") instead. + cmd = ['git', 'push', '.', '+%s:patches/%s' % + (patches_branch, rhel_patches_branch)] log.info(' '.join(cmd)) subprocess.check_call(cmd)
red-hat-storage/rhcephpkg
ccc287abb2d2674338a8f80dbb825a10f834f2f5
diff --git a/rhcephpkg/tests/test_merge_patches.py b/rhcephpkg/tests/test_merge_patches.py index 90da51c..308f0aa 100644 --- a/rhcephpkg/tests/test_merge_patches.py +++ b/rhcephpkg/tests/test_merge_patches.py @@ -42,6 +42,31 @@ class TestMergePatches(object): expected = ['git', 'pull', '--ff-only', 'patches/ceph-2-rhel-patches'] assert self.last_cmd == expected + def test_force_on_debian_branch(self, monkeypatch): + monkeypatch.setenv('HOME', FIXTURES_DIR) + monkeypatch.setattr('subprocess.check_call', self.fake_check_call) + # set current_branch() to a debian branch: + monkeypatch.setattr('rhcephpkg.util.current_branch', + lambda: 'ceph-2-ubuntu') + localbuild = MergePatches(()) + localbuild._run(force=True) + # Verify that we run the "git push" command here. + expected = ['git', 'push', '.', + '+patch-queue/ceph-2-ubuntu:patches/ceph-2-rhel-patches'] + assert self.last_cmd == expected + + def test_force_on_patch_queue_branch(self, monkeypatch): + monkeypatch.setenv('HOME', FIXTURES_DIR) + monkeypatch.setattr('subprocess.check_call', self.fake_check_call) + # set current_branch() to a patch-queue branch: + monkeypatch.setattr('rhcephpkg.util.current_branch', + lambda: 'patch-queue/ceph-2-ubuntu') + localbuild = MergePatches(()) + localbuild._run(force=True) + # Verify that we run the "git reset" command here. + expected = ['git', 'reset', '--hard', 'patches/ceph-2-rhel-patches'] + assert self.last_cmd == expected + class TestMergePatchesRhelPatchesBranch(object):
"merge-patches --hard-reset" Currently the `rhcephpkg merge-patches` command can automatically merge patches from the rdopkg -patches branch *as long as* it is a fast-forward merge. Sometimes if we need to back out a patch, this is no longer a fast-forward merge, and we have to do the following by hand instead: ``` $ git checkout patch-queue/ceph-2-ubuntu $ git reset --hard patches/ceph-2-rhel-patches ``` It would be great to have a `rhcephpkg merge-patches --hard-reset` to do this automatically.
0.0
ccc287abb2d2674338a8f80dbb825a10f834f2f5
[ "rhcephpkg/tests/test_merge_patches.py::TestMergePatches::test_force_on_debian_branch", "rhcephpkg/tests/test_merge_patches.py::TestMergePatches::test_force_on_patch_queue_branch" ]
[ "rhcephpkg/tests/test_merge_patches.py::TestMergePatches::test_merge_patch_on_debian_branch", "rhcephpkg/tests/test_merge_patches.py::TestMergePatches::test_merge_patch_on_patch_queue_branch", "rhcephpkg/tests/test_merge_patches.py::TestMergePatchesRhelPatchesBranch::test_get_rhel_patches_branch[ceph-1.3-ubuntu-ceph-1.3-rhel-patches]", "rhcephpkg/tests/test_merge_patches.py::TestMergePatchesRhelPatchesBranch::test_get_rhel_patches_branch[ceph-2-ubuntu-ceph-2-rhel-patches]", "rhcephpkg/tests/test_merge_patches.py::TestMergePatchesRhelPatchesBranch::test_get_rhel_patches_branch[ceph-2-trusty-ceph-2-rhel-patches]", "rhcephpkg/tests/test_merge_patches.py::TestMergePatchesRhelPatchesBranch::test_get_rhel_patches_branch[ceph-2-xenial-ceph-2-rhel-patches]", "rhcephpkg/tests/test_merge_patches.py::TestMergePatchesRhelPatchesBranch::test_get_rhel_patches_branch[someotherproduct-2-ubuntu-someotherproduct-2-rhel-patches]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2017-01-27 00:26:11+00:00
mit
5,199
redhat-cip__hardware-108
diff --git a/hardware/benchmark/disk.py b/hardware/benchmark/disk.py index 6b987b66..92f779db 100644 --- a/hardware/benchmark/disk.py +++ b/hardware/benchmark/disk.py @@ -37,7 +37,8 @@ RAMP_TIME = 5 def is_booted_storage_device(disk): """Check if a given disk is booted.""" - cmdline = "grep -w /ahcexport /proc/mounts | cut -d ' ' -f 1 | sed -e 's/[0-9]*//g'" # noqa + cmdline = ("grep -w /ahcexport /proc/mounts | cut -d ' ' -f 1 | " + "sed -e 's/[0-9]*//g'") if '/dev/' not in disk: disk = '/dev/%s' % disk grep_cmd = subprocess.Popen(cmdline, diff --git a/hardware/benchmark/mem.py b/hardware/benchmark/mem.py index abd4fd02..1a30ba36 100644 --- a/hardware/benchmark/mem.py +++ b/hardware/benchmark/mem.py @@ -22,6 +22,8 @@ import re import subprocess import sys +import six + from hardware.benchmark import utils @@ -88,6 +90,8 @@ def run_sysbench_memory_threaded(hw_lst, max_time, block_size, cpu_count, shell=True, stdout=subprocess.PIPE) for line in sysbench_cmd.stdout: + if isinstance(line, six.binary_type): + line = line.decode() if "transferred" in line: _, right = line.rstrip('\n').replace(' ', '').split('(') perf, _ = right.split('.') @@ -125,6 +129,8 @@ def run_sysbench_memory_forked(hw_lst, max_time, block_size, cpu_count): process = subprocess.Popen( sysbench_cmd, shell=True, stdout=subprocess.PIPE) for line in process.stdout: + if isinstance(line, six.binary_type): + line = line.decode() if "transferred" in line: _, right = line.rstrip('\n').replace(' ', '').split('(') perf, _ = right.split('.') diff --git a/hardware/cardiff/check.py b/hardware/cardiff/check.py index 92d3fb4d..e935e480 100755 --- a/hardware/cardiff/check.py +++ b/hardware/cardiff/check.py @@ -441,19 +441,36 @@ def print_summary(mode, array, array_name, unit, df, item_value=None): min_cpu_perf = perf_cpu_tables.get_cpu_min_perf(mode, item_value) if min_cpu_perf == 0: - perf_status = (": " + ORANGE + "NO PERF ENTRY IN DB" + - WHITE + " for " + item_value) + perf_status = (": %(orange)sNO PERF ENTRY IN DB" + "%(white)s for %(item_value)s" % + {'orange': ORANGE, + 'white': WHITE, + 'item_value': item_value}) elif mean >= min_cpu_perf: - perf_status = ": " + GREEN + "PERF OK" + WHITE + perf_status = (": %(green)sPERF OK%(white)s" % + {'green': GREEN, + 'white': WHITE}) else: - perf_status = (": " + RED + "PERF FAIL" + WHITE + - " as min perf should have been : " + - str(min_cpu_perf)) - utils.do_print( - mode, utils.Levels.SUMMARY, - "%3d %s%-10s%s hosts with %8.2f %-4s as average value and %8.2f " - "standard deviation %s", len(array), before, array_name, after, - mean, unit, numpy.std(result), perf_status) + perf_status = (": %(red)sPERF FAIL%(white)s as min " + "perf should have been : " + "%(min_cpu_perf)s" % + {'red': RED, + 'white': WHITE, + 'min_cpu_perf': str(min_cpu_perf)}) + + msg = ("%(array_length)3d %(before)s%(array_name)-10s%(after)s hosts " + "with %(mean)8.2f %(unit)-4s as average value and " + "%(result)8.2f standard deviation %(perf_status)s" % + {'array_length': len(array), + 'before': before, + 'array_name': array_name, + 'after': after, + 'mean': mean, + 'unit': unit, + 'result': numpy.std(result), + 'perf_status': perf_status}) + + utils.do_print(mode, utils.Levels.SUMMARY, msg) def cpu_perf(system_list, unique_id, group_number, detail_options,
redhat-cip/hardware
210ba54bd3f18a1eb65a54e434b304f51b6b2a97
diff --git a/hardware/tests/test_benchmark_mem.py b/hardware/tests/test_benchmark_mem.py index 1c0e9e2c..445a4c50 100644 --- a/hardware/tests/test_benchmark_mem.py +++ b/hardware/tests/test_benchmark_mem.py @@ -41,7 +41,40 @@ Test execution summary: Threads fairness: events (avg/stddev): 1957354.0000/0.00 - execution time (avg/stddev): 3.0686/0.00""".splitlines() + execution time (avg/stddev): 3.0686/0.00""" + +EXPECTED_RESULT = [ + ('cpu', 'logical', 'number', 2), + ('cpu', 'physical', 'number', 2), + ('cpu', 'logical_0', 'bandwidth_1K', '382'), + ('cpu', 'logical_0', 'bandwidth_4K', '382'), + ('cpu', 'logical_0', 'bandwidth_1M', '382'), + ('cpu', 'logical_0', 'bandwidth_16M', '382'), + ('cpu', 'logical_0', 'bandwidth_128M', '382'), + ('cpu', 'logical_0', 'bandwidth_1G', '382'), + ('cpu', 'logical_0', 'bandwidth_2G', '382'), + ('cpu', 'logical_1', 'bandwidth_1K', '382'), + ('cpu', 'logical_1', 'bandwidth_4K', '382'), + ('cpu', 'logical_1', 'bandwidth_1M', '382'), + ('cpu', 'logical_1', 'bandwidth_16M', '382'), + ('cpu', 'logical_1', 'bandwidth_128M', '382'), + ('cpu', 'logical_1', 'bandwidth_1G', '382'), + ('cpu', 'logical_1', 'bandwidth_2G', '382'), + ('cpu', 'logical', 'threaded_bandwidth_1K', '382'), + ('cpu', 'logical', 'threaded_bandwidth_4K', '382'), + ('cpu', 'logical', 'threaded_bandwidth_1M', '382'), + ('cpu', 'logical', 'threaded_bandwidth_16M', '382'), + ('cpu', 'logical', 'threaded_bandwidth_128M', '382'), + ('cpu', 'logical', 'threaded_bandwidth_1G', '382'), + ('cpu', 'logical', 'threaded_bandwidth_2G', '382'), + ('cpu', 'logical', 'forked_bandwidth_1K', '382'), + ('cpu', 'logical', 'forked_bandwidth_4K', '382'), + ('cpu', 'logical', 'forked_bandwidth_1M', '382'), + ('cpu', 'logical', 'forked_bandwidth_16M', '382'), + ('cpu', 'logical', 'forked_bandwidth_128M', '382'), + ('cpu', 'logical', 'forked_bandwidth_1G', '382'), + ('cpu', 'logical', 'forked_bandwidth_2G', '382') +] @mock.patch.object(mem, 'get_available_memory') @@ -54,44 +87,26 @@ class TestBenchmarkMem(unittest.TestCase): self.hw_data = [('cpu', 'logical', 'number', 2), ('cpu', 'physical', 'number', 2)] - def test_mem_perf(self, mock_popen, mock_cpu_socket, mock_get_memory): + def test_mem_perf_bytes(self, mock_popen, mock_cpu_socket, + mock_get_memory): mock_get_memory.return_value = 123456789012 - mock_popen.return_value = mock.Mock(stdout=SYSBENCH_OUTPUT) + mock_popen.return_value = mock.Mock( + stdout=SYSBENCH_OUTPUT.encode().splitlines()) mock_cpu_socket.return_value = range(2) mem.mem_perf(self.hw_data) - expected = [ - ('cpu', 'logical', 'number', 2), - ('cpu', 'physical', 'number', 2), - ('cpu', 'logical_0', 'bandwidth_1K', '382'), - ('cpu', 'logical_0', 'bandwidth_4K', '382'), - ('cpu', 'logical_0', 'bandwidth_1M', '382'), - ('cpu', 'logical_0', 'bandwidth_16M', '382'), - ('cpu', 'logical_0', 'bandwidth_128M', '382'), - ('cpu', 'logical_0', 'bandwidth_1G', '382'), - ('cpu', 'logical_0', 'bandwidth_2G', '382'), - ('cpu', 'logical_1', 'bandwidth_1K', '382'), - ('cpu', 'logical_1', 'bandwidth_4K', '382'), - ('cpu', 'logical_1', 'bandwidth_1M', '382'), - ('cpu', 'logical_1', 'bandwidth_16M', '382'), - ('cpu', 'logical_1', 'bandwidth_128M', '382'), - ('cpu', 'logical_1', 'bandwidth_1G', '382'), - ('cpu', 'logical_1', 'bandwidth_2G', '382'), - ('cpu', 'logical', 'threaded_bandwidth_1K', '382'), - ('cpu', 'logical', 'threaded_bandwidth_4K', '382'), - ('cpu', 'logical', 'threaded_bandwidth_1M', '382'), - ('cpu', 'logical', 'threaded_bandwidth_16M', '382'), - ('cpu', 'logical', 'threaded_bandwidth_128M', '382'), - ('cpu', 'logical', 'threaded_bandwidth_1G', '382'), - ('cpu', 'logical', 'threaded_bandwidth_2G', '382'), - ('cpu', 'logical', 'forked_bandwidth_1K', '382'), - ('cpu', 'logical', 'forked_bandwidth_4K', '382'), - ('cpu', 'logical', 'forked_bandwidth_1M', '382'), - ('cpu', 'logical', 'forked_bandwidth_16M', '382'), - ('cpu', 'logical', 'forked_bandwidth_128M', '382'), - ('cpu', 'logical', 'forked_bandwidth_1G', '382'), - ('cpu', 'logical', 'forked_bandwidth_2G', '382') - ] + expected = EXPECTED_RESULT + self.assertEqual(sorted(expected), sorted(self.hw_data)) + + def test_mem_perf_text(self, mock_popen, mock_cpu_socket, + mock_get_memory): + mock_get_memory.return_value = 123456789012 + mock_popen.return_value = mock.Mock( + stdout=SYSBENCH_OUTPUT.splitlines()) + mock_cpu_socket.return_value = range(2) + mem.mem_perf(self.hw_data) + + expected = EXPECTED_RESULT self.assertEqual(sorted(expected), sorted(self.hw_data)) def test_check_mem_size(self, mock_popen, mock_cpu_socket, @@ -107,20 +122,47 @@ class TestBenchmarkMem(unittest.TestCase): for block_size in block_size_list: self.assertFalse(mem.check_mem_size(block_size, 2)) - def test_run_sysbench_memory_forked(self, mock_popen, mock_cpu_socket, - mock_get_memory): + def test_run_sysbench_memory_forked_text(self, mock_popen, mock_cpu_socket, + mock_get_memory): mock_get_memory.return_value = 123456789012 - mock_popen.return_value = mock.Mock(stdout=SYSBENCH_OUTPUT) + mock_popen.return_value = mock.Mock( + stdout=SYSBENCH_OUTPUT.splitlines()) hw_data = [] mem.run_sysbench_memory_forked(hw_data, 10, '1K', 2) self.assertEqual([('cpu', 'logical', 'forked_bandwidth_1K', '382')], hw_data) - def test_run_sysbench_memory_threaded(self, mock_popen, mock_cpu_socket, - mock_get_memory): + def test_run_sysbench_memory_forked_bytes(self, mock_popen, + mock_cpu_socket, + mock_get_memory): + mock_get_memory.return_value = 123456789012 + mock_popen.return_value = mock.Mock( + stdout=SYSBENCH_OUTPUT.encode().splitlines()) + + hw_data = [] + mem.run_sysbench_memory_forked(hw_data, 10, '1K', 2) + self.assertEqual([('cpu', 'logical', 'forked_bandwidth_1K', '382')], + hw_data) + + def test_run_sysbench_memory_threaded_text(self, mock_popen, + mock_cpu_socket, + mock_get_memory): + mock_get_memory.return_value = 123456789012 + mock_popen.return_value = mock.Mock( + stdout=SYSBENCH_OUTPUT.splitlines()) + + hw_data = [] + mem.run_sysbench_memory_threaded(hw_data, 10, '1K', 2) + self.assertEqual([('cpu', 'logical', 'threaded_bandwidth_1K', '382')], + hw_data) + + def test_run_sysbench_memory_threaded_bytes(self, mock_popen, + mock_cpu_socket, + mock_get_memory): mock_get_memory.return_value = 123456789012 - mock_popen.return_value = mock.Mock(stdout=SYSBENCH_OUTPUT) + mock_popen.return_value = mock.Mock( + stdout=SYSBENCH_OUTPUT.encode().splitlines()) hw_data = [] mem.run_sysbench_memory_threaded(hw_data, 10, '1K', 2)
Mem benchmark fails with Python 3 MEM benchmarking fails with error "a bytes-like object is required, not 'str'" ``` hardware-detect --benchmark mem ... Memory Performance: 8 logical CPU to test (ETA: 350 seconds) Benchmarking memory @1K from CPU 0 for 5 seconds (1 threads) Traceback (most recent call last): File "/usr/bin/hardware-detect", line 10, in <module> sys.exit(main()) File "/usr/lib/python3.6/site-packages/hardware/detect.py", line 981, in main bm_mem.mem_perf(hrdw) File "/usr/lib/python3.6/site-packages/hardware/benchmark/mem.py", line 152, in mem_perf block_size, 1, cpu_nb) File "/usr/lib/python3.6/site-packages/hardware/benchmark/mem.py", line 91, in run_sysbench_memory_threaded if "transferred" in line: TypeError: a bytes-like object is required, not 'str' ``` Original report: https://bugzilla.redhat.com/show_bug.cgi?id=1753653
0.0
210ba54bd3f18a1eb65a54e434b304f51b6b2a97
[ "hardware/tests/test_benchmark_mem.py::TestBenchmarkMem::test_run_sysbench_memory_forked_bytes", "hardware/tests/test_benchmark_mem.py::TestBenchmarkMem::test_mem_perf_bytes", "hardware/tests/test_benchmark_mem.py::TestBenchmarkMem::test_run_sysbench_memory_threaded_bytes" ]
[ "hardware/tests/test_benchmark_mem.py::TestBenchmarkMem::test_check_mem_size", "hardware/tests/test_benchmark_mem.py::TestBenchmarkMem::test_run_sysbench_memory_threaded_text", "hardware/tests/test_benchmark_mem.py::TestBenchmarkMem::test_mem_perf_text", "hardware/tests/test_benchmark_mem.py::TestBenchmarkMem::test_run_sysbench_memory_forked_text" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-10-02 11:22:35+00:00
apache-2.0
5,200
redhat-cip__hardware-189
diff --git a/hardware/benchmark/disk.py b/hardware/benchmark/disk.py index 6392f0c5..10de669b 100644 --- a/hardware/benchmark/disk.py +++ b/hardware/benchmark/disk.py @@ -18,8 +18,8 @@ Benchmark Disk functions. """ +import json import os -import re import subprocess import sys @@ -70,7 +70,7 @@ def run_fio(hw_lst, disks_list, mode, io_size, time, rampup_time): for myfile in filelist: os.remove(myfile) fio = ("fio --ioengine=libaio --invalidate=1 --ramp_time=%d --iodepth=32 " - "--runtime=%d --time_based --direct=1 " + "--runtime=%d --time_based --direct=1 --output-format=json " "--bs=%s --rw=%s" % (rampup_time, time, io_size, mode)) global_disk_list = '' @@ -87,54 +87,21 @@ def run_fio(hw_lst, disks_list, mode, io_size, time, rampup_time): 'Benchmarking storage %s for %s seconds in ' '%s mode with blocksize=%s\n' % (global_disk_list, time, mode, io_size)) - fio_cmd = subprocess.Popen(fio, - shell=True, stdout=subprocess.PIPE) - current_disk = '' - for line in fio_cmd.stdout: - line = line.decode(errors='ignore') - if ('MYJOB-' in line) and ('pid=' in line): - # MYJOB-sda: (groupid=0, jobs=1): err= 0: pid=23652: Mon Sep 9 - # 16:21:42 2013 - current_disk = re.search(r"MYJOB-(.*): \(groupid", line).group(1) - continue - if ("read : io=" in line) or ("write: io=" in line): - # read : io=169756KB, bw=16947KB/s, iops=4230, runt= 10017msec - if len(disks_list) > 1: - mode_str = "simultaneous_%s_%s" % (mode, io_size) - else: - mode_str = "standalone_%s_%s" % (mode, io_size) - - try: - perf = re.search('bw=(.*?B/s),', line).group(1) - except Exception: - sys.stderr.write('Failed at detecting ' - 'bwps pattern with %s\n' % line) - else: - multiply = 1 - divide = 1 - if "MB/s" in perf: - multiply = 1024 - elif "KB/s" in perf: - multiply = 1 - elif "B/s" in perf: - divide = 1024 - try: - iperf = perf.replace( - 'KB/s', '').replace('MB/s', '').replace('B/s', '') - except Exception: - True - - value = str(int(float(float(iperf) * multiply / divide))) + fio_cmd = subprocess.check_output(fio, shell=True) + data = json.loads(fio_cmd) + for job in data['jobs']: + current_disk = job['jobname'].replace("MYJOB-", "") + if len(disks_list) > 1: + mode_str = "simultaneous_%s_%s" % (mode, io_size) + else: + mode_str = "standalone_%s_%s" % (mode, io_size) + + for item in ['read', 'write']: + if job[item]['runtime'] > 0: hw_lst.append(('disk', current_disk, mode_str + '_KBps', - value)) - - try: - value = re.search('iops=(.*),', line).group(1).strip(' ') + str(job[item]['bw']))) hw_lst.append(('disk', current_disk, mode_str + '_IOps', - value)) - except Exception: - sys.stderr.write('Failed at detecting iops ' - 'pattern with %s\n' % line) + str(job[item]['iops']))) def disk_perf(hw_lst, destructive=False, running_time=10):
redhat-cip/hardware
e770ff2c286742bd239c8e81f044168a4fe5d66a
diff --git a/hardware/tests/test_benchmark_disk.py b/hardware/tests/test_benchmark_disk.py index 7186f6c1..5c6fde81 100644 --- a/hardware/tests/test_benchmark_disk.py +++ b/hardware/tests/test_benchmark_disk.py @@ -22,8 +22,31 @@ from unittest import mock from hardware.benchmark import disk -FIO_OUTPUT_READ = """MYJOB-fake-disk: (groupid=0, jobs=1): err= 0: pid=5427: - read : io=123456KB, bw=123456KB/s, iops=123, runt= 10304msec""" +FIO_OUTPUT_READ = """{ + "jobs": [ + { + "jobname": "MYJOB-fake-disk", + "groupid": 0, + "error": 0, + "read": { + "io_bytes": 126418944, + "io_kbytes": 123456, + "bw_bytes": 126418944, + "bw": 123456, + "iops": 123, + "runtime": 10304 + }, + "write": { + "io_bytes": 0, + "io_kbytes": 0, + "bw_bytes": 0, + "bw": 0, + "iops": 0, + "runtime": 0 + } + } + ] + }""" DISK_PERF_EXPECTED = [ ('disk', 'fake-disk', 'size', '10'), @@ -43,7 +66,7 @@ DISK_PERF_EXPECTED = [ ] [email protected](subprocess, 'Popen') [email protected](subprocess, 'check_output') class TestBenchmarkDisk(unittest.TestCase): def setUp(self): @@ -51,19 +74,17 @@ class TestBenchmarkDisk(unittest.TestCase): self.hw_data = [('disk', 'fake-disk', 'size', '10'), ('disk', 'fake-disk2', 'size', '15')] - def test_disk_perf_bytes(self, mock_popen): - mock_popen.return_value = mock.Mock( - stdout=FIO_OUTPUT_READ.encode().splitlines()) + def test_disk_perf_bytes(self, mock_check_output): + mock_check_output.return_value = FIO_OUTPUT_READ.encode('utf-8') disk.disk_perf(self.hw_data) self.assertEqual(sorted(DISK_PERF_EXPECTED), sorted(self.hw_data)) - def test_get_disks_name(self, mock_popen): + def test_get_disks_name(self, mock_check_output): result = disk.get_disks_name(self.hw_data) self.assertEqual(sorted(['fake-disk', 'fake-disk2']), sorted(result)) - def test_run_fio(self, mock_popen): - mock_popen.return_value = mock.Mock( - stdout=FIO_OUTPUT_READ.encode().splitlines()) + def test_run_fio(self, mock_check_output): + mock_check_output.return_value = FIO_OUTPUT_READ.encode('utf-8') hw_data = [] disks_list = ['fake-disk', 'fake-disk2'] disk.run_fio(hw_data, disks_list, "read", 123, 10, 5)
hardware-detect disk benchmark fails to parse modern fio output The output of `fio` parsed by the disk benchmark has changed around 2017: https://github.com/axboe/fio/commit/d694a6a7c02f577b2bb5d0ad24331b775acf6869 The disk benchmark code in `hardware-detect` fails to parse its output.
0.0
e770ff2c286742bd239c8e81f044168a4fe5d66a
[ "hardware/tests/test_benchmark_disk.py::TestBenchmarkDisk::test_disk_perf_bytes", "hardware/tests/test_benchmark_disk.py::TestBenchmarkDisk::test_run_fio" ]
[ "hardware/tests/test_benchmark_disk.py::TestBenchmarkDisk::test_get_disks_name" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-10-10 15:24:03+00:00
apache-2.0
5,201
redis__redis-py-2583
diff --git a/redis/connection.py b/redis/connection.py index 2461482..d35980c 100644 --- a/redis/connection.py +++ b/redis/connection.py @@ -1153,6 +1153,7 @@ class UnixDomainSocketConnection(Connection): retry=None, redis_connect_func=None, credential_provider: Optional[CredentialProvider] = None, + command_packer=None, ): """ Initialize a new UnixDomainSocketConnection. @@ -1202,6 +1203,7 @@ class UnixDomainSocketConnection(Connection): self.set_parser(parser_class) self._connect_callbacks = [] self._buffer_cutoff = 6000 + self._command_packer = self._construct_command_packer(command_packer) def repr_pieces(self): pieces = [("path", self.path), ("db", self.db)]
redis/redis-py
5cb5712d283fa8fb300abc9d71a61c1a81de5643
diff --git a/tests/test_connection.py b/tests/test_connection.py index e0b53cd..25b4118 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -7,7 +7,13 @@ import pytest import redis from redis.backoff import NoBackoff -from redis.connection import Connection, HiredisParser, PythonParser +from redis.connection import ( + Connection, + HiredisParser, + PythonParser, + SSLConnection, + UnixDomainSocketConnection, +) from redis.exceptions import ConnectionError, InvalidResponse, TimeoutError from redis.retry import Retry from redis.utils import HIREDIS_AVAILABLE @@ -163,3 +169,39 @@ def test_connection_parse_response_resume(r: redis.Redis, parser_class): pytest.fail("didn't receive a response") assert response assert i > 0 + + [email protected] [email protected]( + "Class", + [ + Connection, + SSLConnection, + UnixDomainSocketConnection, + ], +) +def test_pack_command(Class): + """ + This test verifies that the pack_command works + on all supported connections. #2581 + """ + cmd = ( + "HSET", + "foo", + "key", + "value1", + b"key_b", + b"bytes str", + b"key_i", + 67, + "key_f", + 3.14159265359, + ) + expected = ( + b"*10\r\n$4\r\nHSET\r\n$3\r\nfoo\r\n$3\r\nkey\r\n$6\r\nvalue1\r\n" + b"$5\r\nkey_b\r\n$9\r\nbytes str\r\n$5\r\nkey_i\r\n$2\r\n67\r\n$5" + b"\r\nkey_f\r\n$13\r\n3.14159265359\r\n" + ) + + actual = Class().pack_command(*cmd)[0] + assert actual == expected, f"actual = {actual}, expected = {expected}"
'UnixDomainSocketConnection' object has no attribute '_command_packer' **Version**: v4.5.0 **Platform**: Debian Bullseye using Python v3.9.2 **Description**: The following code which used to work on up to and including v4.4.2 now crashes with the stack trace below on v4.5.0. ```python redis_conn = redis.Redis( unix_socket_path="/var/run/redis/redis-server.sock", decode_responses=True) redis_conn.ping() ``` ``` Traceback (most recent call last): File "<redacted>", line 142, in main redis_conn.ping() File "/usr/local/lib/python3.9/dist-packages/redis/commands/core.py", line 1194, in ping return self.execute_command("PING", **kwargs) File "/usr/local/lib/python3.9/dist-packages/redis/client.py", line 1258, in execute_command return conn.retry.call_with_retry( File "/usr/local/lib/python3.9/dist-packages/redis/retry.py", line 46, in call_with_retry return do() File "/usr/local/lib/python3.9/dist-packages/redis/client.py", line 1259, in <lambda> lambda: self._send_command_parse_response( File "/usr/local/lib/python3.9/dist-packages/redis/client.py", line 1234, in _send_command_parse_response conn.send_command(*args) File "/usr/local/lib/python3.9/dist-packages/redis/connection.py", line 916, in send_command self._command_packer.pack(*args), AttributeError: 'UnixDomainSocketConnection' object has no attribute '_command_packer' ```
0.0
5cb5712d283fa8fb300abc9d71a61c1a81de5643
[ "tests/test_connection.py::test_pack_command[UnixDomainSocketConnection]" ]
[ "tests/test_connection.py::TestConnection::test_disconnect", "tests/test_connection.py::TestConnection::test_disconnect__shutdown_OSError", "tests/test_connection.py::TestConnection::test_disconnect__close_OSError", "tests/test_connection.py::TestConnection::test_connect_without_retry_on_os_error", "tests/test_connection.py::TestConnection::test_connect_timeout_error_without_retry", "tests/test_connection.py::test_pack_command[Connection]", "tests/test_connection.py::test_pack_command[SSLConnection]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-02-08 04:03:44+00:00
mit
5,202
redis__redis-py-2584
diff --git a/README.md b/README.md index c02483f..6b53b42 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ For faster performance, install redis with hiredis support, this provides a comp By default, if hiredis >= 1.0 is available, redis-py will attempt to use it for response parsing. ``` bash -$ pip install redis[hiredis] +$ pip install "redis[hiredis]" ``` Looking for a high-level library to handle object mapping? See [redis-om-python](https://github.com/redis/redis-om-python)! diff --git a/redis/commands/core.py b/redis/commands/core.py index b07f12d..28dab81 100644 --- a/redis/commands/core.py +++ b/redis/commands/core.py @@ -2667,7 +2667,11 @@ class ListCommands(CommandsProtocol): """ return self.execute_command("LLEN", name) - def lpop(self, name: str, count: Optional[int] = None) -> Union[str, List, None]: + def lpop( + self, + name: str, + count: Optional[int] = None, + ) -> Union[Awaitable[Union[str, List, None]], Union[str, List, None]]: """ Removes and returns the first elements of the list ``name``. @@ -2744,7 +2748,11 @@ class ListCommands(CommandsProtocol): """ return self.execute_command("LTRIM", name, start, end) - def rpop(self, name: str, count: Optional[int] = None) -> Union[str, List, None]: + def rpop( + self, + name: str, + count: Optional[int] = None, + ) -> Union[Awaitable[Union[str, List, None]], Union[str, List, None]]: """ Removes and returns the last elements of the list ``name``. diff --git a/redis/connection.py b/redis/connection.py index 2461482..d35980c 100644 --- a/redis/connection.py +++ b/redis/connection.py @@ -1153,6 +1153,7 @@ class UnixDomainSocketConnection(Connection): retry=None, redis_connect_func=None, credential_provider: Optional[CredentialProvider] = None, + command_packer=None, ): """ Initialize a new UnixDomainSocketConnection. @@ -1202,6 +1203,7 @@ class UnixDomainSocketConnection(Connection): self.set_parser(parser_class) self._connect_callbacks = [] self._buffer_cutoff = 6000 + self._command_packer = self._construct_command_packer(command_packer) def repr_pieces(self): pieces = [("path", self.path), ("db", self.db)] diff --git a/setup.py b/setup.py index 022a27e..060e9da 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ setup( long_description_content_type="text/markdown", keywords=["Redis", "key-value store", "database"], license="MIT", - version="4.5.0", + version="4.5.1", packages=find_packages( include=[ "redis",
redis/redis-py
5cb5712d283fa8fb300abc9d71a61c1a81de5643
diff --git a/tests/test_connection.py b/tests/test_connection.py index e0b53cd..25b4118 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -7,7 +7,13 @@ import pytest import redis from redis.backoff import NoBackoff -from redis.connection import Connection, HiredisParser, PythonParser +from redis.connection import ( + Connection, + HiredisParser, + PythonParser, + SSLConnection, + UnixDomainSocketConnection, +) from redis.exceptions import ConnectionError, InvalidResponse, TimeoutError from redis.retry import Retry from redis.utils import HIREDIS_AVAILABLE @@ -163,3 +169,39 @@ def test_connection_parse_response_resume(r: redis.Redis, parser_class): pytest.fail("didn't receive a response") assert response assert i > 0 + + [email protected] [email protected]( + "Class", + [ + Connection, + SSLConnection, + UnixDomainSocketConnection, + ], +) +def test_pack_command(Class): + """ + This test verifies that the pack_command works + on all supported connections. #2581 + """ + cmd = ( + "HSET", + "foo", + "key", + "value1", + b"key_b", + b"bytes str", + b"key_i", + 67, + "key_f", + 3.14159265359, + ) + expected = ( + b"*10\r\n$4\r\nHSET\r\n$3\r\nfoo\r\n$3\r\nkey\r\n$6\r\nvalue1\r\n" + b"$5\r\nkey_b\r\n$9\r\nbytes str\r\n$5\r\nkey_i\r\n$2\r\n67\r\n$5" + b"\r\nkey_f\r\n$13\r\n3.14159265359\r\n" + ) + + actual = Class().pack_command(*cmd)[0] + assert actual == expected, f"actual = {actual}, expected = {expected}"
Unable to install with hiredis option pip install redis[hiredis] return "no matches found: redis[hiredis]" python version 3.8 pip install redis and pip install hiredis work
0.0
5cb5712d283fa8fb300abc9d71a61c1a81de5643
[ "tests/test_connection.py::test_pack_command[UnixDomainSocketConnection]" ]
[ "tests/test_connection.py::TestConnection::test_disconnect", "tests/test_connection.py::TestConnection::test_disconnect__shutdown_OSError", "tests/test_connection.py::TestConnection::test_disconnect__close_OSError", "tests/test_connection.py::TestConnection::test_connect_without_retry_on_os_error", "tests/test_connection.py::TestConnection::test_connect_timeout_error_without_retry", "tests/test_connection.py::test_pack_command[Connection]", "tests/test_connection.py::test_pack_command[SSLConnection]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-02-08 08:26:10+00:00
mit
5,203
redis__redis-py-2752
diff --git a/CHANGES b/CHANGES index 3865ed1..ea171f6 100644 --- a/CHANGES +++ b/CHANGES @@ -1,3 +1,4 @@ + * Revert #2104, #2673, add `disconnect_on_error` option to `read_response()` (issues #2506, #2624) * Add `address_remap` parameter to `RedisCluster` * Fix incorrect usage of once flag in async Sentinel * asyncio: Fix memory leak caused by hiredis (#2693) diff --git a/redis/asyncio/client.py b/redis/asyncio/client.py index 3e6626a..7479b74 100644 --- a/redis/asyncio/client.py +++ b/redis/asyncio/client.py @@ -139,8 +139,12 @@ class Redis( arguments always win. """ + single_connection_client = kwargs.pop("single_connection_client", False) connection_pool = ConnectionPool.from_url(url, **kwargs) - return cls(connection_pool=connection_pool) + return cls( + connection_pool=connection_pool, + single_connection_client=single_connection_client, + ) def __init__( self, @@ -455,7 +459,7 @@ class Redis( _DEL_MESSAGE = "Unclosed Redis client" def __del__(self, _warnings: Any = warnings) -> None: - if self.connection is not None: + if hasattr(self, "connection") and (self.connection is not None): _warnings.warn( f"Unclosed client session {self!r}", ResourceWarning, source=self ) @@ -500,23 +504,6 @@ class Redis( ): raise error - async def _try_send_command_parse_response(self, conn, *args, **options): - try: - return await conn.retry.call_with_retry( - lambda: self._send_command_parse_response( - conn, args[0], *args, **options - ), - lambda error: self._disconnect_raise(conn, error), - ) - except asyncio.CancelledError: - await conn.disconnect(nowait=True) - raise - finally: - if self.single_connection_client: - self._single_conn_lock.release() - if not self.connection: - await self.connection_pool.release(conn) - # COMMAND EXECUTION AND PROTOCOL PARSING async def execute_command(self, *args, **options): """Execute a command and return a parsed response""" @@ -527,10 +514,18 @@ class Redis( if self.single_connection_client: await self._single_conn_lock.acquire() - - return await asyncio.shield( - self._try_send_command_parse_response(conn, *args, **options) - ) + try: + return await conn.retry.call_with_retry( + lambda: self._send_command_parse_response( + conn, command_name, *args, **options + ), + lambda error: self._disconnect_raise(conn, error), + ) + finally: + if self.single_connection_client: + self._single_conn_lock.release() + if not self.connection: + await pool.release(conn) async def parse_response( self, connection: Connection, command_name: Union[str, bytes], **options @@ -774,18 +769,10 @@ class PubSub: is not a TimeoutError. Otherwise, try to reconnect """ await conn.disconnect() - if not (conn.retry_on_timeout and isinstance(error, TimeoutError)): raise error await conn.connect() - async def _try_execute(self, conn, command, *arg, **kwargs): - try: - return await command(*arg, **kwargs) - except asyncio.CancelledError: - await conn.disconnect() - raise - async def _execute(self, conn, command, *args, **kwargs): """ Connect manually upon disconnection. If the Redis server is down, @@ -794,11 +781,9 @@ class PubSub: called by the # connection to resubscribe us to any channels and patterns we were previously listening to """ - return await asyncio.shield( - conn.retry.call_with_retry( - lambda: self._try_execute(conn, command, *args, **kwargs), - lambda error: self._disconnect_raise_connect(conn, error), - ) + return await conn.retry.call_with_retry( + lambda: command(*args, **kwargs), + lambda error: self._disconnect_raise_connect(conn, error), ) async def parse_response(self, block: bool = True, timeout: float = 0): @@ -816,7 +801,9 @@ class PubSub: await conn.connect() read_timeout = None if block else timeout - response = await self._execute(conn, conn.read_response, timeout=read_timeout) + response = await self._execute( + conn, conn.read_response, timeout=read_timeout, disconnect_on_error=False + ) if conn.health_check_interval and response == self.health_check_response: # ignore the health check message as user might not expect it @@ -1200,18 +1187,6 @@ class Pipeline(Redis): # lgtm [py/init-calls-subclass] await self.reset() raise - async def _try_send_command_parse_response(self, conn, *args, **options): - try: - return await conn.retry.call_with_retry( - lambda: self._send_command_parse_response( - conn, args[0], *args, **options - ), - lambda error: self._disconnect_reset_raise(conn, error), - ) - except asyncio.CancelledError: - await conn.disconnect() - raise - async def immediate_execute_command(self, *args, **options): """ Execute a command immediately, but don't auto-retry on a @@ -1227,8 +1202,12 @@ class Pipeline(Redis): # lgtm [py/init-calls-subclass] command_name, self.shard_hint ) self.connection = conn - return await asyncio.shield( - self._try_send_command_parse_response(conn, *args, **options) + + return await conn.retry.call_with_retry( + lambda: self._send_command_parse_response( + conn, command_name, *args, **options + ), + lambda error: self._disconnect_reset_raise(conn, error), ) def pipeline_execute_command(self, *args, **options): @@ -1396,19 +1375,6 @@ class Pipeline(Redis): # lgtm [py/init-calls-subclass] await self.reset() raise - async def _try_execute(self, conn, execute, stack, raise_on_error): - try: - return await conn.retry.call_with_retry( - lambda: execute(conn, stack, raise_on_error), - lambda error: self._disconnect_raise_reset(conn, error), - ) - except asyncio.CancelledError: - # not supposed to be possible, yet here we are - await conn.disconnect(nowait=True) - raise - finally: - await self.reset() - async def execute(self, raise_on_error: bool = True): """Execute all the commands in the current pipeline""" stack = self.command_stack @@ -1430,11 +1396,10 @@ class Pipeline(Redis): # lgtm [py/init-calls-subclass] conn = cast(Connection, conn) try: - return await asyncio.shield( - self._try_execute(conn, execute, stack, raise_on_error) + return await conn.retry.call_with_retry( + lambda: execute(conn, stack, raise_on_error), + lambda error: self._disconnect_raise_reset(conn, error), ) - except RuntimeError: - await self.reset() finally: await self.reset() diff --git a/redis/asyncio/cluster.py b/redis/asyncio/cluster.py index eb5f4db..929d3e4 100644 --- a/redis/asyncio/cluster.py +++ b/redis/asyncio/cluster.py @@ -1016,33 +1016,12 @@ class ClusterNode: await connection.send_packed_command(connection.pack_command(*args), False) # Read response - return await asyncio.shield( - self._parse_and_release(connection, args[0], **kwargs) - ) - - async def _parse_and_release(self, connection, *args, **kwargs): try: - return await self.parse_response(connection, *args, **kwargs) - except asyncio.CancelledError: - # should not be possible - await connection.disconnect(nowait=True) - raise + return await self.parse_response(connection, args[0], **kwargs) finally: + # Release connection self._free.append(connection) - async def _try_parse_response(self, cmd, connection, ret): - try: - cmd.result = await asyncio.shield( - self.parse_response(connection, cmd.args[0], **cmd.kwargs) - ) - except asyncio.CancelledError: - await connection.disconnect(nowait=True) - raise - except Exception as e: - cmd.result = e - ret = True - return ret - async def execute_pipeline(self, commands: List["PipelineCommand"]) -> bool: # Acquire connection connection = self.acquire_connection() @@ -1055,7 +1034,13 @@ class ClusterNode: # Read responses ret = False for cmd in commands: - ret = await asyncio.shield(self._try_parse_response(cmd, connection, ret)) + try: + cmd.result = await self.parse_response( + connection, cmd.args[0], **cmd.kwargs + ) + except Exception as e: + cmd.result = e + ret = True # Release connection self._free.append(connection) diff --git a/redis/asyncio/connection.py b/redis/asyncio/connection.py index 59f75aa..462673f 100644 --- a/redis/asyncio/connection.py +++ b/redis/asyncio/connection.py @@ -804,7 +804,11 @@ class Connection: raise ConnectionError( f"Error {err_no} while writing to socket. {errmsg}." ) from e - except Exception: + except BaseException: + # BaseExceptions can be raised when a socket send operation is not + # finished, e.g. due to a timeout. Ideally, a caller could then re-try + # to send un-sent data. However, the send_packed_command() API + # does not support it so there is no point in keeping the connection open. await self.disconnect(nowait=True) raise @@ -828,6 +832,8 @@ class Connection: self, disable_decoding: bool = False, timeout: Optional[float] = None, + *, + disconnect_on_error: bool = True, ): """Read the response from a previously sent command""" read_timeout = timeout if timeout is not None else self.socket_timeout @@ -843,22 +849,24 @@ class Connection: ) except asyncio.TimeoutError: if timeout is not None: - # user requested timeout, return None + # user requested timeout, return None. Operation can be retried return None # it was a self.socket_timeout error. - await self.disconnect(nowait=True) + if disconnect_on_error: + await self.disconnect(nowait=True) raise TimeoutError(f"Timeout reading from {self.host}:{self.port}") except OSError as e: - await self.disconnect(nowait=True) + if disconnect_on_error: + await self.disconnect(nowait=True) raise ConnectionError( f"Error while reading from {self.host}:{self.port} : {e.args}" ) - except asyncio.CancelledError: - # need this check for 3.7, where CancelledError - # is subclass of Exception, not BaseException - raise - except Exception: - await self.disconnect(nowait=True) + except BaseException: + # Also by default close in case of BaseException. A lot of code + # relies on this behaviour when doing Command/Response pairs. + # See #1128. + if disconnect_on_error: + await self.disconnect(nowait=True) raise if self.health_check_interval: diff --git a/redis/client.py b/redis/client.py index 79a7bff..9fd5b7c 100755 --- a/redis/client.py +++ b/redis/client.py @@ -420,9 +420,13 @@ def parse_slowlog_get(response, **options): # an O(N) complexity) instead of the command. if isinstance(item[3], list): result["command"] = space.join(item[3]) + result["client_address"] = item[4] + result["client_name"] = item[5] else: result["complexity"] = item[3] result["command"] = space.join(item[4]) + result["client_address"] = item[5] + result["client_name"] = item[6] return result return [parse_item(item) for item in response] @@ -902,8 +906,12 @@ class Redis(AbstractRedis, RedisModuleCommands, CoreCommands, SentinelCommands): arguments always win. """ + single_connection_client = kwargs.pop("single_connection_client", False) connection_pool = ConnectionPool.from_url(url, **kwargs) - return cls(connection_pool=connection_pool) + return cls( + connection_pool=connection_pool, + single_connection_client=single_connection_client, + ) def __init__( self, @@ -1529,7 +1537,7 @@ class PubSub: return None else: conn.connect() - return conn.read_response() + return conn.read_response(disconnect_on_error=False) response = self._execute(conn, try_read) diff --git a/redis/commands/core.py b/redis/commands/core.py index d67291b..1a4acb2 100644 --- a/redis/commands/core.py +++ b/redis/commands/core.py @@ -761,6 +761,17 @@ class ManagementCommands(CommandsProtocol): """ return self.execute_command("CLIENT NO-EVICT", mode) + def client_no_touch(self, mode: str) -> Union[Awaitable[str], str]: + """ + # The command controls whether commands sent by the client will alter + # the LRU/LFU of the keys they access. + # When turned on, the current client will not change LFU/LRU stats, + # unless it sends the TOUCH command. + + For more information see https://redis.io/commands/client-no-touch + """ + return self.execute_command("CLIENT NO-TOUCH", mode) + def command(self, **kwargs): """ Returns dict reply of details about all Redis commands. diff --git a/redis/connection.py b/redis/connection.py index 8b2389c..5af8928 100644 --- a/redis/connection.py +++ b/redis/connection.py @@ -834,7 +834,11 @@ class AbstractConnection: errno = e.args[0] errmsg = e.args[1] raise ConnectionError(f"Error {errno} while writing to socket. {errmsg}.") - except Exception: + except BaseException: + # BaseExceptions can be raised when a socket send operation is not + # finished, e.g. due to a timeout. Ideally, a caller could then re-try + # to send un-sent data. However, the send_packed_command() API + # does not support it so there is no point in keeping the connection open. self.disconnect() raise @@ -859,7 +863,9 @@ class AbstractConnection: self.disconnect() raise ConnectionError(f"Error while reading from {host_error}: {e.args}") - def read_response(self, disable_decoding=False): + def read_response( + self, disable_decoding=False, *, disconnect_on_error: bool = True + ): """Read the response from a previously sent command""" host_error = self._host_error() @@ -867,15 +873,21 @@ class AbstractConnection: try: response = self._parser.read_response(disable_decoding=disable_decoding) except socket.timeout: - self.disconnect() + if disconnect_on_error: + self.disconnect() raise TimeoutError(f"Timeout reading from {host_error}") except OSError as e: - self.disconnect() + if disconnect_on_error: + self.disconnect() raise ConnectionError( f"Error while reading from {host_error}" f" : {e.args}" ) - except Exception: - self.disconnect() + except BaseException: + # Also by default close in case of BaseException. A lot of code + # relies on this behaviour when doing Command/Response pairs. + # See #1128. + if disconnect_on_error: + self.disconnect() raise if self.health_check_interval:
redis/redis-py
cfdcfd87acdc10bedba6230b0cbe7dcf44b4652a
diff --git a/tests/test_asyncio/test_commands.py b/tests/test_asyncio/test_commands.py index 409934c..955b9d4 100644 --- a/tests/test_asyncio/test_commands.py +++ b/tests/test_asyncio/test_commands.py @@ -1,9 +1,11 @@ """ Tests async overrides of commands from their mixins """ +import asyncio import binascii import datetime import re +import sys from string import ascii_letters import pytest @@ -18,6 +20,11 @@ from tests.conftest import ( skip_unless_arch_bits, ) +if sys.version_info >= (3, 11, 3): + from asyncio import timeout as async_timeout +else: + from async_timeout import timeout as async_timeout + REDIS_6_VERSION = "5.9.0" @@ -446,6 +453,14 @@ class TestRedisCommands: with pytest.raises(exceptions.RedisError): await r.client_pause(timeout="not an integer") + @skip_if_server_version_lt("7.2.0") + @pytest.mark.onlynoncluster + async def test_client_no_touch(self, r: redis.Redis): + assert await r.client_no_touch("ON") == b"OK" + assert await r.client_no_touch("OFF") == b"OK" + with pytest.raises(TypeError): + await r.client_no_touch() + async def test_config_get(self, r: redis.Redis): data = await r.config_get() assert "maxmemory" in data @@ -3008,6 +3023,37 @@ class TestRedisCommands: for x in await r.module_list(): assert isinstance(x, dict) + @pytest.mark.onlynoncluster + async def test_interrupted_command(self, r: redis.Redis): + """ + Regression test for issue #1128: An Un-handled BaseException + will leave the socket with un-read response to a previous + command. + """ + ready = asyncio.Event() + + async def helper(): + with pytest.raises(asyncio.CancelledError): + # blocking pop + ready.set() + await r.brpop(["nonexist"]) + # If the following is not done, further Timout operations will fail, + # because the timeout won't catch its Cancelled Error if the task + # has a pending cancel. Python documentation probably should reflect this. + if sys.version_info >= (3, 11): + asyncio.current_task().uncancel() + # if all is well, we can continue. The following should not hang. + await r.set("status", "down") + + task = asyncio.create_task(helper()) + await ready.wait() + await asyncio.sleep(0.01) + # the task is now sleeping, lets send it an exception + task.cancel() + # If all is well, the task should finish right away, otherwise fail with Timeout + async with async_timeout(0.1): + await task + @pytest.mark.onlynoncluster class TestBinarySave: diff --git a/tests/test_asyncio/test_connection.py b/tests/test_asyncio/test_connection.py index e2d77fc..158b854 100644 --- a/tests/test_asyncio/test_connection.py +++ b/tests/test_asyncio/test_connection.py @@ -184,7 +184,7 @@ async def test_connection_parse_response_resume(r: redis.Redis): conn._parser._stream = MockStream(message, interrupt_every=2) for i in range(100): try: - response = await conn.read_response() + response = await conn.read_response(disconnect_on_error=False) break except MockStream.TestError: pass @@ -271,3 +271,9 @@ async def test_connection_disconect_race(parser_class): vals = await asyncio.gather(do_read(), do_close()) assert vals == [b"Hello, World!", None] + + [email protected] +def test_create_single_connection_client_from_url(): + client = Redis.from_url("redis://localhost:6379/0?", single_connection_client=True) + assert client.single_connection_client is True diff --git a/tests/test_asyncio/test_cwe_404.py b/tests/test_asyncio/test_cwe_404.py index d3a0666..21f2ddd 100644 --- a/tests/test_asyncio/test_cwe_404.py +++ b/tests/test_asyncio/test_cwe_404.py @@ -128,7 +128,6 @@ async def test_standalone(delay, master_host): assert await r.get("foo") == b"foo" [email protected](reason="cancel does not cause disconnect") @pytest.mark.onlynoncluster @pytest.mark.parametrize("delay", argvalues=[0.05, 0.5, 1, 2]) async def test_standalone_pipeline(delay, master_host): diff --git a/tests/test_commands.py b/tests/test_commands.py index 2b769be..c71e347 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -1,9 +1,12 @@ import binascii import datetime import re +import threading import time +from asyncio import CancelledError from string import ascii_letters from unittest import mock +from unittest.mock import patch import pytest @@ -693,6 +696,14 @@ class TestRedisCommands: with pytest.raises(TypeError): r.client_no_evict() + @pytest.mark.onlynoncluster + @skip_if_server_version_lt("7.2.0") + def test_client_no_touch(self, r): + assert r.client_no_touch("ON") == b"OK" + assert r.client_no_touch("OFF") == b"OK" + with pytest.raises(TypeError): + r.client_no_touch() + @pytest.mark.onlynoncluster @skip_if_server_version_lt("3.2.0") def test_client_reply(self, r, r_timeout): @@ -861,6 +872,8 @@ class TestRedisCommands: # make sure other attributes are typed correctly assert isinstance(slowlog[0]["start_time"], int) assert isinstance(slowlog[0]["duration"], int) + assert isinstance(slowlog[0]["client_address"], bytes) + assert isinstance(slowlog[0]["client_name"], bytes) # Mock result if we didn't get slowlog complexity info. if "complexity" not in slowlog[0]: @@ -4741,6 +4754,38 @@ class TestRedisCommands: res = r2.psync(r2.client_id(), 1) assert b"FULLRESYNC" in res + @pytest.mark.onlynoncluster + def test_interrupted_command(self, r: redis.Redis): + """ + Regression test for issue #1128: An Un-handled BaseException + will leave the socket with un-read response to a previous + command. + """ + + ok = False + + def helper(): + with pytest.raises(CancelledError): + # blocking pop + with patch.object( + r.connection._parser, "read_response", side_effect=CancelledError + ): + r.brpop(["nonexist"]) + # if all is well, we can continue. + r.set("status", "down") # should not hang + nonlocal ok + ok = True + + thread = threading.Thread(target=helper) + thread.start() + thread.join(0.1) + try: + assert not thread.is_alive() + assert ok + finally: + # disconnect here so that fixture cleanup can proceed + r.connection.disconnect() + @pytest.mark.onlynoncluster class TestBinarySave: diff --git a/tests/test_connection.py b/tests/test_connection.py index 25b4118..31268a9 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -160,7 +160,7 @@ def test_connection_parse_response_resume(r: redis.Redis, parser_class): conn._parser._sock = mock_socket for i in range(100): try: - response = conn.read_response() + response = conn.read_response(disconnect_on_error=False) break except MockSocket.TestError: pass @@ -205,3 +205,11 @@ def test_pack_command(Class): actual = Class().pack_command(*cmd)[0] assert actual == expected, f"actual = {actual}, expected = {expected}" + + [email protected] +def test_create_single_connection_client_from_url(): + client = redis.Redis.from_url( + "redis://localhost:6379/0?", single_connection_client=True + ) + assert client.connection is not None
Redis.from_url() is a misnomer **Version**: 4.5.2 **Platform**: Python 3.11.2 **Description**: Redis.from_url is a convenience function, but the kwargs are passed into the ConnectionPool object and not the Redis instance. This formerly wasn't a problem, but it appears as though auto_close_connection_pool now defaults to true, so you can't reliably use Redis.from_url() in a singleton.
0.0
cfdcfd87acdc10bedba6230b0cbe7dcf44b4652a
[ "tests/test_asyncio/test_connection.py::test_create_single_connection_client_from_url" ]
[ "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_addslots[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_count_failure_reports[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_countkeysinslot[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_delslots[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_failover[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_forget[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_info[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_keyslot[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_meet[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_nodes[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_replicate[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_reset[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_saveconfig[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_setslot[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_cluster_slaves[pool-python-parser]", "tests/test_asyncio/test_commands.py::TestRedisCommands::test_readonly[pool-python-parser]", "tests/test_asyncio/test_connection.py::test_single_connection", "tests/test_asyncio/test_connection.py::test_connect_without_retry_on_os_error", "tests/test_asyncio/test_connection.py::test_connect_timeout_error_without_retry", "tests/test_asyncio/test_connection.py::test_connection_disconect_race[PythonParser]", "tests/test_connection.py::TestConnection::test_disconnect", "tests/test_connection.py::TestConnection::test_disconnect__shutdown_OSError", "tests/test_connection.py::TestConnection::test_disconnect__close_OSError", "tests/test_connection.py::TestConnection::test_connect_without_retry_on_os_error", "tests/test_connection.py::TestConnection::test_connect_timeout_error_without_retry", "tests/test_connection.py::test_pack_command[Connection]", "tests/test_connection.py::test_pack_command[SSLConnection]", "tests/test_connection.py::test_pack_command[UnixDomainSocketConnection]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-08 08:29:13+00:00
mit
5,204
redis__redis-py-2894
diff --git a/redis/asyncio/sentinel.py b/redis/asyncio/sentinel.py index 501e234..5ed9240 100644 --- a/redis/asyncio/sentinel.py +++ b/redis/asyncio/sentinel.py @@ -335,11 +335,15 @@ class Sentinel(AsyncSentinelCommands): kwargs["is_master"] = True connection_kwargs = dict(self.connection_kwargs) connection_kwargs.update(kwargs) - return redis_class( - connection_pool=connection_pool_class( - service_name, self, **connection_kwargs - ) + + connection_pool = connection_pool_class(service_name, self, **connection_kwargs) + # The Redis object "owns" the pool + auto_close_connection_pool = True + client = redis_class( + connection_pool=connection_pool, ) + client.auto_close_connection_pool = auto_close_connection_pool + return client def slave_for( self, @@ -368,8 +372,12 @@ class Sentinel(AsyncSentinelCommands): kwargs["is_master"] = False connection_kwargs = dict(self.connection_kwargs) connection_kwargs.update(kwargs) - return redis_class( - connection_pool=connection_pool_class( - service_name, self, **connection_kwargs - ) + + connection_pool = connection_pool_class(service_name, self, **connection_kwargs) + # The Redis object "owns" the pool + auto_close_connection_pool = True + client = redis_class( + connection_pool=connection_pool, ) + client.auto_close_connection_pool = auto_close_connection_pool + return client diff --git a/redis/sentinel.py b/redis/sentinel.py index 0ba179b..836e781 100644 --- a/redis/sentinel.py +++ b/redis/sentinel.py @@ -55,12 +55,17 @@ class SentinelManagedConnection(Connection): return self.retry.call_with_retry(self._connect_retry, lambda error: None) def read_response( - self, disable_decoding=False, *, disconnect_on_error: Optional[bool] = False + self, + disable_decoding=False, + *, + disconnect_on_error: Optional[bool] = False, + push_request: Optional[bool] = False, ): try: return super().read_response( disable_decoding=disable_decoding, disconnect_on_error=disconnect_on_error, + push_request=push_request, ) except ReadOnlyError: if self.connection_pool.is_master:
redis/redis-py
6968431983c20a6f874a97d92c4d11366721b83b
diff --git a/tests/test_asyncio/test_sentinel.py b/tests/test_asyncio/test_sentinel.py index 2091f2c..a2d52f1 100644 --- a/tests/test_asyncio/test_sentinel.py +++ b/tests/test_asyncio/test_sentinel.py @@ -1,4 +1,5 @@ import socket +from unittest import mock import pytest import pytest_asyncio @@ -239,3 +240,28 @@ async def test_flushconfig(cluster, sentinel): async def test_reset(cluster, sentinel): cluster.master["is_odown"] = True assert await sentinel.sentinel_reset("mymaster") + + [email protected] [email protected]("method_name", ["master_for", "slave_for"]) +async def test_auto_close_pool(cluster, sentinel, method_name): + """ + Check that the connection pool created by the sentinel client is + automatically closed + """ + + method = getattr(sentinel, method_name) + client = method("mymaster", db=9) + pool = client.connection_pool + assert client.auto_close_connection_pool is True + calls = 0 + + async def mock_disconnect(): + nonlocal calls + calls += 1 + + with mock.patch.object(pool, "disconnect", mock_disconnect): + await client.close() + + assert calls == 1 + await pool.disconnect()
SentinelManagedConnection.read_response() got an unexpected keyword argument 'push_request' Version: 3.5.3 Platform: Python 3.10 on MacOS 13.3.1 Description: [redis.client.PubSub().parse_response()](https://github.com/redis/redis-py/blob/master/redis/client.py#L777) is calling [SentinelManagedConnection.read_response()](https://github.com/redis/redis-py/blob/master/redis/sentinel.py#L57) with a non-existent `push_request` keyword argument. ``` Traceback (most recent call last): File "/usr/local/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/local/lib/python3.10/site-packages/redis/client.py", line 1108, in run pubsub.get_message(ignore_subscribe_messages=True, timeout=sleep_time) File "/usr/local/lib/python3.10/site-packages/redis/client.py", line 983, in get_message response = self.parse_response(block=(timeout is None), timeout=timeout) File "/usr/local/lib/python3.10/site-packages/redis/client.py", line 796, in parse_response response = self._execute(conn, try_read) File "/usr/local/lib/python3.10/site-packages/redis/client.py", line 772, in _execute return conn.retry.call_with_retry( File "/usr/local/lib/python3.10/site-packages/redis/retry.py", line 46, in call_with_retry return do() File "/usr/local/lib/python3.10/site-packages/redis/client.py", line 773, in <lambda> File "/usr/local/lib/python3.10/site-packages/redis/client.py", line 794, in try_read return conn.read_response(disconnect_on_error=False, push_request=True) TypeError: SentinelManagedConnection.read_response() got an unexpected keyword argument 'push_request' ``` This issue looks identical to #2754
0.0
6968431983c20a6f874a97d92c4d11366721b83b
[ "tests/test_asyncio/test_sentinel.py::test_auto_close_pool[master_for]", "tests/test_asyncio/test_sentinel.py::test_auto_close_pool[slave_for]" ]
[ "tests/test_asyncio/test_sentinel.py::test_discover_master", "tests/test_asyncio/test_sentinel.py::test_discover_master_error", "tests/test_asyncio/test_sentinel.py::test_discover_master_sentinel_down", "tests/test_asyncio/test_sentinel.py::test_discover_master_sentinel_timeout", "tests/test_asyncio/test_sentinel.py::test_master_min_other_sentinels", "tests/test_asyncio/test_sentinel.py::test_master_odown", "tests/test_asyncio/test_sentinel.py::test_master_sdown", "tests/test_asyncio/test_sentinel.py::test_discover_slaves", "tests/test_asyncio/test_sentinel.py::test_slave_for_slave_not_found_error", "tests/test_asyncio/test_sentinel.py::test_slave_round_robin", "tests/test_asyncio/test_sentinel.py::test_ckquorum", "tests/test_asyncio/test_sentinel.py::test_flushconfig", "tests/test_asyncio/test_sentinel.py::test_reset" ]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-08-16 07:05:10+00:00
mit
5,205
redis__redis-py-2982
diff --git a/redis/_parsers/resp3.py b/redis/_parsers/resp3.py index ad766a8..569e7ee 100644 --- a/redis/_parsers/resp3.py +++ b/redis/_parsers/resp3.py @@ -96,8 +96,9 @@ class _RESP3Parser(_RESPBase): pass # map response elif byte == b"%": - # we use this approach and not dict comprehension here - # because this dict comprehension fails in python 3.7 + # We cannot use a dict-comprehension to parse stream. + # Evaluation order of key:val expression in dict comprehension only + # became defined to be left-right in version 3.8 resp_dict = {} for _ in range(int(response)): key = self._read_response(disable_decoding=disable_decoding) @@ -225,12 +226,16 @@ class _AsyncRESP3Parser(_AsyncRESPBase): pass # map response elif byte == b"%": - response = { - (await self._read_response(disable_decoding=disable_decoding)): ( - await self._read_response(disable_decoding=disable_decoding) + # We cannot use a dict-comprehension to parse stream. + # Evaluation order of key:val expression in dict comprehension only + # became defined to be left-right in version 3.8 + resp_dict = {} + for _ in range(int(response)): + key = await self._read_response(disable_decoding=disable_decoding) + resp_dict[key] = await self._read_response( + disable_decoding=disable_decoding, push_request=push_request ) - for _ in range(int(response)) - } + response = resp_dict # push response elif byte == b">": response = [ diff --git a/redis/asyncio/connection.py b/redis/asyncio/connection.py index 7b04434..7731221 100644 --- a/redis/asyncio/connection.py +++ b/redis/asyncio/connection.py @@ -880,6 +880,7 @@ URL_QUERY_ARGUMENT_PARSERS: Mapping[str, Callable[..., object]] = MappingProxyTy "max_connections": int, "health_check_interval": int, "ssl_check_hostname": to_bool, + "timeout": float, } ) diff --git a/redis/connection.py b/redis/connection.py index b39ba28..fead613 100644 --- a/redis/connection.py +++ b/redis/connection.py @@ -853,6 +853,7 @@ URL_QUERY_ARGUMENT_PARSERS = { "max_connections": int, "health_check_interval": int, "ssl_check_hostname": to_bool, + "timeout": float, }
redis/redis-py
d3a3ada03e080f39144807c9fbe44876c40e0548
diff --git a/tests/test_asyncio/test_connection_pool.py b/tests/test_asyncio/test_connection_pool.py index c93fa91..ed90fc7 100644 --- a/tests/test_asyncio/test_connection_pool.py +++ b/tests/test_asyncio/test_connection_pool.py @@ -454,6 +454,31 @@ class TestConnectionPoolURLParsing: ) +class TestBlockingConnectionPoolURLParsing: + def test_extra_typed_querystring_options(self): + pool = redis.BlockingConnectionPool.from_url( + "redis://localhost/2?socket_timeout=20&socket_connect_timeout=10" + "&socket_keepalive=&retry_on_timeout=Yes&max_connections=10&timeout=13.37" + ) + + assert pool.connection_class == redis.Connection + assert pool.connection_kwargs == { + "host": "localhost", + "db": 2, + "socket_timeout": 20.0, + "socket_connect_timeout": 10.0, + "retry_on_timeout": True, + } + assert pool.max_connections == 10 + assert pool.timeout == 13.37 + + def test_invalid_extra_typed_querystring_options(self): + with pytest.raises(ValueError): + redis.BlockingConnectionPool.from_url( + "redis://localhost/2?timeout=_not_a_float_" + ) + + class TestConnectionPoolUnixSocketURLParsing: def test_defaults(self): pool = redis.ConnectionPool.from_url("unix:///socket") diff --git a/tests/test_connection_pool.py b/tests/test_connection_pool.py index ef70a8f..d1e984e 100644 --- a/tests/test_connection_pool.py +++ b/tests/test_connection_pool.py @@ -359,6 +359,31 @@ class TestConnectionPoolURLParsing: ) +class TestBlockingConnectionPoolURLParsing: + def test_extra_typed_querystring_options(self): + pool = redis.BlockingConnectionPool.from_url( + "redis://localhost/2?socket_timeout=20&socket_connect_timeout=10" + "&socket_keepalive=&retry_on_timeout=Yes&max_connections=10&timeout=42" + ) + + assert pool.connection_class == redis.Connection + assert pool.connection_kwargs == { + "host": "localhost", + "db": 2, + "socket_timeout": 20.0, + "socket_connect_timeout": 10.0, + "retry_on_timeout": True, + } + assert pool.max_connections == 10 + assert pool.timeout == 42.0 + + def test_invalid_extra_typed_querystring_options(self): + with pytest.raises(ValueError): + redis.BlockingConnectionPool.from_url( + "redis://localhost/2?timeout=_not_a_float_" + ) + + class TestConnectionPoolUnixSocketURLParsing: def test_defaults(self): pool = redis.ConnectionPool.from_url("unix:///socket")
resp3 parser async parser incorrectly parses maps Issue discovered in pr #2947 the evaulation order of `key:val` in `{key():val() for foo in bar}` dict comprehension is undefined in Python. It mostly is left-right, but some versions, notably recent 3.7 versions, don't behave that way. It is best to use explicit ordering when reading from a stream. This had already been fixed for __non-async__ parsing, but in pr #2947 caused some scheduling behaviour which triggered this to happen. A fix for __async__ has been added there.
0.0
d3a3ada03e080f39144807c9fbe44876c40e0548
[ "tests/test_asyncio/test_connection_pool.py::TestBlockingConnectionPoolURLParsing::test_extra_typed_querystring_options", "tests/test_asyncio/test_connection_pool.py::TestBlockingConnectionPoolURLParsing::test_invalid_extra_typed_querystring_options", "tests/test_connection_pool.py::TestBlockingConnectionPoolURLParsing::test_extra_typed_querystring_options", "tests/test_connection_pool.py::TestBlockingConnectionPoolURLParsing::test_invalid_extra_typed_querystring_options" ]
[ "tests/test_asyncio/test_connection_pool.py::TestConnectionPool::test_connection_creation", "tests/test_asyncio/test_connection_pool.py::TestConnectionPool::test_aclosing", "tests/test_asyncio/test_connection_pool.py::TestConnectionPool::test_repr_contains_db_info_tcp", "tests/test_asyncio/test_connection_pool.py::TestConnectionPool::test_repr_contains_db_info_unix", "tests/test_asyncio/test_connection_pool.py::TestBlockingConnectionPool::test_connection_creation", "tests/test_asyncio/test_connection_pool.py::TestBlockingConnectionPool::test_disconnect", "tests/test_asyncio/test_connection_pool.py::TestBlockingConnectionPool::test_multiple_connections", "tests/test_asyncio/test_connection_pool.py::TestBlockingConnectionPool::test_connection_pool_blocks_until_timeout", "tests/test_asyncio/test_connection_pool.py::TestBlockingConnectionPool::test_connection_pool_blocks_until_conn_available", "tests/test_asyncio/test_connection_pool.py::TestBlockingConnectionPool::test_reuse_previously_released_connection", "tests/test_asyncio/test_connection_pool.py::TestBlockingConnectionPool::test_repr_contains_db_info_tcp", "tests/test_asyncio/test_connection_pool.py::TestBlockingConnectionPool::test_repr_contains_db_info_unix", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_hostname", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_quoted_hostname", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_port", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_username", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_quoted_username", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_password", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_quoted_password", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_username_and_password", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_db_as_argument", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_db_in_path", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_db_in_querystring", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_extra_typed_querystring_options", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_boolean_parsing", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_client_name_in_querystring", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_invalid_extra_typed_querystring_options", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_extra_querystring_options", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_calling_from_subclass_returns_correct_instance", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_client_creates_connection_pool", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolURLParsing::test_invalid_scheme_raises_error", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_defaults", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_username", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_quoted_username", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_password", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_quoted_password", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_quoted_path", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_db_as_argument", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_db_in_querystring", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_client_name_in_querystring", "tests/test_asyncio/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_extra_querystring_options", "tests/test_asyncio/test_connection_pool.py::TestSSLConnectionURLParsing::test_host", "tests/test_asyncio/test_connection_pool.py::TestSSLConnectionURLParsing::test_cert_reqs_options", "tests/test_asyncio/test_connection_pool.py::TestConnection::test_on_connect_error", "tests/test_asyncio/test_connection_pool.py::TestConnection::test_connect_from_url_tcp", "tests/test_asyncio/test_connection_pool.py::TestConnection::test_connect_from_url_unix", "tests/test_connection_pool.py::TestConnectionPool::test_connection_creation", "tests/test_connection_pool.py::TestConnectionPool::test_closing", "tests/test_connection_pool.py::TestConnectionPool::test_repr_contains_db_info_tcp", "tests/test_connection_pool.py::TestConnectionPool::test_repr_contains_db_info_unix", "tests/test_connection_pool.py::TestBlockingConnectionPool::test_connection_creation", "tests/test_connection_pool.py::TestBlockingConnectionPool::test_multiple_connections", "tests/test_connection_pool.py::TestBlockingConnectionPool::test_connection_pool_blocks_until_timeout", "tests/test_connection_pool.py::TestBlockingConnectionPool::test_connection_pool_blocks_until_conn_available", "tests/test_connection_pool.py::TestBlockingConnectionPool::test_reuse_previously_released_connection", "tests/test_connection_pool.py::TestBlockingConnectionPool::test_repr_contains_db_info_tcp", "tests/test_connection_pool.py::TestBlockingConnectionPool::test_repr_contains_db_info_unix", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_hostname", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_quoted_hostname", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_port", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_username", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_quoted_username", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_password", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_quoted_password", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_username_and_password", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_db_as_argument", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_db_in_path", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_db_in_querystring", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_extra_typed_querystring_options", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_boolean_parsing", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_client_name_in_querystring", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_invalid_extra_typed_querystring_options", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_extra_querystring_options", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_calling_from_subclass_returns_correct_instance", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_client_creates_connection_pool", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_invalid_scheme_raises_error", "tests/test_connection_pool.py::TestConnectionPoolURLParsing::test_invalid_scheme_raises_error_when_double_slash_missing", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_defaults", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_username", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_quoted_username", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_password", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_quoted_password", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_quoted_path", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_db_as_argument", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_db_in_querystring", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_client_name_in_querystring", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_extra_querystring_options", "tests/test_connection_pool.py::TestConnectionPoolUnixSocketURLParsing::test_connection_class_override", "tests/test_connection_pool.py::TestSSLConnectionURLParsing::test_host", "tests/test_connection_pool.py::TestSSLConnectionURLParsing::test_connection_class_override", "tests/test_connection_pool.py::TestSSLConnectionURLParsing::test_cert_reqs_options", "tests/test_connection_pool.py::TestConnection::test_on_connect_error", "tests/test_connection_pool.py::TestConnection::test_connect_from_url_tcp", "tests/test_connection_pool.py::TestConnection::test_connect_from_url_unix" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-10-05 14:42:02+00:00
mit
5,206
reframe-hpc__reframe-2515
diff --git a/docs/manpage.rst b/docs/manpage.rst index 531b7399..4c6356bf 100644 --- a/docs/manpage.rst +++ b/docs/manpage.rst @@ -484,6 +484,10 @@ Options controlling ReFrame execution Set variable ``VAR`` in all tests or optionally only in test ``TEST`` to ``VAL``. + ``TEST`` can have the form ``[TEST.][FIXT.]*``, in which case ``VAR`` will be set in fixture ``FIXT`` of ``TEST``. + Note that this syntax is recursive on fixtures, so that a variable can be set in a fixture arbitrarily deep. + ``TEST`` prefix refers to the test class name, *not* the test name, but ``FIXT`` refers to the fixture name *inside* the referenced test. + Multiple variables can be set at the same time by passing this option multiple times. This option *cannot* change arbitrary test attributes, but only test variables declared with the :attr:`~reframe.core.pipeline.RegressionMixin.variable` built-in. If an attempt is made to change an inexistent variable or a test parameter, a warning will be issued. @@ -511,8 +515,6 @@ Options controlling ReFrame execution Conversions to arbitrary objects are also supported. See :class:`~reframe.utility.typecheck.ConvertibleType` for more details. - The optional ``TEST.`` prefix refers to the test class name, *not* the test name. - Variable assignments passed from the command line happen *before* the test is instantiated and is the exact equivalent of assigning a new value to the variable *at the end* of the test class body. This has a number of implications that users of this feature should be aware of: @@ -561,6 +563,10 @@ Options controlling ReFrame execution Proper handling of boolean variables. + .. versionchanged:: 3.11.1 + + Allow setting variables in fixtures. + .. option:: --skip-performance-check diff --git a/reframe/core/meta.py b/reframe/core/meta.py index a28162a0..5e5b227f 100644 --- a/reframe/core/meta.py +++ b/reframe/core/meta.py @@ -535,6 +535,17 @@ class RegressionTestMeta(type): ''' + if '.' in name: + # `name` refers to a fixture variable + fixtname, varname = name.split('.', maxsplit=1) + try: + fixt_space = super().__getattribute__('_rfm_fixture_space') + except AttributeError: + '''Catch early access attempt to the variable space.''' + + if fixtname in fixt_space: + return fixt_space[fixtname].cls.setvar(varname, value) + try: var_space = super().__getattribute__('_rfm_var_space') if name in var_space: diff --git a/reframe/core/variables.py b/reframe/core/variables.py index 48da55e3..b90bf97e 100644 --- a/reframe/core/variables.py +++ b/reframe/core/variables.py @@ -281,7 +281,7 @@ class TestVar: def _check_is_defined(self): if not self.is_defined(): raise ReframeSyntaxError( - f'variable {self._name} is not assigned a value' + f'variable {self._name!r} is not assigned a value' ) def __repr__(self):
reframe-hpc/reframe
f9d69c8aaa9379baf94159906b827ded169a38c3
diff --git a/unittests/resources/checks_unlisted/externalvars.py b/unittests/resources/checks_unlisted/externalvars.py index eaafa529..113061fe 100644 --- a/unittests/resources/checks_unlisted/externalvars.py +++ b/unittests/resources/checks_unlisted/externalvars.py @@ -3,19 +3,33 @@ import reframe.utility.sanity as sn import reframe.utility.typecheck as typ +class Bacon(rfm.RunOnlyRegressionTest): + bacon = variable(int, value=-1) + executable = 'echo' + sanity_patterns = sn.assert_true(1) + + +class Eggs(rfm.RunOnlyRegressionTest): + eggs = fixture(Bacon) + executable = 'echo' + sanity_patterns = sn.assert_true(1) + + @rfm.simple_test class external_x(rfm.RunOnlyRegressionTest): valid_systems = ['*'] valid_prog_environs = ['*'] foo = variable(int, value=1) ham = variable(typ.Bool, value=False) + spam = fixture(Eggs) executable = 'echo' @sanity_function def assert_foo(self): return sn.all([ sn.assert_eq(self.foo, 3), - sn.assert_true(self.ham) + sn.assert_true(self.ham), + sn.assert_eq(self.spam.eggs.bacon, 10) ]) diff --git a/unittests/test_cli.py b/unittests/test_cli.py index ce762d2a..4bb5f52e 100644 --- a/unittests/test_cli.py +++ b/unittests/test_cli.py @@ -837,13 +837,17 @@ def test_detect_host_topology_file(run_reframe, tmp_path): def test_external_vars(run_reframe): returncode, stdout, stderr = run_reframe( checkpath=['unittests/resources/checks_unlisted/externalvars.py'], - more_options=['-S', 'external_x.foo=3', '-S', 'external_y.foo=2', - '-S', 'foolist=3,4', '-S', 'bar=@none', + more_options=['-S', 'external_x.foo=3', '-S', 'external_x.ham=true', - '-S', 'external_y.baz=false'] + '-S', 'external_x.spam.eggs.bacon=10', + '-S', 'external_y.foo=2', + '-S', 'external_y.baz=false', + '-S', 'foolist=3,4', + '-S', 'bar=@none'] ) + assert 'PASSED' in stdout + assert 'Ran 6/6 test case(s)' in stdout assert 'Traceback' not in stdout - assert 'Ran 2/2 test case(s)' in stdout assert 'Traceback' not in stderr assert returncode == 0
Fixture variables cannot be set from the command line This is very easy to reproduce by simply trying doing `-S fixture_class.var=val`. You will notice that the variable is not set. This is due to the following: https://github.com/eth-cscs/reframe/blob/f44e37c781da8d4bbc20daf52597458ffb5da377/reframe/frontend/loader.py#L173-L205 Although we set the variables in all the tests in the test registry, this does not include the fixtures, which are actually instantiated just after.
0.0
f9d69c8aaa9379baf94159906b827ded169a38c3
[ "unittests/test_cli.py::test_external_vars" ]
[ "unittests/test_cli.py::test_check_success", "unittests/test_cli.py::test_check_restore_session_failed", "unittests/test_cli.py::test_check_restore_session_succeeded_test", "unittests/test_cli.py::test_check_restore_session_check_search_path", "unittests/test_cli.py::test_check_success_force_local", "unittests/test_cli.py::test_report_file_with_sessionid", "unittests/test_cli.py::test_report_ends_with_newline", "unittests/test_cli.py::test_check_failure", "unittests/test_cli.py::test_check_setup_failure", "unittests/test_cli.py::test_check_kbd_interrupt", "unittests/test_cli.py::test_check_sanity_failure", "unittests/test_cli.py::test_dont_restage", "unittests/test_cli.py::test_checkpath_symlink", "unittests/test_cli.py::test_performance_check_failure", "unittests/test_cli.py::test_perflogdir_from_env", "unittests/test_cli.py::test_performance_report", "unittests/test_cli.py::test_skip_system_check_option", "unittests/test_cli.py::test_skip_prgenv_check_option", "unittests/test_cli.py::test_sanity_of_checks", "unittests/test_cli.py::test_unknown_system", "unittests/test_cli.py::test_sanity_of_optconfig", "unittests/test_cli.py::test_checkpath_recursion", "unittests/test_cli.py::test_same_output_stage_dir", "unittests/test_cli.py::test_execution_modes", "unittests/test_cli.py::test_timestamp_option", "unittests/test_cli.py::test_timestamp_option_default", "unittests/test_cli.py::test_list_empty_prgenvs_check_and_options", "unittests/test_cli.py::test_list_check_with_empty_prgenvs", "unittests/test_cli.py::test_list_empty_prgenvs_in_check_and_options", "unittests/test_cli.py::test_list_with_details", "unittests/test_cli.py::test_list_concretized", "unittests/test_cli.py::test_list_tags", "unittests/test_cli.py::test_filtering_multiple_criteria", "unittests/test_cli.py::test_show_config_all", "unittests/test_cli.py::test_show_config_param", "unittests/test_cli.py::test_show_config_unknown_param", "unittests/test_cli.py::test_show_config_null_param", "unittests/test_cli.py::test_verbosity", "unittests/test_cli.py::test_verbosity_with_check", "unittests/test_cli.py::test_quiesce_with_check", "unittests/test_cli.py::test_failure_stats", "unittests/test_cli.py::test_maxfail_option", "unittests/test_cli.py::test_maxfail_invalid_option", "unittests/test_cli.py::test_maxfail_negative", "unittests/test_cli.py::test_detect_host_topology", "unittests/test_cli.py::test_detect_host_topology_file", "unittests/test_cli.py::test_external_vars_invalid_expr", "unittests/test_cli.py::test_fixture_registry_env_sys", "unittests/test_cli.py::test_fixture_resolution", "unittests/test_cli.py::test_dynamic_tests", "unittests/test_cli.py::test_dynamic_tests_filtering" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-05-12 14:32:52+00:00
bsd-3-clause
5,207
reframe-hpc__reframe-2533
diff --git a/reframe/frontend/filters.py b/reframe/frontend/filters.py index 5eade732..46fefac4 100644 --- a/reframe/frontend/filters.py +++ b/reframe/frontend/filters.py @@ -49,7 +49,10 @@ def have_any_name(names): regex_matches = [] for n in names: if has_compact_names and '@' in n: - exact_matches.append(n.replace('@', '_')) + test, _, variant = n.rpartition('@') + if variant.isdigit(): + exact_matches.append((test, int(variant))) + else: regex_matches.append(n) @@ -61,7 +64,8 @@ def have_any_name(names): def _fn(case): # Check if we have an exact match for m in exact_matches: - if m == case.check.unique_name: + cls_name = type(case.check).__name__ + if (cls_name, case.check.variant_num) == m: return True display_name = case.check.display_name.replace(' ', '') diff --git a/reframe/frontend/runreport.py b/reframe/frontend/runreport.py index f8ac0a9f..25e08b68 100644 --- a/reframe/frontend/runreport.py +++ b/reframe/frontend/runreport.py @@ -18,7 +18,7 @@ import reframe.utility.jsonext as jsonext # The schema data version # Major version bumps are expected to break the validation of previous schemas -DATA_VERSION = '2.0' +DATA_VERSION = '2.1' _SCHEMA = os.path.join(rfm.INSTALL_PREFIX, 'reframe/schemas/runreport.json') diff --git a/reframe/frontend/statistics.py b/reframe/frontend/statistics.py index 8457958e..de908223 100644 --- a/reframe/frontend/statistics.py +++ b/reframe/frontend/statistics.py @@ -110,6 +110,7 @@ class TestStats: 'environment': None, 'fail_phase': None, 'fail_reason': None, + 'fixture': check.is_fixture(), 'jobid': None, 'job_stderr': None, 'job_stdout': None, @@ -234,7 +235,7 @@ class TestStats: f"{r['dependencies_actual']}") printer.info(f" * Maintainers: {r['maintainers']}") printer.info(f" * Failing phase: {r['fail_phase']}") - if rerun_info: + if rerun_info and not r['fixture']: if rt.runtime().get_option('general/0/compact_test_names'): cls = r['display_name'].split(' ')[0] variant = r['unique_name'].replace(cls, '') diff --git a/reframe/schemas/runreport.json b/reframe/schemas/runreport.json index bdc5ea17..d67db1d0 100644 --- a/reframe/schemas/runreport.json +++ b/reframe/schemas/runreport.json @@ -40,6 +40,7 @@ "fail_reason": {"type": ["string", "null"]}, "fail_severe": {"type": "boolean"}, "filename": {"type": "string"}, + "fixture": {"type": "boolean"}, "jobid": {"type": ["string", "null"]}, "job_stderr": {"type": ["string", "null"]}, "job_stdout": {"type": ["string", "null"]},
reframe-hpc/reframe
1d85917cee54243c047a8d9adc01c90050ca503b
diff --git a/unittests/test_filters.py b/unittests/test_filters.py index 90548586..8388980d 100644 --- a/unittests/test_filters.py +++ b/unittests/test_filters.py @@ -52,7 +52,7 @@ def use_compact_names(make_exec_ctx_g): @pytest.fixture def sample_param_cases(use_compact_names): class _X(rfm.RegressionTest): - p = parameter([1, 1, 3]) + p = parameter([1] + list(range(11))) valid_systems = ['*'] valid_prog_environs = ['*'] @@ -66,7 +66,7 @@ def sample_param_cases_compat(): # `general/compact_test_names=False` class _X(rfm.RegressionTest): - p = parameter([1, 1, 3]) + p = parameter([1] + list(range(11))) valid_systems = ['*'] valid_prog_environs = ['*'] @@ -87,17 +87,22 @@ def test_have_any_name(sample_cases): def test_have_any_name_param_test(sample_param_cases): - assert 2 == count_checks(filters.have_any_name(['.*%p=1']), + # The regex will match "_X%p=1" as well as "_X%p=10" + assert 3 == count_checks(filters.have_any_name(['.*%p=1']), + sample_param_cases) + assert 2 == count_checks(filters.have_any_name(['.*%p=1$']), sample_param_cases) assert 1 == count_checks(filters.have_any_name(['_X%p=3']), sample_param_cases) assert 1 == count_checks(filters.have_any_name(['_X@2']), sample_param_cases) - assert 0 == count_checks(filters.have_any_name(['_X@3']), + assert 1 == count_checks(filters.have_any_name(['_X@002']), + sample_param_cases) + assert 0 == count_checks(filters.have_any_name(['_X@12']), sample_param_cases) assert 2 == count_checks(filters.have_any_name(['_X@0', '_X@1']), sample_param_cases) - assert 3 == count_checks(filters.have_any_name(['_X@0', '_X.*']), + assert 12 == count_checks(filters.have_any_name(['_X@0', '_X.*']), sample_param_cases) @@ -108,11 +113,14 @@ def test_have_any_name_param_test_compat(sample_param_cases_compat): sample_param_cases_compat) assert 0 == count_checks(filters.have_any_name(['_X@2']), sample_param_cases_compat) - assert 2 == count_checks(filters.have_any_name(['_X_1']), + # The regex will match "_X_1" as well as "_X_10" + assert 3 == count_checks(filters.have_any_name(['_X_1']), + sample_param_cases_compat) + assert 2 == count_checks(filters.have_any_name(['_X_1$']), sample_param_cases_compat) assert 0 == count_checks(filters.have_any_name(['_X@0', '_X@1']), sample_param_cases_compat) - assert 3 == count_checks(filters.have_any_name(['_X@0', '_X.*']), + assert 12 == count_checks(filters.have_any_name(['_X@0', '_X.*']), sample_param_cases_compat)
When selecting tests by their id, their id is taken literally as a string In a parameterised test with more than 10 variants, you can't select a test with a single digit variant, e.g., `testA@0` will match no test, whereas `testA@00` will. The variant ID should be interpreted as an integer when matching tests by variant.
0.0
1d85917cee54243c047a8d9adc01c90050ca503b
[ "unittests/test_filters.py::test_have_any_name_param_test" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-06-08 11:06:27+00:00
bsd-3-clause
5,208
reframe-hpc__reframe-2544
diff --git a/reframe/frontend/executors/__init__.py b/reframe/frontend/executors/__init__.py index 795d2869..aa2b47e2 100644 --- a/reframe/frontend/executors/__init__.py +++ b/reframe/frontend/executors/__init__.py @@ -36,11 +36,11 @@ class TestCase: def __init__(self, check, partition, environ): self._check_orig = check - self._check = copy.deepcopy(check) - self._partition = copy.deepcopy(partition) - self._environ = copy.deepcopy(environ) - self._check._case = weakref.ref(self) + self._check = check + self._partition = partition + self._environ = environ self._deps = [] + self._is_ready = False # Incoming dependencies self.in_degree = 0 @@ -72,6 +72,15 @@ class TestCase: e = self.environ.name if self.environ else None return f'({c!r}, {p!r}, {e!r})' + def prepare(self): + '''Prepare test case for sending down the test pipeline''' + if self._is_ready: + return + + self._check = copy.deepcopy(self._check) + self._check._case = weakref.ref(self) + self._is_ready = True + @property def check(self): return self._check @@ -97,8 +106,14 @@ class TestCase: return TestCase(self._check_orig, self._partition, self._environ) -def generate_testcases(checks): - '''Generate concrete test cases from checks.''' +def generate_testcases(checks, prepare=False): + '''Generate concrete test cases from checks. + + If `prepare` is true then each of the cases will also be prepared for + being sent to the test pipeline. Note that setting this to true may slow down + the test case generation. + + ''' rt = runtime.runtime() cases = [] @@ -107,7 +122,11 @@ def generate_testcases(checks): c.valid_prog_environs) for part, environs in valid_comb.items(): for env in environs: - cases.append(TestCase(c, part, env)) + case = TestCase(c, part, env) + if prepare: + case.prepare() + + cases.append(case) return cases @@ -295,6 +314,7 @@ class RegressionTask: raise TaskExit from e def setup(self, *args, **kwargs): + self.testcase.prepare() self._safe_call(self.check.setup, *args, **kwargs) self._notify_listeners('on_task_setup') diff --git a/reframe/schemas/config.json b/reframe/schemas/config.json index 472b0d8a..46df7c9f 100644 --- a/reframe/schemas/config.json +++ b/reframe/schemas/config.json @@ -514,7 +514,7 @@ "environments/features": [], "environments/target_systems": ["*"], "general/dump_pipeline_progress": false, - "general/pipeline_timeout": null, + "general/pipeline_timeout": 3, "general/check_search_path": ["${RFM_INSTALL_PREFIX}/checks/"], "general/check_search_recursive": false, "general/clean_stagedir": true,
reframe-hpc/reframe
faab025bf7ca8d6e4a4c03ce9fad13213d6f0d3f
diff --git a/unittests/test_dependencies.py b/unittests/test_dependencies.py index 3cf15f3e..29066810 100644 --- a/unittests/test_dependencies.py +++ b/unittests/test_dependencies.py @@ -375,7 +375,11 @@ def test_build_deps_deprecated_syntax(loader, default_exec_ctx): def test_build_deps(loader, default_exec_ctx): checks = loader.load_all(force=True) - cases = executors.generate_testcases(checks) + + # We need to prepare the test cases as if we were about to run them, + # because we want to test `getdep()` as well, which normally gets resolved + # during the `setup` phase of the pipeline + cases = executors.generate_testcases(checks, prepare=True) # Test calling getdep() before having built the graph t = find_check('Test1_fully', checks) diff --git a/unittests/test_pipeline.py b/unittests/test_pipeline.py index f3ba74ed..8ef7818b 100644 --- a/unittests/test_pipeline.py +++ b/unittests/test_pipeline.py @@ -1210,7 +1210,7 @@ def test_require_deps(HelloTest, local_exec_ctx): def setz(self, T0): self.z = T0().x + 2 - cases = executors.generate_testcases([T0(), T1()]) + cases = executors.generate_testcases([T0(), T1()], prepare=True) deps, _ = dependencies.build_deps(cases) for c in dependencies.toposort(deps): _run(*c)
`--distribute` option is too slow ``` time ./bin/reframe -C config/cscs.py -c cscstests/microbenchmarks/gpu/gpu_burn/gpu_burn_test.py -S num_tasks=1 -J reservation=foo -l ... real 0m0.734s user 0m0.509s sys 0m0.105s ``` ``` time ./bin/reframe -C config/cscs.py -c cscstests/microbenchmarks/gpu/gpu_burn/gpu_burn_test.py -S num_tasks=1 -J reservation=foo --distribute=all -l ... real 0m4.629s user 0m3.077s sys 0m0.443s ``` I think that the slowdown is due to the `scontrol`s done behind the scenes, but we need to investigate further and either improve it or add a note in the documentation.
0.0
faab025bf7ca8d6e4a4c03ce9fad13213d6f0d3f
[ "unittests/test_dependencies.py::test_build_deps", "unittests/test_pipeline.py::test_require_deps" ]
[ "unittests/test_dependencies.py::test_eq_hash", "unittests/test_dependencies.py::test_dependecies_how_functions", "unittests/test_dependencies.py::test_dependecies_how_functions_undoc", "unittests/test_dependencies.py::test_build_deps_deprecated_syntax", "unittests/test_dependencies.py::test_build_deps_empty", "unittests/test_dependencies.py::test_valid_deps", "unittests/test_dependencies.py::test_cyclic_deps", "unittests/test_dependencies.py::test_cyclic_deps_by_env", "unittests/test_dependencies.py::test_validate_deps_empty", "unittests/test_dependencies.py::test_skip_unresolved_deps", "unittests/test_dependencies.py::test_prune_deps", "unittests/test_dependencies.py::test_toposort", "unittests/test_dependencies.py::test_toposort_subgraph", "unittests/test_pipeline.py::test_hellocheck_local_prepost_run", "unittests/test_pipeline.py::test_run_only_set_sanity_in_a_hook", "unittests/test_pipeline.py::test_run_only_decorated_sanity", "unittests/test_pipeline.py::test_run_only_no_srcdir", "unittests/test_pipeline.py::test_run_only_srcdir_set_to_none", "unittests/test_pipeline.py::test_executable_is_required", "unittests/test_pipeline.py::test_compile_only_failure", "unittests/test_pipeline.py::test_compile_only_warning", "unittests/test_pipeline.py::test_pinned_test", "unittests/test_pipeline.py::test_supports_sysenv", "unittests/test_pipeline.py::test_sourcesdir_none", "unittests/test_pipeline.py::test_sourcesdir_build_system", "unittests/test_pipeline.py::test_sourcesdir_none_generated_sources", "unittests/test_pipeline.py::test_sourcesdir_none_compile_only", "unittests/test_pipeline.py::test_sourcesdir_none_run_only", "unittests/test_pipeline.py::test_sourcepath_abs", "unittests/test_pipeline.py::test_sourcepath_upref", "unittests/test_pipeline.py::test_sourcepath_non_existent", "unittests/test_pipeline.py::test_extra_resources", "unittests/test_pipeline.py::test_unkown_pre_hook", "unittests/test_pipeline.py::test_unkown_post_hook", "unittests/test_pipeline.py::test_pre_init_hook", "unittests/test_pipeline.py::test_post_init_hook", "unittests/test_pipeline.py::test_setup_hooks", "unittests/test_pipeline.py::test_compile_hooks", "unittests/test_pipeline.py::test_run_hooks", "unittests/test_pipeline.py::test_multiple_hooks", "unittests/test_pipeline.py::test_stacked_hooks", "unittests/test_pipeline.py::test_multiple_inheritance", "unittests/test_pipeline.py::test_inherited_hooks", "unittests/test_pipeline.py::test_inherited_hooks_order", "unittests/test_pipeline.py::test_inherited_hooks_from_instantiated_tests", "unittests/test_pipeline.py::test_overriden_hooks", "unittests/test_pipeline.py::test_overriden_hook_different_stages", "unittests/test_pipeline.py::test_disabled_hooks", "unittests/test_pipeline.py::test_trap_job_errors_without_sanity_patterns", "unittests/test_pipeline.py::test_trap_job_errors_with_sanity_patterns", "unittests/test_pipeline.py::test_sanity_success", "unittests/test_pipeline.py::test_sanity_failure", "unittests/test_pipeline.py::test_sanity_failure_noassert", "unittests/test_pipeline.py::test_sanity_multiple_patterns", "unittests/test_pipeline.py::test_sanity_multiple_files", "unittests/test_pipeline.py::test_performance_failure", "unittests/test_pipeline.py::test_reference_unknown_tag", "unittests/test_pipeline.py::test_reference_unknown_system", "unittests/test_pipeline.py::test_reference_empty", "unittests/test_pipeline.py::test_reference_default", "unittests/test_pipeline.py::test_reference_tag_resolution", "unittests/test_pipeline.py::test_performance_invalid_value", "unittests/test_pipeline.py::test_perf_patterns_evaluation", "unittests/test_pipeline.py::test_validate_default_perf_variables", "unittests/test_pipeline.py::test_perf_vars_without_reference", "unittests/test_pipeline.py::test_perf_vars_with_reference", "unittests/test_pipeline.py::test_incompat_perf_syntax", "unittests/test_pipeline.py::test_unknown_container_platform", "unittests/test_pipeline.py::test_not_configured_container_platform", "unittests/test_pipeline.py::test_skip_if_no_topo", "unittests/test_pipeline.py::test_make_test_without_builtins", "unittests/test_pipeline.py::test_make_test_with_builtins", "unittests/test_pipeline.py::test_make_test_with_builtins_inline" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-06-27 13:24:25+00:00
bsd-3-clause
5,209
reframe-hpc__reframe-2575
diff --git a/docs/manpage.rst b/docs/manpage.rst index 90543a9f..8ee59874 100644 --- a/docs/manpage.rst +++ b/docs/manpage.rst @@ -418,6 +418,23 @@ Options controlling ReFrame execution .. versionadded:: 3.11.0 + +.. option:: --exec-order=ORDER + + Impose an execution order for the independent tests. + The ``ORDER`` argument can take one of the following values: + + - ``name``: Order tests by their display name. + - ``rname``: Order tests by their display name in reverse order. + - ``uid``: Order tests by their unique name. + - ``ruid``: Order tests by their unique name in reverse order. + - ``random``: Randomize the order of execution. + + If this option is not specified the order of execution of independent tests is implementation defined. + This option can be combined with any of the listing options (:option:`-l` or :option:`-L`) to list the tests in the order. + + .. versionadded:: 4.0.0 + .. option:: --exec-policy=POLICY The execution policy to be used for running tests. diff --git a/reframe/frontend/cli.py b/reframe/frontend/cli.py index 83bba0fb..0412fd61 100644 --- a/reframe/frontend/cli.py +++ b/reframe/frontend/cli.py @@ -7,6 +7,7 @@ import inspect import itertools import json import os +import random import shlex import socket import sys @@ -25,6 +26,7 @@ import reframe.frontend.ci as ci import reframe.frontend.dependencies as dependencies import reframe.frontend.filters as filters import reframe.frontend.runreport as runreport +import reframe.utility as util import reframe.utility.jsonext as jsonext import reframe.utility.osext as osext import reframe.utility.typecheck as typ @@ -386,6 +388,11 @@ def main(): help=('Distribute the selected single-node jobs on every node that' 'is in STATE (default: "idle"') ) + run_options.add_argument( + '--exec-order', metavar='ORDER', action='store', + choices=['name', 'random', 'rname', 'ruid', 'uid'], + help='Impose an execution order for independent tests' + ) run_options.add_argument( '--exec-policy', metavar='POLICY', action='store', choices=['async', 'serial'], default='async', @@ -1054,8 +1061,8 @@ def main(): "a non-negative integer" ) from None - testcases = repeat_tests(testcases, num_repeats) - testcases_all = testcases + testcases_all = repeat_tests(testcases, num_repeats) + testcases = testcases_all if options.distribute: node_map = getallnodes(options.distribute, parsed_job_options) @@ -1070,15 +1077,31 @@ def main(): x for x in parsed_job_options if (not x.startswith('-w') and not x.startswith('--nodelist')) ] - testcases = distribute_tests(testcases, node_map) - testcases_all = testcases + testcases_all = distribute_tests(testcases, node_map) + testcases = testcases_all + + @logging.time_function + def _sort_testcases(testcases): + if options.exec_order in ('name', 'rname'): + testcases.sort(key=lambda c: c.check.display_name, + reverse=(options.exec_order == 'rname')) + elif options.exec_order in ('uid', 'ruid'): + testcases.sort(key=lambda c: c.check.unique_name, + reverse=(options.exec_order == 'ruid')) + elif options.exec_order == 'random': + random.shuffle(testcases) + + _sort_testcases(testcases) + if testcases_all is not testcases: + _sort_testcases(testcases_all) # Prepare for running printer.debug('Building and validating the full test DAG') testgraph, skipped_cases = dependencies.build_deps(testcases_all) if skipped_cases: # Some cases were skipped, so adjust testcases - testcases = list(set(testcases) - set(skipped_cases)) + testcases = list(util.OrderedSet(testcases) - + util.OrderedSet(skipped_cases)) printer.verbose( f'Filtering test case(s) due to unresolved dependencies: ' f'{len(testcases)} remaining'
reframe-hpc/reframe
833c6ea3582bdcf4cceb6dc7a1aa667d0ca029e2
diff --git a/unittests/test_cli.py b/unittests/test_cli.py index 0136b66f..12ce3ad0 100644 --- a/unittests/test_cli.py +++ b/unittests/test_cli.py @@ -834,7 +834,7 @@ def test_repeat_invalid_option(run_reframe): def test_repeat_negative(run_reframe): returncode, stdout, stderr = run_reframe( - more_options=['--repeat', 'foo'], + more_options=['--repeat', '-1'], checkpath=['unittests/resources/checks/hellocheck.py'] ) errmsg = "argument to '--repeat' option must be a non-negative integer" @@ -844,6 +844,44 @@ def test_repeat_negative(run_reframe): assert returncode == 1 [email protected](params=['name', 'rname', 'uid', 'ruid', 'random']) +def exec_order(request): + return request.param + + +def test_exec_order(run_reframe, exec_order): + import reframe.utility.sanity as sn + + returncode, stdout, stderr = run_reframe( + more_options=['--repeat', '11', '-n', 'HelloTest', + f'--exec-order={exec_order}'], + checkpath=['unittests/resources/checks/hellocheck.py'], + action='list_detailed', + ) + assert 'Traceback' not in stdout + assert 'Traceback' not in stderr + assert 'Found 11 check(s)' in stdout + assert returncode == 0 + + # Verify the order + if exec_order == 'name': + repeat_no = sn.extractsingle_s(r'- HelloTest.*repeat_no=(\d+)', + stdout, 1, int, 2).evaluate() + assert repeat_no == 10 + elif exec_order == 'rname': + repeat_no = sn.extractsingle_s(r'- HelloTest.*repeat_no=(\d+)', + stdout, 1, int, -3).evaluate() + assert repeat_no == 10 + elif exec_order == 'uid': + repeat_no = sn.extractsingle_s(r'- HelloTest.*repeat_no=(\d+)', + stdout, 1, int, -1).evaluate() + assert repeat_no == 10 + elif exec_order == 'ruid': + repeat_no = sn.extractsingle_s(r'- HelloTest.*repeat_no=(\d+)', + stdout, 1, int, 0).evaluate() + assert repeat_no == 10 + + def test_detect_host_topology(run_reframe): from reframe.utility.cpuinfo import cpuinfo
RFE: randomize test execution order I don't think this is possible right now. It would be useful to be able to add a CLI argument to randomize the execution order of all the tests. Ideally it would randomize the tests across all files passed to Reframe, e.g. with `-c test1.py -c test2.py -c test3.py` it would randomize and interleave tests between all 3 files, not just within each file. To replay particular sequence of execution, perhaps the argument could accept an optional seed for the RNG. The rationale is that some test A might change the state of the system like making the system very hot and throttling clocks, that could cause a failure in a later test C only if you run A -> C -> B instead of always executing A -> B -> C, for example if test B is long but does not stress the system (giving the system the time to cool down). Similarly, if the same Reframe test starts in parallel on 10 machines, they might all reach a network test at the same time, creating heavy congestion (which is useful in itself, but might not be the target of the test). If possible, it would also be great if the performance report printed would always stay in the same order to make it easier to compare runs despite the randomized execution order.
0.0
833c6ea3582bdcf4cceb6dc7a1aa667d0ca029e2
[ "unittests/test_cli.py::test_exec_order[name]", "unittests/test_cli.py::test_exec_order[rname]", "unittests/test_cli.py::test_exec_order[uid]", "unittests/test_cli.py::test_exec_order[ruid]", "unittests/test_cli.py::test_exec_order[random]" ]
[ "unittests/test_cli.py::test_check_success", "unittests/test_cli.py::test_check_restore_session_failed", "unittests/test_cli.py::test_check_restore_session_succeeded_test", "unittests/test_cli.py::test_check_restore_session_check_search_path", "unittests/test_cli.py::test_check_success_force_local", "unittests/test_cli.py::test_report_file_with_sessionid", "unittests/test_cli.py::test_report_ends_with_newline", "unittests/test_cli.py::test_check_failure", "unittests/test_cli.py::test_check_setup_failure", "unittests/test_cli.py::test_check_kbd_interrupt", "unittests/test_cli.py::test_check_sanity_failure", "unittests/test_cli.py::test_dont_restage", "unittests/test_cli.py::test_checkpath_symlink", "unittests/test_cli.py::test_performance_check_failure", "unittests/test_cli.py::test_perflogdir_from_env", "unittests/test_cli.py::test_performance_report", "unittests/test_cli.py::test_skip_system_check_option", "unittests/test_cli.py::test_skip_prgenv_check_option", "unittests/test_cli.py::test_sanity_of_checks", "unittests/test_cli.py::test_unknown_system", "unittests/test_cli.py::test_sanity_of_optconfig", "unittests/test_cli.py::test_checkpath_recursion", "unittests/test_cli.py::test_same_output_stage_dir", "unittests/test_cli.py::test_execution_modes", "unittests/test_cli.py::test_timestamp_option", "unittests/test_cli.py::test_timestamp_option_default", "unittests/test_cli.py::test_list_empty_prgenvs_check_and_options", "unittests/test_cli.py::test_list_check_with_empty_prgenvs", "unittests/test_cli.py::test_list_empty_prgenvs_in_check_and_options", "unittests/test_cli.py::test_list_with_details", "unittests/test_cli.py::test_list_concretized", "unittests/test_cli.py::test_list_tags", "unittests/test_cli.py::test_filtering_multiple_criteria", "unittests/test_cli.py::test_show_config_all", "unittests/test_cli.py::test_show_config_param", "unittests/test_cli.py::test_show_config_unknown_param", "unittests/test_cli.py::test_show_config_null_param", "unittests/test_cli.py::test_verbosity", "unittests/test_cli.py::test_verbosity_with_check", "unittests/test_cli.py::test_quiesce_with_check", "unittests/test_cli.py::test_failure_stats", "unittests/test_cli.py::test_maxfail_option", "unittests/test_cli.py::test_maxfail_invalid_option", "unittests/test_cli.py::test_maxfail_negative", "unittests/test_cli.py::test_repeat_option", "unittests/test_cli.py::test_repeat_invalid_option", "unittests/test_cli.py::test_repeat_negative", "unittests/test_cli.py::test_detect_host_topology", "unittests/test_cli.py::test_detect_host_topology_file", "unittests/test_cli.py::test_external_vars", "unittests/test_cli.py::test_external_vars_invalid_expr", "unittests/test_cli.py::test_fixture_registry_env_sys", "unittests/test_cli.py::test_fixture_resolution", "unittests/test_cli.py::test_dynamic_tests", "unittests/test_cli.py::test_dynamic_tests_filtering" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-08-05 06:45:36+00:00
bsd-3-clause
5,210
reframe-hpc__reframe-2581
diff --git a/reframe/core/containers.py b/reframe/core/containers.py index d108746b..15be3766 100644 --- a/reframe/core/containers.py +++ b/reframe/core/containers.py @@ -255,7 +255,7 @@ class Singularity(ContainerPlatform): run_opts.append('--nv') if self.workdir: - run_opts.append(f'-W {self.workdir}') + run_opts.append(f'--pwd {self.workdir}') run_opts += self.options if self.command:
reframe-hpc/reframe
0d2c11214c914584c754afffac360bfd3c3383f8
diff --git a/unittests/test_containers.py b/unittests/test_containers.py index 6518781c..ea713465 100644 --- a/unittests/test_containers.py +++ b/unittests/test_containers.py @@ -104,15 +104,15 @@ def expected_cmd_mount_points(container_variant): elif container_variant in {'Singularity', 'Singularity+nopull'}: return ('singularity exec -B"/path/one:/one" ' '-B"/path/two:/two" -B"/foo:/rfm_workdir" ' - '-W /rfm_workdir image:tag cmd') + '--pwd /rfm_workdir image:tag cmd') elif container_variant == 'Singularity+cuda': return ('singularity exec -B"/path/one:/one" ' '-B"/path/two:/two" -B"/foo:/rfm_workdir" --nv ' - '-W /rfm_workdir image:tag cmd') + '--pwd /rfm_workdir image:tag cmd') elif container_variant == 'Singularity+nocommand': return ('singularity run -B"/path/one:/one" ' '-B"/path/two:/two" -B"/foo:/rfm_workdir" ' - '-W /rfm_workdir image:tag') + '--pwd /rfm_workdir image:tag') @pytest.fixture @@ -265,7 +265,7 @@ def expected_run_with_workdir(container_variant_noopt): '--foo image:tag cmd1' ) elif container_variant_noopt == 'Singularity': - return ('singularity exec -B\"/foo:/rfm_workdir\" -W foodir ' + return ('singularity exec -B\"/foo:/rfm_workdir\" --pwd foodir ' '--foo image:tag cmd1')
The Singularity container platform doesn't change automatically to the mounted stage directory In the Singularity container platform the change to the mounted `stage` directory is done with https://github.com/reframe-hpc/reframe/blob/0d2c11214c914584c754afffac360bfd3c3383f8/reframe/core/containers.py#L257-L258 but `-W` doesn't change the directory like docker or sarus. From `singularity --help`: ``` -W, --workdir string working directory to be used for /tmp, /var/tmp and $HOME (if -c/--contain was also used) ``` As a result the test doesn't start in the stage directory.
0.0
0d2c11214c914584c754afffac360bfd3c3383f8
[ "unittests/test_containers.py::test_mount_points[Singularity]", "unittests/test_containers.py::test_mount_points[Singularity+nocommand]", "unittests/test_containers.py::test_mount_points[Singularity+cuda]", "unittests/test_containers.py::test_run_with_workdir[Singularity]" ]
[ "unittests/test_containers.py::test_mount_points[Docker]", "unittests/test_containers.py::test_mount_points[Docker+nocommand]", "unittests/test_containers.py::test_mount_points[Docker+nopull]", "unittests/test_containers.py::test_mount_points[Sarus]", "unittests/test_containers.py::test_mount_points[Sarus+nocommand]", "unittests/test_containers.py::test_mount_points[Sarus+nopull]", "unittests/test_containers.py::test_mount_points[Sarus+mpi]", "unittests/test_containers.py::test_mount_points[Sarus+load]", "unittests/test_containers.py::test_mount_points[Shifter]", "unittests/test_containers.py::test_mount_points[Shifter+nocommand]", "unittests/test_containers.py::test_mount_points[Shifter+mpi]", "unittests/test_containers.py::test_mount_points[Shifter+nopull]", "unittests/test_containers.py::test_mount_points[Shifter+load]", "unittests/test_containers.py::test_prepare_command[Docker]", "unittests/test_containers.py::test_prepare_command[Docker+nocommand]", "unittests/test_containers.py::test_prepare_command[Docker+nopull]", "unittests/test_containers.py::test_prepare_command[Sarus]", "unittests/test_containers.py::test_prepare_command[Sarus+nocommand]", "unittests/test_containers.py::test_prepare_command[Sarus+nopull]", "unittests/test_containers.py::test_prepare_command[Sarus+mpi]", "unittests/test_containers.py::test_prepare_command[Sarus+load]", "unittests/test_containers.py::test_prepare_command[Shifter]", "unittests/test_containers.py::test_prepare_command[Shifter+nocommand]", "unittests/test_containers.py::test_prepare_command[Shifter+mpi]", "unittests/test_containers.py::test_prepare_command[Shifter+nopull]", "unittests/test_containers.py::test_prepare_command[Shifter+load]", "unittests/test_containers.py::test_prepare_command[Singularity]", "unittests/test_containers.py::test_prepare_command[Singularity+nocommand]", "unittests/test_containers.py::test_prepare_command[Singularity+cuda]", "unittests/test_containers.py::test_run_opts[Docker]", "unittests/test_containers.py::test_run_opts[Docker+nocommand]", "unittests/test_containers.py::test_run_opts[Docker+nopull]", "unittests/test_containers.py::test_run_opts[Sarus]", "unittests/test_containers.py::test_run_opts[Sarus+nocommand]", "unittests/test_containers.py::test_run_opts[Sarus+nopull]", "unittests/test_containers.py::test_run_opts[Sarus+mpi]", "unittests/test_containers.py::test_run_opts[Sarus+load]", "unittests/test_containers.py::test_run_opts[Shifter]", "unittests/test_containers.py::test_run_opts[Shifter+nocommand]", "unittests/test_containers.py::test_run_opts[Shifter+mpi]", "unittests/test_containers.py::test_run_opts[Shifter+nopull]", "unittests/test_containers.py::test_run_opts[Shifter+load]", "unittests/test_containers.py::test_run_opts[Singularity]", "unittests/test_containers.py::test_run_opts[Singularity+nocommand]", "unittests/test_containers.py::test_run_opts[Singularity+cuda]", "unittests/test_containers.py::test_run_with_workdir[Docker]", "unittests/test_containers.py::test_run_with_workdir[Sarus]", "unittests/test_containers.py::test_run_with_workdir[Shifter]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-08-30 13:26:58+00:00
bsd-3-clause
5,211
reframe-hpc__reframe-2613
diff --git a/docs/config_reference.rst b/docs/config_reference.rst index 356a97ce..d03e882f 100644 --- a/docs/config_reference.rst +++ b/docs/config_reference.rst @@ -467,6 +467,7 @@ ReFrame can launch containerized applications, but you need to configure properl The type of the container platform. Available values are the following: + - ``Apptainer``: The `Apptainer <https://apptainer.org/>`__ container runtime. - ``Docker``: The `Docker <https://www.docker.com/>`__ container runtime. - ``Sarus``: The `Sarus <https://sarus.readthedocs.io/>`__ container runtime. - ``Shifter``: The `Shifter <https://github.com/NERSC/shifter>`__ container runtime. diff --git a/reframe/core/containers.py b/reframe/core/containers.py index 15be3766..6182b3d8 100644 --- a/reframe/core/containers.py +++ b/reframe/core/containers.py @@ -243,6 +243,7 @@ class Singularity(ContainerPlatform): def __init__(self): super().__init__() self.with_cuda = False + self._launch_command = 'singularity' def emit_prepare_commands(self, stagedir): return [] @@ -259,10 +260,23 @@ class Singularity(ContainerPlatform): run_opts += self.options if self.command: - return (f'singularity exec {" ".join(run_opts)} ' + return (f'{self._launch_command} exec {" ".join(run_opts)} ' f'{self.image} {self.command}') - return f'singularity run {" ".join(run_opts)} {self.image}' + return f'{self._launch_command} run {" ".join(run_opts)} {self.image}' + + +class Apptainer(Singularity): + '''Container platform backend for running containers with `Apptainer + <https://apptainer.org/>`__. + + .. versionadded:: 4.0.0 + + ''' + + def __init__(self): + super().__init__() + self._launch_command = 'apptainer' class ContainerPlatformField(fields.TypedField):
reframe-hpc/reframe
0cd78028c73c047ed49314e6cf9f00bf0e76458e
diff --git a/unittests/test_containers.py b/unittests/test_containers.py index ea713465..b4d30724 100644 --- a/unittests/test_containers.py +++ b/unittests/test_containers.py @@ -13,7 +13,8 @@ import reframe.core.containers as containers 'Sarus', 'Sarus+nocommand', 'Sarus+nopull', 'Sarus+mpi', 'Sarus+load', 'Shifter', 'Shifter+nocommand', 'Shifter+mpi', 'Shifter+nopull', 'Shifter+load', - 'Singularity', 'Singularity+nocommand', 'Singularity+cuda' + 'Singularity', 'Singularity+nocommand', 'Singularity+cuda', + 'Apptainer', 'Apptainer+nocommand', 'Apptainer+cuda' ]) def container_variant(request): return request.param @@ -101,7 +102,7 @@ def expected_cmd_mount_points(container_variant): '--mount=type=bind,source="/path/two",destination="/two" ' '--mount=type=bind,source="/foo",destination="/rfm_workdir" ' 'load/library/image:tag cmd') - elif container_variant in {'Singularity', 'Singularity+nopull'}: + elif container_variant == 'Singularity': return ('singularity exec -B"/path/one:/one" ' '-B"/path/two:/two" -B"/foo:/rfm_workdir" ' '--pwd /rfm_workdir image:tag cmd') @@ -113,6 +114,19 @@ def expected_cmd_mount_points(container_variant): return ('singularity run -B"/path/one:/one" ' '-B"/path/two:/two" -B"/foo:/rfm_workdir" ' '--pwd /rfm_workdir image:tag') + elif container_variant == 'Apptainer': + return ('apptainer exec -B"/path/one:/one" ' + '-B"/path/two:/two" -B"/foo:/rfm_workdir" ' + '--pwd /rfm_workdir image:tag cmd') + elif container_variant == 'Apptainer+cuda': + return ('apptainer exec -B"/path/one:/one" ' + '-B"/path/two:/two" -B"/foo:/rfm_workdir" --nv ' + '--pwd /rfm_workdir image:tag cmd') + elif container_variant == 'Apptainer+nocommand': + return ('apptainer run -B"/path/one:/one" ' + '-B"/path/two:/two" -B"/foo:/rfm_workdir" ' + '--pwd /rfm_workdir image:tag') + @pytest.fixture @@ -180,7 +194,7 @@ def expected_cmd_run_opts(container_variant): '--mount=type=bind,source="/path/one",destination="/one" ' '--mount=type=bind,source="/foo",destination="/rfm_workdir" ' '--mpi --foo --bar image:tag cmd') - elif container_variant in {'Singularity'}: + elif container_variant == 'Singularity': return ('singularity exec -B"/path/one:/one" -B"/foo:/rfm_workdir" ' '--foo --bar image:tag cmd') elif container_variant == 'Singularity+cuda': @@ -189,6 +203,15 @@ def expected_cmd_run_opts(container_variant): elif container_variant == 'Singularity+nocommand': return ('singularity run -B"/path/one:/one" -B"/foo:/rfm_workdir" ' '--foo --bar image:tag') + elif container_variant == 'Apptainer': + return ('apptainer exec -B"/path/one:/one" -B"/foo:/rfm_workdir" ' + '--foo --bar image:tag cmd') + elif container_variant == 'Apptainer+cuda': + return ('apptainer exec -B"/path/one:/one" -B"/foo:/rfm_workdir" ' + '--nv --foo --bar image:tag cmd') + elif container_variant == 'Apptainer+nocommand': + return ('apptainer run -B"/path/one:/one" -B"/foo:/rfm_workdir" ' + '--foo --bar image:tag') def test_mount_points(container_platform, expected_cmd_mount_points): @@ -245,6 +268,9 @@ def expected_run_with_commands(container_variant_noopt): elif container_variant_noopt == 'Singularity': return ("singularity exec -B\"/foo:/rfm_workdir\" " "--foo image:tag bash -c 'cmd1; cmd2'") + elif container_variant_noopt == 'Apptainer': + return ("apptainer exec -B\"/foo:/rfm_workdir\" " + "--foo image:tag bash -c 'cmd1; cmd2'") @pytest.fixture @@ -267,6 +293,9 @@ def expected_run_with_workdir(container_variant_noopt): elif container_variant_noopt == 'Singularity': return ('singularity exec -B\"/foo:/rfm_workdir\" --pwd foodir ' '--foo image:tag cmd1') + elif container_variant_noopt == 'Apptainer': + return ('apptainer exec -B\"/foo:/rfm_workdir\" --pwd foodir ' + '--foo image:tag cmd1') def test_run_with_workdir(container_platform_with_opts,
Support apptainer container platform As far as I understand from @teojgo , it should be very easy to add as we already support Singularity.
0.0
0cd78028c73c047ed49314e6cf9f00bf0e76458e
[ "unittests/test_containers.py::test_mount_points[Apptainer]", "unittests/test_containers.py::test_mount_points[Apptainer+nocommand]", "unittests/test_containers.py::test_mount_points[Apptainer+cuda]", "unittests/test_containers.py::test_prepare_command[Apptainer]", "unittests/test_containers.py::test_prepare_command[Apptainer+nocommand]", "unittests/test_containers.py::test_prepare_command[Apptainer+cuda]", "unittests/test_containers.py::test_run_opts[Apptainer]", "unittests/test_containers.py::test_run_opts[Apptainer+nocommand]", "unittests/test_containers.py::test_run_opts[Apptainer+cuda]" ]
[ "unittests/test_containers.py::test_mount_points[Docker]", "unittests/test_containers.py::test_mount_points[Docker+nocommand]", "unittests/test_containers.py::test_mount_points[Docker+nopull]", "unittests/test_containers.py::test_mount_points[Sarus]", "unittests/test_containers.py::test_mount_points[Sarus+nocommand]", "unittests/test_containers.py::test_mount_points[Sarus+nopull]", "unittests/test_containers.py::test_mount_points[Sarus+mpi]", "unittests/test_containers.py::test_mount_points[Sarus+load]", "unittests/test_containers.py::test_mount_points[Shifter]", "unittests/test_containers.py::test_mount_points[Shifter+nocommand]", "unittests/test_containers.py::test_mount_points[Shifter+mpi]", "unittests/test_containers.py::test_mount_points[Shifter+nopull]", "unittests/test_containers.py::test_mount_points[Shifter+load]", "unittests/test_containers.py::test_mount_points[Singularity]", "unittests/test_containers.py::test_mount_points[Singularity+nocommand]", "unittests/test_containers.py::test_mount_points[Singularity+cuda]", "unittests/test_containers.py::test_prepare_command[Docker]", "unittests/test_containers.py::test_prepare_command[Docker+nocommand]", "unittests/test_containers.py::test_prepare_command[Docker+nopull]", "unittests/test_containers.py::test_prepare_command[Sarus]", "unittests/test_containers.py::test_prepare_command[Sarus+nocommand]", "unittests/test_containers.py::test_prepare_command[Sarus+nopull]", "unittests/test_containers.py::test_prepare_command[Sarus+mpi]", "unittests/test_containers.py::test_prepare_command[Sarus+load]", "unittests/test_containers.py::test_prepare_command[Shifter]", "unittests/test_containers.py::test_prepare_command[Shifter+nocommand]", "unittests/test_containers.py::test_prepare_command[Shifter+mpi]", "unittests/test_containers.py::test_prepare_command[Shifter+nopull]", "unittests/test_containers.py::test_prepare_command[Shifter+load]", "unittests/test_containers.py::test_prepare_command[Singularity]", "unittests/test_containers.py::test_prepare_command[Singularity+nocommand]", "unittests/test_containers.py::test_prepare_command[Singularity+cuda]", "unittests/test_containers.py::test_run_opts[Docker]", "unittests/test_containers.py::test_run_opts[Docker+nocommand]", "unittests/test_containers.py::test_run_opts[Docker+nopull]", "unittests/test_containers.py::test_run_opts[Sarus]", "unittests/test_containers.py::test_run_opts[Sarus+nocommand]", "unittests/test_containers.py::test_run_opts[Sarus+nopull]", "unittests/test_containers.py::test_run_opts[Sarus+mpi]", "unittests/test_containers.py::test_run_opts[Sarus+load]", "unittests/test_containers.py::test_run_opts[Shifter]", "unittests/test_containers.py::test_run_opts[Shifter+nocommand]", "unittests/test_containers.py::test_run_opts[Shifter+mpi]", "unittests/test_containers.py::test_run_opts[Shifter+nopull]", "unittests/test_containers.py::test_run_opts[Shifter+load]", "unittests/test_containers.py::test_run_opts[Singularity]", "unittests/test_containers.py::test_run_opts[Singularity+nocommand]", "unittests/test_containers.py::test_run_opts[Singularity+cuda]", "unittests/test_containers.py::test_run_with_workdir[Docker]", "unittests/test_containers.py::test_run_with_workdir[Singularity]", "unittests/test_containers.py::test_run_with_workdir[Sarus]", "unittests/test_containers.py::test_run_with_workdir[Shifter]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-09-30 10:14:45+00:00
bsd-3-clause
5,212
reframe-hpc__reframe-2656
diff --git a/reframe/core/launchers/mpi.py b/reframe/core/launchers/mpi.py index 633a1c05..1a936c99 100644 --- a/reframe/core/launchers/mpi.py +++ b/reframe/core/launchers/mpi.py @@ -3,15 +3,52 @@ # # SPDX-License-Identifier: BSD-3-Clause +import semver +import re + +import reframe.utility.osext as osext from reframe.core.backends import register_launcher from reframe.core.launchers import JobLauncher +from reframe.core.logging import getlogger from reframe.utility import seconds_to_hms @register_launcher('srun') class SrunLauncher(JobLauncher): + def __init__(self): + self.options = [] + self.use_cpus_per_task = True + try: + out = osext.run_command('srun --version') + match = re.search('slurm (\d+)\.(\d+)\.(\d+)', out.stdout) + if match: + # We cannot pass to semver strings like 22.05.1 directly + # because it is not a valid version string for semver. We + # need to remove all the leading zeros. + slurm_version = ( + semver.VersionInfo( + match.group(1), match.group(2), match.group(3) + ) + ) + if slurm_version < semver.VersionInfo(22, 5, 0): + self.use_cpus_per_task = False + else: + getlogger().warning( + 'could not get version of Slurm, --cpus-per-task will be ' + 'set according to the num_cpus_per_task attribute' + ) + except Exception: + getlogger().warning( + 'could not get version of Slurm, --cpus-per-task will be set ' + 'according to the num_cpus_per_task attribute' + ) + def command(self, job): - return ['srun'] + ret = ['srun'] + if self.use_cpus_per_task and job.num_cpus_per_task: + ret.append(f'--cpus-per-task={job.num_cpus_per_task}') + + return ret @register_launcher('ibrun')
reframe-hpc/reframe
93de6f4ce259bdbceba478dbc29e6051c9b2e245
diff --git a/unittests/test_launchers.py b/unittests/test_launchers.py index 66cd9753..987517b0 100644 --- a/unittests/test_launchers.py +++ b/unittests/test_launchers.py @@ -104,6 +104,9 @@ def minimal_job(make_job, launcher): def test_run_command(job): launcher_name = type(job.launcher).registered_name + # This is relevant only for the srun launcher, because it may + # run in different platforms with older versions of Slurm + job.launcher.use_cpus_per_task = True command = job.launcher.run_command(job) if launcher_name == 'alps': assert command == 'aprun -n 4 -N 2 -d 2 -j 0 --foo' @@ -116,7 +119,7 @@ def test_run_command(job): elif launcher_name == 'mpirun': assert command == 'mpirun -np 4 --foo' elif launcher_name == 'srun': - assert command == 'srun --foo' + assert command == 'srun --cpus-per-task=2 --foo' elif launcher_name == 'srunalloc': assert command == ('srun ' '--job-name=fake_job ' @@ -147,6 +150,9 @@ def test_run_command(job): def test_run_command_minimal(minimal_job): launcher_name = type(minimal_job.launcher).registered_name + # This is relevant only for the srun launcher, because it may + # run in different platforms with older versions of Slurm + minimal_job.launcher.use_cpus_per_task = True command = minimal_job.launcher.run_command(minimal_job) if launcher_name == 'alps': assert command == 'aprun -n 1 --foo'
Change of behaviour in Slurm version 22.05 From the release notes: https://slurm.schedmd.com/news.html ``` RELEASE NOTES FOR SLURM VERSION 22.05 ... -- srun will no longer read in SLURM_CPUS_PER_TASK. This means you will implicitly have to specify --cpus-per-task on your srun calls, or set the new SRUN_CPUS_PER_TASK env var to accomplish the same thing. ``` To achieve the same behavior as before we need either to pass explicitly `--cpus-per-task=$SLURM_CPUS_PER_TASK` or set the new `SRUN_CPUS_PER_TASK` env var. ``` export SRUN_CPUS_PER_TASK=$SLURM_CPUS_PER_TASK ``` As far as I understand we can pass the option for older version of slurm as well so there is no need to check for the version.
0.0
93de6f4ce259bdbceba478dbc29e6051c9b2e245
[ "unittests/test_launchers.py::test_run_command[srun]" ]
[ "unittests/test_launchers.py::test_run_command[alps]", "unittests/test_launchers.py::test_run_command[launcherwrapper]", "unittests/test_launchers.py::test_run_command[local]", "unittests/test_launchers.py::test_run_command[mpiexec]", "unittests/test_launchers.py::test_run_command[mpirun]", "unittests/test_launchers.py::test_run_command[srunalloc]", "unittests/test_launchers.py::test_run_command[ssh]", "unittests/test_launchers.py::test_run_command[upcrun]", "unittests/test_launchers.py::test_run_command[upcxx-run]", "unittests/test_launchers.py::test_run_command[lrun]", "unittests/test_launchers.py::test_run_command[lrun-gpu]", "unittests/test_launchers.py::test_run_command_minimal[alps]", "unittests/test_launchers.py::test_run_command_minimal[launcherwrapper]", "unittests/test_launchers.py::test_run_command_minimal[local]", "unittests/test_launchers.py::test_run_command_minimal[mpiexec]", "unittests/test_launchers.py::test_run_command_minimal[mpirun]", "unittests/test_launchers.py::test_run_command_minimal[srun]", "unittests/test_launchers.py::test_run_command_minimal[srunalloc]", "unittests/test_launchers.py::test_run_command_minimal[ssh]", "unittests/test_launchers.py::test_run_command_minimal[upcrun]", "unittests/test_launchers.py::test_run_command_minimal[upcxx-run]", "unittests/test_launchers.py::test_run_command_minimal[lrun]", "unittests/test_launchers.py::test_run_command_minimal[lrun-gpu]" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2022-11-15 08:55:46+00:00
bsd-3-clause
5,213
reframe-hpc__reframe-2688
diff --git a/reframe/frontend/filters.py b/reframe/frontend/filters.py index 20441a18..9edf3ced 100644 --- a/reframe/frontend/filters.py +++ b/reframe/frontend/filters.py @@ -26,6 +26,9 @@ def _have_name(patt): if '@' in patt: # Do an exact match on the unique name return patt.replace('@', '_') == case.check.unique_name + elif patt.startswith('/'): + # Do an exact match on the hashcode + return patt[1:] == case.check.hashcode else: return regex.match(display_name)
reframe-hpc/reframe
32f9e258a22caace2ca7f9fef3b89d6082939b22
diff --git a/unittests/test_cli.py b/unittests/test_cli.py index 6a6ca2da..031ad27d 100644 --- a/unittests/test_cli.py +++ b/unittests/test_cli.py @@ -574,7 +574,7 @@ def test_list_tags(run_reframe): assert returncode == 0 -def test_filtering_multiple_criteria(run_reframe): +def test_filtering_multiple_criteria_name(run_reframe): returncode, stdout, stderr = run_reframe( checkpath=['unittests/resources/checks'], action='list', @@ -586,6 +586,30 @@ def test_filtering_multiple_criteria(run_reframe): assert returncode == 0 +def test_filtering_multiple_criteria_hash(run_reframe): + returncode, stdout, stderr = run_reframe( + checkpath=['unittests/resources/checks'], + action='list', + more_options=['-t', 'foo', '-n', '/2b3e4546'] + ) + assert 'Traceback' not in stdout + assert 'Traceback' not in stderr + assert 'Found 1 check(s)' in stdout + assert returncode == 0 + + +def test_filtering_exclude_hash(run_reframe): + returncode, stdout, stderr = run_reframe( + checkpath=['unittests/resources/checks'], + action='list', + more_options=['-x', '/2b3e4546'] + ) + assert 'Traceback' not in stdout + assert 'Traceback' not in stderr + assert 'Found 8 check(s)' in stdout + assert returncode == 0 + + def test_show_config_all(run_reframe): # Just make sure that this option does not make the frontend crash returncode, stdout, stderr = run_reframe(
`-n` and `-x` are not combined correctly Combining the `-n` and trying to exclude a test using the `-x` it has no effect. How to reproduce: ``` ./bin/reframe -C config/machines.py -c tutorials/cscs-webinar-2022/tests/stream9.py -n stream_scale_test -x /5ccda674 -l ``` ``` - stream_scale_test %threading=4 %stream_binaries.elem_type=float /5ccda674 ^stream_build %elem_type=float ~tresa:default+gnu /bed1cb01 - stream_scale_test %threading=2 %stream_binaries.elem_type=float /a02e1a74 ^stream_build %elem_type=float ~tresa:default+gnu /bed1cb01 - stream_scale_test %threading=1 %stream_binaries.elem_type=float /a54fb2dd ^stream_build %elem_type=float ~tresa:default+gnu /bed1cb01 - stream_scale_test %threading=4 %stream_binaries.elem_type=double /986c1e0b ^stream_build %elem_type=double ~tresa:default+gnu /3d9fd09f - stream_scale_test %threading=2 %stream_binaries.elem_type=double /d976421a ^stream_build %elem_type=double ~tresa:default+gnu /3d9fd09f - stream_scale_test %threading=1 %stream_binaries.elem_type=double /b7f1a81d ^stream_build %elem_type=double ~tresa:default+gnu /3d9fd09f ``` Although the `stream_scale_test` is selected, but the test with `threading=4` (5ccda674) is still selected.
0.0
32f9e258a22caace2ca7f9fef3b89d6082939b22
[ "unittests/test_cli.py::test_filtering_exclude_hash" ]
[ "unittests/test_cli.py::test_check_success", "unittests/test_cli.py::test_check_restore_session_failed", "unittests/test_cli.py::test_check_restore_session_succeeded_test", "unittests/test_cli.py::test_check_restore_session_check_search_path", "unittests/test_cli.py::test_check_success_force_local", "unittests/test_cli.py::test_report_file_with_sessionid", "unittests/test_cli.py::test_report_ends_with_newline", "unittests/test_cli.py::test_check_failure", "unittests/test_cli.py::test_check_setup_failure", "unittests/test_cli.py::test_check_kbd_interrupt", "unittests/test_cli.py::test_check_sanity_failure", "unittests/test_cli.py::test_dont_restage", "unittests/test_cli.py::test_checkpath_symlink", "unittests/test_cli.py::test_performance_check_failure", "unittests/test_cli.py::test_perflogdir_from_env", "unittests/test_cli.py::test_performance_report", "unittests/test_cli.py::test_skip_system_check_option", "unittests/test_cli.py::test_skip_prgenv_check_option", "unittests/test_cli.py::test_sanity_of_checks", "unittests/test_cli.py::test_unknown_system", "unittests/test_cli.py::test_sanity_of_optconfig", "unittests/test_cli.py::test_checkpath_recursion", "unittests/test_cli.py::test_same_output_stage_dir", "unittests/test_cli.py::test_execution_modes", "unittests/test_cli.py::test_timestamp_option", "unittests/test_cli.py::test_timestamp_option_default", "unittests/test_cli.py::test_list_empty_prgenvs_check_and_options", "unittests/test_cli.py::test_list_check_with_empty_prgenvs", "unittests/test_cli.py::test_list_empty_prgenvs_in_check_and_options", "unittests/test_cli.py::test_list_with_details", "unittests/test_cli.py::test_list_concretized", "unittests/test_cli.py::test_list_tags", "unittests/test_cli.py::test_filtering_multiple_criteria_name", "unittests/test_cli.py::test_filtering_multiple_criteria_hash", "unittests/test_cli.py::test_show_config_all", "unittests/test_cli.py::test_show_config_param", "unittests/test_cli.py::test_show_config_unknown_param", "unittests/test_cli.py::test_show_config_null_param", "unittests/test_cli.py::test_verbosity", "unittests/test_cli.py::test_verbosity_with_check", "unittests/test_cli.py::test_quiesce_with_check", "unittests/test_cli.py::test_failure_stats", "unittests/test_cli.py::test_maxfail_option", "unittests/test_cli.py::test_maxfail_invalid_option", "unittests/test_cli.py::test_maxfail_negative", "unittests/test_cli.py::test_repeat_option", "unittests/test_cli.py::test_repeat_invalid_option", "unittests/test_cli.py::test_repeat_negative", "unittests/test_cli.py::test_exec_order[name]", "unittests/test_cli.py::test_exec_order[rname]", "unittests/test_cli.py::test_exec_order[uid]", "unittests/test_cli.py::test_exec_order[ruid]", "unittests/test_cli.py::test_exec_order[random]", "unittests/test_cli.py::test_detect_host_topology", "unittests/test_cli.py::test_detect_host_topology_file", "unittests/test_cli.py::test_external_vars", "unittests/test_cli.py::test_external_vars_invalid_expr", "unittests/test_cli.py::test_fixture_registry_env_sys", "unittests/test_cli.py::test_fixture_resolution", "unittests/test_cli.py::test_dynamic_tests", "unittests/test_cli.py::test_dynamic_tests_filtering" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-11-24 17:03:35+00:00
bsd-3-clause
5,214
reframe-hpc__reframe-2689
diff --git a/reframe/utility/__init__.py b/reframe/utility/__init__.py index aa678bce..f6b7d664 100644 --- a/reframe/utility/__init__.py +++ b/reframe/utility/__init__.py @@ -836,6 +836,9 @@ class _NodeGroup: self.__nodes.append(nid) def __str__(self): + if not self.__nodes: + return self.__name + abbrev = [] encoded = _rl_encode(_delta_encode(self.nodes)) for unit in encoded: @@ -920,7 +923,8 @@ def nodelist_abbrev(nodes): basename, width, nid = _parse_node(n) ng = _NodeGroup(basename, width) node_groups.setdefault(ng, ng) - node_groups[ng].add(nid) + if nid is not None: + node_groups[ng].add(nid) return ','.join(str(ng) for ng in node_groups)
reframe-hpc/reframe
673316e8bc2b0d0a78657d41a0a52bcd62a9afdb
diff --git a/unittests/test_utility.py b/unittests/test_utility.py index 4e9f8fe7..d3392b8d 100644 --- a/unittests/test_utility.py +++ b/unittests/test_utility.py @@ -1800,6 +1800,8 @@ def test_nodelist_utilities(): assert nodelist(['nid01', 'nid10', 'nid20']) == 'nid01,nid10,nid20' assert nodelist([]) == '' assert nodelist(['nid001']) == 'nid001' + assert nodelist(['node']) == 'node' + assert nodelist(['nid001', 'node', 'nid002']) == 'nid00[1-2],node' # Test the reverse operation assert expand('nid00[0-4],nid01[0-4],nid02[0-4]') == sorted(nid_nodes)
Nodelist in failure report adds a `None` at the end This is very easy to reproduce: ``` ./bin/reframe -c unittests/resources/checks/hellocheck.py -S 'prerun_cmds=set -e;foo' -r ``` ``` FAILURE INFO for HelloTest * Expanded name: HelloTest * Description: C Hello World test * System partition: generic:default * Environment: builtin * Stage directory: /Users/karakasv/Repositories/reframe/stage/generic/default/builtin/HelloTest * Node list: tresa.localNone * Job type: local (id=80795) * Dependencies (conceptual): [] * Dependencies (actual): [] * Maintainers: ['VK'] * Failing phase: sanity * Rerun with '-n /2b3e4546 -p builtin --system generic:default -r' * Reason: sanity error: pattern 'Hello, World\\!' not found in 'rfm_job.out' ```
0.0
673316e8bc2b0d0a78657d41a0a52bcd62a9afdb
[ "unittests/test_utility.py::test_nodelist_utilities" ]
[ "unittests/test_utility.py::test_command_success", "unittests/test_utility.py::test_command_success_cmd_seq", "unittests/test_utility.py::test_command_error", "unittests/test_utility.py::test_command_error_cmd_seq", "unittests/test_utility.py::test_command_timeout", "unittests/test_utility.py::test_command_stdin", "unittests/test_utility.py::test_command_async", "unittests/test_utility.py::test_copytree", "unittests/test_utility.py::test_copytree_src_parent_of_dst", "unittests/test_utility.py::test_copytree_dst_notdir[dirs_exist_ok=True]", "unittests/test_utility.py::test_copytree_dst_notdir[dirs_exist_ok=False]", "unittests/test_utility.py::test_copytree_src_notdir[dirs_exist_ok=True]", "unittests/test_utility.py::test_copytree_src_notdir[dirs_exist_ok=False]", "unittests/test_utility.py::test_copytree_src_does_not_exist[dirs_exist_ok=True]", "unittests/test_utility.py::test_copytree_src_does_not_exist[dirs_exist_ok=False]", "unittests/test_utility.py::test_rmtree", "unittests/test_utility.py::test_rmtree_onerror", "unittests/test_utility.py::test_rmtree_error", "unittests/test_utility.py::test_inpath", "unittests/test_utility.py::test_subdirs", "unittests/test_utility.py::test_samefile", "unittests/test_utility.py::test_is_interactive", "unittests/test_utility.py::test_is_url", "unittests/test_utility.py::test_git_repo_hash", "unittests/test_utility.py::test_git_repo_hash_no_git", "unittests/test_utility.py::test_git_repo_hash_no_git_repo", "unittests/test_utility.py::test_git_repo_exists", "unittests/test_utility.py::test_force_remove_file", "unittests/test_utility.py::test_expandvars_dollar", "unittests/test_utility.py::test_expandvars_backticks", "unittests/test_utility.py::test_expandvars_mixed_syntax", "unittests/test_utility.py::test_expandvars_error", "unittests/test_utility.py::test_strange_syntax", "unittests/test_utility.py::test_expandvars_nocmd", "unittests/test_utility.py::test_virtual_copy_nolinks", "unittests/test_utility.py::test_virtual_copy_nolinks_dirs_exist", "unittests/test_utility.py::test_virtual_copy_valid_links", "unittests/test_utility.py::test_virtual_copy_inexistent_links", "unittests/test_utility.py::test_virtual_copy_absolute_paths", "unittests/test_utility.py::test_virtual_copy_irrelevant_paths", "unittests/test_utility.py::test_virtual_copy_linkself", "unittests/test_utility.py::test_virtual_copy_linkparent", "unittests/test_utility.py::test_virtual_copy_symlinks_dirs_exist[symlinks=True]", "unittests/test_utility.py::test_virtual_copy_symlinks_dirs_exist[symlinks=False]", "unittests/test_utility.py::test_import_from_file_load_relpath", "unittests/test_utility.py::test_import_from_file_load_directory", "unittests/test_utility.py::test_import_from_file_load_abspath", "unittests/test_utility.py::test_import_from_file_existing_module_name", "unittests/test_utility.py::test_import_from_file_load_directory_relative", "unittests/test_utility.py::test_import_from_file_load_relative", "unittests/test_utility.py::test_import_from_file_load_twice", "unittests/test_utility.py::test_import_from_file_load_namespace_package", "unittests/test_utility.py::test_ppretty_simple_types", "unittests/test_utility.py::test_ppretty_mixed_types", "unittests/test_utility.py::test_ppretty_obj_print", "unittests/test_utility.py::test_repr_default", "unittests/test_utility.py::test_attrs", "unittests/test_utility.py::test_change_dir_working", "unittests/test_utility.py::test_exception_propagation", "unittests/test_utility.py::test_allx", "unittests/test_utility.py::test_decamelize", "unittests/test_utility.py::test_sanitize", "unittests/test_utility.py::test_scoped_dict_construction", "unittests/test_utility.py::test_scoped_dict_contains", "unittests/test_utility.py::test_scoped_dict_iter_keys", "unittests/test_utility.py::test_scoped_dict_iter_items", "unittests/test_utility.py::test_scoped_dict_iter_values", "unittests/test_utility.py::test_scoped_dict_key_resolution", "unittests/test_utility.py::test_scoped_dict_setitem", "unittests/test_utility.py::test_scoped_dict_delitem", "unittests/test_utility.py::test_scoped_dict_scope_key_name_pseudoconflict", "unittests/test_utility.py::test_scoped_dict_update", "unittests/test_utility.py::test_sequence_view", "unittests/test_utility.py::test_mapping_view", "unittests/test_utility.py::test_shortest_sequence", "unittests/test_utility.py::test_longest_sequence", "unittests/test_utility.py::test_ordered_set_construction", "unittests/test_utility.py::test_ordered_set_construction_empty", "unittests/test_utility.py::test_ordered_set_str", "unittests/test_utility.py::test_ordered_set_construction_error", "unittests/test_utility.py::test_ordered_set_repr", "unittests/test_utility.py::test_ordered_set_operators", "unittests/test_utility.py::test_ordered_set_union", "unittests/test_utility.py::test_ordered_set_intersection", "unittests/test_utility.py::test_ordered_set_difference", "unittests/test_utility.py::test_ordered_set_reversed", "unittests/test_utility.py::test_concat_files", "unittests/test_utility.py::test_unique_abs_paths", "unittests/test_utility.py::test_cray_cdt_version", "unittests/test_utility.py::test_cray_cdt_version_unknown_fmt", "unittests/test_utility.py::test_cray_cdt_version_empty_file", "unittests/test_utility.py::test_cray_cdt_version_no_such_file", "unittests/test_utility.py::test_cray_cle_info", "unittests/test_utility.py::test_cray_cle_info_no_such_file", "unittests/test_utility.py::test_cray_cle_info_missing_parts", "unittests/test_utility.py::test_find_modules[nomod]", "unittests/test_utility.py::test_find_modules_env_mapping[nomod]", "unittests/test_utility.py::test_find_modules_errors", "unittests/test_utility.py::test_jsonext_dump", "unittests/test_utility.py::test_jsonext_dumps", "unittests/test_utility.py::test_jsonext_load", "unittests/test_utility.py::test_attr_validator", "unittests/test_utility.py::test_is_picklable", "unittests/test_utility.py::test_is_copyable", "unittests/test_utility.py::test_is_trivially_callable", "unittests/test_utility.py::test_cached_return_value" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-11-24 23:01:03+00:00
bsd-3-clause
5,215
reframe-hpc__reframe-2788
diff --git a/docs/config_reference.rst b/docs/config_reference.rst index a5277e21..29c4eae1 100644 --- a/docs/config_reference.rst +++ b/docs/config_reference.rst @@ -1400,6 +1400,8 @@ This handler transmits the whole log record, meaning that all the information wi +.. _exec-mode-config: + Execution Mode Configuration ---------------------------- diff --git a/docs/manpage.rst b/docs/manpage.rst index 5e72b4ad..5fc291ef 100644 --- a/docs/manpage.rst +++ b/docs/manpage.rst @@ -489,8 +489,15 @@ Options controlling ReFrame execution ReFrame execution mode to use. - An execution mode is simply a predefined invocation of ReFrame that is set with the :data:`modes` configuration parameter. - If an option is specified both in an execution mode and in the command-line, then command-line takes precedence. + An execution mode is simply a predefined set of options that is set in the :attr:`~modes` :ref:`configuration parameter <exec-mode-config>`. + Additional options can be passed to the command line, in which case they will be combined with the options defined in the selected execution mode. + More specifically, any additional ReFrame options will be *appended* to the command line options of the selected mode. + As a result, if a normal option is specified both inside the execution mode and the in the command line, the command line option will take precedence. + On the other hand, if an option that is allowed to be specified multiple times, e.g., the :option:`-S` option, is passed both inside the execution mode and in the command line, their values will be combined. + For example, if the execution mode ``foo`` defines ``-S modules=foo``, the invocation ``--mode=foo -S num_tasks=10`` is the equivalent of ``-S modules=foo -S num_tasks=10``. + + .. versionchanged:: 4.1 + Options that can be specified multiple times are now combined between execution modes and the command line. .. option:: --repeat=N diff --git a/reframe/frontend/argparse.py b/reframe/frontend/argparse.py index 55f77c51..5c108f2b 100644 --- a/reframe/frontend/argparse.py +++ b/reframe/frontend/argparse.py @@ -9,6 +9,7 @@ import os import reframe.utility.typecheck as typ + # # Notes on the ArgumentParser design # @@ -278,10 +279,20 @@ class ArgumentParser(_ArgumentHolder): # Update parser's defaults with groups' defaults self._update_defaults() + + # Update the parsed options of those from the given namespace and/or + # the defaults for attr, val in options.__dict__.items(): if val is None: - options.__dict__[attr] = self._resolve_attr( - attr, [namespace, self._defaults] - ) + resolved = self._resolve_attr(attr, + [namespace, self._defaults]) + options.__dict__[attr] = resolved + elif self._option_map[attr][2] == 'append': + # 'append' options are combined with those from the given + # namespace, but *not* with the defaults (important) + resolved = self._resolve_attr(attr, [namespace]) + if resolved is not None: + v = options.__dict__[attr] + options.__dict__[attr] = resolved + v return _Namespace(options, self._option_map)
reframe-hpc/reframe
b6e14c6c3a38160a2d63ea5664ee67ec1dbd4243
diff --git a/unittests/test_argparser.py b/unittests/test_argparser.py index 5abdbd80..cc7e80f8 100644 --- a/unittests/test_argparser.py +++ b/unittests/test_argparser.py @@ -74,7 +74,9 @@ def test_parsing(argparser, foo_options, bar_options): '--bar beer --foolist any'.split(), options ) assert 'name' == options.foo - assert ['any'] == options.foolist + + # 'append' options are extended + assert ['gag', 'any'] == options.foolist assert not options.foobar assert not options.unfoo assert 'beer' == options.bar
The `-S` option resets any test variable set in an execution mode using the `-S` option ## How to reproduce Create the following `mode_config.py`: ```python site_configuration = { 'modes': [ { 'name': 'foo', 'options': ['-c unittests/resources/checks/hellocheck.py', '-n ^HelloTest', '-S descr=foo_test'] } ] } ``` and then run the following: ``` reframe -C mode_config.py --mode=foo --describe | jq .[].descr ``` The test description is as expected: ```json "foo_test" ``` However if we set an irrelevant variable, the variable set in the mode will be lost: ``` reframe -C mode_config.py --mode=foo -S num_tasks=1 --describe | jq .[].descr ``` Then the test description is reset: ```json "C Hello World test" ```
0.0
b6e14c6c3a38160a2d63ea5664ee67ec1dbd4243
[ "unittests/test_argparser.py::test_parsing" ]
[ "unittests/test_argparser.py::test_arguments", "unittests/test_argparser.py::test_option_precedence", "unittests/test_argparser.py::test_option_with_config", "unittests/test_argparser.py::test_option_envvar_conversion_error", "unittests/test_argparser.py::test_envvar_option", "unittests/test_argparser.py::test_envvar_option_default_val" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-02-12 20:37:11+00:00
bsd-3-clause
5,216
reframe-hpc__reframe-2790
diff --git a/reframe/frontend/cli.py b/reframe/frontend/cli.py index 9a465ea2..54436755 100644 --- a/reframe/frontend/cli.py +++ b/reframe/frontend/cli.py @@ -737,16 +737,22 @@ def main(): # Update options from the selected execution mode if options.mode: - mode_args = site_config.get(f'modes/@{options.mode}/options') - - # We lexically split the mode options, because otherwise spaces - # will be treated as part of the option argument; see GH bug #1554 - mode_args = list(itertools.chain.from_iterable(shlex.split(m) - for m in mode_args)) - # Parse the mode's options and reparse the command-line - options = argparser.parse_args(mode_args) - options = argparser.parse_args(namespace=options.cmd_options) - options.update_config(site_config) + mode = site_config.get(f'modes/@{options.mode}') + if mode is None: + printer.warning(f'invalid mode: {options.mode!r}; ignoring...') + else: + mode_args = site_config.get(f'modes/@{options.mode}/options') + + # We lexically split the mode options, because otherwise spaces + # will be treated as part of the option argument; + # see GH bug #1554 + mode_args = list( + itertools.chain.from_iterable(shlex.split(m) + for m in mode_args)) + # Parse the mode's options and reparse the command-line + options = argparser.parse_args(mode_args) + options = argparser.parse_args(namespace=options.cmd_options) + options.update_config(site_config) logging.configure_logging(site_config) except (OSError, errors.ConfigError) as e:
reframe-hpc/reframe
ec6acac0d5d63bd25553f6352c057a17d46993fe
diff --git a/unittests/test_cli.py b/unittests/test_cli.py index bfdb59f3..adfe5d0f 100644 --- a/unittests/test_cli.py +++ b/unittests/test_cli.py @@ -478,6 +478,20 @@ def test_execution_modes(run_reframe): assert 'Ran 2/2 test case' in stdout +def test_invalid_mode_warning(run_reframe): + mode = 'invalid' + returncode, stdout, stderr = run_reframe( + action='list', + checkpath=[], + environs=[], + local=False, + mode=mode + ) + assert 'Traceback' not in stdout + assert 'Traceback' not in stderr + assert f'invalid mode: {mode!r}; ignoring' in stdout + + def test_timestamp_option(run_reframe): timefmt = time.strftime('xxx_%F') returncode, stdout, _ = run_reframe(
Issue a warning if an execution mode requested with `--mode` is not found Currently no warning is issued: `reframe --mode=foo -l`.
0.0
ec6acac0d5d63bd25553f6352c057a17d46993fe
[ "unittests/test_cli.py::test_invalid_mode_warning" ]
[ "unittests/test_cli.py::test_check_success", "unittests/test_cli.py::test_check_restore_session_failed", "unittests/test_cli.py::test_check_restore_session_succeeded_test", "unittests/test_cli.py::test_check_restore_session_check_search_path", "unittests/test_cli.py::test_check_success_force_local", "unittests/test_cli.py::test_report_file_with_sessionid", "unittests/test_cli.py::test_report_ends_with_newline", "unittests/test_cli.py::test_check_failure", "unittests/test_cli.py::test_check_setup_failure", "unittests/test_cli.py::test_check_kbd_interrupt", "unittests/test_cli.py::test_check_sanity_failure", "unittests/test_cli.py::test_dont_restage", "unittests/test_cli.py::test_checkpath_symlink", "unittests/test_cli.py::test_performance_check_failure", "unittests/test_cli.py::test_perflogdir_from_env", "unittests/test_cli.py::test_performance_report", "unittests/test_cli.py::test_skip_system_check_option", "unittests/test_cli.py::test_skip_prgenv_check_option", "unittests/test_cli.py::test_sanity_of_checks", "unittests/test_cli.py::test_unknown_system", "unittests/test_cli.py::test_sanity_of_optconfig", "unittests/test_cli.py::test_checkpath_recursion", "unittests/test_cli.py::test_same_output_stage_dir", "unittests/test_cli.py::test_execution_modes", "unittests/test_cli.py::test_timestamp_option", "unittests/test_cli.py::test_timestamp_option_default", "unittests/test_cli.py::test_list_empty_prgenvs_check_and_options", "unittests/test_cli.py::test_list_check_with_empty_prgenvs", "unittests/test_cli.py::test_list_empty_prgenvs_in_check_and_options", "unittests/test_cli.py::test_list_with_details", "unittests/test_cli.py::test_list_concretized", "unittests/test_cli.py::test_list_tags", "unittests/test_cli.py::test_filtering_multiple_criteria_name", "unittests/test_cli.py::test_filtering_multiple_criteria_hash", "unittests/test_cli.py::test_filtering_exclude_hash", "unittests/test_cli.py::test_show_config_all", "unittests/test_cli.py::test_show_config_param", "unittests/test_cli.py::test_show_config_unknown_param", "unittests/test_cli.py::test_show_config_null_param", "unittests/test_cli.py::test_verbosity", "unittests/test_cli.py::test_verbosity_with_check", "unittests/test_cli.py::test_quiesce_with_check", "unittests/test_cli.py::test_failure_stats", "unittests/test_cli.py::test_maxfail_option", "unittests/test_cli.py::test_maxfail_invalid_option", "unittests/test_cli.py::test_maxfail_negative", "unittests/test_cli.py::test_repeat_option", "unittests/test_cli.py::test_repeat_invalid_option", "unittests/test_cli.py::test_repeat_negative", "unittests/test_cli.py::test_exec_order[name]", "unittests/test_cli.py::test_exec_order[rname]", "unittests/test_cli.py::test_exec_order[uid]", "unittests/test_cli.py::test_exec_order[ruid]", "unittests/test_cli.py::test_exec_order[random]", "unittests/test_cli.py::test_detect_host_topology", "unittests/test_cli.py::test_detect_host_topology_file", "unittests/test_cli.py::test_external_vars", "unittests/test_cli.py::test_external_vars_invalid_expr", "unittests/test_cli.py::test_fixture_registry_env_sys", "unittests/test_cli.py::test_fixture_resolution", "unittests/test_cli.py::test_dynamic_tests", "unittests/test_cli.py::test_dynamic_tests_filtering", "unittests/test_cli.py::test_testlib_inherit_fixture_in_different_files" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2023-02-15 15:12:35+00:00
bsd-3-clause
5,217
reframe-hpc__reframe-2876
diff --git a/docs/manpage.rst b/docs/manpage.rst index a59add04..ee2348cd 100644 --- a/docs/manpage.rst +++ b/docs/manpage.rst @@ -650,6 +650,9 @@ Options controlling ReFrame execution - Sequence types: ``-S seqvar=1,2,3,4`` - Mapping types: ``-S mapvar=a:1,b:2,c:3`` + Nested mapping types can also be converted using JSON syntax. + For example, the :attr:`~reframe.core.pipeline.RegressionTest.extra_resources` complex dictionary could be set with ``-S extra_resources='{"gpu": {"num_gpus_per_node":8}}'``. + Conversions to arbitrary objects are also supported. See :class:`~reframe.utility.typecheck.ConvertibleType` for more details. @@ -705,6 +708,9 @@ Options controlling ReFrame execution Allow setting variables in fixtures. + .. versionchanged:: 4.4 + + Allow setting nested mapping types using JSON syntax. .. option:: --skip-performance-check diff --git a/reframe/utility/typecheck.py b/reframe/utility/typecheck.py index 9f27234e..e09bc503 100644 --- a/reframe/utility/typecheck.py +++ b/reframe/utility/typecheck.py @@ -95,6 +95,7 @@ of :class:`List[int]`. import abc import datetime +import json import re @@ -322,19 +323,23 @@ class _MappingType(_BuiltinType): mappping_type = cls._type key_type = cls._key_type value_type = cls._value_type - seq = [] - for key_datum in s.split(','): - try: - k, v = key_datum.split(':') - except ValueError: - # Re-raise as TypeError - raise TypeError( - f'cannot convert string {s!r} to {cls.__name__!r}' - ) from None - - seq.append((key_type(k), value_type(v))) - - return mappping_type(seq) + + try: + items = json.loads(s) + except json.JSONDecodeError: + items = [] + for key_datum in s.split(','): + try: + k, v = key_datum.split(':') + except ValueError: + # Re-raise as TypeError + raise TypeError( + f'cannot convert string {s!r} to {cls.__name__!r}' + ) from None + + items.append((key_type(k), value_type(v))) + + return mappping_type(items) class _StrType(_SequenceType):
reframe-hpc/reframe
53ee447060d0660536cc25ee5eae7d033815fc39
diff --git a/unittests/test_typecheck.py b/unittests/test_typecheck.py index f640a9d7..79342d37 100644 --- a/unittests/test_typecheck.py +++ b/unittests/test_typecheck.py @@ -208,6 +208,14 @@ def test_mapping_type(): # Test conversions assert typ.Dict[str, int]('a:1,b:2') == {'a': 1, 'b': 2} + # Conversion with JSON syntax, for nested dictionaries + s = '{"gpu":{"num_gpus_per_node": 8}, "mpi": {"num_slots": 64}}' + expected = { + 'gpu': {'num_gpus_per_node': 8}, + 'mpi': {'num_slots': 64}, + } + assert typ.Dict[str, typ.Dict[str, object]](s) == expected + with pytest.raises(TypeError): typ.Dict[str, int]('a:1,b')
Feature request: set multi-level dictionaries from the command line I'd like to set `extra_resources` from the command line, but it's currently not possible because it's a dictionary of dictionaries, and there's currently no syntax for that. I should have some time to work on this, but I'd need some directions, in terms of where the code is located (I haven't tried to search it yet) and discuss what the syntax for this would look like.
0.0
53ee447060d0660536cc25ee5eae7d033815fc39
[ "unittests/test_typecheck.py::test_mapping_type" ]
[ "unittests/test_typecheck.py::test_bool_type", "unittests/test_typecheck.py::test_duration_type", "unittests/test_typecheck.py::test_list_type", "unittests/test_typecheck.py::test_set_type", "unittests/test_typecheck.py::test_uniform_tuple_type", "unittests/test_typecheck.py::test_non_uniform_tuple_type", "unittests/test_typecheck.py::test_str_type", "unittests/test_typecheck.py::test_type_names", "unittests/test_typecheck.py::test_custom_types", "unittests/test_typecheck.py::test_custom_types_conversion", "unittests/test_typecheck.py::test_composition_of_types" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-05-02 09:50:50+00:00
bsd-3-clause
5,218
reframe-hpc__reframe-2913
diff --git a/docs/manpage.rst b/docs/manpage.rst index 2320c26f..9de42be8 100644 --- a/docs/manpage.rst +++ b/docs/manpage.rst @@ -545,6 +545,24 @@ Options controlling ReFrame execution .. versionchanged:: 4.1 Options that can be specified multiple times are now combined between execution modes and the command line. +.. option:: -P, --parameterize=[TEST.]VAR=VAL0,VAL1,... + + Parameterize a test on an existing variable. + + This option will create a new test with a parameter named ``$VAR`` with the values given in the comma-separated list ``VAL0,VAL1,...``. + The values will be converted based on the type of the target variable ``VAR``. + The ``TEST.`` prefix will only parameterize the variable ``VAR`` of test ``TEST``. + + The :option:`-P` can be specified multiple times in order to parameterize multiple variables. + + .. note:: + + Conversely to the :option:`-S` option that can set a variable in an arbitrarily nested fixture, + the :option:`-P` option can only parameterize the leaf test: + it cannot be used to parameterize a fixture of the test. + + .. versionadded:: 4.3 + .. option:: --repeat=N Repeat the selected tests ``N`` times. diff --git a/reframe/core/meta.py b/reframe/core/meta.py index 95c35e7b..9654a531 100644 --- a/reframe/core/meta.py +++ b/reframe/core/meta.py @@ -936,20 +936,18 @@ def make_test(name, bases, body, methods=None, module=None, **kwargs): namespace = RegressionTestMeta.__prepare__(name, bases, **kwargs) methods = methods or [] - # Add methods to the body + # Update the namespace with the body elements + # + # NOTE: We do not use `update()` here so as to force the `__setitem__` + # logic + for k, v in body.items(): + namespace[k] = v + + # Add methods to the namespace for m in methods: - body[m.__name__] = m - - # We update the namespace with the body of the class and we explicitly - # call reset on each namespace key to trigger the functionality of - # `__setitem__()` as if the body elements were actually being typed in the - # class definition - namespace.update(body) - for k in list(namespace.keys()): - namespace.reset(k) + namespace[m.__name__] = m cls = RegressionTestMeta(name, bases, namespace, **kwargs) - if not module: # Set the test's module to be that of our callers caller = inspect.currentframe().f_back diff --git a/reframe/frontend/cli.py b/reframe/frontend/cli.py index 55dc6fb7..b3ea5af7 100644 --- a/reframe/frontend/cli.py +++ b/reframe/frontend/cli.py @@ -30,7 +30,8 @@ import reframe.utility.osext as osext import reframe.utility.typecheck as typ from reframe.frontend.testgenerators import (distribute_tests, - getallnodes, repeat_tests) + getallnodes, repeat_tests, + parameterize_tests) from reframe.frontend.executors.policies import (SerialExecutionPolicy, AsynchronousExecutionPolicy) from reframe.frontend.executors import Runner, generate_testcases @@ -436,6 +437,10 @@ def main(): run_options.add_argument( '--mode', action='store', help='Execution mode to use' ) + run_options.add_argument( + '-P', '--parameterize', action='append', metavar='VAR:VAL0,VAL1,...', + default=[], help='Parameterize a test on a set of variables' + ) run_options.add_argument( '--repeat', action='store', metavar='N', help='Repeat selected tests N times' @@ -1096,6 +1101,22 @@ def main(): f'{len(testcases)} remaining' ) + if options.parameterize: + # Prepare parameters + params = {} + for param_spec in options.parameterize: + try: + var, values_spec = param_spec.split('=') + except ValueError: + raise errors.CommandLineError( + f'invalid parameter spec: {param_spec}' + ) from None + else: + params[var] = values_spec.split(',') + + testcases_all = parameterize_tests(testcases, params) + testcases = testcases_all + if options.repeat is not None: try: num_repeats = int(options.repeat)
reframe-hpc/reframe
eaad7e184ce4d99d1d909392be03cb842fbbf3e8
diff --git a/reframe/frontend/testgenerators.py b/reframe/frontend/testgenerators.py index 3b827898..49510536 100644 --- a/reframe/frontend/testgenerators.py +++ b/reframe/frontend/testgenerators.py @@ -9,6 +9,7 @@ import reframe.core.runtime as runtime import reframe.utility as util from reframe.core.decorators import TestRegistry +from reframe.core.fields import make_convertible from reframe.core.logging import getlogger, time_function from reframe.core.meta import make_test from reframe.core.schedulers import Job @@ -48,36 +49,7 @@ def getallnodes(state='all', jobs_cli_options=None): return nodes -def _rfm_pin_run_nodes(obj): - nodelist = getattr(obj, '$nid') - if not obj.local: - obj.job.pin_nodes = nodelist - - -def _rfm_pin_build_nodes(obj): - pin_nodes = getattr(obj, '$nid') - if not obj.local and not obj.build_locally: - obj.build_job.pin_nodes = pin_nodes - - -def make_valid_systems_hook(systems): - '''Returns a function to be used as a hook that sets the - valid systems. - - Since valid_systems change for each generated test, we need to - generate different post-init hooks for each one of them. - ''' - def _rfm_set_valid_systems(obj): - obj.valid_systems = systems - - return _rfm_set_valid_systems - - -@time_function -def distribute_tests(testcases, node_map): - '''Returns new testcases that will be parameterized to run in node of - their partitions based on the nodemap - ''' +def _generate_tests(testcases, gen_fn): tmp_registry = TestRegistry() # We don't want to register the same check for every environment @@ -94,7 +66,41 @@ def distribute_tests(testcases, node_map): variant_info = cls.get_variant_info( check.variant_num, recurse=True ) - nc = make_test( + nc, params = gen_fn(tc) + nc._rfm_custom_prefix = check.prefix + for i in range(nc.num_variants): + # Check if this variant should be instantiated + vinfo = nc.get_variant_info(i, recurse=True) + for p in params: + vinfo['params'].pop(p) + + if vinfo == variant_info: + tmp_registry.add(nc, variant_num=i) + + new_checks = tmp_registry.instantiate_all() + return generate_testcases(new_checks) + + +@time_function +def distribute_tests(testcases, node_map): + def _rfm_pin_run_nodes(obj): + nodelist = getattr(obj, '$nid') + if not obj.local: + obj.job.pin_nodes = nodelist + + def _rfm_pin_build_nodes(obj): + pin_nodes = getattr(obj, '$nid') + if not obj.local and not obj.build_locally: + obj.build_job.pin_nodes = pin_nodes + + def _make_dist_test(testcase): + check, partition, _ = testcase + cls = type(check) + + def _rfm_set_valid_systems(obj): + obj.valid_systems = [partition.fullname] + + return make_test( f'{cls.__name__}_{partition.fullname.replace(":", "_")}', (cls,), { @@ -108,55 +114,70 @@ def distribute_tests(testcases, node_map): builtins.run_before('run')(_rfm_pin_run_nodes), builtins.run_before('compile')(_rfm_pin_build_nodes), # We re-set the valid system in a hook to make sure that it - # will not be overwriten by a parent post-init hook - builtins.run_after('init')( - make_valid_systems_hook([partition.fullname]) - ), + # will not be overwritten by a parent post-init hook + builtins.run_after('init')(_rfm_set_valid_systems), ] - ) - - # We have to set the prefix manually - nc._rfm_custom_prefix = check.prefix - for i in range(nc.num_variants): - # Check if this variant should be instantiated - vinfo = nc.get_variant_info(i, recurse=True) - vinfo['params'].pop('$nid') - if vinfo == variant_info: - tmp_registry.add(nc, variant_num=i) + ), ['$nid'] - new_checks = tmp_registry.instantiate_all() - return generate_testcases(new_checks) + return _generate_tests(testcases, _make_dist_test) @time_function def repeat_tests(testcases, num_repeats): '''Returns new test cases parameterized over their repetition number''' - tmp_registry = TestRegistry() - unique_checks = set() - for tc in testcases: - check = tc.check - if check.is_fixture() or check in unique_checks: - continue - - unique_checks.add(check) - cls = type(check) - variant_info = cls.get_variant_info( - check.variant_num, recurse=True - ) - nc = make_test( + def _make_repeat_test(testcase): + cls = type(testcase.check) + return make_test( f'{cls.__name__}', (cls,), { '$repeat_no': builtins.parameter(range(num_repeats)) } - ) - nc._rfm_custom_prefix = check.prefix - for i in range(nc.num_variants): - # Check if this variant should be instantiated - vinfo = nc.get_variant_info(i, recurse=True) - vinfo['params'].pop('$repeat_no') - if vinfo == variant_info: - tmp_registry.add(nc, variant_num=i) + ), ['$repeat_no'] - new_checks = tmp_registry.instantiate_all() - return generate_testcases(new_checks) + return _generate_tests(testcases, _make_repeat_test) + + +@time_function +def parameterize_tests(testcases, paramvars): + '''Returns new test cases parameterized over specific variables.''' + + def _make_parameterized_test(testcase): + check = testcase.check + cls = type(check) + + # Check that all the requested variables exist + body = {} + for var, values in paramvars.items(): + var_parts = var.split('.') + if len(var_parts) == 1: + var = var_parts[0] + elif len(var_parts) == 2: + var_check, var = var_parts + if var_check != cls.__name__: + continue + else: + getlogger().warning(f'cannot set a variable in a fixture') + continue + + if not var in cls.var_space: + getlogger().warning( + f'variable {var!r} not defined for test ' + f'{check.display_name!r}; ignoring parameterization' + ) + continue + + body[f'${var}'] = builtins.parameter(values) + + def _set_vars(self): + for var in body.keys(): + setattr(self, var[1:], + make_convertible(getattr(self, f'{var}'))) + + return make_test( + f'{cls.__name__}', (cls,), + body=body, + methods=[builtins.run_after('init')(_set_vars)] + ), body.keys() + + return _generate_tests(testcases, _make_parameterized_test) diff --git a/unittests/test_cli.py b/unittests/test_cli.py index 22d80868..d2e9589e 100644 --- a/unittests/test_cli.py +++ b/unittests/test_cli.py @@ -105,6 +105,8 @@ def run_reframe(tmp_path, monkeypatch): argv += ['--list-tags'] elif action == 'help': argv += ['-h'] + elif action == 'describe': + argv += ['--describe'] if perflogdir: argv += ['--perflogdir', perflogdir] @@ -957,6 +959,32 @@ def test_repeat_negative(run_reframe): assert returncode == 1 +def test_parameterize_tests(run_reframe): + returncode, stdout, _ = run_reframe( + more_options=['-P', 'num_tasks=2,4,8', '-n', '^HelloTest'], + checkpath=['unittests/resources/checks/hellocheck.py'], + action='describe' + ) + assert returncode == 0 + + test_descr = json.loads(stdout) + print(json.dumps(test_descr, indent=2)) + num_tasks = {t['num_tasks'] for t in test_descr} + assert num_tasks == {2, 4, 8} + + +def test_parameterize_tests_invalid_params(run_reframe): + returncode, stdout, stderr = run_reframe( + more_options=['-P', 'num_tasks', '-n', '^HelloTest'], + checkpath=['unittests/resources/checks/hellocheck.py'], + action='list' + ) + assert returncode == 1 + assert 'Traceback' not in stdout + assert 'Traceback' not in stderr + assert 'invalid parameter spec' in stdout + + def test_reruns_negative(run_reframe): returncode, stdout, stderr = run_reframe( more_options=['--reruns', '-1'], diff --git a/unittests/test_testgenerators.py b/unittests/test_testgenerators.py index 8c787dc0..810ddde3 100644 --- a/unittests/test_testgenerators.py +++ b/unittests/test_testgenerators.py @@ -5,9 +5,11 @@ import pytest +import reframe as rfm import reframe.frontend.executors as executors import reframe.frontend.filters as filters -from reframe.frontend.testgenerators import (distribute_tests, repeat_tests) +from reframe.frontend.testgenerators import (distribute_tests, + parameterize_tests, repeat_tests) from reframe.frontend.loader import RegressionCheckLoader @@ -69,3 +71,38 @@ def test_repeat_testcases(): testcases = repeat_tests(testcases, 10) assert len(testcases) == 20 + + [email protected] +def hello_test_cls(): + class _HelloTest(rfm.RunOnlyRegressionTest): + message = variable(str, value='world') + number = variable(int, value=1) + valid_systems = ['*'] + valid_prog_environs = ['*'] + executable = 'echo' + executable_opts = ['hello'] + + @run_before('run') + def set_message(self): + self.executable_opts += [self.message, str(self.number)] + + @sanity_function + def validate(self): + return sn.assert_found(rf'hello {self.message} {self.number}', + self.stdout) + + return _HelloTest + + +def test_parameterize_tests(hello_test_cls): + testcases = executors.generate_testcases([hello_test_cls()]) + assert len(testcases) == 1 + + testcases = parameterize_tests( + testcases, {'message': ['x', 'y'], + '_HelloTest.number': [1, '2', 3], + 'UnknownTest.var': 3, + 'unknown': 1} + ) + assert len(testcases) == 6
Allow the parameterisation of a test on an existing variable from the command line It's a common pattern if you have a test with a variable that can take multiple values to be able to parametrise the test on that variable. Currently, this cannot be done from the command line and we have to write some boilerplate code. For example, ```python class MyTest(...): x = variable(int, value=0) class MyTestWithX(MyTest): xx = parameter(range(10)) @run_after('init') def set_x(self): self.x = self.xx ``` Ideally, users should be able to do `--parameterise=x:1,2,3,4`
0.0
eaad7e184ce4d99d1d909392be03cb842fbbf3e8
[ "unittests/test_cli.py::test_parameterize_tests", "unittests/test_cli.py::test_parameterize_tests_invalid_params" ]
[ "unittests/test_cli.py::test_check_success[run]", "unittests/test_cli.py::test_check_success[dry_run]", "unittests/test_cli.py::test_check_restore_session_failed", "unittests/test_cli.py::test_check_restore_session_succeeded_test", "unittests/test_cli.py::test_check_restore_session_check_search_path", "unittests/test_cli.py::test_check_success_force_local[run]", "unittests/test_cli.py::test_check_success_force_local[dry_run]", "unittests/test_cli.py::test_report_file_with_sessionid[run]", "unittests/test_cli.py::test_report_file_with_sessionid[dry_run]", "unittests/test_cli.py::test_report_ends_with_newline[run]", "unittests/test_cli.py::test_report_ends_with_newline[dry_run]", "unittests/test_cli.py::test_report_file_symlink_latest[run]", "unittests/test_cli.py::test_report_file_symlink_latest[dry_run]", "unittests/test_cli.py::test_check_failure", "unittests/test_cli.py::test_check_setup_failure", "unittests/test_cli.py::test_check_kbd_interrupt", "unittests/test_cli.py::test_check_sanity_failure[run]", "unittests/test_cli.py::test_check_sanity_failure[dry_run]", "unittests/test_cli.py::test_dont_restage", "unittests/test_cli.py::test_checkpath_symlink", "unittests/test_cli.py::test_performance_check_failure[run]", "unittests/test_cli.py::test_performance_check_failure[dry_run]", "unittests/test_cli.py::test_perflogdir_from_env", "unittests/test_cli.py::test_performance_report[run]", "unittests/test_cli.py::test_performance_report[dry_run]", "unittests/test_cli.py::test_skip_system_check_option[run]", "unittests/test_cli.py::test_skip_system_check_option[dry_run]", "unittests/test_cli.py::test_skip_prgenv_check_option[run]", "unittests/test_cli.py::test_skip_prgenv_check_option[dry_run]", "unittests/test_cli.py::test_sanity_of_checks", "unittests/test_cli.py::test_unknown_system", "unittests/test_cli.py::test_sanity_of_optconfig", "unittests/test_cli.py::test_checkpath_recursion", "unittests/test_cli.py::test_same_output_stage_dir", "unittests/test_cli.py::test_execution_modes[run]", "unittests/test_cli.py::test_execution_modes[dry_run]", "unittests/test_cli.py::test_invalid_mode_warning", "unittests/test_cli.py::test_timestamp_option", "unittests/test_cli.py::test_timestamp_option_default", "unittests/test_cli.py::test_list_empty_prgenvs_check_and_options", "unittests/test_cli.py::test_list_check_with_empty_prgenvs", "unittests/test_cli.py::test_list_empty_prgenvs_in_check_and_options", "unittests/test_cli.py::test_list_with_details", "unittests/test_cli.py::test_list_concretized", "unittests/test_cli.py::test_list_tags", "unittests/test_cli.py::test_list_tests_with_deps", "unittests/test_cli.py::test_list_tests_with_fixtures", "unittests/test_cli.py::test_filtering_multiple_criteria_name", "unittests/test_cli.py::test_filtering_multiple_criteria_hash", "unittests/test_cli.py::test_filtering_exclude_hash", "unittests/test_cli.py::test_show_config_all", "unittests/test_cli.py::test_show_config_param", "unittests/test_cli.py::test_show_config_unknown_param", "unittests/test_cli.py::test_show_config_null_param", "unittests/test_cli.py::test_verbosity", "unittests/test_cli.py::test_verbosity_with_check", "unittests/test_cli.py::test_quiesce_with_check", "unittests/test_cli.py::test_failure_stats[run]", "unittests/test_cli.py::test_failure_stats[dry_run]", "unittests/test_cli.py::test_maxfail_option", "unittests/test_cli.py::test_maxfail_invalid_option", "unittests/test_cli.py::test_maxfail_negative", "unittests/test_cli.py::test_repeat_option[run]", "unittests/test_cli.py::test_repeat_option[dry_run]", "unittests/test_cli.py::test_repeat_invalid_option", "unittests/test_cli.py::test_repeat_negative", "unittests/test_cli.py::test_reruns_negative", "unittests/test_cli.py::test_reruns_with_duration", "unittests/test_cli.py::test_exec_order[name]", "unittests/test_cli.py::test_exec_order[rname]", "unittests/test_cli.py::test_exec_order[uid]", "unittests/test_cli.py::test_exec_order[ruid]", "unittests/test_cli.py::test_exec_order[random]", "unittests/test_cli.py::test_detect_host_topology", "unittests/test_cli.py::test_detect_host_topology_file", "unittests/test_cli.py::test_external_vars[run]", "unittests/test_cli.py::test_external_vars[dry_run]", "unittests/test_cli.py::test_external_vars_invalid_expr[run]", "unittests/test_cli.py::test_external_vars_invalid_expr[dry_run]", "unittests/test_cli.py::test_fixture_registry_env_sys", "unittests/test_cli.py::test_fixture_resolution[run]", "unittests/test_cli.py::test_fixture_resolution[dry_run]", "unittests/test_cli.py::test_dynamic_tests[run]", "unittests/test_cli.py::test_dynamic_tests[dry_run]", "unittests/test_cli.py::test_dynamic_tests_filtering[run]", "unittests/test_cli.py::test_dynamic_tests_filtering[dry_run]", "unittests/test_cli.py::test_testlib_inherit_fixture_in_different_files", "unittests/test_testgenerators.py::test_distribute_testcases" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-06-06 22:45:26+00:00
bsd-3-clause
5,219
reframe-hpc__reframe-2927
diff --git a/reframe/frontend/dependencies.py b/reframe/frontend/dependencies.py index 2b15ca87..d26f72af 100644 --- a/reframe/frontend/dependencies.py +++ b/reframe/frontend/dependencies.py @@ -205,6 +205,14 @@ def prune_deps(graph, testcases, max_depth=None): if adj not in pruned_graph: unvisited.append(adj) + # Re-calculate the in-degree of the pruned graph nodes + for u in pruned_graph: + u.in_degree = 0 + + for u, adjacent in pruned_graph.items(): + for v in adjacent: + v.in_degree += 1 + return pruned_graph
reframe-hpc/reframe
fe49f64bf4f86e2289e97729cda224f35ce5f05c
diff --git a/unittests/test_dependencies.py b/unittests/test_dependencies.py index d4ffa3b0..2a15e1e3 100644 --- a/unittests/test_dependencies.py +++ b/unittests/test_dependencies.py @@ -697,6 +697,14 @@ def test_prune_deps(default_exec_ctx): assert len(pruned_deps[node('t5')]) == 0 assert len(pruned_deps[node('t0')]) == 0 + # Check the degree of the nodes of the pruned graph + assert in_degree(pruned_deps, node('t0')) == 1 + assert in_degree(pruned_deps, node('t1')) == 2 + assert in_degree(pruned_deps, node('t2')) == 1 + assert in_degree(pruned_deps, node('t3')) == 0 + assert in_degree(pruned_deps, node('t5')) == 1 + assert in_degree(pruned_deps, node('t7')) == 0 + def test_toposort(default_exec_ctx): #
Cleanup is not called for fixtures that are referenced also in test that are not run This can be reproduced with the `fixtures_simple.py` example. The fixture setup is the following there: ```bash ./bin/reframe -c unittests/resources/checks_unlisted/fixtures_simple.py -l ``` ```console - TestB /cc291487 ^HelloTest ~generic 'ff /98821229 ^HelloFixture ~generic 'f /93cd42f0 - TestA /f41565ab ^HelloFixture ~generic 'f /93cd42f0 - HelloTest /2b3e4546 ``` The `HelloFixture` is used by `TestA` and `TestB`. If we execute all the tests, the `HelloFixture`'s stage directory is cleaned up as well: ```bash ls stage/generic/default/builtin/ # empty ``` However, if we only select `TestA` to run, then the `HelloFixture`'s cleanup is not called and the stage directory is not deleted: ```bash ./bin/reframe -c unittests/resources/checks_unlisted/fixtures_simple.py -n ^TestA -r ls stage/generic/default/builtin/ # HelloFixture_93cd42f0/ ``` The reason for that is that the reference count for the fixtures or, generally, the dependencies, is not updated after we filter the tests. As a result, when `TestA` finishes the reference count is 1, so it is not cleaned up. But since we don't execute `TestB`, the resources of `HelloFixture` are leaked.
0.0
fe49f64bf4f86e2289e97729cda224f35ce5f05c
[ "unittests/test_dependencies.py::test_prune_deps" ]
[ "unittests/test_dependencies.py::test_eq_hash", "unittests/test_dependencies.py::test_dependecies_how_functions", "unittests/test_dependencies.py::test_dependecies_how_functions_undoc", "unittests/test_dependencies.py::test_build_deps", "unittests/test_dependencies.py::test_build_deps_empty", "unittests/test_dependencies.py::test_valid_deps", "unittests/test_dependencies.py::test_cyclic_deps", "unittests/test_dependencies.py::test_cyclic_deps_by_env", "unittests/test_dependencies.py::test_validate_deps_empty", "unittests/test_dependencies.py::test_skip_unresolved_deps", "unittests/test_dependencies.py::test_toposort", "unittests/test_dependencies.py::test_toposort_subgraph" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-06-14 22:18:25+00:00
bsd-3-clause
5,220
reframe-hpc__reframe-2931
diff --git a/reframe/core/runtime.py b/reframe/core/runtime.py index 8048876f..9ff0db00 100644 --- a/reframe/core/runtime.py +++ b/reframe/core/runtime.py @@ -9,7 +9,7 @@ import os import functools -from datetime import datetime +import time import reframe.core.config as config import reframe.utility.osext as osext @@ -31,7 +31,7 @@ class RuntimeContext: self._site_config = site_config self._system = System.create(site_config) self._current_run = 0 - self._timestamp = datetime.now() + self._timestamp = time.localtime() def _makedir(self, *dirs, wipeout=False): ret = os.path.join(*dirs) @@ -111,7 +111,7 @@ class RuntimeContext: @property def timestamp(self): timefmt = self.site_config.get('general/0/timestamp_dirs') - return self._timestamp.strftime(timefmt) + return time.strftime(timefmt, self._timestamp) @property def output_prefix(self): diff --git a/reframe/frontend/cli.py b/reframe/frontend/cli.py index b3ea5af7..e0ed7da3 100644 --- a/reframe/frontend/cli.py +++ b/reframe/frontend/cli.py @@ -286,7 +286,7 @@ def main(): envvar='RFM_SAVE_LOG_FILES', configvar='general/save_log_files' ) output_options.add_argument( - '--timestamp', action='store', nargs='?', const='%FT%T', + '--timestamp', action='store', nargs='?', const='%y%m%dT%H%M%S%z', metavar='TIMEFMT', help=('Append a timestamp to the output and stage directory prefixes ' '(default: "%%FT%%T")'),
reframe-hpc/reframe
37d33d8be90892b8e20f894953b9db107b5ffef4
diff --git a/unittests/test_cli.py b/unittests/test_cli.py index d2e9589e..14ba5fc5 100644 --- a/unittests/test_cli.py +++ b/unittests/test_cli.py @@ -553,14 +553,17 @@ def test_timestamp_option(run_reframe): def test_timestamp_option_default(run_reframe): - timefmt_date_part = time.strftime('%FT') returncode, stdout, _ = run_reframe( checkpath=['unittests/resources/checks'], action='list', more_options=['-R', '--timestamp'] ) assert returncode == 0 - assert timefmt_date_part in stdout + + matches = re.findall( + r'(stage|output) directory: .*\/(\d{6}T\d{6}\+\d{4})', stdout + ) + assert len(matches) == 2 def test_list_empty_prgenvs_check_and_options(run_reframe):
Update the default `--timestamp` value so as not to use `:` The paths containing colons are problematic for CMake and Bash's autocompletion does not like them either. It seems that we can still have an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) compliant default timestamp without dashes and colons: `20230422T151055` instead of the current `2023-04-22T15:10:55`
0.0
37d33d8be90892b8e20f894953b9db107b5ffef4
[ "unittests/test_cli.py::test_timestamp_option_default" ]
[ "unittests/test_cli.py::test_check_success[run]", "unittests/test_cli.py::test_check_success[dry_run]", "unittests/test_cli.py::test_check_restore_session_failed", "unittests/test_cli.py::test_check_restore_session_succeeded_test", "unittests/test_cli.py::test_check_restore_session_check_search_path", "unittests/test_cli.py::test_check_success_force_local[run]", "unittests/test_cli.py::test_check_success_force_local[dry_run]", "unittests/test_cli.py::test_report_file_with_sessionid[run]", "unittests/test_cli.py::test_report_file_with_sessionid[dry_run]", "unittests/test_cli.py::test_report_ends_with_newline[run]", "unittests/test_cli.py::test_report_ends_with_newline[dry_run]", "unittests/test_cli.py::test_report_file_symlink_latest[run]", "unittests/test_cli.py::test_report_file_symlink_latest[dry_run]", "unittests/test_cli.py::test_check_failure", "unittests/test_cli.py::test_check_setup_failure", "unittests/test_cli.py::test_check_kbd_interrupt", "unittests/test_cli.py::test_check_sanity_failure[run]", "unittests/test_cli.py::test_check_sanity_failure[dry_run]", "unittests/test_cli.py::test_dont_restage", "unittests/test_cli.py::test_checkpath_symlink", "unittests/test_cli.py::test_performance_check_failure[run]", "unittests/test_cli.py::test_performance_check_failure[dry_run]", "unittests/test_cli.py::test_perflogdir_from_env", "unittests/test_cli.py::test_performance_report[run]", "unittests/test_cli.py::test_performance_report[dry_run]", "unittests/test_cli.py::test_skip_system_check_option[run]", "unittests/test_cli.py::test_skip_system_check_option[dry_run]", "unittests/test_cli.py::test_skip_prgenv_check_option[run]", "unittests/test_cli.py::test_skip_prgenv_check_option[dry_run]", "unittests/test_cli.py::test_sanity_of_checks", "unittests/test_cli.py::test_unknown_system", "unittests/test_cli.py::test_sanity_of_optconfig", "unittests/test_cli.py::test_checkpath_recursion", "unittests/test_cli.py::test_same_output_stage_dir", "unittests/test_cli.py::test_execution_modes[run]", "unittests/test_cli.py::test_execution_modes[dry_run]", "unittests/test_cli.py::test_invalid_mode_warning", "unittests/test_cli.py::test_timestamp_option", "unittests/test_cli.py::test_list_empty_prgenvs_check_and_options", "unittests/test_cli.py::test_list_check_with_empty_prgenvs", "unittests/test_cli.py::test_list_empty_prgenvs_in_check_and_options", "unittests/test_cli.py::test_list_with_details", "unittests/test_cli.py::test_list_concretized", "unittests/test_cli.py::test_list_tags", "unittests/test_cli.py::test_list_tests_with_deps", "unittests/test_cli.py::test_list_tests_with_fixtures", "unittests/test_cli.py::test_filtering_multiple_criteria_name", "unittests/test_cli.py::test_filtering_multiple_criteria_hash", "unittests/test_cli.py::test_filtering_exclude_hash", "unittests/test_cli.py::test_show_config_all", "unittests/test_cli.py::test_show_config_param", "unittests/test_cli.py::test_show_config_unknown_param", "unittests/test_cli.py::test_show_config_null_param", "unittests/test_cli.py::test_verbosity", "unittests/test_cli.py::test_verbosity_with_check", "unittests/test_cli.py::test_quiesce_with_check", "unittests/test_cli.py::test_failure_stats[run]", "unittests/test_cli.py::test_failure_stats[dry_run]", "unittests/test_cli.py::test_maxfail_option", "unittests/test_cli.py::test_maxfail_invalid_option", "unittests/test_cli.py::test_maxfail_negative", "unittests/test_cli.py::test_repeat_option[run]", "unittests/test_cli.py::test_repeat_option[dry_run]", "unittests/test_cli.py::test_repeat_invalid_option", "unittests/test_cli.py::test_repeat_negative", "unittests/test_cli.py::test_parameterize_tests", "unittests/test_cli.py::test_parameterize_tests_invalid_params", "unittests/test_cli.py::test_reruns_negative", "unittests/test_cli.py::test_reruns_with_duration", "unittests/test_cli.py::test_exec_order[name]", "unittests/test_cli.py::test_exec_order[rname]", "unittests/test_cli.py::test_exec_order[uid]", "unittests/test_cli.py::test_exec_order[ruid]", "unittests/test_cli.py::test_exec_order[random]", "unittests/test_cli.py::test_detect_host_topology", "unittests/test_cli.py::test_detect_host_topology_file", "unittests/test_cli.py::test_external_vars[run]", "unittests/test_cli.py::test_external_vars[dry_run]", "unittests/test_cli.py::test_external_vars_invalid_expr[run]", "unittests/test_cli.py::test_external_vars_invalid_expr[dry_run]", "unittests/test_cli.py::test_fixture_registry_env_sys", "unittests/test_cli.py::test_fixture_resolution[run]", "unittests/test_cli.py::test_fixture_resolution[dry_run]", "unittests/test_cli.py::test_dynamic_tests[run]", "unittests/test_cli.py::test_dynamic_tests[dry_run]", "unittests/test_cli.py::test_dynamic_tests_filtering[run]", "unittests/test_cli.py::test_dynamic_tests_filtering[dry_run]", "unittests/test_cli.py::test_testlib_inherit_fixture_in_different_files" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-06-19 23:02:50+00:00
bsd-3-clause
5,221
reframe-hpc__reframe-2992
diff --git a/reframe/core/builtins.py b/reframe/core/builtins.py index 8d4eb599..6f32c3a7 100644 --- a/reframe/core/builtins.py +++ b/reframe/core/builtins.py @@ -37,7 +37,7 @@ def final(fn): # Hook-related builtins -def run_before(stage): +def run_before(stage, *, always_last=False): '''Attach the decorated function before a certain pipeline stage. The function will run just before the specified pipeline stage and it @@ -47,14 +47,25 @@ def run_before(stage): :param stage: The pipeline stage where this function will be attached to. See :ref:`pipeline-hooks` for the list of valid stage values. + + :param always_last: Run this hook always as the last one of the stage. In + a whole test hierarchy, only a single hook can be explicitly pinned at + the end of the same-stage sequence of hooks. If another hook is + declared as ``always_last`` in the same stage, an error will be + issued. + + .. versionchanged:: 4.4 + The ``always_last`` argument was added. + ''' - return hooks.attach_to('pre_' + stage) + + return hooks.attach_to('pre_' + stage, always_last) -def run_after(stage): +def run_after(stage, *, always_last=False): '''Attach the decorated function after a certain pipeline stage. - This is analogous to :func:`~RegressionMixin.run_before`, except that the + This is analogous to :func:`run_before`, except that the hook will execute right after the stage it was attached to. This decorator also supports ``'init'`` as a valid ``stage`` argument, where in this case, the hook will execute right after the test is initialized (i.e. @@ -81,7 +92,7 @@ def run_after(stage): Add support for post-init hooks. ''' - return hooks.attach_to('post_' + stage) + return hooks.attach_to('post_' + stage, always_last) require_deps = hooks.require_deps diff --git a/reframe/core/hooks.py b/reframe/core/hooks.py index 4fde8932..74fab55a 100644 --- a/reframe/core/hooks.py +++ b/reframe/core/hooks.py @@ -9,16 +9,16 @@ import inspect import reframe.utility as util -def attach_to(phase): +def attach_to(phase, always_last): '''Backend function to attach a hook to a given phase. :meta private: ''' def deco(func): if hasattr(func, '_rfm_attach'): - func._rfm_attach.append(phase) + func._rfm_attach.append((phase, always_last)) else: - func._rfm_attach = [phase] + func._rfm_attach = [(phase, always_last)] try: # no need to resolve dependencies independently; this function is @@ -124,6 +124,7 @@ class Hook: @property def stages(self): return self._rfm_attach + # return [stage for stage, _ in self._rfm_attach] def __getattr__(self, attr): return getattr(self.__fn, attr) @@ -179,7 +180,7 @@ class HookRegistry: self.__hooks.discard(h) self.__hooks.add(h) elif hasattr(v, '_rfm_resolve_deps'): - v._rfm_attach = ['post_setup'] + v._rfm_attach = [('post_setup', None)] self.__hooks.add(Hook(v)) def update(self, other, *, denied_hooks=None): diff --git a/reframe/core/pipeline.py b/reframe/core/pipeline.py index ee72e4a0..ac08e2fc 100644 --- a/reframe/core/pipeline.py +++ b/reframe/core/pipeline.py @@ -179,12 +179,32 @@ class RegressionTest(RegressionMixin, jsonext.JSONSerializable): @classmethod def pipeline_hooks(cls): ret = {} + last = {} for hook in cls._rfm_hook_registry: - for stage in hook.stages: - try: - ret[stage].append(hook.fn) - except KeyError: - ret[stage] = [hook.fn] + for stage, always_last in hook.stages: + if always_last: + if stage in last: + hook_name = hook.__qualname__ + pinned_name = last[stage].__qualname__ + raise ReframeSyntaxError( + f'cannot pin hook {hook_name!r} as last ' + f'of stage {stage!r} as {pinned_name!r} ' + f'is already pinned last' + ) + + last[stage] = hook + else: + try: + ret[stage].append(hook.fn) + except KeyError: + ret[stage] = [hook.fn] + + # Append the last hooks + for stage, hook in last.items(): + try: + ret[stage].append(hook.fn) + except KeyError: + ret[stage] = [hook.fn] return ret
reframe-hpc/reframe
0667c8308fb7b8f3933f8c7c489d066c2dc09fb9
diff --git a/docs/regression_test_api.rst b/docs/regression_test_api.rst index a42dcd62..dc5695eb 100644 --- a/docs/regression_test_api.rst +++ b/docs/regression_test_api.rst @@ -67,9 +67,9 @@ The use of this module is required only when creating new tests programmatically .. autodecorator:: reframe.core.builtins.require_deps -.. autodecorator:: reframe.core.builtins.run_after(stage) +.. autodecorator:: reframe.core.builtins.run_after(stage, *, always_last=False) -.. autodecorator:: reframe.core.builtins.run_before(stage) +.. autodecorator:: reframe.core.builtins.run_before(stage, *, always_last=False) .. autodecorator:: reframe.core.builtins.sanity_function diff --git a/unittests/test_meta.py b/unittests/test_meta.py index 53c7095a..060df0bf 100644 --- a/unittests/test_meta.py +++ b/unittests/test_meta.py @@ -189,7 +189,7 @@ def test_hook_attachments(MyMeta): def hook_a(self): pass - @run_before('compile') + @run_before('compile', always_last=True) def hook_b(self): pass @@ -198,11 +198,11 @@ def test_hook_attachments(MyMeta): pass @classmethod - def hook_in_stage(cls, hook, stage): + def hook_in_stage(cls, hook, stage, always_last=False): '''Assert that a hook is in a given registry stage.''' for h in cls._rfm_hook_registry: if h.__name__ == hook: - if stage in h.stages: + if (stage, always_last) in h.stages: return True break @@ -210,7 +210,7 @@ def test_hook_attachments(MyMeta): return False assert Foo.hook_in_stage('hook_a', 'post_setup') - assert Foo.hook_in_stage('hook_b', 'pre_compile') + assert Foo.hook_in_stage('hook_b', 'pre_compile', True) assert Foo.hook_in_stage('hook_c', 'post_run') class Bar(Foo): diff --git a/unittests/test_pipeline.py b/unittests/test_pipeline.py index 0bb95574..56dfb457 100644 --- a/unittests/test_pipeline.py +++ b/unittests/test_pipeline.py @@ -1162,6 +1162,61 @@ def test_overriden_hook_different_stages(HelloTest, local_exec_ctx): assert test.pipeline_hooks() == {'post_setup': [MyTest.foo]} +def test_pinned_hooks(): + @test_util.custom_prefix('unittests/resources/checks') + class X(rfm.RunOnlyRegressionTest): + @run_before('run', always_last=True) + def foo(self): + pass + + @run_after('sanity', always_last=True) + def fooX(self): + '''Check that a single `always_last` hook is registered + correctly.''' + + class Y(X): + @run_before('run') + def bar(self): + pass + + test = Y() + assert test.pipeline_hooks() == { + 'pre_run': [Y.bar, X.foo], + 'post_sanity': [X.fooX] + } + + +def test_pinned_hooks_multiple_last(): + @test_util.custom_prefix('unittests/resources/checks') + class X(rfm.RunOnlyRegressionTest): + @run_before('run', always_last=True) + def foo(self): + pass + + class Y(X): + @run_before('run', always_last=True) + def bar(self): + pass + + with pytest.raises(ReframeSyntaxError): + test = Y() + + +def test_pinned_hooks_multiple_last_inherited(): + @test_util.custom_prefix('unittests/resources/checks') + class X(rfm.RunOnlyRegressionTest): + @run_before('run', always_last=True) + def foo(self): + pass + + @run_before('run', always_last=True) + def bar(self): + pass + + with pytest.raises(ReframeSyntaxError): + test = X() + + def test_disabled_hooks(HelloTest, local_exec_ctx): @test_util.custom_prefix('unittests/resources/checks') class BaseTest(HelloTest):
Allow defining pipeline hooks that run after any same-stage subclass hooks Currently, hooks in the same stage follow the reverse MRO order, i.e., hooks from the parent classes execute first. This is problematic in cases that the base class hooks provide final functionality needed by the subclasses and the subclasses simply need to set some test variables; this is a typical scenario in library tests. Due to this limitation, tests inheriting from a a base class have to be aware of where the base class hooks are placed and define their hooks accordingly. This harms portability. I would like to be able to define a base class test as such: ```python class base_func(...): some_var = variable(str) @run_before('run', when='last') def prepare_run(self): self.executable_opts = ['-f', self.some_var] @rfm.simple_test class my_test(base_func): @run_before('run') def i_cannot_set_this_before(self): self.some_var = 'foo' ``` This example currently fails as `some_var` is undefined when the `prepare_run` hook is executed, but I would like to be able specify that this hooks should be the last of all to run in that phase.
0.0
0667c8308fb7b8f3933f8c7c489d066c2dc09fb9
[ "unittests/test_meta.py::test_hook_attachments", "unittests/test_pipeline.py::test_pinned_hooks_multiple_last", "unittests/test_pipeline.py::test_pinned_hooks_multiple_last_inherited" ]
[ "unittests/test_meta.py::test_class_attr_access", "unittests/test_meta.py::test_directives", "unittests/test_meta.py::test_bind_directive", "unittests/test_meta.py::test_sanity_function_decorator", "unittests/test_meta.py::test_deferrable_decorator", "unittests/test_meta.py::test_final", "unittests/test_meta.py::test_callable_attributes", "unittests/test_meta.py::test_performance_function", "unittests/test_meta.py::test_double_define_performance_function", "unittests/test_meta.py::test_performance_function_errors", "unittests/test_meta.py::test_setting_variables_on_instantiation", "unittests/test_meta.py::test_variants", "unittests/test_meta.py::test_get_info", "unittests/test_meta.py::test_get_variant_nums", "unittests/test_meta.py::test_loggable_attrs", "unittests/test_meta.py::test_inherited_loggable_attrs", "unittests/test_meta.py::test_deprecated_loggable_attrs", "unittests/test_pipeline.py::test_hellocheck_local_prepost_run", "unittests/test_pipeline.py::test_run_only_set_sanity_in_a_hook", "unittests/test_pipeline.py::test_run_only_decorated_sanity", "unittests/test_pipeline.py::test_run_only_no_srcdir", "unittests/test_pipeline.py::test_run_only_srcdir_set_to_none", "unittests/test_pipeline.py::test_executable_is_required", "unittests/test_pipeline.py::test_compile_only_failure", "unittests/test_pipeline.py::test_compile_only_warning", "unittests/test_pipeline.py::test_pinned_test", "unittests/test_pipeline.py::test_supports_sysenv", "unittests/test_pipeline.py::test_sourcesdir_none", "unittests/test_pipeline.py::test_sourcesdir_build_system", "unittests/test_pipeline.py::test_sourcesdir_none_generated_sources", "unittests/test_pipeline.py::test_sourcesdir_none_compile_only", "unittests/test_pipeline.py::test_sourcesdir_none_run_only", "unittests/test_pipeline.py::test_sourcepath_abs", "unittests/test_pipeline.py::test_sourcepath_upref", "unittests/test_pipeline.py::test_sourcepath_non_existent", "unittests/test_pipeline.py::test_extra_resources", "unittests/test_pipeline.py::test_unkown_pre_hook", "unittests/test_pipeline.py::test_unkown_post_hook", "unittests/test_pipeline.py::test_pre_init_hook", "unittests/test_pipeline.py::test_post_init_hook", "unittests/test_pipeline.py::test_setup_hooks", "unittests/test_pipeline.py::test_compile_hooks", "unittests/test_pipeline.py::test_run_hooks", "unittests/test_pipeline.py::test_multiple_hooks", "unittests/test_pipeline.py::test_stacked_hooks", "unittests/test_pipeline.py::test_multiple_inheritance", "unittests/test_pipeline.py::test_inherited_hooks", "unittests/test_pipeline.py::test_inherited_hooks_order", "unittests/test_pipeline.py::test_inherited_hooks_from_instantiated_tests", "unittests/test_pipeline.py::test_overriden_hooks", "unittests/test_pipeline.py::test_overriden_hook_different_stages", "unittests/test_pipeline.py::test_disabled_hooks", "unittests/test_pipeline.py::test_require_deps", "unittests/test_pipeline.py::test_trap_job_errors_without_sanity_patterns", "unittests/test_pipeline.py::test_trap_job_errors_with_sanity_patterns", "unittests/test_pipeline.py::test_sanity_success", "unittests/test_pipeline.py::test_sanity_failure", "unittests/test_pipeline.py::test_sanity_failure_noassert", "unittests/test_pipeline.py::test_sanity_multiple_patterns", "unittests/test_pipeline.py::test_sanity_multiple_files", "unittests/test_pipeline.py::test_performance_failure", "unittests/test_pipeline.py::test_reference_unknown_tag", "unittests/test_pipeline.py::test_reference_unknown_system", "unittests/test_pipeline.py::test_reference_empty", "unittests/test_pipeline.py::test_reference_default", "unittests/test_pipeline.py::test_reference_tag_resolution", "unittests/test_pipeline.py::test_required_reference[classic]", "unittests/test_pipeline.py::test_required_reference[modern]", "unittests/test_pipeline.py::test_reference_deferrable[classic]", "unittests/test_pipeline.py::test_reference_deferrable[modern]", "unittests/test_pipeline.py::test_performance_invalid_value", "unittests/test_pipeline.py::test_perf_patterns_evaluation", "unittests/test_pipeline.py::test_validate_default_perf_variables", "unittests/test_pipeline.py::test_perf_vars_without_reference", "unittests/test_pipeline.py::test_perf_vars_with_reference", "unittests/test_pipeline.py::test_incompat_perf_syntax", "unittests/test_pipeline.py::test_unknown_container_platform", "unittests/test_pipeline.py::test_not_configured_container_platform", "unittests/test_pipeline.py::test_skip_if_no_topo", "unittests/test_pipeline.py::test_make_test_without_builtins", "unittests/test_pipeline.py::test_make_test_with_module", "unittests/test_pipeline.py::test_make_test_with_builtins", "unittests/test_pipeline.py::test_make_test_with_builtins_inline" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-09-10 21:25:05+00:00
bsd-3-clause
5,222
reframe-hpc__reframe-2999
diff --git a/reframe/utility/__init__.py b/reframe/utility/__init__.py index 12edb01e..a381abea 100644 --- a/reframe/utility/__init__.py +++ b/reframe/utility/__init__.py @@ -1275,6 +1275,9 @@ class ScopedDict(UserDict): def __missing__(self, key): raise KeyError(str(key)) + def __rfm_json_encode__(self): + return self.data + @functools.total_ordering class OrderedSet(collections.abc.MutableSet):
reframe-hpc/reframe
b7b9e3ec656bbc430f132d9558ae0360ddfeccdf
diff --git a/unittests/test_utility.py b/unittests/test_utility.py index b89236ce..224d4dc0 100644 --- a/unittests/test_utility.py +++ b/unittests/test_utility.py @@ -799,7 +799,6 @@ def test_scoped_dict_construction(): 'a': {'k1': 3, 'k2': 4}, 'b': {'k3': 5} } - namespace_dict = reframe.utility.ScopedDict() namespace_dict = reframe.utility.ScopedDict(d) # Change local dict and verify that the stored values are not affected @@ -1088,6 +1087,17 @@ def test_scoped_dict_update(): assert scoped_dict == scoped_dict_alt +def test_scoped_dict_json_enc(): + import json + + d = { + 'a': {'k1': 3, 'k2': 4}, + 'b': {'k3': 5} + } + ns_dict = reframe.utility.ScopedDict(d) + assert d == json.loads(jsonext.dumps(ns_dict)) + + def test_sequence_view(): l = util.SequenceView([1, 2, 2]) assert 1 == l[0]
`--describe` option shows `reference` as `null` even if it is defined Example: ```python @rfm.simple_test class stream_test(rfm.RegressionTest): valid_systems = ['*'] valid_prog_environs = ['+openmp'] build_system = 'SingleSource' sourcepath = 'stream.c' reference = { 'tresa': { 'copy_bandwidth': (23000, -0.05, None, 'MB/s') } } ... ``` ```bash ./bin/reframe -C tutorials/cscs-webinar-2022/config/mysettings.py -c tutorials/cscs-webinar-2022/tests/stream6.py --describe | jq .[].reference ``` ```console null null ```
0.0
b7b9e3ec656bbc430f132d9558ae0360ddfeccdf
[ "unittests/test_utility.py::test_scoped_dict_json_enc" ]
[ "unittests/test_utility.py::test_command_success", "unittests/test_utility.py::test_command_success_cmd_seq", "unittests/test_utility.py::test_command_error", "unittests/test_utility.py::test_command_error_cmd_seq", "unittests/test_utility.py::test_command_timeout", "unittests/test_utility.py::test_command_stdin", "unittests/test_utility.py::test_command_async", "unittests/test_utility.py::test_copytree", "unittests/test_utility.py::test_copytree_src_parent_of_dst", "unittests/test_utility.py::test_copytree_dst_notdir[dirs_exist_ok=True]", "unittests/test_utility.py::test_copytree_dst_notdir[dirs_exist_ok=False]", "unittests/test_utility.py::test_copytree_src_notdir[dirs_exist_ok=True]", "unittests/test_utility.py::test_copytree_src_notdir[dirs_exist_ok=False]", "unittests/test_utility.py::test_copytree_src_does_not_exist[dirs_exist_ok=True]", "unittests/test_utility.py::test_copytree_src_does_not_exist[dirs_exist_ok=False]", "unittests/test_utility.py::test_rmtree", "unittests/test_utility.py::test_rmtree_onerror", "unittests/test_utility.py::test_rmtree_error", "unittests/test_utility.py::test_inpath", "unittests/test_utility.py::test_subdirs", "unittests/test_utility.py::test_samefile", "unittests/test_utility.py::test_is_interactive", "unittests/test_utility.py::test_is_url", "unittests/test_utility.py::test_git_repo_hash", "unittests/test_utility.py::test_git_repo_hash_no_git", "unittests/test_utility.py::test_git_repo_hash_no_git_repo", "unittests/test_utility.py::test_git_repo_exists", "unittests/test_utility.py::test_force_remove_file", "unittests/test_utility.py::test_expandvars_dollar", "unittests/test_utility.py::test_expandvars_backticks", "unittests/test_utility.py::test_expandvars_mixed_syntax", "unittests/test_utility.py::test_expandvars_error", "unittests/test_utility.py::test_strange_syntax", "unittests/test_utility.py::test_expandvars_nocmd", "unittests/test_utility.py::test_virtual_copy_nolinks", "unittests/test_utility.py::test_virtual_copy_nolinks_dirs_exist", "unittests/test_utility.py::test_virtual_copy_valid_links", "unittests/test_utility.py::test_virtual_copy_inexistent_links", "unittests/test_utility.py::test_virtual_copy_absolute_paths", "unittests/test_utility.py::test_virtual_copy_irrelevant_paths", "unittests/test_utility.py::test_virtual_copy_linkself", "unittests/test_utility.py::test_virtual_copy_linkparent", "unittests/test_utility.py::test_virtual_copy_symlinks_dirs_exist[symlinks=True]", "unittests/test_utility.py::test_virtual_copy_symlinks_dirs_exist[symlinks=False]", "unittests/test_utility.py::test_import_from_file_load_relpath", "unittests/test_utility.py::test_import_from_file_load_directory", "unittests/test_utility.py::test_import_from_file_load_abspath", "unittests/test_utility.py::test_import_from_file_existing_module_name", "unittests/test_utility.py::test_import_from_file_load_directory_relative", "unittests/test_utility.py::test_import_from_file_load_relative", "unittests/test_utility.py::test_import_from_file_load_twice", "unittests/test_utility.py::test_import_from_file_load_namespace_package", "unittests/test_utility.py::test_import_module", "unittests/test_utility.py::test_ppretty_simple_types", "unittests/test_utility.py::test_ppretty_mixed_types", "unittests/test_utility.py::test_ppretty_obj_print", "unittests/test_utility.py::test_repr_default", "unittests/test_utility.py::test_attrs", "unittests/test_utility.py::test_change_dir_working", "unittests/test_utility.py::test_exception_propagation", "unittests/test_utility.py::test_allx", "unittests/test_utility.py::test_decamelize", "unittests/test_utility.py::test_sanitize", "unittests/test_utility.py::test_scoped_dict_construction", "unittests/test_utility.py::test_scoped_dict_contains", "unittests/test_utility.py::test_scoped_dict_iter_keys", "unittests/test_utility.py::test_scoped_dict_iter_items", "unittests/test_utility.py::test_scoped_dict_iter_values", "unittests/test_utility.py::test_scoped_dict_key_resolution", "unittests/test_utility.py::test_scoped_dict_setitem", "unittests/test_utility.py::test_scoped_dict_delitem", "unittests/test_utility.py::test_scoped_dict_scope_key_name_pseudoconflict", "unittests/test_utility.py::test_scoped_dict_update", "unittests/test_utility.py::test_sequence_view", "unittests/test_utility.py::test_mapping_view", "unittests/test_utility.py::test_shortest_sequence", "unittests/test_utility.py::test_longest_sequence", "unittests/test_utility.py::test_ordered_set_construction", "unittests/test_utility.py::test_ordered_set_construction_empty", "unittests/test_utility.py::test_ordered_set_str", "unittests/test_utility.py::test_ordered_set_construction_error", "unittests/test_utility.py::test_ordered_set_repr", "unittests/test_utility.py::test_ordered_set_operators", "unittests/test_utility.py::test_ordered_set_union", "unittests/test_utility.py::test_ordered_set_intersection", "unittests/test_utility.py::test_ordered_set_difference", "unittests/test_utility.py::test_ordered_set_reversed", "unittests/test_utility.py::test_concat_files", "unittests/test_utility.py::test_unique_abs_paths", "unittests/test_utility.py::test_cray_cdt_version", "unittests/test_utility.py::test_cray_cdt_version_unknown_fmt", "unittests/test_utility.py::test_cray_cdt_version_empty_file", "unittests/test_utility.py::test_cray_cdt_version_no_such_file", "unittests/test_utility.py::test_cray_cle_info", "unittests/test_utility.py::test_cray_cle_info_no_such_file", "unittests/test_utility.py::test_cray_cle_info_missing_parts", "unittests/test_utility.py::test_find_modules[nomod]", "unittests/test_utility.py::test_find_modules_env_mapping[nomod]", "unittests/test_utility.py::test_find_modules_errors", "unittests/test_utility.py::test_jsonext_dump", "unittests/test_utility.py::test_jsonext_dumps", "unittests/test_utility.py::test_jsonext_load", "unittests/test_utility.py::test_attr_validator", "unittests/test_utility.py::test_is_picklable", "unittests/test_utility.py::test_is_copyable", "unittests/test_utility.py::test_is_trivially_callable", "unittests/test_utility.py::test_nodelist_utilities", "unittests/test_utility.py::test_cached_return_value" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-09-16 21:41:42+00:00
bsd-3-clause
5,223
reframe-hpc__reframe-3010
diff --git a/docs/manpage.rst b/docs/manpage.rst index ee2348cd..3b458538 100644 --- a/docs/manpage.rst +++ b/docs/manpage.rst @@ -68,6 +68,21 @@ This happens recursively so that if test ``T1`` depends on ``T2`` and ``T2`` dep The value of this attribute is not required to be non-zero for GPU tests. Tests may or may not make use of it. + .. deprecated:: 4.4 + + Please use ``-E 'not num_gpus_per_node'`` instead. + +.. option:: -E, --filter-expr=EXPR + + Select only tests that satisfy the given expression. + + The expression ``EXPR`` can be any valid Python expression on the test variables or parameters. + For example, ``-E num_tasks > 10`` will select all tests, whose :attr:`~reframe.core.pipeline.RegressionTest.num_tasks` exceeds ``10``. + You may use any test variable in expression, even user-defined. + Multiple variables can also be included such as ``-E num_tasks >= my_param``, where ``my_param`` is user-defined parameter. + + .. versionadded:: 4.4 + .. option:: --failed Select only the failed test cases for a previous run. @@ -77,6 +92,7 @@ This happens recursively so that if test ``T1`` depends on ``T2`` and ``T2`` dep .. versionadded:: 3.4 + .. option:: --gpu-only Select tests that can run on GPUs. @@ -84,6 +100,10 @@ This happens recursively so that if test ``T1`` depends on ``T2`` and ``T2`` dep These are all tests with :attr:`num_gpus_per_node` greater than zero. This option and :option:`--cpu-only` are mutually exclusive. + .. deprecated:: 4.4 + + Please use ``-E num_gpus_per_node`` instead. + .. option:: --maintainer=MAINTAINER Filter tests by maintainer. @@ -101,6 +121,7 @@ This happens recursively so that if test ``T1`` depends on ``T2`` and ``T2`` dep The ``MAINTAINER`` pattern is matched anywhere in the maintainer's name and not at its beginning. If you want to match at the beginning of the name, you should prepend ``^``. + .. option:: -n, --name=NAME Filter tests by name. diff --git a/reframe/frontend/cli.py b/reframe/frontend/cli.py index 7b4ea826..8c59a680 100644 --- a/reframe/frontend/cli.py +++ b/reframe/frontend/cli.py @@ -356,6 +356,10 @@ def main(): metavar='PATTERN', default=[], help='Exclude checks whose name matches PATTERN' ) + select_options.add_argument( + '-E', '--filter-expr', action='store', metavar='EXPR', + help='Select checks that satisfy the expression EXPR' + ) # Action options action_options.add_argument( @@ -1048,6 +1052,16 @@ def main(): f'Filtering test cases(s) by tags: {len(testcases)} remaining' ) + if options.filter_expr: + testcases = filter(filters.validates(options.filter_expr), + testcases) + + testcases = list(testcases) + printer.verbose( + f'Filtering test cases(s) by {options.filter_expr}: ' + f'{len(testcases)} remaining' + ) + # Filter test cases by maintainers for maint in options.maintainers: testcases = filter(filters.have_maintainer(maint), testcases) @@ -1059,8 +1073,12 @@ def main(): sys.exit(1) if options.gpu_only: + printer.warning('the `--gpu-only` option is deprecated; ' + 'please use `-E num_gpus_per_node` instead') testcases = filter(filters.have_gpu_only(), testcases) elif options.cpu_only: + printer.warning('the `--cpu-only` option is deprecated; ' + 'please use `-E "not num_gpus_per_node"` instead') testcases = filter(filters.have_cpu_only(), testcases) testcases = list(testcases) diff --git a/reframe/frontend/filters.py b/reframe/frontend/filters.py index f6e80741..2bcc1052 100644 --- a/reframe/frontend/filters.py +++ b/reframe/frontend/filters.py @@ -109,16 +109,18 @@ def have_maintainer(patt): def have_gpu_only(): - def _fn(case): - # NOTE: This takes into account num_gpus_per_node being None - return case.check.num_gpus_per_node - - return _fn + return validates('num_gpus_per_node') def have_cpu_only(): + return validates('not num_gpus_per_node') + + +def validates(expr): def _fn(case): - # NOTE: This takes into account num_gpus_per_node being None - return not case.check.num_gpus_per_node + try: + return eval(expr, None, case.check.__dict__) + except Exception as err: + raise ReframeError(f'invalid expression `{expr}`') from err return _fn
reframe-hpc/reframe
29047c42cc0a2c682c3939890e3a6214f4ca36bf
diff --git a/unittests/test_cli.py b/unittests/test_cli.py index 14ba5fc5..d5d8f148 100644 --- a/unittests/test_cli.py +++ b/unittests/test_cli.py @@ -698,6 +698,42 @@ def test_filtering_exclude_hash(run_reframe): assert returncode == 0 +def test_filtering_cpu_only(run_reframe): + returncode, stdout, stderr = run_reframe( + checkpath=['unittests/resources/checks/hellocheck.py'], + action='list', + more_options=['--cpu-only'] + ) + assert 'Traceback' not in stdout + assert 'Traceback' not in stderr + assert 'Found 2 check(s)' in stdout + assert returncode == 0 + + +def test_filtering_gpu_only(run_reframe): + returncode, stdout, stderr = run_reframe( + checkpath=['unittests/resources/checks/hellocheck.py'], + action='list', + more_options=['--gpu-only'] + ) + assert 'Traceback' not in stdout + assert 'Traceback' not in stderr + assert 'Found 0 check(s)' in stdout + assert returncode == 0 + + +def test_filtering_by_expr(run_reframe): + returncode, stdout, stderr = run_reframe( + checkpath=['unittests/resources/checks/hellocheck.py'], + action='list', + more_options=['-E num_tasks==1'] + ) + assert 'Traceback' not in stdout + assert 'Traceback' not in stderr + assert 'Found 2 check(s)' in stdout + assert returncode == 0 + + def test_show_config_all(run_reframe): # Just make sure that this option does not make the frontend crash returncode, stdout, stderr = run_reframe( diff --git a/unittests/test_filters.py b/unittests/test_filters.py index 1a06c2f8..30e91b23 100644 --- a/unittests/test_filters.py +++ b/unittests/test_filters.py @@ -11,6 +11,7 @@ import reframe.frontend.executors as executors import reframe.frontend.filters as filters import reframe.utility.sanity as sn import unittests.utility as test_util +from reframe.core.exceptions import ReframeError def count_checks(filter_fn, checks): @@ -140,3 +141,30 @@ def test_invalid_regex(sample_cases): with pytest.raises(errors.ReframeError): count_checks(filters.have_tag('*foo'), sample_cases).evaluate() + + +def test_validates_expr(sample_cases, sample_param_cases): + validates = filters.validates + assert count_checks(validates('"a" in tags'), sample_cases) == 2 + assert count_checks(validates('num_gpus_per_node == 1'), sample_cases) == 2 + assert count_checks(validates('p > 5'), sample_param_cases) == 5 + assert count_checks(validates('p > 5 or p < 1'), sample_param_cases) == 6 + assert count_checks(validates('num_tasks in tags'), sample_cases) == 0 + + +def test_validates_expr_invalid(sample_cases): + validates = filters.validates + + # undefined variables + with pytest.raises(ReframeError): + assert count_checks(validates('foo == 3'), sample_cases) + + # invalid syntax + with pytest.raises(ReframeError): + assert count_checks(validates('num_tasks = 2'), sample_cases) + + with pytest.raises(ReframeError): + assert count_checks(validates('import os'), sample_cases) + + with pytest.raises(ReframeError): + assert count_checks(validates('"foo" i tags'), sample_cases)
Filtering tests based on the number of nodes Today we can filter individual tests based on their name using a regex, but the number of nodes is not always part of the test's name, for instance when `num_nodes` is not parameterized. It would be great to be able to specify a maximum (and possibly minimum) number of nodes to use and have ReFrame automatically ignore tests that do not match the constraint. I discussed with @vkarak and he pointed out related features in https://github.com/reframe-hpc/reframe/issues/2665 and https://github.com/reframe-hpc/reframe/issues/2674, but those features would still require knowledge of which configurations are supported by each test, and thus might require setting different parameters for each test. Whereas the request here would be less fine grained but would not require a priori knowledge about the existing tests, for instance it would work with tests using any of those statements: ```python num_nodes = 1 num_nodes = 16 num_nodes = parameter(range(16)) num_nodes = parameter([10, 40, 80]) num_nodes = parameter([2, 4, 8, 16, 32]) num_nodes = int(os.getenv("TEST_NNODES", "10")) ```
0.0
29047c42cc0a2c682c3939890e3a6214f4ca36bf
[ "unittests/test_cli.py::test_filtering_by_expr" ]
[ "unittests/test_cli.py::test_check_success[run]", "unittests/test_cli.py::test_check_success[dry_run]", "unittests/test_cli.py::test_check_restore_session_failed", "unittests/test_cli.py::test_check_restore_session_succeeded_test", "unittests/test_cli.py::test_check_restore_session_check_search_path", "unittests/test_cli.py::test_check_success_force_local[run]", "unittests/test_cli.py::test_check_success_force_local[dry_run]", "unittests/test_cli.py::test_report_file_with_sessionid[run]", "unittests/test_cli.py::test_report_file_with_sessionid[dry_run]", "unittests/test_cli.py::test_report_ends_with_newline[run]", "unittests/test_cli.py::test_report_ends_with_newline[dry_run]", "unittests/test_cli.py::test_report_file_symlink_latest[run]", "unittests/test_cli.py::test_report_file_symlink_latest[dry_run]", "unittests/test_cli.py::test_check_failure", "unittests/test_cli.py::test_check_setup_failure", "unittests/test_cli.py::test_check_kbd_interrupt", "unittests/test_cli.py::test_check_sanity_failure[run]", "unittests/test_cli.py::test_check_sanity_failure[dry_run]", "unittests/test_cli.py::test_dont_restage", "unittests/test_cli.py::test_checkpath_symlink", "unittests/test_cli.py::test_performance_check_failure[run]", "unittests/test_cli.py::test_performance_check_failure[dry_run]", "unittests/test_cli.py::test_perflogdir_from_env", "unittests/test_cli.py::test_performance_report[run]", "unittests/test_cli.py::test_performance_report[dry_run]", "unittests/test_cli.py::test_skip_system_check_option[run]", "unittests/test_cli.py::test_skip_system_check_option[dry_run]", "unittests/test_cli.py::test_skip_prgenv_check_option[run]", "unittests/test_cli.py::test_skip_prgenv_check_option[dry_run]", "unittests/test_cli.py::test_sanity_of_checks", "unittests/test_cli.py::test_unknown_system", "unittests/test_cli.py::test_sanity_of_optconfig", "unittests/test_cli.py::test_checkpath_recursion", "unittests/test_cli.py::test_same_output_stage_dir", "unittests/test_cli.py::test_execution_modes[run]", "unittests/test_cli.py::test_execution_modes[dry_run]", "unittests/test_cli.py::test_invalid_mode_warning", "unittests/test_cli.py::test_timestamp_option", "unittests/test_cli.py::test_timestamp_option_default", "unittests/test_cli.py::test_list_empty_prgenvs_check_and_options", "unittests/test_cli.py::test_list_check_with_empty_prgenvs", "unittests/test_cli.py::test_list_empty_prgenvs_in_check_and_options", "unittests/test_cli.py::test_list_with_details", "unittests/test_cli.py::test_list_concretized", "unittests/test_cli.py::test_list_tags", "unittests/test_cli.py::test_list_tests_with_deps", "unittests/test_cli.py::test_list_tests_with_fixtures", "unittests/test_cli.py::test_filtering_multiple_criteria_name", "unittests/test_cli.py::test_filtering_multiple_criteria_hash", "unittests/test_cli.py::test_filtering_exclude_hash", "unittests/test_cli.py::test_filtering_cpu_only", "unittests/test_cli.py::test_filtering_gpu_only", "unittests/test_cli.py::test_show_config_all", "unittests/test_cli.py::test_show_config_param", "unittests/test_cli.py::test_show_config_unknown_param", "unittests/test_cli.py::test_show_config_null_param", "unittests/test_cli.py::test_verbosity", "unittests/test_cli.py::test_verbosity_with_check", "unittests/test_cli.py::test_quiesce_with_check", "unittests/test_cli.py::test_failure_stats[run]", "unittests/test_cli.py::test_failure_stats[dry_run]", "unittests/test_cli.py::test_maxfail_option", "unittests/test_cli.py::test_maxfail_invalid_option", "unittests/test_cli.py::test_maxfail_negative", "unittests/test_cli.py::test_repeat_option[run]", "unittests/test_cli.py::test_repeat_option[dry_run]", "unittests/test_cli.py::test_repeat_invalid_option", "unittests/test_cli.py::test_repeat_negative", "unittests/test_cli.py::test_parameterize_tests", "unittests/test_cli.py::test_parameterize_tests_invalid_params", "unittests/test_cli.py::test_reruns_negative", "unittests/test_cli.py::test_reruns_with_duration", "unittests/test_cli.py::test_exec_order[name]", "unittests/test_cli.py::test_exec_order[rname]", "unittests/test_cli.py::test_exec_order[uid]", "unittests/test_cli.py::test_exec_order[ruid]", "unittests/test_cli.py::test_exec_order[random]", "unittests/test_cli.py::test_detect_host_topology", "unittests/test_cli.py::test_detect_host_topology_file", "unittests/test_cli.py::test_external_vars[run]", "unittests/test_cli.py::test_external_vars[dry_run]", "unittests/test_cli.py::test_external_vars_invalid_expr[run]", "unittests/test_cli.py::test_external_vars_invalid_expr[dry_run]", "unittests/test_cli.py::test_fixture_registry_env_sys", "unittests/test_cli.py::test_fixture_resolution[run]", "unittests/test_cli.py::test_fixture_resolution[dry_run]", "unittests/test_cli.py::test_dynamic_tests[run]", "unittests/test_cli.py::test_dynamic_tests[dry_run]", "unittests/test_cli.py::test_dynamic_tests_filtering[run]", "unittests/test_cli.py::test_dynamic_tests_filtering[dry_run]", "unittests/test_cli.py::test_testlib_inherit_fixture_in_different_files" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-10-02 21:36:45+00:00
bsd-3-clause
5,224
reframe-hpc__reframe-3058
diff --git a/reframe/core/launchers/mpi.py b/reframe/core/launchers/mpi.py index 9bb19ba3..fce5bf84 100644 --- a/reframe/core/launchers/mpi.py +++ b/reframe/core/launchers/mpi.py @@ -126,12 +126,6 @@ class SrunAllocationLauncher(JobLauncher): h, m, s = seconds_to_hms(job.time_limit) ret += ['--time=%d:%d:%d' % (h, m, s)] - if job.stdout: - ret += ['--output=%s' % job.stdout] - - if job.stderr: - ret += ['--error=%s' % job.stderr] - if job.num_tasks: ret += ['--ntasks=%s' % str(job.num_tasks)]
reframe-hpc/reframe
20a1a5e6a9c1fcc5a7b5bcfb202e9d1d2dcdd86a
diff --git a/unittests/test_launchers.py b/unittests/test_launchers.py index 6a59a4db..1ea59d95 100644 --- a/unittests/test_launchers.py +++ b/unittests/test_launchers.py @@ -130,8 +130,6 @@ def test_run_command(job): assert command == ('srun ' '--job-name=fake_job ' '--time=0:10:0 ' - '--output=fake_stdout ' - '--error=fake_stderr ' '--ntasks=4 ' '--ntasks-per-node=2 ' '--ntasks-per-core=1 ' @@ -177,8 +175,6 @@ def test_run_command_minimal(minimal_job): elif launcher_name == 'srunalloc': assert command == ('srun ' '--job-name=fake_job ' - '--output=fake_job.out ' - '--error=fake_job.err ' '--ntasks=1 ' '--foo') elif launcher_name == 'ssh':
`srunalloc` launcher makes reframe lose track of the `prerun_cmds` etc. output The problem is that the test's standard output/error files are passed as options to the `srun` command, thus overriding the output of the whole script. Here's how to reproduce: Configuration file (you can add the `access` options accordingly if needed): ```python site_configuration = { 'systems': [ { 'name': 'system', 'hostnames': ['nid0'], 'partitions': [ { 'name': 'part', 'scheduler': 'local', 'launcher': 'srunalloc', 'environs': ['builtin'] } ] } ] } ``` And the test file: ```python import reframe as rfm import reframe.utility.sanity as sn @rfm.simple_test class srunalloc_fail_test(rfm.RunOnlyRegressionTest): executable = 'hostname' prerun_cmds = ['echo hello'] valid_systems = ['system:part'] valid_prog_environs = ['*'] @sanity_function def validate(self): return sn.assert_found('hello', self.stdout) ``` Running the test fails as follows: ```console SUMMARY OF FAILURES ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- FAILURE INFO for srunalloc_fail_test (run: 1/1) * Description: * System partition: system:part * Environment: builtin * Stage directory: /home/user/reframe/stage/system/part/builtin/srunalloc_fail_test * Node list: nid0001 * Job type: local (id=83006) * Dependencies (conceptual): [] * Dependencies (actual): [] * Maintainers: [] * Failing phase: sanity * Rerun with '-n /b359e5de -p builtin --system system:part -r' * Reason: sanity error: pattern 'hello' not found in 'rfm_job.out' --- rfm_job.out (first 10 lines) --- nid0001 --- rfm_job.out --- --- rfm_job.err (first 10 lines) --- --- rfm_job.err --- ``` Removing the `--output` and `--error` srun options here solves the issue: https://github.com/reframe-hpc/reframe/blob/a3366b6c9ab7567df295fc9f30bae13fd5fa7dfc/reframe/core/launchers/mpi.py#L129-L133
0.0
20a1a5e6a9c1fcc5a7b5bcfb202e9d1d2dcdd86a
[ "unittests/test_launchers.py::test_run_command[srunalloc]", "unittests/test_launchers.py::test_run_command_minimal[srunalloc]" ]
[ "unittests/test_launchers.py::test_run_command[alps]", "unittests/test_launchers.py::test_run_command[clush]", "unittests/test_launchers.py::test_run_command[launcherwrapper]", "unittests/test_launchers.py::test_run_command[local]", "unittests/test_launchers.py::test_run_command[mpiexec]", "unittests/test_launchers.py::test_run_command[mpirun]", "unittests/test_launchers.py::test_run_command[pdsh]", "unittests/test_launchers.py::test_run_command[srun]", "unittests/test_launchers.py::test_run_command[ssh]", "unittests/test_launchers.py::test_run_command[upcrun]", "unittests/test_launchers.py::test_run_command[upcxx-run]", "unittests/test_launchers.py::test_run_command[lrun]", "unittests/test_launchers.py::test_run_command[lrun-gpu]", "unittests/test_launchers.py::test_run_command_minimal[alps]", "unittests/test_launchers.py::test_run_command_minimal[clush]", "unittests/test_launchers.py::test_run_command_minimal[launcherwrapper]", "unittests/test_launchers.py::test_run_command_minimal[local]", "unittests/test_launchers.py::test_run_command_minimal[mpiexec]", "unittests/test_launchers.py::test_run_command_minimal[mpirun]", "unittests/test_launchers.py::test_run_command_minimal[pdsh]", "unittests/test_launchers.py::test_run_command_minimal[srun]", "unittests/test_launchers.py::test_run_command_minimal[ssh]", "unittests/test_launchers.py::test_run_command_minimal[upcrun]", "unittests/test_launchers.py::test_run_command_minimal[upcxx-run]", "unittests/test_launchers.py::test_run_command_minimal[lrun]", "unittests/test_launchers.py::test_run_command_minimal[lrun-gpu]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-11-30 22:11:11+00:00
bsd-3-clause
5,225
reframe-hpc__reframe-3070
diff --git a/reframe/frontend/cli.py b/reframe/frontend/cli.py index 8c59a680..2a257c11 100644 --- a/reframe/frontend/cli.py +++ b/reframe/frontend/cli.py @@ -791,7 +791,7 @@ def main(): if options.mode: mode = site_config.get(f'modes/@{options.mode}') if mode is None: - printer.warning(f'invalid mode: {options.mode!r}; ignoring...') + raise errors.ReframeError(f'invalid mode: {options.mode!r}') else: mode_args = site_config.get(f'modes/@{options.mode}/options') @@ -811,6 +811,10 @@ def main(): printer.error(f'failed to load configuration: {e}') printer.info(logfiles_message()) sys.exit(1) + except errors.ReframeError as e: + printer.error(str(e)) + printer.info(logfiles_message()) + sys.exit(1) printer.colorize = site_config.get('general/0/colorize') if not restrict_logging():
reframe-hpc/reframe
67d07ffb791312f858675e1afe302e5e7fccf5c3
diff --git a/unittests/test_cli.py b/unittests/test_cli.py index d5d8f148..b468658f 100644 --- a/unittests/test_cli.py +++ b/unittests/test_cli.py @@ -527,7 +527,7 @@ def test_execution_modes(run_reframe, run_action): assert 'Ran 1/1 test case' in stdout -def test_invalid_mode_warning(run_reframe): +def test_invalid_mode_error(run_reframe): mode = 'invalid' returncode, stdout, stderr = run_reframe( action='list', @@ -538,7 +538,8 @@ def test_invalid_mode_warning(run_reframe): ) assert 'Traceback' not in stdout assert 'Traceback' not in stderr - assert f'invalid mode: {mode!r}; ignoring' in stdout + assert returncode == 1 + assert f'ERROR: invalid mode: {mode!r}' in stdout def test_timestamp_option(run_reframe):
Passing an invalid mode should issue an error not a warning Currently, passing an inexistent mode with the `--mode` option, only a warning will be issued and the option will be ignored. This is error prone, as reframe continues execution as if the option wasn't passed.
0.0
67d07ffb791312f858675e1afe302e5e7fccf5c3
[ "unittests/test_cli.py::test_invalid_mode_error" ]
[ "unittests/test_cli.py::test_check_success[run]", "unittests/test_cli.py::test_check_success[dry_run]", "unittests/test_cli.py::test_check_restore_session_failed", "unittests/test_cli.py::test_check_restore_session_succeeded_test", "unittests/test_cli.py::test_check_restore_session_check_search_path", "unittests/test_cli.py::test_check_success_force_local[run]", "unittests/test_cli.py::test_check_success_force_local[dry_run]", "unittests/test_cli.py::test_report_file_with_sessionid[run]", "unittests/test_cli.py::test_report_file_with_sessionid[dry_run]", "unittests/test_cli.py::test_report_ends_with_newline[run]", "unittests/test_cli.py::test_report_ends_with_newline[dry_run]", "unittests/test_cli.py::test_report_file_symlink_latest[run]", "unittests/test_cli.py::test_report_file_symlink_latest[dry_run]", "unittests/test_cli.py::test_check_failure", "unittests/test_cli.py::test_check_setup_failure", "unittests/test_cli.py::test_check_kbd_interrupt", "unittests/test_cli.py::test_check_sanity_failure[run]", "unittests/test_cli.py::test_check_sanity_failure[dry_run]", "unittests/test_cli.py::test_dont_restage", "unittests/test_cli.py::test_checkpath_symlink", "unittests/test_cli.py::test_performance_check_failure[run]", "unittests/test_cli.py::test_performance_check_failure[dry_run]", "unittests/test_cli.py::test_perflogdir_from_env", "unittests/test_cli.py::test_performance_report[run]", "unittests/test_cli.py::test_performance_report[dry_run]", "unittests/test_cli.py::test_skip_system_check_option[run]", "unittests/test_cli.py::test_skip_system_check_option[dry_run]", "unittests/test_cli.py::test_skip_prgenv_check_option[run]", "unittests/test_cli.py::test_skip_prgenv_check_option[dry_run]", "unittests/test_cli.py::test_sanity_of_checks", "unittests/test_cli.py::test_unknown_system", "unittests/test_cli.py::test_sanity_of_optconfig", "unittests/test_cli.py::test_checkpath_recursion", "unittests/test_cli.py::test_same_output_stage_dir", "unittests/test_cli.py::test_execution_modes[run]", "unittests/test_cli.py::test_execution_modes[dry_run]", "unittests/test_cli.py::test_timestamp_option", "unittests/test_cli.py::test_timestamp_option_default", "unittests/test_cli.py::test_list_empty_prgenvs_check_and_options", "unittests/test_cli.py::test_list_check_with_empty_prgenvs", "unittests/test_cli.py::test_list_empty_prgenvs_in_check_and_options", "unittests/test_cli.py::test_list_with_details", "unittests/test_cli.py::test_list_concretized", "unittests/test_cli.py::test_list_tags", "unittests/test_cli.py::test_list_tests_with_deps", "unittests/test_cli.py::test_list_tests_with_fixtures", "unittests/test_cli.py::test_filtering_multiple_criteria_name", "unittests/test_cli.py::test_filtering_multiple_criteria_hash", "unittests/test_cli.py::test_filtering_exclude_hash", "unittests/test_cli.py::test_filtering_cpu_only", "unittests/test_cli.py::test_filtering_gpu_only", "unittests/test_cli.py::test_filtering_by_expr", "unittests/test_cli.py::test_show_config_all", "unittests/test_cli.py::test_show_config_param", "unittests/test_cli.py::test_show_config_unknown_param", "unittests/test_cli.py::test_show_config_null_param", "unittests/test_cli.py::test_verbosity", "unittests/test_cli.py::test_verbosity_with_check", "unittests/test_cli.py::test_quiesce_with_check", "unittests/test_cli.py::test_failure_stats[run]", "unittests/test_cli.py::test_failure_stats[dry_run]", "unittests/test_cli.py::test_maxfail_option", "unittests/test_cli.py::test_maxfail_invalid_option", "unittests/test_cli.py::test_maxfail_negative", "unittests/test_cli.py::test_repeat_option[run]", "unittests/test_cli.py::test_repeat_option[dry_run]", "unittests/test_cli.py::test_repeat_invalid_option", "unittests/test_cli.py::test_repeat_negative", "unittests/test_cli.py::test_parameterize_tests", "unittests/test_cli.py::test_parameterize_tests_invalid_params", "unittests/test_cli.py::test_reruns_negative", "unittests/test_cli.py::test_reruns_with_duration", "unittests/test_cli.py::test_exec_order[name]", "unittests/test_cli.py::test_exec_order[rname]", "unittests/test_cli.py::test_exec_order[uid]", "unittests/test_cli.py::test_exec_order[ruid]", "unittests/test_cli.py::test_exec_order[random]", "unittests/test_cli.py::test_detect_host_topology", "unittests/test_cli.py::test_detect_host_topology_file", "unittests/test_cli.py::test_external_vars[run]", "unittests/test_cli.py::test_external_vars[dry_run]", "unittests/test_cli.py::test_external_vars_invalid_expr[run]", "unittests/test_cli.py::test_external_vars_invalid_expr[dry_run]", "unittests/test_cli.py::test_fixture_registry_env_sys", "unittests/test_cli.py::test_fixture_resolution[run]", "unittests/test_cli.py::test_fixture_resolution[dry_run]", "unittests/test_cli.py::test_dynamic_tests[run]", "unittests/test_cli.py::test_dynamic_tests[dry_run]", "unittests/test_cli.py::test_dynamic_tests_filtering[run]", "unittests/test_cli.py::test_dynamic_tests_filtering[dry_run]", "unittests/test_cli.py::test_testlib_inherit_fixture_in_different_files" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2023-12-04 21:35:26+00:00
bsd-3-clause
5,226
reframe-hpc__reframe-3114
diff --git a/reframe/core/launchers/__init__.py b/reframe/core/launchers/__init__.py index 662facc9..d1c10b2c 100644 --- a/reframe/core/launchers/__init__.py +++ b/reframe/core/launchers/__init__.py @@ -4,12 +4,16 @@ # SPDX-License-Identifier: BSD-3-Clause import abc - -import reframe.core.fields as fields import reframe.utility.typecheck as typ +from reframe.core.meta import RegressionTestMeta +from reframe.core.warnings import user_deprecation_warning + +class _JobLauncherMeta(RegressionTestMeta, abc.ABCMeta): + '''Job launcher metaclass.''' -class JobLauncher(abc.ABC): + +class JobLauncher(metaclass=_JobLauncherMeta): '''Abstract base class for job launchers. A job launcher is the executable that actually launches a distributed @@ -30,7 +34,28 @@ class JobLauncher(abc.ABC): #: #: :type: :class:`List[str]` #: :default: ``[]`` - options = fields.TypedField(typ.List[str]) + options = variable(typ.List[str], value=[]) + + #: Optional modifier of the launcher command. + #: + #: This will be combined with the :attr:`modifier_options` and prepended to + #: the parallel launch command. + #: + #: :type: :class:`str` + #: :default: ``''`` + #: + #: .. versionadded:: 4.6.0 + modifier = variable(str, value='') + + #: Options to be passed to the launcher :attr:`modifier`. + #: + #: If the modifier is empty, these options will be ignored. + #: + #: :type: :clas:`List[str]` + #: :default: ``[]`` + #: + #: :versionadded:: 4.6.0 + modifier_options = variable(typ.List[str], value=[]) def __init__(self): self.options = [] @@ -53,7 +78,13 @@ class JobLauncher(abc.ABC): :param job: a job descriptor. :returns: the launcher command as a string. ''' - return ' '.join(self.command(job) + self.options) + cmd_tokens = [] + if self.modifier: + cmd_tokens.append(self.modifier) + cmd_tokens += self.modifier_options + + cmd_tokens += self.command(job) + self.options + return ' '.join(cmd_tokens) class LauncherWrapper(JobLauncher): @@ -90,8 +121,13 @@ class LauncherWrapper(JobLauncher): ''' - def __init__(self, target_launcher, wrapper_command, wrapper_options=[]): + def __init__(self, target_launcher, wrapper_command, wrapper_options=None): super().__init__() + user_deprecation_warning("'LauncherWrapper is deprecated; " + "please use the launcher's 'modifier' and " + "'modifier_options' instead") + + wrapper_options = wrapper_options or [] self.options = target_launcher.options self._target_launcher = target_launcher self._wrapper_command = [wrapper_command] + wrapper_options diff --git a/reframe/core/launchers/rsh.py b/reframe/core/launchers/rsh.py index 984f11a5..d858caf1 100644 --- a/reframe/core/launchers/rsh.py +++ b/reframe/core/launchers/rsh.py @@ -29,5 +29,11 @@ class SSHLauncher(JobLauncher): return ['ssh', '-o BatchMode=yes'] + ssh_opts + [hostname] def run_command(self, job): + cmd_tokens = [] + if self.modifier: + cmd_tokens.append(self.modifier) + cmd_tokens += self.modifier_options + # self.options is processed specially above - return ' '.join(self.command(job)) + cmd_tokens += self.command(job) + return ' '.join(cmd_tokens)
reframe-hpc/reframe
98d812420597a39029786c0bae0d0690836efe62
diff --git a/unittests/test_launchers.py b/unittests/test_launchers.py index 5d84ce7f..561dffd8 100644 --- a/unittests/test_launchers.py +++ b/unittests/test_launchers.py @@ -8,6 +8,7 @@ import pytest import reframe.core.launchers as launchers from reframe.core.backends import getlauncher from reframe.core.schedulers import Job, JobScheduler +from reframe.core.warnings import ReframeDeprecationWarning @pytest.fixture(params=[ @@ -20,9 +21,10 @@ def launcher(request): # convenience for the rest of the unit tests wrapper_cls = launchers.LauncherWrapper wrapper_cls.registered_name = 'launcherwrapper' - return wrapper_cls( - getlauncher('alps')(), 'ddt', ['--offline'] - ) + with pytest.warns(ReframeDeprecationWarning): + return wrapper_cls( + getlauncher('alps')(), 'ddt', ['--offline'] + ) return getlauncher(request.param)() @@ -154,38 +156,52 @@ def test_run_command(job): assert command == 'lrun -N 2 -T 2 -M "-gpu" --foo' -def test_run_command_minimal(minimal_job): [email protected](params=['modifiers', 'plain']) +def use_modifiers(request): + return request.param == 'modifiers' + + +def test_run_command_minimal(minimal_job, use_modifiers): launcher_name = type(minimal_job.launcher).registered_name # This is relevant only for the srun launcher, because it may # run in different platforms with older versions of Slurm minimal_job.launcher.use_cpus_per_task = True + if use_modifiers and launcher_name != 'launcherwrapper': + minimal_job.launcher.modifier = 'ddt' + minimal_job.launcher.modifier_options = ['--offline'] + prefix = 'ddt --offline' + if launcher_name != 'local': + prefix += ' ' + else: + prefix = '' + command = minimal_job.launcher.run_command(minimal_job) if launcher_name == 'alps': - assert command == 'aprun -n 1 --foo' + assert command == f'{prefix}aprun -n 1 --foo' elif launcher_name == 'launcherwrapper': assert command == 'ddt --offline aprun -n 1 --foo' elif launcher_name == 'local': - assert command == '' + assert command == f'{prefix}' elif launcher_name == 'mpiexec': - assert command == 'mpiexec -n 1 --foo' + assert command == f'{prefix}mpiexec -n 1 --foo' elif launcher_name == 'mpirun': - assert command == 'mpirun -np 1 --foo' + assert command == f'{prefix}mpirun -np 1 --foo' elif launcher_name == 'srun': - assert command == 'srun --foo' + assert command == f'{prefix}srun --foo' elif launcher_name == 'srunalloc': - assert command == ('srun ' + assert command == (f'{prefix}srun ' '--job-name=fake_job ' '--ntasks=1 ' '--foo') elif launcher_name == 'ssh': - assert command == 'ssh -o BatchMode=yes --foo host' + assert command == f'{prefix}ssh -o BatchMode=yes --foo host' elif launcher_name in ('clush', 'pdsh'): - assert command == f'{launcher_name} -w host --foo' + assert command == f'{prefix}{launcher_name} -w host --foo' elif launcher_name == 'upcrun': - assert command == 'upcrun -n 1 --foo' + assert command == f'{prefix}upcrun -n 1 --foo' elif launcher_name == 'upcxx-run': - assert command == 'upcxx-run -n 1 --foo' + assert command == f'{prefix}upcxx-run -n 1 --foo' elif launcher_name == 'lrun': - assert command == 'lrun -N 1 -T 1 --foo' + assert command == f'{prefix}lrun -N 1 -T 1 --foo' elif launcher_name == 'lrun-gpu': - assert command == 'lrun -N 1 -T 1 -M "-gpu" --foo' + assert command == f'{prefix}lrun -N 1 -T 1 -M "-gpu" --foo'
Support parallel launcher modifiers in an easier way This is currently possible using the `LauncherWrapper` but the syntax is a bit cumbersome. I suggest using extending the `Launcher` itself with something like `launcher.modifier = 'gdb'` and `launcher.modifier_opts = ['--args', ...]`.
0.0
98d812420597a39029786c0bae0d0690836efe62
[ "unittests/test_launchers.py::test_run_command[launcherwrapper]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-alps]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-clush]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-launcherwrapper]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-local]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-mpiexec]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-mpirun]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-pdsh]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-srun]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-srunalloc]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-ssh]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-upcrun]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-upcxx-run]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-lrun]", "unittests/test_launchers.py::test_run_command_minimal[modifiers-lrun-gpu]", "unittests/test_launchers.py::test_run_command_minimal[plain-launcherwrapper]" ]
[ "unittests/test_launchers.py::test_run_command[alps]", "unittests/test_launchers.py::test_run_command[clush]", "unittests/test_launchers.py::test_run_command[local]", "unittests/test_launchers.py::test_run_command[mpiexec]", "unittests/test_launchers.py::test_run_command[mpirun]", "unittests/test_launchers.py::test_run_command[pdsh]", "unittests/test_launchers.py::test_run_command[srun]", "unittests/test_launchers.py::test_run_command[srunalloc]", "unittests/test_launchers.py::test_run_command[ssh]", "unittests/test_launchers.py::test_run_command[upcrun]", "unittests/test_launchers.py::test_run_command[upcxx-run]", "unittests/test_launchers.py::test_run_command[lrun]", "unittests/test_launchers.py::test_run_command[lrun-gpu]", "unittests/test_launchers.py::test_run_command_minimal[plain-alps]", "unittests/test_launchers.py::test_run_command_minimal[plain-clush]", "unittests/test_launchers.py::test_run_command_minimal[plain-local]", "unittests/test_launchers.py::test_run_command_minimal[plain-mpiexec]", "unittests/test_launchers.py::test_run_command_minimal[plain-mpirun]", "unittests/test_launchers.py::test_run_command_minimal[plain-pdsh]", "unittests/test_launchers.py::test_run_command_minimal[plain-srun]", "unittests/test_launchers.py::test_run_command_minimal[plain-srunalloc]", "unittests/test_launchers.py::test_run_command_minimal[plain-ssh]", "unittests/test_launchers.py::test_run_command_minimal[plain-upcrun]", "unittests/test_launchers.py::test_run_command_minimal[plain-upcxx-run]", "unittests/test_launchers.py::test_run_command_minimal[plain-lrun]", "unittests/test_launchers.py::test_run_command_minimal[plain-lrun-gpu]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2024-02-10 21:42:12+00:00
bsd-3-clause
5,227
regionmask__regionmask-486
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 84b6128..5bcd1f9 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -16,18 +16,16 @@ v0.12.0 (unreleased) Breaking Changes ~~~~~~~~~~~~~~~~ +- Deprecated ``Regions.coords`` because they are no longer used (:pull:`486`). - Removed support for Python 3.8 (:pull:`465`). - Removed the ``regionmask.defined_regions.natural_earth`` regions which were deprecated - in v0.9.0 (:pull:`479`) + in v0.9.0, (:pull:`479`) - Removed the deprecated ``subsample`` keyword from the plotting methods (:pull:`468`). -- Removed the deprecated ``_ar6_pre_revisions`` regions (:pull:`#466`). +- Removed the deprecated ``_ar6_pre_revisions`` regions (:pull:`466`). Enhancements ~~~~~~~~~~~~ -Deprecations -~~~~~~~~~~~~ - New regions ~~~~~~~~~~~ diff --git a/regionmask/core/regions.py b/regionmask/core/regions.py index 976fc06..c5f8db9 100644 --- a/regionmask/core/regions.py +++ b/regionmask/core/regions.py @@ -4,6 +4,7 @@ # Date: import copy +import warnings import geopandas as gp import numpy as np @@ -242,6 +243,13 @@ class Regions: @property def coords(self): + warnings.warn( + "`Regions.coords` has been deprecated in v0.12.0 and will be removed. " + "Please raise an issue if you have an use case for them.", + FutureWarning, + stacklevel=2, + ) + """list of coordinates of the region vertices as numpy array""" return [r.coords for r in self.regions.values()]
regionmask/regionmask
45b940956bd1998c08a894769da4eb0373dad2a8
diff --git a/regionmask/tests/test_Regions.py b/regionmask/tests/test_Regions.py index 4aae512..ab01969 100644 --- a/regionmask/tests/test_Regions.py +++ b/regionmask/tests/test_Regions.py @@ -84,6 +84,13 @@ def test_abbrevs(test_regions): assert test_regions.abbrevs == ["uSq1", "uSq2"] +def test_coords_deprecated(): + + with pytest.warns(FutureWarning, match="`Regions.coords` has been deprecated"): + test_regions1.coords + + [email protected]("ignore:`Regions.coords` has been deprecated") def test_coords(): # passing numpy coords does not automatically close the coords assert np.allclose(test_regions1.coords, [outl1, outl2]) diff --git a/regionmask/tests/test_mask.py b/regionmask/tests/test_mask.py index c873309..8996f0e 100644 --- a/regionmask/tests/test_mask.py +++ b/regionmask/tests/test_mask.py @@ -86,7 +86,7 @@ def test_mask_wrong_number_fill(func): ) with pytest.raises(ValueError, match="`numbers` and `coords` must have"): - func(dummy_ds.lon, dummy_ds.lat, dummy_region.coords, numbers=[5]) + func(dummy_ds.lon, dummy_ds.lat, dummy_region.polygons, numbers=[5]) @pytest.mark.parametrize("method", MASK_METHODS) diff --git a/regionmask/tests/test_plot.py b/regionmask/tests/test_plot.py index 48d8f22..3a47594 100644 --- a/regionmask/tests/test_plot.py +++ b/regionmask/tests/test_plot.py @@ -65,7 +65,8 @@ r3 = Regions([multipoly]) r4 = Regions(outlines, numbers=[0.0, 1.0]) # a region with segments longer than 1, use Polygon to close the coords -r_large = regionmask.Regions([Polygon(c * 10) for c in r1.coords]) +_p = [Polygon(np.array(c.exterior.coords) * 10) for c in r1.polygons] +r_large = regionmask.Regions(_p) # create a polygon with a hole interior1_closed = ((0.2, 0.2), (0.2, 0.45), (0.45, 0.45), (0.45, 0.2), (0.2, 0.2)) @@ -372,8 +373,12 @@ def test_plot_lines_tolerance_None(plotfunc): ax = func(tolerance=None) lines = ax.collections[0].get_paths() - np.testing.assert_allclose(lines[0].vertices, r_large.coords[0]) - np.testing.assert_allclose(lines[1].vertices, r_large.coords[1]) + np.testing.assert_allclose( + lines[0].vertices, r_large.polygons[0].exterior.coords + ) + np.testing.assert_allclose( + lines[1].vertices, r_large.polygons[1].exterior.coords + ) @requires_matplotlib @@ -421,7 +426,7 @@ def test_plot_lines_from_poly(plotfunc): lines = ax.collections[0].get_segments() assert len(lines) == 2 - assert np.allclose(lines[0], r2.coords[0]) + assert np.allclose(lines[0], r2.polygons[0].exterior.coords) # -----------------------------------------------------------------------------
remove Regions.coords? Deprecate `Regions.coords`? I don't think it's needed anywhere anymore?
0.0
45b940956bd1998c08a894769da4eb0373dad2a8
[ "regionmask/tests/test_Regions.py::test_coords_deprecated" ]
[ "regionmask/tests/test_Regions.py::test_regions_single_region", "regionmask/tests/test_Regions.py::test_len[test_regions0]", "regionmask/tests/test_Regions.py::test_len[test_regions1]", "regionmask/tests/test_Regions.py::test_len[test_regions2]", "regionmask/tests/test_Regions.py::test_len[test_regions3]", "regionmask/tests/test_Regions.py::test_name[test_regions0]", "regionmask/tests/test_Regions.py::test_name[test_regions1]", "regionmask/tests/test_Regions.py::test_name[test_regions2]", "regionmask/tests/test_Regions.py::test_name[test_regions3]", "regionmask/tests/test_Regions.py::test_numbers[test_regions0-numbers0]", "regionmask/tests/test_Regions.py::test_numbers[test_regions1-numbers1]", "regionmask/tests/test_Regions.py::test_numbers[test_regions2-numbers2]", "regionmask/tests/test_Regions.py::test_numbers[test_regions3-numbers3]", "regionmask/tests/test_Regions.py::test_names[test_regions0]", "regionmask/tests/test_Regions.py::test_names[test_regions1]", "regionmask/tests/test_Regions.py::test_names[test_regions2]", "regionmask/tests/test_Regions.py::test_names[test_regions3]", "regionmask/tests/test_Regions.py::test_abbrevs[test_regions0]", "regionmask/tests/test_Regions.py::test_abbrevs[test_regions1]", "regionmask/tests/test_Regions.py::test_abbrevs[test_regions2]", "regionmask/tests/test_Regions.py::test_abbrevs[test_regions3]", "regionmask/tests/test_Regions.py::test_coords", "regionmask/tests/test_Regions.py::test_bounds[test_regions0]", "regionmask/tests/test_Regions.py::test_bounds[test_regions1]", "regionmask/tests/test_Regions.py::test_bounds[test_regions2]", "regionmask/tests/test_Regions.py::test_bounds[test_regions3]", "regionmask/tests/test_Regions.py::test_bounds_global[test_regions0]", "regionmask/tests/test_Regions.py::test_bounds_global[test_regions1]", "regionmask/tests/test_Regions.py::test_bounds_global[test_regions2]", "regionmask/tests/test_Regions.py::test_bounds_global[test_regions3]", "regionmask/tests/test_Regions.py::test_polygon[test_regions0]", "regionmask/tests/test_Regions.py::test_polygon[test_regions1]", "regionmask/tests/test_Regions.py::test_polygon[test_regions2]", "regionmask/tests/test_Regions.py::test_polygon[test_regions3]", "regionmask/tests/test_Regions.py::test_centroid[test_regions0]", "regionmask/tests/test_Regions.py::test_centroid[test_regions1]", "regionmask/tests/test_Regions.py::test_centroid[test_regions2]", "regionmask/tests/test_Regions.py::test_centroid[test_regions3]", "regionmask/tests/test_Regions.py::test_centroid_multipolygon", "regionmask/tests/test_Regions.py::test_map_keys_one[test_regions0-0]", "regionmask/tests/test_Regions.py::test_map_keys_one[test_regions1-1]", "regionmask/tests/test_Regions.py::test_map_keys_one[test_regions2-2]", "regionmask/tests/test_Regions.py::test_map_keys_one[test_regions3-0.0]", "regionmask/tests/test_Regions.py::test_map_keys_np_integer", "regionmask/tests/test_Regions.py::test_map_keys_several[test_regions0-numbers0]", "regionmask/tests/test_Regions.py::test_map_keys_several[test_regions1-numbers1]", "regionmask/tests/test_Regions.py::test_map_keys_several[test_regions2-numbers2]", "regionmask/tests/test_Regions.py::test_map_keys_several[test_regions3-numbers3]", "regionmask/tests/test_Regions.py::test_map_keys_mixed", "regionmask/tests/test_Regions.py::test_map_keys_unique", "regionmask/tests/test_Regions.py::test_subset_to_OneRegion[test_regions0-0]", "regionmask/tests/test_Regions.py::test_subset_to_OneRegion[test_regions1-1]", "regionmask/tests/test_Regions.py::test_subset_to_OneRegion[test_regions2-2]", "regionmask/tests/test_Regions.py::test_subset_to_OneRegion[test_regions3-0.0]", "regionmask/tests/test_Regions.py::test_Regions_iter[test_region0]", "regionmask/tests/test_Regions.py::test_Regions_iter[test_region1]", "regionmask/tests/test_Regions.py::test_Regions_iter[test_region2]", "regionmask/tests/test_Regions.py::test_Regions_iter[test_region3]", "regionmask/tests/test_Regions.py::test_subset_to_Regions[test_regions0-0]", "regionmask/tests/test_Regions.py::test_subset_to_Regions[test_regions1-1]", "regionmask/tests/test_Regions.py::test_subset_to_Regions[test_regions2-2]", "regionmask/tests/test_Regions.py::test_subset_to_Regions[test_regions3-0.0]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-None-None-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-None-None-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-None-names-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-None-names-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-None-names2-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-None-names2-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs-None-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs-None-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs-names-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs-names-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs-names2-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs-names2-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs2-None-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs2-None-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs2-names-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs2-names-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs2-names2-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[None-abbrevs2-names2-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-None-None-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-None-None-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-None-names-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-None-names-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-None-names2-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-None-names2-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs-None-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs-None-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs-names-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs-names-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs-names2-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs-names2-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs2-None-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs2-None-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs2-names-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs2-names-numbers1]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs2-names2-None]", "regionmask/tests/test_Regions.py::test_optional_arguments[name-abbrevs2-names2-numbers1]", "regionmask/tests/test_Regions.py::test_lon_extent", "regionmask/tests/test_Regions.py::test_error_on_non_numeric[numbers0]", "regionmask/tests/test_Regions.py::test_error_on_non_numeric[numbers1]", "regionmask/tests/test_Regions.py::test_regions_sorted", "regionmask/tests/test_Regions.py::test_getitem_sorted[numbers0]", "regionmask/tests/test_Regions.py::test_getitem_sorted[numbers1]", "regionmask/tests/test_Regions.py::test_overlap[None]", "regionmask/tests/test_Regions.py::test_overlap[True]", "regionmask/tests/test_Regions.py::test_overlap[False]", "regionmask/tests/test_Regions.py::test_overlap_getitem[None]", "regionmask/tests/test_Regions.py::test_overlap_getitem[True]", "regionmask/tests/test_Regions.py::test_overlap_getitem[False]", "regionmask/tests/test_Regions.py::test_to_geodataframe", "regionmask/tests/test_Regions.py::test_to_series", "regionmask/tests/test_Regions.py::test_to_dataframe", "regionmask/tests/test_Regions.py::test_from_geodataframe", "regionmask/tests/test_Regions.py::test_from_geodataframe_roundtrip[True]", "regionmask/tests/test_Regions.py::test_from_geodataframe_roundtrip[False]", "regionmask/tests/test_Regions.py::test_from_geodataframe_roundtrip[None]", "regionmask/tests/test_mask.py::test_mask_func[_mask_rasterize]", "regionmask/tests/test_mask.py::test_mask_func[_mask_shapely]", "regionmask/tests/test_mask.py::test_mask_func[_mask_shapely_v2]", "regionmask/tests/test_mask.py::test_mask_wrong_number_fill[_mask_rasterize]", "regionmask/tests/test_mask.py::test_mask_wrong_number_fill[_mask_shapely]", "regionmask/tests/test_mask.py::test_mask_wrong_number_fill[_mask_shapely_v2]", "regionmask/tests/test_mask.py::test_mask[rasterize]", "regionmask/tests/test_mask.py::test_mask[shapely]", "regionmask/tests/test_mask.py::test_mask_method_internal[rasterize]", "regionmask/tests/test_mask.py::test_mask_method_internal[shapely]", "regionmask/tests/test_mask.py::test_missing_pygeos_error", "regionmask/tests/test_mask.py::test_mask_xr_keep_name[rasterize]", "regionmask/tests/test_mask.py::test_mask_xr_keep_name[shapely]", "regionmask/tests/test_mask.py::test_mask_poly_z_value[rasterize]", "regionmask/tests/test_mask.py::test_mask_poly_z_value[shapely]", "regionmask/tests/test_mask.py::test_mask_xarray_name[rasterize]", "regionmask/tests/test_mask.py::test_mask_xarray_name[shapely]", "regionmask/tests/test_mask.py::test_mask_unequal_ndim[ndims0]", "regionmask/tests/test_mask.py::test_mask_unequal_ndim[ndims1]", "regionmask/tests/test_mask.py::test_mask_unequal_2D_shapes", "regionmask/tests/test_mask.py::test_mask_ndim_ne_1_2[0]", "regionmask/tests/test_mask.py::test_mask_ndim_ne_1_2[3]", "regionmask/tests/test_mask.py::test_mask_ndim_ne_1_2[4]", "regionmask/tests/test_mask.py::test_mask_obj[rasterize-lat-lon]", "regionmask/tests/test_mask.py::test_mask_obj[rasterize-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_obj[rasterize-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_obj[rasterize-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_obj[shapely-lat-lon]", "regionmask/tests/test_mask.py::test_mask_obj[shapely-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_obj[shapely-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_obj[shapely-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_wrap[rasterize]", "regionmask/tests/test_mask.py::test_mask_wrap[shapely]", "regionmask/tests/test_mask.py::test_wrap_lon_no_error_wrap_lon_false[mask]", "regionmask/tests/test_mask.py::test_wrap_lon_no_error_wrap_lon_false[mask_3D]", "regionmask/tests/test_mask.py::test_wrap_lon_error_wrap_lon[mask]", "regionmask/tests/test_mask.py::test_wrap_lon_error_wrap_lon[mask_3D]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon0-extent0-rasterize]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon0-extent0-shapely]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon1-extent1-rasterize]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon1-extent1-shapely]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon2-extent2-rasterize]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon2-extent2-shapely]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon3-extent3-rasterize]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon3-extent3-shapely]", "regionmask/tests/test_mask.py::test_mask_wrong_method", "regionmask/tests/test_mask.py::test_mask_2D_overlap_error[rasterize]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_error[shapely]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_false[rasterize]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_false[shapely]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_none[rasterize]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_none[shapely]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_default[rasterize]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_default[shapely]", "regionmask/tests/test_mask.py::test_mask_3D_overlap[rasterize-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap[rasterize-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap[shapely-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap[shapely-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_one[rasterize-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_one[rasterize-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_one[shapely-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_one[shapely-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[rasterize-None]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[rasterize-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[rasterize-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[shapely-None]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[shapely-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[shapely-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_default[rasterize-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_default[rasterize-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_default[shapely-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_default[shapely-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_empty[rasterize]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_empty[shapely]", "regionmask/tests/test_mask.py::test_mask_overlap_unstructured[shapely-True]", "regionmask/tests/test_mask.py::test_mask_overlap_unstructured[shapely-False]", "regionmask/tests/test_mask.py::test_mask_flag", "regionmask/tests/test_mask.py::test_mask_flag_space", "regionmask/tests/test_mask.py::test_mask_flag_only_found", "regionmask/tests/test_mask.py::test_mask_2D[shapely]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat0-lon0]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat0-lon1]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat0-0]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat1-lon0]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat1-lon1]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat1-0]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[0-lon0]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[0-lon1]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[0-0]", "regionmask/tests/test_mask.py::test_mask_xarray_in_out_2D[shapely]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-2--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-2--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-2--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-2--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-2--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-2--5]", "regionmask/tests/test_mask.py::test_rasterize[nan-0-1]", "regionmask/tests/test_mask.py::test_rasterize[nan-4-5]", "regionmask/tests/test_mask.py::test_rasterize[3-0-1]", "regionmask/tests/test_mask.py::test_rasterize[3-4-5]", "regionmask/tests/test_mask.py::test_mask_empty[rasterize]", "regionmask/tests/test_mask.py::test_mask_empty[shapely]", "regionmask/tests/test_mask.py::test_mask_unstructured[shapely]", "regionmask/tests/test_mask.py::test_mask_3D[rasterize-True]", "regionmask/tests/test_mask.py::test_mask_3D[rasterize-False]", "regionmask/tests/test_mask.py::test_mask_3D[shapely-True]", "regionmask/tests/test_mask.py::test_mask_3D[shapely-False]", "regionmask/tests/test_mask.py::test_mask_3D_empty[rasterize]", "regionmask/tests/test_mask.py::test_mask_3D_empty[shapely]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-True-lat-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-True-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-True-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-True-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-False-lat-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-False-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-False-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-False-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-True-lat-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-True-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-True-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-True-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-False-lat-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-False-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-False-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-False-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_warn_radian[mask]", "regionmask/tests/test_mask.py::test_mask_warn_radian[mask_3D]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions2-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions2-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions3-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions3-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions2-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions2-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions3-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions3-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions2-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions2-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions3-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions3-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions2-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions2-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions3-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions3-shapely]", "regionmask/tests/test_mask.py::test_deg45_rasterize_shapely_equal[regions0]", "regionmask/tests/test_mask.py::test_deg45_rasterize_shapely_equal[regions1]", "regionmask/tests/test_mask.py::test_deg45_rasterize_offset_equal[regions0]", "regionmask/tests/test_mask.py::test_deg45_rasterize_offset_equal[regions1]", "regionmask/tests/test_mask.py::test_rasterize_on_split_lon[regions_1800-ds_3600]", "regionmask/tests/test_mask.py::test_rasterize_on_split_lon[regions_1800-ds_3601]", "regionmask/tests/test_mask.py::test_rasterize_on_split_lon[regions_1801-ds_3600]", "regionmask/tests/test_mask.py::test_rasterize_on_split_lon[regions_1801-ds_3601]", "regionmask/tests/test_mask.py::test_rasterize_on_split_lon_asymmetric", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon0-0]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon1-0]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon2-1]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon3-2]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon4-3]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon5-3]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon6-3]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon0-0]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon1-0]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon2-1]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon3-2]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon4-3]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon5-3]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon6-3]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon0-0]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon1-0]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon2-1]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon3-2]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon4-3]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon5-3]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon6-3]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon0-0]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon1-0]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon2-1]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon3-2]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon4-3]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon5-3]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon6-3]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon0-0]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon1-0]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon2-1]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon3-2]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon4-3]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon5-3]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon6-3]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon0-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon0-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon0-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon0-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon1-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon1-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon1-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon1-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_nan_lon[lon0-regions0]", "regionmask/tests/test_mask.py::test_mask_whole_grid_nan_lon[lon0-regions1]", "regionmask/tests/test_mask.py::test_mask_whole_grid_nan_lon[lon1-regions0]", "regionmask/tests/test_mask.py::test_mask_whole_grid_nan_lon[lon1-regions1]", "regionmask/tests/test_mask.py::test_mask_whole_grid_unusual_lon[regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_unusual_lon[regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_unusual_lon[regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_unusual_lon[regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon0-outline0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon0-outline0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon0-outline1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon0-outline1-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon1-outline0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon1-outline0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon1-outline1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon1-outline1-shapely]", "regionmask/tests/test_mask.py::test_inject_mask_docstring", "regionmask/tests/test_plot.py::test_flatten_polygons", "regionmask/tests/test_plot.py::test_polygons_coords" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2023-10-27 16:59:18+00:00
mit
5,228
regionmask__regionmask-494
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ac4facf..b9765a1 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -23,7 +23,7 @@ jobs: matrix: os: ["ubuntu-latest"] # Bookend python versions - python-version: ["3.9", "3.11"] + python-version: ["3.9", "3.12"] steps: - uses: actions/checkout@v4 with: diff --git a/.github/workflows/linting.yaml b/.github/workflows/linting.yaml index 6c2b3d6..e5a3b70 100644 --- a/.github/workflows/linting.yaml +++ b/.github/workflows/linting.yaml @@ -23,7 +23,7 @@ jobs: matrix: os: ["ubuntu-latest"] # Bookend python versions - python-version: ["3.11"] + python-version: ["3.12"] steps: - uses: actions/checkout@v4 with: diff --git a/.github/workflows/upstream-dev-ci.yaml b/.github/workflows/upstream-dev-ci.yaml index 0841085..2f11651 100644 --- a/.github/workflows/upstream-dev-ci.yaml +++ b/.github/workflows/upstream-dev-ci.yaml @@ -33,7 +33,7 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.11"] + python-version: ["3.12"] steps: - uses: actions/checkout@v4 with: diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 5bcd1f9..39baca4 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -26,12 +26,15 @@ Breaking Changes Enhancements ~~~~~~~~~~~~ +- Add python 3.12 to list of supported versions (:pull:`494`). + New regions ~~~~~~~~~~~ Bug Fixes ~~~~~~~~~ +- Ensure correct masks are created for `float32` coordinates (:issue:`489`, :pull:`493`). - Fixed the default value of ``overlap`` of :py:func:`from_geopandas` to ``None`` (:issue:`453`, :pull:`470`). Docs diff --git a/ci/requirements/docs.yml b/ci/requirements/docs.yml index af14e8e..40d3cea 100644 --- a/ci/requirements/docs.yml +++ b/ci/requirements/docs.yml @@ -5,7 +5,7 @@ channels: - nodefaults dependencies: - - python=3.11 + - python=3.12 # regionmask dependencies - cartopy - geopandas diff --git a/regionmask/core/mask.py b/regionmask/core/mask.py index cf1f85e..eba2571 100644 --- a/regionmask/core/mask.py +++ b/regionmask/core/mask.py @@ -204,8 +204,8 @@ def _mask( "be converted to degree?" ) - lon_arr = np.asarray(lon) - lat_arr = np.asarray(lat) + lon_arr = np.asarray(lon, dtype=float) + lat_arr = np.asarray(lat, dtype=float) # automatically detect whether wrapping is necessary if wrap_lon is None: diff --git a/setup.cfg b/setup.cfg index 32ae80f..acdf717 100644 --- a/setup.cfg +++ b/setup.cfg @@ -17,6 +17,7 @@ classifiers = Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 + Programming Language :: Python :: 3.12 Topic :: Scientific/Engineering Topic :: Scientific/Engineering :: Atmospheric Science Topic :: Scientific/Engineering :: GIS
regionmask/regionmask
e9ddf7aad514c8563662c0323d8a80e8bb35e993
diff --git a/regionmask/tests/test_mask.py b/regionmask/tests/test_mask.py index 8996f0e..b279a1c 100644 --- a/regionmask/tests/test_mask.py +++ b/regionmask/tests/test_mask.py @@ -964,12 +964,29 @@ def test_mask_whole_grid(method, regions, lon): mask = regions.mask(lon, lat, method=method) assert (mask == 0).all() + assert mask.lon.dtype == int + assert mask.lat.dtype == int # with wrap_lon=False the edges are not masked mask = regions.mask(lon, lat, method=method, wrap_lon=False) assert mask.sel(lat=-90).isnull().all() [email protected]("method", MASK_METHODS) [email protected]("regions", [r_GLOB_180, r_GLOB_360]) [email protected]("lon", [lon180, lon360]) +def test_mask_whole_grid_float32(method, regions, lon): + + lat = np.arange(90, -91, -10, dtype=np.float32) + lon = lon.astype(np.float32) # creates a copy + mask = regions.mask(lon, lat, method=method) + + assert (mask == 0).all() + + assert mask.lon.dtype == np.float32 + assert mask.lat.dtype == np.float32 + + @pytest.mark.parametrize("regions", [r_GLOB_180, r_GLOB_360]) @pytest.mark.parametrize("lon", [lon180, lon360]) def test_mask_whole_grid_nan_lon(regions, lon):
test on python 3.12 All dependencies are ready and the tests pass. So it should just be a matter of updating everything that is needed.
0.0
e9ddf7aad514c8563662c0323d8a80e8bb35e993
[ "regionmask/tests/test_mask.py::test_mask_whole_grid_float32[lon0-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_float32[lon0-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_float32[lon0-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_float32[lon0-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_float32[lon1-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_float32[lon1-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_float32[lon1-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_float32[lon1-regions1-shapely]" ]
[ "regionmask/tests/test_mask.py::test_mask_func[_mask_rasterize]", "regionmask/tests/test_mask.py::test_mask_func[_mask_shapely]", "regionmask/tests/test_mask.py::test_mask_func[_mask_shapely_v2]", "regionmask/tests/test_mask.py::test_mask_wrong_number_fill[_mask_rasterize]", "regionmask/tests/test_mask.py::test_mask_wrong_number_fill[_mask_shapely]", "regionmask/tests/test_mask.py::test_mask_wrong_number_fill[_mask_shapely_v2]", "regionmask/tests/test_mask.py::test_mask[rasterize]", "regionmask/tests/test_mask.py::test_mask[shapely]", "regionmask/tests/test_mask.py::test_mask_method_internal[rasterize]", "regionmask/tests/test_mask.py::test_mask_method_internal[shapely]", "regionmask/tests/test_mask.py::test_missing_pygeos_error", "regionmask/tests/test_mask.py::test_mask_xr_keep_name[rasterize]", "regionmask/tests/test_mask.py::test_mask_xr_keep_name[shapely]", "regionmask/tests/test_mask.py::test_mask_poly_z_value[rasterize]", "regionmask/tests/test_mask.py::test_mask_poly_z_value[shapely]", "regionmask/tests/test_mask.py::test_mask_xarray_name[rasterize]", "regionmask/tests/test_mask.py::test_mask_xarray_name[shapely]", "regionmask/tests/test_mask.py::test_mask_unequal_ndim[ndims0]", "regionmask/tests/test_mask.py::test_mask_unequal_ndim[ndims1]", "regionmask/tests/test_mask.py::test_mask_unequal_2D_shapes", "regionmask/tests/test_mask.py::test_mask_ndim_ne_1_2[0]", "regionmask/tests/test_mask.py::test_mask_ndim_ne_1_2[3]", "regionmask/tests/test_mask.py::test_mask_ndim_ne_1_2[4]", "regionmask/tests/test_mask.py::test_mask_obj[rasterize-lat-lon]", "regionmask/tests/test_mask.py::test_mask_obj[rasterize-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_obj[rasterize-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_obj[rasterize-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_obj[shapely-lat-lon]", "regionmask/tests/test_mask.py::test_mask_obj[shapely-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_obj[shapely-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_obj[shapely-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_wrap[rasterize]", "regionmask/tests/test_mask.py::test_mask_wrap[shapely]", "regionmask/tests/test_mask.py::test_wrap_lon_no_error_wrap_lon_false[mask]", "regionmask/tests/test_mask.py::test_wrap_lon_no_error_wrap_lon_false[mask_3D]", "regionmask/tests/test_mask.py::test_wrap_lon_error_wrap_lon[mask]", "regionmask/tests/test_mask.py::test_wrap_lon_error_wrap_lon[mask_3D]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon0-extent0-rasterize]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon0-extent0-shapely]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon1-extent1-rasterize]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon1-extent1-shapely]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon2-extent2-rasterize]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon2-extent2-shapely]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon3-extent3-rasterize]", "regionmask/tests/test_mask.py::test_mask_autowrap[lon3-extent3-shapely]", "regionmask/tests/test_mask.py::test_mask_wrong_method", "regionmask/tests/test_mask.py::test_mask_2D_overlap_error[rasterize]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_error[shapely]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_false[rasterize]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_false[shapely]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_none[rasterize]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_none[shapely]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_default[rasterize]", "regionmask/tests/test_mask.py::test_mask_2D_overlap_default[shapely]", "regionmask/tests/test_mask.py::test_mask_3D_overlap[rasterize-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap[rasterize-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap[shapely-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap[shapely-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_one[rasterize-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_one[rasterize-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_one[shapely-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_one[shapely-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[rasterize-None]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[rasterize-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[rasterize-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[shapely-None]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[shapely-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_more_than_64[shapely-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_default[rasterize-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_default[rasterize-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_default[shapely-True]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_default[shapely-False]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_empty[rasterize]", "regionmask/tests/test_mask.py::test_mask_3D_overlap_empty[shapely]", "regionmask/tests/test_mask.py::test_mask_overlap_unstructured[shapely-True]", "regionmask/tests/test_mask.py::test_mask_overlap_unstructured[shapely-False]", "regionmask/tests/test_mask.py::test_mask_flag", "regionmask/tests/test_mask.py::test_mask_flag_space", "regionmask/tests/test_mask.py::test_mask_flag_only_found", "regionmask/tests/test_mask.py::test_mask_2D[shapely]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat0-lon0]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat0-lon1]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat0-0]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat1-lon0]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat1-lon1]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[lat1-0]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[0-lon0]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[0-lon1]", "regionmask/tests/test_mask.py::test_mask_rasterize_irregular[0-0]", "regionmask/tests/test_mask.py::test_mask_xarray_in_out_2D[shapely]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-0-2--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1-1-2--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[1--5-2--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-0-2--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2-1-2--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-1-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-1-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-1--5]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-2-0]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-2-1]", "regionmask/tests/test_mask.py::test_transform_from_latlon[2--5-2--5]", "regionmask/tests/test_mask.py::test_rasterize[nan-0-1]", "regionmask/tests/test_mask.py::test_rasterize[nan-4-5]", "regionmask/tests/test_mask.py::test_rasterize[3-0-1]", "regionmask/tests/test_mask.py::test_rasterize[3-4-5]", "regionmask/tests/test_mask.py::test_mask_empty[rasterize]", "regionmask/tests/test_mask.py::test_mask_empty[shapely]", "regionmask/tests/test_mask.py::test_mask_unstructured[shapely]", "regionmask/tests/test_mask.py::test_mask_3D[rasterize-True]", "regionmask/tests/test_mask.py::test_mask_3D[rasterize-False]", "regionmask/tests/test_mask.py::test_mask_3D[shapely-True]", "regionmask/tests/test_mask.py::test_mask_3D[shapely-False]", "regionmask/tests/test_mask.py::test_mask_3D_empty[rasterize]", "regionmask/tests/test_mask.py::test_mask_3D_empty[shapely]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-True-lat-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-True-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-True-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-True-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-False-lat-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-False-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-False-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[rasterize-False-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-True-lat-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-True-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-True-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-True-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-False-lat-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-False-lat-longitude]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-False-latitude-lon]", "regionmask/tests/test_mask.py::test_mask_3D_obj[shapely-False-latitude-longitude]", "regionmask/tests/test_mask.py::test_mask_warn_radian[mask]", "regionmask/tests/test_mask.py::test_mask_warn_radian[mask_3D]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions2-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions2-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions3-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US0-False-regions3-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions2-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions2-shapely]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions3-rasterize]", "regionmask/tests/test_mask.py::test_mask_edge[ds_US1-True-regions3-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions2-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions2-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions3-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US0-False-regions3-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions2-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions2-shapely]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions3-rasterize]", "regionmask/tests/test_mask.py::test_mask_interior_and_edge[ds_US1-True-regions3-shapely]", "regionmask/tests/test_mask.py::test_deg45_rasterize_shapely_equal[regions0]", "regionmask/tests/test_mask.py::test_deg45_rasterize_shapely_equal[regions1]", "regionmask/tests/test_mask.py::test_deg45_rasterize_offset_equal[regions0]", "regionmask/tests/test_mask.py::test_deg45_rasterize_offset_equal[regions1]", "regionmask/tests/test_mask.py::test_rasterize_on_split_lon[regions_1800-ds_3600]", "regionmask/tests/test_mask.py::test_rasterize_on_split_lon[regions_1800-ds_3601]", "regionmask/tests/test_mask.py::test_rasterize_on_split_lon[regions_1801-ds_3600]", "regionmask/tests/test_mask.py::test_rasterize_on_split_lon[regions_1801-ds_3601]", "regionmask/tests/test_mask.py::test_rasterize_on_split_lon_asymmetric", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon0-0]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon1-0]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon2-1]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon3-2]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon4-3]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon5-3]", "regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon6-3]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon0-0]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon1-0]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon2-1]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon3-2]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon4-3]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon5-3]", "regionmask/tests/test_mask.py::test_determine_method[lat1-0-lon6-3]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon0-0]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon1-0]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon2-1]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon3-2]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon4-3]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon5-3]", "regionmask/tests/test_mask.py::test_determine_method[lat2-3-lon6-3]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon0-0]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon1-0]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon2-1]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon3-2]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon4-3]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon5-3]", "regionmask/tests/test_mask.py::test_determine_method[lat3-3-lon6-3]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon0-0]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon1-0]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon2-1]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon3-2]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon4-3]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon5-3]", "regionmask/tests/test_mask.py::test_determine_method[lat4-3-lon6-3]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon0-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon0-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon0-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon0-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon1-regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon1-regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon1-regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid[lon1-regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_nan_lon[lon0-regions0]", "regionmask/tests/test_mask.py::test_mask_whole_grid_nan_lon[lon0-regions1]", "regionmask/tests/test_mask.py::test_mask_whole_grid_nan_lon[lon1-regions0]", "regionmask/tests/test_mask.py::test_mask_whole_grid_nan_lon[lon1-regions1]", "regionmask/tests/test_mask.py::test_mask_whole_grid_unusual_lon[regions0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_unusual_lon[regions0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_unusual_lon[regions1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_unusual_lon[regions1-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon0-outline0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon0-outline0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon0-outline1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon0-outline1-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon1-outline0-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon1-outline0-shapely]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon1-outline1-rasterize]", "regionmask/tests/test_mask.py::test_mask_whole_grid_overlap[lon1-outline1-shapely]", "regionmask/tests/test_mask.py::test_inject_mask_docstring" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-11-03 22:34:12+00:00
mit
5,229
repobee__repobee-196
diff --git a/docs/getting_started.rst b/docs/getting_started.rst index 2a3aab7..65324f8 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -16,8 +16,8 @@ workflow can be summarized in the following steps: 1. Create an organization (the target organization). 2. Configure RepoBee for the target organization. 3. Verify settings. -4. Migrate master repositories into the target organization. -5. Create one copy of each master repo for each student. +4. Setting up the master repos. +5. Setting up the student repos. There is more to RepoBee, such as opening/closing issues, updating student repos and cloning repos in batches, but here we will just look at the bare @@ -150,9 +150,9 @@ recommend having a separate, persistent organization so that you can work on repos across course rounds. If you already have a master organization with your master repos set up somewhere, and ``master_org_name`` is specified in the config, you're good to go. If you need to migrate repos into the target -organization (i.e. you are not using a master organization), see the -:ref:`migrate` section. For all commands but the ``migrate`` command, the way -you set this up does not matter as RepoBee commands go. +organization (e.g. if you keep master repos in the target organization), see +the :ref:`migrate` section. For all commands but the ``migrate`` command, the +way you set this up does not matter as far as RepoBee commands go. .. _setup: diff --git a/docs/migrate.rst b/docs/migrate.rst index cdc8863..09cb674 100644 --- a/docs/migrate.rst +++ b/docs/migrate.rst @@ -1,16 +1,18 @@ .. _migrate: -Migrate master repositories into the target (or master) organization (``migrate`` command) -****************************************************************************************** -This step sounds complicated, but it's actually very easy, and can be performed -with a single RepoBee command. There is however a pre-requisite that must -be fulfilled. You must either +Migrate repositories into the target (or master) organization (``migrate`` command) +*********************************************************************************** +Migrating repositories from one organization to another can be useful in a few +cases. You may have repos that should be accessible to students and need to be +moved across course rounds, or you might be storing your master repos in the +target organization and need to migrate them for each new course round. To +migrate repos into the target organization, they need to be either: -* Have local copies of your master repos. +* Local in the current working directory, and specified by name. or -* Have all master repos in the same GitHub instance as your target organization. +* Somewhere in the target GitHub instance, and specified by URL. Assuming we have the repos ``master-repo-1`` and ``master-repo-2`` in the current working directory (i.e. local repos), all we have to do is this: @@ -18,7 +20,6 @@ current working directory (i.e. local repos), all we have to do is this: .. code-block:: bash $ repobee migrate -mn master-repo-1 master-repo-2 - [INFO] created team master_repos [INFO] cloning into file:///some/directory/path/master-repo-1 [INFO] cloning into file:///some/directory/path/master-repo-2 [INFO] created repobee-demo/master-repo-1 @@ -34,16 +35,15 @@ current working directory (i.e. local repos), all we have to do is this: you must specify it with the ``--org-name`` option here (instead of the ``--master-org-name``). -There are a few things to note here. First of all, the team ``master_repos`` is -created. This only happens the first time ``migrate`` is run on a new -organization. As the name suggests, this team houses all of the master repos. -Each master repo that is migrated with the ``migrate`` command is added to this -team, so they can easily be found at a later time. It may also be confusing that -the local repos are being cloned (into a temporary directory). This is simply -an implementation detail that does not need much thinking about. Finally, the -local repos are pushed to the ``master`` branch of the remote repo. This command -is perfectly safe to run several times, in case you think you missed something. -Running the same thing again yields the following output: +What happens here is pretty straightforward, except for the local repos being +cloned, which is an implementation detail that does not need to be thought +further of. Note that only the defualt branch is actually migrated, and pushed +to ``master`` in the new repo. local repos are pushed to the ``master`` branch +of the remote repo. Migrating several branches is something that we've never +had a need to do, but if you do, please open an issue on GitHub with a feature +request. ``migrate`` is perfectly safe to run several times, in case you think +you missed something, or need to update repos. Running the same thing again +without changing the local repos yields the following output: .. code-block:: bash @@ -59,8 +59,7 @@ Running the same thing again yields the following output: In fact, all RepoBee commands that deal with pushing to or cloning from repos in some way are safe to run over and over. This is mostly because of -how git works, and has little to do with RepoBee itself. Now that -our master repos are migrated, we can move on to setting up the student repos! +how Git works, and has little to do with RepoBee itself. .. note:: diff --git a/repobee/cli.py b/repobee/cli.py index 0c7cf53..5215ca3 100644 --- a/repobee/cli.py +++ b/repobee/cli.py @@ -621,11 +621,7 @@ def _add_subparsers(parser): "Migrate master repositories into the target organization. " "The repos must either be local on disk (and specified with " "`-mn`), or somewhere in the target GitHub instance (and " - "specified with `-mu`). Migrate repos are added to the `{}` " - "team. `migrate-repos` can also be used to update already " - "migrated repos, by simply running the command again.".format( - command.MASTER_TEAM - ) + "specified with `-mu`)." ), parents=[base_parser, base_user_parser], ) diff --git a/repobee/command.py b/repobee/command.py index 86887b6..1cd50c1 100644 --- a/repobee/command.py +++ b/repobee/command.py @@ -36,8 +36,6 @@ from repobee.git import Push LOGGER = daiquiri.getLogger(__file__) -MASTER_TEAM = "master_repos" - def setup_student_repos( master_repo_urls: Iterable[str], @@ -393,8 +391,6 @@ def migrate_repos(master_repo_urls: Iterable[str], api: GitHubAPI) -> None: the username that is used in the push. api: A GitHubAPI instance used to interface with the GitHub instance. """ - master_team, *_ = api.ensure_teams_and_members({MASTER_TEAM: []}) - master_names = [util.repo_name(url) for url in master_repo_urls] infos = [ @@ -402,7 +398,6 @@ def migrate_repos(master_repo_urls: Iterable[str], api: GitHubAPI) -> None: name=master_name, description="Master repository {}".format(master_name), private=True, - team_id=master_team.id, ) for master_name in master_names ]
repobee/repobee
902d70b59be10200d75907edb0a212f043996117
diff --git a/tests/test_command.py b/tests/test_command.py index 9d09848..e423071 100644 --- a/tests/test_command.py +++ b/tests/test_command.py @@ -600,9 +600,9 @@ class TestMigrateRepo: git_clone_mock.assert_has_calls(expected_clone_calls) assert api_mock.create_repos.called - api_mock.ensure_teams_and_members.assert_called_once_with( - {command.MASTER_TEAM: []} - ) + assert ( + not api_mock.ensure_teams_and_members.called + ), "master repos should no longer be added to a team" git_push_mock.assert_called_once_with(expected_pts)
Don't add migrated repos to `master_repos` team `migrate` is probably most useful for moving course content that students should actually be able to access, so adding it to the `master_repos` team is inconvenient. There's also the fact that since the `migrate` command was introduced, the recommended way of storing master repos has changed from keeping them in the target org, to keeping them in a separate master org. That, and the fact that it introduces a new namespace on GitLab, which complicates cloning master repos that are housed in the target organization. This does not actually affect any functionality in RepoBee, as the `master_repos` team is not used anywhere, so it's safe to just remove.
0.0
902d70b59be10200d75907edb0a212f043996117
[ "tests/test_command.py::TestMigrateRepo::test_happy_path" ]
[ "tests/test_command.py::TestSetupStudentRepos::test_raises_on_clone_failure", "tests/test_command.py::TestSetupStudentRepos::test_raises_on_duplicate_master_urls", "tests/test_command.py::TestSetupStudentRepos::test_happy_path", "tests/test_command.py::TestUpdateStudentRepos::test_raises_on_duplicate_master_urls", "tests/test_command.py::TestUpdateStudentRepos::test_happy_path", "tests/test_command.py::TestUpdateStudentRepos::test_issues_on_exceptions[issue0]", "tests/test_command.py::TestUpdateStudentRepos::test_issues_on_exceptions[None]", "tests/test_command.py::TestUpdateStudentRepos::test_issues_arent_opened_on_exceptions_if_unspeficied", "tests/test_command.py::TestOpenIssue::test_happy_path", "tests/test_command.py::TestCloseIssue::test_happy_path", "tests/test_command.py::TestCloneRepos::test_happy_path", "tests/test_command.py::TestListIssues::test_happy_path[slarse-True--closed]", "tests/test_command.py::TestListIssues::test_happy_path[slarse-True-^.*$-closed]", "tests/test_command.py::TestListIssues::test_happy_path[slarse-False--closed]", "tests/test_command.py::TestListIssues::test_happy_path[slarse-False-^.*$-closed]", "tests/test_command.py::test_purge_review_teams", "tests/test_command.py::TestAssignPeerReviewers::test_too_few_students_raises[3-3]", "tests/test_command.py::TestAssignPeerReviewers::test_too_few_students_raises[3-4]", "tests/test_command.py::TestAssignPeerReviewers::test_zero_reviews_raises", "tests/test_command.py::TestAssignPeerReviewers::test_happy_path" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-22 18:35:49+00:00
mit
5,230
repobee__repobee-201
diff --git a/repobee/github_api.py b/repobee/github_api.py index 5a698af..a1d4585 100644 --- a/repobee/github_api.py +++ b/repobee/github_api.py @@ -21,6 +21,7 @@ import github from repobee import exception from repobee import tuples from repobee import util +from repobee import apimeta REQUIRED_OAUTH_SCOPES = {"admin:org", "repo"} @@ -95,7 +96,7 @@ def _try_api_request(ignore_statuses: Optional[Iterable[int]] = None): ) -class GitHubAPI: +class GitHubAPI(apimeta.API): """A highly specialized GitHub API class for repobee. The API is affiliated both with an organization, and with the whole GitHub instance. Almost all operations take place on the target @@ -136,7 +137,7 @@ class GitHubAPI: def token(self): return self._token - def get_teams_in( + def _get_teams_in( self, team_names: Iterable[str] ) -> Generator[github.Team.Team, None, None]: """Get all teams that match any team name in the team_names iterable. @@ -163,7 +164,7 @@ class GitHubAPI: team_names: A list of team names for teams to be deleted. """ deleted = set() # only for logging - for team in self.get_teams_in(team_names): + for team in self._get_teams_in(team_names): team.delete() deleted.add(team.name) LOGGER.info("deleted team {}".format(team.name)) @@ -220,7 +221,7 @@ class GitHubAPI: for team in [team for team in teams if member_lists[team.name]]: self._ensure_members_in_team(team, member_lists[team.name]) - return list(self.get_teams_in(set(member_lists.keys()))) + return list(self._get_teams_in(set(member_lists.keys()))) def _ensure_teams_exist( self, team_names: Iterable[str], permission: str = "push" @@ -280,9 +281,9 @@ class GitHubAPI: ", ".join(existing_members), team.name ) ) - self.add_to_team(missing_members, team) + self._add_to_team(missing_members, team) - def add_to_team(self, members: Iterable[str], team: github.Team.Team): + def _add_to_team(self, members: Iterable[str], team: github.Team.Team): """Add members to a team. Args: @@ -294,18 +295,18 @@ class GitHubAPI: for user in users: team.add_membership(user) - def create_repos(self, repo_infos: Iterable[tuples.Repo]): + def create_repos(self, repos: Iterable[tuples.Repo]): """Create repositories in the given organization according to the Repos. Repos that already exist are skipped. Args: - repo_infos: An iterable of Repo namedtuples. + repos: An iterable of Repo namedtuples. Returns: A list of urls to all repos corresponding to the Repos. """ repo_urls = [] - for info in repo_infos: + for info in repos: created = False with _try_api_request(ignore_statuses=[422]): kwargs = dict( @@ -489,7 +490,7 @@ class GitHubAPI: issue: An an optional Issue tuple to override the default issue. """ issue = issue or DEFAULT_REVIEW_ISSUE - for team, repo in self.add_repos_to_teams(team_to_repos): + for team, repo in self._add_repos_to_teams(team_to_repos): # TODO team.get_members() api request is a bit redundant, it # can be solved in a more efficient way by passing in the # allocations @@ -527,7 +528,7 @@ class GitHubAPI: assigned_repos is a :py:class:`~repobee.tuples.Review`. """ reviews = collections.defaultdict(list) - teams = self.get_teams_in(review_team_names) + teams = self._get_teams_in(review_team_names) for team in teams: with _try_api_request(): LOGGER.info("processing {}".format(team.name)) @@ -557,7 +558,7 @@ class GitHubAPI: return reviews - def add_repos_to_teams( + def _add_repos_to_teams( self, team_to_repos: Mapping[str, Iterable[str]] ) -> Generator[ Tuple[github.Team.Team, github.Repository.Repository], None, None
repobee/repobee
771ab4e3b32ee13edf575b442f27f7c840db2dff
diff --git a/tests/test_github_api.py b/tests/test_github_api.py index f03a05a..9976d19 100644 --- a/tests/test_github_api.py +++ b/tests/test_github_api.py @@ -668,7 +668,7 @@ class TestGetIssues: @pytest.fixture def team_to_repos(api, no_repos, organization): - """Create a team_to_repos mapping for use in add_repos_to_teams, anc create + """Create a team_to_repos mapping for use in _add_repos_to_teams, anc create each team and repo. Return the team_to_repos mapping. """ num_teams = 10 @@ -718,7 +718,7 @@ class TestAddReposToTeams: expected_tups = sorted(team_to_repos.items()) # act - result = list(api.add_repos_to_teams(team_to_repos)) + result = list(api._add_repos_to_teams(team_to_repos)) result.sort(key=lambda tup: tup[0].name) # assert
Adapt github_api.GitHubAPI to make use of the apimeta.API class
0.0
771ab4e3b32ee13edf575b442f27f7c840db2dff
[ "tests/test_github_api.py::TestAddReposToTeams::test_happy_path" ]
[ "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_no_previous_teams", "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_all_teams_exist_but_without_members", "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_raises_on_non_422_exception[unexpected_exc0]", "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_raises_on_non_422_exception[unexpected_exc1]", "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_raises_on_non_422_exception[unexpected_exc2]", "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_running_twice_has_no_ill_effects", "tests/test_github_api.py::TestCreateRepos::test_creates_correct_repos", "tests/test_github_api.py::TestCreateRepos::test_skips_existing_repos", "tests/test_github_api.py::TestCreateRepos::test_raises_on_unexpected_error[unexpected_exception0]", "tests/test_github_api.py::TestCreateRepos::test_raises_on_unexpected_error[unexpected_exception1]", "tests/test_github_api.py::TestCreateRepos::test_raises_on_unexpected_error[unexpected_exception2]", "tests/test_github_api.py::TestCreateRepos::test_returns_all_urls", "tests/test_github_api.py::TestCreateRepos::test_create_repos_without_team_id", "tests/test_github_api.py::TestGetRepoUrls::test_with_token_without_user", "tests/test_github_api.py::TestGetRepoUrls::test_with_token_and_user", "tests/test_github_api.py::TestGetRepoUrls::test_with_students", "tests/test_github_api.py::TestOpenIssue::test_on_existing_repos", "tests/test_github_api.py::TestOpenIssue::test_on_some_non_existing_repos", "tests/test_github_api.py::TestOpenIssue::test_no_crash_when_no_repos_are_found", "tests/test_github_api.py::TestCloseIssue::test_closes_correct_issues", "tests/test_github_api.py::TestCloseIssue::test_no_crash_if_no_repos_found", "tests/test_github_api.py::TestCloseIssue::test_no_crash_if_no_issues_found", "tests/test_github_api.py::TestGetIssues::test_get_all_open_issues", "tests/test_github_api.py::TestGetIssues::test_get_all_closed_issues", "tests/test_github_api.py::TestGetIssues::test_get_issues_when_one_repo_doesnt_exist", "tests/test_github_api.py::TestGetIssues::test_get_open_issues_by_regex", "tests/test_github_api.py::TestAddReposToReviewTeams::test_with_default_issue", "tests/test_github_api.py::TestDeleteTeams::test_delete_non_existing_teams_does_not_crash", "tests/test_github_api.py::TestDeleteTeams::test_delete_existing_teams", "tests/test_github_api.py::TestVerifySettings::test_happy_path", "tests/test_github_api.py::TestVerifySettings::test_empty_token_raises_bad_credentials", "tests/test_github_api.py::TestVerifySettings::test_incorrect_info_raises_not_found_error[get_user]", "tests/test_github_api.py::TestVerifySettings::test_incorrect_info_raises_not_found_error[get_organization]", "tests/test_github_api.py::TestVerifySettings::test_bad_token_scope_raises", "tests/test_github_api.py::TestVerifySettings::test_not_owner_raises", "tests/test_github_api.py::TestVerifySettings::test_raises_unexpected_exception_on_unexpected_status", "tests/test_github_api.py::TestVerifySettings::test_none_user_raises", "tests/test_github_api.py::TestVerifySettings::test_mismatching_user_login_raises", "tests/test_github_api.py::TestGetPeerReviewProgress::test_nothing_returns", "tests/test_github_api.py::TestGetPeerReviewProgress::test_with_review_teams_but_no_repos" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-26 20:29:54+00:00
mit
5,231
repobee__repobee-202
diff --git a/repobee/cli.py b/repobee/cli.py index b63c37b..d54ea61 100644 --- a/repobee/cli.py +++ b/repobee/cli.py @@ -760,7 +760,6 @@ def _create_base_parsers(): @contextmanager def _sys_exit_on_expected_error(): - """Expect either git.GitError or github_api.APIError.""" try: yield except exception.PushFailedError as exc: diff --git a/repobee/exception.py b/repobee/exception.py index 15e6e06..6b1163e 100644 --- a/repobee/exception.py +++ b/repobee/exception.py @@ -40,7 +40,7 @@ class FileError(RepoBeeException): """Raise when reading or writing to a file errors out.""" -class GitHubError(RepoBeeException): +class APIError(RepoBeeException): """An exception raised when the API responds with an error code.""" def __init__(self, msg="", status=None): @@ -48,30 +48,24 @@ class GitHubError(RepoBeeException): self.status = status -class NotFoundError(GitHubError): +class NotFoundError(APIError): """An exception raised when the API responds with a 404.""" -class ServiceNotFoundError(GitHubError): +class ServiceNotFoundError(APIError): """Raise if the base url can't be located.""" -class BadCredentials(GitHubError): +class BadCredentials(APIError): """Raise when credentials are rejected.""" -class UnexpectedException(GitHubError): +class UnexpectedException(APIError): """An exception raised when an API request raises an unexpected exception. """ -class APIError(RepoBeeException): - """Raise when something unexpected happens when interacting with the - API. - """ - - class GitError(RepoBeeException): """A generic error to raise when a git command exits with a non-zero exit status. diff --git a/repobee/github_api.py b/repobee/github_api.py index a1d4585..5089d7e 100644 --- a/repobee/github_api.py +++ b/repobee/github_api.py @@ -67,7 +67,7 @@ def _try_api_request(ignore_statuses: Optional[Iterable[int]] = None): Raises: exception.NotFoundError exception.BadCredentials - exception.GitHubError + exception.APIError exception.ServiceNotFoundError exception.UnexpectedException """ @@ -85,7 +85,7 @@ def _try_api_request(ignore_statuses: Optional[Iterable[int]] = None): status=401, ) else: - raise exception.GitHubError(str(e), status=e.status) + raise exception.APIError(str(e), status=e.status) except gaierror: raise exception.ServiceNotFoundError( "GitHub service could not be found, check the url" @@ -191,7 +191,7 @@ class GitHubAPI(apimeta.API): existing_users.append(self._github.get_user(name)) except github.GithubException as exc: if exc.status != 404: - raise exception.GitHubError( + raise exception.APIError( "Got unexpected response code from the GitHub API", status=exc.status, )
repobee/repobee
aa6378f691bd96d39bb4f8d307368654a0e065fe
diff --git a/tests/test_github_api.py b/tests/test_github_api.py index 9976d19..df8729b 100644 --- a/tests/test_github_api.py +++ b/tests/test_github_api.py @@ -338,9 +338,9 @@ class TestEnsureTeamsAndMembers: @pytest.mark.parametrize( "unexpected_exc", [ - exception.GitHubError("", 404), - exception.GitHubError("", 400), - exception.GitHubError("", 500), + exception.APIError("", 404), + exception.APIError("", 400), + exception.APIError("", 500), ], ) def test_raises_on_non_422_exception( @@ -421,7 +421,7 @@ class TestCreateRepos: side_effect_github_exception = [unexpected_exception] + side_effect[1:] create_repo_mock.side_effect = side_effect_github_exception - with pytest.raises(exception.GitHubError): + with pytest.raises(exception.APIError): api.create_repos(repo_infos) def test_returns_all_urls(self, mocker, repos, repo_infos, api):
Generalize exception.GitHubError to exception.APIError Such that it makes sense for both GitLab and GitHub. Probably don't need to change any of the internals other than class names.
0.0
aa6378f691bd96d39bb4f8d307368654a0e065fe
[ "tests/test_github_api.py::TestCreateRepos::test_raises_on_unexpected_error[unexpected_exception0]", "tests/test_github_api.py::TestCreateRepos::test_raises_on_unexpected_error[unexpected_exception1]", "tests/test_github_api.py::TestCreateRepos::test_raises_on_unexpected_error[unexpected_exception2]" ]
[ "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_no_previous_teams", "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_all_teams_exist_but_without_members", "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_raises_on_non_422_exception[unexpected_exc0]", "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_raises_on_non_422_exception[unexpected_exc1]", "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_raises_on_non_422_exception[unexpected_exc2]", "tests/test_github_api.py::TestEnsureTeamsAndMembers::test_running_twice_has_no_ill_effects", "tests/test_github_api.py::TestCreateRepos::test_creates_correct_repos", "tests/test_github_api.py::TestCreateRepos::test_skips_existing_repos", "tests/test_github_api.py::TestCreateRepos::test_returns_all_urls", "tests/test_github_api.py::TestCreateRepos::test_create_repos_without_team_id", "tests/test_github_api.py::TestGetRepoUrls::test_with_token_without_user", "tests/test_github_api.py::TestGetRepoUrls::test_with_token_and_user", "tests/test_github_api.py::TestGetRepoUrls::test_with_students", "tests/test_github_api.py::TestOpenIssue::test_on_existing_repos", "tests/test_github_api.py::TestOpenIssue::test_on_some_non_existing_repos", "tests/test_github_api.py::TestOpenIssue::test_no_crash_when_no_repos_are_found", "tests/test_github_api.py::TestCloseIssue::test_closes_correct_issues", "tests/test_github_api.py::TestCloseIssue::test_no_crash_if_no_repos_found", "tests/test_github_api.py::TestCloseIssue::test_no_crash_if_no_issues_found", "tests/test_github_api.py::TestGetIssues::test_get_all_open_issues", "tests/test_github_api.py::TestGetIssues::test_get_all_closed_issues", "tests/test_github_api.py::TestGetIssues::test_get_issues_when_one_repo_doesnt_exist", "tests/test_github_api.py::TestGetIssues::test_get_open_issues_by_regex", "tests/test_github_api.py::TestAddReposToReviewTeams::test_with_default_issue", "tests/test_github_api.py::TestAddReposToTeams::test_happy_path", "tests/test_github_api.py::TestDeleteTeams::test_delete_non_existing_teams_does_not_crash", "tests/test_github_api.py::TestDeleteTeams::test_delete_existing_teams", "tests/test_github_api.py::TestVerifySettings::test_happy_path", "tests/test_github_api.py::TestVerifySettings::test_empty_token_raises_bad_credentials", "tests/test_github_api.py::TestVerifySettings::test_incorrect_info_raises_not_found_error[get_user]", "tests/test_github_api.py::TestVerifySettings::test_incorrect_info_raises_not_found_error[get_organization]", "tests/test_github_api.py::TestVerifySettings::test_bad_token_scope_raises", "tests/test_github_api.py::TestVerifySettings::test_not_owner_raises", "tests/test_github_api.py::TestVerifySettings::test_raises_unexpected_exception_on_unexpected_status", "tests/test_github_api.py::TestVerifySettings::test_none_user_raises", "tests/test_github_api.py::TestVerifySettings::test_mismatching_user_login_raises", "tests/test_github_api.py::TestGetPeerReviewProgress::test_nothing_returns", "tests/test_github_api.py::TestGetPeerReviewProgress::test_with_review_teams_but_no_repos" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-27 15:46:35+00:00
mit
5,232
repobee__repobee-207
diff --git a/repobee/gitlab_api.py b/repobee/gitlab_api.py index 66e43e4..6038109 100644 --- a/repobee/gitlab_api.py +++ b/repobee/gitlab_api.py @@ -294,7 +294,8 @@ class GitLabAPI(apimeta.API): Returns: a list of urls corresponding to the repo names. """ - group_url = "{}/{}".format(self._base_url, self._group_name) + group_name = org_name if org_name else self._group_name + group_url = "{}/{}".format(self._base_url, group_name) repo_urls = ( [ "{}/{}.git".format(group_url, repo_name)
repobee/repobee
56406c954267f04b1cd53b9fd36bb98a5fbc299a
diff --git a/tests/test_gitlab_api.py b/tests/test_gitlab_api.py index 545c735..de395b1 100644 --- a/tests/test_gitlab_api.py +++ b/tests/test_gitlab_api.py @@ -332,15 +332,93 @@ class TestEnsureTeamsAndMembers: assert not group.members.list() [email protected] +def master_repo_names(): + return ["task-1", "task-2", "task-3"] + + +class TestGetRepoUrls: + def test_get_master_repo_urls(self, master_repo_names): + """When supplied with only master_repo_names, get_repo_urls should + return urls for those master repos, expecting them to be in the target + group. + """ + # arrange + api = repobee.gitlab_api.GitLabAPI(BASE_URL, TOKEN, TARGET_GROUP) + expected_urls = [ + api._insert_auth("{}/{}/{}.git".format(BASE_URL, TARGET_GROUP, mn)) + for mn in master_repo_names + ] + assert ( + expected_urls + ), "there must be at least some urls for this test to make sense" + + # act + actual_urls = api.get_repo_urls(master_repo_names) + + # assert + assert sorted(actual_urls) == sorted(expected_urls) + + def test_get_master_repo_urls_in_master_group(self, master_repo_names): + """When supplied with master_repo_names and org_name, the urls + generated should go to the group named org_name instead of the default + target group. + """ + # arrange + master_group = "master-" + TARGET_GROUP # guaranteed != TARGET_GROUP + api = repobee.gitlab_api.GitLabAPI(BASE_URL, TOKEN, TARGET_GROUP) + expected_urls = [ + api._insert_auth("{}/{}/{}.git".format(BASE_URL, master_group, mn)) + for mn in master_repo_names + ] + assert ( + expected_urls + ), "there must be at least some urls for this test to make sense" + + # act + actual_urls = api.get_repo_urls( + master_repo_names, org_name=master_group + ) + + # assert + assert sorted(actual_urls) == sorted(expected_urls) + + def test_get_student_repo_urls(self, master_repo_names): + """When supplied with the students argument, the generated urls should + go to the student repos related to the supplied master repos. + """ + # arrange + api = repobee.gitlab_api.GitLabAPI(BASE_URL, TOKEN, TARGET_GROUP) + expected_urls = [ + api._insert_auth( + "{}/{}/{}/{}.git".format( + BASE_URL, + TARGET_GROUP, + str(student_group), + repobee.util.generate_repo_name(str(student_group), mn), + ) + ) + for student_group in constants.STUDENTS + for mn in master_repo_names + ] + assert ( + expected_urls + ), "there must be at least some urls for this test to make sense" + + # act + actual_urls = api.get_repo_urls( + master_repo_names, students=constants.STUDENTS + ) + + # assert + assert sorted(actual_urls) == sorted(expected_urls) + + class TestCreateRepos: @pytest.fixture def api(self, api_mock): yield repobee.gitlab_api.GitLabAPI(BASE_URL, TOKEN, TARGET_GROUP) - @pytest.fixture - def master_repo_names(self): - return ["task-1", "task-2", "task-3"] - @pytest.fixture def repos(self, api, master_repo_names): """Setup repo tuples along with groups for the repos to be created
GitLabAPI.get_repo_urls ignores org_name argument It always uses the target group's name, but supplying org_name should override it. This becomes problematic when trying to clone master repos from a master group that is separate from the target group (as is recommended).
0.0
56406c954267f04b1cd53b9fd36bb98a5fbc299a
[ "tests/test_gitlab_api.py::TestGetRepoUrls::test_get_master_repo_urls_in_master_group" ]
[ "tests/test_gitlab_api.py::TestEnsureTeamsAndMembers::test_with_no_pre_existing_groups", "tests/test_gitlab_api.py::TestEnsureTeamsAndMembers::test_with_multi_student_groups", "tests/test_gitlab_api.py::TestEnsureTeamsAndMembers::test_run_twice", "tests/test_gitlab_api.py::TestGetRepoUrls::test_get_master_repo_urls", "tests/test_gitlab_api.py::TestGetRepoUrls::test_get_student_repo_urls", "tests/test_gitlab_api.py::TestCreateRepos::test_run_once_for_valid_repos", "tests/test_gitlab_api.py::TestCreateRepos::test_run_twice_for_valid_repos" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-05-29 17:01:56+00:00
mit
5,233
repobee__repobee-214
diff --git a/repobee/apimeta.py b/repobee/apimeta.py index 5ea0424..fb49f48 100644 --- a/repobee/apimeta.py +++ b/repobee/apimeta.py @@ -27,6 +27,8 @@ from repobee import exception LOGGER = daiquiri.getLogger(__file__) +MAX_NAME_LENGTH = 100 + class APIObject: """Base wrapper class for platform API objects.""" @@ -36,17 +38,16 @@ def _check_name_length(name): """Check that a Team/Repository name does not exceed the maximum GitHub allows (100 characters) """ - max_len = 100 - if len(name) > max_len: + if len(name) > MAX_NAME_LENGTH: LOGGER.error("Team/Repository name {} is too long".format(name)) raise ValueError( "generated Team/Repository name is too long, was {} chars, " - "max is {} chars".format(len(name), max_len) + "max is {} chars".format(len(name), MAX_NAME_LENGTH) ) - elif len(name) > max_len * 0.8: + elif len(name) > MAX_NAME_LENGTH * 0.8: LOGGER.warning( "Team/Repository name {} is {} chars long, close to the max of " - "{} chars.".format(name, len(name), max_len) + "{} chars.".format(name, len(name), MAX_NAME_LENGTH) ) @@ -85,6 +86,9 @@ class Team( _check_name_length(name) return super().__new__(cls, name, members, id, implementation) + def __str__(self): + return self.name + class Issue( APIObject, diff --git a/repobee/cli.py b/repobee/cli.py index 53a533d..6732cef 100644 --- a/repobee/cli.py +++ b/repobee/cli.py @@ -30,6 +30,7 @@ from repobee import util from repobee import tuples from repobee import exception from repobee import config +from repobee import apimeta daiquiri.setup( level=logging.INFO, @@ -795,7 +796,7 @@ def _extract_groups(args: argparse.Namespace) -> List[str]: `students_file` is in the namespace. """ if "students" in args and args.students: - students = [tuples.Group([s]) for s in args.students] + students = [apimeta.Team(members=[s]) for s in args.students] elif "students_file" in args and args.students_file: students_file = pathlib.Path(args.students_file) try: # raises FileNotFoundError in 3.5 if no such file exists @@ -809,7 +810,7 @@ def _extract_groups(args: argparse.Namespace) -> List[str]: if not students_file.stat().st_size: raise exception.FileError("'{!s}' is empty".format(students_file)) students = [ - tuples.Group(members=[s for s in group.strip().split()]) + apimeta.Team(members=[s for s in group.strip().split()]) for group in students_file.read_text( encoding=sys.getdefaultencoding() ).split(os.linesep) diff --git a/repobee/command.py b/repobee/command.py index f71952a..4b8d79f 100644 --- a/repobee/command.py +++ b/repobee/command.py @@ -26,7 +26,6 @@ import repobee_plug as plug from repobee import git from repobee import util -from repobee import tuples from repobee import apimeta from repobee import exception from repobee import config @@ -39,17 +38,18 @@ LOGGER = daiquiri.getLogger(__file__) def setup_student_repos( master_repo_urls: Iterable[str], - students: Iterable[tuples.Group], + teams: Iterable[apimeta.Team], api: GitHubAPI, ) -> None: """Setup student repositories based on master repo templates. Performs three primary tasks: - 1. Create one team per student and add the corresponding students to - their teams. If a team already exists, it is left as-is. If a student - is already in its team, nothing happens. If no account exists with the - specified username, the team is created regardless but no one is added - to it. + 1. Create the specified teams on the target platform and add the + specifed members to their teams. If a team already exists, it is left + as-is. If a student is already in a team they are assigned to, nothing + happens. If no account exists for some specified username, that + particular student is ignored, but any associated teams are still + created. 2. For each master repository, create one student repo per team and add it to the corresponding student team. If a repository already exists, @@ -60,7 +60,7 @@ def setup_student_repos( Args: master_repo_urls: URLs to master repos. Must be in the organization that the api is set up for. - students: An iterable of student GitHub usernames. + teams: An iterable of student teams specifying the teams to be setup. api: A GitHubAPI instance used to interface with the GitHub instance. """ urls = list(master_repo_urls) # safe copy @@ -69,7 +69,7 @@ def setup_student_repos( LOGGER.info("cloning into master repos ...") master_repo_paths = _clone_all(urls, cwd=tmpdir) - teams = add_students_to_teams(students, api) + teams = _add_students_to_teams(teams, api) repo_urls = _create_student_repos(urls, teams, api) push_tuples = _create_push_tuples(master_repo_paths, repo_urls) @@ -77,22 +77,22 @@ def setup_student_repos( git.push(push_tuples) -def add_students_to_teams( - students: Iterable[tuples.Group], api: GitHubAPI +def _add_students_to_teams( + teams: Iterable[apimeta.Team], api: GitHubAPI ) -> List[apimeta.Team]: - """Create one team for each student (with the same name as the student), - and add the student to the team. If a team already exists, it is not - created. If a student is already in his/her team, nothing happens. + """Create the specified teams on the target platform, + and add the specified members to their teams. If a team already exists, it + is not created. If a student is already in his/her team, that student is + ignored. Args: - students: Student GitHub usernames. + teams: Team objects specifying student groups. api: A GitHubAPI instance. Returns: all teams associated with the students in the students list. """ - # TODO simply pass the group to ensure_teams_and_members instead - member_lists = {str(group): group.members for group in students} + member_lists = {str(team): team.members for team in teams} return api.ensure_teams_and_members(member_lists) @@ -101,13 +101,12 @@ def _create_student_repos( teams: Iterable[apimeta.Team], api: GitHubAPI, ) -> List[str]: - """Create student repos. Each team (usually representing one student) is - assigned a single repo per master repo. Repos that already exist are not - created, but their urls are returned all the same. + """Create student repos. Each team is assigned a single repo per master + repo. Repos that already exist are not created, but their urls are returned + all the same. Args: - master_repo_urls: URLs to master repos. Must be in the organization - that the api is set up for. + master_repo_urls: URLs to master repos. teams: An iterable of namedtuples designating different teams. api: A GitHubAPI instance used to interface with the GitHub instance. @@ -147,7 +146,7 @@ def _clone_all(urls: Iterable[str], cwd: str): def update_student_repos( master_repo_urls: Iterable[str], - students: Iterable[tuples.Group], + teams: Iterable[apimeta.Team], api: GitHubAPI, issue: Optional[apimeta.Issue] = None, ) -> None: @@ -156,7 +155,7 @@ def update_student_repos( Args: master_repo_urls: URLs to master repos. Must be in the organization that the api is set up for. - students: An iterable of student GitHub usernames. + teams: Team objects specifying student groups. api: A GitHubAPI instance used to interface with the GitHub instance. issue: An optional issue to open in repos to which pushing fails. """ @@ -167,7 +166,7 @@ def update_student_repos( master_repo_names = [util.repo_name(url) for url in urls] - repo_urls = api.get_repo_urls(master_repo_names, students=students) + repo_urls = api.get_repo_urls(master_repo_names, students=teams) with tempfile.TemporaryDirectory() as tmpdir: LOGGER.info("cloning into master repos ...") @@ -200,7 +199,7 @@ def _open_issue_by_urls( def list_issues( master_repo_names: Iterable[str], - students: Iterable[tuples.Group], + teams: Iterable[apimeta.Team], api: GitHubAPI, state: str = "open", title_regex: str = "", @@ -211,7 +210,7 @@ def list_issues( Args: master_repo_names: Names of master repositories. - students: An iterable of student GitHub usernames. + teams: Team objects specifying student groups. state: state of the repo (open or closed). Defaults to 'open'. api: A GitHubAPI instance used to interface with the GitHub instance. title_regex: If specified, only issues with titles matching the regex @@ -220,7 +219,7 @@ def list_issues( default info. author: Only show issues by this author. """ - repo_names = util.generate_repo_names(students, master_repo_names) + repo_names = util.generate_repo_names(teams, master_repo_names) max_repo_name_length = max(map(len, repo_names)) issues_per_repo = api.get_issues(repo_names, state, title_regex) @@ -310,25 +309,25 @@ def _limit_line_length(s: str, max_line_length: int = 100) -> str: def open_issue( issue: apimeta.Issue, master_repo_names: Iterable[str], - students: Iterable[tuples.Group], + teams: Iterable[apimeta.Team], api: GitHubAPI, ) -> None: """Open an issue in student repos. Args: master_repo_names: Names of master repositories. - students: An iterable of student GitHub usernames. + teams: Team objects specifying student groups. issue: An issue to open. api: A GitHubAPI instance used to interface with the GitHub instance. """ - repo_names = util.generate_repo_names(students, master_repo_names) + repo_names = util.generate_repo_names(teams, master_repo_names) api.open_issue(issue.title, issue.body, repo_names) def close_issue( title_regex: str, master_repo_names: Iterable[str], - students: Iterable[tuples.Group], + teams: Iterable[apimeta.Team], api: GitHubAPI, ) -> None: """Close issues whose titles match the title_regex in student repos. @@ -336,26 +335,27 @@ def close_issue( Args: title_regex: A regex to match against issue titles. master_repo_names: Names of master repositories. - students: An iterable of student GitHub usernames. + teams: Team objects specifying student groups. api: A GitHubAPI instance used to interface with the GitHub instance. """ - repo_names = util.generate_repo_names(students, master_repo_names) + repo_names = util.generate_repo_names(teams, master_repo_names) api.close_issue(title_regex, repo_names) def clone_repos( master_repo_names: Iterable[str], - students: Iterable[tuples.Group], + teams: Iterable[apimeta.Team], api: GitHubAPI, ) -> None: - """Clone all student repos related to the provided master repos and students. + """Clone all student repos related to the provided master repos and student + teams. Args: master_repo_names: Names of master repos. - students: Student usernames. + teams: Team objects specifying student groups. api: A GitHubAPI instance. """ - repo_urls = api.get_repo_urls(master_repo_names, students=students) + repo_urls = api.get_repo_urls(master_repo_names, students=teams) LOGGER.info("cloning into student repos ...") git.clone(repo_urls) @@ -363,7 +363,7 @@ def clone_repos( if ( len(plug.manager.get_plugins()) > 1 ): # something else than the default loaded - repo_names = util.generate_repo_names(students, master_repo_names) + repo_names = util.generate_repo_names(teams, master_repo_names) _execute_post_clone_hooks(repo_names, api) @@ -424,7 +424,7 @@ def migrate_repos(master_repo_urls: Iterable[str], api: GitHubAPI) -> None: def assign_peer_reviews( master_repo_names: Iterable[str], - students: Iterable[tuples.Group], + teams: Iterable[apimeta.Team], num_reviews: int, issue: Optional[apimeta.Issue], api: GitHubAPI, @@ -441,15 +441,15 @@ def assign_peer_reviews( Args: master_repo_names: Names of master repos. - students: An iterable of student GitHub usernames. + teams: Team objects specifying student groups. num_reviews: Amount of reviews each student should perform (consequently, the amount of reviews of each repo) api: A GitHubAPI instance used to interface with the GitHub instance. """ - # currently only supports single students - # TODO support groups - assert all(map(lambda g: len(g.members) == 1, students)) - single_students = [g.members[0] for g in students] + # currently only supports single student teams + # TODO support groups of students + assert all(map(lambda g: len(g.members) == 1, teams)) + single_students = [t.members[0] for t in teams] for master_name in master_repo_names: allocations = plug.manager.hook.generate_review_allocations( @@ -472,7 +472,7 @@ def assign_peer_reviews( def purge_review_teams( master_repo_names: Iterable[str], - students: Iterable[tuples.Group], + students: Iterable[apimeta.Team], api: GitHubAPI, ) -> None: """Delete all review teams associated with the given master repo names and @@ -492,7 +492,7 @@ def purge_review_teams( def check_peer_review_progress( master_repo_names: Iterable[str], - students: Iterable[tuples.Group], + students: Iterable[apimeta.Team], title_regex: str, num_reviews: int, api: GitHubAPI, diff --git a/repobee/github_api.py b/repobee/github_api.py index d984160..88a88e3 100644 --- a/repobee/github_api.py +++ b/repobee/github_api.py @@ -341,7 +341,7 @@ class GitHubAPI(apimeta.API): self, master_repo_names: Iterable[str], org_name: Optional[str] = None, - students: Optional[List[tuples.Group]] = None, + students: Optional[List[apimeta.Team]] = None, ) -> List[str]: """Get repo urls for all specified repo names in organization. Assumes that the repos exist, there is no guarantee that they actually do as diff --git a/repobee/gitlab_api.py b/repobee/gitlab_api.py index 18b55ff..420cdba 100644 --- a/repobee/gitlab_api.py +++ b/repobee/gitlab_api.py @@ -20,7 +20,6 @@ import gitlab from repobee import exception from repobee import apimeta -from repobee import tuples from repobee import util LOGGER = daiquiri.getLogger(__file__) @@ -284,7 +283,7 @@ class GitLabAPI(apimeta.API): self, master_repo_names: Iterable[str], org_name: Optional[str] = None, - students: Optional[List[tuples.Group]] = None, + students: Optional[List[apimeta.Team]] = None, ) -> List[str]: """Get repo urls for all specified repo names in organization. Assumes that the repos exist, there is no guarantee that they actually do as diff --git a/repobee/tuples.py b/repobee/tuples.py index 3623d69..ce4dbdb 100644 --- a/repobee/tuples.py +++ b/repobee/tuples.py @@ -16,39 +16,6 @@ import daiquiri LOGGER = daiquiri.getLogger(__file__) - -def _check_name_length(name): - """Check that a Team/Repository name does not exceed the maximum GitHub - allows (100 characters) - """ - max_len = 100 - if len(name) > max_len: - LOGGER.error("Team/Repository name {} is too long".format(name)) - raise ValueError( - "generated Team/Repository name is too long, was {} chars, " - "max is {} chars".format(len(name), max_len) - ) - elif len(name) > max_len * 0.8: - LOGGER.warning( - "Team/Repository name {} is {} chars long, close to the max of " - "{} chars.".format(name, len(name), max_len) - ) - - -class Group(namedtuple("Group", ("members"))): - # GitHub allows only 100 characters for repository names - MAX_STR_LEN = 100 - - def __str__(self): - return "-".join(sorted(self.members)) - - def __new__(cls, members): - instance = super().__new__(cls, members) - team_name = Group.__str__(instance) - _check_name_length(team_name) - return instance - - Args = namedtuple( "Args", (
repobee/repobee
5020962de4b8bd9f36fcee6f511db23256d36f68
diff --git a/tests/constants.py b/tests/constants.py index 8cd839d..c335448 100644 --- a/tests/constants.py +++ b/tests/constants.py @@ -4,7 +4,6 @@ import collections from datetime import datetime from itertools import permutations -from repobee import tuples from repobee import apimeta USER = "slarse" @@ -15,7 +14,7 @@ GITHUB_BASE_URL = "{}/api/v3".format(HOST_URL) # 5! = 120 different students STUDENTS = tuple( - tuples.Group(members=["".join(perm)]) + apimeta.Team(members=["".join(perm)]) for perm in permutations(string.ascii_lowercase[:5]) ) ISSUE_PATH = "some/issue/path" diff --git a/tests/test_cli.py b/tests/test_cli.py index 4f1aa6e..82cf186 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -574,7 +574,7 @@ class TestStudentParsing: ["cat", "dog", "mouse"], ) expected_groups = sorted( - tuples.Group(members=group) for group in groupings + apimeta.Team(members=group) for group in groupings ) empty_students_file.write( os.linesep.join([" ".join(group) for group in groupings]) @@ -603,7 +603,7 @@ class TestStudentParsing: # arrange groupings = ( ["buddy", "shuddy"], - ["a" * tuples.Group.MAX_STR_LEN, "b"], + ["a" * apimeta.MAX_NAME_LENGTH, "b"], ["cat", "dog", "mouse"], ) empty_students_file.write( diff --git a/tests/test_command.py b/tests/test_command.py index 73ecaf0..f857c44 100644 --- a/tests/test_command.py +++ b/tests/test_command.py @@ -658,12 +658,12 @@ class TestAssignPeerReviewers: def test_too_few_students_raises( self, master_names, students, api_mock, num_students, num_reviews ): - students = students[:num_students] + teams = students[:num_students] with pytest.raises(ValueError) as exc_info: command.assign_peer_reviews( master_repo_names=master_names, - students=students, + teams=teams, num_reviews=num_reviews, issue=None, api=api_mock, @@ -677,7 +677,7 @@ class TestAssignPeerReviewers: with pytest.raises(ValueError): command.assign_peer_reviews( master_repo_names=master_names, - students=students, + teams=students, num_reviews=num_reviews, issue=None, api=api_mock, @@ -702,7 +702,7 @@ class TestAssignPeerReviewers: command.assign_peer_reviews( master_repo_names=master_names, - students=students, + teams=students, num_reviews=num_reviews, issue=issue, api=api_mock, diff --git a/tests/test_gitlab_api.py b/tests/test_gitlab_api.py index f91e5d3..d04e8be 100644 --- a/tests/test_gitlab_api.py +++ b/tests/test_gitlab_api.py @@ -279,7 +279,7 @@ class TestEnsureTeamsAndMembers: num_students = len(constants.STUDENTS) allocations = { str( - repobee.tuples.Group(members=g1.members + g2.members) + repobee.apimeta.Team(members=g1.members + g2.members) ): g1.members + g2.members for g1, g2 in zip(
Replace tuples.Group with apimeta.Team Separating these causes some amount of terminology confusion, so they may as well be merged. The downside is that it's a bit less clear _what_ should go into a Team when creating it, a Group clearly just takes the members. But I think this can be structured such that it makes sense.
0.0
5020962de4b8bd9f36fcee6f511db23256d36f68
[ "tests/test_cli.py::TestStudentParsing::test_parser_listing_students[setup|['-u',", "tests/test_cli.py::TestStudentParsing::test_parser_listing_students[update|['-u',", "tests/test_cli.py::TestStudentParsing::test_parser_listing_students[close-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_parser_listing_students[open-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_parser_student_file[setup|['-u',", "tests/test_cli.py::TestStudentParsing::test_parser_student_file[update|['-u',", "tests/test_cli.py::TestStudentParsing::test_parser_student_file[close-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_parser_student_file[open-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[setup|['-u',", "tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[update|['-u',", "tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[close-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_student_groups_parsed_correcly[open-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[setup|['-u',", "tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[update|['-u',", "tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[close-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_raises_if_generated_team_name_too_long[open-issues|['-mn',", "tests/test_cli.py::TestConfig::test_full_config[setup-extra_args0]", "tests/test_cli.py::TestConfig::test_full_config[update-extra_args1]", "tests/test_cli.py::TestConfig::test_full_config[open-issues-extra_args2]", "tests/test_cli.py::TestCloneParser::test_happy_path", "tests/test_command.py::TestSetupStudentRepos::test_happy_path", "tests/test_command.py::TestAssignPeerReviewers::test_too_few_students_raises[3-3]", "tests/test_command.py::TestAssignPeerReviewers::test_too_few_students_raises[3-4]", "tests/test_command.py::TestAssignPeerReviewers::test_zero_reviews_raises", "tests/test_command.py::TestAssignPeerReviewers::test_happy_path", "tests/test_gitlab_api.py::TestEnsureTeamsAndMembers::test_with_multi_student_groups" ]
[ "tests/test_cli.py::TestDispatchCommand::test_raises_on_invalid_subparser_value", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[setup]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[update]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[clone]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[migrate]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[open-issues]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[close-issues]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[list-issues]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[verify-settings]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[assign-reviews]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[purge-review-teams]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[show-config]", "tests/test_cli.py::TestDispatchCommand::test_no_crash_on_valid_args[check-reviews]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[setup-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[update-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[clone-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[migrate-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[open-issues-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[close-issues-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[list-issues-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[verify-settings-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[assign-reviews-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[purge-review-teams-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[purge-review-teams-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[purge-review-teams-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[purge-review-teams-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[show-config-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock0]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock1]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock2]", "tests/test_cli.py::TestDispatchCommand::test_expected_exception_results_in_system_exit[check-reviews-command_all_raise_mock3]", "tests/test_cli.py::TestDispatchCommand::test_setup_student_repos_called_with_correct_args", "tests/test_cli.py::TestDispatchCommand::test_update_student_repos_called_with_correct_args", "tests/test_cli.py::TestDispatchCommand::test_open_issue_called_with_correct_args", "tests/test_cli.py::TestDispatchCommand::test_close_issue_called_with_correct_args", "tests/test_cli.py::TestDispatchCommand::test_migrate_repos_called_with_correct_args", "tests/test_cli.py::TestDispatchCommand::test_clone_repos_called_with_correct_args", "tests/test_cli.py::TestDispatchCommand::test_verify_settings_called_with_correct_args", "tests/test_cli.py::TestDispatchCommand::test_verify_settings_called_with_master_org_name", "tests/test_cli.py::TestBaseParsing::test_raises_on_invalid_org", "tests/test_cli.py::TestBaseParsing::test_raises_on_bad_credentials", "tests/test_cli.py::TestBaseParsing::test_raises_on_invalid_base_url", "tests/test_cli.py::TestBaseParsing::test_master_org_overrides_target_org_for_master_repos[setup]", "tests/test_cli.py::TestBaseParsing::test_master_org_overrides_target_org_for_master_repos[update]", "tests/test_cli.py::TestBaseParsing::test_master_org_name_defaults_to_org_name[setup]", "tests/test_cli.py::TestBaseParsing::test_master_org_name_defaults_to_org_name[update]", "tests/test_cli.py::TestBaseParsing::test_token_env_variable_picked_up[setup]", "tests/test_cli.py::TestBaseParsing::test_token_env_variable_picked_up[update]", "tests/test_cli.py::TestBaseParsing::test_token_cli_arg_picked_up[setup]", "tests/test_cli.py::TestBaseParsing::test_token_cli_arg_picked_up[update]", "tests/test_cli.py::TestBaseParsing::test_raises_on_non_tls_api_url[http://some_enterprise_host/api/v3]", "tests/test_cli.py::TestBaseParsing::test_raises_on_non_tls_api_url[ftp://some_enterprise_host/api/v3]", "tests/test_cli.py::TestBaseParsing::test_raises_on_non_tls_api_url[some_enterprise_host/api/v3]", "tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[setup|['-u',", "tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[update|['-u',", "tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[close-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_raises_if_students_file_is_not_a_file[open-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[setup|['-u',", "tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[update|['-u',", "tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[close-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_student_parsers_raise_on_empty_student_file[open-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[setup|['-u',", "tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[update|['-u',", "tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[close-issues|['-mn',", "tests/test_cli.py::TestStudentParsing::test_parsers_raise_if_both_file_and_listing[open-issues|['-mn',", "tests/test_cli.py::TestConfig::test_missing_option_is_required[-g]", "tests/test_cli.py::TestConfig::test_missing_option_is_required[-u]", "tests/test_cli.py::TestConfig::test_missing_option_is_required[-sf]", "tests/test_cli.py::TestConfig::test_missing_option_is_required[-o]", "tests/test_cli.py::TestConfig::test_missing_option_is_required[-mo]", "tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[-g]", "tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[-u]", "tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[-sf]", "tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[-o]", "tests/test_cli.py::TestConfig::test_missing_option_can_be_specified[-mo]", "tests/test_cli.py::TestSetupAndUpdateParsers::test_happy_path[setup]", "tests/test_cli.py::TestSetupAndUpdateParsers::test_happy_path[update]", "tests/test_cli.py::TestSetupAndUpdateParsers::test_finds_local_repo[setup]", "tests/test_cli.py::TestSetupAndUpdateParsers::test_finds_local_repo[update]", "tests/test_cli.py::TestMigrateParser::test_happy_path", "tests/test_cli.py::TestVerifyParser::test_happy_path", "tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[setup-extra_args0]", "tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[update-extra_args1]", "tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[open-issues-extra_args2]", "tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[close-issues-extra_args3]", "tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[verify-settings-extra_args4]", "tests/test_cli.py::TestCloneParser::test_no_other_parser_gets_parse_hook[migrate-extra_args5]", "tests/test_cli.py::TestShowConfigParser::test_happy_path", "tests/test_cli.py::TestCommandDeprecation::test_deprecated_commands_parsed_to_current_commands[assign-peer-reviews-assign-reviews-sys_args0]", "tests/test_cli.py::TestCommandDeprecation::test_deprecated_commands_parsed_to_current_commands[purge-peer-review-teams-purge-review-teams-sys_args1]", "tests/test_cli.py::TestCommandDeprecation::test_deprecated_commands_parsed_to_current_commands[check-peer-review-progress-check-reviews-sys_args2]", "tests/test_command.py::TestSetupStudentRepos::test_raises_on_clone_failure", "tests/test_command.py::TestSetupStudentRepos::test_raises_on_duplicate_master_urls", "tests/test_command.py::TestUpdateStudentRepos::test_raises_on_duplicate_master_urls", "tests/test_command.py::TestUpdateStudentRepos::test_happy_path", "tests/test_command.py::TestUpdateStudentRepos::test_issues_on_exceptions[issue0]", "tests/test_command.py::TestUpdateStudentRepos::test_issues_on_exceptions[None]", "tests/test_command.py::TestUpdateStudentRepos::test_issues_arent_opened_on_exceptions_if_unspeficied", "tests/test_command.py::TestOpenIssue::test_happy_path", "tests/test_command.py::TestCloseIssue::test_happy_path", "tests/test_command.py::TestCloneRepos::test_happy_path", "tests/test_command.py::TestMigrateRepo::test_happy_path", "tests/test_command.py::TestListIssues::test_happy_path[slarse-True--closed]", "tests/test_command.py::TestListIssues::test_happy_path[slarse-True-^.*$-closed]", "tests/test_command.py::TestListIssues::test_happy_path[slarse-False--closed]", "tests/test_command.py::TestListIssues::test_happy_path[slarse-False-^.*$-closed]", "tests/test_command.py::test_purge_review_teams", "tests/test_gitlab_api.py::TestEnsureTeamsAndMembers::test_with_no_pre_existing_groups", "tests/test_gitlab_api.py::TestEnsureTeamsAndMembers::test_run_twice", "tests/test_gitlab_api.py::TestGetRepoUrls::test_get_master_repo_urls", "tests/test_gitlab_api.py::TestGetRepoUrls::test_get_master_repo_urls_in_master_group", "tests/test_gitlab_api.py::TestGetRepoUrls::test_get_student_repo_urls", "tests/test_gitlab_api.py::TestCreateRepos::test_run_once_for_valid_repos", "tests/test_gitlab_api.py::TestCreateRepos::test_run_twice_for_valid_repos" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-30 18:38:56+00:00
mit
5,234