예제 #1
0
def test_run():
    logger = setup_custom_logger(__name__)
    os.environ['_HANDLER'] = 'test_lambda.example_lambda'
    agent = Agent()
    agent.instrument(None)
    memory_exporter = configure_inmemory_span_exporter(agent)

    logger.info('Running test calls.')
    lamb = boto.awslambda.connect_to_region("us-east-2")

    # multiple calls
    try:
        lamb.list_functions()
    except:
        pass

    spans = memory_exporter.get_finished_spans()
    assert spans
    assert len(spans) == 1
    span = spans[0]

    assert span.attributes['endpoint'] == 'lambda'
    assert span.attributes['http.method'] == 'GET'
    assert span.attributes['aws.region'] == 'us-east-2'
    assert span.attributes['aws.operation'] == 'list_functions'
    memory_exporter.clear()
예제 #2
0
def test_run(agent_with_filter, exporter):
    logger = setup_custom_logger(__name__)

    app = Flask(__name__)

    @app.route("/route1")
    def api_1():
        logger.info('Serving request for /route1.')
        response = flask.Response(mimetype='application/json')
        response.headers['tester3'] = 'tester3'
        response.data = str('{ "a": "a", "xyz": "xyz" }')
        return response

    agent_with_filter.instrument(app)

    server = FlaskServer(app)

    logger.info('Running test calls.')
    with app.test_client() as c:
        logger.info('Making test call to /route1')
        r1 = app.test_client().get('http://localhost:5000/route1',
                                   headers={'tester1': 'tester1', 'tester2': 'tester2'})

        assert r1.status_code == 403
        span_list = exporter.get_finished_spans()
        assert span_list
        assert len(span_list) == 1
        flaskSpanAsObject = json.loads(span_list[0].to_json())

        # Check that the expected results are in the flask extended span attributes
        assert flaskSpanAsObject['attributes']['http.method'] == 'GET'
        assert flaskSpanAsObject['attributes']['http.target'] == '/route1'
        assert flaskSpanAsObject['attributes']['http.status_code'] == 403
예제 #3
0
def test_run(agent, exporter):
    logger = setup_custom_logger(__name__)
    logger.info('Initializing flask app.')
    # Create Flask app
    app = Flask(__name__)

    @app.route("/route1")
    def api_1():
        logger.info('Serving request for /route1.')
        return send_file("./app.py")

    @app.route("/unicode")
    def api_2():
        response = flask.Response(mimetype='application/x-www-form-urlencoded')
        response.data = b'\x80abc'
        return response

    agent.instrument(app)
    logger.info('Agent initialized.')

    logger.info('Running test calls.')
    with app.test_client() as c:
        logger.info('Making test call to /route1')
        r1 = app.test_client().get('http://localhost:5000/route1',
                                   headers={'tester1': 'tester1', 'tester2': 'tester2'})

        assert r1.status_code == 200
        span_list = exporter.get_finished_spans()
        assert span_list
        assert len(span_list) == 1
        flaskSpanAsObject = json.loads(span_list[0].to_json())

        # Check that the expected results are in the flask extended span attributes
        assert flaskSpanAsObject['attributes']['http.method'] == 'GET'
        assert flaskSpanAsObject['attributes']['http.target'] == '/route1'
        assert flaskSpanAsObject['attributes']['http.status_code'] == 200
        body_message = ""
        try:
            body_message = flaskSpanAsObject['attributes']['http.response.body']
        except KeyError:
            body_message = "key does not exist"
            print("key does not exist")

        assert body_message == "key does not exist"

        exporter.clear()

        r2 = app.test_client().get('http://localhost:5000/unicode')
        assert r2.status_code == 200
        span_list = exporter.get_finished_spans()
        assert span_list
        assert len(span_list) == 1
        flaskSpanAsObject = json.loads(span_list[0].to_json())

        # Check that the expected results are in the flask extended span attributes
        assert flaskSpanAsObject['attributes']['http.method'] == 'GET'
        assert flaskSpanAsObject['attributes']['http.target'] == '/unicode'
        assert flaskSpanAsObject['attributes']['http.response.body'] == "\\x80abc"
