Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reads a set of FHIR resources from a folder, validates them against a server and dynamically builds a set of unittest cases Currently - put each JSON resource into the RESOURCE_FOLDER as a .json file (1 file per resource). #TODO Allow reading of XML resources and GETing a resource from a url.
import unittest
import os
import os.path
import json
import requests
"""
Reads a set of FHIR resources from a folder, validates them against a server
and dynamically builds a set of unittest cases
Currently - put each JSON resource into the RESOURCE_FOLDER as a .json file (1 file per resource).
#TODO Allow reading of XML resources and GETing a resource from a url.
"""
RESOURCE_FOLDER = "./resources"
VALIDATE_URL = "https://data.developer.nhs.uk/ccri-fhir/STU3/%(resourceType)s/$validate"
def load_resources(folder = RESOURCE_FOLDER):
resources = [] # [(filename,mimetype,resource),]
files = os.listdir(folder)
for name in files:
if name.endswith(".json"):
with open(os.path.join(folder,name),"r") as f:
json_resource = json.load(f)
resources.append((name,"application/fhir+json", json_resource))
elif name.endswith(".xml"):
raise ValueError("XML Not yet supported")
elif name.endswith(".urls"):
raise ValueError("URL List not yet supported")
return resources
def validate_resource(mimetype,resource):
headers = {"Content-Type": mimetype}
if mimetype == "application/fhir+json":
resource_type = resource["resourceType"]
else:
raise ValueError("Mimetype %s not supported" % mimetype)
validate_url = VALIDATE_URL % {"resourceType": resource_type}
response = requests.post(validate_url,data = json.dumps(resource),headers=headers)
return response.status_code,response
class TestResourceContainer(unittest.TestCase):
longMessage = True
def test_generator(status,response):
def test(self):
self.assertEqual(status,200,msg=response.text)
return test
def go():
resources = load_resources()
results = []
for name, mimetype, resource in resources:
status, response = validate_resource(mimetype, resource)
test_func = test_generator(status,response)
setattr(TestResourceContainer, 'test_{0}'.format(name), test_func)
unittest.main()
if __name__=="__main__":
go()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.