class Module07Test(unittest.TestCase):
    """
	Use this to setup your tests. This is where you may want to load configuration
	information (if needed), initialize class-scoped variables, create class-scoped
	instances of complex objects, initialize any requisite connections, etc.
	"""
    def setUp(self):
        host = '127.0.0.1'
        #port number to connect
        port = 5683
        #resource uri
        path = 'temperature'
        self.coap_client = CoapClientConnector(host, port, path)

    """
	Use this to tear down any allocated resources after your tests are complete. This
	is where you may want to release connections, zero out any long-term data, etc.
	"""

    def tearDown(self):
        #setting to none to destroy
        self.coap_client = None

    """
 Method to check ping 
	"""

    def test_pinging(self):
        """start ping test"""
        assert (self.coap_client.ping())

    """	Method to check GET	"""

    def test_get_method(self):
        """start get test"""
        assert (self.coap_client.get())

    """
 Method to check PUT
	"""

    def test_put_method(self):
        #demo json data
        jsonData = "{'name': 'temperature'}"
        assert (self.coap_client.put(jsonData))

    """
 Method to check POST
	"""

    def test_post_method(self):
        jsonData = "{'name': 'temperature'}"
        assert (self.coap_client.post(jsonData))

    """
 Method to check DELETE	
	"""

    def test_delete_method(self):
        assert (self.coap_client.delete())
 def setUp(self):
     host = '127.0.0.1'
     #port number to connect
     port = 5683
     #resource uri
     path = 'temperature'
     self.coap_client = CoapClientConnector(host, port, path)
Exemple #3
0
	def setUp(self):

		"""
		Initialize TempSensorAdaptor, TempSensorAdaptorTask, DeviceDataManager 
		and CoapClientConnector (Modules in Module7)
		"""
		self.tempSensorAdaptor 		= 		TempSensorAdaptor()
		self.tempSensorAdaptorTask	= 		TempSensorAdaptorTask()
		self.deviceDataManager 		= 		DeviceDataManager()
		self.coapClientConnector 	= 		CoapClientConnector()
    def setUp(self):

        #getting the host data
        host = ConfigUtil().getProperty(ConfigConst.COAP_DEVICE_SECTION,
                                        ConfigConst.HOST_KEY)

        #port number to connect
        port = int(ConfigUtil().getProperty(ConfigConst.COAP_DEVICE_SECTION,
                                            ConfigConst.PORT_KEY))

        #resource uri
        path = 'Temperature Resource'

        #connecting to my CoAp client connector
        self.coap_client = CoapClientConnector(host, port, path)
class DeviceDataManager(object):
    '''
    The manager for the device responsible for creating 
    the CoapClientConnector to be used for this Module
    Also responsible for starting the TempSensorAdaptor thread
    '''
    #Instantiate the modules
    coapClientConnector = CoapClientConnector()
    tempSensorAdaptor = TempSensorAdaptor()

    #Empty constructor as we do not want to initialize anything during instantiation
    def __init__(self):
        '''
        Constructor
        '''  
    """
    Method that passes its own reference CoapClientConnector to TempSensorAdaptor
    and starts the TempSensorAdaptor's thread so that it can get SensorData from
    the TempSensorAdaptorTask
    """
    def run(self):
        
        #Set the CoapClientConnector of the TempSensorAdaptor to the current CoapClientConnector reference
        self.tempSensorAdaptor.setCoapClient(self.coapClientConnector)
        
        #Enable the fetcher of adaptor
        self.tempSensorAdaptor.enableFetcher = True
        
        #Start
        self.tempSensorAdaptor.start()

        #will always return true as no error can occur here
        return True
