Skip to content

Commit 5d11893

Browse files
authored
Validate IPHost unique attributes are working properly (#6559)
1 parent 8210210 commit 5d11893

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import copy
2+
3+
import pytest
4+
from infrahub_sdk import InfrahubClient
5+
from infrahub_sdk.exceptions import GraphQLError
6+
7+
from infrahub.core.branch.models import Branch
8+
from infrahub.core.node import Node
9+
from infrahub.core.schema import SchemaRoot
10+
from infrahub.core.schema.attribute_schema import AttributeSchema
11+
from infrahub.core.schema.schema_branch import SchemaBranch
12+
from infrahub.database import InfrahubDatabase
13+
from tests.constants import TestKind
14+
from tests.helpers.schema import load_schema
15+
from tests.helpers.schema.device import DEVICE
16+
from tests.helpers.test_app import TestInfrahubApp
17+
18+
19+
class TestUniqueIPHost(TestInfrahubApp):
20+
@pytest.fixture(scope="class", autouse=True)
21+
def schema(self, default_branch: Branch, register_internal_schema: SchemaBranch) -> SchemaRoot:
22+
device_with_ip = copy.deepcopy(DEVICE)
23+
device_with_ip.inherit_from = []
24+
device_with_ip.generate_template = False
25+
device_with_ip.attributes.append(
26+
AttributeSchema(name="primary_address", kind="IPHost", optional=False, unique=True)
27+
)
28+
return SchemaRoot(nodes=[device_with_ip])
29+
30+
@pytest.fixture(scope="class")
31+
async def data(
32+
self,
33+
db: InfrahubDatabase,
34+
initialize_registry: None,
35+
client: InfrahubClient,
36+
default_branch: Branch,
37+
schema: SchemaRoot,
38+
) -> dict[str, Node]:
39+
await load_schema(db, schema=schema, update_db=True)
40+
41+
device = await Node.init(db=db, schema=TestKind.DEVICE)
42+
await device.new(
43+
db=db,
44+
name="Foo",
45+
manufacturer="Foo Inc.",
46+
weight=10,
47+
airflow="Front to rear",
48+
primary_address="192.168.1.1/24",
49+
)
50+
await device.save(db=db)
51+
52+
return {"device": device}
53+
54+
async def test_create_devices(self, client: InfrahubClient, data: dict[str, Node]) -> None:
55+
device_1 = await client.create(
56+
TestKind.DEVICE,
57+
name="Bar",
58+
manufacturer="Bar Inc.",
59+
weight=10,
60+
airflow="Front to rear",
61+
primary_address="192.168.1.2/24",
62+
)
63+
await device_1.save()
64+
65+
devices = await client.all(kind=TestKind.DEVICE)
66+
assert len(devices) == 2
67+
68+
device_2 = await client.create(
69+
TestKind.DEVICE,
70+
name="Baz",
71+
manufacturer="Baz Inc.",
72+
weight=10,
73+
airflow="Front to rear",
74+
primary_address="192.168.1.2/255.255.255.0",
75+
)
76+
with pytest.raises(GraphQLError) as exc:
77+
await device_2.save()
78+
assert exc.value.errors[0]["message"] == "Violates uniqueness constraint 'primary_address'"
79+
80+
devices = await client.all(kind=TestKind.DEVICE)
81+
assert len(devices) == 2

0 commit comments

Comments
 (0)