Skip to content

Commit

Permalink
change behaviour of extension in file_path
Browse files Browse the repository at this point in the history
  • Loading branch information
gotofritz committed Dec 20, 2023
1 parent 3cedfaf commit e2809b8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
17 changes: 15 additions & 2 deletions faker/providers/file/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import re
import string

from collections import OrderedDict
from typing import Dict, Optional
from typing import Dict, List, Optional, Union

from .. import BaseProvider, ElementsType

Expand Down Expand Up @@ -257,7 +258,7 @@ def file_path(
self,
depth: int = 1,
category: Optional[str] = None,
extension: Optional[str] = None,
extension: Optional[Union[str, List[str]]] = None,
absolute: Optional[bool] = True,
) -> str:
"""Generate an pathname to a file.
Expand All @@ -269,12 +270,24 @@ def file_path(
If ``absolute`` is ``True`` (default), the generated path starts with
``/`` and is absolute. Otherwise, the generated path is relative.
If used, ``extension`` can be either a string, forcing that extension, a
list of strings (one will be picked at random), or an empty list (the
path will have no extension). Default behaviour is the same as |file_name|
:sample: size=10
:sample: depth=3
:sample: depth=5, category='video'
:sample: depth=5, category='video', extension='abcdef'
:sample: extension=[]
:sample: extension=["a", "bc", "def"]
"""
if isinstance(extension, list):
if extension:
extension = self.random_element(extension)
else:
extension = "..."
file: str = self.file_name(category, extension)
file = re.sub(r"\.{4}$", "", file)
path: str = f"/{file}"
for _ in range(0, depth):
path = f"/{self.generator.word()}{path}"
Expand Down
8 changes: 6 additions & 2 deletions tests/providers/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,13 @@ def test_file_path(self):
file_path = self.fake.file_path(depth=3)
assert re.search(r"\/\w+\/\w+\/\w+\.\w+", file_path)
file_path = self.fake.file_path(extension="pdf")
assert re.search(r"\/\w+\/\w+\.pdf", file_path)
assert re.search(r"\/\w+\/\w+\.pdf$", file_path)
file_path = self.fake.file_path(extension=["a", "bc", "def", "ghij", "klmno"])
assert re.search(r"\/\w+\/\w+\.(a|bc|def|ghij|klmno)$", file_path)
file_path = self.fake.file_path(extension=[])
assert re.search(r"\/\w+\/\w+$", file_path)
file_path = self.fake.file_path(category="image")
assert re.search(r"\/\w+\/\w+\.(bmp|gif|jpeg|jpg|png|tiff)", file_path)
assert re.search(r"\/\w+\/\w+\.(bmp|gif|jpeg|jpg|png|tiff)$", file_path)

def test_unix_device(self):
reg_device = re.compile(r"^/dev/(vd|sd|xvd)[a-z]$")
Expand Down

0 comments on commit e2809b8

Please sign in to comment.