class DeviceDataManager:
    #Default Constructor
    def __init__(self):
        self.sensorAdaptor = MultiSensorAdaptor()
        self.ccc = CoapClientConnector()

    # Method execution block
    def run(self):
        i = 0
        logging.info("Connecting to Server")
        while (i < 1):
            logging.info("Publishing data")
            message = DataUtil.toJsonFromSensorData(
                self.sensorAdaptor.getSensorData())
            self.ccc.send(message)
            i += 1
            sleep(5)
        logging.info("Finished Publishing")
        return True
class Module07Test(unittest.TestCase):
    """
	Use this to setup your tests. This is where you may want to load configuration
	information (if needed), initialize class-scoped variables, create class-scoped
	instances of complex objects, initialize any requisite connections, etc.
	"""
    def setUp(self):
        self.ccc = CoapClientConnector()
        pass

    """
	Use this to tear down any allocated resources after your tests are complete. This
	is where you may want to release connections, zero out any long-term data, etc.
	"""

    def tearDown(self):
        pass

    """
	Place your comments describing the test here.
	"""

    def testSend(self):
        message = "Test"
        self.assertTrue(self.ccc.send(message), "Message issues")

    def testPut(self):
        message = "Test"
        self.assertTrue(self.ccc.put(message), "put issues")

    def testGet(self):
        message = "Test"
        self.assertTrue(self.ccc.get(), "get issues")

    def testPost(self):
        message = "Test"
        self.assertTrue(self.ccc.put(message), "put issues")

    def testDelete(self):
        message = "Test"
        self.assertTrue(self.ccc.delete(), "delete issues")
