View Javadoc

1   package com.atlassian.vcache.internal.core.service;
2   
3   import com.atlassian.vcache.RequestCache;
4   import com.atlassian.vcache.internal.RequestContext;
5   import com.atlassian.vcache.internal.core.WorkContextRequestContextSupplier;
6   import com.atlassian.workcontext.api.EstablishWorkContext;
7   import com.atlassian.workcontext.api.WorkContextFuture;
8   import org.junit.Rule;
9   import org.junit.Test;
10  import org.junit.rules.ExpectedException;
11  
12  import java.util.Optional;
13  
14  import static org.hamcrest.Matchers.is;
15  import static org.hamcrest.Matchers.not;
16  import static org.hamcrest.Matchers.notNullValue;
17  import static org.junit.Assert.assertThat;
18  
19  public class WorkContextRequestContextSupplierTest {
20      @Rule
21      public ExpectedException thrown = ExpectedException.none();
22  
23      @Rule
24      public EstablishWorkContext establishWorkContext = new EstablishWorkContext();
25  
26      @Test
27      public void normal_flow() {
28          final WorkContextRequestContextSupplier supplier = new WorkContextRequestContextSupplier(() -> "abc");
29  
30          final RequestContext context = supplier.get();
31  
32          assertThat(context, notNullValue());
33          assertThat(context.partitionIdentifier(), is("abc"));
34      }
35  
36      @Test
37      public void add_to_cache_across_threads() {
38          final RequestCache<String, String> cache = new DefaultRequestCache<>("cache", new WorkContextRequestContextSupplier(() -> "abc"));
39          cache.put("1", "2");
40          final String threadName = Thread.currentThread().getName();
41  
42          // Test in another thread.
43          WorkContextFuture.runAsync( () -> {
44              assertThat(Thread.currentThread().getName(), not(threadName));  // Definitely a new thread
45              assertThat(cache.get("1"), is(Optional.of("2")));
46              cache.put("2", "2");
47          }).join();
48  
49          assertThat(cache.get("2"), is(Optional.of("2")));
50      }
51  }