summaryrefslogtreecommitdiff
path: root/tests/internals/utils_save_atomic.py
blob: d1d3949502ed35091912bf4c7913644f3ff3eebb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import os

import pytest

from buildstream.utils import save_file_atomic


def test_save_new_file(tmpdir):
    filename = os.path.join(str(tmpdir), "savefile-success.test")
    with save_file_atomic(filename, "w") as f:
        f.write("foo\n")

    assert os.listdir(str(tmpdir)) == ["savefile-success.test"]
    with open(filename) as f:
        assert f.read() == "foo\n"


def test_save_over_existing_file(tmpdir):
    filename = os.path.join(str(tmpdir), "savefile-overwrite.test")

    with open(filename, "w") as f:
        f.write("existing contents\n")

    with save_file_atomic(filename, "w") as f:
        f.write("overwritten contents\n")

    assert os.listdir(str(tmpdir)) == ["savefile-overwrite.test"]
    with open(filename) as f:
        assert f.read() == "overwritten contents\n"


def test_exception_new_file(tmpdir):
    filename = os.path.join(str(tmpdir), "savefile-exception.test")

    with pytest.raises(RuntimeError):
        with save_file_atomic(filename, "w") as f:
            f.write("Some junk\n")
            raise RuntimeError("Something goes wrong")

    assert os.listdir(str(tmpdir)) == []


def test_exception_existing_file(tmpdir):
    filename = os.path.join(str(tmpdir), "savefile-existing.test")

    with open(filename, "w") as f:
        f.write("existing contents\n")

    with pytest.raises(RuntimeError):
        with save_file_atomic(filename, "w") as f:
            f.write("Some junk\n")
            raise RuntimeError("Something goes wrong")

    assert os.listdir(str(tmpdir)) == ["savefile-existing.test"]
    with open(filename) as f:
        assert f.read() == "existing contents\n"


def test_attributes(tmpdir):
    filename = os.path.join(str(tmpdir), "savefile-attributes.test")
    with save_file_atomic(filename, "w") as f:
        assert f.real_filename == filename
        assert f.name != filename