Ejemplo n.º 1
0
 def test_command_service_models(self):
     testDir = pathlib.Path(__file__).parent.absolute()
     with open(f"{testDir}/command-models.json") as json_file:
         data = json.load(json_file)
         for p in data['Units']:
             assert (Units[p].name == p)
         for p in data['UTCTime']:
             t1 = UTCTime.from_str(p)
             t2 = UTCTime.from_str(str(t1))
             assert (t1 == t2)
         for p in data['CurrentState']:
             cs = CurrentState._fromDict(p)
             assert (str(cs.prefix) == "CSW.ncc.trombone")
             assert (str(cs.stateName) == "idle")
             assert (len(cs.paramSet) == 25)
             for entry in p['paramSet']:
                 for key in entry:
                     # Round-trip test
                     # (ignore time values since resolution of fractional seconds is different in Typescript!)
                     if key not in ['UTCTimeKey', 'TAITimeKey']:
                         assert (
                             entry == Parameter._fromDict(entry)._asDict())
         for p in data["CommandIssue"]:
             # Check that the CommandIssue subclass exists
             assert (p['_type'] in self.commandIssueSubclasses)
Ejemplo n.º 2
0
 def test_location_service_models(self):
     testDir = pathlib.Path(__file__).parent.absolute()
     with open(f"{testDir}/location-models.json") as json_file:
         data = json.load(json_file)
         for p in data['ComponentType']:
             assert (ComponentType[p].name == p)
         for p in data['Connection']:
             connectionInfo = ConnectionInfo.from_dict(p)
             self.log.debug(f"Connection: {connectionInfo}")
             assert (connectionInfo.to_dict() == p)
         for p in data['Registration']:
             regType = p['_type']
             if regType == "HttpRegistration":
                 registration = HttpRegistration.from_dict(p)
             elif regType == "TcpRegistration":
                 registration = TcpRegistration.from_dict(p)
             elif regType == "AkkaRegistration":
                 registration = AkkaRegistration.from_dict(p)
             assert (registration.to_dict() == p)
         for p in data['ComponentId']:
             componentId = ComponentId.from_dict(p)
             self.log.debug(f"ComponentId: {componentId}")
             assert (componentId.to_dict() == p)
         for p in data['Prefix']:
             prefix = Prefix.from_str(p)
             assert (str(prefix) == p)
         for p in data['ConnectionType']:
             assert (ConnectionType(p).value == p)
         for p in data['Subsystem']:
             assert (Subsystems[p].name == p)
         for p in data['Location']:
             locType = p['_type']
             if locType == "AkkaLocation":
                 loc = AkkaLocation.from_dict(p)
             elif locType == "HttpLocation":
                 loc = HttpLocation.from_dict(p)
             elif locType == "TcpLocation":
                 loc = TcpLocation.from_dict(p)
             self.log.debug(f"Location: {loc}")
             assert (loc.to_dict() == p)
