Skip to content

Commit

Permalink
(#102) ContentController: last test groundwork
Browse files Browse the repository at this point in the history
  • Loading branch information
ForNeVeR committed Aug 27, 2022
1 parent 9100471 commit 107c4be
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 26 deletions.
1 change: 1 addition & 0 deletions Emulsion.TestFramework/Emulsion.TestFramework.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<Compile Include="TelegramClientMock.fs" />
<Compile Include="WebFileStorage.fs" />
<Compile Include="SimpleHttpClientFactory.fs" />
<Compile Include="TestFileCache.fs" />
</ItemGroup>

<ItemGroup>
Expand Down
22 changes: 22 additions & 0 deletions Emulsion.TestFramework/TestFileCache.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module Emulsion.TestFramework.TestFileCache

open System.IO

open Emulsion.ContentProxy
open Emulsion.Settings
open Emulsion.TestFramework.Logging

let newCacheDirectory() =
let path = Path.GetTempFileName()
File.Delete path
Directory.CreateDirectory path |> ignore
path

let setUpFileCache outputHelper sha256 cacheDirectory (totalLimitBytes: uint64) =
let settings = {
Directory = cacheDirectory
FileSizeLimitBytes = 10UL * 1024UL * 1024UL
TotalCacheSizeLimitBytes = totalLimitBytes
}

new FileCache(xunitLogger outputHelper, settings, SimpleHttpClientFactory(), sha256)
23 changes: 5 additions & 18 deletions Emulsion.Tests/ContentProxy/FileCacheTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,16 @@ open Xunit
open Xunit.Abstractions

open Emulsion.ContentProxy
open Emulsion.Settings
open Emulsion.TestFramework
open Emulsion.TestFramework.Logging

type FileCacheTests(outputHelper: ITestOutputHelper) =

let sha256 = SHA256.Create()

let cacheDirectory = lazy (
let path = Path.GetTempFileName()
File.Delete path
Directory.CreateDirectory path |> ignore
path
)
let cacheDirectory = lazy TestFileCache.newCacheDirectory()

let setUpFileCache(totalLimitBytes: uint64) =
let settings = {
Directory = cacheDirectory.Value
FileSizeLimitBytes = 10UL * 1024UL * 1024UL
TotalCacheSizeLimitBytes = totalLimitBytes
}

new FileCache(xunitLogger outputHelper, settings, SimpleHttpClientFactory(), sha256)
TestFileCache.setUpFileCache outputHelper sha256 cacheDirectory.Value totalLimitBytes

let assertCacheState(entries: (string * byte[]) seq) =
let files =
Expand Down Expand Up @@ -82,6 +69,9 @@ type FileCacheTests(outputHelper: ITestOutputHelper) =
return buffer.ToArray()
}

interface IDisposable with
member _.Dispose() = sha256.Dispose()

[<Fact>]
member _.``File cache should throw a validation exception if the cache directory contains directories``(): unit =
assertCacheValidationError
Expand Down Expand Up @@ -203,6 +193,3 @@ type FileCacheTests(outputHelper: ITestOutputHelper) =
let! content = readAllBytes stream
Assert.Equal<byte>(fileStorage.Content "a", content)
}

interface IDisposable with
member _.Dispose() = sha256.Dispose()
56 changes: 48 additions & 8 deletions Emulsion.Tests/Web/ContentControllerTests.fs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace Emulsion.Tests.Web

open System
open System.Security.Cryptography
open System.Threading.Tasks

open Microsoft.AspNetCore.Mvc
Expand Down Expand Up @@ -29,25 +30,35 @@ type ContentControllerTests(output: ITestOutputHelper) =
let logger = xunitLogger output
let telegramClient = TelegramClientMock()

