Debian Codegraph @

debian/missing-sources/gio/src/subclass/file/tests.rs

raw
1 // Take a look at the license at the top of the repository in the LICENSE file.
2
3 // The following tests rely on a custom type `MyCustomFile` that extends the existing GIO type `MyFile`. Both types implement the interface `gio::auto::File`.
4 // For each virtual method defined in interface `crate::ffi::GFileIface`, a test checks that `MyCustomFile` and `MyFile` return the same results.
5
6 use std::path::{Path, PathBuf};
7
8 use futures_channel::oneshot;
9
10 use super::*;
11 use crate::{FileMonitorEvent, FileType, prelude::*};
12
13 mod imp {
14 use super::*;
15 use crate::{FileAttributeInfoFlags, FileAttributeType, subclass::prelude::*};
16 use glib::ValueDelegate;
17 use std::{
18 cell::{Cell, RefCell},
19 hash::{self, Hash, Hasher},
20 };
21
22 const SCHEME: &str = "myfile";
23
24 // Define custom types to use for properties in `MyFile`.
25 #[derive(Copy, Clone, Debug, PartialEq, ValueDelegate)]
26 #[value_delegate(from = ffi::GFileType)]
27 pub struct MyFileType(pub FileType);
28
29 impl Default for MyFileType {
30 fn default() -> Self {
31 Self(FileType::Unknown)
32 }
33 }
34
35 impl From<ffi::GFileType> for MyFileType {
36 fn from(v: ffi::GFileType) -> Self {
37 Self(unsafe { FileType::from_glib(v) })
38 }
39 }
40
41 impl<'a> From<&'a MyFileType> for ffi::GFileType {
42 fn from(v: &'a MyFileType) -> Self {
43 v.0.into_glib()
44 }
45 }
46
47 impl From<MyFileType> for ffi::GFileType {
48 fn from(v: MyFileType) -> Self {
49 From::from(&v)
50 }
51 }
52
53 #[derive(Default, Copy, Clone, Debug, PartialEq, ValueDelegate)]
54 #[value_delegate(from = u8)]
55 pub enum MyFileState {
56 #[default]
57 DoesNotExist,
58 Exist,
59 Deleted,
60 Trashed,
61 }
62
63 impl From<u8> for MyFileState {
64 fn from(v: u8) -> Self {
65 match v {
66 1 => Self::Exist,
67 2 => Self::Deleted,
68 3 => Self::Trashed,
69 _ => Self::DoesNotExist,
70 }
71 }
72 }
73
74 impl<'a> From<&'a MyFileState> for u8 {
75 fn from(v: &'a MyFileState) -> Self {
76 match v {
77 MyFileState::DoesNotExist => 0,
78 MyFileState::Exist => 1,
79 MyFileState::Deleted => 2,
80 MyFileState::Trashed => 3,
81 }
82 }
83 }
84
85 impl From<MyFileState> for u8 {
86 fn from(v: MyFileState) -> Self {
87 From::from(&v)
88 }
89 }
90
91 // Define `MyFile` as a subclass of `File`.
92 #[derive(glib::Properties, Default, Debug)]
93 #[properties(wrapper_type = super::MyFile)]
94 pub struct MyFile {
95 #[property(construct_only)]
96 path: RefCell<PathBuf>,
97 #[property(construct_only)]
98 xattrs: RefCell<Vec<String>>,
99 #[property(construct_only)]
100 children: RefCell<Vec<String>>,
101 #[property(construct_only)]
102 type_: Cell<MyFileType>,
103 #[property(construct_only)]
104 state: Cell<MyFileState>,
105 }
106
107 #[glib::object_subclass]
108 impl ObjectSubclass for MyFile {
109 const NAME: &'static str = "MyFile";
110 type Type = super::MyFile;
111 type Interfaces = (File,);
112 }
113
114 #[glib::derived_properties]
115 impl ObjectImpl for MyFile {}
116
117 // Implements `FileImpl` with custom implementation.
118 impl FileImpl for MyFile {
119 const SUPPORT_THREAD_CONTEXT: bool = true;
120
121 fn dup(&self) -> File {
122 Self::Type::new(self.path.borrow().clone()).upcast()
123 }
124
125 fn hash(&self) -> u32 {
126 let mut hasher = hash::DefaultHasher::new();
127 self.path.borrow().hash(&mut hasher);
128 hasher.finish() as u32
129 }
130
131 fn equal(&self, file2: &File) -> bool {
132 match file2.downcast_ref::<Self::Type>() {
133 Some(file2) => self.path == file2.imp().path,
134 None => false,
135 }
136 }
137
138 fn is_native(&self) -> bool {
139 false
140 }
141
142 fn has_uri_scheme(&self, uri_scheme: &str) -> bool {
143 uri_scheme == SCHEME
144 }
145
146 fn uri_scheme(&self) -> Option<String> {
147 Some(SCHEME.to_owned())
148 }
149
150 fn basename(&self) -> Option<PathBuf> {
151 self.path.borrow().file_name().map(PathBuf::from)
152 }
153
154 fn path(&self) -> Option<PathBuf> {
155 Some(self.path.borrow().to_path_buf())
156 }
157
158 fn uri(&self) -> String {
159 format!("{}://{}", SCHEME, self.path.borrow().to_string_lossy())
160 }
161
162 fn parse_name(&self) -> String {
163 self.uri()
164 }
165
166 fn parent(&self) -> Option<File> {
167 self.path
168 .borrow()
169 .parent()
170 .map(|parent| Self::Type::new(parent).upcast())
171 }
172
173 fn has_prefix(&self, prefix: &File) -> bool {
174 if let Some(prefix_path) = prefix.path() {
175 self.path.borrow().starts_with(prefix_path)
176 } else {
177 false
178 }
179 }
180
181 fn relative_path(&self, descendant: &File) -> Option<PathBuf> {
182 match descendant.downcast_ref::<Self::Type>() {
183 Some(descendant) => descendant
184 .imp()
185 .path
186 .borrow()
187 .as_path()
188 .strip_prefix(self.path.borrow().as_path())
189 .ok()
190 .map(PathBuf::from),
191 None => None,
192 }
193 }
194
195 fn resolve_relative_path(&self, relative_path: impl AsRef<std::path::Path>) -> File {
196 let relative_pathbuf = PathBuf::from(relative_path.as_ref());
197 let path = if relative_pathbuf.is_absolute() {
198 relative_pathbuf
199 } else {
200 self.path.borrow().join(relative_pathbuf)
201 };
202 Self::Type::new(path).upcast()
203 }
204
205 fn child_for_display_name(&self, display_name: &str) -> Result<File, Error> {
206 let path = self.path.borrow().join(display_name);
207 Ok(Self::Type::new(path).upcast())
208 }
209
210 fn enumerate_children(
211 &self,
212 _attributes: &str,
213 _flags: FileQueryInfoFlags,
214 _cancellable: Option<&Cancellable>,
215 ) -> Result<FileEnumerator, Error> {
216 if self.type_.get().0 != FileType::Directory {
217 Err(Error::new(
218 IOErrorEnum::NotDirectory,
219 "File is not a directory",
220 ))
221 } else if self.state.get() != MyFileState::Exist {
222 Err(Error::new(IOErrorEnum::NotFound, "File does not exist"))
223 } else {
224 let enumerator =
225 super::MyFileEnumerator::new(self.children.borrow().clone()).upcast();
226 Ok(enumerator)
227 }
228 }
229
230 fn query_info(
231 &self,
232 attributes: &str,
233 _flags: FileQueryInfoFlags,
234 _cancellable: Option<&Cancellable>,
235 ) -> Result<FileInfo, Error> {
236 let file_info = FileInfo::new();
237 let (mut name, mut xattr) = (false, Vec::new());
238 for attribute in attributes.split(",") {
239 let (n, x) = match attribute {
240 "*" => (true, "*"),
241 "standard::*" | "standard::name" => (true, ""),
242 attribute if attribute.starts_with("xattr::") => (false, attribute),
243 _ => {
244 return Err(Error::new(
245 IOErrorEnum::InvalidArgument,
246 &format!("Querying attributes {attribute} not supported for MyFile"),
247 ));
248 }
249 };
250 name |= n;
251 xattr.push(x);
252 }
253 if name {
254 file_info.set_name(
255 self.path
256 .borrow()
257 .file_name()
258 .map_or("none", |s| s.to_str().unwrap_or("none")),
259 );
260 }
261 if !xattr.is_empty() {
262 let all = xattr.contains(&"xattr::*");
263 for xattr in self.xattrs.borrow().iter() {
264 let (key, value) = xattr.split_once('=').unwrap_or((xattr, ""));
265 if all || xattr.contains(key) {
266 file_info.set_attribute(key, value);
267 }
268 }
269 }
270 Ok(file_info)
271 }
272
273 fn query_filesystem_info(
274 &self,
275 attributes: &str,
276 cancellable: Option<&Cancellable>,
277 ) -> Result<FileInfo, Error> {
278 self.query_info(attributes, FileQueryInfoFlags::NONE, cancellable)
279 }
280
281 fn find_enclosing_mount(&self, _cancellable: Option<&Cancellable>) -> Result<Mount, Error> {
282 Err(Error::new(
283 IOErrorEnum::NotSupported,
284 "Find enclosing mount not supported for MyFile",
285 ))
286 }
287
288 fn set_display_name(
289 &self,
290 display_name: &str,
291 _query_writable_namespaces_async: Option<&Cancellable>,
292 ) -> Result<File, Error> {
293 let path = match self.path.borrow().parent() {
294 Some(parent) => parent.join(display_name),
295 None => PathBuf::from(display_name),
296 };
297 Ok(Self::Type::new(path).upcast())
298 }
299
300 fn query_settable_attributes(
301 &self,
302 _cancellable: Option<&Cancellable>,
303 ) -> Result<FileAttributeInfoList, Error> {
304 let file_attribute_info_list = FileAttributeInfoList::new();
305 file_attribute_info_list.add(
306 "standard::name",
307 FileAttributeType::String,
308 FileAttributeInfoFlags::NONE,
309 );
310 for xattr in self.xattrs.borrow().iter() {
311 let (key, _value) = xattr.split_once('=').unwrap_or((xattr, ""));
312 file_attribute_info_list.add(
313 &format!("xattr::{key}"),
314 FileAttributeType::String,
315 FileAttributeInfoFlags::NONE,
316 );
317 }
318 Ok(file_attribute_info_list)
319 }
320
321 fn query_writable_namespaces(
322 &self,
323 _cancellable: Option<&Cancellable>,
324 ) -> Result<FileAttributeInfoList, Error> {
325 let file_attribute_info_list = FileAttributeInfoList::new();
326 file_attribute_info_list.add(
327 "xattr",
328 FileAttributeType::String,
329 FileAttributeInfoFlags::NONE,
330 );
331 Ok(file_attribute_info_list)
332 }
333
334 fn set_attribute<'a>(
335 &self,
336 attribute: &str,
337 value: impl Into<FileAttributeValue<'a>>,
338 _flags: FileQueryInfoFlags,
339 _cancellable: Option<&Cancellable>,
340 ) -> Result<(), Error> {
341 let value = value.into();
342 match (attribute, value.type_(), value.as_ptr()) {
343 ("standard::name", FileAttributeType::String, p) => {
344 let name = unsafe {
345 <String as FromGlibPtrNone<*mut libc::c_char>>::from_glib_none(p as *mut _)
346 };
347 self.path.borrow_mut().set_file_name(name);
348 Ok(())
349 }
350 (attribute, FileAttributeType::String, p) if attribute.starts_with("xattr:") => {
351 let value = unsafe {
352 <String as FromGlibPtrNone<*mut libc::c_char>>::from_glib_none(p as *mut _)
353 };
354 self.xattrs
355 .borrow_mut()
356 .push(format!("{attribute}={value}"));
357 Ok(())
358 }
359 (attribute, type_, _) => Err(Error::new(
360 IOErrorEnum::InvalidArgument,
361 &format!(
362 "Setting attribute '{attribute}' ({type_:?}) not supported for MyFile"
363 ),
364 )),
365 }
366 }
367
368 fn set_attributes_from_info(
369 &self,
370 info: &FileInfo,
371 flags: FileQueryInfoFlags,
372 cancellable: Option<&Cancellable>,
373 ) -> Result<(), Error> {
374 for attribute in info.list_attributes(None) {
375 let value = info.attribute_as_string(attribute.as_str()).unwrap();
376 self.set_attribute(attribute.as_str(), value.as_str(), flags, cancellable)?;
377 }
378 Ok(())
379 }
380
381 fn read_fn(&self, _cancellable: Option<&Cancellable>) -> Result<FileInputStream, Error> {
382 Err(Error::new(
383 IOErrorEnum::NotSupported,
384 "Reading not supported for MyFile",
385 ))
386 }
387
388 fn append_to(
389 &self,
390 _flags: FileCreateFlags,
391 _cancellable: Option<&Cancellable>,
392 ) -> Result<FileOutputStream, Error> {
393 Err(Error::new(
394 IOErrorEnum::NotSupported,
395 "Appending to file not supported for MyFile",
396 ))
397 }
398
399 fn create(
400 &self,
401 _flags: FileCreateFlags,
402 _cancellable: Option<&Cancellable>,
403 ) -> Result<FileOutputStream, Error> {
404 Err(Error::new(
405 IOErrorEnum::NotSupported,
406 "Creating file not supported for MyFile",
407 ))
408 }
409
410 fn replace(
411 &self,
412 _etag: Option<&str>,
413 _make_backup: bool,
414 _flags: FileCreateFlags,
415 _cancellable: Option<&Cancellable>,
416 ) -> Result<FileOutputStream, Error> {
417 Err(Error::new(
418 IOErrorEnum::NotSupported,
419 "Replacing file not supported for MyFile",
420 ))
421 }
422
423 fn delete(&self, _cancellable: Option<&Cancellable>) -> Result<(), Error> {
424 if self.state.get() != MyFileState::Exist {
425 Err(Error::new(IOErrorEnum::NotFound, "File does not exist"))
426 } else {
427 self.state.set(MyFileState::Deleted);
428 Ok(())
429 }
430 }
431
432 fn trash(&self, _cancellable: Option<&Cancellable>) -> Result<(), Error> {
433 if self.state.get() != MyFileState::Exist {
434 Err(Error::new(IOErrorEnum::NotFound, "File does not exist"))
435 } else {
436 self.state.set(MyFileState::Trashed);
437 Ok(())
438 }
439 }
440
441 fn make_directory(&self, _cancellable: Option<&Cancellable>) -> Result<(), Error> {
442 if self.state.get() == MyFileState::Exist {
443 Err(Error::new(IOErrorEnum::Exists, "File already exists"))
444 } else {
445 self.state.set(MyFileState::Exist);
446 self.type_.set(MyFileType(FileType::Directory));
447 Ok(())
448 }
449 }
450
451 fn make_symbolic_link(
452 &self,
453 _symlink_value: impl AsRef<std::path::Path>,
454 _cancellable: Option<&Cancellable>,
455 ) -> Result<(), Error> {
456 if self.state.get() == MyFileState::Exist {
457 Err(Error::new(IOErrorEnum::Exists, "File already exists"))
458 } else {
459 self.state.set(MyFileState::Exist);
460 self.type_.set(MyFileType(FileType::SymbolicLink));
461 Ok(())
462 }
463 }
464
465 fn copy(
466 source: &File,
467 destination: &File,
468 flags: FileCopyFlags,
469 cancellable: Option<&Cancellable>,
470 progress_callback: Option<&mut dyn FnMut(i64, i64)>,
471 ) -> Result<(), Error> {
472 let source_exists = source.downcast_ref::<Self::Type>().map_or_else(
473 || source.query_exists(cancellable),
474 |f| f.imp().state.get() == MyFileState::Exist,
475 );
476 let source_type = source.downcast_ref::<Self::Type>().map_or_else(
477 || source.query_file_type(FileQueryInfoFlags::NONE, cancellable),
478 |f| f.imp().type_.get().0,
479 );
480 let destination_exists = destination.downcast_ref::<Self::Type>().map_or_else(
481 || destination.query_exists(cancellable),
482 |f| f.imp().state.get() == MyFileState::Exist,
483 );
484 let destination_type = destination.downcast_ref::<Self::Type>().map_or_else(
485 || destination.query_file_type(FileQueryInfoFlags::NONE, cancellable),
486 |f| f.imp().type_.get().0,
487 );
488 let overwrite = flags.contains(FileCopyFlags::OVERWRITE);
489 match (
490 source_exists,
491 source_type,
492 destination_exists,
493 destination_type,
494 overwrite,
495 ) {
496 (false, _, _, _, _) => {
497 Err(Error::new(IOErrorEnum::NotFound, "Source does not exist"))
498 }
499 (true, _, true, _, false) => Err(Error::new(
500 IOErrorEnum::Exists,
501 "Destination already exists",
502 )),
503 (true, FileType::Regular, true, FileType::Directory, true) => Err(Error::new(
504 IOErrorEnum::IsDirectory,
505 "Cannot overwrite a directory with a file",
506 )),
507 (true, FileType::Directory, true, FileType::Directory, true) => Err(Error::new(
508 IOErrorEnum::WouldMerge,
509 "Cannot overwrite a directory with a directory",
510 )),
511 (true, FileType::Directory, false, _, _) => Err(Error::new(
512 IOErrorEnum::WouldRecurse,
513 "Cannot handle recursive copy of source directory",
514 )),
515 (true, FileType::Directory, true, FileType::Regular, true) => Err(Error::new(
516 IOErrorEnum::WouldRecurse,
517 "Cannot handle recursive copy of source directory",
518 )),
519 _ => {
520 // Simulate a copy operation
521 if let Some(callback) = progress_callback {
522 for i in 0..10 {
523 // Simulate progress
524 callback(i * 10_i64, 100);
525 }
526 }
527 if let Some(dest) = destination.downcast_ref::<Self::Type>() {
528 dest.imp().state.set(MyFileState::Exist);
529 dest.imp().type_.set(MyFileType(source_type));
530 }
531 Ok(())
532 }
533 }
534 }
535
536 fn move_(
537 source: &File,
538 destination: &File,
539 flags: FileCopyFlags,
540 cancellable: Option<&Cancellable>,
541 progress_callback: Option<&mut dyn FnMut(i64, i64)>,
542 ) -> Result<(), Error> {
543 let source_exists = source.downcast_ref::<Self::Type>().map_or_else(
544 || source.query_exists(cancellable),
545 |f| f.imp().state.get() == MyFileState::Exist,
546 );
547 let source_type = source.downcast_ref::<Self::Type>().map_or_else(
548 || source.query_file_type(FileQueryInfoFlags::NONE, cancellable),
549 |f| f.imp().type_.get().0,
550 );
551 let destination_exists = destination.downcast_ref::<Self::Type>().map_or_else(
552 || destination.query_exists(cancellable),
553 |f| f.imp().state.get() == MyFileState::Exist,
554 );
555 let destination_type = destination.downcast_ref::<Self::Type>().map_or_else(
556 || destination.query_file_type(FileQueryInfoFlags::NONE, cancellable),
557 |f| f.imp().type_.get().0,
558 );
559 let overwrite = flags.contains(FileCopyFlags::OVERWRITE);
560 match (
561 source_exists,
562 source_type,
563 destination_exists,
564 destination_type,
565 overwrite,
566 ) {
567 (false, _, _, _, _) => {
568 Err(Error::new(IOErrorEnum::NotFound, "Source does not exist"))
569 }
570 (true, _, true, _, false) => Err(Error::new(
571 IOErrorEnum::Exists,
572 "Destination already exists",
573 )),
574 (true, FileType::Regular, true, FileType::Directory, true) => Err(Error::new(
575 IOErrorEnum::IsDirectory,
576 "Cannot overwrite a directory with a file",
577 )),
578 (true, FileType::Directory, true, FileType::Directory, true) => Err(Error::new(
579 IOErrorEnum::WouldMerge,
580 "Cannot overwrite a directory with a directory",
581 )),
582 (true, FileType::Directory, false, _, _) => Err(Error::new(
583 IOErrorEnum::WouldRecurse,
584 "Cannot handle recursive copy of source directory",
585 )),
586 (true, FileType::Directory, true, FileType::Regular, true) => Err(Error::new(
587 IOErrorEnum::WouldRecurse,
588 "Cannot handle recursive copy of source directory",
589 )),
590 _ => {
591 // Simulate a move operation
592 if let Some(callback) = progress_callback {
593 for i in 0..10 {
594 // Simulate progress
595 callback(i * 10_i64, 100);
596 }
597 }
598 if let Some(dest) = destination.downcast_ref::<Self::Type>() {
599 dest.imp().state.set(MyFileState::Exist);
600 dest.imp().type_.set(MyFileType(source_type));
601 }
602 Ok(())
603 }
604 }
605 }
606
607 fn mount_mountable<P: FnOnce(&Self::Type, &AsyncResult) + 'static>(
608 &self,
609 _flags: MountMountFlags,
610 _mount_operation: Option<&MountOperation>,
611 cancellable: Option<&Cancellable>,
612 callback: Option<P>,
613 ) {
614 let callback = callback.expect("callback is required");
615 let task = unsafe {
616 crate::LocalTask::new(
617 Some(self.obj().as_ref()),
618 cancellable,
619 move |task: crate::LocalTask<File>, source: Option<&Self::Type>| {
620 callback(source.unwrap(), task.upcast_ref::<AsyncResult>())
621 },
622 )
623 };
624 task.return_result(Err(Error::new(
625 IOErrorEnum::NotSupported,
626 "Mounting mountable not supported for MyFile",
627 )));
628 }
629
630 fn mount_mountable_finish(&self, res: &AsyncResult) -> Result<File, Error> {
631 unsafe {
632 res.downcast_ref::<crate::LocalTask<File>>()
633 .expect("res expected to be a LocalTask")
634 .to_owned()
635 .propagate()
636 }
637 }
638
639 fn unmount_mountable<P: FnOnce(&Self::Type, &AsyncResult) + 'static>(
640 &self,
641 _flags: MountUnmountFlags,
642 cancellable: Option<&Cancellable>,
643 callback: Option<P>,
644 ) {
645 let callback = callback.expect("callback is required");
646 let task = unsafe {
647 crate::LocalTask::new(
648 Some(self.obj().as_ref()),
649 cancellable,
650 move |task: crate::LocalTask<bool>, source: Option<&Self::Type>| {
651 callback(source.unwrap(), task.upcast_ref::<AsyncResult>())
652 },
653 )
654 };
655 task.return_result(Err(Error::new(
656 IOErrorEnum::NotSupported,
657 "Unmounting mountable not supported for MyFile",
658 )));
659 }
660
661 fn unmount_mountable_finish(&self, res: &AsyncResult) -> Result<(), Error> {
662 unsafe {
663 res.downcast_ref::<crate::LocalTask<bool>>()
664 .expect("res expected to be a LocalTask")
665 .to_owned()
666 .propagate()
667 .map(|_| ())
668 }
669 }
670
671 fn eject_mountable<P: FnOnce(&Self::Type, &AsyncResult) + 'static>(
672 &self,
673 _flags: MountUnmountFlags,
674 cancellable: Option<&Cancellable>,
675 callback: Option<P>,
676 ) {
677 let callback = callback.expect("callback is required");
678 let task = unsafe {
679 crate::LocalTask::new(
680 Some(self.obj().as_ref()),
681 cancellable,
682 move |task: crate::LocalTask<bool>, source: Option<&Self::Type>| {
683 callback(source.unwrap(), task.upcast_ref::<AsyncResult>())
684 },
685 )
686 };
687 task.return_result(Err(Error::new(
688 IOErrorEnum::NotSupported,
689 "Ejecting mountable not supported for MyFile",
690 )));
691 }
692
693 fn eject_mountable_finish(&self, res: &AsyncResult) -> Result<(), Error> {
694 unsafe {
695 res.downcast_ref::<crate::LocalTask<bool>>()
696 .expect("res expected to be a LocalTask")
697 .to_owned()
698 .propagate()
699 .map(|_| ())
700 }
701 }
702
703 fn mount_enclosing_volume<P: FnOnce(&Self::Type, &AsyncResult) + 'static>(
704 &self,
705 _flags: MountMountFlags,
706 _mount_operation: Option<&MountOperation>,
707 cancellable: Option<&Cancellable>,
708 callback: Option<P>,
709 ) {
710 let callback = callback.expect("callback is required");
711 let task = unsafe {
712 crate::LocalTask::new(
713 Some(self.obj().as_ref()),
714 cancellable,
715 move |task: crate::LocalTask<bool>, source: Option<&Self::Type>| {
716 callback(source.unwrap(), task.upcast_ref::<AsyncResult>())
717 },
718 )
719 };
720 task.return_result(Err(Error::new(
721 IOErrorEnum::NotSupported,
722 "Mounting enclosing volume not supported for MyFile",
723 )));
724 }
725
726 fn mount_enclosing_volume_finish(&self, res: &AsyncResult) -> Result<(), Error> {
727 unsafe {
728 res.downcast_ref::<crate::LocalTask<bool>>()
729 .expect("res expected to be a LocalTask")
730 .to_owned()
731 .propagate()
732 .map(|_| ())
733 }
734 }
735
736 fn monitor_dir(
737 &self,
738 _flags: FileMonitorFlags,
739 _cancellable: Option<&Cancellable>,
740 ) -> Result<FileMonitor, Error> {
741 if self.type_.get().0 != FileType::Directory {
742 Err(Error::new(
743 IOErrorEnum::NotDirectory,
744 "File is not a directory",
745 ))
746 } else if self.state.get() != MyFileState::Exist {
747 Err(Error::new(IOErrorEnum::NotFound, "File does not exist"))
748 } else {
749 let monitor = super::MyFileMonitor::new().upcast();
750 Ok(monitor)
751 }
752 }
753
754 fn monitor_file(
755 &self,
756 _flags: FileMonitorFlags,
757 _cancellable: Option<&Cancellable>,
758 ) -> Result<FileMonitor, Error> {
759 if self.type_.get().0 != FileType::Regular {
760 Err(Error::new(
761 IOErrorEnum::NotRegularFile,
762 "File is not a file",
763 ))
764 } else if self.state.get() != MyFileState::Exist {
765 Err(Error::new(IOErrorEnum::NotFound, "File does not exist"))
766 } else {
767 let monitor = super::MyFileMonitor::new().upcast();
768 Ok(monitor)
769 }
770 }
771
772 fn open_readwrite(
773 &self,
774 _cancellable: Option<&Cancellable>,
775 ) -> Result<FileIOStream, Error> {
776 Err(Error::new(
777 IOErrorEnum::NotSupported,
778 "Opening file for read/write not supported for MyFile",
779 ))
780 }
781
782 fn create_readwrite(
783 &self,
784 _flags: FileCreateFlags,
785 _cancellable: Option<&Cancellable>,
786 ) -> Result<FileIOStream, Error> {
787 Err(Error::new(
788 IOErrorEnum::NotSupported,
789 "Creating file for read/write not supported for MyFile",
790 ))
791 }
792
793 fn replace_readwrite(
794 &self,
795 _etag: Option<&str>,
796 _make_backup: bool,
797 _flags: FileCreateFlags,
798 _cancellable: Option<&Cancellable>,
799 ) -> Result<FileIOStream, Error> {
800 Err(Error::new(
801 IOErrorEnum::NotSupported,
802 "Replacing file for read/write not supported for MyFile",
803 ))
804 }
805
806 fn start_mountable<P: FnOnce(&Self::Type, &AsyncResult) + 'static>(
807 &self,
808 _flags: DriveStartFlags,
809 _mount_operation: Option<&MountOperation>,
810 cancellable: Option<&Cancellable>,
811 callback: Option<P>,
812 ) {
813 let callback = callback.expect("callback is required");
814 let task = unsafe {
815 crate::LocalTask::new(
816 Some(self.obj().as_ref()),
817 cancellable,
818 move |task: crate::LocalTask<bool>, source: Option<&Self::Type>| {
819 callback(source.unwrap(), task.upcast_ref::<AsyncResult>())
820 },
821 )
822 };
823 task.return_result(Err(Error::new(
824 IOErrorEnum::NotSupported,
825 "Starting mountable not supported for MyFile",
826 )));
827 }
828
829 fn start_mountable_finish(&self, res: &AsyncResult) -> Result<(), Error> {
830 unsafe {
831 res.downcast_ref::<crate::LocalTask<bool>>()
832 .expect("res expected to be a LocalTask")
833 .to_owned()
834 .propagate()
835 .map(|_| ())
836 }
837 }
838
839 fn stop_mountable<P: FnOnce(&Self::Type, &AsyncResult) + 'static>(
840 &self,
841 _flags: MountUnmountFlags,
842 _mount_operation: Option<&MountOperation>,
843 cancellable: Option<&Cancellable>,
844 callback: Option<P>,
845 ) {
846 let callback = callback.expect("callback is required");
847 let task = unsafe {
848 crate::LocalTask::new(
849 Some(self.obj().as_ref()),
850 cancellable,
851 move |task: crate::LocalTask<bool>, source: Option<&Self::Type>| {
852 callback(source.unwrap(), task.upcast_ref::<AsyncResult>())
853 },
854 )
855 };
856 task.return_result(Err(Error::new(
857 IOErrorEnum::NotSupported,
858 "Stopping mountable not supported for MyFile",
859 )));
860 }
861
862 fn stop_mountable_finish(&self, res: &AsyncResult) -> Result<(), Error> {
863 unsafe {
864 res.downcast_ref::<crate::LocalTask<bool>>()
865 .expect("res expected to be a LocalTask")
866 .to_owned()
867 .propagate()
868 .map(|_| ())
869 }
870 }
871
872 fn unmount_mountable_with_operation<P: FnOnce(&Self::Type, &AsyncResult) + 'static>(
873 &self,
874 _flags: MountUnmountFlags,
875 _mount_operation: Option<&MountOperation>,
876 cancellable: Option<&Cancellable>,
877 callback: Option<P>,
878 ) {
879 let callback = callback.expect("callback is required");
880 let task = unsafe {
881 crate::LocalTask::new(
882 Some(self.obj().as_ref()),
883 cancellable,
884 move |task: crate::LocalTask<bool>, source: Option<&Self::Type>| {
885 callback(source.unwrap(), task.upcast_ref::<AsyncResult>())
886 },
887 )
888 };
889 task.return_result(Err(Error::new(
890 IOErrorEnum::NotSupported,
891 "Unmounting mountable with operation not supported for MyFile",
892 )));
893 }
894
895 fn unmount_mountable_with_operation_finish(&self, res: &AsyncResult) -> Result<(), Error> {
896 unsafe {
897 res.downcast_ref::<crate::LocalTask<bool>>()
898 .expect("res expected to be a LocalTask")
899 .to_owned()
900 .propagate()
901 .map(|_| ())
902 }
903 }
904
905 fn eject_mountable_with_operation<P: FnOnce(&Self::Type, &AsyncResult) + 'static>(
906 &self,
907 _flags: MountUnmountFlags,
908 _mount_operation: Option<&MountOperation>,
909 cancellable: Option<&Cancellable>,
910 callback: Option<P>,
911 ) {
912 let callback = callback.expect("callback is required");
913 let task = unsafe {
914 crate::LocalTask::new(
915 Some(self.obj().as_ref()),
916 cancellable,
917 move |task: crate::LocalTask<bool>, source: Option<&Self::Type>| {
918 callback(source.unwrap(), task.upcast_ref::<AsyncResult>())
919 },
920 )
921 };
922 task.return_result(Err(Error::new(
923 IOErrorEnum::NotSupported,
924 "Ejecting mountable with operation not supported for MyFile",
925 )));
926 }
927
928 fn eject_mountable_with_operation_finish(&self, res: &AsyncResult) -> Result<(), Error> {
929 unsafe {
930 res.downcast_ref::<crate::LocalTask<bool>>()
931 .expect("res expected to be a LocalTask")
932 .to_owned()
933 .propagate()
934 .map(|_| ())
935 }
936 }
937
938 fn poll_mountable<P: FnOnce(&Self::Type, &AsyncResult) + 'static>(
939 &self,
940 cancellable: Option<&Cancellable>,
941 callback: Option<P>,
942 ) {
943 let callback = callback.expect("callback is required");
944 let task = unsafe {
945 crate::LocalTask::new(
946 Some(self.obj().as_ref()),
947 cancellable,
948 move |task: crate::LocalTask<bool>, source: Option<&Self::Type>| {
949 callback(source.unwrap(), task.upcast_ref::<AsyncResult>())
950 },
951 )
952 };
953 task.return_result(Err(Error::new(
954 IOErrorEnum::NotSupported,
955 "Polling mountable not supported for MyFile",
956 )));
957 }
958
959 fn poll_mountable_finish(&self, res: &AsyncResult) -> Result<(), Error> {
960 unsafe {
961 res.downcast_ref::<crate::LocalTask<bool>>()
962 .expect("res expected to be a LocalTask")
963 .to_owned()
964 .propagate()
965 .map(|_| ())
966 }
967 }
968
969 fn measure_disk_usage(
970 &self,
971 _flags: FileMeasureFlags,
972 _cancellable: Option<&Cancellable>,
973 progress_callback: Option<&mut dyn FnMut(bool, u64, u64, u64)>,
974 ) -> Result<(u64, u64, u64), Error> {
975 // Simulate a measure disk operation
976 if let Some(callback) = progress_callback {
977 for i in 0..10u64 {
978 // Simulate progress
979 callback(true, i * 10, i, i * 5);
980 }
981 callback(false, 100u64, 10u64, 50u64);
982 }
983 Ok((100u64, 10u64, 50u64))
984 }
985
986 fn query_exists(&self, _cancellable: Option<&Cancellable>) -> bool {
987 true
988 }
989 }
990
991 #[derive(Default)]
992 pub struct MyCustomFile;
993
994 // Define `MyCustomFile` as a subclass of `MyFile`.
995 #[glib::object_subclass]
996 impl ObjectSubclass for MyCustomFile {
997 const NAME: &'static str = "MyCustomFile";
998 type Type = super::MyCustomFile;
999 type ParentType = super::MyFile;
1000 type Interfaces = (File,);
1001 }
1002
1003 impl ObjectImpl for MyCustomFile {}
1004
1005 // Implements `FileImpl` with default implementation, which calls the parent's implementation.
1006 impl FileImpl for MyCustomFile {}
1007
1008 impl MyFileImpl for MyCustomFile {}
1009
1010 pub(super) mod file_enumerator {
1011 use super::*;
1012
1013 // Define `MyFileEnumerator` as a subclass of `FileEnumerator`.
1014 #[derive(glib::Properties, Default, Debug)]
1015 #[properties(wrapper_type = super::MyFileEnumerator)]
1016 pub struct MyFileEnumerator {
1017 #[property(construct_only)]
1018 children: RefCell<Vec<String>>,
1019 index: Cell<i32>,
1020 }
1021
1022 #[glib::object_subclass]
1023 impl ObjectSubclass for MyFileEnumerator {
1024 const NAME: &'static str = "MyFileMyEnumerator"; // Different name than `MyFileEnumerator` defined in `FileEnumerator` tests.
1025 type Type = super::MyFileEnumerator;
1026 type ParentType = FileEnumerator;
1027 }
1028
1029 #[glib::derived_properties]
1030 impl ObjectImpl for MyFileEnumerator {
1031 fn dispose(&self) {
1032 let _ = self.obj().close(Cancellable::NONE);
1033 }
1034 }
1035
1036 // Implements `FileEnumeratorImpl` with custom implementation.
1037 impl FileEnumeratorImpl for MyFileEnumerator {
1038 fn next_file(
1039 &self,
1040 _cancellable: Option<&Cancellable>,
1041 ) -> Result<Option<FileInfo>, glib::Error> {
1042 match self.index.get() {
1043 -1 => Err(glib::Error::new::<IOErrorEnum>(
1044 IOErrorEnum::Closed,
1045 "Enumerator is closed",
1046 )),
1047 i if (i as usize) < self.children.borrow().len() => {
1048 let file_info = FileInfo::new();
1049 file_info.set_name(self.children.borrow()[i as usize].as_str());
1050 self.index.set(i + 1);
1051 Ok(Some(file_info))
1052 }
1053 _ => Ok(None),
1054 }
1055 }
1056
1057 fn close(&self, _cancellable: Option<&Cancellable>) -> (bool, Option<glib::Error>) {
1058 self.index.set(-1);
1059 (true, None)
1060 }
1061 }
1062 }
1063
1064 pub(super) mod file_monitor {
1065 use super::*;
1066
1067 // Define `MyFileMonitor` as a subclass of `FileMonitor`.
1068 #[derive(Default, Debug)]
1069 pub struct MyFileMonitor;
1070
1071 #[glib::object_subclass]
1072 impl ObjectSubclass for MyFileMonitor {
1073 const NAME: &'static str = "MyFileMyMonitor"; // Different name than `MyFileMonitor` defined in `FileMonitor` tests.
1074 type Type = super::MyFileMonitor;
1075 type ParentType = FileMonitor;
1076 }
1077
1078 impl ObjectImpl for MyFileMonitor {}
1079
1080 // Implements `FileMonitorImpl` with custom implementation.
1081 impl FileMonitorImpl for MyFileMonitor {
1082 fn cancel(&self) {}
1083 }
1084 }
1085 }
1086
1087 use imp::{MyFileState, MyFileType};
1088
1089 glib::wrapper! {
1090 pub struct MyFile(ObjectSubclass<imp::MyFile>) @implements File;
1091 }
1092
1093 impl MyFile {
1094 fn new<P: AsRef<Path>>(path: P) -> Self {
1095 Object::builder()
1096 .property("path", path.as_ref().to_path_buf())
1097 .build()
1098 }
1099
1100 fn with_xattr<'a, P: AsRef<Path>, X: AsRef<[&'a str]>>(path: P, xattrs: X) -> Self {
1101 Object::builder()
1102 .property("path", path.as_ref().to_path_buf())
1103 .property("xattrs", xattrs.as_ref())
1104 .build()
1105 }
1106
1107 fn with_children<'a, P: AsRef<Path>, C: AsRef<[&'a str]>>(path: P, children: C) -> Self {
1108 Object::builder()
1109 .property("path", path.as_ref().to_path_buf())
1110 .property("children", children.as_ref())
1111 .property("type", MyFileType(FileType::Directory))
1112 .property("state", MyFileState::Exist)
1113 .build()
1114 }
1115
1116 fn with_type_state<P: AsRef<Path>>(path: P, type_: FileType, state: MyFileState) -> Self {
1117 Object::builder()
1118 .property("path", path.as_ref().to_path_buf())
1119 .property("type", MyFileType(type_))
1120 .property("state", state)
1121 .build()
1122 }
1123 }
1124
1125 pub trait MyFileImpl: ObjectImpl + ObjectSubclass<Type: IsA<MyFile> + IsA<File>> {}
1126
1127 // To make this class subclassable we need to implement IsSubclassable
1128 unsafe impl<T: MyFileImpl + FileImpl> IsSubclassable<T> for MyFile {}
1129
1130 glib::wrapper! {
1131 pub struct MyCustomFile(ObjectSubclass<imp::MyCustomFile>) @extends MyFile, @implements File;
1132 }
1133
1134 impl MyCustomFile {
1135 fn new<P: AsRef<Path>>(path: P) -> Self {
1136 Object::builder()
1137 .property("path", path.as_ref().to_path_buf())
1138 .build()
1139 }
1140
1141 fn with_xattr<'a, P: AsRef<Path>, X: AsRef<[&'a str]>>(path: P, xattrs: X) -> Self {
1142 Object::builder()
1143 .property("path", path.as_ref().to_path_buf())
1144 .property("xattrs", xattrs.as_ref())
1145 .build()
1146 }
1147
1148 fn with_children<'a, P: AsRef<Path>, C: AsRef<[&'a str]>>(path: P, children: C) -> Self {
1149 Object::builder()
1150 .property("path", path.as_ref().to_path_buf())
1151 .property("children", children.as_ref())
1152 .property("type", MyFileType(FileType::Directory))
1153 .property("state", MyFileState::Exist)
1154 .build()
1155 }
1156
1157 fn with_type_state<P: AsRef<Path>>(path: P, type_: FileType, state: MyFileState) -> Self {
1158 Object::builder()
1159 .property("path", path.as_ref().to_path_buf())
1160 .property("type", MyFileType(type_))
1161 .property("state", state)
1162 .build()
1163 }
1164 }
1165
1166 glib::wrapper! {
1167 pub struct MyFileEnumerator(ObjectSubclass<imp::file_enumerator::MyFileEnumerator>) @extends FileEnumerator;
1168 }
1169
1170 impl MyFileEnumerator {
1171 pub fn new(children: Vec<String>) -> Self {
1172 Object::builder().property("children", children).build()
1173 }
1174 }
1175
1176 glib::wrapper! {
1177 pub struct MyFileMonitor(ObjectSubclass<imp::file_monitor::MyFileMonitor>) @extends FileMonitor;
1178 }
1179
1180 impl MyFileMonitor {
1181 pub fn new() -> Self {
1182 Object::builder().build()
1183 }
1184 }
1185
1186 impl Default for MyFileMonitor {
1187 fn default() -> Self {
1188 Self::new()
1189 }
1190 }
1191
1192 #[test]
1193 fn file_dup() {
1194 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::dup`
1195 let my_custom_file = MyCustomFile::new("/my_file");
1196 let dup = my_custom_file.dup();
1197
1198 // invoke `MyFile` implementation of `crate::ffi::GFileIface::dup`
1199 let my_file = MyFile::new("/my_file");
1200 let expected = my_file.dup();
1201
1202 // both results should equal
1203 assert!(dup.equal(&expected));
1204 }
1205
1206 // checker-ignore-item
1207 #[test]
1208 fn file_hash() {
1209 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::hash`
1210 let my_custom_file = MyCustomFile::new("/my_file");
1211 let hash = unsafe {
1212 crate::ffi::g_file_hash(
1213 <MyCustomFile as ToGlibPtr<
1214 *mut glib::subclass::basic::InstanceStruct<imp::MyCustomFile>,
1215 >>::to_glib_none(&my_custom_file)
1216 .0 as glib::ffi::gconstpointer,
1217 )
1218 };
1219
1220 // invoke `MyFile` implementation of `crate::ffi::GFileIface::hash`
1221 let my_file = MyFile::new("/my_file");
1222 let expected = unsafe {
1223 crate::ffi::g_file_hash(
1224 <MyFile as ToGlibPtr<
1225 *mut glib::subclass::basic::InstanceStruct<imp::MyFile>,
1226 >>::to_glib_none(&my_file)
1227 .0 as glib::ffi::gconstpointer,
1228 )
1229 };
1230
1231 // both hash values should equal
1232 assert_eq!(hash, expected);
1233 }
1234
1235 #[test]
1236 fn file_equal() {
1237 // 2 instances of `MyCustomFile` with same path should equal
1238 let my_custom_file = MyCustomFile::new("/my_file");
1239 let expected = MyCustomFile::new("/my_file");
1240 assert!(my_custom_file.equal(&expected));
1241
1242 // instances of `MyCustomFile` and of `MyFile` with same path should not equal (because type is different)
1243 let expected = File::for_path(PathBuf::from("/my_file"));
1244 assert!(!my_custom_file.equal(&expected));
1245 }
1246
1247 #[test]
1248 fn file_is_native() {
1249 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::is_native`
1250 let my_custom_file = MyCustomFile::new("/my_file");
1251 let is_native = my_custom_file.is_native();
1252
1253 // invoke `MyFile` implementation of `crate::ffi::GFileIface::is_native`
1254 let my_file = MyFile::new("/my_file");
1255 let expected = my_file.is_native();
1256
1257 // both results should equal
1258 assert_eq!(is_native, expected);
1259 }
1260
1261 #[test]
1262 fn file_has_uri_scheme() {
1263 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::has_uri_scheme`
1264 let my_custom_file = MyCustomFile::new("/my_file");
1265 let has_file = my_custom_file.has_uri_scheme("file");
1266 let has_foo = my_custom_file.has_uri_scheme("foo");
1267
1268 // invoke `MyFile` implementation of `crate::ffi::GFileIface::has_uri_scheme`
1269 let my_file = MyFile::new("/my_file");
1270
1271 let expected_file = my_file.has_uri_scheme("file");
1272 let expected_foo = my_file.has_uri_scheme("foo");
1273
1274 // both results should equal
1275 assert_eq!(has_file, expected_file);
1276 assert_eq!(has_foo, expected_foo);
1277 }
1278
1279 #[test]
1280 fn file_uri_scheme() {
1281 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::uri_scheme`
1282 let my_custom_file = MyCustomFile::new("/my_file");
1283 let uri_scheme = my_custom_file.uri_scheme();
1284
1285 // invoke `MyFile` implementation of `crate::ffi::GFileIface::uri_scheme`
1286 let my_file = MyFile::new("/my_file");
1287 let expected = my_file.uri_scheme();
1288
1289 // both uri schemes should equal
1290 assert_eq!(uri_scheme, expected);
1291 }
1292
1293 #[test]
1294 fn file_basename() {
1295 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::basename`
1296 let my_custom_file = MyCustomFile::new("/my_file");
1297 let basename = my_custom_file.basename();
1298
1299 // invoke `MyFile` implementation of `crate::ffi::GFileIface::basename`
1300 let my_file = MyFile::new("/my_file");
1301 let expected = my_file.basename();
1302
1303 // both basenames should equal
1304 assert_eq!(basename, expected);
1305 }
1306
1307 #[test]
1308 fn file_path() {
1309 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::path`
1310 let my_custom_file = MyCustomFile::new("/my_file");
1311 let path = my_custom_file.path();
1312
1313 // invoke `MyFile` implementation of `crate::ffi::GFileIface::path`
1314 let my_file = MyFile::new("/my_file");
1315 let expected = my_file.path();
1316
1317 // both paths should equal
1318 assert_eq!(path, expected);
1319 }
1320
1321 #[test]
1322 fn file_uri() {
1323 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::uri`
1324 let my_custom_file = MyCustomFile::new("/my_file");
1325 let uri = my_custom_file.uri();
1326
1327 // invoke `MyFile` implementation of `crate::ffi::GFileIface::uri`
1328 let my_file = MyFile::new("/my_file");
1329 let expected = my_file.uri();
1330
1331 // both uris should equal
1332 assert_eq!(uri, expected);
1333 }
1334
1335 #[test]
1336 fn file_parse_name() {
1337 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::parse_name`
1338 let my_custom_file = MyCustomFile::new("/my_file");
1339 let parse_name = my_custom_file.parse_name();
1340
1341 // invoke `MyFile` implementation of `crate::ffi::GFileIface::parse_name`
1342 let my_file = MyFile::new("/my_file");
1343 let expected = my_file.parse_name();
1344
1345 // both parse names should equal
1346 assert_eq!(parse_name, expected);
1347 }
1348
1349 #[test]
1350 fn file_parent() {
1351 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::parent`
1352 let my_custom_file = MyCustomFile::new("/my_parent/my_file");
1353 let res = my_custom_file.parent();
1354 assert!(res.is_some(), "unexpected None");
1355 let parent = res.unwrap();
1356
1357 // invoke `MyFile` implementation of `crate::ffi::GFileIface::parent`
1358 let my_file = MyFile::new("/my_parent/my_file");
1359 let res = my_file.parent();
1360 assert!(res.is_some(), "unexpected None");
1361 let expected = res.unwrap();
1362
1363 // both parents should equal
1364 assert!(parent.equal(&expected));
1365 }
1366
1367 #[test]
1368 fn file_has_prefix() {
1369 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::has_prefix`
1370 let my_custom_file = MyCustomFile::new("/my_prefix/my_file");
1371 let my_custom_prefix = MyCustomFile::new("/my_prefix");
1372 let has_prefix = my_custom_file.has_prefix(&my_custom_prefix);
1373
1374 // invoke `MyFile` implementation of `crate::ffi::GFileIface::has_prefix`
1375 let my_file = MyFile::new("/my_prefix/my_file");
1376 let my_prefix = MyFile::new("/my_prefix");
1377 let expected = my_file.has_prefix(&my_prefix);
1378
1379 // both results should equal
1380 assert_eq!(has_prefix, expected);
1381 }
1382
1383 #[test]
1384 fn file_relative_path() {
1385 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::relative_path`
1386 let my_custom_parent = MyCustomFile::new("/my_parent");
1387 let my_custom_descendant = MyCustomFile::new("/my_parent/my_descendant");
1388 let relative_path = my_custom_parent.relative_path(&my_custom_descendant);
1389
1390 // invoke `MyFile` implementation of `crate::ffi::GFileIface::relative_path`
1391 let my_parent = MyFile::new("/my_parent");
1392 let my_descendant = MyFile::new("/my_parent/my_descendant");
1393 let expected = my_parent.relative_path(&my_descendant);
1394
1395 // both relative paths should equal
1396 assert_eq!(relative_path, expected);
1397 }
1398
1399 #[test]
1400 fn file_resolve_relative_path() {
1401 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::resolve_relative_path`
1402 let my_custom_prefix = MyCustomFile::new("/my_prefix");
1403 let resolved_path = my_custom_prefix.resolve_relative_path("my_file");
1404
1405 // invoke `MyFile` implementation of `crate::ffi::GFileIface::resolve_relative_path`
1406 let my_prefix = MyFile::new("/my_prefix");
1407 let expected = my_prefix.resolve_relative_path("my_file");
1408
1409 // both resolved path result should equal
1410 assert!(resolved_path.equal(&expected));
1411 }
1412
1413 #[test]
1414 fn file_child_for_display_name() {
1415 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::child_for_display_name`
1416 let my_custom_parent = MyCustomFile::new("/my_parent");
1417 let res = my_custom_parent.child_for_display_name("my_file");
1418 assert!(res.is_ok(), "{}", res.unwrap_err());
1419 let child = res.unwrap();
1420
1421 // invoke `MyFile` implementation of `crate::ffi::GFileIface::child_for_display_name`
1422 let my_parent = MyFile::new("/my_parent");
1423 let res = my_parent.child_for_display_name("my_file");
1424 assert!(res.is_ok(), "{}", res.unwrap_err());
1425 let expected = res.unwrap();
1426
1427 // both children should equal
1428 assert!(child.equal(&expected))
1429 }
1430
1431 #[test]
1432 fn file_enumerate_children() {
1433 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::enumerate_children`
1434 let my_custom_file =
1435 MyCustomFile::with_type_state("/my_file", FileType::Regular, MyFileState::Exist);
1436 let res = my_custom_file.enumerate_children("*", FileQueryInfoFlags::NONE, Cancellable::NONE);
1437 assert!(res.is_err(), "unexpected enumerator");
1438 let err = res.unwrap_err();
1439
1440 // invoke `MyFile` implementation of `crate::ffi::GFileIface::enumerate_children`
1441 let my_file = MyFile::with_type_state("/my_file", FileType::Regular, MyFileState::Exist);
1442 let res = my_file.enumerate_children("*", FileQueryInfoFlags::NONE, Cancellable::NONE);
1443 assert!(res.is_err(), "unexpected enumerator");
1444 let expected = res.unwrap_err();
1445
1446 // both errors should equal
1447 assert_eq!(err.message(), expected.message());
1448 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1449
1450 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::enumerate_children`
1451 let my_custom_parent = MyCustomFile::with_children("/my_parent", vec!["my_file1", "my_file2"]);
1452 let res = my_custom_parent.enumerate_children("*", FileQueryInfoFlags::NONE, Cancellable::NONE);
1453 assert!(res.is_ok(), "{}", res.unwrap_err());
1454 let my_custom_enumerator = res.unwrap();
1455 let res = my_custom_enumerator
1456 .map(|res| res.map(|file_info| file_info.name()))
1457 .collect::<Result<Vec<_>, _>>();
1458 assert!(res.is_ok(), "{}", res.unwrap_err());
1459 let my_custom_children = res.unwrap();
1460
1461 // invoke `MyFile` implementation of `crate::ffi::GFileIface::enumerate_children`
1462 let my_parent = MyFile::with_children("/my_parent", vec!["my_file1", "my_file2"]);
1463 let res = my_parent.enumerate_children("*", FileQueryInfoFlags::NONE, Cancellable::NONE);
1464 assert!(res.is_ok(), "{}", res.unwrap_err());
1465 let my_enumerator = res.unwrap();
1466 let res = my_enumerator
1467 .map(|res| res.map(|file_info| file_info.name()))
1468 .collect::<Result<Vec<_>, _>>();
1469 assert!(res.is_ok(), "{}", res.unwrap_err());
1470 let expected = res.unwrap();
1471
1472 // both children should equal
1473 assert_eq!(my_custom_children, expected)
1474 }
1475
1476 #[test]
1477 fn file_query_info() {
1478 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::query_info`
1479 let my_custom_file =
1480 MyCustomFile::with_xattr("/my_file", vec!["xattr::key1=value1", "xattr::key2=value2"]);
1481 let res = my_custom_file.query_info("*", FileQueryInfoFlags::NONE, Cancellable::NONE);
1482 assert!(res.is_ok(), "{}", res.unwrap_err());
1483 let file_info = res.unwrap();
1484
1485 // invoke `MyFile` implementation of `crate::ffi::GFileIface::query_info`
1486 let my_file = MyFile::with_xattr("/my_file", vec!["xattr::key1=value1", "xattr::key2=value2"]);
1487 let res = my_file.query_info("*", FileQueryInfoFlags::NONE, Cancellable::NONE);
1488 assert!(res.is_ok(), "{}", res.unwrap_err());
1489 let expected = res.unwrap();
1490
1491 // both results should equal
1492 assert_eq!(file_info.name(), expected.name());
1493 assert_eq!(
1494 file_info.attribute_as_string("xattr::key1"),
1495 expected.attribute_as_string("xattr::key1")
1496 );
1497 assert_eq!(
1498 file_info.attribute_as_string("xattr::key2"),
1499 expected.attribute_as_string("xattr::key2")
1500 );
1501 }
1502
1503 #[test]
1504 fn file_query_filesystem_info() {
1505 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::query_filesystem_info`
1506 let my_custom_file =
1507 MyCustomFile::with_xattr("/my_file", vec!["xattr::key1=value1", "xattr::key2=value2"]);
1508 let res = my_custom_file.query_filesystem_info("*", Cancellable::NONE);
1509 assert!(res.is_ok(), "{}", res.unwrap_err());
1510 let file_info = res.unwrap();
1511
1512 // invoke `MyFile` implementation of `crate::ffi::GFileIface::query_filesystem_info`
1513 let my_file = MyFile::with_xattr("/my_file", vec!["xattr::key1=value1", "xattr::key2=value2"]);
1514 let res = my_file.query_filesystem_info("*", Cancellable::NONE);
1515 assert!(res.is_ok(), "{}", res.unwrap_err());
1516 let expected = res.unwrap();
1517
1518 // both results should equal
1519 assert_eq!(file_info.name(), expected.name());
1520 assert_eq!(
1521 file_info.attribute_as_string("xattr::key1"),
1522 expected.attribute_as_string("xattr::key1")
1523 );
1524 assert_eq!(
1525 file_info.attribute_as_string("xattr::key2"),
1526 expected.attribute_as_string("xattr::key2")
1527 );
1528 }
1529
1530 #[test]
1531 fn file_find_enclosing_mount() {
1532 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::find_enclosing_mount`
1533 let my_custom_dir = MyCustomFile::new("/my_directory");
1534 let res = my_custom_dir.find_enclosing_mount(Cancellable::NONE);
1535 assert!(res.is_err(), "unexpected mount {:?}", res.ok().unwrap());
1536 let err = res.unwrap_err();
1537
1538 // invoke `MyFile` implementation of `crate::ffi::GFileIface::find_enclosing_mount`
1539 let my_dir = MyFile::new("/my_directory");
1540 let res = my_dir.find_enclosing_mount(Cancellable::NONE);
1541 assert!(res.is_err(), "unexpected mount {:?}", res.ok().unwrap());
1542 let expected = res.unwrap_err();
1543
1544 // both errors should equal
1545 assert_eq!(err.message(), expected.message());
1546 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1547 }
1548
1549 #[test]
1550 fn file_set_display_name() {
1551 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::set_display_name`
1552 let my_custom_file = MyCustomFile::new("/my_file");
1553 let res = my_custom_file.set_display_name("my_file_new_name", Cancellable::NONE);
1554 assert!(res.is_ok(), "{}", res.unwrap_err());
1555 let renamed = res.unwrap();
1556
1557 // invoke `MyFile` implementation of `crate::ffi::GFileIface::set_display_name`
1558 let my_file = MyFile::new("/my_file");
1559 let res = my_file.set_display_name("my_file_new_name", Cancellable::NONE);
1560 let expected = res.unwrap();
1561
1562 // both new paths should equal
1563 assert_eq!(renamed.path(), expected.path());
1564 }
1565
1566 #[test]
1567 fn file_query_settable_attributes() {
1568 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::query_settable_attributes`
1569 let my_custom_file =
1570 MyCustomFile::with_xattr("/my_file", vec!["xattr::key1=value1", "xattr::key2=value2"]);
1571 let res = my_custom_file.query_settable_attributes(Cancellable::NONE);
1572 assert!(res.is_ok(), "{}", res.unwrap_err());
1573 let file_attribute_infos = res.unwrap();
1574
1575 // invoke `MyFile` implementation of `crate::ffi::GFileIface::query_settable_attributes`
1576 let my_file = MyFile::with_xattr("/my_file", vec!["xattr::key1=value1", "xattr::key2=value2"]);
1577 let res = my_file.query_settable_attributes(Cancellable::NONE);
1578 assert!(res.is_ok(), "{}", res.unwrap_err());
1579 let expected = res.unwrap();
1580
1581 // both file attribute infos should equal
1582 assert_eq!(
1583 file_attribute_infos
1584 .attributes()
1585 .iter()
1586 .map(|attr| attr.name().to_owned())
1587 .collect::<Vec<_>>(),
1588 expected
1589 .attributes()
1590 .iter()
1591 .map(|attr| attr.name().to_owned())
1592 .collect::<Vec<_>>()
1593 );
1594 }
1595
1596 #[test]
1597 fn file_query_writable_namespaces() {
1598 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::query_writable_namespaces`
1599 let my_custom_file = MyCustomFile::new("/my_file");
1600 let res = my_custom_file.query_writable_namespaces(Cancellable::NONE);
1601 assert!(res.is_ok(), "{}", res.unwrap_err());
1602 let file_attribute_infos = res.unwrap();
1603
1604 // invoke `MyFile` implementation of `crate::ffi::GFileIface::query_writable_namespaces`
1605 let my_file = MyFile::new("/my_file");
1606 let res = my_file.query_writable_namespaces(Cancellable::NONE);
1607 assert!(res.is_ok(), "{}", res.unwrap_err());
1608 let expected = res.unwrap();
1609
1610 // both file attribute infos should equal
1611 assert_eq!(
1612 file_attribute_infos
1613 .attributes()
1614 .iter()
1615 .map(|attr| attr.name().to_owned())
1616 .collect::<Vec<_>>(),
1617 expected
1618 .attributes()
1619 .iter()
1620 .map(|attr| attr.name().to_owned())
1621 .collect::<Vec<_>>()
1622 );
1623 }
1624
1625 #[test]
1626 fn file_set_attribute() {
1627 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::set_attribute`
1628 let my_custom_file = MyCustomFile::new("/my_file");
1629 let res = my_custom_file.set_attribute(
1630 "xattr::key1",
1631 "value1",
1632 FileQueryInfoFlags::NONE,
1633 Cancellable::NONE,
1634 );
1635 assert!(res.is_ok(), "{}", res.unwrap_err());
1636 let res = my_custom_file.query_info("xattr::key1", FileQueryInfoFlags::NONE, Cancellable::NONE);
1637 assert!(res.is_ok(), "{}", res.unwrap_err());
1638 let file_info = res.unwrap();
1639
1640 // invoke `MyFile` implementation of `crate::ffi::GFileIface::set_attribute`
1641 let my_file = MyFile::new("/my_file");
1642 let res = my_file.set_attribute(
1643 "xattr::key1",
1644 "value1",
1645 FileQueryInfoFlags::NONE,
1646 Cancellable::NONE,
1647 );
1648 assert!(res.is_ok(), "{}", res.unwrap_err());
1649 let res = my_file.query_info("xattr::key1", FileQueryInfoFlags::NONE, Cancellable::NONE);
1650 assert!(res.is_ok(), "{}", res.unwrap_err());
1651 let expected = res.unwrap();
1652
1653 // both file attributes should equal
1654 assert_eq!(
1655 file_info.attribute_as_string("xattr::key1"),
1656 expected.attribute_as_string("xattr::key1")
1657 );
1658 }
1659
1660 #[test]
1661 fn file_set_attributes_from_info() {
1662 let file_info = FileInfo::new();
1663 file_info.set_attribute_string("xattr::key1", "value1");
1664
1665 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::set_attributes_from_info`
1666 let my_custom_file = MyCustomFile::new("/my_file");
1667 let res = my_custom_file.set_attributes_from_info(
1668 &file_info,
1669 FileQueryInfoFlags::NONE,
1670 Cancellable::NONE,
1671 );
1672 assert!(res.is_ok(), "{}", res.unwrap_err());
1673 let res = my_custom_file.query_info("xattr::key1", FileQueryInfoFlags::NONE, Cancellable::NONE);
1674 assert!(res.is_ok(), "{}", res.unwrap_err());
1675 let file_info = res.unwrap();
1676
1677 // invoke `MyFile` implementation of `crate::ffi::GFileIface::set_attributes_from_info`
1678 let my_file = MyFile::new("/my_file");
1679 let res =
1680 my_file.set_attributes_from_info(&file_info, FileQueryInfoFlags::NONE, Cancellable::NONE);
1681 assert!(res.is_ok(), "{}", res.unwrap_err());
1682 let res = my_file.query_info("xattr::key1", FileQueryInfoFlags::NONE, Cancellable::NONE);
1683 assert!(res.is_ok(), "{}", res.unwrap_err());
1684 let expected = res.unwrap();
1685
1686 // both file attributes should equal
1687 assert_eq!(
1688 file_info.attribute_as_string("xattr::key1"),
1689 expected.attribute_as_string("xattr::key1")
1690 );
1691 }
1692
1693 #[test]
1694 fn file_read_fn() {
1695 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::read_fn`
1696 let my_custom_file = MyCustomFile::new("/my_file");
1697 let res = my_custom_file.read(Cancellable::NONE);
1698 assert!(
1699 res.is_err(),
1700 "unexpected file input stream {:?}",
1701 res.ok().unwrap()
1702 );
1703 let err = res.unwrap_err();
1704
1705 // invoke `MyFile` implementation of `crate::ffi::GFileIface::read_fn`
1706 let my_file = MyFile::new("/my_file");
1707 let res = my_file.read(Cancellable::NONE);
1708 assert!(
1709 res.is_err(),
1710 "unexpected file input stream {:?}",
1711 res.ok().unwrap()
1712 );
1713 let expected = res.unwrap_err();
1714
1715 // both errors should equal
1716 assert_eq!(err.message(), expected.message());
1717 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1718 }
1719
1720 #[test]
1721 fn file_append_to() {
1722 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::append_to`
1723 let my_custom_file = MyCustomFile::new("/my_file");
1724 let res = my_custom_file.append_to(FileCreateFlags::NONE, Cancellable::NONE);
1725 assert!(
1726 res.is_err(),
1727 "unexpected file output stream {:?}",
1728 res.ok().unwrap()
1729 );
1730 let err = res.unwrap_err();
1731
1732 // invoke `MyFile` implementation of `crate::ffi::GFileIface::append_to`
1733 let my_file = MyFile::new("/my_file");
1734 let res = my_file.append_to(FileCreateFlags::NONE, Cancellable::NONE);
1735 assert!(
1736 res.is_err(),
1737 "unexpected file output stream {:?}",
1738 res.ok().unwrap()
1739 );
1740 let expected = res.unwrap_err();
1741
1742 // both errors should equal
1743 assert_eq!(err.message(), expected.message());
1744 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1745 }
1746
1747 #[test]
1748 fn file_create() {
1749 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::create`
1750 let my_custom_file = MyCustomFile::new("/my_file");
1751 let res = my_custom_file.create(FileCreateFlags::NONE, Cancellable::NONE);
1752 assert!(
1753 res.is_err(),
1754 "unexpected file output stream {:?}",
1755 res.ok().unwrap()
1756 );
1757 let err = res.unwrap_err();
1758
1759 // invoke `MyFile` implementation of `crate::ffi::GFileIface::create`
1760 let my_file = MyFile::new("/my_file");
1761 let res = my_file.create(FileCreateFlags::NONE, Cancellable::NONE);
1762 assert!(
1763 res.is_err(),
1764 "unexpected file output stream {:?}",
1765 res.ok().unwrap()
1766 );
1767 let expected = res.unwrap_err();
1768
1769 // both errors should equal
1770 assert_eq!(err.message(), expected.message());
1771 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1772 }
1773
1774 #[test]
1775 fn file_replace() {
1776 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::replace`
1777 let my_custom_file = MyCustomFile::new("/my_file");
1778 let res = my_custom_file.replace(None, false, FileCreateFlags::NONE, Cancellable::NONE);
1779 assert!(
1780 res.is_err(),
1781 "unexpected file output stream {:?}",
1782 res.ok().unwrap()
1783 );
1784 let err = res.unwrap_err();
1785
1786 // invoke `MyFile` implementation of `crate::ffi::GFileIface::replace`
1787 let my_file = MyFile::new("/my_file");
1788 let res = my_file.replace(None, false, FileCreateFlags::NONE, Cancellable::NONE);
1789 assert!(
1790 res.is_err(),
1791 "unexpected file output stream {:?}",
1792 res.ok().unwrap()
1793 );
1794 let expected = res.unwrap_err();
1795
1796 // both errors should equal
1797 assert_eq!(err.message(), expected.message());
1798 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1799 }
1800
1801 #[test]
1802 fn file_delete() {
1803 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::delete`
1804 let my_custom_file =
1805 MyCustomFile::with_type_state("/my_file", FileType::Unknown, MyFileState::Exist);
1806 let res = my_custom_file.delete(Cancellable::NONE);
1807 assert!(res.is_ok(), "{}", res.unwrap_err());
1808
1809 // invoke `MyFile` implementation of `crate::ffi::GFileIface::delete`
1810 let my_file = MyFile::with_type_state("/my_file", FileType::Unknown, MyFileState::Exist);
1811 let res = my_file.delete(Cancellable::NONE);
1812 assert!(res.is_ok(), "{}", res.unwrap_err());
1813
1814 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::delete`
1815 let res = my_custom_file.delete(Cancellable::NONE);
1816 assert!(res.is_err(), "unexpected deleted file");
1817 let err = res.unwrap_err();
1818
1819 // invoke `MyFile` implementation of `crate::ffi::GFileIface::delete`
1820 let res = my_custom_file.delete(Cancellable::NONE);
1821 assert!(res.is_err(), "unexpected deleted file");
1822 let expected = res.unwrap_err();
1823
1824 // both errors should equal
1825 assert_eq!(err.message(), expected.message());
1826 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1827 }
1828
1829 #[test]
1830 fn file_trash() {
1831 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::trash`
1832 let my_custom_file =
1833 MyCustomFile::with_type_state("/my_file", FileType::Unknown, MyFileState::Exist);
1834 let res = my_custom_file.trash(Cancellable::NONE);
1835 assert!(res.is_ok(), "{}", res.unwrap_err());
1836
1837 // invoke `MyFile` implementation of `crate::ffi::GFileIface::trash`
1838 let my_file = MyFile::with_type_state("/my_file", FileType::Unknown, MyFileState::Exist);
1839 let res = my_file.trash(Cancellable::NONE);
1840 assert!(res.is_ok(), "{}", res.unwrap_err());
1841
1842 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::trash`
1843 let res = my_custom_file.trash(Cancellable::NONE);
1844 assert!(res.is_err(), "unexpected trashed file");
1845 let err = res.unwrap_err();
1846
1847 // invoke `MyFile` implementation of `crate::ffi::GFileIface::trash`
1848 let res = my_custom_file.trash(Cancellable::NONE);
1849 assert!(res.is_err(), "unexpected trashed file");
1850 let expected = res.unwrap_err();
1851
1852 // both errors should equal
1853 assert_eq!(err.message(), expected.message());
1854 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1855 }
1856
1857 #[test]
1858 fn file_make_directory() {
1859 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::make_directory`
1860 let my_custom_dir = MyCustomFile::new("/my_directory");
1861 let res = my_custom_dir.make_directory(Cancellable::NONE);
1862 assert!(res.is_ok(), "{}", res.unwrap_err());
1863
1864 // invoke `MyFile` implementation of `crate::ffi::GFileIface::make_directory`
1865 let my_dir = MyFile::new("/my_directory");
1866 let res = my_dir.make_directory(Cancellable::NONE);
1867 assert!(res.is_ok(), "{}", res.unwrap_err());
1868
1869 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::make_directory`
1870 let res = my_custom_dir.make_directory(Cancellable::NONE);
1871 assert!(res.is_err(), "unexpected created directory");
1872 let err = res.unwrap_err();
1873
1874 // invoke `MyFile` implementation of `crate::ffi::GFileIface::make_directory`
1875 let res = my_custom_dir.make_directory(Cancellable::NONE);
1876 assert!(res.is_err(), "unexpected created directory");
1877 let expected = res.unwrap_err();
1878
1879 // both errors should equal
1880 assert_eq!(err.message(), expected.message());
1881 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1882 }
1883
1884 #[test]
1885 fn file_make_symbolic_link() {
1886 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::make_symbolic_link`
1887 let my_custom_symlink = MyCustomFile::new("/my_symbolic_link");
1888 let res = my_custom_symlink.make_symbolic_link("/my_target", Cancellable::NONE);
1889 assert!(res.is_ok(), "{}", res.unwrap_err());
1890
1891 // invoke `MyFile` implementation of `crate::ffi::GFileIface::make_symbolic_link`
1892 let my_symlink = MyFile::new("/my_symbolic_link");
1893 let res = my_symlink.make_symbolic_link("/my_target", Cancellable::NONE);
1894 assert!(res.is_ok(), "{}", res.unwrap_err());
1895
1896 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::make_symbolic_link`
1897 let res = my_custom_symlink.make_symbolic_link("/my_target", Cancellable::NONE);
1898 assert!(res.is_err(), "unexpected created directory");
1899 let err = res.unwrap_err();
1900
1901 // invoke `MyFile` implementation of `crate::ffi::GFileIface::make_symbolic_link`
1902 let res = my_custom_symlink.make_symbolic_link("/my_target", Cancellable::NONE);
1903 assert!(res.is_err(), "unexpected created directory");
1904 let expected = res.unwrap_err();
1905
1906 // both errors should equal
1907 assert_eq!(err.message(), expected.message());
1908 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1909 }
1910
1911 #[test]
1912 fn file_copy() {
1913 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::copy`
1914 let my_custom_source_file = MyCustomFile::new("/my_file1");
1915 let my_custom_destination_file = MyCustomFile::new("/my_file2");
1916 let res = my_custom_source_file.copy(
1917 &my_custom_destination_file,
1918 FileCopyFlags::NONE,
1919 Cancellable::NONE,
1920 None,
1921 );
1922 assert!(res.is_err(), "unexpected copy");
1923 let err = res.unwrap_err();
1924
1925 // invoke `MyFile` implementation of `crate::ffi::GFileIface::copy`
1926 let my_source_file = MyFile::new("/my_file1");
1927 let my_destination_file = MyFile::new("/my_file2");
1928 let res = my_source_file.copy(
1929 &my_destination_file,
1930 FileCopyFlags::NONE,
1931 Cancellable::NONE,
1932 None,
1933 );
1934 assert!(res.is_err(), "unexpected copy");
1935 let expected = res.unwrap_err();
1936
1937 // both errors should equal
1938 assert_eq!(err.message(), expected.message());
1939 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1940 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::NotFound));
1941
1942 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::copy`
1943 let my_custom_source_file =
1944 MyCustomFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
1945 let my_custom_destination_file =
1946 MyCustomFile::with_type_state("/my_file2", FileType::Regular, MyFileState::Exist);
1947 let res = my_custom_source_file.copy(
1948 &my_custom_destination_file,
1949 FileCopyFlags::NONE,
1950 Cancellable::NONE,
1951 None,
1952 );
1953 assert!(res.is_err(), "unexpected copy");
1954 let err = res.unwrap_err();
1955
1956 // invoke `MyFile` implementation of `crate::ffi::GFileIface::copy`
1957 let my_source_file =
1958 MyFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
1959 let my_destination_file =
1960 MyFile::with_type_state("/my_file2", FileType::Regular, MyFileState::Exist);
1961 let res = my_source_file.copy(
1962 &my_destination_file,
1963 FileCopyFlags::NONE,
1964 Cancellable::NONE,
1965 None,
1966 );
1967 assert!(res.is_err(), "unexpected copy");
1968 let expected = res.unwrap_err();
1969
1970 // both errors should equal
1971 assert_eq!(err.message(), expected.message());
1972 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
1973 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::Exists));
1974
1975 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::copy`
1976 let my_custom_source_file =
1977 MyCustomFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
1978 let my_custom_destination_directory =
1979 MyCustomFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::Exist);
1980 let res = my_custom_source_file.copy(
1981 &my_custom_destination_directory,
1982 FileCopyFlags::OVERWRITE,
1983 Cancellable::NONE,
1984 None,
1985 );
1986 assert!(res.is_err(), "unexpected copy");
1987 let err = res.unwrap_err();
1988
1989 // invoke `MyFile` implementation of `crate::ffi::GFileIface::copy`
1990 let my_source_file =
1991 MyFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
1992 let my_destination_directory =
1993 MyFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::Exist);
1994 let res = my_source_file.copy(
1995 &my_destination_directory,
1996 FileCopyFlags::OVERWRITE,
1997 Cancellable::NONE,
1998 None,
1999 );
2000 assert!(res.is_err(), "unexpected copy");
2001 let expected = res.unwrap_err();
2002
2003 // both errors should equal
2004 assert_eq!(err.message(), expected.message());
2005 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2006 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::IsDirectory));
2007
2008 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::copy`
2009 let my_custom_source_directory =
2010 MyCustomFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2011 let my_custom_destination_directory =
2012 MyCustomFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::Exist);
2013 let res = my_custom_source_directory.copy(
2014 &my_custom_destination_directory,
2015 FileCopyFlags::OVERWRITE,
2016 Cancellable::NONE,
2017 None,
2018 );
2019 assert!(res.is_err(), "unexpected copy");
2020 let err = res.unwrap_err();
2021
2022 // invoke `MyFile` implementation of `crate::ffi::GFileIface::copy`
2023 let my_source_directory =
2024 MyFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2025 let my_destination_directory =
2026 MyFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::Exist);
2027 let res = my_source_directory.copy(
2028 &my_destination_directory,
2029 FileCopyFlags::OVERWRITE,
2030 Cancellable::NONE,
2031 None,
2032 );
2033 assert!(res.is_err(), "unexpected copy");
2034 let expected = res.unwrap_err();
2035
2036 // both errors should equal
2037 assert_eq!(err.message(), expected.message());
2038 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2039 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::WouldMerge));
2040
2041 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::copy`
2042 let my_custom_source_directory =
2043 MyCustomFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2044 let my_custom_destination_directory =
2045 MyCustomFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::DoesNotExist);
2046 let res = my_custom_source_directory.copy(
2047 &my_custom_destination_directory,
2048 FileCopyFlags::NONE,
2049 Cancellable::NONE,
2050 None,
2051 );
2052 assert!(res.is_err(), "unexpected copy");
2053 let err = res.unwrap_err();
2054
2055 // invoke `MyFile` implementation of `crate::ffi::GFileIface::copy`
2056 let my_source_directory =
2057 MyFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2058 let my_destination_directory =
2059 MyFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::DoesNotExist);
2060 let res = my_source_directory.copy(
2061 &my_destination_directory,
2062 FileCopyFlags::NONE,
2063 Cancellable::NONE,
2064 None,
2065 );
2066 assert!(res.is_err(), "unexpected copy");
2067 let expected = res.unwrap_err();
2068
2069 // both errors should equal
2070 assert_eq!(err.message(), expected.message());
2071 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2072 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::WouldRecurse));
2073
2074 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::copy`
2075 let my_custom_source_directory =
2076 MyCustomFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2077 let my_custom_destination_file =
2078 MyCustomFile::with_type_state("/my_file2", FileType::Regular, MyFileState::Exist);
2079 let res = my_custom_source_directory.copy(
2080 &my_custom_destination_file,
2081 FileCopyFlags::OVERWRITE,
2082 Cancellable::NONE,
2083 None,
2084 );
2085 assert!(res.is_err(), "unexpected copy");
2086 let err = res.unwrap_err();
2087
2088 // invoke `MyFile` implementation of `crate::ffi::GFileIface::copy`
2089 let my_source_directory =
2090 MyFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2091 let my_destination_file =
2092 MyFile::with_type_state("/my_file2", FileType::Regular, MyFileState::Exist);
2093 let res = my_source_directory.copy(
2094 &my_destination_file,
2095 FileCopyFlags::OVERWRITE,
2096 Cancellable::NONE,
2097 None,
2098 );
2099 assert!(res.is_err(), "unexpected copy");
2100 let expected = res.unwrap_err();
2101
2102 // both errors should equal
2103 assert_eq!(err.message(), expected.message());
2104 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2105 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::WouldRecurse));
2106
2107 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::copy`
2108 let my_custom_source_file =
2109 MyCustomFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
2110 let my_custom_destination_file =
2111 MyCustomFile::with_type_state("/my_file2", FileType::Regular, MyFileState::DoesNotExist);
2112 let (mut copied, mut total) = (0, 0);
2113 let res = my_custom_source_file.copy(
2114 &my_custom_destination_file,
2115 FileCopyFlags::NONE,
2116 Cancellable::NONE,
2117 Some(&mut move |current_num_bytes, total_num_bytes| {
2118 assert!(current_num_bytes >= copied);
2119 assert!(total_num_bytes >= total);
2120 copied = current_num_bytes;
2121 total = total_num_bytes;
2122 }),
2123 );
2124 assert!(res.is_ok(), "{}", res.unwrap_err());
2125
2126 // invoke `MyFile` implementation of `crate::ffi::GFileIface::copy`
2127 let my_source_file =
2128 MyFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
2129 let my_destination_file =
2130 MyFile::with_type_state("/my_file2", FileType::Regular, MyFileState::DoesNotExist);
2131 let (mut copied, mut total) = (0, 0);
2132 let expected = my_source_file.copy(
2133 &my_destination_file,
2134 FileCopyFlags::NONE,
2135 Cancellable::NONE,
2136 Some(&mut move |current_num_bytes, total_num_bytes| {
2137 assert!(current_num_bytes >= copied);
2138 assert!(total_num_bytes >= total);
2139 copied = current_num_bytes;
2140 total = total_num_bytes;
2141 }),
2142 );
2143 assert!(expected.is_ok(), "{}", expected.unwrap_err());
2144
2145 // both results should equal
2146 assert_eq!(res, expected);
2147 }
2148
2149 #[test]
2150 fn file_move_() {
2151 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::move_`
2152 let my_custom_source_file = MyCustomFile::new("/my_file1");
2153 let my_custom_destination_file = MyCustomFile::new("/my_file2");
2154 let res = my_custom_source_file.move_(
2155 &my_custom_destination_file,
2156 FileCopyFlags::NONE,
2157 Cancellable::NONE,
2158 None,
2159 );
2160 assert!(res.is_err(), "unexpected move_");
2161 let err = res.unwrap_err();
2162
2163 // invoke `MyFile` implementation of `crate::ffi::GFileIface::move_`
2164 let my_source_file = MyFile::new("/my_file1");
2165 let my_destination_file = MyFile::new("/my_file2");
2166 let res = my_source_file.move_(
2167 &my_destination_file,
2168 FileCopyFlags::NONE,
2169 Cancellable::NONE,
2170 None,
2171 );
2172 assert!(res.is_err(), "unexpected move_");
2173 let expected = res.unwrap_err();
2174
2175 // both errors should equal
2176 assert_eq!(err.message(), expected.message());
2177 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2178 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::NotFound));
2179
2180 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::move_`
2181 let my_custom_source_file =
2182 MyCustomFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
2183 let my_custom_destination_file =
2184 MyCustomFile::with_type_state("/my_file2", FileType::Regular, MyFileState::Exist);
2185 let res = my_custom_source_file.move_(
2186 &my_custom_destination_file,
2187 FileCopyFlags::NONE,
2188 Cancellable::NONE,
2189 None,
2190 );
2191 assert!(res.is_err(), "unexpected move_");
2192 let err = res.unwrap_err();
2193
2194 // invoke `MyFile` implementation of `crate::ffi::GFileIface::move_`
2195 let my_source_file =
2196 MyFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
2197 let my_destination_file =
2198 MyFile::with_type_state("/my_file2", FileType::Regular, MyFileState::Exist);
2199 let res = my_source_file.move_(
2200 &my_destination_file,
2201 FileCopyFlags::NONE,
2202 Cancellable::NONE,
2203 None,
2204 );
2205 assert!(res.is_err(), "unexpected move_");
2206 let expected = res.unwrap_err();
2207
2208 // both errors should equal
2209 assert_eq!(err.message(), expected.message());
2210 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2211 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::Exists));
2212
2213 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::move_`
2214 let my_custom_source_file =
2215 MyCustomFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
2216 let my_custom_destination_directory =
2217 MyCustomFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::Exist);
2218 let res = my_custom_source_file.move_(
2219 &my_custom_destination_directory,
2220 FileCopyFlags::OVERWRITE,
2221 Cancellable::NONE,
2222 None,
2223 );
2224 assert!(res.is_err(), "unexpected move_");
2225 let err = res.unwrap_err();
2226
2227 // invoke `MyFile` implementation of `crate::ffi::GFileIface::move_`
2228 let my_source_file =
2229 MyFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
2230 let my_destination_directory =
2231 MyFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::Exist);
2232 let res = my_source_file.move_(
2233 &my_destination_directory,
2234 FileCopyFlags::OVERWRITE,
2235 Cancellable::NONE,
2236 None,
2237 );
2238 assert!(res.is_err(), "unexpected move_");
2239 let expected = res.unwrap_err();
2240
2241 // both errors should equal
2242 assert_eq!(err.message(), expected.message());
2243 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2244 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::IsDirectory));
2245
2246 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::move_`
2247 let my_custom_source_directory =
2248 MyCustomFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2249 let my_custom_destination_directory =
2250 MyCustomFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::Exist);
2251 let res = my_custom_source_directory.move_(
2252 &my_custom_destination_directory,
2253 FileCopyFlags::OVERWRITE,
2254 Cancellable::NONE,
2255 None,
2256 );
2257 assert!(res.is_err(), "unexpected move_");
2258 let err = res.unwrap_err();
2259
2260 // invoke `MyFile` implementation of `crate::ffi::GFileIface::move_`
2261 let my_source_directory =
2262 MyFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2263 let my_destination_directory =
2264 MyFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::Exist);
2265 let res = my_source_directory.move_(
2266 &my_destination_directory,
2267 FileCopyFlags::OVERWRITE,
2268 Cancellable::NONE,
2269 None,
2270 );
2271 assert!(res.is_err(), "unexpected move_");
2272 let expected = res.unwrap_err();
2273
2274 // both errors should equal
2275 assert_eq!(err.message(), expected.message());
2276 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2277 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::WouldMerge));
2278
2279 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::move_`
2280 let my_custom_source_directory =
2281 MyCustomFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2282 let my_custom_destination_directory =
2283 MyCustomFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::DoesNotExist);
2284 let res = my_custom_source_directory.move_(
2285 &my_custom_destination_directory,
2286 FileCopyFlags::NONE,
2287 Cancellable::NONE,
2288 None,
2289 );
2290 assert!(res.is_err(), "unexpected move_");
2291 let err = res.unwrap_err();
2292
2293 // invoke `MyFile` implementation of `crate::ffi::GFileIface::move_`
2294 let my_source_directory =
2295 MyFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2296 let my_destination_directory =
2297 MyFile::with_type_state("/my_dir2", FileType::Directory, MyFileState::DoesNotExist);
2298 let res = my_source_directory.move_(
2299 &my_destination_directory,
2300 FileCopyFlags::NONE,
2301 Cancellable::NONE,
2302 None,
2303 );
2304 assert!(res.is_err(), "unexpected move_");
2305 let expected = res.unwrap_err();
2306
2307 // both errors should equal
2308 assert_eq!(err.message(), expected.message());
2309 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2310 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::WouldRecurse));
2311
2312 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::move_`
2313 let my_custom_source_directory =
2314 MyCustomFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2315 let my_custom_destination_file =
2316 MyCustomFile::with_type_state("/my_file2", FileType::Regular, MyFileState::Exist);
2317 let res = my_custom_source_directory.move_(
2318 &my_custom_destination_file,
2319 FileCopyFlags::OVERWRITE,
2320 Cancellable::NONE,
2321 None,
2322 );
2323 assert!(res.is_err(), "unexpected move_");
2324 let err = res.unwrap_err();
2325
2326 // invoke `MyFile` implementation of `crate::ffi::GFileIface::move_`
2327 let my_source_directory =
2328 MyFile::with_type_state("/my_dir1", FileType::Directory, MyFileState::Exist);
2329 let my_destination_file =
2330 MyFile::with_type_state("/my_file2", FileType::Regular, MyFileState::Exist);
2331 let res = my_source_directory.move_(
2332 &my_destination_file,
2333 FileCopyFlags::OVERWRITE,
2334 Cancellable::NONE,
2335 None,
2336 );
2337 assert!(res.is_err(), "unexpected move_");
2338 let expected = res.unwrap_err();
2339
2340 // both errors should equal
2341 assert_eq!(err.message(), expected.message());
2342 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2343 assert_eq!(err.kind::<IOErrorEnum>(), Some(IOErrorEnum::WouldRecurse));
2344
2345 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::move_`
2346 let my_custom_source_file =
2347 MyCustomFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
2348 let my_custom_destination_file =
2349 MyCustomFile::with_type_state("/my_file2", FileType::Regular, MyFileState::DoesNotExist);
2350 let (mut copied, mut total) = (0, 0);
2351 let res = my_custom_source_file.move_(
2352 &my_custom_destination_file,
2353 FileCopyFlags::NONE,
2354 Cancellable::NONE,
2355 Some(&mut move |current_num_bytes, total_num_bytes| {
2356 assert!(current_num_bytes >= copied);
2357 assert!(total_num_bytes >= total);
2358 copied = current_num_bytes;
2359 total = total_num_bytes;
2360 }),
2361 );
2362 assert!(res.is_ok(), "{}", res.unwrap_err());
2363
2364 // invoke `MyFile` implementation of `crate::ffi::GFileIface::move_`
2365 let my_source_file =
2366 MyFile::with_type_state("/my_file1", FileType::Regular, MyFileState::Exist);
2367 let my_destination_file =
2368 MyFile::with_type_state("/my_file2", FileType::Regular, MyFileState::DoesNotExist);
2369 let (mut copied, mut total) = (0, 0);
2370 let expected = my_source_file.move_(
2371 &my_destination_file,
2372 FileCopyFlags::NONE,
2373 Cancellable::NONE,
2374 Some(&mut move |current_num_bytes, total_num_bytes| {
2375 assert!(current_num_bytes >= copied);
2376 assert!(total_num_bytes >= total);
2377 copied = current_num_bytes;
2378 total = total_num_bytes;
2379 }),
2380 );
2381 assert!(expected.is_ok(), "{}", expected.unwrap_err());
2382
2383 // both results should equal
2384 assert_eq!(res, expected);
2385 }
2386
2387 #[test]
2388 fn file_mount_mountable() {
2389 // run test in a main context dedicated and configured as the thread default one
2390 let _ = glib::MainContext::new().with_thread_default(|| {
2391 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::mount_mountable`
2392 let my_custom_path = MyCustomFile::new("/my_path");
2393
2394 let (tx, rx) = oneshot::channel();
2395 let res = glib::MainContext::ref_thread_default().block_on(async {
2396 my_custom_path.mount_mountable(
2397 MountMountFlags::NONE,
2398 MountOperation::NONE,
2399 Cancellable::NONE,
2400 move |res| tx.send(res).unwrap(),
2401 );
2402 rx.await.unwrap()
2403 });
2404 assert!(res.is_err(), "unexpected file mount mountable success");
2405 let err = res.unwrap_err();
2406
2407 // invoke `MyFile` implementation of `crate::ffi::GFileIface::mount_mountable`
2408 let my_path = MyFile::new("/my_path");
2409
2410 let (tx, rx) = oneshot::channel();
2411 let res = glib::MainContext::ref_thread_default().block_on(async {
2412 my_path.mount_mountable(
2413 MountMountFlags::NONE,
2414 MountOperation::NONE,
2415 Cancellable::NONE,
2416 move |res| tx.send(res).unwrap(),
2417 );
2418 rx.await.unwrap()
2419 });
2420 assert!(res.is_err(), "unexpected file mount mountable success");
2421 let expected = res.unwrap_err();
2422
2423 // both errors should equal
2424 assert_eq!(err.message(), expected.message());
2425 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2426 });
2427 }
2428
2429 // checker-ignore-item
2430 #[test]
2431 fn file_unmount_mountable() {
2432 // run test in a main context dedicated and configured as the thread default one
2433 let _ = glib::MainContext::new().with_thread_default(|| {
2434 // implement the deprecated function unmount_mountable which is useful for this test
2435 fn unmount_mountable<T: IsA<File>, P: FnOnce(Result<(), glib::Error>) + 'static>(
2436 file: &T,
2437 flags: MountUnmountFlags,
2438 cancellable: Option<&Cancellable>,
2439 callback: P,
2440 ) {
2441 use glib::translate::{IntoGlib, from_glib_full};
2442 use std::boxed::Box as Box_;
2443 let main_context = glib::MainContext::ref_thread_default();
2444 let is_main_context_owner = main_context.is_owner();
2445 let has_acquired_main_context = (!is_main_context_owner)
2446 .then(|| main_context.acquire().ok())
2447 .flatten();
2448 assert!(
2449 is_main_context_owner || has_acquired_main_context.is_some(),
2450 "Async operations only allowed if the thread is owning the MainContext"
2451 );
2452
2453 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
2454 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
2455 unsafe extern "C" fn unmount_mountable_trampoline<
2456 P: FnOnce(Result<(), glib::Error>) + 'static,
2457 >(
2458 _source_object: *mut glib::gobject_ffi::GObject,
2459 res: *mut crate::ffi::GAsyncResult,
2460 user_data: glib::ffi::gpointer,
2461 ) {
2462 unsafe {
2463 let mut error = std::ptr::null_mut();
2464 crate::ffi::g_file_unmount_mountable_finish(
2465 _source_object as *mut _,
2466 res,
2467 &mut error,
2468 );
2469 let result = if error.is_null() {
2470 Ok(())
2471 } else {
2472 Err(from_glib_full(error))
2473 };
2474 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
2475 Box_::from_raw(user_data as *mut _);
2476 let callback: P = callback.into_inner();
2477 callback(result);
2478 }
2479 }
2480 let callback = unmount_mountable_trampoline::<P>;
2481 unsafe {
2482 crate::ffi::g_file_unmount_mountable(
2483 file.as_ref().to_glib_none().0,
2484 flags.into_glib(),
2485 cancellable.to_glib_none().0,
2486 Some(callback),
2487 Box_::into_raw(user_data) as *mut _,
2488 );
2489 }
2490 }
2491
2492 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::unmount_mountable`
2493 let my_custom_path = MyCustomFile::new("/my_path");
2494
2495 let (tx, rx) = oneshot::channel();
2496 let res = glib::MainContext::ref_thread_default().block_on(async {
2497 unmount_mountable(
2498 &my_custom_path,
2499 MountUnmountFlags::NONE,
2500 Cancellable::NONE,
2501 move |res| tx.send(res).unwrap(),
2502 );
2503 rx.await.unwrap()
2504 });
2505 assert!(res.is_err(), "unexpected file unmount mountable success");
2506 let err = res.unwrap_err();
2507
2508 // invoke `MyFile` implementation of `crate::ffi::GFileIface::unmount_mountable`
2509 let my_path = MyFile::new("/my_path");
2510
2511 let (tx, rx) = oneshot::channel();
2512 let res = glib::MainContext::ref_thread_default().block_on(async {
2513 unmount_mountable(
2514 &my_path,
2515 MountUnmountFlags::NONE,
2516 Cancellable::NONE,
2517 move |res| tx.send(res).unwrap(),
2518 );
2519 rx.await.unwrap()
2520 });
2521 assert!(res.is_err(), "unexpected file unmount mountable success");
2522 let expected = res.unwrap_err();
2523
2524 // both errors should equal
2525 assert_eq!(err.message(), expected.message());
2526 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2527 });
2528 }
2529
2530 // checker-ignore-item
2531 #[test]
2532 fn file_eject_mountable() {
2533 // run test in a main context dedicated and configured as the thread default one
2534 let _ = glib::MainContext::new().with_thread_default(|| {
2535 // implement the deprecated function eject_mountable which is useful for this test
2536 fn eject_mountable<T: IsA<File>, P: FnOnce(Result<(), glib::Error>) + 'static>(
2537 file: &T,
2538 flags: MountUnmountFlags,
2539 cancellable: Option<&Cancellable>,
2540 callback: P,
2541 ) {
2542 use glib::translate::{IntoGlib, from_glib_full};
2543 use std::boxed::Box as Box_;
2544 let main_context = glib::MainContext::ref_thread_default();
2545 let is_main_context_owner = main_context.is_owner();
2546 let has_acquired_main_context = (!is_main_context_owner)
2547 .then(|| main_context.acquire().ok())
2548 .flatten();
2549 assert!(
2550 is_main_context_owner || has_acquired_main_context.is_some(),
2551 "Async operations only allowed if the thread is owning the MainContext"
2552 );
2553
2554 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
2555 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
2556 unsafe extern "C" fn eject_mountable_trampoline<
2557 P: FnOnce(Result<(), glib::Error>) + 'static,
2558 >(
2559 _source_object: *mut glib::gobject_ffi::GObject,
2560 res: *mut crate::ffi::GAsyncResult,
2561 user_data: glib::ffi::gpointer,
2562 ) {
2563 unsafe {
2564 let mut error = std::ptr::null_mut();
2565 crate::ffi::g_file_eject_mountable_finish(
2566 _source_object as *mut _,
2567 res,
2568 &mut error,
2569 );
2570 let result = if error.is_null() {
2571 Ok(())
2572 } else {
2573 Err(from_glib_full(error))
2574 };
2575 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
2576 Box_::from_raw(user_data as *mut _);
2577 let callback: P = callback.into_inner();
2578 callback(result);
2579 }
2580 }
2581 let callback = eject_mountable_trampoline::<P>;
2582 unsafe {
2583 crate::ffi::g_file_eject_mountable(
2584 file.as_ref().to_glib_none().0,
2585 flags.into_glib(),
2586 cancellable.to_glib_none().0,
2587 Some(callback),
2588 Box_::into_raw(user_data) as *mut _,
2589 );
2590 }
2591 }
2592
2593 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::eject_mountable`
2594 let my_custom_path = MyCustomFile::new("/my_path");
2595
2596 let (tx, rx) = oneshot::channel();
2597 let res = glib::MainContext::ref_thread_default().block_on(async {
2598 eject_mountable(
2599 &my_custom_path,
2600 MountUnmountFlags::NONE,
2601 Cancellable::NONE,
2602 move |res| tx.send(res).unwrap(),
2603 );
2604 rx.await.unwrap()
2605 });
2606 assert!(res.is_err(), "unexpected file eject mountable success");
2607 let err = res.unwrap_err();
2608
2609 // invoke `MyFile` implementation of `crate::ffi::GFileIface::eject_mountable`
2610 let my_path = MyFile::new("/my_path");
2611
2612 let (tx, rx) = oneshot::channel();
2613 let res = glib::MainContext::ref_thread_default().block_on(async {
2614 eject_mountable(
2615 &my_path,
2616 MountUnmountFlags::NONE,
2617 Cancellable::NONE,
2618 move |res| tx.send(res).unwrap(),
2619 );
2620 rx.await.unwrap()
2621 });
2622 assert!(res.is_err(), "unexpected file eject mountable success");
2623 let expected = res.unwrap_err();
2624
2625 // both errors should equal
2626 assert_eq!(err.message(), expected.message());
2627 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2628 });
2629 }
2630
2631 #[test]
2632 fn file_mount_enclosing_volume() {
2633 // run test in a main context dedicated and configured as the thread default one
2634 let _ = glib::MainContext::new().with_thread_default(|| {
2635 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::mount_enclosing_volume`
2636 let my_custom_path = MyCustomFile::new("/my_path");
2637
2638 let (tx, rx) = oneshot::channel();
2639 let res = glib::MainContext::ref_thread_default().block_on(async {
2640 my_custom_path.mount_enclosing_volume(
2641 MountMountFlags::NONE,
2642 MountOperation::NONE,
2643 Cancellable::NONE,
2644 move |res| tx.send(res).unwrap(),
2645 );
2646 rx.await.unwrap()
2647 });
2648 assert!(
2649 res.is_err(),
2650 "unexpected file mount enclosing volume success"
2651 );
2652 let err = res.unwrap_err();
2653
2654 // invoke `MyFile` implementation of `crate::ffi::GFileIface::mount_enclosing_volume`
2655 let my_path = MyFile::new("/my_path");
2656
2657 let (tx, rx) = oneshot::channel();
2658 let res = glib::MainContext::ref_thread_default().block_on(async {
2659 my_path.mount_enclosing_volume(
2660 MountMountFlags::NONE,
2661 MountOperation::NONE,
2662 Cancellable::NONE,
2663 move |res| tx.send(res).unwrap(),
2664 );
2665 rx.await.unwrap()
2666 });
2667 assert!(
2668 res.is_err(),
2669 "unexpected file mount enclosing volume success"
2670 );
2671 let expected = res.unwrap_err();
2672
2673 // both errors should equal
2674 assert_eq!(err.message(), expected.message());
2675 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2676 });
2677 }
2678
2679 #[test]
2680 fn file_monitor_dir() {
2681 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::monitor_dir`
2682 let my_custom_file =
2683 MyCustomFile::with_type_state("/my_file", FileType::Regular, MyFileState::Exist);
2684 let res = my_custom_file.monitor_directory(FileMonitorFlags::NONE, Cancellable::NONE);
2685 assert!(res.is_err(), "unexpected monitor");
2686 let err = res.unwrap_err();
2687
2688 // invoke `MyFile` implementation of `crate::ffi::GFileIface::monitor_dir`
2689 let my_file = MyFile::with_type_state("/my_file", FileType::Regular, MyFileState::Exist);
2690 let res = my_file.monitor_directory(FileMonitorFlags::NONE, Cancellable::NONE);
2691 assert!(res.is_err(), "unexpected monitor");
2692 let expected = res.unwrap_err();
2693
2694 // both errors should equal
2695 assert_eq!(err.message(), expected.message());
2696 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2697
2698 // run test in a main context dedicated and configured as the thread default one
2699 let _ = glib::MainContext::new().with_thread_default(|| {
2700 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::monitor_dir`
2701 let my_custom_dir =
2702 MyCustomFile::with_type_state("/my_directory", FileType::Directory, MyFileState::Exist);
2703 let res = my_custom_dir.monitor_directory(FileMonitorFlags::NONE, Cancellable::NONE);
2704 assert!(res.is_ok(), "{}", res.unwrap_err());
2705 let my_custom_dir_monitor = res.unwrap();
2706
2707 let rx = {
2708 let (tx, rx) = async_channel::bounded(3);
2709 my_custom_dir_monitor.connect_changed(move |_, file, other_file, event_type| {
2710 let res = glib::MainContext::ref_thread_default().block_on(tx.send((
2711 file.uri(),
2712 other_file.map(File::uri),
2713 event_type,
2714 )));
2715 assert!(res.is_ok(), "{}", res.err().unwrap());
2716 });
2717 rx
2718 };
2719 // emit 1st event
2720 let my_custom_child =
2721 MyCustomFile::with_type_state("/my_child", FileType::Regular, MyFileState::Exist);
2722 my_custom_dir_monitor.emit_event(
2723 &my_custom_child,
2724 None::<&MyCustomFile>,
2725 FileMonitorEvent::Created,
2726 );
2727 // emit 2nd event
2728 my_custom_dir_monitor.emit_event(
2729 &my_custom_child,
2730 None::<&MyCustomFile>,
2731 FileMonitorEvent::Changed,
2732 );
2733 // emit 3rd event
2734 my_custom_dir_monitor.emit_event(
2735 &my_custom_child,
2736 None::<&MyCustomFile>,
2737 FileMonitorEvent::ChangesDoneHint,
2738 );
2739 let res = glib::MainContext::ref_thread_default().block_on(rx.recv());
2740 assert!(res.is_ok(), "{}", res.err().unwrap());
2741 let event1 = res.unwrap();
2742 let res = glib::MainContext::ref_thread_default().block_on(rx.recv());
2743 assert!(res.is_ok(), "{}", res.err().unwrap());
2744 let event2 = res.unwrap();
2745 let res = glib::MainContext::ref_thread_default().block_on(rx.recv());
2746 assert!(res.is_ok(), "{}", res.err().unwrap());
2747 let event3 = res.unwrap();
2748
2749 // invoke `MyFile` implementation of `crate::ffi::GFileIface::monitor_dir`
2750 let my_dir =
2751 MyFile::with_type_state("/my_directory", FileType::Directory, MyFileState::Exist);
2752 let res = my_dir.monitor_directory(FileMonitorFlags::NONE, Cancellable::NONE);
2753 assert!(res.is_ok(), "{}", res.unwrap_err());
2754 let my_dir_monitor = res.unwrap();
2755
2756 let rx = {
2757 let (tx, rx) = async_channel::bounded(3);
2758 my_dir_monitor.connect_changed(move |_, file, other_file, event_type| {
2759 let res = glib::MainContext::ref_thread_default().block_on(tx.send((
2760 file.uri(),
2761 other_file.map(File::uri),
2762 event_type,
2763 )));
2764 assert!(res.is_ok(), "{}", res.err().unwrap());
2765 });
2766 rx
2767 };
2768 // emit an event
2769 let my_child = MyFile::with_type_state("/my_child", FileType::Regular, MyFileState::Exist);
2770 my_dir_monitor.emit_event(&my_child, None::<&MyFile>, FileMonitorEvent::Created);
2771 my_dir_monitor.emit_event(&my_child, None::<&MyFile>, FileMonitorEvent::Changed);
2772 my_dir_monitor.emit_event(
2773 &my_child,
2774 None::<&MyFile>,
2775 FileMonitorEvent::ChangesDoneHint,
2776 );
2777 let res = glib::MainContext::ref_thread_default().block_on(rx.recv());
2778 assert!(res.is_ok(), "{}", res.err().unwrap());
2779 let expected1 = res.unwrap();
2780 let res = glib::MainContext::ref_thread_default().block_on(rx.recv());
2781 assert!(res.is_ok(), "{}", res.err().unwrap());
2782 let expected2 = res.unwrap();
2783 let res = glib::MainContext::ref_thread_default().block_on(rx.recv());
2784 assert!(res.is_ok(), "{}", res.err().unwrap());
2785 let expected3 = res.unwrap();
2786
2787 // both events should equal
2788 assert_eq!(event1, expected1);
2789 assert_eq!(event2, expected2);
2790 assert_eq!(event3, expected3);
2791 });
2792 }
2793
2794 #[test]
2795 fn file_monitor_file() {
2796 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::monitor_file`
2797 let my_custom_dir =
2798 MyCustomFile::with_type_state("/my_directory", FileType::Directory, MyFileState::Exist);
2799 let res = my_custom_dir.monitor_file(FileMonitorFlags::NONE, Cancellable::NONE);
2800 assert!(res.is_ok(), "{}", res.unwrap_err());
2801 let monitor = res.unwrap();
2802 assert_ne!(monitor.type_(), MyFileMonitor::static_type());
2803
2804 // invoke `MyFile` implementation of `crate::ffi::GFileIface::monitor_file`
2805 let my_dir = MyFile::with_type_state("/my_directory", FileType::Directory, MyFileState::Exist);
2806 let res = my_dir.monitor_file(FileMonitorFlags::NONE, Cancellable::NONE);
2807 let expected = res.unwrap();
2808 assert_ne!(expected.type_(), MyFileMonitor::static_type());
2809
2810 // both results should equal
2811 assert_eq!(monitor.type_(), expected.type_());
2812
2813 // run test in a main context dedicated and configured as the thread default one
2814 let _ = glib::MainContext::new().with_thread_default(|| {
2815 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::monitor_file`
2816 let my_custom_file =
2817 MyCustomFile::with_type_state("/my_file", FileType::Regular, MyFileState::Exist);
2818 let res = my_custom_file.monitor_file(FileMonitorFlags::NONE, Cancellable::NONE);
2819 assert!(res.is_ok(), "{}", res.unwrap_err());
2820 let my_custom_file_monitor = res.unwrap();
2821
2822 let rx = {
2823 let (tx, rx) = async_channel::bounded(2);
2824 my_custom_file_monitor.connect_changed(move |_, file, other_file, event_type| {
2825 let res = glib::MainContext::ref_thread_default().block_on(tx.send((
2826 file.uri(),
2827 other_file.map(File::uri),
2828 event_type,
2829 )));
2830 assert!(res.is_ok(), "{}", res.err().unwrap());
2831 });
2832 rx
2833 };
2834 // emit 1st event
2835 my_custom_file_monitor.emit_event(
2836 &my_custom_file,
2837 None::<&MyCustomFile>,
2838 FileMonitorEvent::Changed,
2839 );
2840 // emit 2nd event
2841 my_custom_file_monitor.emit_event(
2842 &my_custom_file,
2843 None::<&MyCustomFile>,
2844 FileMonitorEvent::ChangesDoneHint,
2845 );
2846 let res = glib::MainContext::ref_thread_default().block_on(rx.recv());
2847 assert!(res.is_ok(), "{}", res.err().unwrap());
2848 let event1 = res.unwrap();
2849 let res = glib::MainContext::ref_thread_default().block_on(rx.recv());
2850 assert!(res.is_ok(), "{}", res.err().unwrap());
2851 let event2 = res.unwrap();
2852
2853 // invoke `MyFile` implementation of `crate::ffi::GFileIface::monitor_file`
2854 let my_file = MyFile::with_type_state("/my_file", FileType::Regular, MyFileState::Exist);
2855 let res = my_file.monitor_file(FileMonitorFlags::NONE, Cancellable::NONE);
2856 assert!(res.is_ok(), "{}", res.unwrap_err());
2857 let my_file_monitor = res.unwrap();
2858
2859 let rx = {
2860 let (tx, rx) = async_channel::bounded(2);
2861 my_file_monitor.connect_changed(move |_, file, other_file, event_type| {
2862 let res = glib::MainContext::ref_thread_default().block_on(tx.send((
2863 file.uri(),
2864 other_file.map(File::uri),
2865 event_type,
2866 )));
2867 assert!(res.is_ok(), "{}", res.err().unwrap());
2868 });
2869 rx
2870 };
2871 // emit an event
2872 my_file_monitor.emit_event(&my_file, None::<&MyFile>, FileMonitorEvent::Changed);
2873 my_file_monitor.emit_event(&my_file, None::<&MyFile>, FileMonitorEvent::ChangesDoneHint);
2874 let res = glib::MainContext::ref_thread_default().block_on(rx.recv());
2875 assert!(res.is_ok(), "{}", res.err().unwrap());
2876 let expected1 = res.unwrap();
2877 let res = glib::MainContext::ref_thread_default().block_on(rx.recv());
2878 assert!(res.is_ok(), "{}", res.err().unwrap());
2879 let expected2 = res.unwrap();
2880
2881 // both events should equal
2882 assert_eq!(event1, expected1);
2883 assert_eq!(event2, expected2);
2884 });
2885 }
2886
2887 #[test]
2888 fn file_open_readwrite() {
2889 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::open_readwrite`
2890 let my_custom_file = MyCustomFile::new("/my_file");
2891 let res = my_custom_file.open_readwrite(Cancellable::NONE);
2892 assert!(
2893 res.is_err(),
2894 "unexpected file open read write success {:?}",
2895 res.ok().unwrap()
2896 );
2897 let err = res.unwrap_err();
2898
2899 // invoke `MyFile` implementation of `crate::ffi::GFileIface::open_readwrite`
2900 let my_file = MyFile::new("/my_file");
2901 let res = my_file.open_readwrite(Cancellable::NONE);
2902 assert!(
2903 res.is_err(),
2904 "unexpected file open read write success {:?}",
2905 res.ok().unwrap()
2906 );
2907 let expected = res.unwrap_err();
2908
2909 // both errors should equal
2910 assert_eq!(err.message(), expected.message());
2911 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2912 }
2913
2914 #[test]
2915 fn file_create_readwrite() {
2916 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::create_readwrite`
2917 let my_custom_file = MyCustomFile::new("/my_file");
2918 let res = my_custom_file.create_readwrite(FileCreateFlags::NONE, Cancellable::NONE);
2919 assert!(
2920 res.is_err(),
2921 "unexpected file create read write success {:?}",
2922 res.ok().unwrap()
2923 );
2924 let err = res.unwrap_err();
2925
2926 // invoke `MyFile` implementation of `crate::ffi::GFileIface::create_readwrite`
2927 let my_file = MyFile::new("/my_file");
2928 let res = my_file.create_readwrite(FileCreateFlags::NONE, Cancellable::NONE);
2929 assert!(
2930 res.is_err(),
2931 "unexpected file create read write success {:?}",
2932 res.ok().unwrap()
2933 );
2934 let expected = res.unwrap_err();
2935
2936 // both errors should equal
2937 assert_eq!(err.message(), expected.message());
2938 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2939 }
2940
2941 #[test]
2942 fn file_replace_readwrite() {
2943 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::replace_readwrite`
2944 let my_custom_file = MyCustomFile::new("/my_file");
2945 let res =
2946 my_custom_file.replace_readwrite(None, false, FileCreateFlags::NONE, Cancellable::NONE);
2947 assert!(
2948 res.is_err(),
2949 "unexpected file replace read write success {:?}",
2950 res.ok().unwrap()
2951 );
2952 let err = res.unwrap_err();
2953
2954 // invoke `MyFile` implementation of `crate::ffi::GFileIface::replace_readwrite`
2955 let my_file = MyFile::new("/my_file");
2956 let res = my_file.replace_readwrite(None, false, FileCreateFlags::NONE, Cancellable::NONE);
2957 assert!(
2958 res.is_err(),
2959 "unexpected file replace read write success {:?}",
2960 res.ok().unwrap()
2961 );
2962 let expected = res.unwrap_err();
2963
2964 // both errors should equal
2965 assert_eq!(err.message(), expected.message());
2966 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
2967 }
2968
2969 #[test]
2970 fn file_start_mountable() {
2971 // run test in a main context dedicated and configured as the thread default one
2972 let _ = glib::MainContext::new().with_thread_default(|| {
2973 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::start_mountable`
2974 let my_custom_path = MyCustomFile::new("/my_path");
2975
2976 let (tx, rx) = oneshot::channel();
2977 let res = glib::MainContext::ref_thread_default().block_on(async {
2978 my_custom_path.start_mountable(
2979 DriveStartFlags::NONE,
2980 MountOperation::NONE,
2981 Cancellable::NONE,
2982 move |res| tx.send(res).unwrap(),
2983 );
2984 rx.await.unwrap()
2985 });
2986 assert!(res.is_err(), "unexpected file start mountable success");
2987 let err = res.unwrap_err();
2988
2989 // invoke `MyFile` implementation of `crate::ffi::GFileIface::start_mountable`
2990 let my_path = MyFile::new("/my_path");
2991
2992 let (tx, rx) = oneshot::channel();
2993 let res = glib::MainContext::ref_thread_default().block_on(async {
2994 my_path.start_mountable(
2995 DriveStartFlags::NONE,
2996 MountOperation::NONE,
2997 Cancellable::NONE,
2998 move |res| tx.send(res).unwrap(),
2999 );
3000 rx.await.unwrap()
3001 });
3002 assert!(res.is_err(), "unexpected file start mountable success");
3003 let expected = res.unwrap_err();
3004
3005 // both errors should equal
3006 assert_eq!(err.message(), expected.message());
3007 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
3008 });
3009 }
3010
3011 #[test]
3012 fn file_stop_mountable() {
3013 // run test in a main context dedicated and configured as the thread default one
3014 let _ = glib::MainContext::new().with_thread_default(|| {
3015 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::stop_mountable`
3016 let my_custom_path = MyCustomFile::new("/my_path");
3017
3018 let (tx, rx) = oneshot::channel();
3019 let res = glib::MainContext::ref_thread_default().block_on(async {
3020 my_custom_path.stop_mountable(
3021 MountUnmountFlags::NONE,
3022 MountOperation::NONE,
3023 Cancellable::NONE,
3024 move |res| tx.send(res).unwrap(),
3025 );
3026 rx.await.unwrap()
3027 });
3028 assert!(res.is_err(), "unexpected file stop mountable success");
3029 let err = res.unwrap_err();
3030
3031 // invoke `MyFile` implementation of `crate::ffi::GFileIface::stop_mountable`
3032 let my_path = MyFile::new("/my_path");
3033
3034 let (tx, rx) = oneshot::channel();
3035 let res = glib::MainContext::ref_thread_default().block_on(async {
3036 my_path.stop_mountable(
3037 MountUnmountFlags::NONE,
3038 MountOperation::NONE,
3039 Cancellable::NONE,
3040 move |res| tx.send(res).unwrap(),
3041 );
3042 rx.await.unwrap()
3043 });
3044 assert!(res.is_err(), "unexpected file stop mountable success");
3045 let expected = res.unwrap_err();
3046
3047 // both errors should equal
3048 assert_eq!(err.message(), expected.message());
3049 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
3050 });
3051 }
3052
3053 #[test]
3054 fn file_unmount_mountable_with_operation() {
3055 // run test in a main context dedicated and configured as the thread default one
3056 let _ = glib::MainContext::new().with_thread_default(|| {
3057 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::unmount_mountable_with_operation`
3058 let my_custom_path = MyCustomFile::new("/my_path");
3059
3060 let (tx, rx) = oneshot::channel();
3061 let res = glib::MainContext::ref_thread_default().block_on(async {
3062 my_custom_path.unmount_mountable_with_operation(
3063 MountUnmountFlags::NONE,
3064 MountOperation::NONE,
3065 Cancellable::NONE,
3066 move |res| tx.send(res).unwrap(),
3067 );
3068 rx.await.unwrap()
3069 });
3070 assert!(
3071 res.is_err(),
3072 "unexpected file unmount mountable with operation success"
3073 );
3074 let err = res.unwrap_err();
3075
3076 // invoke `MyFile` implementation of `crate::ffi::GFileIface::unmount_mountable_with_operation`
3077 let my_path = MyFile::new("/my_path");
3078
3079 let (tx, rx) = oneshot::channel();
3080 let res = glib::MainContext::ref_thread_default().block_on(async {
3081 my_path.unmount_mountable_with_operation(
3082 MountUnmountFlags::NONE,
3083 MountOperation::NONE,
3084 Cancellable::NONE,
3085 move |res| tx.send(res).unwrap(),
3086 );
3087 rx.await.unwrap()
3088 });
3089 assert!(
3090 res.is_err(),
3091 "unexpected file unmount mountable with operation success"
3092 );
3093 let expected = res.unwrap_err();
3094
3095 // both errors should equal
3096 assert_eq!(err.message(), expected.message());
3097 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
3098 });
3099 }
3100
3101 #[test]
3102 fn file_eject_mountable_with_operation() {
3103 // run test in a main context dedicated and configured as the thread default one
3104 let _ = glib::MainContext::new().with_thread_default(|| {
3105 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::eject_mountable_with_operation`
3106 let my_custom_path = MyCustomFile::new("/my_path");
3107
3108 let (tx, rx) = oneshot::channel();
3109 let res = glib::MainContext::ref_thread_default().block_on(async {
3110 my_custom_path.eject_mountable_with_operation(
3111 MountUnmountFlags::NONE,
3112 MountOperation::NONE,
3113 Cancellable::NONE,
3114 move |res| tx.send(res).unwrap(),
3115 );
3116 rx.await.unwrap()
3117 });
3118 assert!(
3119 res.is_err(),
3120 "unexpected file eject mountable with operation success"
3121 );
3122 let err = res.unwrap_err();
3123
3124 // invoke `MyFile` implementation of `crate::ffi::GFileIface::eject_mountable_with_operation`
3125 let my_path = MyFile::new("/my_path");
3126
3127 let (tx, rx) = oneshot::channel();
3128 let res = glib::MainContext::ref_thread_default().block_on(async {
3129 my_path.eject_mountable_with_operation(
3130 MountUnmountFlags::NONE,
3131 MountOperation::NONE,
3132 Cancellable::NONE,
3133 move |res| tx.send(res).unwrap(),
3134 );
3135 rx.await.unwrap()
3136 });
3137 assert!(
3138 res.is_err(),
3139 "unexpected file eject mountable with operation success"
3140 );
3141 let expected = res.unwrap_err();
3142
3143 // both errors should equal
3144 assert_eq!(err.message(), expected.message());
3145 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
3146 });
3147 }
3148
3149 #[test]
3150 fn file_poll_mountable() {
3151 // run test in a main context dedicated and configured as the thread default one
3152 let _ = glib::MainContext::new().with_thread_default(|| {
3153 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::poll_mountable`
3154 let my_custom_path = MyCustomFile::new("/my_path");
3155
3156 let (tx, rx) = oneshot::channel();
3157 let res = glib::MainContext::ref_thread_default().block_on(async {
3158 my_custom_path.poll_mountable(Cancellable::NONE, move |res| tx.send(res).unwrap());
3159 rx.await.unwrap()
3160 });
3161 assert!(res.is_err(), "unexpected file poll mountable success");
3162 let err = res.unwrap_err();
3163
3164 // invoke `MyFile` implementation of `crate::ffi::GFileIface::poll_mountable`
3165 let my_path = MyFile::new("/my_path");
3166
3167 let (tx, rx) = oneshot::channel();
3168 let res = glib::MainContext::ref_thread_default().block_on(async {
3169 my_path.poll_mountable(Cancellable::NONE, move |res| tx.send(res).unwrap());
3170 rx.await.unwrap()
3171 });
3172 assert!(res.is_err(), "unexpected file poll mountable success");
3173 let expected = res.unwrap_err();
3174
3175 // both errors should equal
3176 assert_eq!(err.message(), expected.message());
3177 assert_eq!(err.kind::<IOErrorEnum>(), expected.kind::<IOErrorEnum>());
3178 });
3179 }
3180
3181 #[test]
3182 fn file_measure_disk_usage() {
3183 // invoke `MyCustomFile` implementation of `crate::ffi::GFileIface::measure_disk_usage`
3184 let my_custom_file =
3185 MyCustomFile::with_type_state("/my_file", FileType::Regular, MyFileState::Exist);
3186
3187 let (mut completed, mut size, mut nb_dirs, mut nb_files) = (false, 0u64, 0u64, 0u64);
3188 let res = my_custom_file.measure_disk_usage(
3189 FileMeasureFlags::NONE,
3190 Cancellable::NONE,
3191 Some(
3192 &mut move |reporting: bool, current_size, num_dirs, num_files| {
3193 if reporting {
3194 assert!(!completed);
3195 }
3196 assert!(current_size >= size);
3197 assert!(num_dirs >= nb_dirs);
3198 assert!(num_files >= nb_files);
3199 completed = !reporting;
3200 size = current_size;
3201 nb_dirs = num_dirs;
3202 nb_files = num_files;
3203 },
3204 ),
3205 );
3206 assert!(res.is_ok(), "{}", res.unwrap_err());
3207 let result = res.unwrap();
3208
3209 // invoke `MyFile` implementation of `crate::ffi::GFileIface::measure_disk_usage`
3210 let my_file = MyFile::with_type_state("/my_file", FileType::Regular, MyFileState::Exist);
3211 let (mut completed, mut size, mut nb_dirs, mut nb_files) = (false, 0u64, 0u64, 0u64);
3212 let res = my_file.measure_disk_usage(
3213 FileMeasureFlags::NONE,
3214 Cancellable::NONE,
3215 Some(
3216 &mut move |reporting: bool, current_size, num_dirs, num_files| {
3217 if reporting {
3218 assert!(!completed);
3219 }
3220 assert!(current_size >= size);
3221 assert!(num_dirs >= nb_dirs);
3222 assert!(num_files >= nb_files);
3223 completed = !reporting;
3224 size = current_size;
3225 nb_dirs = num_dirs;
3226 nb_files = num_files;
3227 },
3228 ),
3229 );
3230 assert!(res.is_ok(), "{}", res.unwrap_err());
3231 let expected = res.unwrap();
3232
3233 // both results should equal
3234 assert_eq!(result, expected);
3235 }