Skip to content

Commit

Permalink
Change most usages of os.path to pathlib
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasmohrin committed Feb 3, 2025
1 parent 7c8af6c commit b456ecb
Show file tree
Hide file tree
Showing 11 changed files with 35 additions and 55 deletions.
4 changes: 1 addition & 3 deletions evap/development/management/commands/dump_testdata.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import os

from django.conf import settings
from django.core.management.base import BaseCommand

Expand All @@ -12,7 +10,7 @@ class Command(BaseCommand):
requires_migrations_checks = True

def handle(self, *args, **options):
outfile_name = os.path.join(settings.MODULE, "development", "fixtures", "test_data.json")
outfile_name = settings.MODULE / "development" / "fixtures" / "test_data.json"
logged_call_command(
self.stdout,
"dumpdata",
Expand Down
3 changes: 1 addition & 2 deletions evap/development/tests/test_commands.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
from io import StringIO
from unittest.mock import call, patch

Expand All @@ -14,7 +13,7 @@ def test_dumpdata_called():
with patch("evap.evaluation.management.commands.tools.call_command") as mock:
management.call_command("dump_testdata", stdout=StringIO())

outfile_name = os.path.join(settings.MODULE, "development", "fixtures", "test_data.json")
outfile_name = settings.MODULE / "development" / "fixtures" / "test_data.json"
mock.assert_called_once_with(
"dumpdata",
"auth.group",
Expand Down
6 changes: 2 additions & 4 deletions evap/development/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import os

from django.conf import settings
from django.core.exceptions import BadRequest
from django.http import HttpResponse
Expand All @@ -16,9 +14,9 @@ def development_components(request):


def development_rendered(request, filename):
fixtures_directory = os.path.join(settings.STATICFILES_DIRS[0], "ts", "rendered")
fixtures_directory = settings.STATICFILES_DIRS[0] / "ts" / "rendered"
try:
with open(os.path.join(fixtures_directory, filename), encoding="utf-8") as fixture:
with open(fixtures_directory / filename, encoding="utf-8") as fixture:
return HttpResponse(fixture)
except (FileNotFoundError, ValueError, OSError) as e:
raise BadRequest from e
5 changes: 2 additions & 3 deletions evap/evaluation/management/commands/scss.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import subprocess # nosec

from django.conf import settings
Expand All @@ -24,8 +23,8 @@ def handle(self, *args, **options):
command = [
"npx",
"sass",
os.path.join(static_directory, "scss", "evap.scss"),
os.path.join(static_directory, "css", "evap.css"),
static_directory / "scss" / "evap.scss",
static_directory / "css" / "evap.css",
]

if options["watch"]:
Expand Down
8 changes: 2 additions & 6 deletions evap/evaluation/management/commands/ts.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import argparse
import os
import subprocess # nosec
import unittest

Expand Down Expand Up @@ -67,17 +66,14 @@ def compile(self, watch=False, fresh=False, **_options):
"npx",
"tsc",
"--project",
os.path.join(static_directory, "ts", "tsconfig.compile.json"),
static_directory / "ts" / "tsconfig.compile.json",
]

if watch:
command += ["--watch"]

if fresh:
try:
os.remove(os.path.join(static_directory, "ts", ".tsbuildinfo.json"))
except FileNotFoundError:
pass
(static_directory / "ts" / ".tsbuildinfo.json").unlink(missing_ok=True)

Check warning on line 76 in evap/evaluation/management/commands/ts.py

View check run for this annotation

Codecov / codecov/patch

evap/evaluation/management/commands/ts.py#L76

Added line #L76 was not covered by tests

self.run_command(command)

Expand Down
13 changes: 6 additions & 7 deletions evap/evaluation/tests/test_commands.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import random
from collections import defaultdict
from datetime import date, datetime, timedelta
Expand Down Expand Up @@ -204,8 +203,8 @@ def test_calls_cache_results(self):

class TestScssCommand(TestCase):
def setUp(self):
self.scss_path = os.path.join(settings.STATICFILES_DIRS[0], "scss", "evap.scss")
self.css_path = os.path.join(settings.STATICFILES_DIRS[0], "css", "evap.css")
self.scss_path = settings.STATICFILES_DIRS[0] / "scss" / "evap.scss"
self.css_path = settings.STATICFILES_DIRS[0] / "css" / "evap.css"

@patch("subprocess.run")
def test_scss_called(self, mock_subprocess_run):
Expand Down Expand Up @@ -246,14 +245,14 @@ def test_scss_called_with_no_sass_installed(self, mock_subprocess_run):

class TestTsCommand(TestCase):
def setUp(self):
self.ts_path = os.path.join(settings.STATICFILES_DIRS[0], "ts")
self.ts_path = settings.STATICFILES_DIRS[0] / "ts"

@patch("subprocess.run")
def test_ts_compile(self, mock_subprocess_run):
management.call_command("ts", "compile")

mock_subprocess_run.assert_called_once_with(
["npx", "tsc", "--project", os.path.join(self.ts_path, "tsconfig.compile.json")],
["npx", "tsc", "--project", self.ts_path / "tsconfig.compile.json"],
check=True,
)

Expand All @@ -264,7 +263,7 @@ def test_ts_compile_with_watch(self, mock_subprocess_run):
management.call_command("ts", "compile", "--watch")

mock_subprocess_run.assert_called_once_with(
["npx", "tsc", "--project", os.path.join(self.ts_path, "tsconfig.compile.json"), "--watch"],
["npx", "tsc", "--project", self.ts_path / "tsconfig.compile.json", "--watch"],
check=True,
)

Expand All @@ -280,7 +279,7 @@ def test_ts_test(self, mock_render_pages, mock_call_command, mock_subprocess_run
mock_subprocess_run.assert_has_calls(
[
call(
["npx", "tsc", "--project", os.path.join(self.ts_path, "tsconfig.compile.json")],
["npx", "tsc", "--project", self.ts_path / "tsconfig.compile.json"],
check=True,
),
call(["npx", "jest"], check=True),
Expand Down
5 changes: 2 additions & 3 deletions evap/evaluation/tests/test_misc.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os.path
from io import StringIO

from django.conf import settings
Expand Down Expand Up @@ -29,7 +28,7 @@ def test_sample_semester_file(self):
original_user_count = UserProfile.objects.count()

form = page.forms["semester-import-form"]
form["excel_file"] = (os.path.join(settings.MODULE, "static", "sample.xlsx"),)
form["excel_file"] = (str(settings.MODULE / "static" / "sample.xlsx"),)
page = form.submit(name="operation", value="test")

form = page.forms["semester-import-form"]
Expand All @@ -45,7 +44,7 @@ def test_sample_user_file(self):
original_user_count = UserProfile.objects.count()

form = page.forms["user-import-form"]
form["excel_file"] = (os.path.join(settings.MODULE, "static", "sample_user.xlsx"),)
form["excel_file"] = (str(settings.MODULE / "static" / "sample_user.xlsx"),)
page = form.submit(name="operation", value="test")

form = page.forms["user-import-form"]
Expand Down
4 changes: 2 additions & 2 deletions evap/evaluation/tests/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ def let_user_vote_for_evaluation(user, evaluation, create_answers=False):


def store_ts_test_asset(relative_path: str, content) -> None:
absolute_path = os.path.join(settings.STATICFILES_DIRS[0], "ts", "rendered", relative_path)
absolute_path = settings.STATICFILES_DIRS[0] / "ts" / "rendered" / relative_path

os.makedirs(os.path.dirname(absolute_path), exist_ok=True)
absolute_path.parent.mkdir(parents=True, exist_ok=True)

with open(absolute_path, "wb") as file:
file.write(content)
Expand Down
3 changes: 1 addition & 2 deletions evap/staff/tests/test_views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import csv
import datetime
import os
from abc import ABC, abstractmethod
from io import BytesIO
from typing import Literal
Expand Down Expand Up @@ -420,7 +419,7 @@ def test_shows_swap_users_option(self):

class TestUserBulkUpdateView(WebTestStaffMode):
url = "/staff/user/bulk_update"
filename = os.path.join(settings.MODULE, "staff/fixtures/test_user_bulk_update_file.txt")
filename = str(settings.MODULE / "staff" / "fixtures" / "test_user_bulk_update_file.txt")

@classmethod
def setUpTestData(cls):
Expand Down
10 changes: 3 additions & 7 deletions evap/staff/tests/utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import os
import time
from contextlib import contextmanager

from evap.evaluation.tests.tools import WebTest, WebTestWith200Check
from evap.staff.tools import ImportType, generate_import_filename
from evap.staff.tools import ImportType, generate_import_path


def helper_enter_staff_mode(webtest):
Expand Down Expand Up @@ -46,11 +45,8 @@ def setUp(self):

def helper_delete_all_import_files(user_id):
for import_type in ImportType:
filename = generate_import_filename(user_id, import_type)
try:
os.remove(filename)
except FileNotFoundError:
pass
path = generate_import_path(user_id, import_type)
path.unlink(missing_ok=True)


# For some form fields, like a <select> which can be configured to create new options,
Expand Down
29 changes: 13 additions & 16 deletions evap/staff/tools.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
from collections.abc import Iterable
from datetime import date, datetime, timedelta
from enum import Enum
from pathlib import Path

from django.conf import settings
from django.contrib import messages
Expand Down Expand Up @@ -29,37 +29,34 @@ class ImportType(Enum):
USER_BULK_UPDATE = "user_bulk_update"


def generate_import_filename(user_id, import_type):
return os.path.join(settings.MEDIA_ROOT, "temp_import_files", f"{user_id}.{import_type.value}.xls")
def generate_import_path(user_id, import_type) -> Path:
return settings.MEDIA_ROOT / "temp_import_files" / f"{user_id}.{import_type.value}.xls"


def save_import_file(excel_file, user_id, import_type):
filename = generate_import_filename(user_id, import_type)
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "wb") as file:
path = generate_import_path(user_id, import_type)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "wb") as file:
for chunk in excel_file.chunks():
file.write(chunk)
excel_file.seek(0)


def delete_import_file(user_id, import_type):
filename = generate_import_filename(user_id, import_type)
try:
os.remove(filename)
except OSError:
pass
path = generate_import_path(user_id, import_type)
path.unlink(missing_ok=True)


def import_file_exists(user_id, import_type):
filename = generate_import_filename(user_id, import_type)
return os.path.isfile(filename)
path = generate_import_path(user_id, import_type)
return path.is_file()


def get_import_file_content_or_raise(user_id, import_type):
filename = generate_import_filename(user_id, import_type)
if not os.path.isfile(filename):
path = generate_import_path(user_id, import_type)
if not path.is_file():
raise SuspiciousOperation("No test run performed previously.")
with open(filename, "rb") as file:
with open(path, "rb") as file:
return file.read()


Expand Down

0 comments on commit b456ecb

Please sign in to comment.