summaryrefslogtreecommitdiff
path: root/nexus/src/test/kotlin/DatabaseTest.kt
blob: ec9bfae36d497c458002f58fc2a2b8ffb89ace16 (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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import kotlinx.coroutines.runBlocking
import org.junit.Test
import tech.libeufin.nexus.*
import java.time.Instant
import kotlin.random.Random
import kotlin.test.*
import kotlin.test.assertEquals


class OutgoingPaymentsTest {
    @Test
    fun register() {
        val db = prepDb(TalerConfig(NEXUS_CONFIG_SOURCE))
        runBlocking {
            // With reconciling
            genOutPay("paid by nexus", "first").run {
                assertEquals(
                    PaymentInitiationOutcome.SUCCESS,
                    db.initiatedPaymentCreate(genInitPay("waiting for reconciliation", "first"))
                )
                assertEquals(
                    OutgoingRegistrationResult.New(true),
                    db.registerOutgoing(this)
                )
                assertEquals(
                    OutgoingRegistrationResult.AlreadyRegistered,
                    db.registerOutgoing(this)
                )
            }
            // Without reconciling
            genOutPay("not paid by nexus", "second").run {
                assertEquals(
                    OutgoingRegistrationResult.New(false),
                    db.registerOutgoing(this)
                )
                assertEquals(
                    OutgoingRegistrationResult.AlreadyRegistered,
                    db.registerOutgoing(this)
                )
            }
        }
    }
}

class IncomingPaymentsTest {
    // Tests creating and bouncing incoming payments in one DB transaction.
    @Test
    fun bounce() {
        val db = prepDb(TalerConfig(NEXUS_CONFIG_SOURCE))
        runBlocking {
            // creating and bouncing one incoming transaction.
            val payment = genInPay("incoming and bounced")
            assertTrue(db.registerMalformedIncoming(
                payment,
                "UID",
                TalerAmount(2, 53000000, "KUDOS"),
                "Bounce UID",
                Instant.now()
            ))
            assertFalse(db.registerMalformedIncoming(
                payment,
                "UID",
                TalerAmount(2, 53000000, "KUDOS"),
                "Bounce UID",
                Instant.now()
            ))
            db.runConn {
                // Checking one incoming got created
                val checkIncoming = it.prepareStatement("""
                    SELECT (amount).val as amount_value, (amount).frac as amount_frac 
                    FROM incoming_transactions WHERE incoming_transaction_id = 1
                """).executeQuery()
                assertTrue(checkIncoming.next())
                assertEquals(payment.amount.value, checkIncoming.getLong("amount_value"))
                assertEquals(payment.amount.fraction, checkIncoming.getInt("amount_frac"))
                // Checking the bounced table got its row.
                val checkBounced = it.prepareStatement("""
                    SELECT 1 FROM bounced_transactions 
                    WHERE incoming_transaction_id = 1 AND initiated_outgoing_transaction_id = 1
                """).executeQuery()
                assertTrue(checkBounced.next())
                // check the related initiated payment exists.
                val checkInitiated = it.prepareStatement("""
                    SELECT
                        (amount).val as amount_value
                        ,(amount).frac as amount_frac
                    FROM initiated_outgoing_transactions
                    WHERE initiated_outgoing_transaction_id = 1
                """).executeQuery()
                assertTrue(checkInitiated.next())
                assertEquals(
                    53000000,
                    checkInitiated.getInt("amount_frac")
                )
                assertEquals(
                    2,
                    checkInitiated.getInt("amount_value")
                )
            }
        }
    }

    // Tests the creation of a talerable incoming payment.
    @Test
    fun talerable() {
        val db = prepDb(TalerConfig(NEXUS_CONFIG_SOURCE))
        val reservePub = ByteArray(32)
        Random.nextBytes(reservePub)

        runBlocking {
            val inc = genInPay("reserve-pub")
            // Checking the reserve is not found.
            assertFalse(db.isReservePubFound(reservePub))
            assertTrue(db.registerTalerableIncoming(inc, reservePub))
            // Checking the reserve is not found.
            assertTrue(db.isReservePubFound(reservePub))
            assertFalse(db.registerTalerableIncoming(inc, reservePub))
        }
    }
}
class PaymentInitiationsTest {

    // Testing the insertion of the failure message.
    @Test
    fun setFailureMessage() {
        val db = prepDb(TalerConfig(NEXUS_CONFIG_SOURCE))
        runBlocking {
            assertEquals(
                db.initiatedPaymentCreate(genInitPay("not submitted, has row ID == 1")),
                PaymentInitiationOutcome.SUCCESS
            )
            assertFalse(db.initiatedPaymentSetFailureMessage(3, "3 not existing"))
            assertTrue(db.initiatedPaymentSetFailureMessage(1, "expired"))
            // Checking the value from the database.
            db.runConn { conn ->
                val idOne = conn.execSQLQuery("""
                    SELECT failure_message
                      FROM initiated_outgoing_transactions
                      WHERE initiated_outgoing_transaction_id = 1;
                """.trimIndent())
                assertTrue(idOne.next())
                val maybeMessage = idOne.getString("failure_message")
                assertEquals("expired", maybeMessage)
            }
        }
    }
    // Tests the flagging of payments as submitted.
    @Test
    fun paymentInitiationSetAsSubmitted() {
        val db = prepDb(TalerConfig(NEXUS_CONFIG_SOURCE))
        val getRowOne = """
                    SELECT submitted
                      FROM initiated_outgoing_transactions
                      WHERE initiated_outgoing_transaction_id=1
                """
        runBlocking {
            // Creating the record first.  Defaults to submitted == false.
            assertEquals(
                PaymentInitiationOutcome.SUCCESS,
                db.initiatedPaymentCreate(genInitPay("not submitted, has row ID == 1")),
            )
            // Asserting on the false default submitted state.
            db.runConn { conn ->
                val isSubmitted = conn.execSQLQuery(getRowOne)
                assertTrue(isSubmitted.next())
                assertEquals("unsubmitted", isSubmitted.getString("submitted"))
            }
            // Switching the submitted state to success.
            assertTrue(db.initiatedPaymentSetSubmittedState(1, DatabaseSubmissionState.success))
            // Asserting on the submitted state being TRUE now.
            db.runConn { conn ->
                val isSubmitted = conn.execSQLQuery(getRowOne)
                assertTrue(isSubmitted.next())
                assertEquals("success", isSubmitted.getString("submitted"))
            }
        }
    }

    // Tests creation, unique constraint violation handling, and
    // retrieving only one non-submitted payment.
    @Test
    fun paymentInitiation() {
        val db = prepDb(TalerConfig(NEXUS_CONFIG_SOURCE))
        runBlocking {
            val beEmpty = db.initiatedPaymentsSubmittableGet("KUDOS") // expect no records.
            assertEquals(beEmpty.size, 0)
        }
        val initPay = InitiatedPayment(
            amount = TalerAmount(44, 0, "KUDOS"),
            creditPaytoUri = "payto://iban/TEST-IBAN?receiver-name=Test",
            wireTransferSubject = "test",
            requestUid = "unique",
            initiationTime = Instant.now()
        )
        runBlocking {
            assertNull(db.initiatedPaymentGetFromUid("unique"))
            assertEquals(db.initiatedPaymentCreate(initPay), PaymentInitiationOutcome.SUCCESS)
            assertEquals(db.initiatedPaymentCreate(initPay), PaymentInitiationOutcome.UNIQUE_CONSTRAINT_VIOLATION)
            val haveOne = db.initiatedPaymentsSubmittableGet("KUDOS")
            assertTrue("Size ${haveOne.size} instead of 1") {
                haveOne.size == 1
                        && haveOne.containsKey(1)
                        && haveOne[1]?.requestUid == "unique"
            }
            assertTrue(db.initiatedPaymentSetSubmittedState(1, DatabaseSubmissionState.success))
            assertNotNull(db.initiatedPaymentGetFromUid("unique"))
        }
    }

    /**
     * The SQL that gets submittable payments checks multiple
     * statuses from them.  Checking it here.
     */
    @Test
    fun submittablePayments() {
        val db = prepDb(TalerConfig(NEXUS_CONFIG_SOURCE))
        runBlocking {
            val beEmpty = db.initiatedPaymentsSubmittableGet("KUDOS")
            assertEquals(0, beEmpty.size)
            assertEquals(
                db.initiatedPaymentCreate(genInitPay(requestUid = "first")),
                PaymentInitiationOutcome.SUCCESS
            )
            assertEquals(
                db.initiatedPaymentCreate(genInitPay(requestUid = "second")),
                PaymentInitiationOutcome.SUCCESS
            )
            assertEquals(
                db.initiatedPaymentCreate(genInitPay(requestUid = "third")),
                PaymentInitiationOutcome.SUCCESS
            )

            // Setting the first as "transient_failure", must be found.
            assertTrue(db.initiatedPaymentSetSubmittedState(
                1, DatabaseSubmissionState.transient_failure
            ))
            // Setting the second as "success", must not be found.
            assertTrue(db.initiatedPaymentSetSubmittedState(
                2, DatabaseSubmissionState.success
            ))
            val expectTwo = db.initiatedPaymentsSubmittableGet("KUDOS")
            // the third initiation keeps the default "unsubmitted"
            // state, must be found.  Total 2.
            assertEquals(2, expectTwo.size)
        }
    }

    // Tests how the fetch method gets the list of
    // multiple unsubmitted payment initiations.
    @Test
    fun paymentInitiationsMultiple() {
        val db = prepDb(TalerConfig(NEXUS_CONFIG_SOURCE))
        runBlocking {
            assertEquals(db.initiatedPaymentCreate(genInitPay("#1", "unique1")), PaymentInitiationOutcome.SUCCESS)
            assertEquals(db.initiatedPaymentCreate(genInitPay("#2", "unique2")), PaymentInitiationOutcome.SUCCESS)
            assertEquals(db.initiatedPaymentCreate(genInitPay("#3", "unique3")), PaymentInitiationOutcome.SUCCESS)
            assertEquals(db.initiatedPaymentCreate(genInitPay("#4", "unique4")), PaymentInitiationOutcome.SUCCESS)

            // Marking one as submitted, hence not expecting it in the results.
            db.runConn { conn ->
                conn.execSQLUpdate("""
                    UPDATE initiated_outgoing_transactions
                      SET submitted='success'
                      WHERE initiated_outgoing_transaction_id=3;
                """.trimIndent())
            }

            // Expecting all the payments BUT the #3 in the result.
            db.initiatedPaymentsSubmittableGet("KUDOS").apply {
                assertEquals(3, this.size)
                assertEquals("#1", this[1]?.wireTransferSubject)
                assertEquals("#2", this[2]?.wireTransferSubject)
                assertEquals("#4", this[4]?.wireTransferSubject)
            }
        }
    }
}