Esempio n. 1
0
 def test_decode_json_error(self):
     '''Test decode_json in the case that parsing the JSON fails'''
     try:
         # the single quotes are invalid for JSON strings
         decode_json(json="[{'foo':1}]")
     except MonitisError, error:
         assert_equal(str(error.msg),
             'JSON parse error: '
             + 'Expecting property name: line 1 column 2 (char 2)')
Esempio n. 2
0
 def test_decode_json_error(self):
     '''Test decode_json in the case that parsing the JSON fails'''
     try:
         # the single quotes are invalid for JSON strings
         decode_json(json="[{'foo':1}]")
     except MonitisError, error:
         assert_equal(
             str(error.msg), 'JSON parse error: ' +
             'Expecting property name: line 1 column 2 (char 2)')
Esempio n. 3
0
    def add_additional_results(self, checktime=None, results=None):
        """Add additional results to an existing result
        
        checktime: the checktime of a previously submitted result
        results: an instance of AdditionalResults 
        
        """

        if not checktime:
            raise MonitisError("addAdditionalResults: checktime required")

        if not results:
            raise MonitisError("addAdditionalResults: " + \
                                   "results required")

        action = 'addAdditionalResults'
        # use the current time if the user didn't specify one
        checktime = checktime or api_checktime()

        # use dumps to format the results parameter as a JSON list
        response_string = self.post(action=action,
                                    monitorId=self.monitor_id,
                                    checktime=checktime,
                                    results=dumps(results))
        response = decode_json(response_string)
        if response['status'] != 'ok':
            raise MonitisError('addAdditionalResults failed: ' + response)

        return checktime
Esempio n. 4
0
 def add_additional_results(self, checktime=None, results=None):
     """Add additional results to an existing result
     
     checktime: the checktime of a previously submitted result
     results: an instance of AdditionalResults 
     
     """
     
     if not checktime:
         raise MonitisError("addAdditionalResults: checktime required")
     
     if not results:
         raise MonitisError("addAdditionalResults: " + \
                                "results required")
     
     action = 'addAdditionalResults'
     # use the current time if the user didn't specify one
     checktime = checktime or api_checktime()
     
     # use dumps to format the results parameter as a JSON list
     response_string =  self.post(action=action,
                                  monitorId=self.monitor_id,
                                  checktime=checktime,
                                  results=dumps(results))
     response = decode_json(response_string)
     if response['status'] != 'ok':
         raise MonitisError('addAdditionalResults failed: ' + response)
         
     return checktime
Esempio n. 5
0
 def delete_monitor(self):
     """Delete the custom monitor with ID monitor_id"""
     result = decode_json(self.post(action='deleteMonitor',
                                     monitorId=self.monitor_id))
     if result['status'] != 'ok':
         raise MonitisError(
             'delete_monitor error: ' + result['status'])
Esempio n. 6
0
    def edit_monitor(self, *args, **kwargs):
        """Edit an existing custom monitor
        
        monitor_params
        name
        tag
        """

        # Need to use kwargs rather than named args so we can have
        # a variable numer of args for *Params
        required = []
        allowed = ['name', 'tag', 'monitor_params']

        CustomMonitor._validate_kwargs(required, allowed, **kwargs)

        # build the dict to pass to post
        add = dict()
        # copy name and tag to add, if they exist
        for arg_name in ['name', 'tag']:
            if arg_name in kwargs.keys():
                add[arg_name] = kwargs[arg_name]
        # copy monitorParams into add, if it exists
        if 'monitor_params' in kwargs.keys():
            add['monitorParams'] = kwargs['monitor_params']
        add['action'] = 'editMonitor'
        add['monitorId'] = self.monitor_id

        result_params, additional_result_params, monitor_params = \
                                                         _encode_params(*args)

        # add the *params args to add
        if monitor_params:
            add['monitorParams'] = monitor_params
        if result_params:
            raise MonitisError("edit_monitor: result_params not allowed")
        if additional_result_params:
            raise MonitisError("edit_monitor: additional_result_params " + \
                                   "not allowed")

        json_result = self.post(**add)
        result = decode_json(json_result)

        if result['status'] == 'ok':
            # copy additional values into the new CustomMonitor object
            for key in ('name', 'tag'):
                if key in kwargs:
                    self.__dict__[key] = kwargs[key]

            self.monitor_params = monitor_params
        else:
            raise MonitisError("add_monitor failed: " + json_result)

        return result