예제 #4
0
def test_run(agent, exporter):
    logger = setup_custom_logger(__name__)
    logger.info('Initializing flask app.')
    # Create Flask app
    app = Flask(__name__)

    @app.route("/route1")
    def api_1():
        logger.info('Serving request for /route1.')
        response = flask.Response(mimetype='application/json')
        response.headers['tester3'] = 'tester3'
        response.data = str('{ "a": "a", "xyz": "xyz" }')
        return response

    @app.route("/route2")
    def api_2():
        logger.info('Serving request for /route2.')
        response = flask.Response(mimetype='application/json')
        response.headers['tester3'] = 'tester3'
        response.data = str('{ "a": "a", "xyz": "xyz" }')
        return response

    agent.instrument(app)

    server = FlaskServer(app)
    server.start()

    logger.info('Running test calls.')
    with app.test_client() as c:
        logger.info('Making test call to /route1')
        r1 = app.test_client().get('http://localhost:5000/route1',
                                   headers={
                                       'tester1': 'tester1',
                                       'tester2': 'tester2'
                                   })
        logger.info('Making test call to /route2')
        r2 = app.test_client().get('http://localhost:5000/route2',
                                   headers={
                                       'tester1': 'tester1',
                                       'tester2': 'tester2'
                                   })

        logger.info('Reading /route1 response.')
        a1 = r1.get_json()['a']
        logger.info('Reading /route2 response.')
        a2 = r2.get_json()['a']
        assert a1 == 'a'
        assert a2 == 'a'
        logger.info('r1 result: ' + str(a1))
        logger.info('r2 result: ' + str(a2))
        logger.info('Exiting from flask instrumentation test.')
        server.shutdown()
예제 #5
0
def test_run(agent, exporter):
    logger = setup_custom_logger(__name__)
    logger.info('Initializing flask app.')
    # Create Flask app
    app = Flask(__name__)

    @app.route("/route1")
    def testAPI1():
        logger.info('Serving request for /route1.')
        response = flask.Response(mimetype='application/json')
        response.headers['tester3'] = 'tester3'
        response.data = str('{ "a": "a", "xyz": "xyz" }')
        return response

    agent.instrument(app)

    server = FlaskServer(app)
    server.start()
    logger.info('Running test calls.')
    with app.test_client() as c:
        logger.info('Making test call to /route1')
        r1 = app.test_client().get('http://localhost:5000/route1',
                                   headers={
                                       'tester1': 'tester1',
                                       'tester2': 'tester2'
                                   })
        # Get all of the in memory spans that were recorded for this iteration
        span_list = exporter.get_finished_spans()
        # Confirm something was returned.
        assert span_list
        # Confirm there are three spans
        logger.debug('len(span_list): ' + str(len(span_list)))
        assert len(span_list) == 1
        logger.debug('span_list: ' + str(span_list[0].attributes))
        flaskSpanAsObject = json.loads(span_list[0].to_json())
        # Check that the expected results are in the flask extended span attributes
        assert flaskSpanAsObject['attributes']['http.method'] == 'GET'
        assert flaskSpanAsObject['attributes']['http.target'] == '/route1'
        assert flaskSpanAsObject['attributes'][
            'http.request.header.tester1'] == 'tester1'
        assert flaskSpanAsObject['attributes'][
            'http.request.header.tester2'] == 'tester2'
        assert flaskSpanAsObject['attributes'][
            'http.response.header.content-type'] == 'application/json'
        assert flaskSpanAsObject['attributes'][
            'http.response.body'] == '{ "a": "a", "xyz": "xyz" }'
        assert flaskSpanAsObject['attributes']['http.status_code'] == 200
        assert flaskSpanAsObject['attributes'][
            'http.response.header.tester3'] == 'tester3'
        exporter.clear()
        server.shutdown()
예제 #6
0
def test_run():
    logger = setup_custom_logger(__name__)
    agent = Agent()
    agent.instrument(None)

    # Setup In-Memory Span Exporter
    logger.info('Agent initialized.')
    logger.info('Adding in-memory span exporter.')
    memoryExporter = InMemorySpanExporter()
    simpleExportSpanProcessor = SimpleSpanProcessor(memoryExporter)
    agent.register_processor(simpleExportSpanProcessor)
    logger.info('Added in-memory span exporter')

    logger.info('Running test calls.')
    try:
        session = botocore.session.get_session()
        session.set_credentials(access_key="access-key",
                                secret_key="secret-key")
        region = "us-west-2"
        client = session.create_client("lambda", region_name=region)
        iam_client = session.create_client("iam", region_name=region)
        arn = _create_role_and_get_arn(iam_client)
        result = _create_lambda_function('some_function',
                                         return_headers_lambda_str(), client,
                                         arn)
        memoryExporter.clear()
        response = client.invoke(
            Payload=json.dumps({}),
            FunctionName=result['FunctionArn'],
            InvocationType="RequestResponse",
        )

        spans = memoryExporter.get_finished_spans()
        invoke_span = spans[-1]

        assert invoke_span.attributes['faas.invoked_name'] == 'some_function'
        assert invoke_span.attributes['http.status_code'] == 200
        assert invoke_span.attributes['rpc.service'] == 'Lambda'
        memoryExporter.clear()

        return 0
    except:
        logger.error(
            'Failed to test boto instrumentation wrapper: exception=%s, stacktrace=%s',
            sys.exc_info()[0], traceback.format_exc())
        raise sys.exc_info()[0]
