Skip to content

Commit

Permalink
tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kreynoldsf5 committed May 2, 2024
1 parent 0a74764 commit 385e515
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 55 deletions.
2 changes: 1 addition & 1 deletion cloudapp/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def echo_html():

@app.route('/foo/', methods=['GET'])
def ex_test():
return jsonify({'info': 'bar'})
return jsonify({"info": { "foo": True}})

return app

Expand Down
54 changes: 4 additions & 50 deletions labapp/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import requests
import markdown
from ce import get_ce_info, get_ce_state
from fetch import cloudapp_fetch

app = Flask(__name__)
app.config['ce_info'] = None
Expand Down Expand Up @@ -43,53 +44,6 @@ def eph_ns() -> str:
this_eph_ns = request.cookies.get('eph_ns', None)
return this_eph_ns

def cloudapp_fetch(session, url, timeout, prop, value, headers = {}):
"""
Fetch data from URL
Validate prop and value in the JSON response
"""
response = session.get(url, timeout=timeout)
response.raise_for_status()
data = response.json()
if data.get(prop) != value:
raise ValueError(f"Invalid {prop}: expected {value}, got {data.get(prop)}")
if data.get("request_headers"):
clean_headers = headers_cleaner(data['request_headers'])
data['request_headers'] = clean_headers
return data
return data

def cloudapp_fetch2(session, url, timeout, prop, key, value):
"""
Fetch data from URL
Validate if a specific key-value pair is present in the dictionary located at `prop` in the JSON response
"""
response = session.get(url, timeout=timeout)
response.raise_for_status()
data = response.json()

prop_data = data.get(prop, {})
if not isinstance(prop_data, dict) or prop_data.get(key) != value:
raise ValueError(f"Expected {key}: {value} in {prop}, but got {key}: {prop_data.get(key)}")

if data.get("request_headers"):
clean_headers = headers_cleaner(data['request_headers'])
data['request_headers'] = clean_headers

return data

def headers_cleaner(headers):
"""
Remove headers that contain specific substrings.
Use this to make responses look nicer.
"""
unwanted_substrings = ['x-envoy', 'cloudfront', 'x-k8se']
filtered_headers = {
key: value for key, value in headers.items()
if not any(substring in key.lower() for substring in unwanted_substrings)
}
return filtered_headers

@app.errorhandler(404)
@app.errorhandler(500)
def return_err(err):
Expand Down Expand Up @@ -248,7 +202,7 @@ def ex_test():
s = requests.Session()
s.headers.update({"User-Agent": "MCN-Lab-Runner/1.0"})
url = f"https://foo.{app.config['base_url']}/"
data = cloudapp_fetch2(s, url, 5, 'info', 'bar')
data = cloudapp_fetch(s, url, 7, 'info', {"foo": True})
return jsonify(status='success', data=data)
except (LabException, requests.RequestException, ValueError) as e:
return jsonify(status='fail', error=str(e))
Expand All @@ -260,7 +214,7 @@ def ex_test2():
s = requests.Session()
s.headers.update({"User-Agent": "MCN-Lab-Runner/1.0"})
url = f"https://bar.{app.config['base_url']}/"
data = cloudapp_fetch(s, url, 5, 'info', 'foo')
data = cloudapp_fetch(s, url, 7, 'info', {"bar": True})
return jsonify(status='success', data=data)
except (LabException, requests.RequestException, ValueError) as e:
return jsonify(status='fail', error=str(e))
Expand All @@ -276,7 +230,7 @@ def lb_aws():
if not ns:
raise LabException("Ephemeral NS not set")
url = f"https://{ns}.{app.config['base_url']}"
data = cloudapp_fetch(s, url, 5, 'env', 'AWS')
data = cloudapp_fetch(s, url, 7, 'env', 'AWS', None)
return jsonify(status='success', data=data)
except (LabException, requests.RequestException, ValueError) as e:
return jsonify(status='fail', error=str(e))
Expand Down
51 changes: 51 additions & 0 deletions labapp/app/fetch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
def headers_cleaner(headers):
"""
Remove headers that contain specific substrings.
Use this to make responses look nicer.
"""
unwanted_substrings = ['x-envoy', 'cloudfront', 'x-k8se']
filtered_headers = {
key: value for key, value in headers.items()
if not any(substring in key.lower() for substring in unwanted_substrings)
}
return filtered_headers

def cloudapp_fetch(session, url, timeout, prop, value):
"""
Fetch data from URL
Validate prop and value in the JSON response
"""
response = session.get(url, timeout=timeout)
response.raise_for_status()
data = response.json()
print(data)
if data.get(prop) != value:
raise ValueError(f'Invalid {prop}: expected {value}, got {data.get(prop)}')
if data.get("request_headers"):
clean_headers = headers_cleaner(data['request_headers'])
data['request_headers'] = clean_headers
return data
return data

def cloudapp_fetch_new(session, url, timeout, prop, key, value):
"""
Fetch data from URL
Validate if a specific key-value pair is present in the dictionary located at `prop` in the JSON response
"""
response = session.get(url, timeout=timeout)
response.raise_for_status()

print(response.text)
data = response.json()

print(data)

prop_data = data.get(prop, {})
if not isinstance(prop_data, dict) or prop_data.get(key) != value:
raise ValueError(f"Expected {key}: {value} in {prop}, but got {dict}")

if data.get("request_headers"):
clean_headers = headers_cleaner(data['request_headers'])
data['request_headers'] = clean_headers

return data
12 changes: 8 additions & 4 deletions labapp/app/markdown/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ Here are some examples to try.
GET https://foo.f5demos.com/ HTTP/1.1
{
"info": "bar"
"info": {
"foo": True
}
}
```

Expand All @@ -89,15 +91,17 @@ document.getElementById('requestBtn1').addEventListener('click', () => {
</script>

The test made a request to <strong>https://foo.f5demos.com</strong>.
The test succeeded because the response contained the ``JSON`` string ``{ "info": "bar" }``.
The test succeeded because the response contained the ``JSON`` string ``{ "info": { "foo": True }}``.

<div style="height:25px"></div>

```http
GET https://bar.f5demos.com/ HTTP/1.1
{
"info": "foo"
"info": {
"bar": True
}
}
```

Expand All @@ -112,7 +116,7 @@ document.getElementById('requestBtn2').addEventListener('click', () => {
</script>

The test made a request to <strong>https://bar.f5demos.com</strong>.
The test failed because the response did not contain the ``JSON`` string ``{ "info": "bar" }``.
The test failed because the response did not contain the ``JSON`` string ``{ "info": { "bar": True}}``.


<div style="height:25px"></div>
Expand Down

0 comments on commit 385e515

Please sign in to comment.