Unit test /tmp path question

In XCTestCase, I write data to a file "/tmp/somefile", but the file does not exist in /tmp when I do ls in Terminal.

Where is the file actually created?

Answered by Documentation Engineer in 790069022

Hello!

Are you receiving an error when you write the file? If you're using e.g. Data's write(to:options:) then you'd see an error if it didn't create the file.

How are you creating the path to your temporary directory? I'd recommend using NSFileManager's temporaryDirectory which will find the correct path. This will identify the correct temporary directory to use in all scenarios, "/tmp" itself may not always be appropriate.

Here's some sample code, this creates a file which happens to be in /var/folders/pb/c447t7310p78y0wvh40l6q0m0000gp/T/ as that's identified as the correct temporary directory.

let tempDirectory = FileManager.default.temporaryDirectory
let newFileURL = tempDirectory.appendingPathComponent("MyFile.txt")
try "Hello, World!".write(to: newFileURL, atomically: true, encoding: .utf8)
print("Path of the temporary file: \(newFileURL)")

Hello!

Are you receiving an error when you write the file? If you're using e.g. Data's write(to:options:) then you'd see an error if it didn't create the file.

How are you creating the path to your temporary directory? I'd recommend using NSFileManager's temporaryDirectory which will find the correct path. This will identify the correct temporary directory to use in all scenarios, "/tmp" itself may not always be appropriate.

Here's some sample code, this creates a file which happens to be in /var/folders/pb/c447t7310p78y0wvh40l6q0m0000gp/T/ as that's identified as the correct temporary directory.

let tempDirectory = FileManager.default.temporaryDirectory
let newFileURL = tempDirectory.appendingPathComponent("MyFile.txt")
try "Hello, World!".write(to: newFileURL, atomically: true, encoding: .utf8)
print("Path of the temporary file: \(newFileURL)")

It's strange. When I tried again, I found the file in /tmp:

- (void)test {
    NSError* error;
    [@"abc123" writeToFile:@"/tmp/testfile" atomically:NO encoding:NSUTF8StringEncoding error:&error];
    if (error) NSLog(@"%@", error);
}
Unit test /tmp path question
 
 
Q