def test_multiple_queries_3(agent, exporter):
    agent.instrument()
    logger = setup_custom_logger(__name__)

    cnx = mysql.connector.connect(database='hypertrace',
                                  username='******',
                                  password='******',
                                  host='localhost',
                                  port=3306)
    cursor = cnx.cursor()

    insert_sql = "INSERT INTO hypertrace_data (col1, col2) VALUES (321, '123456789')"
    cursor.execute(insert_sql)

    delete_sql = "DELETE FROM hypertrace_data WHERE col1 = 321 AND col2='123456789'"
    cursor.execute(delete_sql)
    cursor.fetchall()

    select_sql = "SELECT * FROM hypertrace_data WHERE col1 = 432 AND col2= '0303456'"
    cursor.execute(select_sql)
    result = cursor.fetchall()
    assert result == []

    cursor.close()

    cnx.close()

    span_list = exporter.get_finished_spans()
    assert span_list

    logger.debug('len(span_list): ' + str(len(span_list)))

    expected_sql_statements = [insert_sql, delete_sql, select_sql]
    for i in range(len(expected_sql_statements)):
        span = json.loads(span_list[i].to_json())
        assert span['attributes']['db.system'] == 'mysql'
        assert span['attributes']['db.name'] == 'hypertrace'
        assert span['attributes']['db.statement'] == expected_sql_statements[i]
        assert span['attributes']['db.user'] == 'hypertrace'
        assert span['attributes']['net.peer.name'] == 'localhost'
        assert span['attributes']['net.peer.port'] == 3306
예제 #8
0
async def test_aiohttp_post(agent, exporter):
    logger = setup_custom_logger(__name__)
    app = Flask(__name__)
    app.use_reloader = False

    @app.route("/route1", methods=["POST"])
    def api_example():
        response = flask.Response(mimetype='application/json')
        response.headers['tester3'] = 'tester3'
        response.data = str('{ "a": "a", "xyz": "xyz" }')
        return response

    server = FlaskServer(app)
    server.start()
    agent.instrument(app)

    # Make test call
    async with aiohttp.ClientSession() as session:
        async with session.post(f'http://localhost:{server.port}/route1', data='{ "a":"b", "c": "d" }',
                                headers={'tester1': 'tester1', 'tester2': 'tester2'}) as response:
            response_body = await response.json()
            logger.info('Received: %s', str(response_body))
            a = response_body['a']
            assert a == 'a'
            span_list = exporter.get_finished_spans()

            assert span_list

            assert len(span_list) == 3
            aiohttpSpanAsObject = json.loads(span_list[0].to_json())

            assert aiohttpSpanAsObject['attributes']['http.method'] == 'POST'
            assert aiohttpSpanAsObject['attributes']['http.url'] == f'http://localhost:{server.port}/route1'
            assert aiohttpSpanAsObject['attributes']['http.request.header.tester1'] == 'tester1'
            assert aiohttpSpanAsObject['attributes']['http.request.header.tester2'] == 'tester2'
            assert aiohttpSpanAsObject['attributes']['http.response.header.content-type'] == 'application/json'
            assert aiohttpSpanAsObject['attributes']['http.response.body'] == '{ "a": "a", "xyz": "xyz" }'

            assert aiohttpSpanAsObject['attributes']['http.status_code'] == 200
            server.shutdown()
