Pulling a sub element in any array

Working with the F5 Cloud and pulling back pool data, want to query which servers are currently in the pool - three servers that may or may not currently be in the pool.

Partial json Structure:
{
“spec”:{

“origin_servers”: [
{
“public_ip”: {
“ip”: “10.170.247.102”
},
“labels”: {}
},
{
“public_ip”: {
“ip”: “10.170.247.104”
},
“labels”: {}
}
],
}
“port”: 8443
}
}

My code:
const JSONobj = pm.response.json();
var poolSpec = JSONobj.spec;
var servers = poolSpec.origin_servers;
pm.test(“server1_online”,function(){
for (var i = 0; i < servers.length; i++) {
pm.expect(servers[i].public_ip.ip).to.eql(“10.170.247.102”);
}
})

Result:
server1 | AssertionError: expected ‘10.170.247.104’ to deeply equal ‘10.170.247.102’

In the end, I’m looking to output a table:
server1 online
server2 offline
server online
But right now I’ll settle for
pass/fail server1_online
pass/fail server2_online
pass/fail server3_online

Ok, but what is your question? What area do you need help with?

Having a cursory look over your logic, your pm.test function should be inside the loop. Otherwise as soon as the first assertion fails, it will stop executing any more code. Plus the IP address for the comparison is hardcoded. Therefore if the servers have different IP addresses, only one will ever pass the test.

You could have an array of IP addresses for the servers that should exist in the response. Then loop through that array with an assertion that checks if the current IP address exists in the origin servers array from the response.

You can also use a technique called string literals to customize the test case name.

Here’s some code as an example…

const response = pm.response.json();

let public_ips = response.spec.origin_servers.map(origin_servers => origin_servers.public_ip.ip);

let serversToCheck = [
    {
        "serverName": "Server1",
        "ipAddress": "10.170.247.102"
    },
    {
        "serverName": "Server2",
        "ipAddress": "10.170.247.104"
    }
];

serversToCheck.forEach(server => {
    pm.test(`${server.serverName} - ${server.ipAddress} - Online`, () => {
        pm.expect(public_ips).to.include(server.ipAddress);
    });
});

image

If I change one of the IP addresses, then you can see it failing.

Thank you, that gave me what I needed to finish the testing script.