-
Notifications
You must be signed in to change notification settings - Fork 30
/
service_proxy.rs
288 lines (242 loc) · 8.74 KB
/
service_proxy.rs
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
/*
* Copyright 2019 The Exonum Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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.
*/
extern crate integration_tests;
extern crate java_bindings;
#[macro_use]
extern crate lazy_static;
extern crate exonum_testkit;
#[macro_use]
extern crate serde_derive;
use integration_tests::{
mock::{service::ServiceMockBuilder, transaction::create_empty_raw_transaction},
test_service::{create_test_map, create_test_service, INITIAL_ENTRY_KEY, INITIAL_ENTRY_VALUE},
vm::create_vm_for_tests_with_fake_classes,
};
use java_bindings::{
exonum::{
blockchain::Service,
crypto::hash,
storage::{Database, MemoryDB},
},
jni::{objects::JObject, JavaVM},
serde_json::{self, Value},
utils::{any_to_string, convert_to_string, unwrap_jni},
JniExecutor, MainExecutor,
};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Arc;
use exonum_testkit::TestKitBuilder;
lazy_static! {
static ref VM: Arc<JavaVM> = create_vm_for_tests_with_fake_classes();
pub static ref EXECUTOR: MainExecutor = MainExecutor::new(VM.clone());
}
const EXCEPTION_CLASS: &str = "java/lang/RuntimeException";
const TEST_EXCEPTION_CLASS: &str = "com/exonum/binding/fakes/mocks/TestException";
const OOM_ERROR_CLASS: &str = "java/lang/OutOfMemoryError";
const TEST_CONFIG_JSON: &str = r#""test config""#;
const TEST_CONFIG_NOT_JSON: &str = r#"()"#;
lazy_static! {
static ref TEST_CONFIG_VALUE: Value = Value::String("test config".to_string());
}
#[test]
fn service_id() {
let service_id: u16 = 24;
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.id(service_id)
.build();
assert_eq!(service_id, service.service_id());
}
#[test]
fn service_id_negative() {
// Check that value is converted between rust `u16` and java `short` without loss.
let service_id: u16 = -24_i16 as u16; // 65512;
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.id(service_id)
.build();
assert_eq!(service_id, service.service_id());
}
#[test]
fn service_name() {
let service_name: &str = "test_service";
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.name(service_name)
.build();
assert_eq!(service_name, service.service_name());
}
#[test]
fn state_hash() {
let db = MemoryDB::new();
let snapshot = db.snapshot();
let hashes = [hash(&[1]), hash(&[2]), hash(&[3])];
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.state_hashes(&hashes)
.build();
assert_eq!(&hashes, service.state_hash(&*snapshot).as_slice());
}
#[test]
#[should_panic(expected = "Java exception: java.lang.OutOfMemoryError")]
fn tx_from_raw_should_panic_if_java_error_occurred() {
let raw = create_empty_raw_transaction();
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.convert_transaction_throwing(OOM_ERROR_CLASS)
.build();
service.tx_from_raw(raw).unwrap();
}
#[test]
fn tx_from_raw_should_return_err_if_java_exception_occurred() {
let raw = create_empty_raw_transaction();
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.convert_transaction_throwing(EXCEPTION_CLASS)
.build();
let err = service
.tx_from_raw(raw)
.expect_err("This transaction should be de-serialized with an error!");
assert!(err
.to_string()
.starts_with("Java exception: java.lang.RuntimeException"));
}
#[test]
fn initialize_config() {
let db = MemoryDB::new();
let mut fork = db.fork();
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.initial_global_config(TEST_CONFIG_JSON.to_string())
.build();
let config = service.initialize(&mut fork);
assert_eq!(config, *TEST_CONFIG_VALUE);
}
#[test]
fn initialize_config_null() {
let db = MemoryDB::new();
let mut fork = db.fork();
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.initial_global_config(None)
.build();
let config = service.initialize(&mut fork);
assert_eq!(config, Value::Null);
}
#[test]
fn initialize_config_parse_error() {
let db = MemoryDB::new();
let mut fork = db.fork();
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.initial_global_config(TEST_CONFIG_NOT_JSON.to_string())
.build();
match catch_unwind(AssertUnwindSafe(|| service.initialize(&mut fork))) {
Ok(_config) => panic!("This test should panic"),
Err(ref e) => {
let error = any_to_string(e);
assert!(error.starts_with("JSON deserialization error: "));
assert!(error.ends_with(r#"; json string: "()""#));
}
};
}
#[test]
#[should_panic(expected = "Java exception: java.lang.RuntimeException")]
fn initialize_should_panic_if_java_exception_occurred() {
let db = MemoryDB::new();
let mut fork = db.fork();
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.initial_global_config_throwing(EXCEPTION_CLASS)
.build();
service.initialize(&mut fork);
}
#[test]
fn service_can_modify_db_on_initialize() {
let db = MemoryDB::new();
let service = create_test_service(EXECUTOR.clone());
{
let mut fork = db.fork();
service.initialize(&mut fork);
db.merge(fork.into_patch())
.expect("Failed to merge changes");
}
// Check that the Java service implementation has successfully written the initial value
// into the storage.
let snapshot = db.snapshot();
let test_map = create_test_map(&*snapshot, service.service_name());
let key = hash(INITIAL_ENTRY_KEY.as_ref());
let value = test_map
.get(&key)
.expect("Failed to find the entry created in the test service");
assert_eq!(INITIAL_ENTRY_VALUE, value);
}
#[test]
#[should_panic(expected = "Java exception: com.exonum.binding.fakes.mocks.TestException")]
fn after_commit_throwing() {
let service = ServiceMockBuilder::new(EXECUTOR.clone())
.after_commit_throwing(TEST_EXCEPTION_CLASS)
.build();
// It turned out that it is MUCH easier to use testkit in order to trigger the after_commit()
// callback than calling it by hands providing manually constructed ServiceContext entity.
let mut testkit = TestKitBuilder::validator()
.with_service(service.clone())
.create();
testkit.create_block();
}
#[test]
fn after_commit_validator() {
let (builder, interactor) =
ServiceMockBuilder::new(EXECUTOR.clone()).get_mock_interaction_after_commit();
let service = builder.build();
let mut testkit = TestKitBuilder::validator()
.with_service(service.clone())
.create();
testkit.create_block();
testkit.create_block();
let result = get_mock_interaction_result(&EXECUTOR, interactor.as_obj());
let after_commit_args: Vec<AfterCommitArgs> = serde_json::from_str(&result).unwrap();
assert_eq!(after_commit_args.len(), 2);
let item: &AfterCommitArgs = &after_commit_args[0];
assert_ne!(item.handle, 0);
assert_eq!(item.validator, 0);
assert_eq!(item.height, 1);
let item: &AfterCommitArgs = &after_commit_args[1];
assert_ne!(item.handle, 0);
assert_eq!(item.validator, 0);
assert_eq!(item.height, 2);
}
#[test]
fn after_commit_auditor() {
let (builder, interactor) =
ServiceMockBuilder::new(EXECUTOR.clone()).get_mock_interaction_after_commit();
let service = builder.build();
let mut testkit = TestKitBuilder::auditor()
.with_service(service.clone())
.create();
testkit.create_block();
let result = get_mock_interaction_result(&EXECUTOR, interactor.as_obj());
let after_commit_args: Vec<AfterCommitArgs> = serde_json::from_str(&result).unwrap();
assert_eq!(after_commit_args.len(), 1);
let item: &AfterCommitArgs = &after_commit_args[0];
assert_ne!(item.handle, 0);
assert_eq!(item.validator, -1);
assert_eq!(item.height, 1);
}
// Helper methods. Gets the JSON representation of interaction with mock.
fn get_mock_interaction_result(exec: &MainExecutor, obj: JObject) -> String {
unwrap_jni(exec.with_attached(|env| {
env.call_method(obj, "getInteractions", "()Ljava/lang/String;", &[])?
.l()
.and_then(|obj| convert_to_string(env, obj))
}))
}
#[derive(Serialize, Deserialize)]
struct AfterCommitArgs {
handle: i64,
validator: i32,
height: i64,
}