def test_request_client(agent, exporter):
    try:
        logger = setup_custom_logger(__name__)

        app = Flask(__name__)
        app.use_reloader = False

        @app.route("/route1")
        def api_example():
            response = flask.Response(mimetype='application/json')
            response.headers['tester3'] = 'tester3'
            response.data = str('{ "a": "a", "xyz": "xyz" }')
            return response

        agent.instrument(app)
        server = FlaskServer(app)
        server.start()

        url = f'http://localhost:{server.port}/route1'
        response = requests.get(url)

        spans = exporter.get_finished_spans()
        assert spans
        assert len(spans) == 2
        client_span = json.loads(spans[0].to_json())

        assert client_span['attributes']['http.method'] == 'GET'
        assert client_span['attributes'][
            'http.url'] == f'http://localhost:{server.port}/route1'
        assert client_span['attributes']['http.request.header.accept'] == '*/*'
        assert client_span['attributes'][
            'http.response.body'] == '{ "a": "a", "xyz": "xyz" }'
        assert client_span['attributes']['http.status_code'] == 200
        assert client_span['attributes'][
            'http.response.header.tester3'] == 'tester3'
        assert client_span['attributes']['http.request.header.traceparent']
        assert client_span['attributes']['http.method'] == 'GET'
    finally:
        server.shutdown()
def test_multiple_mysql_queries_2(agent, exporter):
    agent.instrument()
    logger = setup_custom_logger(__name__)
    cnx = get_connection(exporter)

    cursor = cnx.cursor()

    insert_sql = "INSERT INTO hypertrace_data (col1, col2) VALUES (321, '123456789')"
    cursor.execute(insert_sql)

    update_sql = "UPDATE hypertrace_data SET col1=432, col2 = '0303456' WHERE col1 = 321 AND col2='123456789'"
    cursor.execute(update_sql)
    cursor.fetchall()

    logger.info('Running SELECT statement.')
    select_sql = "SELECT * FROM hypertrace_data WHERE col1 = 432 AND col2= '0303456'"
    cursor.execute(select_sql)
    result = cursor.fetchall()
    assert result[0][0] == 432
    assert result[0][1] == '0303456'

    cursor.close()
    cnx.close()

    span_list = exporter.get_finished_spans()
    assert span_list

    assert len(span_list) == 3
    expected_sql_statements = [insert_sql, update_sql, select_sql]
    for i in range(len(expected_sql_statements)):
        span = json.loads(span_list[i].to_json())
        assert span['attributes']['db.system'] == 'mysql'
        assert span['attributes']['db.name'] == 'hypertrace'
        assert span['attributes']['db.statement'] == expected_sql_statements[i]
        assert span['attributes']['db.user'] == 'hypertrace'
        assert span['attributes']['net.peer.name'] == 'localhost'
        assert span['attributes']['net.peer.port'] == 3306
예제 #11
0
import flask
import json
from flask import request, Flask
from tests import setup_custom_logger
from tests.hypertrace.agent.instrumentation.flask.app import FlaskServer

logger = setup_custom_logger(__name__)

logger.info('Initializing flask app.')
# Create Flask app
app = Flask(__name__)
logger.info('Flask app initialized.')


@app.route('/test/postdata', methods=['POST'])
def post_api():
    data = request.get_json()
    logger.info('Serving request for /test/postdata')
    response = flask.Response(mimetype='application/json')
    response.headers['tester3'] = 'tester3'
    sum1 = data['d1']
    sum2 = data['d2']
    response.data = str(sum1 + sum2)
    return response


server = FlaskServer(app)


def test_run(agent, exporter):
    agent.instrument(app)
def test_request_propagation(agent, exporter):
    try:
        logger = setup_custom_logger(__name__)
        logger.info('Initializing flask app.')
        # Create Flask app
        app = Flask(__name__)

        @app.route("/route2")
        def api_example_2():
            headers = {'tester1': 'tester1', 'tester2': 'tester2'}
            if flask.request.args.get("a") is None:
                requests.get(
                    url=f'http://localhost:{server.port}/route2?a=foo',
                    headers=headers)
            response = flask.Response(mimetype='application/json')
            response.headers['tester3'] = 'tester3'
            response.data = str('{ "a": "a", "xyz": "xyz" }')
            return response

        agent.instrument(app)
        server = FlaskServer(app)
        server.start()

        logger.info('Agent initialized.')

        r1 = app.test_client().get(f'http://localhost:{server.port}/route2',
                                   headers={
                                       'tester1': 'tester1',
                                       'tester2': 'tester2'
                                   })
        # Get all of the in memory spans that were recorded for this iteration
        spans = exporter.get_finished_spans()
        # Confirm something was returned.
        assert spans
        # 3 spans => server => requests => server
        assert len(spans) == 3
        server_1_span = json.loads(spans[0].to_json())
        request_span = json.loads(spans[1].to_json())
        # Check that the expected results are in the flask extended span attributes
        assert server_1_span["kind"] == "SpanKind.SERVER"
        assert server_1_span['attributes']['http.method'] == 'GET'
        assert server_1_span['attributes']['http.route'] == '/route2'
        assert server_1_span['attributes'][
            'http.response.header.content-type'] == 'application/json'
        assert server_1_span['attributes'][
            'http.response.body'] == '{ "a": "a", "xyz": "xyz" }'
        assert server_1_span['attributes']['http.status_code'] == 200
        assert server_1_span['attributes'][
            'http.response.header.tester3'] == 'tester3'

        assert request_span["kind"] == "SpanKind.CLIENT"
        assert request_span['attributes']['http.request.header.traceparent']
        assert request_span['attributes']['http.method'] == 'GET'
        assert request_span['attributes'][
            'http.url'] == f'http://localhost:{server.port}/route2?a=foo'
        assert request_span['attributes']['http.status_code'] == 200
        exporter.clear()
        a1 = r1.get_json()['a']
        assert a1 == 'a'
    finally:
        server.shutdown()
