Пример #1
0
def test_auto_timestamp(db_string):
    """Ensure that timestamps are autopopulated correctly if not passed."""

    # Define a schema where the timestamp doesn't automatically populate through the database
    schema = {"event": "TEXT", "timestamp": "TIMESTAMP"}

    # Put together two trackers, one that autopopulates the timestamp
    no_auto = pawprint.Tracker(db=db_string,
                               table="no_auto",
                               auto_timestamp=False,
                               schema=schema)
    auto = pawprint.Tracker(db=db_string,
                            table="auto",
                            auto_timestamp=True,
                            schema=schema)

    # Create clean tables
    no_auto.create_table()
    auto.create_table()

    # Write events with no timestamp
    no_auto.write(event="foo")
    auto.write(event="bar")

    assert len(no_auto.read()) == 1
    assert len(auto.read()) == 1

    assert len(no_auto.read().dropna()) == 0
    assert len(auto.read().dropna()) == 1

    # Drop tables at the end
    no_auto.drop_table()
    auto.drop_table()
Пример #2
0
def pawprint_default_tracker_db_with_table(tmpdir, drop_tracker_test_table,
                                           db_string, tracker_test_table_name):
    """Set up DB with table before tests"""
    # TODO: setup DB
    tracker = pawprint.Tracker(db=db_string, table=tracker_test_table_name)
    tracker.create_table()
    return tracker
Пример #3
0
def test_silent_write_errors():
    """When a failure occurs in event write, it should fail silently."""

    tracker = pawprint.Tracker(db=None, table=None)

    try:
        tracker.write(event="This will fail silently.")
    except Exception:
        pytest.fail("Failed to fail silently.")
Пример #4
0
def test_create_table_with_other_options(drop_tracker_test_table, db_string,
                                         tracker_test_table_name):
    """Ensure the table is correctly created with an alternative schema."""

    schema = OrderedDict([("pk", "SERIAL PRIMARY KEY"), ("infofield", "TEXT")])
    tracker = pawprint.Tracker(db=db_string,
                               table=tracker_test_table_name,
                               schema=schema)
    tracker.create_table()

    # Ensure its schema is correct
    schema = pd.io.sql.execute(
        "SELECT column_name, data_type, character_maximum_length "
        "FROM INFORMATION_SCHEMA.COLUMNS "
        "WHERE table_name = '{}'".format(tracker.table),
        tracker.db,
    ).fetchall()

    assert schema == [("pk", "integer", None), ("infofield", "text", None)]
Пример #5
0
def pawprint_default_statistics_tracker(
    tmpdir, drop_statistics_test_table, db_string, statistics_test_table_names
):
    """Set up DB with table before tests"""
    # List of users who performed events
    users = [
        "Frodo",
        "Frodo",
        "Frodo",
        "Frodo",
        "Frodo",
        "Frodo",
        "Gandalf",
        "Gandalf",
        "Frodo",
        "Gandalf",
        "Gandalf",
        "Frodo",
        "Frodo",
        "Frodo",
        "Frodo",
        "Frodo",
    ]

    # List of times ( minutes ) between any event and the first events
    timedeltas = [0, 1, 2, 3, 4, 5, 100, 110, 120, 130, 140, 1000, 1001, 1002, 1003, 1004]

    # Create a tracker
    tracker = pawprint.Tracker(db=db_string, table=statistics_test_table_names["tracker_table"])
    tracker.create_table()

    # Yesterday morning
    today = datetime.now()
    yesterday = datetime(today.year, today.month, today.day, 9, 0) - timedelta(days=1)

    # Write all events
    for user, delta in zip(users, timedeltas):
        tracker.write(user_id=user, timestamp=yesterday + timedelta(minutes=delta))

    # Save the tracker
    return tracker
Пример #6
0
def test_nonsilent_write_errors(error_logger):
    """Test non-silent write errors that should output to the logger or raise exceptions."""

    tracker = pawprint.Tracker(db="postgresql:///fail", logger=error_logger)

    with pytest.raises(Exception):
        tracker.write()
    with pytest.raises(Exception):
        tracker.write(event="going_to_fail")

    with open("pawprint.log", mode="r") as f:
        logs = f.readlines()
        print(logs[3])

    assert len(logs) == 6
    assert logs[0].startswith("pawprint failed to write.")
    assert "Table: None. Query: INSERT INTO None () VALUES ();" in logs[0]
    assert "Query: INSERT INTO None (event) VALUES ('going_to_fail')" in logs[
        3]

    os.remove("pawprint.log")
Пример #7
0
def test_instantiate_tracker_from_dot_file(drop_tracker_test_table):
    """Test instantiating a Tracker with a dotfile instead of using db and table strings."""

    # Write a dotfile to disk
    dotfile = {
        "db": "postgresql:///little_bean_toes",
        "json_field": "such_fuzzy",
    }

    with open(".pawprint", "w") as f:
        json.dump(dotfile, f)

    # Create a tracker from this dotfile
    tracker = pawprint.Tracker(dotfile=".pawprint", json_field="boop")

    # Ensure all the entries are as they should be
    assert tracker.db == "postgresql:///little_bean_toes"
    assert tracker.table is None
    assert tracker.logger is None
    assert tracker.json_field == "boop"  # field present in dotfile but overwritten in init

    os.remove(".pawprint")
Пример #8
0
def test_write(drop_tracker_test_table, db_string, tracker_test_table_name):
    """Test the tracking of an event."""

    tracker = pawprint.Tracker(db=db_string,
                               table=tracker_test_table_name,
                               schema={"id": "INT"})
    tracker.create_table()

    # Check the table's empty
    assert pd.io.sql.execute("SELECT COUNT(*) FROM {}".format(tracker.table),
                             tracker.db).fetchall() == [(0, )]

    # Add some data and check if the row count increases by one
    tracker.write(id=1337)
    assert pd.io.sql.execute("SELECT COUNT(*) FROM {}".format(tracker.table),
                             tracker.db).fetchall() == [(1, )]

    # Pull the data and ensure it's correct
    data = pd.read_sql("SELECT * FROM {}".format(tracker.table), tracker.db)
    assert isinstance(data, pd.DataFrame)
    assert len(data.columns) == 1
    assert data.columns[0] == "id"
    assert data.id[0] == 1337
Пример #9
0
def pawprint_default_tracker_db(
    tmpdir, drop_tracker_test_table, db_string, tracker_test_table_name
):
    """Set up DB before tests, tear down after"""

    return pawprint.Tracker(db=db_string, table=tracker_test_table_name)