Example #1
0
    def __init__(self, send_handler, frequency):
        self.log = getLogger(self.__class__.__name__)
        self.send = send_handler
        # Controls shared object
        self.controls = Controls()
        # Commands uplink queue
        self.commands = Queue()

        # Uplink services uplink generated packets at certain frequency
        self.uplink_services = ServiceManager([
            Service('Controls', self.send, self.controls, frequency, 1),
            Service('Commands', self.command_handler, self.commands, frequency, 2),
        ])

        self.user_input = UserInput(self.controls, self.commands)
        self.user_input.non_flight()

        def signal_handler(sig_num, frame):
            self.log.info('Shutting down')
            self.uplink_services.stop('Controls')
            self.uplink_services.stop('Commands')
            self.user_input.stop(True)
            sys.exit(0)

        signal.signal(signal.SIGINT, signal_handler)

        self.uplink_services.start('Commands')
        self.uplink_services.start('Controls')

        self.user_input.run()
def onnet_CCM_Y1564_CCA(A, B):

    print("!" * 1)
    print("!" * 2)
    print("************** Test {}{} type EP ************* ".format(A, B))
    print("!!" * 3)
    dict1 = yaml.load(open(file_path + '/../Topology/inputfile_CCUA.yml'),
                      Loader=yaml.Loader)
    dict1['site_list'][0]['port_type'] = '{}-type'.format(A)
    dict1['site_list'][1]['port_type'] = '{}-type'.format(B)
    dict1['site_list'][2]['port_type'] = '{}-type'.format(B)
    my_config = Service(**dict1)
    my_config.connect_OLO_nodes()
    my_config.create_commands_OLO()
    my_config.push_OLO_config()
    my_config.connect_nodes()
    my_config.parse_accedian()
    my_config = Service(**dict1)
    my_config.Command_Creation()
    my_config.push_config()
    time.sleep(10)
    test_result = {}
    test_result['ccm_status'] = my_config.Validate_ccm()
    #test_result['Loop_test'] = my_config.Y1564_test()
    #my_config.check_QOS_counters_config()
    #test_result['CFM_Stats_Acc'] = my_config.mep_statistic_accedian()
    #test_result['CFM_Stats_cisco'] = my_config.mep_statistic_cisco()
    my_config.delete_config()
    my_config.disconnect_nodes()
    my_config.delete_OLO_config()
    my_config.disconnect_OLO_nodes()
    return test_result
 def __init__(self):
     parser = ConfigParser()
     parser.read("files/settings.properties")
     self.ui = None
     if parser.get("options", "ui") == "console":
         self.ui = UI
     elif parser.get("options", "ui") == "gui":
         self.ui = GUI
     repo_style = parser.get("options", "repository")
     if repo_style == "memory":
         self.ui = self.ui(Service())
     elif repo_style == "json":
         self.ui = self.ui(
             Service(
                 StudentRepoJson(parser.get("options", "students")),
                 DisciplineRepoJson(parser.get("options", "disciplines")),
                 GradesRepoJson(parser.get("options", "grades"))))
     elif repo_style == "binary":
         self.ui = self.ui(
             Service(
                 StudentRepoBinary(parser.get("options", "students")),
                 DisciplineRepoBinary(parser.get("options", "disciplines")),
                 GradesRepoBinary(parser.get("options", "grades"))))
     elif repo_style == "csv":
         self.ui = self.ui(
             Service(
                 StudentRepoCSV(parser.get("options", "students")),
                 DisciplineRepoCSV(parser.get("options", "disciplines")),
                 GradesRepoCSV(parser.get("options", "grades"))))
     elif repo_style == "database":
         self.ui = self.ui(
             Service(
                 StudentRepoDatabase(parser.get("options", "database")),
                 DisciplineRepoDatabase(parser.get("options", "database")),
                 GradesRepoDatabase(parser.get("options", "database"))))
 def test_divide(self, mock_service):
     mock_service.return_value = 12
     # call the divide fun, iton in service
     assert Service().divide(2) == 6
     assert Service().divide(4) == 3
     assert Service().divide(-2) == -6
     assert Service().divide(12) == 1
     return
    def test_divide(self, mock_service):

        mock_service.return_value = 18
        assert Service().divide(2) == 9
        with pytest.raises(ZeroDivisionError):
            Service().divide(0)
        assert Service().divide(-18) == -1
        assert Service().divide(-2) == -9
        return
 def get():
     print('Get User - Controller')
     try:
         user_id = request.args['userId']
         service = Service()
         response = service.get_user(user_id=int(user_id))
     except:
         service = Service()
         response = service.get_all_users()
     # print('type of response - ', type(response))
     return response
