summaryrefslogtreecommitdiff
path: root/server/tests/common/mod.rs
blob: 62795defbd9869354ee128ad7ef03bcab7f5382c (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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use reqwest::Client;
use std::collections::HashMap;
use std::env;
use std::fs::Permissions;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use test_context::AsyncTestContext;
use testdir::testdir;
use tokio::fs;
use tokio::process::Command;

use eyeballs_api::api_model;

pub struct DockerComposeContext {
    docker_dir: PathBuf,
    test_dir: PathBuf,
    url: String,
    remote_git: String,
    remote_git_key: PathBuf,
}

async fn run(cmd: &mut Command, name: &str) -> Result<(), anyhow::Error> {
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped());
    let child = cmd.spawn()?;
    let output = child.wait_with_output().await?;

    if output.status.success() {
        Ok(())
    } else {
        Err(anyhow::Error::msg(format!(
            "{name} failed with exitcode: {}\n{:?}\n{}",
            output.status,
            cmd.as_std().get_args(),
            std::str::from_utf8(output.stderr.as_slice()).unwrap_or(""),
        )))
    }
}

async fn setup_ssh_file(
    base: impl AsRef<Path>,
    host: &str,
    port: &str,
    identity_file: impl AsRef<Path>,
) -> Result<(), anyhow::Error> {
    let full_identity_file = identity_file.as_ref().canonicalize()?;

    fs::write(
        base.as_ref().join("ssh_config"),
        format!(
            "Host {host}
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null
    UpdateHostKeys no
    Port {port}
    User git
    IdentityFile {}
",
            full_identity_file.to_str().unwrap(),
        ),
    )
    .await?;

    Ok(())
}

async fn git_clone(base: impl AsRef<Path>, remote: &str) -> Result<(), anyhow::Error> {
    let mut cmd = Command::new("git");
    cmd.arg("clone");
    cmd.arg(remote);

    cmd.env("GIT_SSH_COMMAND", "ssh -F ssh_config");
    cmd.current_dir(base);

    run(&mut cmd, "git clone").await
}

async fn git_cmd(base: impl AsRef<Path>, args: &[&str]) -> Result<(), anyhow::Error> {
    let mut cmd = Command::new("git");
    cmd.arg("-C");
    cmd.arg("fake");
    for arg in args {
        cmd.arg(arg);
    }

    cmd.env("GIT_SSH_COMMAND", "ssh -F ../ssh_config");
    cmd.current_dir(base);

    run(&mut cmd, "git command").await
}

const STRINGS_GRD: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<grit current_release="1" latest_public_release="0">
  <outputs>
    <output filename="values/strings.xml" type="android" lang="en" />
    <output filename="values-en-rGB/strings.xml" type="android" lang="en-GB" />
    <output filename="values-sv/strings.xml" type="android" lang="sv" />
  </outputs>
  <translations>
    <file path="translations/strings_en_gb.xlf" lang="en-GB" />
    <file path="translations/strings_sv.xlf" lang="sv" />
  </translations>
  <release allow_pseudo="false" seq="1">
    <messages fallback_to_english="true">
      <part file="extra.grdp" />
      <message desc="Description" name="MAIN_STRING">
        Main test string
      </message>
    </messages>
  </release>
</grit>"#;
const EXTRA_GRDP: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<grit-part>
  <message desc="Some description" name="EXTRA_STRING">
    Extra string, gray
  </message>
</grit-part>"#;
const STRINGS_EN_GB_XLF: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
<file datatype="xml" source-language="en-US" original="strings.grd" target-language="en-gb">
<body>
<trans-unit id="759906012366268261">
  <source>Main test string</source>
  <target>Main test string</target>
  <note>MAIN_STRING
        Description
  </note>
</trans-unit>
<trans-unit id="3195503415604121324">
  <source>Extra string, gray</source>
  <target>Extra string, grey</target>
  <note>EXTRA_STRING
        Some description
  </note>
</trans-unit>
</body>
</file>
</xliff>"#;
pub const STRINGS_SV_XLF: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
<file datatype="xml" source-language="en-US" original="strings.grd" target-language="sv">
<body>
<trans-unit id="759906012366268261">
  <source>Main test string</source>
  <target>Primära teststrängen</target>
  <note>MAIN_STRING
        Description
  </note>
</trans-unit>
<trans-unit id="3195503415604121324">
  <source>Extra string, gray</source>
  <target>Extra sträng, grå</target>
  <note>EXTRA_STRING
        Some description
  </note>
</trans-unit>
</body>
</file>
</xliff>"#;

impl DockerComposeContext {
    pub fn url(&self) -> &str {
        self.url.as_str()
    }

    pub fn remote_git(&self) -> &str {
        self.remote_git.as_str()
    }

    pub fn remote_git_key(&self) -> &Path {
        self.remote_git_key.as_ref()
    }

