Skip to content

Commit 8b9bb5b

Browse files
committed
Revert "added a chek_installed to SNowInstance."
This reverts commit 7fa6929.
1 parent 7fa6929 commit 8b9bb5b

File tree

3 files changed

+128
-128
lines changed

3 files changed

+128
-128
lines changed

src/browsergym/workarena/api/utils.py

Lines changed: 95 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,108 @@
22

33
from ..instance import SNowInstance
44

5-
6-
def table_api_call(instance: SNowInstance, *args, **kwargs) -> dict:
7-
"""Wrapper around SNowInstance.table_api_call for backwards compatibility"""
8-
return instance.table_api_call(*args, **kwargs)
9-
10-
115
from requests.exceptions import HTTPError
126
from time import sleep
137

148
# ServiceNow API configuration
159
SNOW_API_HEADERS = {"Content-Type": "application/json", "Accept": "application/json"}
1610

1711

12+
def table_api_call(
13+
instance: SNowInstance,
14+
table: str,
15+
data: dict = {},
16+
params: dict = {},
17+
json: dict = {},
18+
method: str = "GET",
19+
wait_for_record: bool = False,
20+
max_retries: int = 5,
21+
raise_on_wait_expired: bool = True,
22+
) -> dict:
23+
"""
24+
Make a call to the ServiceNow Table API
25+
26+
Parameters:
27+
-----------
28+
instance: SNowInstance
29+
The ServiceNow instance to interact with
30+
table: str
31+
The name of the table to interact with
32+
data: dict
33+
The data to send with the request
34+
params: dict
35+
The parameters to pass to the API
36+
json: dict
37+
The JSON data to send with the request
38+
method: str
39+
The HTTP method to use (GET, POST, PUT, DELETE).
40+
wait_for_record: bool
41+
If True, will wait up to 2 seconds for the record to be present before returning
42+
max_retries: int
43+
The number of retries to attempt before failing
44+
raise_on_wait_expired: bool
45+
If True, will raise an exception if the record is not found after max_retries.
46+
Otherwise, will return an empty result.
47+
48+
Returns:
49+
--------
50+
dict
51+
The JSON response from the API
52+
53+
"""
54+
55+
# Query API
56+
response = requests.request(
57+
method=method,
58+
url=instance.snow_url + f"/api/now/table/{table}",
59+
auth=instance.snow_credentials,
60+
headers=SNOW_API_HEADERS,
61+
data=data,
62+
params=params,
63+
json=json,
64+
)
65+
if method == "POST":
66+
sys_id = response.json()["result"]["sys_id"]
67+
data = {}
68+
params = {"sysparm_query": f"sys_id={sys_id}"}
69+
70+
# Check for HTTP success code (fail otherwise)
71+
response.raise_for_status()
72+
73+
record_exists = False
74+
num_retries = 0
75+
if method == "POST" or wait_for_record:
76+
while not record_exists:
77+
sleep(0.5)
78+
get_response = table_api_call(
79+
instance=instance,
80+
table=table,
81+
params=params,
82+
json=json,
83+
data=data,
84+
method="GET",
85+
)
86+
record_exists = len(get_response["result"]) > 0
87+
num_retries += 1
88+
if num_retries > max_retries:
89+
if raise_on_wait_expired:
90+
raise HTTPError(f"Record not found after {max_retries} retries")
91+
else:
92+
return {"result": []}
93+
if method == "GET":
94+
response = get_response
95+
96+
if method != "DELETE":
97+
# Decode the JSON response into a dictionary if necessary
98+
# When using wait_for_record=True, the response is already a dict as it is a recursive call
99+
if type(response) == dict:
100+
return response
101+
else:
102+
return response.json()
103+
else:
104+
return response
105+
106+
18107
def table_column_info(instance: SNowInstance, table: str) -> dict:
19108
"""
20109
Get the column information for a ServiceNow table

src/browsergym/workarena/install.py

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def _set_sys_property(property_name: str, value: str):
5656
Set a sys_property in the instance.
5757
5858
"""
59-
instance = SNowInstance(check_installed=False)
59+
instance = SNowInstance()
6060