Example #7
0
 def test_abs_plus(self):
     x = Service()
     self.assertEqual(x.abs_plus(10), 11)
     self.assertEqual(x.abs_plus(0), 1)
     self.assertEqual(x.abs_plus(-10), 11)
     self.assertEqual(x.abs_plus(-sys.maxsize + 1), sys.maxsize)
     self.assertEqual(x.abs_plus(10), 11)
Example #8
0
def save_message():
    try:
        svc = Service()
        svc_response = svc.save_message(request.data)
        return SvcUtils.handle_response(svc_response, status.HTTP_201_CREATED)
    except Exception as ex:
        return SvcError.handle_error(ex)
    def __init__(self,
                 executable_path='IEDriverServer.exe',
                 port=DEFAULT_PORT,
                 timeout=DEFAULT_TIMEOUT,
                 host=DEFAULT_HOST,
                 log_level=DEFAULT_LOG_LEVEL,
                 log_file=DEFAULT_LOG_FILE):
        self.port = port
        if self.port == 0:
            self.port = utils.free_port()
        self.host = host
        self.log_level = log_level
        self.log_file = log_file

        self.iedriver = Service(executable_path,
                                port=self.port,
                                host=self.host,
                                log_level=self.log_level,
                                log_file=self.log_file)

        self.iedriver.start()

        RemoteWebDriver.__init__(
            self,
            command_executor='http://localhost:%d' % self.port,
            desired_capabilities=DesiredCapabilities.INTERNETEXPLORER)
        self._is_remote = False
Example #10
0
 def __init__(self, connection, login, initList):
     Thread.__init__(self)
     self.c = connection
     self.d = Service(self.c)
     self.d.registration(login)
     self.id = self.d.login(login)
     self.l = initList
    def test_bad_random(self):
        mockService = Service()

        #test case good data
        mockData = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"
        with patch('service.open', mock_open(read_data=mockData)):
            mockService.bad_random = mock.Mock(return_value=5)
            badNumber = Service.bad_random()
            fileLines = mockData.count('\n') + 1

        self.assertTrue(0 <= badNumber <= fileLines)

        #test case file not found
        self.assertRaises(FileNotFoundError, Service.bad_random)

        #test case empty file
        mockData = ""
        with patch('service.open', mock_open(read_data=mockData)):
            fileLines = mockData.count('\n') + 1

        self.assertTrue(fileLines == 1)
        self.assertRaises(FileNotFoundError, Service.bad_random)

        #test case not a number
        mockData = "A\nB\nC\nD\nE"
        with patch('service.open', mock_open(read_data=mockData)):
            fileLines = mockData.count('\n') + 1

        self.assertTrue(fileLines == 5)
        self.assertRaises(FileNotFoundError, Service.bad_random)
Example #12
0
def test_complicated_function(divide, bad_random):
    service = Service()

    bad_random.return_value = 8
    divide.return_value = 4

    assert service.complicated_function(2)[0] == 4
    assert service.complicated_function(2)[1] == 0

    bad_random.return_value = 0
    divide.return_value = 0

    assert service.complicated_function(2)[0] == 0
    assert service.complicated_function(2)[1] == 0

    bad_random.return_value = -4
    divide.return_value = -2

    assert service.complicated_function(2)[0] == -2
    assert service.complicated_function(2)[1] == 0

    bad_random.return_value = 5
    divide.return_value = 1

    assert service.complicated_function(5)[0] == 1
    assert service.complicated_function(5)[1] == 1
