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 package com.jcabi.github.mock;
31
32 import java.io.IOException;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.Future;
36 import java.util.concurrent.TimeUnit;
37 import java.util.concurrent.TimeoutException;
38 import org.hamcrest.MatcherAssert;
39 import org.hamcrest.Matchers;
40 import org.junit.Test;
41 import org.xembly.Directives;
42
43
44
45
46
47
48
49 @SuppressWarnings("PMD.DoNotUseThreads")
50 public final class MkStorageTest {
51
52
53
54
55
56 @Test
57 public void readsAndWrites() throws Exception {
58 final MkStorage storage = new MkStorage.InFile();
59 storage.lock();
60 try {
61 storage.apply(
62 new Directives().xpath("/github").add("test")
63 .set("hello, world")
64 );
65 MatcherAssert.assertThat(
66 storage.xml().xpath("/github/test/text()").get(0),
67 Matchers.endsWith(", world")
68 );
69 } finally {
70 storage.unlock();
71 }
72 }
73
74
75
76
77
78 @Test
79 public void locksAndUnlocks() throws Exception {
80 final MkStorage storage = new MkStorage.Synced(new MkStorage.InFile());
81 final ExecutorService executor = Executors.newSingleThreadExecutor();
82 final Runnable second = new Runnable() {
83 @Override
84 public void run() {
85 try {
86 storage.lock();
87 } catch (final IOException ex) {
88 throw new IllegalStateException(ex);
89 }
90 }
91 };
92 storage.lock();
93 Future<?> future = executor.submit(second);
94 try {
95 future.get(1L, TimeUnit.SECONDS);
96 MatcherAssert.assertThat("timeout SHOULD happen", false);
97 } catch (final TimeoutException ex) {
98 future.cancel(true);
99 } finally {
100 storage.unlock();
101 }
102 future = executor.submit(second);
103 try {
104 future.get(1L, TimeUnit.SECONDS);
105 } catch (final TimeoutException ex) {
106 MatcherAssert.assertThat("timeout SHOULD NOT happen", false);
107 future.cancel(true);
108 }
109 executor.shutdown();
110 }
111
112 }