aboutsummaryrefslogtreecommitdiff
path: root/Timeline.Tests/Helpers/TestDatabase.cs
blob: f0c261801c03373fa357f129982e938e310fe7b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using System.Threading.Tasks;
using Timeline.Entities;
using Timeline.Migrations;
using Timeline.Models;
using Timeline.Services;
using Xunit;

namespace Timeline.Tests.Helpers
{
    public class TestDatabase : IAsyncLifetime
    {
        private readonly bool _createUser;

        public TestDatabase(bool createUser = true)
        {
            _createUser = createUser;
            Connection = new SqliteConnection("Data Source=:memory:;");
        }

        public async Task InitializeAsync()
        {
            await Connection.OpenAsync();

            using (var context = CreateContext())
            {
                await context.Database.EnsureCreatedAsync();
                context.JwtToken.Add(new JwtTokenEntity
                {
                    Key = JwtTokenGenerateHelper.GenerateKey()
                });
                await context.SaveChangesAsync();

                if (_createUser)
                {
                    var passwordService = new PasswordService();
                    var userService = new UserService(NullLogger<UserService>.Instance, context, passwordService, new Clock());

                    await userService.CreateUser(new User
                    {
                        Username = "admin",
                        Password = "adminpw",
                        Administrator = true,
                        Nickname = "administrator"
                    });

                    await userService.CreateUser(new User
                    {
                        Username = "user",
                        Password = "userpw",
                        Administrator = false,
                        Nickname = "imuser"
                    });
                }
            }
        }

        public async Task DisposeAsync()
        {
            await Connection.CloseAsync();
            await Connection.DisposeAsync();
        }

        public SqliteConnection Connection { get; }

        public DatabaseContext CreateContext()
        {
            var options = new DbContextOptionsBuilder<DatabaseContext>()
                .UseSqlite(Connection).Options;

            return new DatabaseContext(options);
        }
    }
}