Ejemplo n.º 3
0
class TestEventsWithAssembly:
    log = structlog.get_logger()
    dir = pathlib.Path(__file__).parent.absolute()
    inFileName = "PyTestAssemblyEventHandlers.in"
    outFileName = "PyTestAssemblyEventHandlers.out"
    tmpInFile = f"/tmp/{inFileName}"
    tmpOutFile = f"/tmp/{outFileName}"
    inFile = f"{dir}/{inFileName}"
    outFile = f"{dir}/{outFileName}"
    pub = EventPublisher()
    sub = EventSubscriber()
    prefix = Prefix(Subsystems.CSW, "TestPublisher")

    # def setup_method(self):
    #     self.cleanup()

    def teardown_method(self):
        # pass
        self.cleanup()

    def cleanup(self):
        if os.path.exists(self.tmpInFile):
            os.remove(self.tmpInFile)
        if os.path.exists(self.tmpOutFile):
            os.remove(self.tmpOutFile)

    def test_pub_sub(self):
        time.sleep(1.0)
        self.log.debug("Starting test...")
        thread = self.sub.subscribe([
            EventKey(self.prefix, EventName("testEvent1")),
            EventKey(self.prefix, EventName("testEvent2")),
            EventKey(self.prefix, EventName("testEvent3"))
        ], self.callback)
        try:
            self.publishEvent1()
            self.publishEvent2()
            self.publishEvent3()
            self.publishEvent4()
            self.log.debug("Published three events...")
            # make sure assembly has time to write the file
            time.sleep(3)
            # compare file created from received events below with known good version
            assert filecmp.cmp(self.inFile, self.tmpInFile, False)
            # compare file created by assembly with known good version
            assert filecmp.cmp(self.outFile, self.tmpOutFile, False)
            self.log.info("Event pub/sub tests passed")
        finally:
            self.log.debug("Stopping subscriber...")
            thread.stop()

    def publishEvent1(self):
        keyName = "assemblyEventValue"
        keyType = KeyType.DoubleKey
        values = [42.0]
        param = Parameter(keyName, keyType, values)
        paramSet = [param]
        event = SystemEvent(self.prefix, EventName("testEvent1"), paramSet)
        self.log.debug(f"Publishing event {event}")
        self.pub.publish(event)

    def publishEvent2(self):
        intParam = Parameter("IntValue", KeyType.IntKey, [42], Units.arcsec)
        intArrayParam = Parameter("IntArrayValue", KeyType.IntArrayKey,
                                  [[1, 2, 3, 4], [5, 6, 7, 8]])
        floatArrayParam = Parameter("FloatArrayValue", KeyType.FloatArrayKey,
                                    [[1.2, 2.3, 3.4], [5.6, 7.8, 9.1]],
                                    Units.marcsec)
        intMatrixParam = Parameter("IntMatrixValue", KeyType.IntMatrixKey,
                                   [[[1, 2, 3, 4], [5, 6, 7, 8]],
                                    [[-1, -2, -3, -4], [-5, -6, -7, -8]]],
                                   Units.meter)
        paramSet = [intParam, intArrayParam, floatArrayParam, intMatrixParam]
        event = SystemEvent(self.prefix, EventName("testEvent2"), paramSet)
        self.pub.publish(event)

    def publishEvent3(self):
        intParam = Parameter("IntValue", KeyType.IntKey, [42], Units.arcsec)
        floatParam = Parameter("floatValue", KeyType.FloatKey, [float(42.1)],
                               Units.arcsec)
        longParam = Parameter("longValue", KeyType.LongKey, [42], Units.arcsec)
        shortParam = Parameter("shortValue", KeyType.ShortKey, [42],
                               Units.arcsec)
        byteParam = Parameter("byteValue", KeyType.ByteKey,
                              b'\xDE\xAD\xBE\xEF')
        booleanParam = Parameter("booleanValue", KeyType.BooleanKey,
                                 [True, False], Units.arcsec)

        intArrayParam = Parameter("IntArrayValue", KeyType.IntArrayKey,
                                  [[1, 2, 3, 4], [5, 6, 7, 8]])
        floatArrayParam = Parameter("FloatArrayValue", KeyType.FloatArrayKey,
                                    [[1.2, 2.3, 3.4], [5.6, 7.8, 9.1]],
                                    Units.arcsec)
        doubleArrayParam = Parameter("DoubleArrayValue",
                                     KeyType.DoubleArrayKey,
                                     [[1.2, 2.3, 3.4], [5.6, 7.8, 9.1]],
                                     Units.arcsec)

        byteArrayParam = Parameter(
            "ByteArrayValue", KeyType.ByteArrayKey,
            [b'\xDE\xAD\xBE\xEF', bytes([1, 2, 3, 4])])

        intMatrixParam = Parameter("IntMatrixValue", KeyType.IntMatrixKey,
                                   [[[1, 2, 3, 4], [5, 6, 7, 8]],
                                    [[-1, -2, -3, -4], [-5, -6, -7, -8]]],
                                   Units.meter)

        eqCoord = EqCoord.make(ra="12:13:14.15 hours",
                               dec="-30:31:32.3 deg",
                               frame=EqFrame.FK5,
                               pm=(0.5, 2.33))
        solarSystemCoord = SolarSystemCoord.make("BASE",
                                                 SolarSystemObject.Venus)
        minorPlanetCoord = MinorPlanetCoord.make("GUIDER1", 2000, "90 deg",
                                                 "2 deg", "100 deg", 1.4,
                                                 0.234, "220 deg")
        cometCoord = CometCoord.make("BASE", 2000.0, "90 deg", "2 deg",
                                     "100 deg", 1.4, 0.234)
        altAzCoord = AltAzCoord.make("301 deg", "42.5 deg")
        coordsParam = Parameter("CoordParam", KeyType.CoordKey, [
            eqCoord, solarSystemCoord, minorPlanetCoord, cometCoord, altAzCoord
        ])

        paramSet = [
            coordsParam, byteParam, intParam, floatParam, longParam,
            shortParam, booleanParam, byteArrayParam, intArrayParam,
            floatArrayParam, doubleArrayParam, intMatrixParam
        ]
        event = SystemEvent(self.prefix, EventName("testEvent3"), paramSet)
        self.pub.publish(event)

    def publishEvent4(self):
        keyName = "assemblyEventValue"
        keyType = KeyType.UTCTimeKey
        values = [UTCTime.from_str("2021-09-20T20:43:35.419053077Z")]
        param = Parameter(keyName, keyType, values)
        keyName2 = "assemblyEventValue2"
        keyType2 = KeyType.TAITimeKey
        values2 = [TAITime.from_str("2021-09-20T18:44:12.419084072Z")]
        param2 = Parameter(keyName2, keyType2, values2)
        paramSet = [param, param2]
        event = SystemEvent(self.prefix, EventName("testEvent4"), paramSet)
        self.log.debug(f"Publishing event {event}")
        self.pub.publish(event)

    # Event subscriber callback
    def callback(self, systemEvent):
        self.log.debug(f"Received system event '{systemEvent}'")
        # Save event to file as JSON like dict (Not JSON, since byte arrays are not serializable in python),
        # but change the date and id for comparison
        systemEvent.eventId = "test"
        systemEvent.eventTime = EventTime(0, 0)
        mode = "w" if (systemEvent.eventName.name == "testEvent1") else "a"
        f = open(self.tmpInFile, mode)
        jsonStr = str(systemEvent._asDict())
        f.write(f"{jsonStr}\n")
        f.close()
Ejemplo n.º 4
0
def get_files_from_directory(dir_path, file_extension):  # noqa: CCR001
    for dirpath, _, filenames in os.walk(dir_path):
        for file in filenames:
            if pathlib.Path(file).suffix == f".{file_extension}":
                yield os.path.join(dirpath, file)