예제 #1
0
def _get(query):
    """Get pattoo API server GraphQL query results.

    Args:
        query: GraphQL query string

    Returns:
        result: Dict of JSON response

    """
    # Initialize key variables
    success = False
    config = WebConfig()
    result = None

    # Get the data from the GraphQL API
    url = config.web_api_server_url()
    try:
        response = requests.get(url, params={'query': query})

        # Trigger HTTP errors if present
        response.raise_for_status()
        success = True
    except requests.exceptions.Timeout as err:
        # Maybe set up for a retry, or continue in a retry loop
        log_message = ('''\
Timeout when attempting to access {}. Message: {}\
'''.format(url, err))
        log.log2die(20121, log_message)
    except requests.exceptions.TooManyRedirects as err:
        # Tell the user their URL was bad and try a different one
        log_message = ('''\
Too many redirects when attempting to access {}. Message: {}\
'''.format(url, err))
        log.log2die(20116, log_message)
    except requests.exceptions.HTTPError as err:
        log_message = ('''\
HTTP error when attempting to access {}. Message: {}\
'''.format(url, err))
        log.log2die(20118, log_message)
    except requests.exceptions.RequestException as err:
        # catastrophic error. bail.
        log_message = ('''\
Exception when attempting to access {}. Message: {}\
'''.format(url, err))
        log.log2die(20119, log_message)
    except:
        log_message = ('''API Failure: [{}, {}, {}]\
'''.format(sys.exc_info()[0],
           sys.exc_info()[1],
           sys.exc_info()[2]))
        log.log2die(20120, log_message)

    # Process the data
    if bool(success) is True:
        result = response.json()
    return result
예제 #2
0
    def test_index(self):
        """Testing method / function index."""
        # Initialize key variables
        expected = 'The Pattoo Web API is Operational.\n'

        # Create URL
        config = WebConfig()
        agent_url = config.web_api_server_url(graphql=False)
        url = agent_url.replace('/rest/data', '/status')

        # Check response
        with requests.get(url) as response:
            result = response.text
        self.assertEqual(expected, result)
예제 #3
0
    def create_app(self):
        """Create the test APP for flask.

        Args:
            None

        Returns:
            app: Flask object

        """
        # Create APP and set configuration
        app = APP
        config = WebConfig()

        app.config['TESTING'] = True
        app.config['LIVESERVER_PORT'] = config.web_api_ip_bind_port()
        os.environ['FLASK_ENV'] = 'development'

        # Clear the flask cache
        cache = Cache(config={'CACHE_TYPE': 'null'})
        cache.init_app(app)

        # Return
        return app
예제 #4
0
    def test_route_data(self):
        """Testing method / function route_data."""
        # Initialize key variables
        secondsago = 3600
        ts_start = uri.chart_timestamp_args(secondsago)

        # Initialize key variables
        _data = []
        checksum = data.hashstring(str(random()))
        pattoo_key = data.hashstring(str(random()))
        agent_id = data.hashstring(str(random()))
        _pi = 300 * 1000
        data_type = DATA_FLOAT
        now = int(time.time()) * 1000
        count = 0

        for timestamp in range(ts_start, now, _pi):
            insert = PattooDBrecord(
                pattoo_checksum=checksum,
                pattoo_key=pattoo_key,
                pattoo_agent_id=agent_id,
                pattoo_agent_polling_interval=_pi,
                pattoo_timestamp=timestamp,
                pattoo_data_type=data_type,
                pattoo_value=count,
                pattoo_agent_polled_target='pattoo_agent_polled_target',
                pattoo_agent_program='pattoo_agent_program',
                pattoo_agent_hostname='pattoo_agent_hostname',
                pattoo_metadata=[])
            count += 1

            # Create checksum entry in the DB, then update the data table
            idx_datapoint = datapoint.idx_datapoint(insert)
            _data.append(
                IDXTimestampValue(idx_datapoint=idx_datapoint,
                                  polling_interval=_pi,
                                  timestamp=timestamp,
                                  value=count))

        # Insert rows of new data
        lib_data.insert_rows(_data)

        # Test
        obj = DataPoint(idx_datapoint)
        ts_stop = obj.last_timestamp()
        expected = obj.data(ts_start, ts_stop)

        # Create URL
        config = WebConfig()
        url = ('{}/{}'.format(config.web_api_server_url(graphql=False),
                              idx_datapoint))

        # Check response
        with requests.get(url) as response:
            result = response.json()

        count = 0
        for item in result:
            ts_norm = times.normalized_timestamp(_pi, ts_start)
            if item['timestamp'] < ts_norm:
                self.assertIsNone(item['value'])
            else:
                self.assertEqual(item, expected[count])
                count += 1