Exemple #8
0
class Module07Test(unittest.TestCase):

	"""
	Use this to setup your tests. This is where you may want to load configuration
	information (if needed), initialize class-scoped variables, create class-scoped
	instances of complex objects, initialize any requisite connections, etc.
	"""
	def setUp(self):

		"""
		Initialize TempSensorAdaptor, TempSensorAdaptorTask, DeviceDataManager 
		and CoapClientConnector (Modules in Module7)
		"""
		self.tempSensorAdaptor 		= 		TempSensorAdaptor()
		self.tempSensorAdaptorTask	= 		TempSensorAdaptorTask()
		self.deviceDataManager 		= 		DeviceDataManager()
		self.coapClientConnector 	= 		CoapClientConnector()

	"""
	Use this to tear down any allocated resources after your tests are complete. This
	is where you may want to release connections, zero out any long-term data, etc.
	"""
	def tearDown(self):

		#Set the references for the modules in Module 7 to None to release any resources
		self.deviceDataManager = None
		self.coapClientConnector = None
		self.tempSensorAdaptor = None
		self.tempSensorAdaptorTask = None

	"""
	This method tests the sendSensorData() of CoapClientConnector module, 
	it checks for success (true) when valid host and resource name are given to 
	the method, and false when invalid host and resource name are given to the method
	"""
	def testSendSensorData(self):
		
		#Get the current event loop 
		loop = asyncio.get_event_loop()

		#Assert True when valid host and resource are given
		self.assertEqual(loop.run_until_complete(self.coapClientConnector.sendSensorData("TestString", "pallybook.lan", "Temp")), True)

		#Assert False when invalid host and resource are given
		self.assertEqual(loop.run_until_complete(self.coapClientConnector.sendSensorData("TestString", "notavalidhost", "TestResource")), False)

	"""
	This method tests the sendGETRequest() of CoapClientConnector module, 
	it checks for success (true) when valid host and resource name are given to 
	the method, and false when invalid host and resource name are given to the method
	"""
	def testSendGETRequest(self):
		
		#Get the current event loop 
		loop = asyncio.get_event_loop()
		
		#Assert True when valid host and resource are given
		self.assertEqual(loop.run_until_complete(self.coapClientConnector.sendGETRequest("pallybook.lan", "Temp")), True)

		#Assert False when invalid host and resource are given
		self.assertEqual(loop.run_until_complete(self.coapClientConnector.sendGETRequest("notavalidhost", "TestResource")), False)

	"""
	This method tests the sendDELETERequest() of CoapClientConnector module, 
	it checks for success (true) when valid host and resource name are given to 
	the method, and false when invalid host and resource name are given to the method
	"""
	def testSendDELETERequest(self):
		
		#Get the current event loop 
		loop = asyncio.get_event_loop()
		
		#Assert True when valid host and resource are given
		self.assertEqual(loop.run_until_complete(self.coapClientConnector.sendDELETERequest("pallybook.lan", "Temp")), True)

		#Assert False when invalid host and resource are given
		self.assertEqual(loop.run_until_complete(self.coapClientConnector.sendDELETERequest("notavalidhost", "TestResource")), False)

	"""
	This method tests the sendPOSTRequest() of CoapClientConnector module, 
	it checks for success (true) when valid host and resource name are given to 
	the method, and false when invalid host and resource name are given to the method
	"""
	def testSendPOSTRequest(self):
		
		#Get the current event loop 
		loop = asyncio.get_event_loop()
		
		#Assert True when valid host and resource are given
		self.assertEqual(loop.run_until_complete(self.coapClientConnector.sendPOSTRequest("Testing text", "pallybook.lan", "Temp")), True)

		#Assert False when invalid host and resource are given
		self.assertEqual(loop.run_until_complete(self.coapClientConnector.sendPOSTRequest("Testing text", "notavalidhost", "TestResource")), False)

	"""
	This method tests the prepareAndSendSensorData() of CoapClientConnectorModule. It
	tests for successful running when valid parameters are given(sensor data and event loop)
	And tests for indication of failure when invalid parameters are given (not sensor data type and
	no current event loop exists) 
	"""
	def testPrepareAndSendSensorData(self):

		#Get the current event loop
		loop = asyncio.get_event_loop()

		#Assert false when the event loop given is running but not valid SensorData given
		self.assertEqual(self.coapClientConnector.prepareAndSendSensorData("Hello", loop, "pallybook.lan", "Temp"), False)

		#Create a sensorData object
		sensorData = SensorData()

		#add a value to SensorData
		sensorData.addValue(9)

		#Assert true when given the current event loop is running and valid SensorData
		self.assertEqual(self.coapClientConnector.prepareAndSendSensorData(sensorData, loop, "pallybook.lan", "Temp"), True)

		#Get a new event loop
		loop = asyncio.new_event_loop()

		#Stop the loop such that there is no event loop currently
		loop.stop()

		#Assert false when the event loop given is not running but valid SensorData
		self.assertEqual(self.coapClientConnector.prepareAndSendSensorData(sensorData, loop, "pallybook.lan", "Temp"), False)

	"""
	This method tests the callGETRequest() of CoapClientConnectorModule. It
	tests for successful running when valid parameters are given(event loop)
	And tests for indication of failure when invalid parameters are given (no current event loop 
	exists) 
	"""
	def testCallGETRequest(self):

		#Get the current event loop
		loop = asyncio.get_event_loop()

		#Assert true when given the current event loop is running
		self.assertEqual(self.coapClientConnector.callGETRequest(loop, "pallybook.lan", "Temp"), True)

		#Get a new event loop
		loop = asyncio.new_event_loop()

		#Stop the loop such that there is no event loop currently
		loop.stop()

		#Assert false when the event loop given is not running 
		self.assertEqual(self.coapClientConnector.callGETRequest(loop, "pallybook.lan", "Temp"), False)

	"""
	This method tests the callDELETERequest() of CoapClientConnectorModule. It
	tests for successful running when valid parameters are given(event loop)
	And tests for indication of failure when invalid parameters are given (no current event loop 
	exists) 
	"""
	def testCallDELETERequest(self):

		#Get the current event loop
		loop = asyncio.get_event_loop()

		#Assert true when given the current event loop is running
		self.assertEqual(self.coapClientConnector.callDELETERequest(loop, "pallybook.lan", "Temp"), True)

	"""
	This method tests the callPOSTRequest() of CoapClientConnectorModule. It
	tests for successful running when valid parameters are given(event loop)
	And tests for indication of failure when invalid parameters are given (no current event loop 
	exists) 
	"""
	def testCallDELETERequest(self):

		#Get the current event loop
		loop = asyncio.get_event_loop()

		#Assert true when given the current event loop is running
		self.assertEqual(self.coapClientConnector.callPOSTRequest(loop, "Hello", "pallybook.lan", "Temp"), True)

		#Get a new event loop
		loop = asyncio.new_event_loop()

		#Stop the loop such that there is no event loop currently
		loop.stop()

		#Assert false when the event loop given is not running 
		self.assertEqual(self.coapClientConnector.callPOSTRequest(loop, "Hello", "pallybook.lan", "Temp"), False)

		#Get a new event loop
		loop = asyncio.new_event_loop()

		#Stop the loop such that there is no event loop currently
		loop.stop()

		#Assert false when the event loop given is not running 
		self.assertEqual(self.coapClientConnector.callDELETERequest(loop, "pallybook.lan", "Temp"), False)

	"""
	This method tests the callPOSTRequest() of CoapClientConnectorModule. It
	tests for successful running when valid parameters are given(event loop)
	And tests for indication of failure when invalid parameters are given (no current event loop 
	exists) 
	"""
	def testCallDELETERequest(self):

		#Get the current event loop
		loop = asyncio.get_event_loop()

		#Assert true when given the current event loop is running
		self.assertEqual(self.coapClientConnector.callPOSTRequest(loop, "Hello", "pallybook.lan", "Temp"), True)

		#Get a new event loop
		loop = asyncio.new_event_loop()

		#Stop the loop such that there is no event loop currently
		loop.stop()

		#Assert false when the event loop given is not running 
		self.assertEqual(self.coapClientConnector.callPOSTRequest(loop, "Hello", "pallybook.lan", "Temp"), False)

		#Get a new event loop
		loop = asyncio.new_event_loop()

		#Stop the loop such that there is no event loop currently
		loop.stop()

		#Assert false when the event loop given is not running 
		self.assertEqual(self.coapClientConnector.callDELETERequest(loop, "pallybook.lan", "Temp"), False)

	"""
	This method tests the setCoapClient() method of the TempSensorAdaptor
	It checks for false when sent a null instead of a reference of type CoapClientConnector, and true when 
	appropriate reference type passed
	"""
	def testSetMqttClientConnector(self):
		
		#Set an invalid reference and assert False for failure too assign
		self.assertEqual(False, self.tempSensorAdaptor.setCoapClient(None))

		#Set a valid reference and assert True for successful assignment
		self.assertEqual(True, self.tempSensorAdaptor.setCoapClient(self.coapClientConnector))
	
	"""
	This method tests the start() method of the TempSensorAdaptor
	It checks for false if the number of readings needed is 0 
	or if fetcher is not enabled. Checks true if the readings are taken
	"""
	def testStart(self):
		
		#Check for false when there is no reference to MQTT client connector
		self.assertEqual(False, self.tempSensorAdaptor.start())
		
		#Set the MQTT client connector reference to the current reference 
		self.tempSensorAdaptor.setCoapClient(self.coapClientConnector)
		
		#Enable the fetcher
		self.tempSensorAdaptor.enableFetcher = True
		
		#Change numReadings to a small finite value to check
		self.tempSensorAdaptor.numReadings = 1
		
		#Change sleep time (rateInSec) to a small amount
		self.tempSensorAdaptor.rateInSec = 1
		
		#Run when numReadings > 0 and adaptor is enabled, assert True for readings were taken
		self.assertEqual(True, self.tempSensorAdaptor.start())
		
		#Change numReadings to 0
		self.tempSensorAdaptor.numReadings = 0
		
		#Run when numReadings = 0 and fetcher is enabled, should return false because readings weren't taken
		self.assertEqual(False, self.tempSensorAdaptor.start())
		
		#Disable the fetcher
		self.tempSensorAdaptor.enableFetcher = False
		
		#Change readings to > 0
		self.tempSensorAdaptor.numReadings = 1
		
		#run when numReadings > 0 and Fetcher is disabled, should return false because readings weren't taken
		self.assertEqual(False, self.tempSensorAdaptor.start())

	"""
	This method tests the getTemperature() method of the TempSensorAdaptorTask
	It checks for difference between the gathered temperature from the method 
	should not exceed 55 degrees celsius or be less than -30 degrees celsius 
	(A VALID TEMPERATURE RANGE)
	"""
	def testGetTemperature(self):

		#Get the temperature 
		temperature = self.tempSensorAdaptorTask.getTemperature()

		#Assert if less than 55 degrees
		self.assertTrue(temperature.getCurrentValue() < 55)

		#Assert if greater than -30 degrees
		self.assertTrue(temperature.getCurrentValue() > -30)

	"""
	This method tests the run() method of the DeviceDataManager
	It asserts true always
	"""
	def testRun(self):

		#Set the number of readings to 1
		self.deviceDataManager.tempSensorAdaptor.numReadings = 1

		#Assert true as it is always successful
		self.deviceDataManager.run()
