DEV Community

Hasanul Islam
Hasanul Islam

Posted on

Create Tarfile(tar.gz) in Python

Let's write some test-cases to test the behavior of create_tar_file function.

test_tarfile.py

import pytest

from tarfile import create_tar_file


def test_creates_tarfile_from_source_dir(tmpdir):
    source_dir = tmpdir.mkdir("source")
    file_path = source_dir.join("a.py")
    file_path.write("x=2")
    assert file_path.read() == "x=2"
    create_tar_file("tarfile.tar.gz", source_dir, ["a.py"])


def test_raises_exception_if_source_is_not_a_dir(tmpdir):
    with pytest.raises(ValueError, match="Not a directory"):
        create_tar_file("tarfile.tar.gz", "not_found_dir", ["a.py"])


def test_raises_exception_if_file_not_found_in_source_dir(tmpdir):
    source_dir = tmpdir.mkdir("source")
    file_path = source_dir.join("a.py")
    file_path.write("x=2")

    with pytest.raises(ValueError, match=f"b.py is not a file inside {source_dir}"):
        create_tar_file("tarfile.tar.gz", source_dir, ["b.py"])
Enter fullscreen mode Exit fullscreen mode

Now, let's write the implementation of create_tar_file.

tarfile.py

import os
import tarfile
from typing import List


def create_tar_file(tarfile_path: str, source_dir: str, files: List[str]) -> None:
    if not os.path.isdir(source_dir):
        raise ValueError('Not a directory')

    os.chdir(source_dir)

    with tarfile.open(tarfile_path, "w:gz") as tar:
        for f in files:
            if not os.path.isfile(os.path.join(source_dir, f)):
                raise ValueError(f'{f} is not a file inside {source_dir}')
            tar.add(f)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)