Skip to content

Commit be6968d

Browse files
committed
refactor(variable-set): Iterator pattern and test cases were updated for variable-set and variable-set-variables
1 parent 0d3f6ee commit be6968d

4 files changed

Lines changed: 69 additions & 64 deletions

File tree

examples/variable_sets.py

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def variable_set_example():
6464
list_options = VariableSetListOptions(
6565
page_size=10, include=[VariableSetIncludeOpt.WORKSPACES]
6666
)
67-
variable_sets = client.variable_sets.list(org_name, list_options)
67+
variable_sets = list(client.variable_sets.list(org_name, list_options))
6868
print(f"Found {len(variable_sets)} existing variable sets")
6969

7070
for vs in variable_sets[:3]: # Show first 3
@@ -92,6 +92,15 @@ def variable_set_example():
9292
print(f"Priority: {new_variable_set.priority}")
9393
print()
9494

95+
print("Listing existing variable sets...")
96+
list_options = VariableSetListOptions(page_size=10)
97+
variable_sets = list(client.variable_sets.list(org_name, list_options))
98+
print(f"Found {len(variable_sets)} existing variable sets")
99+
100+
for vs in variable_sets: # Show first 3
101+
print(f"- {vs.name} (ID: {vs.id}, Global: {vs.global_})")
102+
print()
103+
95104
# 3. Create variables in the variable set
96105
print("3. Creating variables in the variable set...")
97106