    pub async fn setup_ssh_key(&self, base: &str, key: &str) -> Result<(), anyhow::Error> {
        let base_dir = self.test_dir.join(base);
        fs::create_dir(&base_dir).await?;
        let identity_file = base_dir.join("id_key");
        fs::write(&identity_file, key).await?;
        let permissions = Permissions::from_mode(0o600);
        fs::set_permissions(&identity_file, permissions).await?;
        setup_ssh_file(&base_dir, "localhost", "10022", &identity_file).await?;
        Ok(())
    }

    pub async fn git_clone(&self, base: &str) -> Result<(), anyhow::Error> {
        git_clone(self.test_dir.join(base), "ssh://localhost/srv/git/fake").await
    }

    pub fn git_dir(&self, base: &str) -> PathBuf {
        self.test_dir.join(base).join("fake")
    }

    pub async fn git_cmd(&self, base: &str, args: &[&str]) -> Result<(), anyhow::Error> {
        git_cmd(self.test_dir.join(base), args).await
    }
}

impl AsyncTestContext for DockerComposeContext {
    async fn setup() -> DockerComposeContext {
        let cargo_dir = match env::var("CARGO_MANIFEST_DIR") {
            Ok(pathstr) => PathBuf::from(pathstr),
            Err(e) => panic!("CARGO_MANIFEST_DIR not set: {e:?}"),
        };
        let docker_dir = cargo_dir.join("../docker/integration_test");
        let remote_git_key = docker_dir.join("web/gitkey");
        let ctx = DockerComposeContext {
            docker_dir: docker_dir,
            test_dir: testdir!(),
            url: "http://localhost:18000".to_string(),
            remote_git: "ssh://git@remote_git/srv/git/fake.git".to_string(),
            remote_git_key,
        };

        // Build githook, needs to use musl to work with the rockstorm/git-server image
        {
            let mut cmd = Command::new("cargo");
            cmd.arg("build");
            cmd.arg("--target=x86_64-unknown-linux-musl");
            cmd.arg("--package");
            cmd.arg("eyeballs-githook");

            cmd.current_dir(cargo_dir);

            run(&mut cmd, "cargo build eyeballs-githook")
                .await
                .expect("cargo build");
        }

        // Start docker compose up
        {
            let mut cmd = Command::new("docker");
            cmd.arg("compose");
            cmd.arg("up");
            // Build images before starting containers
            cmd.arg("--build");
            // Recreate anonymous volumes instead of retrieving data from the previous containers
            cmd.arg("--renew-anon-volumes");
            // Detached mode: Run containers in the background
            cmd.arg("--detach");
            // Wait for services to be running|healthy. Implies detached mode
            cmd.arg("--wait");
            // Assume "yes" as answer to all prompts and run non-interactively
            cmd.arg("-y");

            cmd.current_dir(&ctx.docker_dir);

            run(&mut cmd, "docker compose up")
                .await
                .expect("docker compose up");
        }

        let mod_path = ctx.test_dir.join("mod");
        fs::create_dir(&mod_path).await.expect("create mod");
        setup_ssh_file(
            &mod_path,
            "localhost",
            "12222",
            ctx.docker_dir.join("web/gitkey"),
        )
        .await
        .expect("ssh_config for remote_git");

        // Setup fake remote repo
        {
            let mut cmd = Command::new("ssh");
            cmd.arg("-F");
            cmd.arg("ssh_config");
            cmd.arg("localhost");
            cmd.arg("mkdir /srv/git/fake.git");

            cmd.current_dir(&mod_path);

            run(&mut cmd, "mkdir").await.expect("ssh mkdir");
        }
        {
            let mut cmd = Command::new("ssh");
            cmd.arg("-F");
            cmd.arg("ssh_config");
            cmd.arg("localhost");
            cmd.arg("git-init --bare --initial-branch=main /srv/git/fake.git");

            cmd.current_dir(&mod_path);

            run(&mut cmd, "git-init").await.expect("ssh git-init");
        }

        git_clone(&mod_path, "ssh://localhost/srv/git/fake.git")
            .await
            .expect("git clone");

        fs::write(mod_path.join("fake/README"), "Hello fellow fake person!")
            .await
            .expect("Write README");

        git_cmd(&mod_path, &["add", "README"])
            .await
            .expect("git add README");
        git_cmd(&mod_path, &["commit", "-m", "Initial commit"])
            .await
            .expect("git commit README");
        git_cmd(&mod_path, &["push", "origin", "HEAD:main"])
            .await
            .expect("git push");

        fs::write(mod_path.join("fake/strings.grd"), STRINGS_GRD)
            .await
            .expect("Write strings.grd");
        fs::write(mod_path.join("fake/extra.grdp"), EXTRA_GRDP)
            .await
            .expect("Write extra.grdp");
        fs::create_dir(mod_path.join("fake/translations"))
            .await
            .expect("mkdir translations");
        fs::write(
            mod_path.join("fake/translations/strings_en_gb.xlf"),
            STRINGS_EN_GB_XLF,
        )
        .await
        .expect("Write strings_en_gb.xlf");
        fs::write(
            mod_path.join("fake/translations/strings_sv.xlf"),
            STRINGS_SV_XLF,
        )
        .await
        .expect("Write strings_sv");

        git_cmd(
            &mod_path,
            &[
                "add",
                "strings.grd",
                "extra.grdp",
                "translations/strings_en_gb.xlf",
                "translations/strings_sv.xlf",
            ],
        )
        .await
        .expect("git add");
        git_cmd(&mod_path, &["commit", "-m", "Add strings"])
            .await
            .expect("git commit");
        git_cmd(&mod_path, &["push", "origin", "HEAD:main"])
            .await
            .expect("git push");

        ctx
    }