'''
@author: Mengfan Shi
'''
from labs.module07.CoapClientConnector import CoapClientConnector
'''
connect to local host
'''
host = "coap://127.0.0.1:5683/temp"
test = CoapClientConnector(host)
test.test()
        
        
@author: sk199
'''
from labs.module07.CoapClientConnector import CoapClientConnector
from labs.common.SensorData import SensorData
from labs.module07.TempSensorAdaptorTask import TempSensorAdaptorTask
from labs.common.DataUtil import DataUtil
import logging

if __name__ == '__main__':
    resource = 'temp'
    #payload = "for test"

    logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',
                        level=logging.DEBUG)
    print('------->')
    logging.info("Connecting to Coap Server...")
    coapClientConnector = CoapClientConnector()
    tempSensorData = SensorData()
    temp = TempSensorAdaptorTask()
    dataUtil = DataUtil()

    tempSensorData.addValue(temp.getTemperature())
    payload = dataUtil.toJsonFromSensorData(tempSensorData)
    print("Json Before issuing the request...")
    logging.info(payload)
    print('------->')
    coapClientConnector.postRequest(resource, payload)
    coapClientConnector.putRequest(resource, payload)
    coapClientConnector.getRequest(resource)
    coapClientConnector.deleteRequest(resource)
Exemple #11
0
'''
Created on Mar 19, 2019

