-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathacceptance.rs
2010 lines (1676 loc) · 67.2 KB
/
acceptance.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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Acceptance test: runs zebrad as a subprocess and asserts its
//! output for given argument combinations matches what is expected.
//!
//! ## Note on port conflict
//!
//! If the test child has a cache or port conflict with another test, or a
//! running zebrad or zcashd, then it will panic. But the acceptance tests
//! expect it to run until it is killed.
//!
//! If these conflicts cause test failures:
//! - run the tests in an isolated environment,
//! - run zebrad on a custom cache path and port,
//! - run zcashd on a custom port.
//!
//! ## Failures due to Configured Network Interfaces or Network Connectivity
//!
//! If your test environment does not have any IPv6 interfaces configured, skip IPv6 tests
//! by setting the `ZEBRA_SKIP_IPV6_TESTS` environmental variable.
//!
//! If it does not have any IPv4 interfaces, IPv4 localhost is not on `127.0.0.1`,
//! or you have poor network connectivity,
//! skip all the network tests by setting the `ZEBRA_SKIP_NETWORK_TESTS` environmental variable.
use color_eyre::{
eyre::{Result, WrapErr},
Help,
};
use tempfile::TempDir;
use std::{
collections::HashSet, convert::TryInto, env, net::SocketAddr, path::Path, path::PathBuf,
time::Duration,
};
use zebra_chain::{
block::Height,
parameters::Network::{self, *},
};
use zebra_network::constants::PORT_IN_USE_ERROR;
use zebra_state::constants::LOCK_FILE_ERROR;
use zebra_test::{
command::{ContextFrom, TestDirExt},
net::random_known_port,
prelude::*,
};
use zebrad::{
components::{mempool, sync},
config::{SyncSection, TracingSection, ZebradConfig},
};
/// The amount of time we wait after launching `zebrad`.
///
/// Previously, this value was 3 seconds, which caused rare
/// metrics or tracing test failures in Windows CI.
const LAUNCH_DELAY: Duration = Duration::from_secs(15);
/// The amount of time we wait between launching two
/// conflicting nodes.
const BETWEEN_NODES_DELAY: Duration = Duration::from_secs(2);
/// Returns a config with:
/// - a Zcash listener on an unused port on IPv4 localhost, and
/// - an ephemeral state,
/// - the minimum syncer lookahead limit, and
/// - shorter task intervals, to improve test coverage.
fn default_test_config() -> Result<ZebradConfig> {
const TEST_DURATION: Duration = Duration::from_secs(30);
let network = zebra_network::Config {
// The OS automatically chooses an unused port.
listen_addr: "127.0.0.1:0".parse()?,
crawl_new_peer_interval: TEST_DURATION,
..zebra_network::Config::default()
};
let sync = SyncSection {
// Avoid downloading unnecessary blocks.
lookahead_limit: sync::MIN_LOOKAHEAD_LIMIT,
..SyncSection::default()
};
let mempool = mempool::Config {
eviction_memory_time: TEST_DURATION,
..mempool::Config::default()
};
let consensus = zebra_consensus::Config {
debug_skip_parameter_preload: true,
..zebra_consensus::Config::default()
};
let force_use_color = !matches!(
env::var("ZEBRA_FORCE_USE_COLOR"),
Err(env::VarError::NotPresent)
);
let tracing = TracingSection {
force_use_color,
..TracingSection::default()
};
let config = ZebradConfig {
network,
state: zebra_state::Config::ephemeral(),
sync,
mempool,
consensus,
tracing,
..ZebradConfig::default()
};
Ok(config)
}
fn persistent_test_config() -> Result<ZebradConfig> {
let mut config = default_test_config()?;
config.state.ephemeral = false;
Ok(config)
}
fn testdir() -> Result<TempDir> {
tempfile::Builder::new()
.prefix("zebrad_tests")
.tempdir()
.map_err(Into::into)
}
/// Extension trait for methods on `tempfile::TempDir` for using it as a test
/// directory for `zebrad`.
trait ZebradTestDirExt
where
Self: AsRef<Path> + Sized,
{
// Zebra methods
/// Spawn `zebrad` with `args` as a child process in this test directory,
/// potentially taking ownership of the tempdir for the duration of the
/// child process.
///
/// If there is a config in the test directory, pass it to `zebrad`.
fn spawn_child(self, args: &[&str]) -> Result<TestChild<Self>>;
/// Create a config file and use it for all subsequently spawned `zebrad` processes.
/// Returns an error if the config already exists.
///
/// If needed:
/// - recursively create directories for the config and state
/// - set `config.cache_dir` based on `self`
fn with_config(self, config: &mut ZebradConfig) -> Result<Self>;
/// Create a config file with the exact contents of `config`, and use it for
/// all subsequently spawned `zebrad` processes. Returns an error if the config
/// already exists.
///
/// If needed:
/// - recursively create directories for the config and state
fn with_exact_config(self, config: &ZebradConfig) -> Result<Self>;
/// Overwrite any existing `zebrad` config file, and use the newly written config for
/// all subsequently spawned processes.
///
/// If needed:
/// - recursively create directories for the config and state
/// - set `config.cache_dir` based on `self`
fn replace_config(self, config: &mut ZebradConfig) -> Result<Self>;
/// `cache_dir` config update helper for `zebrad`.
///
/// If needed:
/// - set the cache_dir in the config.
fn cache_config_update_helper(self, config: &mut ZebradConfig) -> Result<Self>;
/// Config writing helper for `zebrad`.
///
/// If needed:
/// - recursively create directories for the config and state,
///
/// Then write out the config.
fn write_config_helper(self, config: &ZebradConfig) -> Result<Self>;
// lightwalletd methods
/// Spawn `lightwalletd` with `args` as a child process in this test directory,
/// potentially taking ownership of the tempdir for the duration of the
/// child process.
///
/// By default, launch a working test instance with logging, and avoid port conflicts.
///
/// # Panics
///
/// If there is no lightwalletd config in the test directory.
fn spawn_lightwalletd_child(self, args: &[&str]) -> Result<TestChild<Self>>;
/// Create a config file and use it for all subsequently spawned `lightwalletd` processes.
/// Returns an error if the config already exists.
///
/// If needed:
/// - recursively create directories for the config
fn with_lightwalletd_config(self, zebra_rpc_listener: SocketAddr) -> Result<Self>;
}
impl<T> ZebradTestDirExt for T
where
Self: TestDirExt + AsRef<Path> + Sized,
{
fn spawn_child(self, args: &[&str]) -> Result<TestChild<Self>> {
let dir = self.as_ref();
let default_config_path = dir.join("zebrad.toml");
if default_config_path.exists() {
let mut extra_args: Vec<_> = vec![
"-c",
default_config_path
.as_path()
.to_str()
.expect("Path is valid Unicode"),
];
extra_args.extend_from_slice(args);
self.spawn_child_with_command(env!("CARGO_BIN_EXE_zebrad"), &extra_args)
} else {
self.spawn_child_with_command(env!("CARGO_BIN_EXE_zebrad"), args)
}
}
fn with_config(self, config: &mut ZebradConfig) -> Result<Self> {
self.cache_config_update_helper(config)?
.write_config_helper(config)
}
fn with_exact_config(self, config: &ZebradConfig) -> Result<Self> {
self.write_config_helper(config)
}
fn replace_config(self, config: &mut ZebradConfig) -> Result<Self> {
use std::fs;
use std::io::ErrorKind;
// Remove any existing config before writing a new one
let dir = self.as_ref();
let config_file = dir.join("zebrad.toml");
match fs::remove_file(config_file) {
Ok(()) => {}
// If the config file doesn't exist, that's ok
Err(e) if e.kind() == ErrorKind::NotFound => {}
Err(e) => Err(e)?,
}
self.cache_config_update_helper(config)?
.write_config_helper(config)
}
fn cache_config_update_helper(self, config: &mut ZebradConfig) -> Result<Self> {
if !config.state.ephemeral {
let dir = self.as_ref();
let cache_dir = dir.join("state");
config.state.cache_dir = cache_dir;
}
Ok(self)
}
fn write_config_helper(self, config: &ZebradConfig) -> Result<Self> {
use std::fs;
use std::io::Write;
let dir = self.as_ref();
if !config.state.ephemeral {
let cache_dir = dir.join("state");
fs::create_dir_all(&cache_dir)?;
} else {
fs::create_dir_all(&dir)?;
}
let config_file = dir.join("zebrad.toml");
fs::File::create(config_file)?.write_all(toml::to_string(&config)?.as_bytes())?;
Ok(self)
}
fn spawn_lightwalletd_child(self, extra_args: &[&str]) -> Result<TestChild<Self>> {
let dir = self.as_ref().to_owned();
let default_config_path = dir.join("lightwalletd-zcash.conf");
assert!(
default_config_path.exists(),
"lightwalletd requires a config"
);
// By default, launch a working test instance with logging,
// and avoid port conflicts.
let mut args: Vec<_> = vec![
// the fake zcashd conf we just wrote
"--zcash-conf-path",
default_config_path
.as_path()
.to_str()
.expect("Path is valid Unicode"),
// the lightwalletd cache directory
//
// TODO: create a sub-directory for lightwalletd
"--data-dir",
dir.to_str().expect("Path is valid Unicode"),
// log to standard output
//
// TODO: if lightwalletd needs to run on Windows,
// work out how to log to the terminal on all platforms
"--log-file",
"/dev/stdout",
// let the OS choose a random available wallet client port
"--grpc-bind-addr",
"127.0.0.1:0",
"--http-bind-addr",
"127.0.0.1:0",
// don't require a TLS certificate for the HTTP server
"--no-tls-very-insecure",
];
args.extend_from_slice(extra_args);
self.spawn_child_with_command("lightwalletd", &args)
}
fn with_lightwalletd_config(self, zebra_rpc_listener: SocketAddr) -> Result<Self> {
use std::fs;
let lightwalletd_config = format!(
"\
rpcbind={}\n\
rpcport={}\n\
",
zebra_rpc_listener.ip(),
zebra_rpc_listener.port(),
);
let dir = self.as_ref();
fs::create_dir_all(dir)?;
let config_file = dir.join("lightwalletd-zcash.conf");
fs::write(config_file, lightwalletd_config.as_bytes())?;
Ok(self)
}
}
#[test]
fn generate_no_args() -> Result<()> {
zebra_test::init();
let child = testdir()?
.with_config(&mut default_test_config()?)?
.spawn_child(&["generate"])?;
let output = child.wait_with_output()?;
let output = output.assert_success()?;
// First line
output.stdout_line_contains("# Default configuration for zebrad")?;
Ok(())
}
/// Panics if `$pred` is false, with an error report containing:
/// * context from `$source`, and
/// * an optional wrapper error, using `$fmt_arg`+ as a format string and
/// arguments.
macro_rules! assert_with_context {
($pred:expr, $source:expr) => {
if !$pred {
use color_eyre::Section as _;
use color_eyre::SectionExt as _;
use zebra_test::command::ContextFrom as _;
let report = color_eyre::eyre::eyre!("failed assertion")
.section(stringify!($pred).header("Predicate:"))
.context_from($source);
panic!("Error: {:?}", report);
}
};
($pred:expr, $source:expr, $($fmt_arg:tt)+) => {
if !$pred {
use color_eyre::Section as _;
use color_eyre::SectionExt as _;
use zebra_test::command::ContextFrom as _;
let report = color_eyre::eyre::eyre!("failed assertion")
.section(stringify!($pred).header("Predicate:"))
.context_from($source)
.wrap_err(format!($($fmt_arg)+));
panic!("Error: {:?}", report);
}
};
}
#[test]
fn generate_args() -> Result<()> {
zebra_test::init();
let testdir = testdir()?;
let testdir = &testdir;
// unexpected free argument `argument`
let child = testdir.spawn_child(&["generate", "argument"])?;
let output = child.wait_with_output()?;
output.assert_failure()?;
// unrecognized option `-f`
let child = testdir.spawn_child(&["generate", "-f"])?;
let output = child.wait_with_output()?;
output.assert_failure()?;
// missing argument to option `-o`
let child = testdir.spawn_child(&["generate", "-o"])?;
let output = child.wait_with_output()?;
output.assert_failure()?;
// Add a config file name to tempdir path
let generated_config_path = testdir.path().join("zebrad.toml");
// Valid
let child =
testdir.spawn_child(&["generate", "-o", generated_config_path.to_str().unwrap()])?;
let output = child.wait_with_output()?;
let output = output.assert_success()?;
assert_with_context!(
testdir.path().exists(),
&output,
"test temp directory not found"
);
assert_with_context!(
generated_config_path.exists(),
&output,
"generated config file not found"
);
Ok(())
}
/// Is `s` a valid `zebrad` version string?
///
/// Trims whitespace before parsing the version.
///
/// Returns false if the version is invalid, or if there is anything else on the
/// line that contains the version. In particular, this check will fail if `s`
/// includes any terminal formatting.
fn is_zebrad_version(s: &str) -> bool {
semver::Version::parse(s.replace("zebrad", "").trim()).is_ok()
}
#[test]
fn help_no_args() -> Result<()> {
zebra_test::init();
let testdir = testdir()?.with_config(&mut default_test_config()?)?;
let child = testdir.spawn_child(&["help"])?;
let output = child.wait_with_output()?;
let output = output.assert_success()?;
// The first line should have the version
output.any_output_line(
is_zebrad_version,
&output.output.stdout,
"stdout",
"a valid zebrad semantic version",
)?;
// Make sure we are in help by looking usage string
output.stdout_line_contains("USAGE:")?;
Ok(())
}
#[test]
fn help_args() -> Result<()> {
zebra_test::init();
let testdir = testdir()?;
let testdir = &testdir;
// The subcommand "argument" wasn't recognized.
let child = testdir.spawn_child(&["help", "argument"])?;
let output = child.wait_with_output()?;
output.assert_failure()?;
// option `-f` does not accept an argument
let child = testdir.spawn_child(&["help", "-f"])?;
let output = child.wait_with_output()?;
output.assert_failure()?;
Ok(())
}
#[test]
fn start_no_args() -> Result<()> {
zebra_test::init();
// start caches state, so run one of the start tests with persistent state
let testdir = testdir()?.with_config(&mut persistent_test_config()?)?;
let mut child = testdir.spawn_child(&["-v", "start"])?;
// Run the program and kill it after a few seconds
std::thread::sleep(LAUNCH_DELAY);
child.kill()?;
let output = child.wait_with_output()?;
let output = output.assert_failure()?;
output.stdout_line_contains("Starting zebrad")?;
// Make sure the command passed the legacy chain check
output.stdout_line_contains("starting legacy chain check")?;
output.stdout_line_contains("no legacy chain found")?;
// Make sure the command was killed
output.assert_was_killed()?;
Ok(())
}
#[test]
fn start_args() -> Result<()> {
zebra_test::init();
let testdir = testdir()?.with_config(&mut default_test_config()?)?;
let testdir = &testdir;
let mut child = testdir.spawn_child(&["start"])?;
// Run the program and kill it after a few seconds
std::thread::sleep(LAUNCH_DELAY);
child.kill()?;
let output = child.wait_with_output()?;
// Make sure the command was killed
output.assert_was_killed()?;
output.assert_failure()?;
// unrecognized option `-f`
let child = testdir.spawn_child(&["start", "-f"])?;
let output = child.wait_with_output()?;
output.assert_failure()?;
Ok(())
}
#[test]
fn persistent_mode() -> Result<()> {
zebra_test::init();
let testdir = testdir()?.with_config(&mut persistent_test_config()?)?;
let testdir = &testdir;
let mut child = testdir.spawn_child(&["-v", "start"])?;
// Run the program and kill it after a few seconds
std::thread::sleep(LAUNCH_DELAY);
child.kill()?;
let output = child.wait_with_output()?;
// Make sure the command was killed
output.assert_was_killed()?;
let cache_dir = testdir.path().join("state");
assert_with_context!(
cache_dir.read_dir()?.count() > 0,
&output,
"state directory empty despite persistent state config"
);
Ok(())
}
/// The cache_dir config used in the ephemeral mode tests
#[derive(Debug, PartialEq, Eq)]
enum EphemeralConfig {
/// the cache_dir config is left at its default value
Default,
/// the cache_dir config is set to a path in the tempdir
MisconfiguredCacheDir,
}
/// The check performed by the ephemeral mode tests
#[derive(Debug, PartialEq, Eq)]
enum EphemeralCheck {
/// an existing directory is not deleted
ExistingDirectory,
/// a missing directory is not created
MissingDirectory,
}
#[test]
fn ephemeral_existing_directory() -> Result<()> {
ephemeral(EphemeralConfig::Default, EphemeralCheck::ExistingDirectory)
}
#[test]
fn ephemeral_missing_directory() -> Result<()> {
ephemeral(EphemeralConfig::Default, EphemeralCheck::MissingDirectory)
}
#[test]
fn misconfigured_ephemeral_existing_directory() -> Result<()> {
ephemeral(
EphemeralConfig::MisconfiguredCacheDir,
EphemeralCheck::ExistingDirectory,
)
}
#[test]
fn misconfigured_ephemeral_missing_directory() -> Result<()> {
ephemeral(
EphemeralConfig::MisconfiguredCacheDir,
EphemeralCheck::MissingDirectory,
)
}
fn ephemeral(cache_dir_config: EphemeralConfig, cache_dir_check: EphemeralCheck) -> Result<()> {
use std::fs;
use std::io::ErrorKind;
zebra_test::init();
let mut config = default_test_config()?;
let run_dir = testdir()?;
let ignored_cache_dir = run_dir.path().join("state");
if cache_dir_config == EphemeralConfig::MisconfiguredCacheDir {
// Write a configuration that sets both the cache_dir and ephemeral options
config.state.cache_dir = ignored_cache_dir.clone();
}
if cache_dir_check == EphemeralCheck::ExistingDirectory {
// We set the cache_dir config to a newly created empty temp directory,
// then make sure that it is empty after the test
fs::create_dir(&ignored_cache_dir)?;
}
let mut child = run_dir
.path()
.with_config(&mut config)?
.spawn_child(&["start"])?;
// Run the program and kill it after a few seconds
std::thread::sleep(LAUNCH_DELAY);
child.kill()?;
let output = child.wait_with_output()?;
// Make sure the command was killed
output.assert_was_killed()?;
let expected_run_dir_file_names = match cache_dir_check {
// we created the state directory, so it should still exist
EphemeralCheck::ExistingDirectory => {
assert_with_context!(
ignored_cache_dir
.read_dir()
.expect("ignored_cache_dir should still exist")
.count()
== 0,
&output,
"ignored_cache_dir not empty for ephemeral {:?} {:?}: {:?}",
cache_dir_config,
cache_dir_check,
ignored_cache_dir.read_dir().unwrap().collect::<Vec<_>>()
);
["state", "zebrad.toml"].iter()
}
// we didn't create the state directory, so it should not exist
EphemeralCheck::MissingDirectory => {
assert_with_context!(
ignored_cache_dir
.read_dir()
.expect_err("ignored_cache_dir should not exist")
.kind()
== ErrorKind::NotFound,
&output,
"unexpected creation of ignored_cache_dir for ephemeral {:?} {:?}: the cache dir exists and contains these files: {:?}",
cache_dir_config,
cache_dir_check,
ignored_cache_dir.read_dir().unwrap().collect::<Vec<_>>()
);
["zebrad.toml"].iter()
}
};
let expected_run_dir_file_names = expected_run_dir_file_names.map(Into::into).collect();
let run_dir_file_names = run_dir
.path()
.read_dir()
.expect("run_dir should still exist")
.map(|dir_entry| dir_entry.expect("run_dir is readable").file_name())
// ignore directory list order, because it can vary based on the OS and filesystem
.collect::<HashSet<_>>();
assert_with_context!(
run_dir_file_names == expected_run_dir_file_names,
&output,
"run_dir not empty for ephemeral {:?} {:?}: expected {:?}, actual: {:?}",
cache_dir_config,
cache_dir_check,
expected_run_dir_file_names,
run_dir_file_names
);
Ok(())
}
#[test]
fn app_no_args() -> Result<()> {
zebra_test::init();
let testdir = testdir()?.with_config(&mut default_test_config()?)?;
let child = testdir.spawn_child(&[])?;
let output = child.wait_with_output()?;
let output = output.assert_success()?;
output.stdout_line_contains("USAGE:")?;
Ok(())
}
#[test]
fn version_no_args() -> Result<()> {
zebra_test::init();
let testdir = testdir()?.with_config(&mut default_test_config()?)?;
let child = testdir.spawn_child(&["version"])?;
let output = child.wait_with_output()?;
let output = output.assert_success()?;
// The output should only contain the version
output.output_check(
is_zebrad_version,
&output.output.stdout,
"stdout",
"a valid zebrad semantic version",
)?;
Ok(())
}
#[test]
fn version_args() -> Result<()> {
zebra_test::init();
let testdir = testdir()?.with_config(&mut default_test_config()?)?;
let testdir = &testdir;
// unexpected free argument `argument`
let child = testdir.spawn_child(&["version", "argument"])?;
let output = child.wait_with_output()?;
output.assert_failure()?;
// unrecognized option `-f`
let child = testdir.spawn_child(&["version", "-f"])?;
let output = child.wait_with_output()?;
output.assert_failure()?;
Ok(())
}
#[test]
fn valid_generated_config_test() -> Result<()> {
// Unlike the other tests, these tests can not be run in parallel, because
// they use the generated config. So parallel execution can cause port and
// cache conflicts.
valid_generated_config("start", "Starting zebrad")?;
Ok(())
}
fn valid_generated_config(command: &str, expect_stdout_line_contains: &str) -> Result<()> {
zebra_test::init();
let testdir = testdir()?;
let testdir = &testdir;
// Add a config file name to tempdir path
let generated_config_path = testdir.path().join("zebrad.toml");
// Generate configuration in temp dir path
let child =
testdir.spawn_child(&["generate", "-o", generated_config_path.to_str().unwrap()])?;
let output = child.wait_with_output()?;
let output = output.assert_success()?;
assert_with_context!(
generated_config_path.exists(),
&output,
"generated config file not found"
);
// Run command using temp dir and kill it after a few seconds
let mut child = testdir.spawn_child(&[command])?;
std::thread::sleep(LAUNCH_DELAY);
child.kill()?;
let output = child.wait_with_output()?;
let output = output.assert_failure()?;
output.stdout_line_contains(expect_stdout_line_contains)?;
// [Note on port conflict](#Note on port conflict)
output.assert_was_killed().wrap_err("Possible port or cache conflict. Are there other acceptance test, zebrad, or zcashd processes running?")?;
assert_with_context!(
testdir.path().exists(),
&output,
"test temp directory not found"
);
assert_with_context!(
generated_config_path.exists(),
&output,
"generated config file not found"
);
Ok(())
}
const TINY_CHECKPOINT_TEST_HEIGHT: Height = Height(0);
const MEDIUM_CHECKPOINT_TEST_HEIGHT: Height =
Height(zebra_consensus::MAX_CHECKPOINT_HEIGHT_GAP as u32);
const LARGE_CHECKPOINT_TEST_HEIGHT: Height =
Height((zebra_consensus::MAX_CHECKPOINT_HEIGHT_GAP * 2) as u32);
const STOP_AT_HEIGHT_REGEX: &str = "stopping at configured height";
/// The text that should be logged when the initial sync finishes at the estimated chain tip.
///
/// This message is only logged if:
/// - we have reached the estimated chain tip,
/// - we have synced all known checkpoints,
/// - the syncer has stopped downloading lots of blocks, and
/// - we are regularly downloading some blocks via the syncer or block gossip.
const SYNC_FINISHED_REGEX: &str = "finished initial sync to chain tip, using gossiped blocks";
/// The maximum amount of time Zebra should take to reload after shutting down.
///
/// This should only take a second, but sometimes CI VMs or RocksDB can be slow.
const STOP_ON_LOAD_TIMEOUT: Duration = Duration::from_secs(10);
/// The maximum amount of time Zebra should take to sync a few hundred blocks.
///
/// Usually the small checkpoint is much shorter than this.
const TINY_CHECKPOINT_TIMEOUT: Duration = Duration::from_secs(120);
/// The maximum amount of time Zebra should take to sync a thousand blocks.
const LARGE_CHECKPOINT_TIMEOUT: Duration = Duration::from_secs(180);
/// The test sync height where we switch to using the default lookahead limit.
///
/// Most tests only download a few blocks. So tests default to the minimum lookahead limit,
/// to avoid downloading extra blocks, and slowing down the test.
///
/// But if we're going to be downloading lots of blocks, we use the default lookahead limit,
/// so that the sync is faster. This can increase the RAM needed for tests.
const MIN_HEIGHT_FOR_DEFAULT_LOOKAHEAD: Height = Height(3 * sync::DEFAULT_LOOKAHEAD_LIMIT as u32);
/// Test if `zebrad` can sync the first checkpoint on mainnet.
///
/// The first checkpoint contains a single genesis block.
#[test]
fn sync_one_checkpoint_mainnet() -> Result<()> {
sync_until(
TINY_CHECKPOINT_TEST_HEIGHT,
Mainnet,
STOP_AT_HEIGHT_REGEX,
TINY_CHECKPOINT_TIMEOUT,
None,
MempoolBehavior::ShouldNotActivate,
// checkpoint sync is irrelevant here - all tested checkpoints are mandatory
true,
true,
)
.map(|_tempdir| ())
}
/// Test if `zebrad` can sync the first checkpoint on testnet.
///
/// The first checkpoint contains a single genesis block.
#[test]
fn sync_one_checkpoint_testnet() -> Result<()> {
sync_until(
TINY_CHECKPOINT_TEST_HEIGHT,
Testnet,
STOP_AT_HEIGHT_REGEX,
TINY_CHECKPOINT_TIMEOUT,
None,
MempoolBehavior::ShouldNotActivate,
// checkpoint sync is irrelevant here - all tested checkpoints are mandatory
true,
true,
)
.map(|_tempdir| ())
}
/// Test if `zebrad` can sync the first checkpoint, restart, and stop on load.
#[test]
fn restart_stop_at_height() -> Result<()> {
zebra_test::init();
restart_stop_at_height_for_network(Network::Mainnet, TINY_CHECKPOINT_TEST_HEIGHT)?;
restart_stop_at_height_for_network(Network::Testnet, TINY_CHECKPOINT_TEST_HEIGHT)?;
Ok(())
}
fn restart_stop_at_height_for_network(network: Network, height: Height) -> Result<()> {
let reuse_tempdir = sync_until(
height,
network,
STOP_AT_HEIGHT_REGEX,
TINY_CHECKPOINT_TIMEOUT,
None,
MempoolBehavior::ShouldNotActivate,
// checkpoint sync is irrelevant here - all tested checkpoints are mandatory
true,
true,
)?;
// if stopping corrupts the rocksdb database, zebrad might hang or crash here
// if stopping does not write the rocksdb database to disk, Zebra will
// sync, rather than stopping immediately at the configured height
sync_until(
height,
network,
"state is already at the configured height",
STOP_ON_LOAD_TIMEOUT,
reuse_tempdir,
MempoolBehavior::ShouldNotActivate,
// checkpoint sync is irrelevant here - all tested checkpoints are mandatory
true,
false,
)?;
Ok(())
}
/// Test if `zebrad` can activate the mempool on mainnet.
/// Debug activation happens after committing the genesis block.
#[test]
fn activate_mempool_mainnet() -> Result<()> {
sync_until(
Height(TINY_CHECKPOINT_TEST_HEIGHT.0 + 1),
Mainnet,
STOP_AT_HEIGHT_REGEX,
TINY_CHECKPOINT_TIMEOUT,
None,
MempoolBehavior::ForceActivationAt(TINY_CHECKPOINT_TEST_HEIGHT),
// checkpoint sync is irrelevant here - all tested checkpoints are mandatory
true,
true,
)
.map(|_tempdir| ())
}
/// Test if `zebrad` can sync some larger checkpoints on mainnet.
///
/// This test might fail or timeout on slow or unreliable networks,
/// so we don't run it by default. It also takes a lot longer than
/// our 10 second target time for default tests.
#[test]
#[ignore]
fn sync_large_checkpoints_mainnet() -> Result<()> {
let reuse_tempdir = sync_until(
LARGE_CHECKPOINT_TEST_HEIGHT,
Mainnet,
STOP_AT_HEIGHT_REGEX,
LARGE_CHECKPOINT_TIMEOUT,
None,
MempoolBehavior::ShouldNotActivate,
// checkpoint sync is irrelevant here - all tested checkpoints are mandatory
true,
true,
)?;
// if this sync fails, see the failure notes in `restart_stop_at_height`
sync_until(
(LARGE_CHECKPOINT_TEST_HEIGHT - 1).unwrap(),
Mainnet,
"previous state height is greater than the stop height",
STOP_ON_LOAD_TIMEOUT,
reuse_tempdir,
MempoolBehavior::ShouldNotActivate,
// checkpoint sync is irrelevant here - all tested checkpoints are mandatory
true,
false,
)?;
Ok(())
}
// TODO: We had `sync_large_checkpoints_testnet` and `sync_large_checkpoints_mempool_testnet`,
// but they were removed because the testnet is unreliable (#1222).
// We should re-add them after we have more testnet instances (#1791).