From 0ec920d2c696380281911ba434eb4835dc719a86 Mon Sep 17 00:00:00 2001 From: finswimmer Date: Tue, 28 Dec 2021 13:01:42 +0100 Subject: [PATCH] replace existing dependency when adding dependency with version constraint --- src/poetry/console/commands/add.py | 8 +++++ tests/console/commands/test_add.py | 47 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/src/poetry/console/commands/add.py b/src/poetry/console/commands/add.py index ad3c2386675..e56ae19df0e 100644 --- a/src/poetry/console/commands/add.py +++ b/src/poetry/console/commands/add.py @@ -1,3 +1,5 @@ +import contextlib + from typing import Dict from typing import List @@ -196,6 +198,12 @@ def handle(self) -> int: constraint = constraint["version"] section[_constraint["name"]] = constraint + + with contextlib.suppress(ValueError): + self.poetry.package.dependency_group(group).remove_dependency( + _constraint["name"] + ) + self.poetry.package.add_dependency( Factory.create_dependency( _constraint["name"], diff --git a/tests/console/commands/test_add.py b/tests/console/commands/test_add.py index 841b44fb565..7dd5f6ce1c2 100644 --- a/tests/console/commands/test_add.py +++ b/tests/console/commands/test_add.py @@ -67,6 +67,53 @@ def test_add_no_constraint( assert content["dependencies"]["cachy"] == "^0.2.0" +def test_add_replace_by_constraint( + app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester" +): + repo.add_package(get_package("cachy", "0.1.0")) + repo.add_package(get_package("cachy", "0.2.0")) + + tester.execute("cachy") + + expected = """\ +Using version ^0.2.0 for cachy + +Updating dependencies +Resolving dependencies... + +Writing lock file + +Package operations: 1 install, 0 updates, 0 removals + + • Installing cachy (0.2.0) +""" + assert tester.io.fetch_output() == expected + assert tester.command.installer.executor.installations_count == 1 + + content = app.poetry.file.read()["tool"]["poetry"] + + assert "cachy" in content["dependencies"] + assert content["dependencies"]["cachy"] == "^0.2.0" + + tester.execute("cachy@0.1.0") + expected = """ +Updating dependencies +Resolving dependencies... + +Writing lock file + +Package operations: 1 install, 0 updates, 0 removals + + • Installing cachy (0.1.0) +""" + assert tester.io.fetch_output() == expected + + content = app.poetry.file.read()["tool"]["poetry"] + + assert "cachy" in content["dependencies"] + assert content["dependencies"]["cachy"] == "0.1.0" + + def test_add_no_constraint_editable_error( app: "PoetryTestApplication", repo: "TestRepository", tester: "CommandTester" ):