예제 #13
0
def test_run(agent, exporter):
    logger = setup_custom_logger(__name__)
    logger.info('Initializing flask app.')
    # Create Flask app
    app = Flask(__name__)

    @app.route("/route1", methods=['GET'])
    def api_1():
        logger.info('Serving request for /route1.')
        response = flask.Response(mimetype='application/json')
        response.headers['tester3'] = 'tester3'
        response.data = str('{ "a": "a", "xyz": "xyz" }')
        return response

    @app.route("/route2", methods=['GET'])
    def api_2():
        logger.info('Serving request for /route2.')
        response = flask.Response(mimetype='application/json')
        response.headers['tester3'] = 'tester3'
        response.data = str('{ "a": "a", "xyz": "xyz" }')
        return response

    @app.route('/home/<name>', methods=['GET'])
    def api_3(name):
        logger.info('Serving request for /home.')
        return "hello," + name

    agent.instrument(app)

    server = FlaskServer(app)
    server.start()

    with app.test_client() as c:
        logger.info('Making test call to /route1')
        r1 = app.test_client().get('http://localhost:5000/route1',
                                   headers={
                                       'tester1': 'tester1',
                                       'tester2': 'tester2'
                                   })
        # Get all of the in memory spans that were recorded for this iteration
        span_list = exporter.get_finished_spans()
        # Confirm something was returned.
        assert span_list
        # Confirm there are three spans
        logger.debug('len(span_list): ' + str(len(span_list)))
        assert len(span_list) == 1
        logger.debug('span_list: ' + str(span_list[0].attributes))
        flaskSpanAsObject = json.loads(span_list[0].to_json())
        # Check that the expected results are in the flask extended span attributes
        assert flaskSpanAsObject['attributes']['http.method'] == 'GET'
        assert flaskSpanAsObject['attributes']['http.target'] == '/route1'
        assert flaskSpanAsObject['attributes'][
            'http.request.header.tester1'] == 'tester1'
        assert flaskSpanAsObject['attributes'][
            'http.request.header.tester2'] == 'tester2'
        assert flaskSpanAsObject['attributes'][
            'http.response.header.content-type'] == 'application/json'
        assert flaskSpanAsObject['attributes'][
            'http.response.body'] == '{ "a": "a", "xyz": "xyz" }'
        assert flaskSpanAsObject['attributes']['http.status_code'] == 200
        assert flaskSpanAsObject['attributes'][
            'http.response.header.tester3'] == 'tester3'
        exporter.clear()

        logger.info('Making test call to /route2')
        r2 = app.test_client().get('http://localhost:5000/route2',
                                   headers={
                                       'tester1': 'tester1',
                                       'tester2': 'tester2'
                                   })
        # Confirm something was returned.
        assert span_list
        # Confirm there are three spans
        logger.debug('len(span_list): ' + str(len(span_list)))
        assert len(span_list) == 1
        logger.debug('span_list: ' + str(span_list[0].attributes))
        flaskSpanAsObject = json.loads(span_list[0].to_json())
        # Check that the expected results are in the flask extended span attributes
        assert flaskSpanAsObject['attributes']['http.method'] == 'GET'
        assert flaskSpanAsObject['attributes']['http.target'] == '/route1'
        assert flaskSpanAsObject['attributes'][
            'http.request.header.tester1'] == 'tester1'
        assert flaskSpanAsObject['attributes'][
            'http.request.header.tester2'] == 'tester2'
        assert flaskSpanAsObject['attributes'][
            'http.response.header.content-type'] == 'application/json'
        assert flaskSpanAsObject['attributes'][
            'http.response.body'] == '{ "a": "a", "xyz": "xyz" }'
        assert flaskSpanAsObject['attributes']['http.status_code'] == 200
        assert flaskSpanAsObject['attributes'][
            'http.response.header.tester3'] == 'tester3'
        exporter.clear()

        logger.info('Making test call to /home')
        r3 = app.test_client().get('http://localhost:5000/home/test')
        span_list = exporter.get_finished_spans()
        # Confirm something was returned.
        assert span_list
        # Confirm there are three spans
        logger.debug('len(span_list): ' + str(len(span_list)))
        assert len(span_list) == 1
        logger.debug('span_list: ' + str(span_list[0].attributes))
        flaskSpanAsObject = json.loads(span_list[0].to_json())
        # Check that the expected results are in the flask extended span attributes
        assert flaskSpanAsObject['attributes']['http.method'] == 'GET'
        assert flaskSpanAsObject['attributes']['http.target'] == '/home/test'
        assert flaskSpanAsObject['attributes']['http.status_code'] == 200
        assert flaskSpanAsObject['name'] == 'GET /home/<name>'

        exporter.clear()

        logger.info('Reading /route1 response.')
        a1 = r1.get_json()['a']
        logger.info('Reading /route2 response.')
        a2 = r2.get_json()['a']
        assert a1 == 'a'
        assert a2 == 'a'
        logger.info('r1 result: ' + str(a1))
        logger.info('r2 result: ' + str(a2))
        logger.info('Exiting from flask instrumentation test.')

        server.shutdown()