6161
property = table_api_call(
6262
instance=instance,
@@ -82,7 +82,20 @@ def _set_sys_property(property_name: str, value: str):
8282
assert property["result"]["value"] == value, f"Error setting {property_name}."
8383

8484

85-
# Remove the _get_sys_property function as it's now in instance.py
85+
def _get_sys_property(property_name: str) -> str:
86+
"""
87+
Get a sys_property from the instance.
88+
89+
"""
90+
instance = SNowInstance()
91+
92+
property_value = table_api_call(
93+
instance=instance,
94+
table="sys_properties",
95+
params={"sysparm_query": f"name={property_name}", "sysparm_fields": "value"},
96+
)["result"][0]["value"]
97+
98+
return property_value
8699

87100

88101
def _install_update_set(path: str, name: str):
@@ -100,7 +113,7 @@ def _install_update_set(path: str, name: str):
100113
101114
"""
102115
with sync_playwright() as playwright:
103-
instance = SNowInstance(check_installed=False)
116+
instance = SNowInstance()
104117
browser = playwright.chromium.launch(headless=True, slow_mo=1000)
105118
page = browser.new_page()
106119
url_login(instance, page)
@@ -339,7 +352,7 @@ def setup_knowledge_bases():
339352
340353
"""
341354
# Get the ServiceNow instance
342-
instance = SNowInstance(check_installed=False)
355+
instance = SNowInstance()
343356
# Mapping between knowledge base name and filepath + whether or not to disable comments + whether or not to add article name
344357
knowledge_bases = {
345358
KB_NAME: (KB_FILEPATH, True, False),
@@ -406,7 +419,7 @@ def check_workflows_installed():
406419
"""
407420
expected_workflow_names = [x["name"] for x in WORKFLOWS.values()]
408421
workflows = table_api_call(
409-
instance=SNowInstance(check_installed=False),
422+
instance=SNowInstance(),
410423
table="wf_workflow",
411424
params={
412425
"sysparm_query": "nameIN" + ",".join(expected_workflow_names),
@@ -598,7 +611,7 @@ def setup_list_columns():
598611
}
599612

600613
logging.info("... Creating a new user account to validate list columns")
601-
admin_instance = SNowInstance(check_installed=False)
614+
admin_instance = SNowInstance()
602615
username, password, usysid = create_user(instance=admin_instance)
603616
user_instance = SNowInstance(snow_credentials=(username, password))
604617

@@ -704,7 +717,7 @@ def setup_form_fields():
704717
}
705718

706719
logging.info("... Creating a new user account to validate form fields")
707-
admin_instance = SNowInstance(check_installed=False)
720+
admin_instance = SNowInstance()
708721
username, password, usysid = create_user(instance=admin_instance)
709722
user_instance = SNowInstance(snow_credentials=(username, password))
710723

@@ -766,7 +779,7 @@ def check_instance_release_support():
766779
bool: True if the version is supported, False otherwise.
767780
768781
"""
769-
instance = SNowInstance(check_installed=False)
782+
instance = SNowInstance()
770783
version_info = instance.release_version
771784
if version_info["build name"] not in SNOW_SUPPORTED_RELEASES:
772785
logging.error(
@@ -803,11 +816,7 @@ def disable_welcome_help_popup():
803816
Disable the welcome help popup
804817
805818
"""
806-
set_user_preference(
807-
instance=SNowInstance(check_installed=False),
808-
key="overview_help.visited.navui",
809-
value="true",
810-
)
819+
set_user_preference(instance=SNowInstance(), key="overview_help.visited.navui", value="true")
811820
logging.info("Welcome help popup disabled.")
812821

813822

@@ -832,24 +841,24 @@ def setup_ui_themes():
832841
logging.info("Setting default UI theme")
833842
_set_sys_property(
834843
property_name="glide.ui.polaris.theme.custom",
835-
value=get_workarena_theme_variants(SNowInstance(check_installed=False))[0]["theme.sys_id"],
844+
value=get_workarena_theme_variants(SNowInstance())[0]["theme.sys_id"],
836845
)
837846

838847
# Set admin user's theme variant
839848
# ... get user's sysid
840849
admin_user = table_api_call(
841-
instance=SNowInstance(check_installed=False),
850+
instance=SNowInstance(),
842851
table="sys_user",
843852
params={"sysparm_query": "user_name=admin", "sysparm_fields": "sys_id"},
844853
)["result"][0]
845854
# ... set user preference
846855
set_user_preference(
847-
instance=SNowInstance(check_installed=False),
856+
instance=SNowInstance(),
848857
user=admin_user["sys_id"],
849858
key="glide.ui.polaris.theme.variant",
850859
value=[
851860
x["style.sys_id"]
852-
for x in get_workarena_theme_variants(SNowInstance(check_installed=False))
861+
for x in get_workarena_theme_variants(SNowInstance())
853862
if x["style.name"] == "Workarena"
854863
][0],
855864
)
@@ -861,7 +870,7 @@ def check_ui_themes_installed():
861870
862871
"""
863872
expected_variants = set([v.lower() for v in UI_THEMES_UPDATE_SET["variants"]])
864-
installed_themes = get_workarena_theme_variants(SNowInstance(check_installed=False))
873+
installed_themes = get_workarena_theme_variants(SNowInstance())
865874
installed_themes = set([t["style.name"].lower() for t in installed_themes])
866875

867876
assert (
@@ -884,7 +893,7 @@ def wipe_system_admin_preferences():
884893
"""
885894
logging.info("Wiping all system admin preferences")
886895
sys_admin_prefs = table_api_call(
887-
instance=SNowInstance(check_installed=False),
896+
instance=SNowInstance(),
888897
table="sys_user_preference",
889898
params={"sysparm_query": "user.user_name=admin", "sysparm_fields": "sys_id,name"},
890899
)["result"]
@@ -894,9 +903,7 @@ def wipe_system_admin_preferences():
894903
for pref in sys_admin_prefs:
895904
logging.info(f"...... deleting {pref['name']}")
896905
table_api_call(
897-
instance=SNowInstance(check_installed=False),
898-
table=f"sys_user_preference/{pref['sys_id']}",
899-
method="DELETE",
906+
instance=SNowInstance(), table=f"sys_user_preference/{pref['sys_id']}", method="DELETE"
900907
)
901908

902909

@@ -919,7 +926,7 @@ def patch_report_filters():
919926
"""
920927
logging.info("Patching reports with date filter...")
921928

922-
instance = SNowInstance(check_installed=False)
929+
instance = SNowInstance()
923930

924931
# Get all reports that are not already patched
925932
reports = table_api_call(
@@ -1047,8 +1054,7 @@ def main():
10471054
logging.basicConfig(level=logging.INFO)
10481055

10491056
try:
1050-
instance = SNowInstance(check_installed=False)
1051-
past_install_date = instance._get_sys_property("workarena.installation.date")
1057+
past_install_date = _get_sys_property("workarena.installation.date")
10521058
logging.info(f"Detected previous installation on {past_install_date}. Reinstalling...")
10531059
except:
10541060
past_install_date = "never"
@@ -1062,7 +1068,7 @@ def main():
10621068
██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
10631069
███ ███ ██████ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██ ████ ██ ██
10641070
1065-
Instance: {SNowInstance(check_installed=False).snow_url}
1071+
Instance: {SNowInstance().snow_url}
10661072
Previous installation: {past_install_date}
10671073
10681074
"""

0 commit comments

Comments
 (0)