let performTestWithPreparation prepareAction testAction = Async.StartAsTask(async {
let sha256 = SHA256.Create()

let cacheDirectory = lazy TestFileCache.newCacheDirectory()

let setUpFileCache(totalLimitBytes: uint64) =
TestFileCache.setUpFileCache output sha256 cacheDirectory.Value totalLimitBytes

let performTestWithPreparation fileCache prepareAction testAction = Async.StartAsTask(async {
return! TestDataStorage.doWithDatabase(fun databaseSettings -> async {
do! prepareAction databaseSettings

use loggerFactory = new SerilogLoggerFactory(logger)
let logger = loggerFactory.CreateLogger<ContentController>()
use context = new EmulsionDbContext(databaseSettings.ContextOptions)
let controller = ContentController(logger, hostingSettings, telegramClient, None, context)
let controller = ContentController(logger, hostingSettings, telegramClient, fileCache, context)
return! testAction controller
})
})

let performTest = performTestWithPreparation(fun _ -> async.Return())
let performTestWithContent content = performTestWithPreparation (fun databaseOptions -> async {
let performTest = performTestWithPreparation None (fun _ -> async.Return())
let performTestWithContent fileCache content = performTestWithPreparation fileCache (fun databaseOptions -> async {
use context = new EmulsionDbContext(databaseOptions.ContextOptions)
do! DataStorage.addAsync context.TelegramContents content
return! Async.Ignore <| Async.AwaitTask(context.SaveChangesAsync())
})

interface IDisposable with
member _.Dispose() = sha256.Dispose()

[<Fact>]
member _.``ContentController returns BadRequest on hashId deserialization error``(): Task =
performTest (fun controller -> async {
Expand All @@ -57,7 +68,7 @@ type ContentControllerTests(output: ITestOutputHelper) =
})

[<Fact>]
member _.``ContentController returns NotFound if the content doesn't exist``(): Task =
member _.``ContentController returns NotFound if the content doesn't exist in the database``(): Task =
performTest (fun controller -> async {
let hashId = Proxy.encodeHashId hostingSettings.HashIdSalt 667L
let! result = Async.AwaitTask <| controller.Get hashId
Expand All @@ -76,16 +87,43 @@ type ContentControllerTests(output: ITestOutputHelper) =
FileId = "foobar"
}

performTestWithContent content (fun controller -> async {
performTestWithContent None content (fun controller -> async {
let hashId = Proxy.encodeHashId hostingSettings.HashIdSalt contentId
let! result = Async.AwaitTask <| controller.Get hashId
let redirect = Assert.IsType<RedirectResult> result
Assert.Equal(Uri $"https://t.me/{chatUserName}/{string messageId}", Uri redirect.Url)
})

[<Fact>]
member _.``ContentController returns NotFound if the content doesn't exist on the Telegram server``(): Task = task {
let contentId = 344L
let chatUserName = "MySuperExampleChat"
let messageId = 777L
let fileId = "foobar1"
let content = {
Id = contentId
ChatUserName = chatUserName
MessageId = messageId
FileId = fileId
}

telegramClient.SetResponse(fileId, None)

let cacheDir = TestFileCache.newCacheDirectory()
use fileCache = TestFileCache.setUpFileCache output sha256 cacheDir 1UL
do! performTestWithContent (Some fileCache) content (fun controller -> async {
let hashId = Proxy.encodeHashId hostingSettings.HashIdSalt contentId
let! result = Async.AwaitTask <| controller.Get hashId
Assert.IsType<NotFoundResult> result |> ignore
})
}

[<Fact>]
member _.``ContentController returns 404 if the cache reports that a file was not found``(): unit =
Assert.True false

[<Fact>]
member _.``ContentController returns a correct result``(): Task =
member _.``ContentController returns a downloaded file from cache``(): Task =
let contentId = 343L
let chatUserName = "MySuperExampleChat"
let messageId = 777L
Expand All @@ -104,9 +142,11 @@ type ContentControllerTests(output: ITestOutputHelper) =
}
telegramClient.SetResponse(fileId, Some testFileInfo)

performTestWithContent content (fun controller -> async {
performTestWithContent None content (fun controller -> async {
let hashId = Proxy.encodeHashId hostingSettings.HashIdSalt contentId
let! result = Async.AwaitTask <| controller.Get hashId
let redirect = Assert.IsType<RedirectResult> result
Assert.Equal(testLink, Uri redirect.Url)
})


0 comments on commit 107c4be

Please sign in to comment.