Simple Python script for Coap Test Application
@author: Shyama Sastha Krishnamoorthy Srinivasan
'''
from labs.module07.CoapClientConnector import CoapClientConnector

#Initiating a client object and running the tests
_coapClient = CoapClientConnector()
_coapClient.runTests("Temperature");
run a number of tests, then exit.
'''
config = ConfigUtil('../../../config/ConnectedDevicesConfig.props')
config.loadConfig()

data = DataUtil()

host = config.getProperty(ConfigConst.ConfigConst.COAP_DEVICE_SECTION, ConfigConst.ConfigConst.HOST_KEY)
port = int(config.getProperty(ConfigConst.ConfigConst.COAP_DEVICE_SECTION, ConfigConst.ConfigConst.PORT_KEY))
path = 'temperature'

sensor = SensorData("Temperature",0.0,30.0)
sensor.addValue(4.0)
print(str(sensor))

coapClient = CoapClientConnector(host, port, path)

coapClient.ping()
json_data = data.SensorDataToJson(sensor)
print("json"+json_data)

#coapClient.get() #Get will respond with NOT_FOUND since data object on server is not initialized
coapClient.post((json_data)) #Post JSON to server
coapClient.get()

sensor.addValue(5.00)
coapClient.put(data.SensorDataToJson(sensor)) #Update resource on the server
coapClient.get()

