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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
use std::borrow::Cow;
use std::env::temp_dir;
use std::ffi::OsString;
use std::fs::File;
use std::process::{Output, Stdio};
use std::thread::sleep;
use std::time::Duration;
use arboard::ImageData;
use crossbeam_channel::Receiver;
use mac_address::MacAddress;
use rustix::path::Arg;
use simple_cmd::debug::CommandDebug;
use simple_cmd::prelude::OutputExt;
use simple_cmd::{Cmd, CommandBuilder};
use uuid::Uuid;
use crate::error::Error;
use crate::prelude::*;
use crate::result::Result;
use crate::traits::AsArgs;
use crate::types::{
Adb, AdbInstallOptions, Client, ConnectionType, LogcatOptions, RebootType, Reconnect, Shell,
UninstallOptions, Wakefulness,
};
static GET_STATE_TIMEOUT: u64 = 200;
static SLEEP_AFTER_ROOT: u64 = 1_000;
impl Client {
pub fn new(adb: Adb, addr: ConnectionType, debug: bool) -> Self {
Client { adb, addr, debug }
}
/// Attempt to connect to a tcp/ip client, optionally waiting until the given
/// timeout expires.
/// # Examples:
/// ```rust
/// use radb_client::types::ConnectionType;
/// use radb_client::types::Client;
///
/// pub fn main() {
/// use std::time::Duration;
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// match client.connect(Some(Duration::from_secs(1))) {
/// Ok(_) => println!("client connected!"),
/// Err(err) => eprintln!("failed to connect: {err}"),
/// }
/// }
/// ```
pub fn connect(&self, timeout: Option<Duration>) -> Result<()> {
if self.is_connected() {
return Ok(());
}
let addr = match self.addr {
ConnectionType::TcpIp(ip) => ip.ip(),
_ => return Err(Error::InvalidConnectionTypeError),
};
let mut command = CommandBuilder::adb(&self.adb).with_debug(self.debug);
command = command
.arg("connect")
.arg(addr.to_string())
.timeout(timeout);
let output = command.build().output()?;
if output.error() {
Err(Error::IoError(std::io::Error::from(
std::io::ErrorKind::NotConnected,
)))
} else {
match self.is_connected() {
true => Ok(()),
false => Err(Error::IoError(std::io::Error::from(
std::io::ErrorKind::NotConnected,
))),
}
}
}
pub fn disconnect(&self) -> Result<bool> {
let mut command = CommandBuilder::adb(&self.adb).with_debug(self.debug);
command = command.arg("disconnect");
command = match self.addr {
ConnectionType::TcpIp(ip) => command.arg(ip.to_string()),
_ => command,
};
match command.build().output() {
Ok(output) => Ok(output.success()),
Err(err) => Err(Error::CommandError(err)),
}
}
pub fn try_disconnect(&self) -> Result<bool> {
let mut command = CommandBuilder::adb(&self.adb).with_debug(self.debug);
command = command.arg("disconnect");
command = match self.addr {
ConnectionType::TcpIp(ip) => command.arg(ip.to_string()),
_ => command,
};
match command.build().run() {
Ok(status) => Ok(status.map_or(false, |status| status.success())),
Err(err) => Err(Error::CommandError(err)),
}
}
pub fn disconnect_all(&self) -> Result<()> {
super::shell::handle_result(
CommandBuilder::adb(&self.adb)
.with_debug(self.debug)
.arg("disconnect")
.build()
.output()?,
)
}
pub fn is_connected(&self) -> bool {
let mut command = CommandBuilder::from(self);
command = command
.arg("get-state")
.timeout(Some(Duration::from_millis(GET_STATE_TIMEOUT)));
let output = command.build().output();
if let Ok(output) = output {
output.success()
} else {
false
}
}
/// Wait for device to be available with an optional timeout
pub fn wait_for_device(&self, timeout: Option<Duration>) -> Result<()> {
CommandBuilder::from(self)
.args([
"wait-for-device",
"shell",
"while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done; input keyevent 143",
])
.timeout(timeout)
.build()
.output()?;
Ok(())
}
pub fn get_wakefulness(&self) -> Result<Wakefulness> {
let command1 = CommandBuilder::from(self)
.args(vec!["shell", "dumpsys", "power"])
.build();
let command2 = Cmd::builder("sed")
.arg("-n")
.arg("s/mWakefulness=\\(\\S*\\)/\\1/p")
.with_debug(self.debug)
.stdout(Some(Stdio::piped()))
.build();
let result = command1.pipe(command2)?;
let awake = Arg::as_str(&result.stdout)?.trim();
Ok(awake.try_into()?)
}
pub fn is_awake(&self) -> Result<bool> {
Ok(self.get_wakefulness()? != Wakefulness::Asleep)
}
pub fn is_root(&self) -> Result<bool> {
self.shell().is_root()
}
pub fn root(&self) -> Result<bool> {
if self.shell().is_root()? {
return Ok(true);
}
let output = CommandBuilder::from(self).arg("root").build().output()?;
if output.success() {
sleep(Duration::from_millis(SLEEP_AFTER_ROOT));
Ok(self.is_root()?)
} else {
Err(Error::CommandError(simple_cmd::Error::from(output)))
}
}
pub fn unroot(&self) -> Result<()> {
super::shell::handle_result(CommandBuilder::from(self).arg("unroot").build().output()?)
}
/// Save screencap to local file.
/// # Examples:
/// ```rust
/// use std::fs::File;
/// use radb_client::types::{Client, ConnectionType};
/// fn test_save_screencap_locally() {
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// client.connect(None).unwrap();
///
/// let output = dirs::desktop_dir().unwrap().join("screencap.png");
/// let output_path = output.as_path();
/// let file = File::create(output_path).expect("failed to create file");
/// let result = client.save_screencap(file);
/// match result {
/// Ok(_) => println!("screenshot saved"),
/// Err(err) => eprintln!("failed to save screenshot: {err}"),
/// }
/// }
/// ```
pub fn save_screencap(&self, output: File) -> Result<()> {
let args = vec!["exec-out", "screencap", "-p"];
let pipe_out = Stdio::from(output);
let mut cmd = std::process::Command::new(self.adb.as_os_str());
cmd.args(self.addr.as_args())
.args(args)
.stdout(pipe_out)
.stderr(Stdio::piped());
if self.debug {
cmd.debug();
}
cmd.output()?;
Ok(())
}
pub fn copy_screencap(&self) -> Result<()> {
let mut dir = temp_dir();
let file_name = format!("{}.png", Uuid::new_v4());
dir.push(file_name);
let path = dir.as_path().to_owned();
let file = File::create(path.as_path())?;
self.save_screencap(file)?;
let img = image::open(path.as_path())?;
let width = img.width();
let height = img.height();
let image_data = ImageData {
width: width as usize,
height: height as usize,
bytes: Cow::from(img.as_bytes()),
};
let mut clipboard = arboard::Clipboard::new()?;
clipboard.set_image(image_data)?;
Ok(())
}
pub fn reboot(&self, reboot_type: Option<RebootType>) -> Result<()> {
// reboot the device; defaults to booting system image but
// supports bootloader and recovery too. sideload reboots
// into recovery and automatically starts sideload mode,
// sideload-auto-reboot is the same but reboots after sideloading.
let mut args = vec!["reboot".to_string()];
if let Some(reboot_type) = reboot_type {
let s = format!("{}", reboot_type);
args.push(s.to_owned());
}
CommandBuilder::from(self).args(args).build().output()?;
Ok(())
}
pub fn remount(&self, reboot_if_required: bool) -> Result<()> {
// remount partitions read-write. if a reboot is required, `reboot_if_required`
// will automatically reboot the device.
let mut cmd = CommandBuilder::from(self).arg("remount");
if reboot_if_required {
cmd = cmd.arg("-R");
}
let result = cmd.build().output()?;
if result.success() {
Ok(())
} else {
Err(simple_cmd::Error::CommandError(simple_cmd::errors::CmdError::from(result)).into())
}
}
/// Get the serial number of the connected device.
///
/// # Returns
/// * `Result<String>` - The serial number as a string.
///
/// # Example
/// ```rust
/// use radb_client::types::{Client, ConnectionType};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// let serial = client.get_seriano().unwrap();
/// println!("Serial: {}", serial);
/// ```
pub fn get_seriano(&self) -> Result<String> {
// print serial-number
let output = CommandBuilder::from(self)
.arg("get-serialno")
.build()
.output()?;
Ok(Arg::as_str(&output.stdout)?.trim().to_string())
}
/// Reconnect the device, optionally specifying the reconnect type.
///
/// # Arguments
/// * `r#type` - Optional reconnect type (e.g., device, offline).
///
/// # Returns
/// * `Result<String>` - The output of the reconnect command.
///
/// # Example
/// ```rust
/// use radb_client::types::{Client, ConnectionType, Reconnect};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// let result = client.reconnect(Some(Reconnect::Device)).unwrap();
/// println!("Reconnect result: {}", result);
/// ```
pub fn reconnect(&self, r#type: Option<Reconnect>) -> Result<String> {
let mut cmd = CommandBuilder::from(self).arg("reconnect".to_string());
if let Some(reconnect_type) = r#type {
cmd = cmd.arg(reconnect_type.to_string());
}
let output = cmd.build().output()?;
Ok(Arg::as_str(&output.stdout)?.trim().to_owned())
}
/// Generate a bug report and save it to the specified output path or to the default location.
///
/// # Arguments
/// * `output` - Optional output path or directory.
///
/// # Returns
/// * `Result<Output>` - The output of the bugreport command.
///
/// # Example
/// ```rust
/// use radb_client::types::{Client, ConnectionType};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// let output = client.bug_report::<&str>(None).unwrap();
/// println!("Bugreport status: {}", output.status);
/// ```
pub fn bug_report<T: Arg>(&self, output: Option<T>) -> Result<Output> {
// bugreport PATH
// write bugreport to given PATH (default=bugreport.zip);
// if PATH is a directory, the bug report is saved in that directory.
// devices that don't support zipped bug reports output to stdout.
let args = match output.as_ref() {
Some(s) => vec!["bugreport", s.as_str()?],
None => vec!["bugreport"],
};
CommandBuilder::from(self)
.args(args)
.build()
.output()
.map_err(|e| e.into())
}
/// Clear all logcat buffers on the device.
///
/// # Returns
/// * `Result<()>` - Ok if successful, or an error if the command fails.
///
/// # Example
/// ```rust
/// use radb_client::types::{Client, ConnectionType};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// client.clear_logcat().unwrap();
/// ```
pub fn clear_logcat(&self) -> Result<()> {
let output = CommandBuilder::from(self)
.args(["logcat", "-b", "all", "-c"])
.build()
.output()?;
if output.error() {
Err(output.into())
} else {
Ok(())
}
}
/// Run logcat with the specified options and optional cancellation signal.
///
/// # Arguments
/// * `options` - Logcat options (filters, format, etc.).
/// * `cancel` - Optional cancellation signal.
///
/// # Returns
/// * `Result<Output>` - The output of the logcat command.
///
/// # Example
/// ```rust
/// use radb_client::types::{Client, ConnectionType, LogcatOptions};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// let options = LogcatOptions::default();
/// let output = client.logcat(options, None).unwrap();
/// println!("Logcat output: {}", String::from_utf8_lossy(&output.stdout));
/// ```
pub fn logcat(&self, options: LogcatOptions, cancel: Option<Receiver<()>>) -> Result<Output> {
let mut command = CommandBuilder::from(self);
let mut args = vec!["logcat".into()];
args.extend(options.clone());
if let Some(timeout) = options.timeout {
command = command.with_timeout(timeout);
}
if let Some(signal) = cancel {
command = command.with_signal(signal);
}
command
.with_args(args)
.build()
.output()
.map_err(|e| e.into())
}
/// Get the MAC address of the device's ethernet interface (eth0).
///
/// # Returns
/// * `Result<MacAddress>` - The MAC address as a `MacAddress` struct.
///
/// # Example
/// ```rust
/// use radb_client::types::{Client, ConnectionType};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// let mac = client.get_mac_address().unwrap();
/// println!("MAC address: {}", mac);
/// ```
pub fn get_mac_address(&self) -> Result<MacAddress> {
// Returns the device mac-address
let output = self.shell().cat("/sys/class/net/eth0/address")?;
let mac_address_str = Arg::as_str(&output)?.trim_end();
let mac_address = MacAddress::try_from(mac_address_str)?;
Ok(mac_address)
}
/// Get the MAC address of the device's WLAN interface (wlan0).
///
/// # Returns
/// * `Result<MacAddress>` - The MAC address as a `MacAddress` struct.
///
/// # Example
/// ```rust
/// use radb_client::types::{Client, ConnectionType};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// let mac = client.get_wlan_address().unwrap();
/// println!("WLAN MAC address: {}", mac);
/// ```
pub fn get_wlan_address(&self) -> Result<MacAddress> {
// Returns the wlan mac-address
let output = self.shell().cat("/sys/class/net/wlan0/address")?;
let mac_address_str = Arg::as_str(&output)?.trim_end();
let mac_address = MacAddress::try_from(mac_address_str)?;
Ok(mac_address)
}
/// Get the boot ID of the device (from /proc/sys/kernel/random/boot_id).
///
/// # Returns
/// * `Result<Uuid>` - The boot ID as a `Uuid` struct.
///
/// # Example
/// ```rust
/// use radb_client::types::{Client, ConnectionType};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// let boot_id = client.get_boot_id().unwrap();
/// println!("Boot ID: {}", boot_id);
/// ```
pub fn get_boot_id(&self) -> Result<Uuid> {
// Returns the boot id
let output = self.shell().cat("/proc/sys/kernel/random/boot_id")?;
let output_str = Arg::as_str(&output)?.trim();
let boot_id = output_str.try_into()?;
Ok(boot_id)
}
/// Disable verity on the device.
///
/// # Returns
/// * `Result<()>` - Ok if successful, or an error if the command fails.
///
/// # Example
/// ```rust
/// use radb_client::types::{Client, ConnectionType};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// client.disable_verity().unwrap();
/// ```
pub fn disable_verity(&self) -> Result<()> {
// Disable verity
let output = CommandBuilder::from(self)
.arg("disable-verity")
.build()
.output()?;
if !output.success() {
Err(output.into())
} else {
Ok(())
}
}
pub fn enable_verity(&self) -> Result<()> {
// Enable verity
let output = CommandBuilder::from(self)
.arg("enable-verity")
.build()
.output()?;
println!("output: {output:?}");
if !output.success() {
Err(output.into())
} else {
Ok(())
}
}
pub fn pull<S, T>(&self, src: S, dst: T) -> Result<Output>
where
S: Arg,
T: Arg,
{
let mut command = CommandBuilder::from(self);
command = command.arg("pull").arg(src.as_str()?).arg(dst.as_str()?);
command.build().output().map_err(|e| e.into())
}
pub fn push<S, T>(&self, src: S, dst: T) -> Result<Output>
where
S: Arg,
T: Arg,
{
let mut command = CommandBuilder::from(self);
command = command.arg("push").arg(src.as_str()?).arg(dst.as_str()?);
command.build().output().map_err(|e| e.into())
}
pub fn install<T>(&self, path: T, install_options: Option<AdbInstallOptions>) -> Result<()>
where
T: Arg,
{
let mut args = vec!["install".into()];
match install_options {
None => {}
Some(options) => args.extend(options),
}
args.push(path.as_str()?.into());
super::shell::handle_result(self.adb.exec(self.addr, args, None, None, self.debug)?)
}
/// Uninstall an application package from the device.
///
/// # Arguments
/// * `package_name` - The name of the package to uninstall.
/// * `options` - Optional uninstall options.
///
/// # Examples
/// ```rust
/// use radb_client::types::{Client, ConnectionType};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// client.connect(None).unwrap();
/// client.uninstall("com.example.app", None).unwrap();
/// ```
pub fn uninstall(&self, package_name: &str, options: Option<UninstallOptions>) -> Result<()> {
let mut args: Vec<OsString> = vec!["uninstall".into()];
match options {
None => {}
Some(options) => args.extend(options.into_iter()),
}
args.push(package_name.into());
super::shell::handle_result(self.adb.exec(self.addr, args, None, None, self.debug)?)
}
/// Return the client shell interface for running shell commands.
///
/// # Examples
/// ```rust
/// use radb_client::types::{Client, ConnectionType};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap();
/// let shell = client.shell();
/// let user = shell.whoami().unwrap();
/// println!("Current user: {}", user);
/// ```
pub fn shell(&self) -> Shell<'_> {
// return the client shell interface
Shell { parent: self }
}
/// Enable or disable debug tracing for the client connection.
///
/// # Arguments
/// * `debug` - If true, enables debug output for all commands.
///
/// # Examples
/// ```rust
/// use radb_client::types::{Client, ConnectionType};
/// let conn = ConnectionType::try_from_ip("192.168.1.101").unwrap();
/// let client = Client::try_from(conn).unwrap().with_debug(true);
/// ```
pub fn with_debug(mut self, debug: bool) -> Self {
self.debug = debug;
self
}
}
#[cfg(test)]
mod test {
use std::fs::{remove_file, File};
use std::io::BufRead;
use std::net::SocketAddr;
use std::time::Duration;
use chrono::Local;
use simple_cmd::prelude::OutputExt;
use crate::error::Error;
use crate::test::test::{
client_from, connect_client, connect_emulator, connect_tcp_ip_client,
connection_from_tcpip, init_log, test_files_dir,
};
use crate::types::{
AdbInstallOptions, Client, ConnectionType, LogcatLevel, LogcatOptions, LogcatTag, Reconnect,
};
#[test]
fn test_new_client() {
let address: ConnectionType = connection_from_tcpip();
let mut client = client_from(address);
client = client.with_debug(true);
let connected = client.is_connected();
println!("connected: {}", connected);
let mut client = connect_emulator();
client = client.with_debug(true);
let connected = client.is_connected();
println!("connected: {}", connected);
}
#[test]
fn test_connect() {
init_log();
let client = connect_tcp_ip_client();
let _ = client
.connect(Some(Duration::from_secs(1)))
.expect("failed to connect");
}
#[test]
fn test_disconnect() {
init_log();
let client = connect_tcp_ip_client();
let disconnected = client.disconnect().expect("failed to disconnect");
println!("disconnected: {disconnected}");
}
#[test]
fn test_try_disconnect() {
init_log();
let client = connect_emulator();
let disconnected = client.try_disconnect().expect("failed to disconnect");
println!("disconnected: {disconnected}");
}
#[test]
fn test_wait_for_device() {
init_log();
let client = connect_client(connection_from_tcpip());
client
.wait_for_device(Some(Duration::from_secs(1)))
.expect("failed to wait for device");
let client = connect_emulator();
client
.wait_for_device(None)
.expect("failed to wait for emulator");
}
#[test]
fn test_get_wakefulness() {
init_log();
let client = connect_client(connection_from_tcpip());
let awake = client
.get_wakefulness()
.expect("failed to get awake status");
println!("awake status: {awake}");
let client = connect_emulator();
let awake = client
.get_wakefulness()
.expect("failed to get awake status");
println!("awake status: {awake}");
}
#[test]
fn test_is_root() {
init_log();
let client = connect_emulator();
let is_root = client.is_root().expect("failed to get root status");
println!("client {client} is root: {is_root}");
}
#[test]
fn test_root() {
init_log();
let client = connect_client(connection_from_tcpip());
if client.is_root().expect("failed to get user") {
client.unroot().expect("failed to unroot");
}
let is_root = client.is_root().expect("failed to get user");
assert!(!is_root);
let success = client.root().expect("failed to root client");
assert!(success);
let is_root = client.is_root().expect("failed to get user status");
assert!(is_root);
client.unroot().expect("failed to unroot");
let is_root = client.is_root().expect("failed to get user status");
assert!(!is_root);
let client = connect_emulator();
let success = client.root();
if let Err(Error::CommandError(simple_cmd::Error::CommandError(err))) = success {
println!("expected error: {}", err);
return;
} else if let Ok(false) = success {
// ok
} else {
println!("err = {:?}", success);
assert!(false, "incorrect error received");
}
}
#[test]
fn test_save_screencap_locally() {
init_log();
let client = connect_client(connection_from_tcpip());
let output = dirs::desktop_dir().unwrap().join("screencap.png");
let output_path = output.as_path();
println!("target local file: {:?}", output_path.to_str());
if output.exists() {
remove_file(output_path).expect("Error deleting file");
}
let file = File::create(output_path).expect("failed to create file");
let _result = client
.save_screencap(file)
.expect("failed to save screencap");
println!("ok. done => {:?}", output);
remove_file(output_path).unwrap();
}
#[test]
pub fn test_copy_screencap() {
init_log();
let client = connect_emulator();
let _result = client.copy_screencap().expect("failed to copy screencap");
}
#[test]
pub fn test_reboot() {
init_log();
let client = connect_emulator();
let _result = client.reboot(None);
}
#[test]
fn test_remount() {
init_log();
let client = connect_emulator();
client
.remount(true)
.expect_err("remount should have returned an error");
let client = connect_tcp_ip_client();
client.root().expect("failed to root client");
client.remount(true).expect("failed to remount");
}
#[test]
fn test_get_serialno() {
init_log();
let client = connect_emulator();
let serial_no = client.get_seriano().expect("failed to get serial number");
assert!(serial_no.starts_with("emulator-"));
println!("serial: {serial_no}");
let client = connect_tcp_ip_client();
let serial_no = client.get_seriano().expect("failed to get serial number");
let ip_addr = serial_no
.parse::<SocketAddr>()
.expect("failed to parse serial no");
println!("serial: {ip_addr}");
}
#[test]
fn test_reconnect() {
init_log();
let client = connect_emulator();
client.reconnect(None).expect("failed to reconnect");
client
.reconnect(Some(Reconnect::Device))
.expect("failed to reconnect device");
client
.reconnect(Some(Reconnect::Offline))
.expect("failed to reconnect offline");
let client = Client::try_from(
ConnectionType::try_from_ip("192.168.1.99:5555").expect("failed to parse ip address"),
)
.expect("failed to create client");
client.reconnect(None).expect("failed to reconnect");
client
.reconnect(Some(Reconnect::Device))
.expect("failed to reconnect");
client
.reconnect(Some(Reconnect::Offline))
.expect("failed to reconnect");
}
#[test]
fn test_bugreport() {
let client = connect_emulator();
let output = dirs::desktop_dir().unwrap().join("bugreport.zip");
if output.exists() {
remove_file(output.as_path()).expect("failed to delete file");
}
let _ = client
.bug_report(Some(output.clone()))
.expect("failed to generate bugreport");
assert!(output.exists());
remove_file(output.as_path()).expect("failed to delete file");
}
#[test]
fn test_clear_logcat() {
let client = connect_emulator();
let _ = client.clear_logcat().expect("failed to clear logcat");
}
#[test]
fn test_get_mac_address() {
let client = connect_tcp_ip_client();
client.root().expect("failed to root");
let mac_address = client
.get_mac_address()
.expect("failed to read mac address");
println!("mac address: {}", mac_address);
}
#[test]
fn test_get_wlan_address() {
let client = connect_tcp_ip_client();
client.root().expect("failed to root");
match client.get_wlan_address() {
Ok(mac_address) => {
println!("wlan mac address: {}", mac_address);
}
Err(err) => {
eprintln!("unable to fetch wlan address: {err}");
}
}
}
#[test]
fn test_get_boot_id() {
let client = connect_tcp_ip_client();
client.root().expect("failed to root");
let boot_id = client.get_boot_id().expect("failed to read boot_id");
println!("boot_id: {boot_id}");
}
#[test]
fn test_disable_verity() {
let client = connect_tcp_ip_client();
client.root().expect("failed to root");
let _ = client.disable_verity().expect("failed to disable verity");
}
#[test]
fn test_enable_verity() {
let client = connect_tcp_ip_client();
client.root().expect("failed to root");
let _ = client.enable_verity().expect("failed to enable verity");
}
#[test]
fn test_logcat() {
init_log();
let client = connect_tcp_ip_client();
let timeout = Some(Duration::from_secs(3));
let since = Some(Local::now() - chrono::Duration::seconds(600));
let options = LogcatOptions {
expr: None,
dump: false,
filename: None,
tags: Some(vec![LogcatTag {
name: "tl.RestClient".to_string(),
level: LogcatLevel::Debug,
}]),
format: None,
since,
pid: None,
timeout,
};
let output = client.logcat(options, None);
match output {
Ok(o) => {
if o.status.success() || o.kill() || o.interrupt() {
let mut index = 0;
let stdout = o.stdout;
let lines = stdout.lines().map(|l| l.unwrap());
for line in lines {
println!("{}", line);
index = index + 1;
if index > 10 {
break;
}
}
} else if o.error() {
panic!("{:?}", o);
} else {
panic!("{:?}", o);
}
}
Err(err) => {
panic!("{}", err);
}
}
}
#[test]
fn test_install() {
init_log();
let client = connect_emulator();
let test_files_dir = test_files_dir();
println!("test_files_dir: {:?}", test_files_dir);
let path = test_files_dir.join("app-debug.apk");
let package_name = "it.sephiroth.android.app.app";
let is_installed = client
.shell()
.pm()
.is_installed(package_name, None)
.expect("failed to check if package is installed");
if is_installed {
client
.uninstall(package_name, None)
.expect("failed to uninstall package");
assert!(!client
.shell()
.pm()
.is_installed(package_name, None)
.unwrap());
}
client
.install(
path,
Some(AdbInstallOptions {
allow_version_downgrade: false,
allow_test_package: false,
replace: false,
forward_lock: false,
install_external: false,
grant_permissions: false,
instant: false,
}),
)
.expect("failed to install apk");
assert!(client
.shell()
.pm()
.is_installed(package_name, None)
.expect("failed to check if package is installed"));
}
}