v2 / vlib / os / os_stat_test.v
69 lines · 59 sloc · 2.46 KB · 84135d733a45b6b9ff337e171bce03692115e906
Raw
1import os
2import rand
3import time
4
5fn test_stat() {
6 start_time := time.utc().add(-2 * time.second)
7
8 temp_dir := os.join_path(os.temp_dir(), rand.ulid())
9 os.mkdir(temp_dir)!
10 defer {
11 os.rmdir(temp_dir) or {}
12 }
13
14 test_file := os.join_path(temp_dir, rand.ulid())
15 test_content := rand.ulid()
16 os.write_file(test_file, test_content)!
17 defer {
18 os.rm(test_file) or {}
19 }
20
21 end_time := time.utc()
22
23 mut fstat := os.stat(test_file)!
24 eprintln(@LOCATION)
25 eprintln(' | start_time: ${start_time.unix()}\n | end_time: ${end_time.unix()}\n | fstat.ctime: ${fstat.ctime}\n | fstat.mtime: ${fstat.mtime}')
26 assert fstat.get_filetype() == .regular
27 assert fstat.size == u64(test_content.len)
28 assert fstat.ctime >= start_time.unix()
29 assert fstat.ctime <= end_time.unix()
30 assert fstat.mtime >= start_time.unix()
31 assert fstat.mtime <= end_time.unix()
32
33 $if !windows {
34 os.chmod(test_file, 0o600)!
35 fstat = os.stat(test_file)!
36
37 mut fmode := fstat.get_mode()
38 assert fmode.typ == .regular
39 assert fmode.owner.read && fmode.owner.write && !fmode.owner.execute
40 assert !fmode.group.read && !fmode.group.write && !fmode.group.execute
41 assert !fmode.others.read && !fmode.others.write && !fmode.others.execute
42
43 os.chmod(test_file, 0o421)!
44 fstat = os.stat(test_file)!
45 fmode = fstat.get_mode()
46 assert fmode.owner.read && !fmode.owner.write && !fmode.owner.execute
47 assert !fmode.group.read && fmode.group.write && !fmode.group.execute
48 assert !fmode.others.read && !fmode.others.write && fmode.others.execute
49
50 os.chmod(test_file, 0o600)!
51 }
52
53 // When using the Time struct, allow for up to 1 second difference due to nanoseconds
54 // which are not captured in the timestamp
55 dstat := os.stat(temp_dir)!
56 assert dstat.get_filetype() == .directory
57 assert fstat.dev == dstat.dev, 'File and directory should be created on same device'
58 $if !freebsd && !openbsd {
59 assert fstat.rdev == dstat.rdev, 'File and directory should have same device ID'
60 } $else {
61 // On FreeBSD and OpenBSD, the rdev values are not necessarily the same for non-devices
62 // such as regular files and directories.
63 // assert fstat.rdev != dstat.rdev, 'File and directory should not have same device ID'
64 // However, see also https://discord.com/channels/592103645835821068/592114487759470596/1222322061217632347 :
65 // > They may be different but don't have to be.
66 // > On zfs it seems to be 0.
67 // Once upon a time (Unix v7) it was (major<<8)|minor to indicate the underlying raw device but those days are long gone.
68 }
69}
70