1 /*
2  * Copyright (C) 2023 Square, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package okio
17 
18 import kotlin.test.BeforeTest
19 import kotlin.test.Test
20 import kotlin.test.assertEquals
21 import kotlin.test.assertFailsWith
22 import kotlin.test.assertNull
23 import okio.Path.Companion.toPath
24 
25 /**
26  * Confirm the [WasiFileSystem] can operate on different preopened directories independently.
27  *
28  * This tracks the `preopens` attribute in `.mjs` script in `okio-wasifilesystem/build.gradle.kts`.
29  */
30 class WasiFileSystemPreopensTest {
31   private val fileSystem = WasiFileSystem
32   private val testId = "${this::class.simpleName}-${randomToken(16)}"
33   private val baseA: Path = "/a".toPath() / testId
34   private val baseB: Path = "/b".toPath() / testId
35 
36   @BeforeTest
setUpnull37   fun setUp() {
38     fileSystem.createDirectory(baseA)
39     fileSystem.createDirectory(baseB)
40   }
41 
42   @Test
operateOnPreopensnull43   fun operateOnPreopens() {
44     fileSystem.write(baseA / "a.txt") {
45       writeUtf8("hello world a")
46     }
47     fileSystem.write(baseB / "b.txt") {
48       writeUtf8("bello burld")
49     }
50     assertEquals(
51       "hello world a".length.toLong(),
52       fileSystem.metadata(baseA / "a.txt").size,
53     )
54     assertEquals(
55       "bello burld".length.toLong(),
56       fileSystem.metadata(baseB / "b.txt").size,
57     )
58   }
59 
60   @Test
operateAcrossPreopensnull61   fun operateAcrossPreopens() {
62     fileSystem.write(baseA / "a.txt") {
63       writeUtf8("hello world")
64     }
65 
66     fileSystem.atomicMove(baseA / "a.txt", baseB / "b.txt")
67 
68     assertEquals(
69       "hello world",
70       fileSystem.read(baseB / "b.txt") {
71         readUtf8()
72       },
73     )
74   }
75 
76   @Test
cannotOperateOutsideOfPreopensnull77   fun cannotOperateOutsideOfPreopens() {
78     val noPreopen = "/c".toPath() / testId
79     assertFailsWith<FileNotFoundException> {
80       fileSystem.createDirectory(noPreopen)
81     }
82     assertFailsWith<FileNotFoundException> {
83       fileSystem.sink(noPreopen)
84     }
85     assertNull(fileSystem.metadataOrNull(noPreopen))
86     assertFailsWith<FileNotFoundException> {
87       fileSystem.metadata(noPreopen)
88     }
89     assertNull(fileSystem.listOrNull(noPreopen))
90     assertFailsWith<FileNotFoundException> {
91       fileSystem.list(noPreopen)
92     }
93   }
94 }
95