class TestXMLParse(unittest.TestCase):
    def setUp(self):
        from openmtc_ngsi.xml import RequestParser
        self.parser = RequestParser()

    def test_RegisterContextRequest(self):
        from openmtc_ngsi.requests import RegisterContextRequest
        request = self.parser.parse_request(
            StringIO(registerContextRequestXML), RegisterContextRequest)
        self.assertIsInstance(request, RegisterContextRequest)
        self.assertIsInstance(request.contextRegistrationList, list)
        self.assertEqual(len(request.contextRegistrationList), 1)
        self.assertIsInstance(request.contextRegistrationList[0].entityIdList,
                              list)
        self.assertEqual(len(request.contextRegistrationList[0].entityIdList),
                         1,
                         len(request.contextRegistrationList[0].entityIdList))
        self.assertIsInstance(
            request.contextRegistrationList[0].entityIdList[0], EntityId)
        self.assertEqual(
            request.contextRegistrationList[0].entityIdList[0].type, "Room")

    def test_DiscoverContextAvailabilityRequest(self):
        from openmtc_ngsi.requests import DiscoverContextAvailabilityRequest
        request = self.parser.parse_request(
            StringIO(discoverContextAvailabilityRequestXML),
            DiscoverContextAvailabilityRequest)
        self.assertIsInstance(request, DiscoverContextAvailabilityRequest)
        self.assertIsInstance(request.entityIdList, list)
        self.assertEqual(len(request.entityIdList), 2)
        self.assertEqual(len(request.attributeList), 4)
        self.assertListEqual(
            request.attributeList,
            ["temperature", "pressure", "occupancy", "lightstatus"])
    def setUp(self):
        #self.scl_process = Popen(expanduser(SCL_PATH))

        #self.scl_process.wait(10)

        #raise Exception(self.scl_process.returncode)

        from openmtc_ngsi.xml import RequestParser
        self.parser = RequestParser()
        self.ngsi9 = NGSI_9()
    def setUp(self):
        super(NGSITestCaseBase, self).setUp()
        #self.scl_process = Popen(expanduser(SCL_PATH))

        #self.scl_process.wait(10)

        #raise Exception(self.scl_process.returncode)

        from openmtc_ngsi.xml import RequestParser
        self.parser = RequestParser()
        self.ngsi9 = NGSI_9()
        self.json_serializer = NGSIJSONWriter()
class TestNGSI9Internal(unittest.TestCase):
    def setUp(self):
        #self.scl_process = Popen(expanduser(SCL_PATH))

        #self.scl_process.wait(10)

        #raise Exception(self.scl_process.returncode)

        from openmtc_ngsi.xml import RequestParser
        self.parser = RequestParser()
        self.ngsi9 = NGSI_9()

    """    
    def tearDown(self):
        self.scl_process.send_signal(SIGTERM)
        self.scl_process.wait(15)
    """

    def _register(self):
        request = self.parser.parse_request(
            StringIO(registerContextRequestXML), RegisterContextRequest)
        return self.ngsi9.registerContext(request)

    def test_RegisterContext(self):
        from openmtc_ngsi.requests import RegisterContextResponse

        response = self._register()

        self.assertIsInstance(response, RegisterContextResponse)
        self.assertEqual(response.duration, 3600 * 24)
        self.assertIsNotNone(response.registrationId)

    def test_DiscoverContextAvailability(self):
        from openmtc_ngsi.requests import DiscoverContextAvailabilityRequest, DiscoverContextAvailabilityResponse
        from openmtc_ngsi.tests.xml import discoverContextAvailabilityRequestXML

        try:
            self._register()
        except NGSIError as e:
            if not isinstance(e[0], SCLConflict):
                raise

        request = self.parser.parse_request(
            StringIO(discoverContextAvailabilityRequestXML),
            DiscoverContextAvailabilityRequest)

        response = self.ngsi9.discoverContextAvailability(request)

        self.assertIsInstance(response, DiscoverContextAvailabilityResponse)
