Xcode writing to file in a unit test - ios

I understand that when a unit test executes, it is in the sandbox environment of Xcode.
In a unit test, I need to write and read data to a file.
Since the project resides in a git repository, this must be done completely from within code (i.e. no special manual test setup of directories is possible)
For all my searching and trying today, I cannot find a way to write to a file from within the unit test.
Does anybody know of a method to write to a file under these conditions?
Edit: This is the problematic code:
let dirPath = NSTemporaryDirectory()!
var filePath = dirPath.stringByAppendingPathComponent("unittest.json")
if !NSFileManager.defaultManager().isWritableFileAtPath(filePath) {
return (nil, "Directory missing or write access not granted for \(path)")
}

You should be able to use the temporary directory: NSTemporaryDirectory() and have it reliably point to a safe place to read and write. I'd suggest making sure you clean up any created files.
let dirPath = NSTemporaryDirectory()
To see whether a file can be created (per the updated question), check the directory for write permissions:
let canCreate = NSFileManager.defaultManager().isWritableFileAtPath(dirPath)

Related

How do I compare 2 files with the same name in iOS to check if they are copies of the same file or different files

I am using UIDocument to save a document file to the local storage sandbox in the Documents directory. I have another file in iCloud with the same name. How would I check if those two files are copies of the same document file or two different document files with the same name?
Using NSFileVersion doesn't tell me if they are the same file, just what version of the file it is.
I tried getting the resource values of the files, but the file in the local storage sandbox gives me nil as the document identifier.
Here is code using the documentIdentifier resource value:
let localFileResourceValues = try? self.document!.fileURL.resourceValues(forKeys: [URLResourceKey.documentIdentifierKey])
let iCloudFileResourceValues = try? destinationURL.resourceValues(forKeys: [URLResourceKey.documentIdentifierKey])
print("documentIdentifier", localFileResourceValues?.documentIdentifier as Any, iCloudFileResourceValues?.documentIdentifier as Any, localFileResourceValues?.documentIdentifier == iCloudFileResourceValues?.documentIdentifier)
Print results:
documentIdentifier nil Optional(133819) false
Is it possible to get an NSMetadataItem from a file in the local storage sandbox?
I would appreciate any help.
To find out if the two file paths point to the same file object, you need to normalise the file paths by using NSString stringByStandardizingPath, then resolve symbolic links by using NSString stringByResolvingSymlinksInPath:, and then compare the paths. This web page has a good description and ready-to-go code.
To find out whether two files have the same contents, even while they might be different file objects, then NSFileManager contentsEqualAtPath:andPath: is useful.

Using Grails to store image but could not store outside CATALINA_HOME in production

I'm using Grails 2.5.6 to store uploaded images to folder on a server.
The following are my code to store the image
mpr.multiFileMap.file.each{fileData->
CommonsMultipartFile file = fileData
File convFile = new File(file.getOriginalFilename());
file.transferTo(convFile);
/** Processing File **/
File uploadedFile = new File("${directory}${generatedFileName}.${extension}")
convFile.renameTo(uploadedFile)
}
I have no problem running on development (MacOSX High Sierra)
But when i deployed on production (Ubuntu 14.04 server), i could not save the file outside CATALINA_HOME directory.
I have checked the permission and ownership of the destination directory, but still, the directory was created but the file was never stored.
For Example, i've tried to store the file on /home/tomcat/ directory (/home directory was in separate partition with tomcat which stored it /var), the directory was created, but the file was never stored.
When i put the destination directory within CATALINA_HOME folder, everything works fine. But this was not the scenario i want to do.
You say your destination directory is on another partition, so maybe another filesystem is used on this partition.
Or if you look on the javadoc of the renameTo method it is said :
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make
sure that the rename operation was successful.
...
#return true if and only if the renaming succeeded;
false otherwise
Thus I think the renameTo method is not able to move the file, don't know why but you can rewrite your code like this :
mpr.multiFileMap.file.each{fileData->
CommonsMultipartFile file = fileData
File uploadedFile = new File("${directory}${generatedFileName}.${extension}")
// String originalFilename = file.getOriginalFilename()
// you can store originalFilename in database for example
if(!uploadedFile.getParentFile().exists()) {
uploadedFile.getParentFile().mkdirs()
// You can set permissions on the target directory if you desired, using PosixFilePermission
}
file.transferTo(uploadedFile)
}

Save Lokijs DB in Electron

there is some way from inside the "main.js" electron to save a file out of the asar?
I'm fighting with this command to point the way out of the write-only area but I can not do it.
It would be nice that the path was inside /my-project/resources/ and would work even without the electron-package.
let configFilePath = `${__dirname}/../config.json`
db = new loki(configFilePath)
if(fs.existsSync(configFilePath))
db.loadDatabase()
Attempting to write a file within the application installation directory is a bad idea, often the user will not have the permission to do so. Instead you should write files to the location returned by app.getPath('userData').

My file exists though fileExistsAtPath always returns false

I'm using the following code to detect if a file exists. The file does exist but fileExistsAtPath always returns false
if let receiptFound = receiptUrl?.checkResourceIsReachableAndReturnError(error){
print("receiptUrl is \(receiptUrl?.path)") }
print("Does the file exist \(NSFileManager.defaultManager().fileExistsAtPath(receiptUrl!.path!))")
if NSFileManager.defaultManager().fileExistsAtPath(receiptUrl!.path!)
{ //work with file
}
My output is:
I can't understand why the statement is returned as false when the file exists?
It looks to me like the URL you are messing with is outside of the app sandbox.
Your app only has access to a very limited number of directories (parts of the app bundle, documents, caches, and a few other folders). The file manager probably doesn't have any access to the StoreKit directory, and so the function fileExistsAtPath returns false.
EDIT
Note that the beginning of your path is /private. That's a strong indication that the file is NOT accessible to a third party app like yours.

Access Denied when creating file in Visual F#

The following code runs without a hitch:
On the other hand, I get an access-denied error with this:
The destination is in my personal folder and I have full control. The directory is not read-only. Anyway, in either of those cases, the first code sample should not run either! I appreciate the help ...
In the second sample, you have two problems:
There are back slashes instead of forward slashes, so some of them may get interpreted as escape sequences.
You completely ignore the first parameter of write and specify what I assume is a folder as destination. You can't open a file stream on a folder, no wonder you get access denied.
This should work:
let write filename (ms:MemoryStream) =
let path = System.IO.Path.Combine( "C:/Users/<whatever>/signal_processor", filename )
use fs = new FileStream( path, FileMode.Create )
ms.WriteTo(fs)

Resources