Esempio n. 7
0
    def edit_monitor(self, *args, **kwargs):
        """Edit an existing custom monitor
        
        monitor_params
        name
        tag
        """
        
        # Need to use kwargs rather than named args so we can have
        # a variable numer of args for *Params
        required = []
        allowed = ['name', 'tag', 'monitor_params']

        CustomMonitor._validate_kwargs(required, allowed, **kwargs)

        # build the dict to pass to post
        add = dict()
        # copy name and tag to add, if they exist
        for arg_name in ['name', 'tag']:
            if arg_name in kwargs.keys():
                add[arg_name] = kwargs[arg_name]
        # copy monitorParams into add, if it exists
        if 'monitor_params' in kwargs.keys():
            add['monitorParams'] = kwargs['monitor_params']
        add['action'] = 'editMonitor'
        add['monitorId'] = self.monitor_id
        
        result_params, additional_result_params, monitor_params = \
                                                         _encode_params(*args)
        
        # add the *params args to add
        if monitor_params:
            add['monitorParams'] = monitor_params
        if result_params:
            raise MonitisError("edit_monitor: result_params not allowed")
        if additional_result_params:
            raise MonitisError("edit_monitor: additional_result_params " + \
                                   "not allowed")
        
        json_result = self.post(**add)
        result = decode_json(json_result)

        if result['status'] == 'ok':
            # copy additional values into the new CustomMonitor object
            for key in ('name','tag'):
                if key in kwargs:
                    self.__dict__[key] = kwargs[key]
            
            self.monitor_params = monitor_params
        else:
            raise MonitisError("add_monitor failed: " + json_result)
        
        return result
Esempio n. 8
0
    def add_result(self, checktime=None, results=None, **kwargs):
        """add results for the specified Custom monitor
        
        One or more results should be passed in a kwargs of the form:
            paramName1=paramValue1,paramName2=paramValue2,...
        
        Returns the checktime, whether passed in as a parameter
        or automatically generated.  This is useful for passing
        to add_additional_results

        """
        action = 'addResult'
        # use the current time if the user didn't specify one
        result_checktime = checktime or api_checktime()

        # merge kwargs and results items into one list
        if results is None:
            results_items = list()
        else:
            results_items = results.items()
        results_items.extend(kwargs.items())

        # build post string elements from combined results items
        result_strings = list()
        for name, value in results_items:
            # urllib.quote each to implement "double encoding"
            # http://monitis.com/api/api.html#api_home
            result_strings.append(quote(':'.join((name, str(value))), ':'))

        result_string = self.post(action=action,
                                  monitorId=self.monitor_id,
                                  checktime=result_checktime,
                                  results=';'.join(result_strings))
        result = decode_json(result_string)
        if result['status'] != 'ok':
            raise MonitisError('add_result failed')

        return result_checktime
Esempio n. 9
0
    def add_result(self, checktime=None, results=None, **kwargs):
        """add results for the specified Custom monitor
        
        One or more results should be passed in a kwargs of the form:
            paramName1=paramValue1,paramName2=paramValue2,...
        
        Returns the checktime, whether passed in as a parameter
        or automatically generated.  This is useful for passing
        to add_additional_results

        """
        action = 'addResult'
        # use the current time if the user didn't specify one
        result_checktime = checktime or api_checktime()
        
        # merge kwargs and results items into one list
        if results is None:
            results_items = list()
        else:
            results_items = results.items()
        results_items.extend(kwargs.items())

        # build post string elements from combined results items
        result_strings = list()
        for name, value in results_items:
            # urllib.quote each to implement "double encoding"
            # http://monitis.com/api/api.html#api_home
            result_strings.append(quote(':'.join((name, str(value)))))
        
        result_string =  self.post(action=action, monitorId=self.monitor_id,
                         checktime=result_checktime,
                         results=';'.join(result_strings))
        result = decode_json(result_string)
        if result['status'] != 'ok':
            raise MonitisError('add_result failed')
            
        return result_checktime