예제 #14
0
def test_run(agent, exporter):
    logger = setup_custom_logger(__name__)
    logger.info('Initializing flask app.')
    # Create Flask app
    app = Flask(__name__)

    @app.route("/route1")
    def testAPI1():
        logger.info('Serving request for /route1.')
        response = flask.Response(mimetype='application/json')
        response.headers['tester3'] = 'tester3'
        response.data = str('{ "a": "a", "xyz": "xyz" }')
        return response

    @app.route("/route2")
    def testAPI2():
        logger.info('Serving request for /route2.')
        response = flask.Response(mimetype='application/json')
        response.headers['tester3'] = 'tester3'
        json_data = {"message": "Hello [('mysql.infoschema', 'localhost')]"}
        response.data = json.dumps(json_data)
        return response

    logger.info('Flask app initialized.')

    #
    # Code snippet here represents the current initialization logic
    #
    logger.info('Initializing agent.')
    agent.instrument(app)
    logger.info('Agent initialized.')

    server = FlaskServer(app)
    server.start()

    logger.info('Running test calls.')
    with app.test_client() as c:
        logger.info('Making test call to /route1')
        r1 = app.test_client().get(f'http://localhost:{server.port}/route1',
                                   headers={
                                       'tester1': 'tester1',
                                       'tester2': 'tester2'
                                   })
        # Get all of the in memory spans that were recorded for this iteration
        span_list = exporter.get_finished_spans()
        # Confirm something was returned.
        assert span_list
        # Confirm there are three spans
        logger.debug('len(span_list): ' + str(len(span_list)))
        assert len(span_list) == 1
        logger.debug('span_list: ' + str(span_list[0].attributes))
        flaskSpanAsObject = json.loads(span_list[0].to_json())
        # Check that the expected results are in the flask extended span attributes
        assert flaskSpanAsObject['attributes']['http.method'] == 'GET'
        assert flaskSpanAsObject['attributes']['http.target'] == '/route1'
        assert flaskSpanAsObject['attributes'][
            'http.request.header.tester1'] == 'tester1'
        assert flaskSpanAsObject['attributes'][
            'http.request.header.tester2'] == 'tester2'
        assert flaskSpanAsObject['attributes'][
            'http.response.header.content-type'] == 'application/json'
        assert flaskSpanAsObject['attributes'][
            'http.response.body'] == '{ "a": "a", "xyz": "xyz" }'
        assert flaskSpanAsObject['attributes']['http.status_code'] == 200
        assert flaskSpanAsObject['attributes'][
            'http.response.header.tester3'] == 'tester3'
        exporter.clear()
        logger.info('Making test call to /route2')
        r2 = app.test_client().get('http://localhost:5000/route2',
                                   headers={
                                       'tester1': 'tester1',
                                       'tester2': 'tester2'
                                   })
        # Confirm something was returned.
        span_list = exporter.get_finished_spans()
        assert span_list
        # Confirm there are three spans
        logger.debug('len(span_list): ' + str(len(span_list)))
        assert len(span_list) == 1
        logger.debug('span_list: ' + str(span_list[0].attributes))
        flaskSpanAsObject = json.loads(span_list[0].to_json())
        # Check that the expected results are in the flask extended span attributes
        assert flaskSpanAsObject['attributes']['http.method'] == 'GET'
        assert flaskSpanAsObject['attributes']['http.target'] == '/route2'
        assert flaskSpanAsObject['attributes'][
            'http.request.header.tester1'] == 'tester1'
        assert flaskSpanAsObject['attributes'][
            'http.request.header.tester2'] == 'tester2'
        assert flaskSpanAsObject['attributes'][
            'http.response.header.content-type'] == 'application/json'
        assert flaskSpanAsObject['attributes'][
            'http.response.body'] == '{"message": "Hello [(\'mysql.infoschema\', \'localhost\')]"}'
        assert flaskSpanAsObject['attributes']['http.status_code'] == 200
        assert flaskSpanAsObject['attributes'][
            'http.response.header.tester3'] == 'tester3'
        exporter.clear()
        logger.info('Reading /route1 response.')
        a1 = r1.get_json()['a']
        logger.info('Reading /route2 response.')
        a2 = r2.get_json()['message']
        assert a1 == 'a'
        assert a2 == 'Hello [(\'mysql.infoschema\', \'localhost\')]'
        logger.info('r1 result: ' + str(a1))
        logger.info('r2 result: ' + str(a2))
        logger.info('Exiting from flask instrumentation test.')

    server.shutdown()
