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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay