Skip to content

Commit 7fa6929

Browse files
committed
added a chek_installed to SNowInstance.
1 parent b8d0b90 commit 7fa6929

File tree

3 files changed

+128
-128
lines changed

3 files changed

+128
-128
lines changed

src/browsergym/workarena/api/utils.py

Lines changed: 6 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -2,108 +2,19 @@
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+
511
from requests.exceptions import HTTPError
612
from time import sleep
713

814
# ServiceNow API configuration
915
SNOW_API_HEADERS = {"Content-Type": "application/json", "Accept": "application/json"}
1016

1117

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-
10718
def table_column_info(instance: SNowInstance, table: str) -> dict:
10819
"""
10920
Get the column information for a ServiceNow table

src/browsergym/workarena/install.py

Lines changed: 26 additions & 32 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()
59+
instance = SNowInstance(check_installed=False)
6060

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

8484

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
85+
# Remove the _get_sys_property function as it's now in instance.py
9986

10087

10188
def _install_update_set(path: str, name: str):
@@ -113,7 +100,7 @@ def _install_update_set(path: str, name: str):
113100
114101
"""
115102
with sync_playwright() as playwright:
116-
instance = SNowInstance()
103+
instance = SNowInstance(check_installed=False)
117104
browser = playwright.chromium.launch(headless=True, slow_mo=1000)
118105
page = browser.new_page()
119106
url_login(instance, page)
@@ -352,7 +339,7 @@ def setup_knowledge_bases():
352339
353340
"""
354341
# Get the ServiceNow instance
355-
instance = SNowInstance()
342+
instance = SNowInstance(check_installed=False)
356343
# Mapping between knowledge base name and filepath + whether or not to disable comments + whether or not to add article name
357344
knowledge_bases = {
358345
KB_NAME: (KB_FILEPATH, True, False),
@@ -419,7 +406,7 @@ def check_workflows_installed():
419406
"""
420407
expected_workflow_names = [x["name"] for x in WORKFLOWS.values()]
421408
workflows = table_api_call(
422-
instance=SNowInstance(),
409+
instance=SNowInstance(check_installed=False),
423410
table="wf_workflow",
424411
params={
425412
"sysparm_query": "nameIN" + ",".join(expected_workflow_names),
@@ -611,7 +598,7 @@ def setup_list_columns():
611598
}
612599

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

@@ -717,7 +704,7 @@ def setup_form_fields():
717704
}
718705

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

@@ -779,7 +766,7 @@ def check_instance_release_support():
779766
bool: True if the version is supported, False otherwise.
780767
781768
"""
782-
instance = SNowInstance()
769+
instance = SNowInstance(check_installed=False)
783770
version_info = instance.release_version
784771
if version_info["build name"] not in SNOW_SUPPORTED_RELEASES:
785772
logging.error(
@@ -816,7 +803,11 @@ def disable_welcome_help_popup():
816803
Disable the welcome help popup
817804
818805
"""
819-
set_user_preference(instance=SNowInstance(), key="overview_help.visited.navui", value="true")
806+
set_user_preference(
807+
instance=SNowInstance(check_installed=False),
808+
key="overview_help.visited.navui",
809+
value="true",
810+
)
820811
logging.info("Welcome help popup disabled.")
821812

822813

@@ -841,24 +832,24 @@ def setup_ui_themes():
841832
logging.info("Setting default UI theme")
842833
_set_sys_property(
843834
property_name="glide.ui.polaris.theme.custom",
844-
value=get_workarena_theme_variants(SNowInstance())[0]["theme.sys_id"],
835+
value=get_workarena_theme_variants(SNowInstance(check_installed=False))[0]["theme.sys_id"],
845836
)
846837

847838
# Set admin user's theme variant
848839
# ... get user's sysid
849840
admin_user = table_api_call(
850-
instance=SNowInstance(),
841+
instance=SNowInstance(check_installed=False),
851842
table="sys_user",
852843
params={"sysparm_query": "user_name=admin", "sysparm_fields": "sys_id"},
853844
)["result"][0]
854845
# ... set user preference
855846
set_user_preference(
856-
instance=SNowInstance(),
847+
instance=SNowInstance(check_installed=False),
857848
user=admin_user["sys_id"],
858849
key="glide.ui.polaris.theme.variant",
859850
value=[
860851
x["style.sys_id"]
861-
for x in get_workarena_theme_variants(SNowInstance())
852+
for x in get_workarena_theme_variants(SNowInstance(check_installed=False))
862853
if x["style.name"] == "Workarena"
863854
][0],
864855
)
@@ -870,7 +861,7 @@ def check_ui_themes_installed():
870861
871862
"""
872863
expected_variants = set([v.lower() for v in UI_THEMES_UPDATE_SET["variants"]])
873-
installed_themes = get_workarena_theme_variants(SNowInstance())
864+
installed_themes = get_workarena_theme_variants(SNowInstance(check_installed=False))
874865
installed_themes = set([t["style.name"].lower() for t in installed_themes])
875866

876867
assert (
@@ -893,7 +884,7 @@ def wipe_system_admin_preferences():
893884
"""
894885
logging.info("Wiping all system admin preferences")
895886
sys_admin_prefs = table_api_call(
896-
instance=SNowInstance(),
887+
instance=SNowInstance(check_installed=False),
897888
table="sys_user_preference",
898889
params={"sysparm_query": "user.user_name=admin", "sysparm_fields": "sys_id,name"},
899890
)["result"]
@@ -903,7 +894,9 @@ def wipe_system_admin_preferences():
903894
for pref in sys_admin_prefs:
904895
logging.info(f"...... deleting {pref['name']}")
905896
table_api_call(
906-
instance=SNowInstance(), table=f"sys_user_preference/{pref['sys_id']}", method="DELETE"
897+
instance=SNowInstance(check_installed=False),
898+
table=f"sys_user_preference/{pref['sys_id']}",
899+
method="DELETE",
907900
)
908901

909902

@@ -926,7 +919,7 @@ def patch_report_filters():
926919
"""
927920
logging.info("Patching reports with date filter...")
928921

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

931924
# Get all reports that are not already patched
932925
reports = table_api_call(
@@ -1054,7 +1047,8 @@ def main():
10541047
logging.basicConfig(level=logging.INFO)
10551048

10561049
try:
1057-
past_install_date = _get_sys_property("workarena.installation.date")
1050+
instance = SNowInstance(check_installed=False)
1051+
past_install_date = instance._get_sys_property("workarena.installation.date")
10581052
logging.info(f"Detected previous installation on {past_install_date}. Reinstalling...")
10591053
except:
10601054
past_install_date = "never"
@@ -1068,7 +1062,7 @@ def main():
10681062
██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
10691063
███ ███ ██████ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██ ████ ██ ██
10701064
1071-
Instance: {SNowInstance().snow_url}
1065+
Instance: {SNowInstance(check_installed=False).snow_url}
10721066
Previous installation: {past_install_date}
10731067
10741068
"""

0 commit comments

Comments
 (0)