Example #13
0
def parse_service_data(data):
    """Create a map of service objects from the weird JSON we get from the console."""
    services = defaultdict()
    for service_url, service_details in data["services"]["_embedded"].items():
        service = Service(service_url, service_details)
        services[service.service_name] = service
    return services
Example #14
0
    def __init__(self, executable_path="chromedriver", port=0,
                 desired_capabilities=None, chrome_options=None):
        """
        Creates a new instance of the chrome driver.

        Starts the service and then creates new instance of chrome driver.

        :Args:
         - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
         - port - port you would like the service to run, if left as 0, a free port will be found.
         - desired_capabilities: Dictionary object with desired capabilities (Can be used to provide various chrome
           switches). This is being deprecated, please use chrome_options
         - chrome_options: this takes an instance of ChromeOptions
        """
        if chrome_options is None:
            options = Options()
        else:
            options = chrome_options

        if desired_capabilities is not None:
            warnings.warn("Desired Capabilities has been deprecated, please user chrome_options.", DeprecationWarning)
            desired_capabilities.update(options.to_capabilities())
        else:
            desired_capabilities = options.to_capabilities()

        self.service = Service(executable_path, port=port)
        self.service.start()

        try:
            RemoteWebDriver.__init__(self,
                command_executor=self.service.service_url,
                desired_capabilities=desired_capabilities)
        except:
            self.quit()
            raise WebDriverException("The Driver was not able to start.")
Example #15
0
 def test_NewLandTrade_LandSold_CorrectAmount(self):
     my_validation=Validation()
     my_service=Service(my_validation)
     my_service.set_acres_owned(1)
     my_service.set_acres_trade(-1)
     my_service.new_land_trade()
     self.assertEqual(my_service.get_acres_owned(), 0)
Example #16
0
 def test_GrainstocksAfterRatInfestation_RatInfestation_NewGrainstocks(self):
     my_validation=Validation()
     my_service=Service(my_validation)
     previous_grainstock=my_service.get_grain_stocks()
     my_service.set_rats_ate(100)
     my_service.grainstocks_after_rat_infestation()
     self.assertLess(my_service.get_grain_stocks(), previous_grainstock)
Example #17
0
    def test(self):
        expected = dict(
            prefix="sqs",
            description="For Queues and Stuffs",
            arn_format="arn:blah:blah:blah",
            arn_regex="arn:.+:.+:.+",
            docs=dict(
                actions_doc_root="",
                authz_doc_page="",
                concepts_doc_root="",
                context_keys_doc_root="",
                api_detail_root="",
                api_doc_root="",
                api_reference_doc_page="",
            ),
            actions=dict(PurgeQueue=dict(
                description="Remove all entries from Queue",
                aws_action_groups=["ReadWrite"],
                calculated_action_group="Write",
                condition_keys=["a4b:amazonId"],
                docs=dict(api_doc="", doc_page_rel="", doc_page=""),
            )),
        )
        expected = json.dumps(expected, sort_keys=True, indent=2)

        # Create Service and Service Action
        my_service = Service(self.url, self.aws_response)
        my_service_action = ServiceAction(my_service, self.body)

        # Associate the two
        my_service.actions[my_service_action.action_name] = my_service_action

        response = json.dumps(my_service.toJSON(), sort_keys=True, indent=2)
        assert expected == response
def test_abs_plus():
    newService = Service()

    assert newService.abs_plus(-10) == (abs(-10) + 1)
    assert newService.abs_plus(10) == (abs(10) + 1)
    assert newService.abs_plus(0) == (abs(0) + 1)
    assert newService.abs_plus(3.14) == (abs(3.14) + 1)
