View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2013-2025 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.jcabi.github.mock;
6   
7   import java.io.IOException;
8   import java.util.concurrent.ExecutionException;
9   import java.util.concurrent.ExecutorService;
10  import java.util.concurrent.Executors;
11  import java.util.concurrent.Future;
12  import java.util.concurrent.TimeUnit;
13  import java.util.concurrent.TimeoutException;
14  import org.hamcrest.MatcherAssert;
15  import org.hamcrest.Matchers;
16  import org.junit.jupiter.api.Test;
17  import org.xembly.Directives;
18  
19  /**
20   * Test case for {@link MkStorage}.
21   * @since 0.5
22   * @checkstyle MultipleStringLiteralsCheck (200 lines)
23   */
24  @SuppressWarnings("PMD.DoNotUseThreads")
25  final class MkStorageTest {
26  
27      @Test
28      void readsAndWrites() throws IOException {
29          final MkStorage storage = new MkStorage.InFile();
30          storage.lock();
31          try {
32              storage.apply(
33                  new Directives().xpath("/github").add("test")
34                      .set("hello, world")
35              );
36              MatcherAssert.assertThat(
37                  "String does not end with expected value",
38                  storage.xml().xpath("/github/test/text()").get(0),
39                  Matchers.endsWith(", world")
40              );
41          } finally {
42              storage.unlock();
43          }
44      }
45  
46      @Test
47      @SuppressWarnings("PMD.CloseResource")
48      void locksAndUnlocks() throws IOException, InterruptedException, ExecutionException {
49          final MkStorage storage = new MkStorage.Synced(new MkStorage.InFile());
50          final ExecutorService executor = Executors.newSingleThreadExecutor();
51          final Runnable second = () -> storage.lock();
52          storage.lock();
53          Future<?> future = executor.submit(second);
54          try {
55              future.get(1L, TimeUnit.SECONDS);
56              MatcherAssert.assertThat(
57                  "Timeout did not occur",
58                  false,
59                  Matchers.is(true)
60              );
61          } catch (final TimeoutException ex) {
62              future.cancel(true);
63          } finally {
64              storage.unlock();
65          }
66          future = executor.submit(second);
67          try {
68              future.get(1L, TimeUnit.SECONDS);
69          } catch (final TimeoutException ex) {
70              MatcherAssert.assertThat(
71                  "Timeout occurred unexpectedly",
72                  false,
73                  Matchers.is(true)
74              );
75              future.cancel(true);
76          }
77          executor.shutdown();
78      }
79  
80  }