#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  Generated from FHIR 4.0.1-9346c8cc45 on 2022-06-22.
#  2022, SMART Health IT.

import io
import json
import logging
import os
import typing
import unittest

from . import plandefinition

from .fhirdate import FHIRDate
import logging


class PlanDefinitionTests(unittest.TestCase):
    def instantiate_from(self, filename):
        datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
        with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle:
            js = json.load(handle)
            self.assertEqual("PlanDefinition", js["resourceType"])
        return plandefinition.PlanDefinition(js)
    
    def testPlanDefinition1(self):
        inst = self.instantiate_from("plandefinition-example-kdn5-simplified.json")
        self.assertIsNotNone(inst, "Must have instantiated a PlanDefinition instance")
        self.implPlanDefinition1(inst)
        
        js = inst.as_json()
        self.assertEqual("PlanDefinition", js["resourceType"])
        inst2 = plandefinition.PlanDefinition(js)
        self.implPlanDefinition1(inst2)
        self.evaluate_simplified_json(inst2)
    
    def implPlanDefinition1(self, inst):
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[0].definitionCanonical, "#1111")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[0].extension[0].extension[0].url, "day")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[0].extension[0].extension[0].valueInteger, 1)
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[0].extension[0].extension[1].url, "day")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[0].extension[0].extension[1].valueInteger, 8)
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[0].extension[0].url, "http://hl7.org/fhir/StructureDefinition/timing-daysOfCycle")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[0].id, "action-1")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[0].textEquivalent, "Gemcitabine 1250 mg/m² IV over 30 minutes on days 1 and 8")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[1].definitionCanonical, "#2222")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[1].extension[0].extension[0].url, "day")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[1].extension[0].extension[0].valueInteger, 1)
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[1].extension[0].url, "http://hl7.org/fhir/StructureDefinition/timing-daysOfCycle")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[1].id, "action-2")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[1].relatedAction[0].actionId, "action-1")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[1].relatedAction[0].relationship, "concurrent-with-start")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].action[1].textEquivalent, "CARBOplatin AUC 5 IV over 30 minutes on Day 1")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].id, "cycle-definition-1")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].textEquivalent, "21-day cycle for 6 cycles")
        self.assertEqual(inst.action[0].action[0].action[0].action[0].timingTiming.repeat.count, 6)
        self.assertEqual(inst.action[0].action[0].action[0].action[0].timingTiming.repeat.duration, 21)
        self.assertEqual(inst.action[0].action[0].action[0].action[0].timingTiming.repeat.durationUnit, "d")
        self.assertEqual(inst.action[0].action[0].action[0].groupingBehavior, "sentence-group")
        self.assertEqual(inst.action[0].action[0].action[0].selectionBehavior, "exactly-one")
        self.assertEqual(inst.action[0].action[0].selectionBehavior, "all")
        self.assertEqual(inst.action[0].selectionBehavior, "exactly-one")
        self.assertEqual(inst.approvalDate.date, FHIRDate("2016-07-27").date)
        self.assertEqual(inst.approvalDate.as_json(), "2016-07-27")
        self.assertEqual(inst.author[0].name, "Lee Surprenant")
        self.assertEqual(inst.contained[0].id, "1111")
        self.assertEqual(inst.contained[1].id, "2222")
        self.assertEqual(inst.copyright, "All rights reserved.")
        self.assertTrue(inst.experimental)
        self.assertEqual(inst.id, "KDN5")
        self.assertEqual(inst.identifier[0].system, "http://example.org/ordertemplates")
        self.assertEqual(inst.identifier[0].value, "KDN5")
        self.assertEqual(inst.lastReviewDate.date, FHIRDate("2016-07-27").date)
        self.assertEqual(inst.lastReviewDate.as_json(), "2016-07-27")
        self.assertEqual(inst.meta.tag[0].code, "HTEST")
        self.assertEqual(inst.meta.tag[0].display, "test health data")
        self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason")
        self.assertEqual(inst.publisher, "National Comprehensive Cancer Network, Inc.")
        self.assertEqual(inst.relatedArtifact[0].display, "NCCN Guidelines for Kidney Cancer. V.2.2016")
        self.assertEqual(inst.relatedArtifact[0].type, "derived-from")
        self.assertEqual(inst.relatedArtifact[0].url, "http://www.example.org/professionals/physician_gls/PDF/kidney.pdf")
        self.assertEqual(inst.relatedArtifact[1].citation, "Oudard S, et al. J Urol. 2007;177(5):1698-702")
        self.assertEqual(inst.relatedArtifact[1].type, "citation")
        self.assertEqual(inst.relatedArtifact[1].url, "http://www.ncbi.nlm.nih.gov/pubmed/17437788")
        self.assertEqual(inst.status, "draft")
        self.assertEqual(inst.text.status, "additional")
        self.assertEqual(inst.title, "Gemcitabine/CARBOplatin")
        self.assertEqual(inst.type.text, "Chemotherapy Order Template")
        self.assertEqual(inst.useContext[0].code.code, "treamentSetting-or-diseaseStatus")
        self.assertEqual(inst.useContext[0].code.system, "http://example.org/fhir/CodeSystem/indications")
        self.assertEqual(inst.useContext[0].extension[0].url, "http://hl7.org/fhir/StructureDefinition/usagecontext-group")
        self.assertEqual(inst.useContext[0].extension[0].valueString, "A")
        self.assertEqual(inst.useContext[0].valueCodeableConcept.text, "Metastatic")
        self.assertEqual(inst.useContext[1].code.code, "disease-or-histology")
        self.assertEqual(inst.useContext[1].code.system, "http://example.org/fhir/CodeSystem/indications")
        self.assertEqual(inst.useContext[1].extension[0].url, "http://hl7.org/fhir/StructureDefinition/usagecontext-group")
        self.assertEqual(inst.useContext[1].extension[0].valueString, "A")
        self.assertEqual(inst.useContext[1].valueCodeableConcept.text, "Collecting Duct/Medullary Subtypes")
        self.assertEqual(inst.useContext[2].code.code, "focus")
        self.assertEqual(inst.useContext[2].code.system, "http://terminology.hl7.org/CodeSystem/usage-context-type")
        self.assertEqual(inst.useContext[2].extension[0].url, "http://hl7.org/fhir/StructureDefinition/usagecontext-group")
        self.assertEqual(inst.useContext[2].extension[0].valueString, "A")
        self.assertEqual(inst.useContext[2].valueCodeableConcept.text, "Kidney Cancer")
        self.assertEqual(inst.useContext[3].code.code, "treatmentSetting-or-diseaseStatus")
        self.assertEqual(inst.useContext[3].code.system, "http://example.org/fhir/CodeSystem/indications")
        self.assertEqual(inst.useContext[3].extension[0].url, "http://hl7.org/fhir/StructureDefinition/usagecontext-group")
        self.assertEqual(inst.useContext[3].extension[0].valueString, "B")
        self.assertEqual(inst.useContext[3].valueCodeableConcept.text, "Relapsed")
        self.assertEqual(inst.useContext[4].code.code, "disease-or-histology")
        self.assertEqual(inst.useContext[4].code.system, "http://example.org/fhir/CodeSystem/indications")
        self.assertEqual(inst.useContext[4].extension[0].url, "http://hl7.org/fhir/StructureDefinition/usagecontext-group")
        self.assertEqual(inst.useContext[4].extension[0].valueString, "B")
        self.assertEqual(inst.useContext[4].valueCodeableConcept.text, "Collecting Duct/Medullary Subtypes")
        self.assertEqual(inst.useContext[5].code.code, "focus")
        self.assertEqual(inst.useContext[5].code.system, "http://terminology.hl7.org/CodeSystem/usage-context-type")
        self.assertEqual(inst.useContext[5].extension[0].url, "http://hl7.org/fhir/StructureDefinition/usagecontext-group")
        self.assertEqual(inst.useContext[5].extension[0].valueString, "B")
        self.assertEqual(inst.useContext[5].valueCodeableConcept.text, "Kidney Cancer – Collecting Duct/Medullary Subtypes - Metastatic")
        self.assertEqual(inst.version, "1")
    
    def testPlanDefinition2(self):
        inst = self.instantiate_from("plandefinition-options-example.json")
        self.assertIsNotNone(inst, "Must have instantiated a PlanDefinition instance")
        self.implPlanDefinition2(inst)
        
        js = inst.as_json()
        self.assertEqual("PlanDefinition", js["resourceType"])
        inst2 = plandefinition.PlanDefinition(js)
        self.implPlanDefinition2(inst2)
        self.evaluate_simplified_json(inst2)
    
    def implPlanDefinition2(self, inst):
        self.assertEqual(inst.action[0].action[0].definitionCanonical, "#activitydefinition-medicationrequest-1")
        self.assertEqual(inst.action[0].action[0].id, "medication-action-1")
        self.assertEqual(inst.action[0].action[0].title, "Administer Medication 1")
        self.assertEqual(inst.action[0].action[1].definitionCanonical, "#activitydefinition-medicationrequest-2")
        self.assertEqual(inst.action[0].action[1].id, "medication-action-2")
        self.assertEqual(inst.action[0].action[1].relatedAction[0].actionId, "medication-action-1")
        self.assertEqual(inst.action[0].action[1].relatedAction[0].offsetDuration.unit, "h")
        self.assertEqual(inst.action[0].action[1].relatedAction[0].offsetDuration.value, 1)
        self.assertEqual(inst.action[0].action[1].relatedAction[0].relationship, "after-end")
        self.assertEqual(inst.action[0].action[1].title, "Administer Medication 2")
        self.assertEqual(inst.action[0].groupingBehavior, "logical-group")
        self.assertEqual(inst.action[0].selectionBehavior, "all")
        self.assertEqual(inst.contained[0].id, "activitydefinition-medicationrequest-1")
        self.assertEqual(inst.contained[1].id, "activitydefinition-medicationrequest-2")
        self.assertEqual(inst.id, "options-example")
        self.assertEqual(inst.meta.tag[0].code, "HTEST")
        self.assertEqual(inst.meta.tag[0].display, "test health data")
        self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason")
        self.assertEqual(inst.status, "draft")
        self.assertEqual(inst.text.div, "<div xmlns=\"http://www.w3.org/1999/xhtml\">[Put rendering here]</div>")
        self.assertEqual(inst.text.status, "generated")
        self.assertEqual(inst.title, "This example illustrates relationships between actions.")
    
    def testPlanDefinition3(self):
        inst = self.instantiate_from("plandefinition-example-cardiology-os.json")
        self.assertIsNotNone(inst, "Must have instantiated a PlanDefinition instance")
        self.implPlanDefinition3(inst)
        
        js = inst.as_json()
        self.assertEqual("PlanDefinition", js["resourceType"])
        inst2 = plandefinition.PlanDefinition(js)
        self.implPlanDefinition3(inst2)
        self.evaluate_simplified_json(inst2)
    
    def implPlanDefinition3(self, inst):
        self.assertEqual(inst.action[0].action[0].action[0].definitionCanonical, "#referralToCardiologyConsult")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[0].expression.expression, "Now()")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[0].path, "timing.event")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[1].expression.expression, "Code '261QM0850X' from CardiologyChestPainLogic.\"NUCC Provider Taxonomy\" display 'Adult Mental Health'")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[1].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[1].path, "specialty")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[2].expression.expression, "CardiologyChestPainLogic.ServiceRequestFulfillmentTime")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[2].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[2].path, "occurrenceDateTime")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[3].expression.expression, "CardiologyChestPainLogic.Patient")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[3].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[3].path, "subject")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[4].expression.expression, "CardiologyChestPainLogic.Practitioner")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[4].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[4].path, "requester.agent")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[5].expression.expression, "CardiologyChestPainLogic.CardiologyReferralReason")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[5].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[5].path, "reasonCode")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[6].expression.expression, "CardiologyChestPainLogic.RiskAssessment")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[6].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[6].path, "reasonReference")
        self.assertEqual(inst.action[0].action[0].action[0].textEquivalent, "Referral to cardiology to evaluate chest pain (routine)")
        self.assertEqual(inst.action[0].action[0].action[1].definitionCanonical, "#CollectReferralReason")
        self.assertEqual(inst.action[0].action[0].action[1].title, "Reason for cardiology consultation")
        self.assertEqual(inst.action[0].action[0].action[2].definitionCanonical, "#CardiologyConsultationGoal")
        self.assertEqual(inst.action[0].action[0].action[2].title, "Goal of cardiology consultation")
        self.assertEqual(inst.action[0].action[0].groupingBehavior, "logical-group")
        self.assertEqual(inst.action[0].action[0].selectionBehavior, "any")
        self.assertEqual(inst.action[0].action[0].title, "Consults and Referrals")
        self.assertEqual(inst.action[0].action[1].action[0].groupingBehavior, "logical-group")
        self.assertEqual(inst.action[0].action[1].action[0].selectionBehavior, "at-most-one")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].definitionCanonical, "#metoprololTartrate25Prescription")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].dynamicValue[0].expression.expression, "'draft'")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].dynamicValue[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].dynamicValue[0].path, "status")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].dynamicValue[1].expression.expression, "CardiologyChestPainLogic.Patient")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].dynamicValue[1].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].dynamicValue[1].path, "patient")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].dynamicValue[2].expression.expression, "CardiologyChestPainLogic.Practitioner")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].dynamicValue[2].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].dynamicValue[2].path, "prescriber")
        self.assertEqual(inst.action[0].action[1].action[1].action[0].textEquivalent, "metoprolol tartrate 25 mg tablet 1 tablet oral 2 time daily")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].definitionCanonical, "#metoprololTartrate50Prescription")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].dynamicValue[0].expression.expression, "'draft'")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].dynamicValue[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].dynamicValue[0].path, "status")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].dynamicValue[1].expression.expression, "CardiologyChestPainLogic.Patient")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].dynamicValue[1].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].dynamicValue[1].path, "patient")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].dynamicValue[2].expression.expression, "CardiologyChestPainLogic.Practitioner")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].dynamicValue[2].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].dynamicValue[2].path, "prescriber")
        self.assertEqual(inst.action[0].action[1].action[1].action[1].textEquivalent, "metoprolol tartrate 50 mg tablet 1 tablet oral 2 time daily")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].definitionCanonical, "#amlodipinePrescription")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].dynamicValue[0].expression.expression, "'draft'")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].dynamicValue[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].dynamicValue[0].path, "status")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].dynamicValue[1].expression.expression, "CardiologyChestPainLogic.Patient")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].dynamicValue[1].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].dynamicValue[1].path, "patient")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].dynamicValue[2].expression.expression, "CardiologyChestPainLogic.Practitioner")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].dynamicValue[2].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].dynamicValue[2].path, "prescriber")
        self.assertEqual(inst.action[0].action[1].action[1].action[2].textEquivalent, "amlodipine 5  tablet 1 tablet oral  daily")
        self.assertEqual(inst.action[0].action[1].action[1].groupingBehavior, "logical-group")
        self.assertEqual(inst.action[0].action[1].action[1].selectionBehavior, "at-most-one")
        self.assertEqual(inst.action[0].action[1].action[1].title, "Antianginal Therapy")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].definitionCanonical, "#nitroglycerinPrescription")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].dynamicValue[0].expression.expression, "'draft'")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].dynamicValue[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].dynamicValue[0].path, "status")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].dynamicValue[1].expression.expression, "CardiologyChestPainLogic.Patient")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].dynamicValue[1].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].dynamicValue[1].path, "patient")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].dynamicValue[2].expression.expression, "CardiologyChestPainLogic.Practitioner")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].dynamicValue[2].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].dynamicValue[2].path, "prescriber")
        self.assertEqual(inst.action[0].action[1].action[2].action[0].textEquivalent, "nitroglycerin 0.4 mg tablet sub-lingual every 5 minutes as needed for chest pain; maximum 3 tablets")
        self.assertEqual(inst.action[0].action[1].action[2].groupingBehavior, "logical-group")
        self.assertEqual(inst.action[0].action[1].action[2].selectionBehavior, "at-most-one")
        self.assertEqual(inst.action[0].action[1].action[2].title, "Nitroglycerin")
        self.assertEqual(inst.action[0].action[1].description, "Consider the following medications for stable patients to be initiated prior to the cardiology consultation.")
        self.assertEqual(inst.action[0].action[1].title, "Medications")
        self.assertEqual(inst.author[0].name, "Bruce Bray MD")
        self.assertEqual(inst.author[1].name, "Scott Wall MD")
        self.assertEqual(inst.author[2].name, "Aiden Abidov MD, PhD")
        self.assertEqual(inst.contained[0].id, "cardiology-chestPain-logic")
        self.assertEqual(inst.contained[1].id, "referralToCardiologyConsult")
        self.assertEqual(inst.contained[2].id, "metoprololTartrate25Prescription")
        self.assertEqual(inst.contained[3].id, "metoprololTartrate25Medication")
        self.assertEqual(inst.contained[4].id, "metoprololTartrate25Substance")
        self.assertEqual(inst.contained[5].id, "metoprololTartrate50Prescription")
        self.assertEqual(inst.contained[6].id, "metoprololTartrate50Medication")
        self.assertEqual(inst.contained[7].id, "metoprololTartrate50Substance")
        self.assertEqual(inst.contained[8].id, "nitroglycerinPrescription")
        self.assertEqual(inst.contained[9].id, "nitroglycerinMedication")
        self.assertEqual(inst.copyright, "© Copyright Cognitive Medical Systems, Inc. 9444 Waples Street Suite 300 San Diego, CA 92121")
        self.assertEqual(inst.date.date, FHIRDate("2017-08-29").date)
        self.assertEqual(inst.date.as_json(), "2017-08-29")
        self.assertEqual(inst.id, "example-cardiology-os")
        self.assertEqual(inst.identifier[0].system, "urn:va.gov:kbs:knart:artifact:r1")
        self.assertEqual(inst.identifier[0].use, "official")
        self.assertEqual(inst.identifier[0].value, "bb7ccea6-9744-4743-854a-bcffd87191f6")
        self.assertEqual(inst.identifier[1].system, "urn:va.gov:kbs:contract:VA118-16-D-1008:to:VA-118-16-F-1008-0007")
        self.assertEqual(inst.identifier[1].value, "CLIN0004AG")
        self.assertEqual(inst.identifier[2].system, "urn:cognitivemedicine.com:lab:jira")
        self.assertEqual(inst.identifier[2].value, "KP-914")
        self.assertEqual(inst.library[0], "#cardiology-chestPain-logic")
        self.assertEqual(inst.name, "ChestPainCoronaryArteryDiseaseOrderSetKNART")
        self.assertEqual(inst.publisher, "Department of Veterans Affairs")
        self.assertEqual(inst.relatedArtifact[0].display, "Cardiology: Chest Pain (CP) / Coronary Artery Disease (CAD) Clinical Content White Paper")
        self.assertEqual(inst.relatedArtifact[0].type, "derived-from")
        self.assertEqual(inst.relatedArtifact[0].url, "NEED-A-URL-HERE")
        self.assertEqual(inst.relatedArtifact[1].display, "Outcome CVD (coronary death, myocardial infarction, coronary insufficiency, angina, ischemic stroke, hemorrhagic stroke, transient ischemic attack, peripheral artery disease, heart failure)")
        self.assertEqual(inst.relatedArtifact[1].type, "justification")
        self.assertEqual(inst.relatedArtifact[1].url, "https://www.framinghamheartstudy.org/risk-functions/cardiovascular-disease/10-year-risk.php")
        self.assertEqual(inst.relatedArtifact[2].display, "General cardiovascular risk profile for use in primary care: the Framingham Heart Study")
        self.assertEqual(inst.relatedArtifact[2].type, "justification")
        self.assertEqual(inst.relatedArtifact[2].url, "https://www.framinghamheartstudy.org/risk-functions/cardiovascular-disease/10-year-risk.php")
        self.assertEqual(inst.relatedArtifact[3].type, "justification")
        self.assertEqual(inst.relatedArtifact[3].url, "NEED-A-URL-HERE")
        self.assertEqual(inst.relatedArtifact[4].type, "justification")
        self.assertEqual(inst.relatedArtifact[4].url, "NEED-A-URL-HERE")
        self.assertEqual(inst.relatedArtifact[5].display, "LABEL: ASPIRIN 81 MG- aspirin tablet, coated")
        self.assertEqual(inst.relatedArtifact[5].type, "justification")
        self.assertEqual(inst.relatedArtifact[5].url, "https://dailymed.nlm.nih.gov/dailymed/drugInfo.cfm?setid=b4064039-2345-4227-b83d-54dc13a838d3")
        self.assertEqual(inst.relatedArtifact[6].display, "LABEL: CLOPIDOGREL- clopidogrel bisulfate tablet, film coated")
        self.assertEqual(inst.relatedArtifact[6].type, "justification")
        self.assertEqual(inst.relatedArtifact[6].url, "https://dailymed.nlm.nih.gov/dailymed/drugInfo.cfm?setid=7fe85155-bc00-406b-b097-e8aece187a8a")
        self.assertEqual(inst.relatedArtifact[7].display, "LABEL: LIPITOR- atorvastatin calcium tablet, film coated")
        self.assertEqual(inst.relatedArtifact[7].type, "justification")
        self.assertEqual(inst.relatedArtifact[7].url, "https://dailymed.nlm.nih.gov/dailymed/drugInfo.cfm?setid=7fe85155-bc00-406b-b097-e8aece187a8a")
        self.assertEqual(inst.relatedArtifact[8].display, "LABEL: METOPROLOL SUCCINATE EXTENDED-RELEASE - metoprolol succinate tablet, film coated, extended release")
        self.assertEqual(inst.relatedArtifact[8].type, "justification")
        self.assertEqual(inst.relatedArtifact[8].url, "https://dailymed.nlm.nih.gov/dailymed/drugInfo.cfm?setid=2d948600-35d8-4490-983b-918bdce488c8")
        self.assertEqual(inst.relatedArtifact[9].display, "LABEL: NITROGLYCERIN- nitroglycerin tablet")
        self.assertEqual(inst.relatedArtifact[9].type, "justification")
        self.assertEqual(inst.relatedArtifact[9].url, "https://dailymed.nlm.nih.gov/dailymed/drugInfo.cfm?setid=67bf2a15-b115-47ac-ae28-ce2dafd6b5c9")
        self.assertEqual(inst.status, "active")
        self.assertEqual(inst.text.status, "generated")
        self.assertEqual(inst.title, "Chest Pain (CP) - Coronary Artery Disease (CAD) Order Set KNART")
        self.assertEqual(inst.type.coding[0].code, "order-set")
        self.assertEqual(inst.type.coding[0].display, "Order Set")
        self.assertEqual(inst.type.coding[0].system, "http://terminology.hl7.org/CodeSystem/plan-definition-type")
        self.assertEqual(inst.url, "http://va.gov/kas/orderset/B5-Cardiology-ChestPainCAD-OS")
        self.assertEqual(inst.useContext[0].code.code, "focus")
        self.assertEqual(inst.useContext[0].code.system, "http://terminology.hl7.org/CodeSystem/usage-context-type")
        self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].code, "look up value")
        self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].display, "appropriate snomed condition")
        self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].system, "http://snomed.info/sct")
        self.assertEqual(inst.version, "0.1")
    
    def testPlanDefinition4(self):
        inst = self.instantiate_from("plandefinition-protocol-example.json")
        self.assertIsNotNone(inst, "Must have instantiated a PlanDefinition instance")
        self.implPlanDefinition4(inst)
        
        js = inst.as_json()
        self.assertEqual("PlanDefinition", js["resourceType"])
        inst2 = plandefinition.PlanDefinition(js)
        self.implPlanDefinition4(inst2)
        self.evaluate_simplified_json(inst2)
    
    def implPlanDefinition4(self, inst):
        self.assertEqual(inst.action[0].cardinalityBehavior, "single")
        self.assertEqual(inst.action[0].condition[0].expression.expression, "exists ([Condition: Obesity]) or not exists ([Observation: BMI] O where O.effectiveDateTime 2 years or less before Today())")
        self.assertEqual(inst.action[0].condition[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].condition[0].kind, "applicability")
        self.assertEqual(inst.action[0].definitionCanonical, "#procedure")
        self.assertEqual(inst.action[0].description, "Measure, Weight, Height, Waist, Circumference; Calculate BMI")
        self.assertEqual(inst.action[0].goalId[0], "reduce-bmi-ratio")
        self.assertEqual(inst.action[0].requiredBehavior, "must-unless-documented")
        self.assertEqual(inst.action[0].title, "Measure BMI")
        self.assertEqual(inst.author[0].name, "National Heart, Lung, and Blood Institute")
        self.assertEqual(inst.author[0].telecom[0].system, "url")
        self.assertEqual(inst.author[0].telecom[0].value, "https://www.nhlbi.nih.gov/health-pro/guidelines")
        self.assertEqual(inst.contained[0].id, "procedure")
        self.assertEqual(inst.goal[0].addresses[0].coding[0].code, "414916001")
        self.assertEqual(inst.goal[0].addresses[0].coding[0].display, "Obesity (disorder)")
        self.assertEqual(inst.goal[0].addresses[0].coding[0].system, "http://snomed.info/sct")
        self.assertEqual(inst.goal[0].category.text, "Treatment")
        self.assertEqual(inst.goal[0].description.text, "Reduce BMI to below 25")
        self.assertEqual(inst.goal[0].documentation[0].display, "Evaluation and Treatment Strategy")
        self.assertEqual(inst.goal[0].documentation[0].type, "justification")
        self.assertEqual(inst.goal[0].documentation[0].url, "https://www.nhlbi.nih.gov/health-pro/guidelines/current/obesity-guidelines/e_textbook/txgd/42.htm")
        self.assertEqual(inst.goal[0].id, "reduce-bmi-ratio")
        self.assertEqual(inst.goal[0].priority.text, "medium-priority")
        self.assertEqual(inst.goal[0].start.text, "When the patient's BMI Ratio is at or above 25")
        self.assertEqual(inst.goal[0].target[0].detailRange.high.unit, "kg/m2")
        self.assertEqual(inst.goal[0].target[0].detailRange.high.value, 24.9)
        self.assertEqual(inst.goal[0].target[0].due.unit, "a")
        self.assertEqual(inst.goal[0].target[0].due.value, 1)
        self.assertEqual(inst.goal[0].target[0].measure.coding[0].code, "39156-5")
        self.assertEqual(inst.goal[0].target[0].measure.coding[0].display, "Body mass index (BMI) [Ratio]")
        self.assertEqual(inst.goal[0].target[0].measure.coding[0].system, "http://loinc.org")
        self.assertEqual(inst.id, "protocol-example")
        self.assertEqual(inst.identifier[0].system, "http://acme.org")
        self.assertEqual(inst.identifier[0].value, "example-1")
        self.assertEqual(inst.meta.tag[0].code, "HTEST")
        self.assertEqual(inst.meta.tag[0].display, "test health data")
        self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason")
        self.assertEqual(inst.purpose, "Example of A medical algorithm for assessment and treatment of overweight and obesity")
        self.assertEqual(inst.relatedArtifact[0].display, "Overweight and Obesity Treatment Guidelines")
        self.assertEqual(inst.relatedArtifact[0].type, "derived-from")
        self.assertEqual(inst.relatedArtifact[0].url, "http://www.nhlbi.nih.gov/health-pro/guidelines/current/obesity-guidelines/e_textbook/txgd/algorthm/algorthm.htm")
        self.assertEqual(inst.status, "draft")
        self.assertEqual(inst.text.status, "generated")
        self.assertEqual(inst.title, "Obesity Assessment Protocol")
        self.assertEqual(inst.type.coding[0].code, "clinical-protocol")
        self.assertEqual(inst.useContext[0].code.code, "focus")
        self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].code, "414916001")
        self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].display, "Obesity (disorder)")
        self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].system, "http://snomed.info/sct")
    
    def testPlanDefinition5(self):
        inst = self.instantiate_from("plandefinition-example.json")
        self.assertIsNotNone(inst, "Must have instantiated a PlanDefinition instance")
        self.implPlanDefinition5(inst)
        
        js = inst.as_json()
        self.assertEqual("PlanDefinition", js["resourceType"])
        inst2 = plandefinition.PlanDefinition(js)
        self.implPlanDefinition5(inst2)
        self.evaluate_simplified_json(inst2)
    
    def implPlanDefinition5(self, inst):
        self.assertEqual(inst.action[0].action[0].action[0].definitionCanonical, "#referralToMentalHealthCare")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[0].expression.expression, "Now()")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[0].path, "timing.event")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[1].expression.expression, "Code '261QM0850X' from SuicideRiskLogic.\"NUCC Provider Taxonomy\" display 'Adult Mental Health'")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[1].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[1].path, "specialty")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[2].expression.expression, "SuicideRiskLogic.ServiceRequestFulfillmentTime")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[2].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[2].path, "occurrenceDateTime")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[3].expression.expression, "SuicideRiskLogic.Patient")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[3].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[3].path, "subject")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[4].expression.expression, "SuicideRiskLogic.Practitioner")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[4].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[4].path, "requester.agent")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[5].expression.expression, "SuicideRiskLogic.RiskAssessmentScore")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[5].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[5].path, "reasonCode")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[6].expression.expression, "SuicideRiskLogic.RiskAssessment")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[6].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].action[0].dynamicValue[6].path, "reasonReference")
        self.assertEqual(inst.action[0].action[0].action[0].textEquivalent, "Refer to outpatient mental health program for evaluation and treatment of mental health conditions now")
        self.assertEqual(inst.action[0].action[0].groupingBehavior, "logical-group")
        self.assertEqual(inst.action[0].action[0].selectionBehavior, "any")
        self.assertEqual(inst.action[0].action[0].title, "Consults and Referrals")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].definitionCanonical, "#citalopramPrescription")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[0].expression.expression, "'draft'")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[0].path, "status")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[1].expression.expression, "SuicideRiskLogic.Patient")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[1].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[1].path, "patient")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[2].expression.expression, "SuicideRiskLogic.Practitioner")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[2].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[2].path, "prescriber")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[3].expression.expression, "SuicideRiskLogic.RiskAssessmentScore")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[3].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[3].path, "reasonCode")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[4].expression.expression, "SuicideRiskLogic.RiskAssessment")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[4].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].dynamicValue[4].path, "reasonReference")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[0].textEquivalent, "citalopram 20 mg tablet 1 tablet oral 1 time daily now (30 table; 3 refills)")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[1].textEquivalent, "escitalopram 10 mg tablet 1 tablet oral 1 time daily now (30 tablet; 3 refills)")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[2].textEquivalent, "fluoxetine 20 mg capsule 1 capsule oral 1 time daily now (30 tablet; 3 refills)")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[3].textEquivalent, "paroxetine 20 mg tablet 1 tablet oral 1 time daily now (30 tablet; 3 refills)")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].action[4].textEquivalent, "sertraline 50 mg tablet 1 tablet oral 1 time daily now (30 tablet; 3 refills)")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].documentation[0].document.contentType, "text/html")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].documentation[0].document.title, "National Library of Medicine. DailyMed website. CITALOPRAM- citalopram hydrobromide tablet, film coated.")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].documentation[0].document.url, "http://dailymed.nlm.nih.gov/dailymed/drugInfo.cfm?setid=6daeb45c-451d-b135-bf8f-2d6dff4b6b01")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].documentation[0].type, "citation")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].groupingBehavior, "logical-group")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].selectionBehavior, "at-most-one")
        self.assertEqual(inst.action[0].action[1].action[0].action[0].title, "Selective Serotonin Reuptake Inhibitors (Choose a mazimum of one or document reasons for exception)")
        self.assertEqual(inst.action[0].action[1].action[0].action[1].textEquivalent, "Dopamine Norepinephrine Reuptake Inhibitors (Choose a maximum of one or document reasons for exception)")
        self.assertEqual(inst.action[0].action[1].action[0].action[2].textEquivalent, "Serotonin Norepinephrine Reuptake Inhibitors (Choose a maximum of one or doument reasons for exception)")
        self.assertEqual(inst.action[0].action[1].action[0].action[3].textEquivalent, "Norepinephrine-Serotonin Modulators (Choose a maximum of one or document reasons for exception)")
        self.assertEqual(inst.action[0].action[1].action[0].documentation[0].document.contentType, "text/html")
        self.assertEqual(inst.action[0].action[1].action[0].documentation[0].document.extension[0].url, "http://hl7.org/fhir/StructureDefinition/cqf-qualityOfEvidence")
        self.assertEqual(inst.action[0].action[1].action[0].documentation[0].document.extension[0].valueCodeableConcept.coding[0].code, "high")
        self.assertEqual(inst.action[0].action[1].action[0].documentation[0].document.extension[0].valueCodeableConcept.coding[0].system, "http://terminology.hl7.org/CodeSystem/evidence-quality")
        self.assertEqual(inst.action[0].action[1].action[0].documentation[0].document.extension[0].valueCodeableConcept.text, "High Quality")
        self.assertEqual(inst.action[0].action[1].action[0].documentation[0].document.title, "Practice Guideline for the Treatment of Patients with Major Depressive Disorder")
        self.assertEqual(inst.action[0].action[1].action[0].documentation[0].document.url, "http://psychiatryonline.org/pb/assets/raw/sitewide/practice_guidelines/guidelines/mdd.pdf")
        self.assertEqual(inst.action[0].action[1].action[0].documentation[0].type, "citation")
        self.assertEqual(inst.action[0].action[1].action[0].groupingBehavior, "logical-group")
        self.assertEqual(inst.action[0].action[1].action[0].selectionBehavior, "at-most-one")
        self.assertEqual(inst.action[0].action[1].action[0].title, "First-Line Antidepressants")
        self.assertEqual(inst.action[0].action[1].groupingBehavior, "logical-group")
        self.assertEqual(inst.action[0].action[1].selectionBehavior, "at-most-one")
        self.assertEqual(inst.action[0].action[1].title, "Medications")
        self.assertEqual(inst.action[0].title, "Suicide Risk Assessment and Outpatient Management")
        self.assertEqual(inst.approvalDate.date, FHIRDate("2016-03-12").date)
        self.assertEqual(inst.approvalDate.as_json(), "2016-03-12")
        self.assertEqual(inst.author[0].name, "Motive Medical Intelligence")
        self.assertEqual(inst.author[0].telecom[0].system, "phone")
        self.assertEqual(inst.author[0].telecom[0].use, "work")
        self.assertEqual(inst.author[0].telecom[0].value, "415-362-4007")
        self.assertEqual(inst.author[0].telecom[1].system, "email")
        self.assertEqual(inst.author[0].telecom[1].use, "work")
        self.assertEqual(inst.author[0].telecom[1].value, "info@motivemi.com")
        self.assertEqual(inst.contact[0].telecom[0].system, "phone")
        self.assertEqual(inst.contact[0].telecom[0].use, "work")
        self.assertEqual(inst.contact[0].telecom[0].value, "415-362-4007")
        self.assertEqual(inst.contact[0].telecom[1].system, "email")
        self.assertEqual(inst.contact[0].telecom[1].use, "work")
        self.assertEqual(inst.contact[0].telecom[1].value, "info@motivemi.com")
        self.assertEqual(inst.contained[0].id, "referralToMentalHealthCare")
        self.assertEqual(inst.contained[1].id, "citalopramPrescription")
        self.assertEqual(inst.contained[2].id, "citalopramMedication")
        self.assertEqual(inst.contained[3].id, "citalopramSubstance")
        self.assertEqual(inst.copyright, "© Copyright 2016 Motive Medical Intelligence. All rights reserved.")
        self.assertEqual(inst.date.date, FHIRDate("2015-08-15").date)
        self.assertEqual(inst.date.as_json(), "2015-08-15")
        self.assertEqual(inst.description, "Orders to be applied to a patient characterized as low suicide risk.")
        self.assertEqual(inst.effectivePeriod.end.date, FHIRDate("2017-12-31").date)
        self.assertEqual(inst.effectivePeriod.end.as_json(), "2017-12-31")
        self.assertEqual(inst.effectivePeriod.start.date, FHIRDate("2016-01-01").date)
        self.assertEqual(inst.effectivePeriod.start.as_json(), "2016-01-01")
        self.assertTrue(inst.experimental)
        self.assertEqual(inst.id, "low-suicide-risk-order-set")
        self.assertEqual(inst.identifier[0].system, "http://motivemi.com/artifacts")
        self.assertEqual(inst.identifier[0].use, "official")
        self.assertEqual(inst.identifier[0].value, "mmi:low-suicide-risk-order-set")
        self.assertEqual(inst.jurisdiction[0].coding[0].code, "US")
        self.assertEqual(inst.jurisdiction[0].coding[0].system, "urn:iso:std:iso:3166")
        self.assertEqual(inst.lastReviewDate.date, FHIRDate("2016-08-15").date)
        self.assertEqual(inst.lastReviewDate.as_json(), "2016-08-15")
        self.assertEqual(inst.library[0], "Library/suiciderisk-orderset-logic")
        self.assertEqual(inst.name, "LowSuicideRiskOrderSet")
        self.assertEqual(inst.publisher, "Motive Medical Intelligence")
        self.assertEqual(inst.purpose, "This order set helps ensure consistent application of appropriate orders for the care of low suicide risk patients.")
        self.assertEqual(inst.relatedArtifact[0].display, "Practice Guideline for the Treatment of Patients with Major Depressive Disorder")
        self.assertEqual(inst.relatedArtifact[0].type, "derived-from")
        self.assertEqual(inst.relatedArtifact[0].url, "http://psychiatryonline.org/pb/assets/raw/sitewide/practice_guidelines/guidelines/mdd.pdf")
        self.assertEqual(inst.relatedArtifact[1].resource, "ActivityDefinition/referralPrimaryCareMentalHealth")
        self.assertEqual(inst.relatedArtifact[1].type, "composed-of")
        self.assertEqual(inst.relatedArtifact[2].resource, "ActivityDefinition/citalopramPrescription")
        self.assertEqual(inst.relatedArtifact[2].type, "composed-of")
        self.assertEqual(inst.status, "active")
        self.assertEqual(inst.text.status, "generated")
        self.assertEqual(inst.title, "Low Suicide Risk Order Set")
        self.assertEqual(inst.topic[0].text, "Suicide risk assessment")
        self.assertEqual(inst.url, "http://motivemi.com/artifacts/PlanDefinition/low-suicide-risk-order-set")
        self.assertEqual(inst.usage, "This order set should be applied after assessing a patient for suicide risk, when the findings of that assessment indicate the patient has low suicide risk.")
        self.assertEqual(inst.useContext[0].code.code, "age")
        self.assertEqual(inst.useContext[0].code.system, "http://terminology.hl7.org/CodeSystem/usage-context-type")
        self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].code, "D000328")
        self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].display, "Adult")
        self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].system, "https://meshb.nlm.nih.gov")
        self.assertEqual(inst.useContext[1].code.code, "focus")
        self.assertEqual(inst.useContext[1].code.system, "http://terminology.hl7.org/CodeSystem/usage-context-type")
        self.assertEqual(inst.useContext[1].valueCodeableConcept.coding[0].code, "87512008")
        self.assertEqual(inst.useContext[1].valueCodeableConcept.coding[0].display, "Mild major depression")
        self.assertEqual(inst.useContext[1].valueCodeableConcept.coding[0].system, "http://snomed.info/sct")
        self.assertEqual(inst.useContext[2].code.code, "focus")
        self.assertEqual(inst.useContext[2].code.system, "http://terminology.hl7.org/CodeSystem/usage-context-type")
        self.assertEqual(inst.useContext[2].valueCodeableConcept.coding[0].code, "40379007")
        self.assertEqual(inst.useContext[2].valueCodeableConcept.coding[0].display, "Major depression, recurrent, mild")
        self.assertEqual(inst.useContext[2].valueCodeableConcept.coding[0].system, "http://snomed.info/sct")
        self.assertEqual(inst.useContext[3].code.code, "focus")
        self.assertEqual(inst.useContext[3].code.system, "http://terminology.hl7.org/CodeSystem/usage-context-type")
        self.assertEqual(inst.useContext[3].valueCodeableConcept.coding[0].code, "394687007")
        self.assertEqual(inst.useContext[3].valueCodeableConcept.coding[0].display, "Low suicide risk")
        self.assertEqual(inst.useContext[3].valueCodeableConcept.coding[0].system, "http://snomed.info/sct")
        self.assertEqual(inst.useContext[4].code.code, "focus")
        self.assertEqual(inst.useContext[4].code.system, "http://terminology.hl7.org/CodeSystem/usage-context-type")
        self.assertEqual(inst.useContext[4].valueCodeableConcept.coding[0].code, "225337009")
        self.assertEqual(inst.useContext[4].valueCodeableConcept.coding[0].display, "Suicide risk assessment")
        self.assertEqual(inst.useContext[4].valueCodeableConcept.coding[0].system, "http://snomed.info/sct")
        self.assertEqual(inst.useContext[5].code.code, "user")
        self.assertEqual(inst.useContext[5].code.system, "http://terminology.hl7.org/CodeSystem/usage-context-type")
        self.assertEqual(inst.useContext[5].valueCodeableConcept.coding[0].code, "309343006")
        self.assertEqual(inst.useContext[5].valueCodeableConcept.coding[0].display, "Physician")
        self.assertEqual(inst.useContext[5].valueCodeableConcept.coding[0].system, "http://snomed.info/sct")
        self.assertEqual(inst.useContext[6].code.code, "venue")
        self.assertEqual(inst.useContext[6].code.system, "http://terminology.hl7.org/CodeSystem/usage-context-type")
        self.assertEqual(inst.useContext[6].valueCodeableConcept.coding[0].code, "440655000")
        self.assertEqual(inst.useContext[6].valueCodeableConcept.coding[0].display, "Outpatient environment")
        self.assertEqual(inst.useContext[6].valueCodeableConcept.coding[0].system, "http://snomed.info/sct")
        self.assertEqual(inst.version, "1.0.0")
    
    def testPlanDefinition6(self):
        inst = self.instantiate_from("plandefinition-predecessor-example.json")
        self.assertIsNotNone(inst, "Must have instantiated a PlanDefinition instance")
        self.implPlanDefinition6(inst)
        
        js = inst.as_json()
        self.assertEqual("PlanDefinition", js["resourceType"])
        inst2 = plandefinition.PlanDefinition(js)
        self.implPlanDefinition6(inst2)
        self.evaluate_simplified_json(inst2)
    
    def implPlanDefinition6(self, inst):
        self.assertEqual(inst.action[0].action[0].condition[0].expression.expression, "Should Administer Zika Virus Exposure Assessment")
        self.assertEqual(inst.action[0].action[0].condition[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[0].condition[0].kind, "applicability")
        self.assertEqual(inst.action[0].action[0].definitionCanonical, "ActivityDefinition/administer-zika-virus-exposure-assessment")
        self.assertEqual(inst.action[0].action[1].condition[0].expression.expression, "Should Order Serum + Urine rRT-PCR Test")
        self.assertEqual(inst.action[0].action[1].condition[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[1].condition[0].kind, "applicability")
        self.assertEqual(inst.action[0].action[1].definitionCanonical, "ActivityDefinition/order-serum-urine-rrt-pcr-test")
        self.assertEqual(inst.action[0].action[2].condition[0].expression.expression, "Should Order Serum Zika Virus IgM + Dengue Virus IgM")
        self.assertEqual(inst.action[0].action[2].condition[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[2].condition[0].kind, "applicability")
        self.assertEqual(inst.action[0].action[2].definitionCanonical, "ActivityDefinition/order-serum-zika-dengue-virus-igm")
        self.assertEqual(inst.action[0].action[3].condition[0].expression.expression, "Should Consider IgM Antibody Testing")
        self.assertEqual(inst.action[0].action[3].condition[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[3].condition[0].kind, "applicability")
        self.assertEqual(inst.action[0].action[3].definitionCanonical, "ActivityDefinition/consider-igm-antibody-testing")
        self.assertEqual(inst.action[0].action[4].action[0].definitionCanonical, "ActivityDefinition/provide-mosquito-prevention-advice")
        self.assertEqual(inst.action[0].action[4].action[1].definitionCanonical, "ActivityDefinition/provide-contraception-advice")
        self.assertEqual(inst.action[0].action[4].condition[0].expression.expression, "Should Provide Mosquito Prevention and Contraception Advice")
        self.assertEqual(inst.action[0].action[4].condition[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].action[4].condition[0].kind, "applicability")
        self.assertEqual(inst.action[0].condition[0].expression.expression, "Is Patient Pregnant")
        self.assertEqual(inst.action[0].condition[0].expression.language, "text/cql")
        self.assertEqual(inst.action[0].condition[0].kind, "applicability")
        self.assertEqual(inst.action[0].title, "Zika Virus Assessment")
        self.assertEqual(inst.action[0].trigger[0].name, "patient-view")
        self.assertEqual(inst.action[0].trigger[0].type, "named-event")
        self.assertEqual(inst.date.date, FHIRDate("2016-11-14").date)
        self.assertEqual(inst.date.as_json(), "2016-11-14")
        self.assertEqual(inst.description, "Zika Virus Management intervention describing the CDC Guidelines for Zika Virus Reporting and Management.")
        self.assertEqual(inst.id, "zika-virus-intervention-initial")
        self.assertEqual(inst.identifier[0].use, "official")
        self.assertEqual(inst.identifier[0].value, "zika-virus-intervention")
        self.assertEqual(inst.library[0], "Library/zika-virus-intervention-logic")
        self.assertEqual(inst.relatedArtifact[0].type, "derived-from")
        self.assertEqual(inst.relatedArtifact[0].url, "https://www.cdc.gov/mmwr/volumes/65/wr/mm6539e1.htm?s_cid=mm6539e1_w")
        self.assertEqual(inst.relatedArtifact[1].resource, "PlanDefinition/zika-virus-intervention")
        self.assertEqual(inst.relatedArtifact[1].type, "successor")
        self.assertEqual(inst.status, "active")
        self.assertEqual(inst.text.status, "generated")
        self.assertEqual(inst.title, "Example Zika Virus Intervention")
        self.assertEqual(inst.topic[0].text, "Zika Virus Management")
        self.assertEqual(inst.url, "http://example.org/PlanDefinition/zika-virus-intervention")
        self.assertEqual(inst.version, "1.0.0")

    def evaluate_simplified_json(self, inst):
        """Ensure simplified json."""
        simplified_js, simplified_schema = inst.as_simplified_json()
        self.assertIsNotNone(simplified_js, "Must create simplified json")

        # test values
        for simplified_key, simplified_values in simplified_js.items():
            if not simplified_values:
                continue
            if not isinstance(simplified_values, typing.List):
                simplified_values = [simplified_values]
            for simplified_value in simplified_values:
                simplified_value_is_fhir_resource = 'fhirclient.models' in simplified_value.__class__.__name__
                if simplified_value_is_fhir_resource:
                    msg = "Should simplify value {} {} {}".format(simplified_key, simplified_value.__class__.__name__, vars(simplified_value))
                    self.assertFalse(simplified_value_is_fhir_resource, msg)



        # test simplify identifiers
        if hasattr(inst, 'identifier'):
            assert 'identifier' not in simplified_js
            if inst.identifier:
                simplified_identifiers = [k for k in simplified_js.keys() if k.startswith('identifier_')]
                if isinstance(inst.identifier, typing.List):
                    identifiers_with_values = [i for i in inst.identifier if i.value]
                else:
                    identifiers_with_values = [inst.identifier]
                self.assertEqual(len(identifiers_with_values), len(simplified_identifiers), "Should simplify identifiers.")

        # test simplify lists
        for name in vars(inst):

            if name == 'identifier':
                continue

            if name == 'extension':
                continue

            value = getattr(inst, name)

            is_coding = value.__class__.__name__ == 'Coding' or (isinstance(value, typing.List) and len(value) == 1 and value[0].__class__.__name__ == 'Coding')
            if is_coding:
                # why are we skipping Coding test?
                continue

            is_date = 'FHIRDate' in value.__class__.__name__
            if is_date:
                simplified_value_is_date = 'FHIRDate' in simplified_js[name].__class__.__name__
                self.assertFalse(simplified_value_is_date, "Should simplify Date {} {} {}".format(name, value.__class__.__name__, vars(value)) )

            if isinstance(getattr(inst, name), typing.List) and len(getattr(inst, name)) == 1:
                # Properties that need to be renamed because of language keyword conflicts
                # see mapping
                if name not in simplified_js:
                    name = name.replace("_fhir", "")
                self.assertFalse(isinstance(simplified_js[name], typing.List), "Should simplify lists {}".format(name))

        # test simplify coding
        # meta has known coding attribute 'tags'
        if hasattr(inst, 'meta'):
            if inst.meta and inst.meta.tag and len(inst.meta.tag) > 0:
                simplified_tags = [k for k in simplified_js['meta'].keys() if k.startswith('tag_')]
                self.assertEqual(len(inst.meta.tag), len(simplified_tags), "Should simplify meta tags.")
                self.assertTrue('tag' not in simplified_js['meta'], "Should not have meta.tag")

        # test simplify extensions
        if hasattr(inst, 'extension'):
            if inst.extension and len(inst.extension) > 0:
                assert 'extension' not in simplified_js
                simplified_extensions = [k for k in simplified_js.keys() if k.startswith('extension_')]
                self.assertEqual(len(inst.extension), len(simplified_extensions), "Should simplify extensions.")
                for simplified_extension in simplified_extensions:
                    assert simplified_js[simplified_extension], f"Missing value for {simplified_extension}"
                    assert 'fhirclient.models.coding.Coding' not in str(simplified_js[simplified_extension]), "Should simplify codes"
                    if simplified_js[simplified_extension] == 'NA':
                        logging.getLogger(__name__).warning(
                            "Extension.value is NA for resource_type:{} simplified_extension:{}".format(
                                inst.resource_type, simplified_extension))
        # test simplify schema
        for k in simplified_js:
            assert k in simplified_schema, "Should have a schema definition for {}".format(k)

        # test simplified, flattened
        from flatten_json import flatten
        flattened = flatten(simplified_js, separator='|')
        for flattened_key in flattened:
            dict_ = simplified_schema
            for flattened_key_part in flattened_key.split('|'):
                if flattened_key_part not in dict_ and flattened_key_part.isnumeric():
                    # traverse over list index
                    continue
                dict_ = dict_[flattened_key_part]
                self.assertIsNotNone(dict_, "Should have a schema entry for {}".format(flattened_key_part))
                if 'docstring' not in dict_:
                    logging.getLogger(__name__).warning(
                        "Missing docstring for resource_type:{} flattened_key:{} flattened_key_part:{} dict:{}".format(
                            inst.resource_type, flattened_key, flattened_key_part, dict_))
                    break