def test_ensure_installed_twice(caplog):
    ensure_installed()
    ensure_installed()

    assert caplog.record_tuples == 2 * [(
        "scout_apm.instruments.pymongo",
        logging.DEBUG,
        "Instrumenting pymongo.",
    )]
def test_ensure_installed_twice(caplog):
    ensure_installed()
    ensure_installed()

    assert caplog.record_tuples == 2 * [(
        "scout_apm.instruments.pymongo",
        logging.INFO,
        "Ensuring pymongo instrumentation is installed.",
    )]
def test_ensure_installed_fail_no_collection(caplog):
    mock_no_collection = mock.patch("scout_apm.instruments.pymongo.Collection",
                                    new=None)
    with mock_no_collection:
        ensure_installed()

    assert caplog.record_tuples == [
        (
            "scout_apm.instruments.pymongo",
            logging.DEBUG,
            "Instrumenting pymongo.",
        ),
        (
            "scout_apm.instruments.pymongo",
            logging.DEBUG,
            "Couldn't import pymongo.Collection - probably not installed.",
        ),
    ]
def test_ensure_installed_fail_no_collection(caplog):
    mock_no_collection = mock.patch("scout_apm.instruments.pymongo.Collection",
                                    new=None)
    with mock_no_collection:
        ensure_installed()

    assert caplog.record_tuples == [
        (
            "scout_apm.instruments.pymongo",
            logging.INFO,
            "Ensuring pymongo instrumentation is installed.",
        ),
        (
            "scout_apm.instruments.pymongo",
            logging.INFO,
            "Unable to import pymongo.Collection",
        ),
    ]
def test_ensure_installed_fail_no_collection_aggregate(caplog):
    mock_not_patched = mock.patch(
        "scout_apm.instruments.pymongo.have_patched_collection", new=False)
    mock_collection = mock.patch("scout_apm.instruments.pymongo.Collection")
    with mock_not_patched, mock_collection as mocked_collection:
        del mocked_collection.aggregate

        ensure_installed()

    assert len(caplog.record_tuples) == 2
    assert caplog.record_tuples[0] == (
        "scout_apm.instruments.pymongo",
        logging.DEBUG,
        "Instrumenting pymongo.",
    )
    logger, level, message = caplog.record_tuples[1]
    assert logger == "scout_apm.instruments.pymongo"
    assert level == logging.WARNING
    assert message.startswith(
        "Failed to instrument pymongo.Collection.aggregate: AttributeError")
def pymongo_client():
    # e.g. export MONGODB_URL="mongodb://localhost:27017"
    ensure_installed()
    if "MONGODB_URL" not in os.environ:
        raise pytest.skip("MongoDB isn't available")
    yield pymongo.MongoClient(os.environ["MONGODB_URL"])