Coverage for tests / unit / views / test_json.py: 100%

43 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-16 21:32 +0000

1from json import loads 

2from pathlib import Path 

3from unittest.mock import mock_open, patch 

4 

5from pytest import fixture 

6 

7from graphable.graph import Graph 

8from graphable.graphable import Graphable 

9from graphable.views.json import ( 

10 JsonStylingConfig, 

11 create_topology_json, 

12 export_topology_json, 

13) 

14 

15 

16class TestJSON: 

17 @fixture 

18 def graph_fixture(self): 

19 a = Graphable("A") 

20 b = Graphable("B") 

21 a.add_tag("tag1") 

22 g = Graph() 

23 g.add_edge(a, b) 

24 return g, a, b 

25 

26 def test_create_topology_json_default(self, graph_fixture): 

27 g, a, b = graph_fixture 

28 json_str = create_topology_json(g) 

29 data = loads(json_str) 

30 

31 assert "nodes" in data 

32 assert "edges" in data 

33 assert len(data["nodes"]) == 2 

34 assert len(data["edges"]) == 1 

35 

36 node_a = next(n for n in data["nodes"] if n["id"] == "A") 

37 assert node_a["tags"] == ["tag1"] 

38 

39 edge = data["edges"][0] 

40 assert edge["source"] == "A" 

41 assert edge["target"] == "B" 

42 

43 def test_create_topology_json_custom_data(self, graph_fixture): 

44 g, a, b = graph_fixture 

45 config = JsonStylingConfig(node_data_fnc=lambda n: {"extra": True}) 

46 json_str = create_topology_json(g, config=config) 

47 data = loads(json_str) 

48 

49 for node in data["nodes"]: 

50 assert node["extra"] is True 

51 

52 def test_export_topology_json(self, graph_fixture): 

53 g, _, _ = graph_fixture 

54 output_path = Path("output.json") 

55 

56 with patch("builtins.open", mock_open()) as mock_file: 

57 export_topology_json(g, output_path) 

58 

59 mock_file.assert_called_with(output_path, "w+") 

60 mock_file().write.assert_called()