Can anyone help me with writing testcases of below python code
for individual_bmh in get_bmh_status():
if "unmanaged" in individual_bmh:
individual_bmh = individual_bmh.split(" ")
with open(r"/opt/cal/cipe/output/init.yaml", "r") as read_file:
data = yaml.load(read_file, Loader=SafeLoader)
load_dict = data["platform"]["baremetal"]["hosts"]
output = 
for i in range(len(load_dict)):
if load_dict[i]['name'] in individual_bmh:
name_node = load_dict[i]['name']
address = load_dict[i]['bmc']['address']
username = load_dict[i]['bmc']['username']
password = load_dict[i]['bmc']['password']
disablecert = load_dict[i]['bmc']['disableCertificateVerification']
# print('Name', name, 'Address:', address, 'username:', user, ' ', 'password:', pas, ' ', 'disableCertificateVerification:',
print(" name_node = ", name_node, "address = ", address, "username = ", username)
replace_string("bmh_cluster.yaml", certificate_string, individual_bmh, username,
password) # replace cluster name in template
# replace_string("bmh_cluster.yaml",individual_bmh,certificate_string) # replace data to original template value
edit_bmh(individual_bmh, address, disablecert)
restore_templatefile_name("bmh_cluster.yaml", certificate_string, individual_bmh, username, password)
The code you posted is clearly part of a larger program. It contains references to several names which are defined somewhere else (
restore_templatefile_name). Without knowing what these are, we cannot help you.
Furthermore, even if you posted the entire program, you are unlikely to find someone willing to write the test for you. You need to narrow down your question to something more specific. Here are some details that you should include to make it easier to help you:
- What do you want to test?
- What have you attempted yourself?
- Where did you get stuck?
Additionally, the code you are showing is difficult to write tests for because
- you are mixing in a single function:
- data input
- data processing
- data output
- the function does not even allow you to specify the data source (it has no parameters)
Could you please provide me some documents and videos where I can get the idea how to write test cases for such scenarios.
Pytest’s documentation is a good starting point.
With code that’s hard to write tests for, you really want to refactor to make that easier (to separate concerns, allow you to use test doubles, etc.). You can’t refactor safely without having tests in the first place because there’s nothing to catch when you break something.
Approvals testing is one way to get such a system under test, letting you refactor safely. Emily Bache has a great talk on the ideas here: Emily Bache "Handling Legacy Code with Approvals and Coverage" 2021/01/11 - YouTube. Her examples are in Java, but the concepts are universal. The Approvals library is available for Python and works with pytest: GitHub - approvals/ApprovalTests.Python: ApprovalTests for python.