예제 #15
0
def test_run(agent, exporter):
    logger = setup_custom_logger(__name__)
    os.environ[
        '_HANDLER'] = 'tests.hypertrace.agent.instrumentation.lambda.lambda_test.example_lambda'
    agent.instrument()
    logger.info('Running test calls.')
    mockEventData = {
        'version': '2.0',
        'routeKey': 'POST /test-function',
        'rawPath': '/default/test-function',
        'rawQueryString': '',
        'headers': {
            'accept': '*/*',
            'content-length': '23',
            'content-type': 'application/json',
            'host': 'something.foo.bar',
            'user-agent': 'insomnia/2021.6.0',
            'x-amzn-trace-id': 'Root=1-61bc2935-0d71070e0218146e5683cd7e',
            'x-forwarded-for': '202.87.208.0, 207.255.222.177',
            'x-forwarded-port': '443',
            'x-forwarded-proto': 'https'
        },
        'cookies': ["name=123", "anothercookie=456"],
        'multiValueHeaders': {
            'accept': ['*/*'],
            'Host': ['something.foo.bar'],
            'User-Agent': ['insomnia/2021.7.2'],
            'X-Amzn-Trace-Id': ['Root=1-61bc2935-0d71070e0218146e5683cd7e'],
            'X-Forwarded-For': ['202.87.208.0, 207.255.222.177'],
            'X-Forwarded-Port': ['443'],
            'X-Forwarded-Proto': ['https']
        },
        'requestContext': {
            'accountId': '286278240186',
            'apiId': 'brz7ycf4q7',
            'domainName': 'something.foo.bar',
            'domainPrefix': 'brz7ycf4q7',
            'http': {
                'method': 'POST',
                'path': '/default/test-function',
                'protocol': 'HTTP/1.1',
                'sourceIp': '207.255.222.177',
                'userAgent': 'insomnia/2021.6.0'
            },
            'requestId': 'Ketgdj-vCYcEMHw=',
            'routeKey': 'POST /test-function',
            'stage': 'default',
            'time': '17/Dec/2021:06:07:49 +0000',
            'timeEpoch': 1639721269962
        },
        'body': '{\n\t"name": "sample body data"\n}',
        'isBase64Encoded': False
    }

    cntxt = ContextStub()
    example_lambda(mockEventData, cntxt)
    # Get all of the in memory spans that were recorded for this iteration
    span_list = exporter.get_finished_spans()
    # Confirm something was returned.
    assert span_list

    assert len(span_list) == 1
    logger.debug('span_list: ' + str(span_list[0].attributes))
    span = json.loads(span_list[0].to_json())
    # Check that the expected results are in the flask extended span attributes
    assert span['attributes']['http.method'] == 'POST'
    assert span['attributes']['http.host'] == 'something.foo.bar'
    assert span['attributes']['http.target'] == '/default/test-function'
    assert span['attributes']['http.scheme'] == 'https'
    assert span['attributes'][
        'http.request.header.x-forwarded-for'] == '202.87.208.0, 207.255.222.177'
    assert span['attributes'][
        'http.request.header.x-amzn-trace-id'] == 'Root=1-61bc2935-0d71070e0218146e5683cd7e'
    assert span['attributes'][
        'http.request.header.cookie'] == 'name=123;anothercookie=456'
    assert span['attributes'][
        'http.response.header.content-type'] == 'application/json'
    assert span['attributes'][
        'http.request.body'] == '{\n\t"name": "sample body data"\n}'
    assert span['attributes'][
        'http.response.body'] == '{"test_key": "test_value"}'
    assert span['attributes']['http.status_code'] == 200
    assert span['attributes'][
        'http.response.header.content-type'] == 'application/json'