coapClient.delete() #Delete resource
coapClient.get()
'''initialise variable for DataUtil class'''

data = DataUtil()
#ip/ or hostname direct
host = '127.0.0.1'  #config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.HOST_KEY)
#port number initialized
port = 5683  #int(config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.PORT_KEY))
#equivalent to channel in mqtt
path = 'temperature'
#instance variable for SensorData class
sensorData = SensorData()

#add new sensordata value
sensorData.addvalue(20.00)
#call the Coapclient connector
coapClient_obj = CoapClientConnector(host, port, path)
'''ping request'''
coapClient_obj.ping()
'''get request'''
coapClient_obj.get()
'''post request'''
coapClient_obj.post(data.tojsonfromSensorData(sensorData))
'''add new value to sensor data'''
sensorData.addvalue(15.00)
'''put request'''
coapClient_obj.put(data.tojsonfromSensorData(sensorData))
'''delete request'''
coapClient_obj.delete()
'''stop the Coap client'''
coapClient_obj.stop()
 def setUp(self):
     self.ccc = CoapClientConnector()
     pass
host = config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.HOST_KEY)

#getting port number to connect
port = int(config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.PORT_KEY))

#defining my resource uri
path = 'Temperature Resource'

#creating my instance variable for SensorData class
sensorData = SensorData()

#adding a new sensordata value
sensorData.addValue(10.00)

#calling the Coapclient connector
coapClient = CoapClientConnector(host, port, path)

#ping request
coapClient.ping()

#get request
coapClient.get()  

#post request
coapClient.post(data.toJsonFromSensorData(sensorData))  

#add new value to sensor data
sensorData.addValue(5.00)

#put request
coapClient.put(data.toJsonFromSensorData(sensorData))  
 def __init__(self):
     self.sensorAdaptor = MultiSensorAdaptor()
     self.ccc = CoapClientConnector()
class Module07Test(unittest.TestCase):
    """
	Use this to setup your tests. This is where you may want to load configuration
	information (if needed), initialize class-scoped variables, create class-scoped
	instances of complex objects, initialize any requisite connections, etc.
	"""
    def setUp(self):

        #getting the host data
        host = ConfigUtil().getProperty(ConfigConst.COAP_DEVICE_SECTION,
                                        ConfigConst.HOST_KEY)

        #port number to connect
        port = int(ConfigUtil().getProperty(ConfigConst.COAP_DEVICE_SECTION,
                                            ConfigConst.PORT_KEY))

        #resource uri
        path = 'Temperature Resource'

        #connecting to my CoAp client connector
        self.coap_client = CoapClientConnector(host, port, path)

    """
	Use this to tear down any allocated resources after your tests are complete. This
	is where you may want to release connections, zero out any long-term data, etc.
	"""

    def tearDown(self):
        self.coap_client = None

    """
	Unit Test Method to check my ping functionality
	"""

    def test_ping(self):
        assert (self.coap_client.ping())

    """
	Unit Test Method to check my GET functionality
	"""

    def test_get(self):
        assert (self.coap_client.get())

    """
	Unit Test Method to check my PUT functionality
	"""

    def test_put(self):
        jsonData = "{'name': 'temperature'}"
        assert (self.coap_client.put(jsonData))

    """
	Unit Test Method to check my POST functionality
	"""

    def test_post(self):
        jsonData = "{'name': 'temperature'}"
        assert (self.coap_client.post(jsonData))

    """
	Unit Test Method to check my DELETE functionality
	"""

    def test_delete(self):
        assert (self.coap_client.delete())
 def coapclient(self):
     host = '127.0.0.1'
     port = 5683
     #invoke coapclientconnector to connect the server
     coapClientConnector = CoapClientConnector(host, port)
     coapClientConnector.runTests("temp")