Esempio n. 10
0
    def add_monitor(cls, *args, **kwargs):
        """Add a custom monitor

        Required parameters:
            name - string
            tag - string
            One or more ResultParams instances

        Optional parameters:
            customUserAgentId - the id of the custom user agent
            m_type - custom string that represents monitor type
            One or more MonitorParams instances
            One or more AdditionalResultParams instances

        Note that all Params objects must come before the keyword arguments
        
        Return a CustomMonitor instance if the operation suceeds, or raises
        MonitisError if the operation fails.
        """

        # Need to use kwargs rather than named args so we can have
        # a variable numer of args for *Params
        required = ['name', 'tag']
        allowed = ['customUserAgentId', 'm_type']

        # ensure that we have the correct args
        # raises MonitisError if it fails
        CustomMonitor._validate_kwargs(required, allowed, **kwargs)
        # all required keys exist in kwargs, none unexpected

        # build the dict to pass to post
        add = dict()
        add.update(**kwargs)  # everything in kwargs passed on to post
        add['action'] = 'addMonitor'

        result_params, additional_result_params, monitor_params = \
                                                         _encode_params(*args)

        # add the *params args to add
        if result_params:
            add['resultParams'] = result_params
        else:
            raise MonitisError('add_monitor: result_params is required')
        if monitor_params:
            add['monitorParams'] = monitor_params
        if additional_result_params:
            add['additionalResultParams'] = additional_result_params

        # Create a mostly empty CustomMonitor, and then populate it
        # once we've successfully created it on the server
        mon = cls(_url=_api_url())
        json_result = mon.post(**add)
        result = decode_json(json_result)

        if result['status'] == 'ok':
            mon.monitor_id = result['data']

            # copy additional values into the new CustomMonitor object
            for key in ('name', 'm_type', 'tag', 'customUserAgentId'):
                if key in kwargs:
                    mon.__dict__[key] = kwargs[key]
        else:
            raise MonitisError("add_monitor failed: " + json_result)
        return mon
Esempio n. 11
0
    def add_monitor(cls, *args, **kwargs):
        """Add a custom monitor

        Required parameters:
            name - string
            tag - string
            One or more ResultParams instances

        Optional parameters:
            customUserAgentId - the id of the custom user agent
            m_type - custom string that represents monitor type
            One or more MonitorParams instances
            One or more AdditionalResultParams instances

        Note that all Params objects must come before the keyword arguments
        
        Return a CustomMonitor instance if the operation suceeds, or raises
        MonitisError if the operation fails.
        """

        # Need to use kwargs rather than named args so we can have
        # a variable numer of args for *Params
        required = ['name','tag']
        allowed = ['customUserAgentId','m_type']
        
        # ensure that we have the correct args
        # raises MonitisError if it fails
        CustomMonitor._validate_kwargs(required, allowed, **kwargs)
        # all required keys exist in kwargs, none unexpected
        
        # build the dict to pass to post
        add = dict()
        add.update(**kwargs) # everything in kwargs passed on to post
        add['action'] = 'addMonitor'
        
        result_params, additional_result_params, monitor_params = \
                                                         _encode_params(*args)
        
        # add the *params args to add
        if result_params:
            add['resultParams'] = result_params
        else:
            raise MonitisError('add_monitor: result_params is required')
        if monitor_params:
            add['monitorParams'] = monitor_params
        if additional_result_params:
            add['additionalResultParams'] = additional_result_params

        # Create a mostly empty CustomMonitor, and then populate it
        # once we've successfully created it on the server
        mon = cls(_url=_api_url())
        json_result = mon.post(**add)
        result = decode_json(json_result)

        if result['status'] == 'ok':
            mon.monitor_id = result['data']

            # copy additional values into the new CustomMonitor object
            for key in ('name', 'm_type', 'tag', 'customUserAgentId'):
                if key in kwargs:
                    mon.__dict__[key] = kwargs[key]
        else:
            raise MonitisError("add_monitor failed: " + json_result)
        return mon