View Javadoc
1   package org.eclipse.jgit.logging;
2   
3   import static org.junit.Assert.assertEquals;
4   import static org.junit.Assert.assertFalse;
5   import static org.junit.Assert.assertTrue;
6   
7   import org.junit.Test;
8   import java.util.List;
9   
10  /**
11   * Tests for performance log context utilities.
12   */
13  public class PerformanceLogContextTest {
14  
15  	@Test
16  	public void testAddEvent() {
17  		PerformanceLogRecord record = new PerformanceLogRecord("record", 0);
18  		PerformanceLogContext.getInstance().addEvent(record);
19  
20  		List<PerformanceLogRecord> eventRecords = PerformanceLogContext
21  				.getInstance().getEventRecords();
22  		assertTrue(eventRecords.contains(record));
23  		assertEquals(1, eventRecords.size());
24  	}
25  
26  	@Test
27  	public void testCleanEvents() {
28  		PerformanceLogRecord record1 = new PerformanceLogRecord("record1", 0);
29  		PerformanceLogContext.getInstance().addEvent(record1);
30  
31  		PerformanceLogRecord record2 = new PerformanceLogRecord("record2", 0);
32  		PerformanceLogContext.getInstance().addEvent(record2);
33  
34  		PerformanceLogContext.getInstance().cleanEvents();
35  		List<PerformanceLogRecord> eventRecords = PerformanceLogContext
36  				.getInstance().getEventRecords();
37  		assertEquals(0, eventRecords.size());
38  	}
39  
40  	@Test
41  	public void testAddEventsTwoThreads() throws InterruptedException {
42  		TestRunnable runnable1 = new TestRunnable("record1", 1);
43  		TestRunnable runnable2 = new TestRunnable("record2", 2);
44  
45  		Thread thread1 = new Thread(runnable1);
46  		Thread thread2 = new Thread(runnable2);
47  
48  		thread1.start();
49  		thread2.start();
50  
51  		thread1.join();
52  		thread2.join();
53  		assertEquals(1, runnable1.getEventRecordsCount());
54  		assertEquals(1, runnable2.getEventRecordsCount());
55  		assertFalse(runnable1.isThrown());
56  		assertFalse(runnable2.isThrown());
57  	}
58  
59  	private static class TestRunnable implements Runnable {
60  		private String name;
61  
62  		private long durationMs;
63  
64  		private long eventRecordsCount;
65  
66  		private boolean thrown = false;
67  
68  		public TestRunnable(String name, long durationMs) {
69  			this.name = name;
70  			this.durationMs = durationMs;
71  		}
72  
73  		public boolean isThrown() {
74  			return thrown;
75  		}
76  
77  		public long getEventRecordsCount() {
78  			return eventRecordsCount;
79  		}
80  
81  		@Override
82  		public void run() {
83  			PerformanceLogRecord record = new PerformanceLogRecord(name,
84  					durationMs);
85  			try {
86  				PerformanceLogContext.getInstance().addEvent(record);
87  				eventRecordsCount = PerformanceLogContext.getInstance()
88  						.getEventRecords().size();
89  				PerformanceLogContext.getInstance().cleanEvents();
90  			} catch (Exception e) {
91  				thrown = true;
92  			}
93  		}
94  	}
95  }