Example #19
0
 def get_service_list(self):
     """Gets a list of Service objects in this TsItem
     
     Searches through the TsItem descriptors for descriptors of type ServiceListDescriptor
     and ChannelListMappingDescriptor. The information from both of these descriptors is used
     to build a dictionary objects keyed by service triplet.
     Returns:
         A dictionary of Service objects keyed by service triplet or None
     """
     svl_types    = {}
     svl_channels = {}
     svl = {}
     for desc in self.descriptors:
         if type(desc) == descriptors.ServiceListDescriptor:
             svl_types = desc.services
         if type(desc) == descriptors.ChannelListMappingDescriptor:
             svl_channels = desc.service_channel_map
     
     if len(svl_types) > 0: svl_iterator = svl_types
     elif len(svl_channels) > 0: svl_iterator = svl_channels
     else: return None#TODO - should select the longest list to iterate with
     
     for service_id in svl_iterator:
         ts_id = self.transport_stream_id
         n_id = self.original_network_id
         channel = None
         stpe = None
         if service_id in svl_channels:
             channel = svl_channels[service_id]
         if service_id in svl_types:
             stpe = svl_types[service_id]
         svc  = Service(nid=n_id, tsid=ts_id, svid=service_id, chan=channel, type=stpe)
         svl[(n_id, ts_id, service_id)] = svc
     return svl
def test_complicated_function(divide, bad_random):
    newService = Service()

    bad_random.return_value = 6
    divide.return_value = 3

    assert newService.complicated_function(2)[0] == 3
    assert newService.complicated_function(2)[1] == 6 % 2

    bad_random.return_value = 6
    divide.return_value = -3

    assert newService.complicated_function(-2)[0] == -3
    assert newService.complicated_function(-2)[1] == 6 % -2

    divide.return_value = 0
    bad_random.return_value = 0

    assert newService.complicated_function(6)[0] == 0
    assert newService.complicated_function(6)[1] == 0

    divide.return_value = None
    bad_random.return_value = 4
    try:
        newService.complicated_function(0)
    except ZeroDivisionError:
        assert True
        divide.return_value = 2
        assert newService.complicated_function(2)[0] == 2
        assert newService.complicated_function(2)[0] == 0
    def test_divide(self):

        mockService = Service()

        #test case divisor is zero
        mockService.bad_random = mock.Mock(return_value=4)
        self.assertRaises(ZeroDivisionError, mockService.divide, 0)

        #test case dividend is zero
        mockService.bad_random = mock.Mock(return_value=0)
        quotient = mockService.divide(4)
        self.assertTrue(quotient == 0)

        #test case dividend and divisor both same non zero value
        mockService.bad_random = mock.Mock(return_value=7)
        quotient = mockService.divide(7)
        self.assertTrue(quotient == 1)

        #test case non zero dividend and divisor different non zero value
        mockService.bad_random = mock.Mock(return_value=6)
        quotient = mockService.divide(3)
        self.assertTrue(quotient == 2)

        #test case non zero dividend and divisor not a number
        mockService.bad_random = mock.Mock(return_value=9)
        self.assertRaises(TypeError, mockService.divide, 'string')
Example #22
0
def execCreateContainer(request):
    print "start execCreateContainer()"
    if request.method=="GET":
        dictCon={}
        rqmc=request.GET.get("rqmc")
        dictCon["rqmc"]=rqmc
        rqzjm=request.GET.get("rqzjm")
        dictCon["rqzjm"]=rqzjm
        wlpz=request.GET.get("wlpz")
        dictCon["wlpz"]=wlpz
        srsclx=request.GET.get("srsclx")
        dictCon["srsclx"]=srsclx
        rqdnsfwq=request.GET.get("rqdnsfwq")
        dictCon["rqdnsfwq"]=rqdnsfwq
        rqdnsssym=request.GET.get("rqdnsssym")
        dictCon["rqdnsssym"]=rqdnsssym
        szjdk=request.GET.get("szjdk")
        dictCon["szjdk"]=szjdk
        rqdk=request.GET.get("rqdk")
        dictCon["rqdk"]=rqdk
        jxm=request.GET.get("jxm")
        dictCon["jxm"]=jxm
        s=Service()
        stdmsg=s.createContainer(dictCon)
        #print "stdmsg="+stdmsg
        return HttpResponse(json.dumps({"rst":stdmsg}))
