def test_makedirs_race_handling(tmpdir, monkeypatch):
    """
    File storage should be robust against directory creation race conditions.
    """
    real_makedirs = os.makedirs

    # Monkey-patch os.makedirs, to simulate a normal call, a raced call,
    # and an error.
    def fake_makedirs(path):
        if path == os.path.join(str(tmpdir), "normal"):
            real_makedirs(path)
        elif path == os.path.join(str(tmpdir), "raced"):
            real_makedirs(path)
            raise OSError(errno.EEXIST, "simulated EEXIST")
        elif path == os.path.join(str(tmpdir), "error"):
            raise OSError(errno.EACCES, "simulated EACCES")
        else:
            pytest.fail("unexpected argument %r" % path)

    monkeypatch.setattr(os, "makedirs", fake_makedirs)

    storage = FileSystemStorage(location=str(tmpdir))

    storage.save("normal/test.file", io.StringIO("saved normally"))
    assert storage.open("normal/test.file").read() == "saved normally"

    storage.save("raced/test.file", io.StringIO("saved with race"))
    assert storage.open("raced/test.file").read() == "saved with race"

    # Check that OSErrors aside from EEXIST are still raised.
    with pytest.raises(OSError):
        storage.save("error/test.file", io.StringIO("not saved"))
def test_file_access_options(tmpdir):
    """
    Standard file access options are available, and work as expected.
    """
    storage = FileSystemStorage(location=str(tmpdir))

    assert not storage.exists("storage_test")

    f = storage.open("storage_test", "w")
    f.write("storage contents")
    f.close()

    assert storage.exists("storage_test")

    f = storage.open("storage_test", "r")
    assert f.read() == "storage contents"
    f.close()

    storage.delete("storage_test")
    assert not storage.exists("storage_test")
def test_file_storage_preserves_filename_case(tmpdir):
    """
    The storage backend should preserve case of filenames.
    """
    storage = FileSystemStorage(location=str(tmpdir))

    f = storage.open("CaSe_SeNsItIvE", "w")
    f.write("storage contents")
    f.close()

    assert os.path.join(str(tmpdir), "CaSe_SeNsItIvE") == storage.path("CaSe_SeNsItIvE")
def test_file_save_with_path(tmpdir):
    """
    Saving a pathname should create intermediate directories as necessary.
    """
    storage = FileSystemStorage(location=str(tmpdir))

    assert not storage.exists("path/to")

    storage.save("path/to/test.file", io.StringIO("file saved with path"))

    assert storage.exists("path/to")
    assert storage.open("path/to/test.file").read() == "file saved with path"
    assert os.path.exists(os.path.join(str(tmpdir), "path", "to", "test.file"))