@@ -147,12 +156,16 @@ def variable_set_example():
147156
# 4. List variables in the variable set
148157
print("4. Listing variables in the variable set...")
149158
var_list_options = VariableSetVariableListOptions(page_size=50)
150-
variables = client.variable_set_variables.list(
151-
created_variable_set_id, var_list_options
159+
variables = list(
160+
client.variable_set_variables.list(
161+
created_variable_set_id, var_list_options
162+
)
152163
)
153164
print(f"Found {len(variables)} variables in the set:")
154165

155-
for var in variables:
166+
for var in client.variable_set_variables.list(
167+
created_variable_set_id, var_list_options
168+
):
156169
sensitive_note = " (sensitive)" if var.sensitive else ""
157170
hcl_note = " (HCL)" if var.hcl else ""
158171
print(f"- {var.key}: {var.category.value}{sensitive_note}{hcl_note}")
@@ -212,10 +225,14 @@ def variable_set_example():
212225
print("Successfully applied to workspace")
213226

214227
# List variable sets for this workspace
215-
workspace_varsets = client.variable_sets.list_for_workspace(
228+
print(f"Listing variable sets for workspace: {first_workspace.name}")
229+
workspace_varsets = 0
230+
for ws_varset in client.variable_sets.list_for_workspace(
216231
first_workspace.id
217-
)
218-
print(f"Workspace now has {len(workspace_varsets)} variable sets")
232+
):
233+
print(f"- {ws_varset.name} (ID: {ws_varset.id})")
234+
workspace_varsets += 1
235+
print(f"Workspace now has {workspace_varsets} variable sets")
219236

220237
# Remove from workspace
221238
remove_ws_options = VariableSetRemoveFromWorkspacesOptions(
@@ -250,10 +267,14 @@ def variable_set_example():
250267
print("Successfully applied to project")
251268

252269
# List variable sets for this project
253-
project_varsets = client.variable_sets.list_for_project(
270+
print(f"Listing variable sets for project: {first_project.name}")
271+
project_varsets = 0
272+
for proj_varset in client.variable_sets.list_for_project(
254273
first_project.id
255-
)
256-
print(f"Project now has {len(project_varsets)} variable sets")
274+
):
275+
print(f"- {proj_varset.name} (ID: {proj_varset.id})")
276+
project_varsets += 1
277+
print(f"Project now has {project_varsets} variable sets")
257278

258279
# Remove from project
259280
remove_proj_options = VariableSetRemoveFromProjectsOptions(

src/pytfe/models/variable_set.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,6 @@ class VariableSetListOptions(BaseModel):
6969
"""Options for listing variable sets."""
7070

7171
# Pagination options
72-
page_number: int | None = None
7372
page_size: int | None = None
7473
include: list[VariableSetIncludeOpt] | None = None
7574
query: str | None = None # Filter by name

src/pytfe/resources/variable_sets.py

Lines changed: 17 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Variable Set resource implementation for the Python TFE SDK."""
22

33
import builtins
4+
from collections.abc import Iterator
45
from typing import Any
56

67
from .._http import HTTPTransport
@@ -48,16 +49,15 @@ def list(
4849
self,
4950
organization: str,
5051
options: VariableSetListOptions | None = None,
51-
) -> list[VariableSet]:
52+
) -> Iterator[VariableSet]:
5253
"""List all variable sets within an organization.
5354
5455
Args:
5556
organization: Organization name
5657
options: Optional parameters for filtering and pagination
5758
5859
Returns:
59-
List of VariableSet objects
60-
60+
Iterator of VariableSet objects within the organization
6161
Raises:
6262
ValueError: If organization name is invalid
6363
TFEError: If API request fails
@@ -69,33 +69,29 @@ def list(
6969
params: dict[str, str] = {}
7070

7171
if options:
72-
if options.page_number:
73-
params["page[number]"] = str(options.page_number)
7472
if options.page_size:
7573
params["page[size]"] = str(options.page_size)
7674
if options.query:
7775
params["q"] = options.query
7876
if options.include:
7977
params["include"] = ",".join([opt.value for opt in options.include])
8078

81-
response = self.t.request("GET", path, params=params)
82-
data = response.json()
83-
84-
return self._parse_variable_sets_response(data)
79+
for item in self._list(path, params=params):
80+
yield self._parse_variable_set(item)
8581

8682
def list_for_workspace(
8783
self,
8884
workspace_id: str,
8985
options: VariableSetListOptions | None = None,
90-
) -> builtins.list[VariableSet]:
86+
) -> Iterator[VariableSet]:
9187
"""List variable sets associated with a workspace.
9288
9389
Args:
9490
workspace_id: Workspace ID
9591
options: Optional parameters for filtering and pagination
9692
9793
Returns:
98-
List of VariableSet objects associated with the workspace
94+
Iterator of VariableSet objects associated with the workspace
9995
10096
Raises:
10197
ValueError: If workspace_id is invalid
@@ -108,33 +104,29 @@ def list_for_workspace(
108104
params: dict[str, str] = {}
109105

110106
if options:
111-
if options.page_number:
112-
params["page[number]"] = str(options.page_number)
113107
if options.page_size:
114108
params["page[size]"] = str(options.page_size)
115109
if options.query:
116110
params["q"] = options.query
117111
if options.include:
118112
params["include"] = ",".join([opt.value for opt in options.include])
119113

120-
response = self.t.request("GET", path, params=params)
121-
data = response.json()
122-
123-
return self._parse_variable_sets_response(data)
114+
for item in self._list(path, params=params):
115+
yield self._parse_variable_set(item)
124116

125117
def list_for_project(
126118
self,
127119
project_id: str,
128120
options: VariableSetListOptions | None = None,
129-
) -> builtins.list[VariableSet]:
121+
) -> Iterator[VariableSet]:
130122
"""List variable sets associated with a project.
131123
132124
Args:
133125
project_id: Project ID
134126
options: Optional parameters for filtering and pagination
135127
136128
Returns:
137-
List of VariableSet objects associated with the project
129+
Iterator of VariableSet objects associated with the project
138130
139131
Raises:
140132
ValueError: If project_id is invalid
@@ -147,19 +139,15 @@ def list_for_project(
147139
params: dict[str, str] = {}
148140

149141
if options:
150-
if options.page_number:
151-
params["page[number]"] = str(options.page_number)
152142
if options.page_size:
153143
params["page[size]"] = str(options.page_size)
154144
if options.query:
155145
params["q"] = options.query
156146
if options.include:
157147
params["include"] = ",".join([opt.value for opt in options.include])
158148

159-
response = self.t.request("GET", path, params=params)
160-
data = response.json()
161-
162-
return self._parse_variable_sets_response(data)
149+
for item in self._list(path, params=params):
150+
yield self._parse_variable_set(item)
163151

164152
def create(
165153
self,
@@ -714,15 +702,15 @@ def list(
714702
self,
715703
variable_set_id: str,
716704
options: VariableSetVariableListOptions | None = None,
717-
) -> list[VariableSetVariable]:
705+
) -> Iterator[VariableSetVariable]:
718706
"""List all variables in a variable set.
719707
720708
Args:
721709
variable_set_id: Variable set ID
722710
options: Optional parameters for pagination
723711
724712
Returns:
725-
List of VariableSetVariable objects
713+
Iterator of VariableSetVariable objects
726714
727715
Raises:
728716
ValueError: If variable_set_id is invalid
@@ -735,19 +723,11 @@ def list(
735723
params: dict[str, str] = {}
736724

737725
if options:
738-
if options.page_number:
739-
params["page[number]"] = str(options.page_number)
740726
if options.page_size:
741727
params["page[size]"] = str(options.page_size)
742728

743-
response = self.t.request("GET", path, params=params)
744-
data = response.json()
745-
746-
variables = []
747-
for item in data.get("data", []):
748-
variables.append(self._parse_variable_set_variable(item))
749-
750-
return variables
729+
for item in self._list(path, params=params):
730+
yield self._parse_variable_set_variable(item)
751731

752732
def create(
753733
self,

tests/units/test_variable_sets.py

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def test_list_variable_sets_success(self):
7272
self.mock_transport.request.return_value = mock_response
7373

7474
# Call the method
75-
result = self.variable_sets_service.list(self.org_name)
75+
result = list(self.variable_sets_service.list(self.org_name))
7676

7777
# Assertions
7878
assert len(result) == 1
@@ -85,7 +85,9 @@ def test_list_variable_sets_success(self):
8585

8686
# Verify API call
8787
self.mock_transport.request.assert_called_once_with(
88-
"GET", f"/api/v2/organizations/{self.org_name}/varsets", params={}
88+
"GET",
89+
f"/api/v2/organizations/{self.org_name}/varsets",
90+
params={"page[number]": 1, "page[size]": 100},
8991
)
9092

9193
def test_list_variable_sets_with_options(self):
@@ -97,21 +99,20 @@ def test_list_variable_sets_with_options(self):
9799

98100
# Create options
99101
options = VariableSetListOptions(
100-
page_number=2,
101102
page_size=50,
102103
query="test",
103104
include=[VariableSetIncludeOpt.WORKSPACES, VariableSetIncludeOpt.PROJECTS],
104105
)
105106

106107
# Call the method
107-
result = self.variable_sets_service.list(self.org_name, options)
108+
result = list(self.variable_sets_service.list(self.org_name, options))
108109

109110
# Verify the result
110111
assert isinstance(result, list)
111112

112113
# Verify API call with parameters
113114
expected_params = {
114-
"page[number]": "2",
115+
"page[number]": 1,
115116
"page[size]": "50",
116117
"q": "test",
117118
"include": "workspaces,projects",
@@ -125,10 +126,10 @@ def test_list_variable_sets_with_options(self):
125126
def test_list_variable_sets_invalid_organization(self):
126127
"""Test listing variable sets with invalid organization."""
127128
with pytest.raises(ValueError, match="Organization name is required"):
128-
self.variable_sets_service.list("")
129+
list(self.variable_sets_service.list(""))
129130

130131
with pytest.raises(ValueError, match="Organization name is required"):
131-
self.variable_sets_service.list(None)
132+
list(self.variable_sets_service.list(None))
132133

133134
def test_list_for_workspace_success(self):
134135
"""Test successful listing of variable sets for workspace."""
@@ -152,21 +153,23 @@ def test_list_for_workspace_success(self):
152153
self.mock_transport.request.return_value = mock_response
153154

154155
# Call the method
155-
result = self.variable_sets_service.list_for_workspace(self.workspace_id)
156+
result = list(self.variable_sets_service.list_for_workspace(self.workspace_id))
156157

157158
# Assertions
158159
assert len(result) == 1
159160
assert result[0].name == "workspace-varset"
160161

161162
# Verify API call
162163
self.mock_transport.request.assert_called_once_with(
163-
"GET", f"/api/v2/workspaces/{self.workspace_id}/varsets", params={}
164+
"GET",
165+
f"/api/v2/workspaces/{self.workspace_id}/varsets",
166+
params={"page[number]": 1, "page[size]": 100},
164167
)
165168

166169
def test_list_for_workspace_invalid_id(self):
167170
"""Test listing for workspace with invalid workspace ID."""
168171
with pytest.raises(ValueError, match="Workspace ID is required"):
169-
self.variable_sets_service.list_for_workspace("")
172+
list(self.variable_sets_service.list_for_workspace(""))
170173

171174
def test_list_for_project_success(self):
172175
"""Test successful listing of variable sets for project."""
@@ -190,21 +193,23 @@ def test_list_for_project_success(self):
190193
self.mock_transport.request.return_value = mock_response
191194

192195
# Call the method
193-
result = self.variable_sets_service.list_for_project(self.project_id)
196+
result = list(self.variable_sets_service.list_for_project(self.project_id))
194197

195198
# Assertions
196199
assert len(result) == 1
197200
assert result[0].name == "project-varset"
198201

199202
# Verify API call
200203
self.mock_transport.request.assert_called_once_with(
201-
"GET", f"/api/v2/projects/{self.project_id}/varsets", params={}
204+
"GET",
205+
f"/api/v2/projects/{self.project_id}/varsets",
206+
params={"page[number]": 1, "page[size]": 100},
202207
)
203208

204209
def test_list_for_project_invalid_id(self):
205210
"""Test listing for project with invalid project ID."""
206211
with pytest.raises(ValueError, match="Project ID is required"):
207-
self.variable_sets_service.list_for_project("")
212+
list(self.variable_sets_service.list_for_project(""))
208213

209214
def test_create_variable_set_success(self):
210215
"""Test successful variable set creation."""
@@ -731,7 +736,7 @@ def test_list_variables_success(self):
731736
self.mock_transport.request.return_value = mock_response
732737

733738
# Call the method
734-
result = self.variables_service.list(self.variable_set_id)
739+
result = list(self.variables_service.list(self.variable_set_id))
735740

736741
# Assertions
737742
assert len(result) == 1
@@ -748,13 +753,13 @@ def test_list_variables_success(self):
748753
self.mock_transport.request.assert_called_once_with(
749754
"GET",
750755
f"/api/v2/varsets/{self.variable_set_id}/relationships/vars",
751-
params={},
756+
params={"page[number]": 1, "page[size]": 100},
752757
)
753758

754759
def test_list_variables_invalid_varset_id(self):
755760
"""Test listing variables with invalid variable set ID."""
756761
with pytest.raises(ValueError, match="Variable set ID is required"):
757-
self.variables_service.list("")
762+
list(self.variables_service.list(""))
758763

759764
def test_create_variable_success(self):
760765
"""Test successful variable creation."""

0 commit comments

Comments
 (0)