Skip to content

Commit

Permalink
revert mongo op changes
Browse files Browse the repository at this point in the history
  • Loading branch information
MiaAltieri committed May 3, 2024
1 parent 719df49 commit a0c32f9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 31 deletions.
53 changes: 27 additions & 26 deletions tests/integration/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ async def run_mongo_op(
suffix: str = "",
expecting_output: bool = True,
stringify: bool = True,
ignore_errors: bool = False,
expect_json_load: bool = True,
) -> SimpleNamespace():
"""Runs provided MongoDB operation in a separate container."""
if mongo_uri is None:
Expand Down Expand Up @@ -185,37 +185,38 @@ async def run_mongo_op(

output.succeeded = True
if expecting_output:
try:
output.data = json.loads(stdout)
except Exception:
logger.error(
"Could not serialize the output into json.{}{}".format(
f"\n\tSTDOUT:\n\t {stdout}" if stdout else "",
f"\n\tSTDERR:\n\t {stderr}" if stderr else "",
)
)
logger.error(f"Failed to serialize output: {output}".format(output=stdout))
if not ignore_errors:
raise
else:
output.data = _process_mongo_operation_result(stdout)
output.data = _process_mongo_operation_result(stdout, stderr, expect_json_load)
logger.info("Done: '%s'", output)
return output


def _process_mongo_operation_result(stdout: str):
"""Attempts to process the mongo operation result when `json.loads` fails to do so."""
def _process_mongo_operation_result(stdout, stderr, expect_json_load):
try:
logger.info("Attempt to cast to python dict manually")
# cast to python dict
dict_string = re.sub(r"(\w+)(\s*:\s*)", r'"\1"\2', stdout)
dict_string = (
dict_string.replace("true", "True").replace("false", "False").replace("null", "None")
)
return eval(dict_string)
return json.loads(stdout)
except Exception:
logger.error(f"Failed to cast response to python dict. Returning stdout: {stdout}")
return stdout
logger.error(
"Could not serialize the output into json.{}{}".format(
f"\n\tSTDOUT:\n\t {stdout}" if stdout else "",
f"\n\tSTDERR:\n\t {stderr}" if stderr else "",
)
)
logger.error(f"Failed to load operation result: {stdout} to json")
if expect_json_load:
raise
else:
try:
logger.info("Attempt to cast to python dict manually")
# cast to python dict
dict_string = re.sub(r"(\w+)(\s*:\s*)", r'"\1"\2', stdout)
dict_string = (
dict_string.replace("true", "True")
.replace("false", "False")
.replace("null", "None")
)
return eval(dict_string)
except Exception:
logger.error(f"Failed to cast response to python dict. Returning stdout: {stdout}")
return stdout


def primary_host(rs_status_data: dict) -> Optional[str]:
Expand Down
10 changes: 5 additions & 5 deletions tests/integration/relation_tests/test_charm_relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ async def verify_crud_operations(ops_test: OpsTest, connection_string: str):
ubuntu_name_updated = '{"$set": {"release_name": "Fancy Fossa"}}'
cmd = f"db.test_collection.updateOne({ubuntu_version}, {ubuntu_name_updated})"
result = await run_mongo_op(
ops_test, cmd, f'"{connection_string}"', stringify=False, ignore_errors=True
ops_test, cmd, f'"{connection_string}"', stringify=False, expect_json_load=True
)
assert result.data["acknowledged"] is True

Expand All @@ -123,7 +123,7 @@ async def verify_crud_operations(ops_test: OpsTest, connection_string: str):
# delete the data
cmd = 'db.test_collection.deleteOne({"release_name": "Fancy Fossa"})'
result = await run_mongo_op(
ops_test, cmd, f'"{connection_string}"', stringify=False, ignore_errors=True
ops_test, cmd, f'"{connection_string}"', stringify=False, expect_json_load=True
)
assert result.data["acknowledged"] is True

Expand Down Expand Up @@ -302,12 +302,12 @@ async def test_user_with_extra_roles(ops_test: OpsTest):

cmd = f'db.createUser({{user: "newTestUser", pwd: "Test123", roles: [{{role: "readWrite", db: "{database}"}}]}});'
result = await run_mongo_op(
ops_test, cmd, f'"{connection_string}"', stringify=False, ignore_errors=False
ops_test, cmd, f'"{connection_string}"', stringify=False, expect_json_load=False
)
assert "newTestUser" in result.data
cmd = 'db = db.getSiblingDB("new_database"); db.test_collection.insertOne({"test": "one"});'
result = await run_mongo_op(
ops_test, cmd, f'"{connection_string}"', stringify=False, ignore_errors=True
ops_test, cmd, f'"{connection_string}"', stringify=False, expect_json_load=True
)
assert '"acknowledged" : true' in result.data

Expand Down Expand Up @@ -460,7 +460,7 @@ async def test_removed_relation_no_longer_has_access(ops_test: OpsTest):
removed_access = False
cmd = "db.runCommand({ replSetGetStatus : 1 });"
result = await run_mongo_op(
ops_test, cmd, f'"{connection_string}"', stringify=False, ignore_errors=False
ops_test, cmd, f'"{connection_string}"', stringify=False, expect_json_load=False
)

removed_access = False
Expand Down

0 comments on commit a0c32f9

Please sign in to comment.