summaryrefslogtreecommitdiff
path: root/integration-tests/util.py
blob: 9e9b19d67eb5173b61944ac318a8b10ea4066d23 (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
# Helpers for the integration tests.

from subprocess import check_call, Popen, PIPE, DEVNULL
import socket
from requests import post, get, auth
from time import sleep
from deepdiff import DeepDiff
import atexit
from pathlib import Path
import sys
import os

class EbicsDetails:
    def get_as_dict(self, with_url):
        ret = dict(
            hostID=self.host,
            partnerID=self.partner,
            userID=self.user
        )
        if with_url:
            ret.update(ebicsURL=self.service_url)
        return ret

    def __init__(self, service_url):
        self.service_url = service_url 
        self.host = "HOST01"
        self.partner = "PARTNER1"
        self.user = "USER1"
        self.version = "H004"

class BankingDetails:
    def __init__(
            self,
            bank_base_url,
            iban="GB33BUKB20201555555555",
            bic="BUKBGB22",
            label="savings",
            name="Oliver Smith"
        ):
        self.iban =  iban
        self.bic = bic
        self.label = label
        self.bank_base_url = bank_base_url
        self.name = name

class NexusDetails:
    def __init__(self, base_url):
        self.base_url = base_url
        self.username = "admin"
        self.password = "x"
        self.bank_connection = "my-ebics"
        self.bank_label = "local-savings" 
        self.auth = auth.HTTPBasicAuth(self.username, self.password)
        self.taler_facade_name = "taler-wire-gateway"

class LibeufinPersona:
    def __init__(self, banking_details, nexus_details, ebics_details):
        self.banking = banking_details
        self.nexus = nexus_details 
        self.ebics = ebics_details 

class CheckJsonField:
    def __init__(self, name, nested=None, optional=False):
        self.name = name
        self.nested = nested
        self.optional = optional

    def check(self, json):
        if self.name not in json and not self.optional:
            print(f"'{self.name}' not found in the JSON: {json}.")
            sys.exit(1)
        if self.nested:
            self.nested.check(json.get(self.name))

class CheckJsonTop:
    def __init__(self, *args):
        self.checks = args

    def check(self, json):
        for check in self.checks:
            check.check(json)
        return json


def assertJsonEqual(json1, json2):
    diff = DeepDiff(json1, json2, ignore_order=True, report_repetition=True)
    assert len(diff.keys()) == 0


def checkPort(port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        s.bind(("0.0.0.0", port))
        s.close()
    except:
        print(f"Port {port} is not available")
        print(sys.exc_info()[0])
        exit(77)

def kill(name, s):
    s.terminate()
    s.wait()

def makeNexusSuperuser():
    check_call([
        "../gradlew",
        "-q", "--console=plain",
        "-p", "..",
        "nexus:run",
        f"--args=superuser admin --password x",
    ])

def dropSandboxTables():
    check_call([
        "../gradlew",
        "-q", "--console=plain",
        "-p", "..",
        "sandbox:run",
        f"--args=reset-tables"
    ])


def dropNexusTables():
    check_call([
        "../gradlew",
        "-q", "--console=plain",
        "-p", "..",
        "nexus:run",
        f"--args=reset-tables"
    ])


def startSandbox():
    check_call(["../gradlew", "-q", "--console=plain", "-p", "..", "sandbox:assemble"])
    checkPort(5000)
    sandbox = Popen([
        "../gradlew",
        "-q",
        "-p",
        "..",
        "sandbox:run",
        "--console=plain",
        "--args=serve"],
        stdin=DEVNULL,
        stdout=open("sandbox-stdout.log", "w"),
        stderr=open("sandbox-stderr.log", "w")
    )
    atexit.register(lambda: kill("sandbox", sandbox))
    for i in range(10):
        try:
            get("http://localhost:5000/")
        except:
            if i == 9:
                stdout, stderr = sandbox.communicate()
                print("Sandbox timed out")
                print("{}\n{}".format(stdout.decode(), stderr.decode()))
                exit(77)
            sleep(2)
            continue
        break


def startNexus():
    check_call(
        ["../gradlew", "-q", "--console=plain", "-p", "..", "nexus:assemble",]
    )
    checkPort(5001)
    nexus = Popen([
        "../gradlew",
        "-q",
        "-p",
        "..",
        "nexus:run",
        "--console=plain",
        "--args=serve")],
        stdin=DEVNULL,
        stdout=open("nexus-stdout.log", "w"),
        stderr=open("nexus-stderr.log", "w")
    )
    atexit.register(lambda: kill("nexus", nexus))
    for i in range(80):
        try:
            get("http://localhost:5001/")
        except:
            if i == 79:
                nexus.terminate()
                print("Nexus timed out")
                exit(77)
            sleep(1)
            continue
        break
    return nexus

def assertResponse(r, acceptedResponses=[200]):
    def http_trace(r):
        request = f"{r.request.method} {r.request.url}\n{r.request.body.decode('utf-8')}"
        response = f"{r.status_code} {r.reason}\n{r.text}"
        return f"(the following communication failed)\n\n{request}\n\n{response}"
    assert r.status_code in acceptedResponses, http_trace(r)
    return r