summaryrefslogtreecommitdiff
path: root/tests/artifactcache/tar.py
blob: ef39be31c69d2f613d27f56a87c43b2a3f1581ef (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import os
import tarfile
import tempfile
from contextlib import ExitStack

import pytest

from buildstream._artifactcache.tarcache import _Tar
from buildstream import utils, ProgramNotFoundError


# Test that it 'works' - this may be equivalent to test_archive_no_tar()
# on some systems.
def test_archive_default():
    with ExitStack() as stack:
        src = stack.enter_context(tempfile.TemporaryDirectory())
        tar_dir = stack.enter_context(tempfile.TemporaryDirectory())
        scratch = stack.enter_context(tempfile.TemporaryDirectory())
        test_file = stack.enter_context(open(os.path.join(src, 'test'), 'a'))
        test_file.write('Test')

        _Tar.archive(os.path.join(tar_dir, 'test.tar'), '.', src)

        with tarfile.open(os.path.join(tar_dir, 'test.tar')) as tar:
            tar.extractall(path=scratch)

        assert os.listdir(scratch) == os.listdir(src)


def test_archive_no_tar():
    # Modify the path to exclude 'tar'
    old_path = os.environ.get('PATH')
    os.environ['PATH'] = ''

    # Ensure we can't find 'tar' or 'gtar'
    try:
        for tar in ['gtar', 'tar']:
            with pytest.raises(ProgramNotFoundError):
                utils.get_host_tool(tar)

    # Run the same test as before, this time 'tar' should not be available
        test_archive_default()

    # Reset the environment
    finally:
        os.environ['PATH'] = old_path


# Same thing as test_archive_default()
def test_extract_default():
    with ExitStack() as stack:
        src = stack.enter_context(tempfile.TemporaryDirectory())
        tar_dir = stack.enter_context(tempfile.TemporaryDirectory())
        scratch = stack.enter_context(tempfile.TemporaryDirectory())
        test_file = stack.enter_context(open(os.path.join(src, 'test'), 'a'))
        test_file.write('Test')

        with tarfile.open(os.path.join(tar_dir, 'test.tar'), 'a:') as tar:
            tar.add(src, 'contents')

        _Tar.extract(os.path.join(tar_dir, 'test.tar'), scratch)

        assert os.listdir(os.path.join(scratch, 'contents')) == os.listdir(src)


def test_extract_no_tar():
    # Modify the path to exclude 'tar'
    old_path = os.environ.get('PATH')
    os.environ['PATH'] = ''

    # Ensure we can't find 'tar' or 'gtar'
    for tar in ['gtar', 'tar']:
        with pytest.raises(ProgramNotFoundError):
            utils.get_host_tool(tar)

    # Run the same test as before, this time 'tar' should not be available
    try:
        test_extract_default()

    # Reset the environment
    finally:
        os.environ['PATH'] = old_path