class HTTPTestCaseBase(TestCaseBase):
    ngsi_uri = "http://localhost:5050"
    parser = RequestParser()
    writer = NGSIXMLWriter()

    def setUp(self):
        super(HTTPTestCaseBase, self).setUp()

        self._start_flask()

        self.client = RestClient(self.ngsi_uri, content_type="application/xml")

    def _start_flask(self):
        self.flask_thread = Thread(target=self._run_flask)
        self.flask_thread.start()
        sleep(1)

    def _run_flask(self):
        import openmtc_ngsi.wsgi_flask
        openmtc_ngsi.wsgi_flask.reset()
        openmtc_ngsi.wsgi_flask.main()

    def tearDown(self):
        try:
            if self.flask_thread:
                import openmtc_ngsi.wsgi_flask
                openmtc_ngsi.wsgi_flask._server.shutdown()
                openmtc_ngsi.wsgi_flask._server.server_close()
                self.flask_thread.join(3)
                if self.flask_thread.isAlive():
                    raise Exception("Failed to stop flask")
                openmtc_ngsi.wsgi_flask._after_notify_hook = None
        finally:
            super(HTTPTestCaseBase, self).tearDown()

    def _send_request(self, path, data, name=None):
        if not isinstance(data, basestring):
            data = self.writer.serialize(data)
        name = name or self.ngsi_name
        path = name + path
        with self.client.post(path, data) as response:
            return self.parser.parse_request(response)

    def _register(self):
        return self._send_request("/registerContext",
                                  registerContextRequestXML, "/NGSI9")

    def _install_notification_handler(self, count=1, handler=None):
        import openmtc_ngsi.wsgi_flask
        handler = handler or NotificationHandler(num=self.num, count=count)
        openmtc_ngsi.wsgi_flask._after_notify_hook = handler
        return handler
class TestXMLParse_10(unittest.TestCase):
    def setUp(self):
        from openmtc_ngsi.xml import RequestParser
        self.parser = RequestParser()

    def test_UpdateContextRequest(self):
        request = self.parser.parse_request(StringIO(updateContextRequestXML),
                                            UpdateContextRequest)
        self.assertIsInstance(request, UpdateContextRequest)
        self.assertIsInstance(request.contextElementList, list)
        self.assertEqual(len(request.contextElementList), 1)
        self.assertIsInstance(request.contextElementList[0].entityId, EntityId)
        self.assertEqual(request.contextElementList[0].entityId.id,
                         "ConferenceRoom")
        self.assertEqual(request.contextElementList[0].entityId.type, "Room")
class NGSITestCaseBase(TestCaseBase):
    def __init__(self, *args, **kw):
        super(NGSITestCaseBase, self).__init__(*args, **kw)

        self._created = []

    def setUp(self):
        super(NGSITestCaseBase, self).setUp()
        #self.scl_process = Popen(expanduser(SCL_PATH))

        #self.scl_process.wait(10)

        #raise Exception(self.scl_process.returncode)

        from openmtc_ngsi.xml import RequestParser
        self.parser = RequestParser()
        self.ngsi9 = NGSI_9()
        self.json_serializer = NGSIJSONWriter()

    def tearDown(self):
        #        self.scl_process.send_signal(SIGTERM)
        #        self.scl_process.wait(15)
        for path in self._created:
            self.ngsi9.scl.delete(path)

        super(NGSITestCaseBase, self).tearDown()

    def _register(self):
        request = self.parser.parse_request(
            StringIO(registerContextRequestXML), RegisterContextRequest)
        response = self.ngsi9.registerContext(request)
        self._created.append(response._m2m_path)
        return response

    def _safe_register(self):
        try:
            self._register()
        except NGSIError as e:
            if not isinstance(e[0], SCLConflict):
                raise

    def _log_message_element(self, me):
        json = self.json_serializer.serialize(me, True)
        self.logger.info("%s: %s", type(me).__name__, json)
 def setUp(self):
     from openmtc_ngsi.xml import RequestParser
     self.parser = RequestParser()