Example #23
0
    def mainstart(self):
        bucle = True
        while bucle:
            try:
                option = int(input("Digita la opción que desees ejecutar: "))
                print()
                if option == 1:
                    Clients().start()
                    self.menu()
                elif option == 2:
                    Vehicles().start()
                    self.menu()
                elif option == 3:
                    Service().start()
                    self.menu()
                elif option == 4:
                    Facturas().get_all()
                    self.menu()
                elif option == 5:
                    Facturas().hola()
                    self.menu()
                elif option == 6:
                    self.menu()
                elif option == 7:
                    bucle = False

                    print()
            except NameError:
                print(NameError)
                print("7. Mostrar menú de modulos [7]")
                print(
                    "La opción digitada es invalida (debe ser un número en el menú)."
                )
                print()
Example #24
0
def execInputCommand(request):
    print "start execInputCommand"
    if request.method=="GET":
        cmd=request.GET.get("srzl")
        s=Service()
        stdmsg=s.execInputCommand(cmd)
        return HttpResponse(json.dumps({"rst":stdmsg}))
Example #25
0
def ping():
    try:
        svc = Service()
        svc_response = svc.ping()
        return SvcUtils.handle_response(svc_response, status.HTTP_200_OK)
    except Exception as ex:
        return SvcError.handle_error(ex)
def test_abs_plus():
    serviceTest = Service()
    testValue = serviceTest.abs_plus(-5)
    assert (testValue == 6)

    testValue = serviceTest.abs_plus(0)
    assert (testValue == 1)
Example #27
0
def get_message_by_username(username):
    try:
        svc = Service()
        svc_response = svc.get_message_by_username(username)
        return SvcUtils.handle_response(svc_response, status.HTTP_200_OK)
    except Exception as ex:
        return SvcError.handle_error(ex)
Example #28
0
    def StartServices(self):
        # check the state of the cluster
        if self.state == "down":
            return

        images = self.GetImages()
        self.services = {} # key:image name, value: image
        
        # build service structure
        for image in images:
            status = ""
            status = raw_input("Do you want to start " + image.repo + " [y/n]:  ").lower()
            if (status == 'y' or status == 'yes'):
                status = 'RUN'
            else:
                status = 'STOP'
            self.services[image.repo] = Service(image, 1, status, 3000, 3000)
        
        # start services
        # could use threads here to go through and start them all, asssuming
        # docker is cool with that...
        for key in self.services:
            if self.services[key].state == "RUN":
                #execute the run command
                print('Starting service: {0}'.format(key))
                self.services[key].start()
            elif self.services[key].state == 'STOP':
                print('Stopping service: {0}'.format(key))
                self.services[key].stop()
Example #29
0
def start(msg=None):
    # rospy.init_node('we_python_sm', None, False, 2, False, False, True)
    rospy.init_node('we_python_sm', log_level=rospy.DEBUG, anonymous=True)
    brain = DNGetMsg()
    if msg == None or len(msg) > 3 or len(msg) == 1:
        stateMachineThread = StateMachine()
    elif len(msg) == 2:
        # msg[1] is name of subroutine
        stateMachineThread = StateMachine(msg[1])
    else:
        # msg[2] is the string argv of the subroutine specified by msg[1]
        stateMachineThread = StateMachine(msg[1], eval(msg[2]))

    stateMachineThread.start()

    serviceThread = Service()
    serviceThread.start()

    rospy.spin()

    serviceThread.stop()
    stateMachineThread.stop()

    serviceThread.join()
    stateMachineThread.join()
Example #30
0
    def addService(self, sDate, iDate, mNum, pNum, code, name, fee):
        """Adds a service to the appropriate member and provider."""
        print('Adding service with' + ' \nService date: ' + sDate +
              ' \nInput date: ' + iDate + ' \nMember Number: ' + mNum +
              ' \nProvider Number: ' + pNum + ' \nCode: ' + str(code) +
              ', Name: ' + str(name) + ', Fee: ' + str(fee))
        mem = self.getMember(mNum)
        prov = self.getProvider(pNum)

        if mem is None:
            deb.warn('Member number was none.')

        if prov is None:
            deb.warn('Provider number was none.')

        service = Service(sDate, iDate, mem, prov, code, name, fee)

        for member in self.members:

            if member.number == mNum:
                member.services.append(service)

        for provider in self.providers:
            if provider.number == pNum:
                provider.services.append(service)