forked from cadence-workflow/cadence-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestActivityEnvironmentInternalTest.java
358 lines (298 loc) · 12.9 KB
/
TestActivityEnvironmentInternalTest.java
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
/*
Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Modifications copyright (C) 2017 Uber Technologies, Inc.
Licensed under the Apache License, Version 2.0 (the "License"). You may not
use this file except in compliance with the License. A copy of the License is
located at
http://aws.amazon.com/apache2.0
or in the "license" file accompanying this file. This file is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing
permissions and limitations under the License.
*/
package com.uber.cadence.internal.sync;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import com.uber.cadence.WorkflowExecution;
import com.uber.cadence.serviceclient.IWorkflowService;
import com.uber.cadence.workflow.Functions;
import com.uber.cadence.workflow.WorkflowInterceptorBase;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.time.Duration;
import java.util.*;
import java.util.function.BiPredicate;
import java.util.function.Supplier;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class TestActivityEnvironmentInternalTest {
@Mock private IWorkflowService mockWorkflowService;
@Mock private WorkflowInterceptorBase mockNext;
private Object testActivityExecutor;
private Object testWorkflowServiceWrapper;
// Helper method to find the inner class
private Class<?> findTestActivityExecutorClass() {
for (Class<?> declaredClass : TestActivityEnvironmentInternal.class.getDeclaredClasses()) {
if (declaredClass.getSimpleName().equals("TestActivityExecutor")) {
return declaredClass;
}
}
throw new RuntimeException("Could not find TestActivityExecutor inner class");
}
// Helper method to find the inner class
private Class<?> findWorkflowServiceWrapperClass() {
for (Class<?> declaredClass : TestActivityEnvironmentInternal.class.getDeclaredClasses()) {
if (declaredClass.getSimpleName().equals("WorkflowServiceWrapper")) {
return declaredClass;
}
}
throw new RuntimeException("Could not find WorkflowServiceWrapper inner class");
}
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
setupActivityExecutor();
setupWorkflowServiceWrapper();
}
private void setupActivityExecutor() {
try {
// Find the inner class first
Class<?> innerClass = findTestActivityExecutorClass();
// Get the constructor with the specific parameter types
Constructor<?> constructor =
innerClass.getDeclaredConstructor(
TestActivityEnvironmentInternal.class,
IWorkflowService.class,
WorkflowInterceptorBase.class);
constructor.setAccessible(true);
// Create an instance of the outer class
TestActivityEnvironmentInternal outerInstance = mock(TestActivityEnvironmentInternal.class);
// Create the instance
testActivityExecutor = constructor.newInstance(outerInstance, mockWorkflowService, mockNext);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to set up test: " + e.getMessage(), e);
}
}
private void setupWorkflowServiceWrapper() {
try {
// Find the inner class first
Class<?> innerClass = findWorkflowServiceWrapperClass();
// Get the constructor with the specific parameter types
Constructor<?> constructor =
innerClass.getDeclaredConstructor(
TestActivityEnvironmentInternal.class, IWorkflowService.class);
constructor.setAccessible(true);
// Create an instance of the outer class
TestActivityEnvironmentInternal outerInstance = mock(TestActivityEnvironmentInternal.class);
// Create the instance
testWorkflowServiceWrapper = constructor.newInstance(outerInstance, mockWorkflowService);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to set up test: " + e.getMessage(), e);
}
}
@Test
public void testWorkflowServiceWrapperMethodDelegation() throws Exception {
// Prepare test cases
List<MethodTestCase> testCases = prepareMethodTestCases();
// Test each method
for (MethodTestCase testCase : testCases) {
try {
// Find the method on the wrapper
Method wrapperMethod =
testWorkflowServiceWrapper
.getClass()
.getMethod(testCase.methodName, testCase.parameterTypes);
// Invoke the method on the wrapper
wrapperMethod.invoke(testWorkflowServiceWrapper, testCase.arguments);
// Generic verification using reflection
verifyMethodInvocation(mockWorkflowService, testCase);
} catch (Exception e) {
// Rethrow to fail the test if any unexpected exception occurs
throw new AssertionError("Failed to test method: " + testCase.methodName, e);
}
}
}
@Test
public void testAllMethodsThrowUnsupportedOperationException() throws Exception {
// Define test cases for different methods
MethodTestCase[] methodCases = {
// Signature: newRandom()
new MethodTestCase("newRandom", new Class<?>[0], new Object[0]),
// Signature: signalExternalWorkflow(String, WorkflowExecution, String, Object[])
new MethodTestCase(
"signalExternalWorkflow",
new Class<?>[] {String.class, WorkflowExecution.class, String.class, Object[].class},
new Object[] {
"testSignal", mock(WorkflowExecution.class), "signalName", new Object[] {}
}),
// Signature: signalExternalWorkflow(WorkflowExecution, String, Object[])
new MethodTestCase(
"signalExternalWorkflow",
new Class<?>[] {WorkflowExecution.class, String.class, Object[].class},
new Object[] {mock(WorkflowExecution.class), "signalName", new Object[] {}}),
// Signature: cancelWorkflow(WorkflowExecution)
new MethodTestCase(
"cancelWorkflow",
new Class<?>[] {WorkflowExecution.class},
new Object[] {mock(WorkflowExecution.class)}),
// Signature: sleep(Duration)
new MethodTestCase(
"sleep", new Class<?>[] {Duration.class}, new Object[] {Duration.ofSeconds(1)}),
// Signature: await(Duration, String, Supplier)
new MethodTestCase(
"await",
new Class<?>[] {Duration.class, String.class, Supplier.class},
new Object[] {Duration.ofSeconds(1), "testReason", (Supplier<?>) () -> true}),
// Signature: await(String, Supplier)
new MethodTestCase(
"await",
new Class<?>[] {String.class, Supplier.class},
new Object[] {"testReason", (Supplier<?>) () -> true}),
// Signature: newTimer(Duration)
new MethodTestCase(
"newTimer", new Class<?>[] {Duration.class}, new Object[] {Duration.ofSeconds(1)}),
// Signature: sideEffect(Class, Type, Functions.Func)
new MethodTestCase(
"sideEffect",
new Class<?>[] {Class.class, Type.class, Functions.Func.class},
new Object[] {String.class, String.class, (Functions.Func<String>) () -> "test"}),
// Signature: mutableSideEffect(String, Class, Type, BiPredicate, Functions.Func)
new MethodTestCase(
"mutableSideEffect",
new Class<?>[] {
String.class, Class.class, Type.class, BiPredicate.class, Functions.Func.class
},
new Object[] {
"testId",
String.class,
String.class,
(BiPredicate<String, String>) (a, b) -> false,
(Functions.Func<String>) () -> "test"
}),
// Signature: getVersion(String, int, int)
new MethodTestCase(
"getVersion",
new Class<?>[] {String.class, int.class, int.class},
new Object[] {"changeId", 0, 1}),
// Signature: continueAsNew(Optional, Optional, Object[])
new MethodTestCase(
"continueAsNew",
new Class<?>[] {Optional.class, Optional.class, Object[].class},
new Object[] {Optional.empty(), Optional.empty(), new Object[] {}}),
// Signature: registerQuery(String, Type[], Func1)
new MethodTestCase(
"registerQuery",
new Class<?>[] {String.class, Type[].class, Functions.Func1.class},
new Object[] {
"queryType",
new Type[] {String.class},
(Functions.Func1<Object[], Object>) args -> "result"
}),
// Signature: randomUUID()
new MethodTestCase("randomUUID", new Class<?>[0], new Object[0]),
// Signature: upsertSearchAttributes(Map)
new MethodTestCase(
"upsertSearchAttributes",
new Class<?>[] {Map.class},
new Object[] {java.util.Collections.emptyMap()})
};
// Test each method
for (MethodTestCase testCase : methodCases) {
try {
// Find the method
Method method =
testActivityExecutor
.getClass()
.getDeclaredMethod(testCase.methodName, testCase.parameterTypes);
method.setAccessible(true);
// Invoke the method
Object result = method.invoke(testActivityExecutor, testCase.arguments);
// If we get here, the method did not throw UnsupportedOperationException
fail("Expected UnsupportedOperationException for method " + testCase.methodName);
} catch (Exception e) {
// Check if the cause is UnsupportedOperationException
if (!(e.getCause() instanceof UnsupportedOperationException)) {
// If it's not the expected exception, rethrow
throw new RuntimeException("Unexpected exception for method " + testCase.methodName, e);
}
// Expected behavior - UnsupportedOperationException was thrown
// Continue to next method
}
}
}
// Helper class to encapsulate method test cases
private static class MethodTestCase {
String methodName;
Class<?>[] parameterTypes;
Object[] arguments;
MethodTestCase(String methodName, Class<?>[] parameterTypes, Object[] arguments) {
this.methodName = methodName;
this.parameterTypes = parameterTypes;
this.arguments = arguments;
}
}
/** Generic method to verify method invocation on mock */
private void verifyMethodInvocation(Object mockObject, MethodTestCase testCase) throws Exception {
// Use Mockito's verify with reflection
if (testCase.arguments.length == 0) {
// For methods with no arguments
verify(mockObject).getClass().getMethod(testCase.methodName).invoke(mockObject);
} else {
// For methods with arguments
Method verifyMethod = org.mockito.Mockito.class.getMethod("verify", Object.class);
Object verifiedMock = verifyMethod.invoke(null, mockObject);
// Invoke the method on the verified mock
verifiedMock
.getClass()
.getMethod(testCase.methodName, testCase.parameterTypes)
.invoke(verifiedMock, testCase.arguments);
}
}
/** Prepares test cases for all methods in IWorkflowService */
private List<MethodTestCase> prepareMethodTestCases() throws Exception {
List<MethodTestCase> testCases = new ArrayList<>();
// You can add more methods here as needed
// Dynamically discover and add more methods from IWorkflowService if required
Method[] allMethods = IWorkflowService.class.getMethods();
for (Method method : allMethods) {
testCases.add(createDefaultMethodTestCase(method));
}
return testCases;
}
/** Creates a default MethodTestCase for a given method */
private MethodTestCase createDefaultMethodTestCase(Method method) throws Exception {
Class<?>[] parameterTypes = method.getParameterTypes();
Object[] arguments = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
arguments[i] = createDefaultArgument(parameterTypes[i]);
}
return new MethodTestCase(method.getName(), parameterTypes, arguments);
}
/** Creates a default argument for different parameter types */
private Object createDefaultArgument(Class<?> type) throws Exception {
if (type.isPrimitive()) {
if (type == boolean.class) return false;
if (type == char.class) return '\u0000';
if (type == byte.class) return (byte) 0;
if (type == short.class) return (short) 0;
if (type == int.class) return 0;
if (type == long.class) return 0L;
if (type == float.class) return 0.0f;
if (type == double.class) return 0.0d;
}
// For non-primitive types, try to create an empty instance
if (type.getConstructors().length > 0
&& Arrays.stream(type.getConstructors())
.anyMatch(constructor -> constructor.getParameterCount() == 0)) {
return type.getDeclaredConstructor().newInstance();
}
// Fallback for complex types
return null;
}
}