summaryrefslogtreecommitdiff
path: root/bank/src/test/kotlin/helpers.kt
blob: 3711bd2c452fafe55d74e85e82692b534b3a08f0 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import io.ktor.http.*
import io.ktor.client.statement.*
import io.ktor.client.request.*
import io.ktor.server.testing.*
import kotlinx.coroutines.*
import kotlinx.serialization.json.*
import net.taler.wallet.crypto.Base32Crockford
import net.taler.common.errorcodes.TalerErrorCode
import kotlin.test.*
import tech.libeufin.bank.*
import java.io.ByteArrayOutputStream
import java.util.zip.DeflaterOutputStream
import tech.libeufin.util.CryptoUtil
import tech.libeufin.util.*

/* ----- Setup ----- */

val customerMerchant = Customer(
    login = "merchant",
    passwordHash = CryptoUtil.hashpw("merchant-password"),
    name = "Merchant",
    phone = "+00",
    email = "merchant@libeufin-bank.com",
    cashoutPayto = "payto://external-IBAN",
    cashoutCurrency = "KUDOS"
)
val bankAccountMerchant = BankAccount(
    internalPaytoUri = IbanPayTo("payto://iban/MERCHANT-IBAN-XYZ"),
    lastNexusFetchRowId = 1L,
    owningCustomerId = 1L,
    hasDebt = false,
    maxDebt = TalerAmount(10, 1, "KUDOS"),
)
val customerExchange = Customer(
    login = "exchange",
    passwordHash = CryptoUtil.hashpw("exchange-password"),
    name = "Exchange",
    phone = "+00",
    email = "exchange@libeufin-bank.com",
    cashoutPayto = "payto://external-IBAN",
    cashoutCurrency = "KUDOS"
)
val bankAccountExchange = BankAccount(
    internalPaytoUri = IbanPayTo("payto://iban/EXCHANGE-IBAN-XYZ"),
    lastNexusFetchRowId = 1L,
    owningCustomerId = 2L,
    hasDebt = false,
    maxDebt = TalerAmount(10, 1, "KUDOS"),
    isTalerExchange = true
)

fun bankSetup(
    conf: String = "test.conf",    
    lambda: suspend ApplicationTestBuilder.(Database) -> Unit
) {
    setup(conf) { db, ctx -> 
        // Creating the exchange and merchant accounts first.
        assertNotNull(db.customerCreate(customerMerchant))
        assertNotNull(db.bankAccountCreate(bankAccountMerchant))
        assertNotNull(db.customerCreate(customerExchange))
        assertNotNull(db.bankAccountCreate(bankAccountExchange))
        // Create admin account
        assertNotNull(db.customerCreate(
            Customer(
                "admin",
                CryptoUtil.hashpw("admin-password"),
                "CFO"
            )
        ))
        assert(maybeCreateAdminAccount(db, ctx))
        testApplication {
            application {
                corebankWebApp(db, ctx)
            }
            lambda(db)
        }
    }
}

fun setup(
    conf: String = "test.conf",
    lambda: suspend (Database, BankApplicationContext) -> Unit
){
    val config = talerConfig("conf/$conf")
    val dbCfg = config.loadDbConfig()
    resetDatabaseTables(dbCfg, "libeufin-bank")
    initializeDatabaseTables(dbCfg, "libeufin-bank")
    val ctx = config.loadBankApplicationContext()
    Database(dbCfg.dbConnStr, ctx.currency).use {
        runBlocking {
            lambda(it, ctx)
        }
    }
}

fun setupDb(lambda: suspend (Database) -> Unit) {
    setup() { db, _ -> lambda(db) }
}

/* ----- Assert ----- */

fun HttpResponse.assertStatus(status: HttpStatusCode): HttpResponse {
    assertEquals(status, this.status);
    return this
}
fun HttpResponse.assertOk(): HttpResponse = assertStatus(HttpStatusCode.OK)
fun HttpResponse.assertCreated(): HttpResponse = assertStatus(HttpStatusCode.Created)
fun HttpResponse.assertNoContent(): HttpResponse = assertStatus(HttpStatusCode.NoContent)
fun HttpResponse.assertNotFound(): HttpResponse = assertStatus(HttpStatusCode.NotFound)
fun HttpResponse.assertUnauthorized(): HttpResponse = assertStatus(HttpStatusCode.Unauthorized)
fun HttpResponse.assertConflict(): HttpResponse = assertStatus(HttpStatusCode.Conflict)
fun HttpResponse.assertBadRequest(): HttpResponse = assertStatus(HttpStatusCode.BadRequest)


suspend fun HttpResponse.assertErr(code: TalerErrorCode): HttpResponse {
    val err = Json.decodeFromString<TalerError>(bodyAsText())
    assertEquals(code.code, err.code)
    return this
}



fun BankTransactionResult.assertSuccess() {
    assertEquals(BankTransactionResult.SUCCESS, this)
}

suspend fun assertTime(min: Int, max: Int, lambda: suspend () -> Unit) {
    val start = System.currentTimeMillis()
    lambda()
    val end = System.currentTimeMillis()
    val time = end - start
    assert(time >= min) { "Expected to last at least $min ms, lasted $time" }
    assert(time <= max) { "Expected to last at most $max ms, lasted $time" }
}

fun assertException(msg: String, lambda: () -> Unit) {
    try {
        lambda()
        throw Exception("Expected failure")
    } catch (e: Exception) {
        assertEquals(msg, e.message)
    }
}

/* ----- Body helper ----- */

inline fun <reified B> HttpRequestBuilder.jsonBody(b: B, deflate: Boolean = false) {
    val json = Json.encodeToString(kotlinx.serialization.serializer<B>(), b);
    contentType(ContentType.Application.Json)
    if (deflate) {
        headers.set("Content-Encoding", "deflate")
        val bos = ByteArrayOutputStream()
        val ios = DeflaterOutputStream(bos)
        ios.write(json.toByteArray())
        ios.finish()
        setBody(bos.toByteArray())
    } else {
        setBody(json)
    }
}

/* ----- Json DSL ----- */

inline fun json(from: JsonObject = JsonObject(emptyMap()), builderAction: JsonBuilder.() -> Unit): JsonObject {
    val builder = JsonBuilder(from)
    builder.apply(builderAction)
    return JsonObject(builder.content)
}

class JsonBuilder(from: JsonObject) {
    val content: MutableMap<String, JsonElement> = from.toMutableMap()

    infix inline fun <reified T> String.to(v: T) {
        val json = Json.encodeToJsonElement(kotlinx.serialization.serializer<T>(), v);
        content.put(this, json)
    }
}

/* ----- Random data generation ----- */

fun randBase32Crockford(lenght: Int): String {
    val bytes = ByteArray(lenght)
    kotlin.random.Random.nextBytes(bytes)
    return Base32Crockford.encode(bytes)
}

fun randHashCode(): HashCode = HashCode(randBase32Crockford(64))
fun randShortHashCode(): ShortHashCode = ShortHashCode(randBase32Crockford(32))
fun randEddsaPublicKey(): EddsaPublicKey = EddsaPublicKey(randBase32Crockford(32))