    async fn teardown(self) {
        let mut cmd = Command::new("docker");
        cmd.arg("compose");
        cmd.arg("down");
        // Remove named volumes declared in the "volumes" section of the Compose file and anonymous
        // volumes attached to containers
        cmd.arg("--volumes");

        cmd.current_dir(&self.docker_dir);

        run(&mut cmd, "docker compose down")
            .await
            .expect("docker compose down");
    }
}

pub fn create_client() -> Result<Client, anyhow::Error> {
    Ok(Client::builder().cookie_store(true).build()?)
}

pub async fn login(
    ctx: &mut DockerComposeContext,
    client: &mut Client,
    username: &str,
    password: &str,
) -> Result<(), anyhow::Error> {
    let mut params = HashMap::new();
    params.insert("username", username);
    params.insert("password", password);
    let result = client
        .post(format!("{}/api/v1/login", ctx.url()))
        .form(&params)
        .send()
        .await?;
    if result.status().is_success() {
        Ok(())
    } else {
        let content = result.text().await?;
        Err(anyhow::Error::msg(content))
    }
}

pub async fn user_key_add(
    ctx: &mut DockerComposeContext,
    client: &mut Client,
    kind: &str,
    data: &str,
) -> Result<api_model::UserKey, anyhow::Error> {
    let data = api_model::UserKeyData {
        kind,
        data: data,
        comment: None,
    };
    let result = client
        .post(format!("{}/api/v1/user/keys/add", ctx.url()))
        .json(&data)
        .send()
        .await?;
    if result.status().is_success() {
        let project = result.json::<api_model::UserKey>().await?;
        Ok(project)
    } else {
        let content = result.text().await?;
        Err(anyhow::Error::msg(content))
    }
}

pub async fn create_project(
    ctx: &mut DockerComposeContext,
    client: &mut Client,
    projectid: &str,
    remote: &str,
    remote_key: &Path,
) -> Result<api_model::Project, anyhow::Error> {
    let remote_key_data = fs::read_to_string(remote_key).await?;
    let data = api_model::ProjectData {
        title: None,
        description: None,
        remote: Some(remote),
        remote_key: Some(remote_key_data),
        main_branch: None,
    };
    let result = client
        .post(format!("{}/api/v1/project/{projectid}/new", ctx.url()))
        .json(&data)
        .send()
        .await?;
    if result.status().is_success() {
        let project = result.json::<api_model::Project>().await?;
        Ok(project)
    } else {
        let content = result.text().await?;
        Err(anyhow::Error::msg(content))
    }
}

pub async fn list_reviews(
    ctx: &mut DockerComposeContext,
    client: &mut Client,
    projectid: &str,
) -> Result<api_model::Reviews, anyhow::Error> {
    let result = client
        .get(format!("{}/api/v1/project/{projectid}/reviews", ctx.url()))
        .send()
        .await?;
    if result.status().is_success() {
        let project = result.json::<api_model::Reviews>().await?;
        Ok(project)
    } else {
        let content = result.text().await?;
        Err(anyhow::Error::msg(content))
    }
}

pub async fn create_translation_review(
    ctx: &mut DockerComposeContext,
    client: &mut Client,
    projectid: &str,
) -> Result<api_model::TranslationReview, anyhow::Error> {
    let data = api_model::TranslationReviewData {
        title: "Test".to_string(),
        description: "Some test".to_string(),
        base: None,
    };
    let result = client
        .post(format!("{}/api/v1/translation/{projectid}/new", ctx.url()))
        .json(&data)
        .send()
        .await?;
    if result.status().is_success() {
        let review = result.json::<api_model::TranslationReview>().await?;
        Ok(review)
    } else {
        let content = result.text().await?;
        Err(anyhow::Error::msg(content))
    }
}

pub async fn list_translation_strings(
    ctx: &mut DockerComposeContext,
    client: &mut Client,
    translation_reviewid: u64,
) -> Result<api_model::LocalizationStrings, anyhow::Error> {
    let result = client
        .get(format!(
            "{}/api/v1/translation/{translation_reviewid}/strings",
            ctx.url()
        ))
        .send()
        .await?;
    if result.status().is_success() {
        let strings = result.json::<api_model::LocalizationStrings>().await?;
        Ok(strings)
    } else {
        let content = result.text().await?;
        Err(anyhow::Error::msg(content))
    }
}