import datetime
import pytest
from girder import auditLogger


@pytest.fixture
def recordModel():
    from girder.plugins.audit_logs import Record
    yield Record()


@pytest.fixture
def resetLog():
    yield auditLogger

    for handler in auditLogger.handlers:
        auditLogger.removeHandler(handler)


@pytest.mark.plugin('audit_logs')
def testAnonymousRestRequestLogging(server, recordModel, resetLog):
    assert list(recordModel.find()) == []

    server.request('/user/me')

    records = recordModel.find()
    assert records.count() == 1
    record = records[0]

    assert record['ip'] == '127.0.0.1'
    assert record['type'] == 'rest.request'
    assert record['userId'] == None
    assert isinstance(record['when'], datetime.datetime)
    assert record['details']['method'] == 'GET'
    assert record['details']['status'] == 200
    assert record['details']['route'] == ['user', 'me']
    assert record['details']['params'] == {}


@pytest.mark.plugin('audit_logs')
def testFailedRestRequestLogging(server, recordModel, resetLog):
    server.request('/folder', method='POST', params={
        'name': 'Foo',
        'parentId': 'foo'
    })
    records = recordModel.find()

    assert records.count() == 1
    details = records[0]['details']

    assert details['method'] == 'POST'
    assert details['status'] == 401
    assert details['route'] == ['folder']
    assert details['params'] == {
        'name': 'Foo',
        'parentId': 'foo'
    }


@pytest.mark.plugin('audit_logs')
def testAuthenticatedRestRequestLogging(server, recordModel, resetLog, admin):
    server.request('/user/me', user=admin)
    records = recordModel.find()
    assert records.count() == 1
    record = records[0]
    assert record['userId'] == admin['_id']

@@ -23,16 +23,27 @@
  pytest%0A
+import six%0A
 from gir
@@ -65,16 +65,132 @@
 tLogger%0A
+from girder.models.file import File%0Afrom girder.models.folder import Folder%0Afrom girder.models.upload import Upload%0A
 %0A%0A@pytes
@@ -1878,8 +1878,829 @@
 %5B'_id'%5D%0A
+%0A%0A@pytest.mark.plugin('audit_logs')%0Adef testDownloadLogging(server, recordModel, resetLog, admin, fsAssetstore):%0A    folder = Folder().find(%7B%0A        'parentId': admin%5B'_id'%5D,%0A        'name': 'Public'%0A    %7D)%5B0%5D%0A    file = Upload().uploadFromFile(%0A        six.BytesIO(b'hello'), size=5, name='test', parentType='folder', parent=folder,%0A        user=admin, assetstore=fsAssetstore)%0A%0A    File().download(file, headers=False, offset=2, endByte=4)%0A%0A    records = recordModel.find()%0A%0A    assert records.count() == 1%0A    record = records%5B0%5D%0A    assert record%5B'ip'%5D == '127.0.0.1'%0A    assert record%5B'type'%5D == 'file.download'%0A    assert record%5B'details'%5D%5B'fileId'%5D == file%5B'_id'%5D%0A    assert record%5B'details'%5D%5B'startByte'%5D == 2%0A    assert record%5B'details'%5D%5B'endByte'%5D == 4%0A    assert isinstance(record%5B'when'%5D, datetime.datetime)%0A

Add test for file download log event