def test_mysql_within_application(agent, exporter):
    logger = setup_custom_logger(__name__)

    app = Flask(__name__)
    agent.instrument(app)
    conn = get_connection(exporter)

    @app.route("/dbtest")
    def api():
        cnx = get_connection(exporter)
        cursor = cnx.cursor()
        cursor.execute(
            "INSERT INTO hypertrace_data (col1, col2) VALUES (123, 'abcdefghijklmnopqrstuvwxyz')")
        cursor.execute(
            "INSERT INTO hypertrace_data (col1, col2) VALUES (456, 'abcdefghijklmnopqrstuvwxyz')")
        cursor.close()
        cnx.close()
        response = flask.Response(mimetype='application/json')
        response.data = str('{ "a": "a", "xyz": "xyz" }')
        return response

    server = FlaskServer(app)

    logger.info('Running test calls.')
    with app.test_client() as c:
        logger.info('Making test call to /dbtest')
        for x in range(10):  # Run 10 requests
            r1 = app.test_client().get(f'http://localhost:{server.port}/dbtest')
            logger.info('Reading /dbtest response.')
            a1 = r1.get_json()['a']
            assert a1 == 'a'
            # Get all of the in memory spans that were recorded for this iteration
            span_list = exporter.get_finished_spans()
            # Confirm something was returned.
            assert span_list

            assert len(span_list) == 3

            flaskSpanAsObject = json.loads(span_list[2].to_json())
            sql1SpanAsObject = json.loads(span_list[1].to_json())
            sql2SpanAsObject = json.loads(span_list[0].to_json())

            assert flaskSpanAsObject['attributes']['http.method'] == 'GET'
            assert flaskSpanAsObject['attributes']['http.target'] == '/dbtest'
            assert flaskSpanAsObject['attributes']['http.response.header.content-type'] == 'application/json'
            assert flaskSpanAsObject['attributes'][
                       'http.response.body'] == '{ "a": "a", "xyz": "xyz" }'
            assert flaskSpanAsObject['attributes']['http.status_code'] == 200

            assert sql1SpanAsObject['attributes']['db.system'] == 'mysql'
            assert sql1SpanAsObject['attributes']['db.name'] == 'hypertrace'
            assert sql1SpanAsObject['attributes']['db.user'] == 'hypertrace'
            assert sql1SpanAsObject['attributes']['net.peer.name'] == 'localhost'
            assert sql1SpanAsObject['attributes']['net.peer.port'] == 3306
            assert sql1SpanAsObject['attributes'][
                       'db.statement'] == "INSERT INTO hypertrace_data (col1, col2) VALUES (456, 'abcdefghijklmnopqrstuvwxyz')"

            assert sql2SpanAsObject['attributes']['db.system'] == 'mysql'
            assert sql2SpanAsObject['attributes']['db.name'] == 'hypertrace'
            assert sql2SpanAsObject['attributes']['db.user'] == 'hypertrace'
            assert sql2SpanAsObject['attributes']['net.peer.name'] == 'localhost'
            assert sql2SpanAsObject['attributes']['net.peer.port'] == 3306
            assert sql2SpanAsObject['attributes'][
                       'db.statement'] == "INSERT INTO hypertrace_data (col1, col2) VALUES (123, 'abcdefghijklmnopqrstuvwxyz')"