mirror of
https://github.com/freedombox/FreedomBox.git
synced 2026-11-29 08:25:10 +00:00
plinth/*: Rename plinth/ folder to freedombox/
Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org> Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
1 parent
dd0161a7e5
commit
23b6aff290
1264 files changed
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,344 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""
|
||||
Functional, browser based tests for gitweb app.
|
||||
"""
|
||||
import contextlib
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import pytest
|
||||
|
||||
from plinth.tests import functional
|
||||
|
||||
pytestmark = [pytest.mark.apps, pytest.mark.gitweb]
|
||||
|
||||
_default_url = functional.config['DEFAULT']['url']
|
||||
|
||||
|
||||
class TestGitwebApp(functional.BaseAppTests):
|
||||
app_name = 'gitweb'
|
||||
has_service = False
|
||||
has_web = True
|
||||
|
||||
def test_all_repos_private(self, session_browser):
|
||||
"""Test repo accessability when all repos are private."""
|
||||
_create_repo(session_browser, 'Test-repo', 'private',
|
||||
ok_if_exists=True)
|
||||
_set_all_repos_private(session_browser)
|
||||
if not functional.user_exists(session_browser, 'gitweb_user'):
|
||||
functional.create_user(session_browser, 'gitweb_user',
|
||||
groups=['git-access'])
|
||||
if not functional.user_exists(session_browser, 'nogroupuser'):
|
||||
functional.create_user(session_browser, 'nogroupuser', groups=[])
|
||||
|
||||
functional.login_with_account(session_browser, functional.base_url,
|
||||
'gitweb_user')
|
||||
assert functional.is_available(session_browser, 'gitweb')
|
||||
assert len(functional.find_on_front_page(session_browser,
|
||||
'gitweb')) == 1
|
||||
|
||||
functional.login_with_account(session_browser, functional.base_url,
|
||||
'nogroupuser')
|
||||
assert not functional.is_available(session_browser, 'gitweb')
|
||||
assert len(functional.find_on_front_page(session_browser,
|
||||
'gitweb')) == 0
|
||||
|
||||
functional.logout(session_browser)
|
||||
functional.access_url(session_browser, 'gitweb')
|
||||
assert functional.is_login_prompt(session_browser)
|
||||
assert len(functional.find_on_front_page(session_browser,
|
||||
'gitweb')) == 0
|
||||
|
||||
@pytest.mark.backups
|
||||
def test_backup_restore(self, session_browser):
|
||||
"""Test backing up and restoring."""
|
||||
_create_repo(session_browser, 'Test-repo', ok_if_exists=True)
|
||||
functional.backup_create(session_browser, 'gitweb', 'test_gitweb')
|
||||
_delete_repo(session_browser, 'Test-repo')
|
||||
functional.backup_restore(session_browser, 'gitweb', 'test_gitweb')
|
||||
assert _repo_exists(session_browser, 'Test-repo')
|
||||
assert functional.is_available(session_browser, 'gitweb')
|
||||
|
||||
@pytest.mark.parametrize('access', ['public', 'private'])
|
||||
@pytest.mark.parametrize('repo_name', ['Test-repo', 'Test-repo.git'])
|
||||
@pytest.mark.parametrize('app_status', ['enabled', 'disabled'])
|
||||
def test_create_delete_repo(self, session_browser, access, repo_name,
|
||||
app_status):
|
||||
"""Test creating and deleting a repo and accessing with a git
|
||||
client."""
|
||||
if app_status == "disabled":
|
||||
functional.app_disable(session_browser, 'gitweb')
|
||||
|
||||
_delete_repo(session_browser, repo_name, ignore_missing=True)
|
||||
_create_repo(session_browser, repo_name, access)
|
||||
|
||||
assert _repo_exists(session_browser, repo_name, access)
|
||||
|
||||
if app_status == "enabled":
|
||||
assert _site_repo_exists(session_browser, repo_name)
|
||||
|
||||
if access == "public":
|
||||
assert _repo_is_readable(repo_name)
|
||||
else:
|
||||
assert not _repo_is_readable(repo_name)
|
||||
|
||||
assert not _repo_is_writable(repo_name)
|
||||
assert _repo_is_readable(repo_name, with_auth=True)
|
||||
assert _repo_is_writable(repo_name, with_auth=True)
|
||||
|
||||
_delete_repo(session_browser, repo_name)
|
||||
assert not _repo_exists(session_browser, repo_name)
|
||||
|
||||
def test_both_private_and_public_repo_exist(self, session_browser):
|
||||
"""Tests when both private and public repo exist."""
|
||||
_create_repo(session_browser, 'Test-repo', 'public', True)
|
||||
_create_repo(session_browser, 'Test-repo-private', 'private', True)
|
||||
|
||||
functional.logout(session_browser)
|
||||
assert _site_repo_exists(session_browser, 'Test-repo')
|
||||
assert not _site_repo_exists(session_browser, 'Test-repo-private')
|
||||
|
||||
@pytest.mark.parametrize('app_status', ['enabled', 'disabled'])
|
||||
def test_edit_repo_metadata(self, session_browser, app_status):
|
||||
"""Test edit repo metadata."""
|
||||
if app_status == "disabled":
|
||||
functional.app_disable(session_browser, 'gitweb')
|
||||
|
||||
_create_repo(session_browser, 'Test-repo2', 'public',
|
||||
ok_if_exists=True)
|
||||
_delete_repo(session_browser, 'Test-repo', ignore_missing=True)
|
||||
repo_metadata = {
|
||||
'name': 'Test-repo',
|
||||
'description': 'Test Description',
|
||||
'owner': 'Test Owner',
|
||||
'access': 'private',
|
||||
}
|
||||
_edit_repo_metadata(session_browser, 'Test-repo2', repo_metadata)
|
||||
assert _get_repo_metadata(session_browser,
|
||||
"Test-repo") == repo_metadata
|
||||
|
||||
if app_status == "enabled":
|
||||
_create_branch('Test-repo', 'branch1')
|
||||
_set_default_branch(session_browser, 'Test-repo', 'branch1')
|
||||
|
||||
assert _get_gitweb_site_default_repo_branch(
|
||||
session_browser, 'Test-repo') == 'branch1'
|
||||
|
||||
|
||||
def _create_local_repo(path):
|
||||
"""Create a local repository."""
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
os.mkdir(path)
|
||||
create_repo_commands = [
|
||||
'git init -q', 'git config http.sslVerify false',
|
||||
'git -c "user.name=Tester" -c "user.email=tester" '
|
||||
'commit -q --allow-empty --no-gpg-sign -m "test"'
|
||||
]
|
||||
for command in create_repo_commands:
|
||||
subprocess.check_call(command, shell=True, cwd=path)
|
||||
|
||||
|
||||
def _create_repo(browser, repo, access=None, ok_if_exists=False):
|
||||
"""Create repository."""
|
||||
if not _repo_exists(browser, repo, access):
|
||||
_delete_repo(browser, repo, ignore_missing=True)
|
||||
browser.links.find_by_href(
|
||||
'/freedombox/apps/gitweb/create/').first.click()
|
||||
browser.find_by_id('id_gitweb-name').fill(repo)
|
||||
if access == 'private':
|
||||
browser.find_by_id('id_gitweb-is_private').check()
|
||||
elif access == 'public':
|
||||
browser.find_by_id('id_gitweb-is_private').uncheck()
|
||||
functional.submit(browser, form_class='form-gitweb')
|
||||
elif not ok_if_exists:
|
||||
assert False, 'Repo already exists.'
|
||||
|
||||
|
||||
def _create_branch(repo, branch):
|
||||
"""Add a branch to the repo."""
|
||||
repo_url = _get_repo_url(repo, with_auth=True)
|
||||
|
||||
with _gitweb_temp_directory() as temp_directory:
|
||||
repo_path = os.path.join(temp_directory, repo)
|
||||
|
||||
_create_local_repo(repo_path)
|
||||
|
||||
add_branch_commands = [['git', 'checkout', '-q', '-b', branch],
|
||||
[
|
||||
'git', '-c', 'user.name=Tester', '-c',
|
||||
'user.email=tester', 'commit', '-q',
|
||||
'--allow-empty', '--no-gpg-sign', '-m',
|
||||
'test_branch1'
|
||||
],
|
||||
['git', 'push', '-q', '-f', repo_url, branch]]
|
||||
for command in add_branch_commands:
|
||||
subprocess.check_call(command, cwd=repo_path)
|
||||
|
||||
|
||||
def _delete_repo(browser, repo, ignore_missing=False):
|
||||
"""Delete repository."""
|
||||
functional.nav_to_module(browser, 'gitweb')
|
||||
if repo.endswith('.git'):
|
||||
repo = repo[:-4]
|
||||
delete_link = browser.links.find_by_href(
|
||||
'/freedombox/apps/gitweb/{}/delete/'.format(repo))
|
||||
if delete_link or not ignore_missing:
|
||||
delete_link.first.click()
|
||||
functional.submit(browser, form_class='form-delete')
|
||||
|
||||
|
||||
def _edit_repo_metadata(browser, repo, metadata):
|
||||
"""Set repository metadata."""
|
||||
functional.nav_to_module(browser, 'gitweb')
|
||||
browser.links.find_by_href(
|
||||
'/freedombox/apps/gitweb/{}/edit/'.format(repo)).first.click()
|
||||
browser.find_by_id('id_gitweb-name').fill(metadata['name'])
|
||||
browser.find_by_id('id_gitweb-description').fill(metadata['description'])
|
||||
browser.find_by_id('id_gitweb-owner').fill(metadata['owner'])
|
||||
if metadata['access'] == 'private':
|
||||
browser.find_by_id('id_gitweb-is_private').check()
|
||||
else:
|
||||
browser.find_by_id('id_gitweb-is_private').uncheck()
|
||||
functional.submit(browser, form_class='form-gitweb')
|
||||
|
||||
|
||||
def _get_gitweb_site_default_repo_branch(browser, repo):
|
||||
functional.nav_to_module(browser, 'gitweb')
|
||||
browser.find_by_css('a[href="/gitweb/{0}.git"]'.format(repo)).first.click()
|
||||
|
||||
return browser.find_by_css('.head').first.text
|
||||
|
||||
|
||||
def _get_repo_metadata(browser, repo):
|
||||
"""Get repository metadata."""
|
||||
functional.nav_to_module(browser, 'gitweb')
|
||||
browser.links.find_by_href(
|
||||
'/freedombox/apps/gitweb/{}/edit/'.format(repo)).first.click()
|
||||
metadata = {}
|
||||
for item in ['name', 'description', 'owner']:
|
||||
metadata[item] = browser.find_by_id('id_gitweb-' + item).value
|
||||
if browser.find_by_id('id_gitweb-is_private').value:
|
||||
metadata['access'] = 'private'
|
||||
else:
|
||||
metadata['access'] = 'public'
|
||||
return metadata
|
||||
|
||||
|
||||
def _get_repo_url(repo, with_auth):
|
||||
""""Get repository URL"""
|
||||
scheme = 'http'
|
||||
if _default_url.startswith('https://'):
|
||||
scheme = 'https'
|
||||
url = _default_url.split(
|
||||
'://')[1] if '://' in _default_url else _default_url
|
||||
password = 'gitweb_wrong_password'
|
||||
if with_auth:
|
||||
password = functional.config['DEFAULT']['password']
|
||||
|
||||
return '{0}://{1}:{2}@{3}/gitweb/{4}'.format(
|
||||
scheme, functional.config['DEFAULT']['username'], password, url, repo)
|
||||
|
||||
|
||||
def _gitweb_git_command_is_successful(command, cwd):
|
||||
"""Check if a command runs successfully or gives authentication error"""
|
||||
# Tell OS not to translate command return messages
|
||||
env = os.environ.copy()
|
||||
env['LC_ALL'] = 'C'
|
||||
|
||||
process = subprocess.run(command, capture_output=True, cwd=cwd, env=env,
|
||||
check=False)
|
||||
if process.returncode != 0:
|
||||
if 'Authentication failed' in process.stderr.decode():
|
||||
return False
|
||||
|
||||
process.check_returncode() # Raise exception
|
||||
return True
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _gitweb_temp_directory():
|
||||
"""Create temporary directory"""
|
||||
name = tempfile.mkdtemp(prefix='plinth_test_gitweb_')
|
||||
yield name
|
||||
shutil.rmtree(name)
|
||||
|
||||
|
||||
def _repo_exists(browser, repo, access=None):
|
||||
"""Check whether the repository exists."""
|
||||
functional.nav_to_module(browser, 'gitweb')
|
||||
if not repo.endswith('.git'):
|
||||
repo = repo + ".git"
|
||||
links_found = browser.links.find_by_href('/gitweb/{}'.format(repo))
|
||||
access_matches = True
|
||||
if links_found and access:
|
||||
parent = links_found.first.find_by_xpath('..').first
|
||||
private_icon = parent.find_by_css('.repo-private-icon')
|
||||
if access == 'private':
|
||||
access_matches = bool(private_icon)
|
||||
if access == 'public':
|
||||
access_matches = not bool(private_icon)
|
||||
return bool(links_found) and access_matches
|
||||
|
||||
|
||||
def _repo_is_readable(repo, with_auth=False):
|
||||
"""Check if a git repo is readable with git client."""
|
||||
url = _get_repo_url(repo, with_auth)
|
||||
git_command = ['git', 'clone', '-c', 'http.sslverify=false', url]
|
||||
with _gitweb_temp_directory() as cwd:
|
||||
return _gitweb_git_command_is_successful(git_command, cwd)
|
||||
|
||||
|
||||
def _repo_is_writable(repo, with_auth=False):
|
||||
"""Check if a git repo is writable with git client."""
|
||||
url = _get_repo_url(repo, with_auth)
|
||||
with _gitweb_temp_directory() as temp_directory:
|
||||
repo_directory = os.path.join(temp_directory, 'test-project')
|
||||
_create_local_repo(repo_directory)
|
||||
git_push_command = [
|
||||
'git', '-c', 'push.default=current', 'push', '-qf', url
|
||||
]
|
||||
return _gitweb_git_command_is_successful(git_push_command,
|
||||
repo_directory)
|
||||
|
||||
|
||||
def _set_all_repos_private(browser):
|
||||
"""Set all repositories private"""
|
||||
functional.nav_to_module(browser, 'gitweb')
|
||||
public_repos = []
|
||||
for element in browser.find_by_css('#gitweb-repo-list .list-group-item'):
|
||||
if not element.find_by_css('.repo-private-icon'):
|
||||
repo = element.find_by_css('.repo-label').first.text
|
||||
public_repos.append(repo)
|
||||
for repo in public_repos:
|
||||
_set_repo_access(browser, repo, 'private')
|
||||
|
||||
|
||||
def _set_default_branch(browser, repo, branch):
|
||||
"""Set default branch of the repository."""
|
||||
functional.nav_to_module(browser, 'gitweb')
|
||||
browser.links.find_by_href(
|
||||
'/freedombox/apps/gitweb/{}/edit/'.format(repo)).first.click()
|
||||
browser.find_by_id('id_gitweb-default_branch').select(branch)
|
||||
functional.submit(browser, form_class='form-gitweb')
|
||||
|
||||
|
||||
def _set_repo_access(browser, repo, access):
|
||||
"""Set repository as public or private."""
|
||||
functional.nav_to_module(browser, 'gitweb')
|
||||
browser.links.find_by_href(
|
||||
'/freedombox/apps/gitweb/{}/edit/'.format(repo)).first.click()
|
||||
if access == 'private':
|
||||
browser.find_by_id('id_gitweb-is_private').check()
|
||||
else:
|
||||
browser.find_by_id('id_gitweb-is_private').uncheck()
|
||||
functional.submit(browser, form_class='form-gitweb')
|
||||
|
||||
|
||||
def _site_repo_exists(browser, repo):
|
||||
"""Check whether the repository exists on Gitweb site."""
|
||||
browser.visit('{}/gitweb'.format(_default_url))
|
||||
if not repo.endswith('.git'):
|
||||
repo = repo + ".git"
|
||||
return bool(browser.find_by_css('a[href="/gitweb/{0}"]'.format(repo)))
|
||||
@@ -0,0 +1,148 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""Test module for gitweb module operations."""
|
||||
|
||||
import pathlib
|
||||
import subprocess
|
||||
from unittest.mock import call, patch
|
||||
|
||||
import pytest
|
||||
from django.forms import ValidationError
|
||||
|
||||
from plinth.modules.gitweb import privileged
|
||||
|
||||
REPO_NAME = 'Test-repo'
|
||||
REPO_DATA = {
|
||||
'name': REPO_NAME,
|
||||
'description': '',
|
||||
'owner': '',
|
||||
'access': 'private',
|
||||
}
|
||||
|
||||
pytestmark = pytest.mark.usefixtures('mock_privileged', 'mock_run_as_user')
|
||||
privileged_modules_to_mock = ['plinth.modules.gitweb.privileged']
|
||||
git_installed = pytest.mark.skipif(not pathlib.Path('/usr/bin/git').exists(),
|
||||
reason='git is not installed')
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fixture_set_repo_path(tmp_path):
|
||||
"""Set a repository path in the actions module."""
|
||||
privileged.GIT_REPO_PATH = tmp_path
|
||||
|
||||
|
||||
@pytest.fixture(name='existing_repo')
|
||||
def fixture_existing_repo():
|
||||
"""A fixture to create a repository."""
|
||||
try:
|
||||
privileged.delete_repo(REPO_NAME)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
privileged.create_repo(name=REPO_NAME, description='', owner='',
|
||||
keep_ownership=True, is_private=True)
|
||||
|
||||
|
||||
@git_installed
|
||||
def test_create_repo():
|
||||
"""Test creating a repository."""
|
||||
privileged.create_repo(name=REPO_NAME, description='', owner='',
|
||||
is_private=True, keep_ownership=True)
|
||||
repo = privileged.repo_info(REPO_NAME)
|
||||
default_branch = repo.pop('default_branch')
|
||||
|
||||
assert repo == REPO_DATA
|
||||
assert default_branch
|
||||
|
||||
|
||||
@git_installed
|
||||
def test_change_repo_medatada(existing_repo):
|
||||
"""Test change a metadata of the repository."""
|
||||
new_data = {
|
||||
'name': REPO_NAME,
|
||||
'description': 'description2',
|
||||
'owner': 'owner2',
|
||||
'access': 'public',
|
||||
}
|
||||
|
||||
privileged.set_repo_description(REPO_NAME, new_data['description'])
|
||||
privileged.set_repo_owner(REPO_NAME, new_data['owner'])
|
||||
privileged.set_repo_access(REPO_NAME, new_data['access'])
|
||||
repo = privileged.repo_info(REPO_NAME)
|
||||
del repo['default_branch']
|
||||
|
||||
assert repo == new_data
|
||||
|
||||
|
||||
@git_installed
|
||||
def test_rename_repository(existing_repo):
|
||||
"""Test renaming a repository."""
|
||||
new_name = 'Test-repo_2'
|
||||
|
||||
privileged.rename_repo(REPO_NAME, new_name)
|
||||
with pytest.raises(RuntimeError, match='Repository not found'):
|
||||
privileged.repo_info(REPO_NAME)
|
||||
|
||||
repo = privileged.repo_info(new_name)
|
||||
assert repo['name'] == new_name
|
||||
|
||||
|
||||
@git_installed
|
||||
def test_get_branches(existing_repo):
|
||||
"""Test getting all the branches of the repository."""
|
||||
result = privileged.get_branches(REPO_NAME)
|
||||
|
||||
assert 'default_branch' in result
|
||||
assert result['branches'] == []
|
||||
|
||||
|
||||
@git_installed
|
||||
def test_delete_repository(existing_repo):
|
||||
"""Test deleting a repository."""
|
||||
privileged.delete_repo(REPO_NAME)
|
||||
|
||||
with pytest.raises(RuntimeError, match='Repository not found'):
|
||||
privileged.repo_info(REPO_NAME)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'name',
|
||||
['.Test-repo', 'Test-repo.git.git', '/root/Test-repo', 'Test-repö'])
|
||||
def test_action_create_repo_with_invalid_names(name):
|
||||
"""Test that creating repository with invalid names fails."""
|
||||
with pytest.raises(ValidationError):
|
||||
privileged.create_repo(name=name, description='', owner='',
|
||||
keep_ownership=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url', [
|
||||
'Test-repo', 'file://root/Test-repo', 'localhost/Test-repo',
|
||||
'ssh://localhost/Test-repo', 'https://localhost/.Test-repo'
|
||||
])
|
||||
def test_action_create_repo_with_invalid_urls(url):
|
||||
"""Test that cloning repository with invalid URL fails."""
|
||||
with pytest.raises(ValidationError):
|
||||
privileged.create_repo(url=url, description='', owner='',
|
||||
keep_ownership=True)
|
||||
|
||||
|
||||
@patch('plinth.action_utils.run')
|
||||
def test_setup_git_creentials(run):
|
||||
"""Test that setting up git credentials works."""
|
||||
url = 'https://user:pass@host.example/path?key=value'
|
||||
safe_url = privileged._setup_git_credentials(url)
|
||||
assert safe_url == 'https://host.example/path?key=value'
|
||||
|
||||
input_ = b'protocol=https\nhost=host.example\nusername=user\n' \
|
||||
b'password=pass\n\n'
|
||||
env = run.mock_calls[0].kwargs.pop('env')
|
||||
assert env['GIT_TERMINAL_PROMPT'] == '0'
|
||||
assert run.mock_calls == [
|
||||
call(['git', 'credential', 'approve'], input=input_,
|
||||
stdout=subprocess.DEVNULL, check=True)
|
||||
]
|
||||
|
||||
run.reset_mock()
|
||||
url = 'https://host2.example/path?key=value'
|
||||
safe_url = privileged._setup_git_credentials(url)
|
||||
assert safe_url == 'https://host2.example/path?key=value'
|
||||
run.assert_not_called()
|
||||
@@ -0,0 +1,360 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""
|
||||
Tests for gitweb views.
|
||||
"""
|
||||
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
from django import urls
|
||||
from django.contrib.messages.storage.fallback import FallbackStorage
|
||||
from django.http.response import Http404
|
||||
|
||||
from plinth import module_loader
|
||||
from plinth.modules.gitweb import views
|
||||
|
||||
# For all tests, use plinth.urls instead of urls configured for testing
|
||||
pytestmark = pytest.mark.urls('plinth.urls')
|
||||
|
||||
EXISTING_REPOS = [
|
||||
{
|
||||
'name': 'something',
|
||||
'description': '',
|
||||
'owner': '',
|
||||
'access': 'public',
|
||||
'is_private': False,
|
||||
'default_branch': 'main',
|
||||
},
|
||||
{
|
||||
'name': 'something2',
|
||||
'description': '',
|
||||
'owner': '',
|
||||
'access': 'private',
|
||||
'is_private': True,
|
||||
'default_branch': 'main',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True, scope='module')
|
||||
def fixture_gitweb_urls():
|
||||
"""Make sure gitweb app's URLs are part of plinth.urls."""
|
||||
with patch('plinth.module_loader._modules_to_load', new=[]) as modules, \
|
||||
patch('plinth.urls.urlpatterns', new=[]):
|
||||
modules.append('plinth.modules.gitweb')
|
||||
module_loader.include_urls()
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def gitweb_patch():
|
||||
"""Patch gitweb."""
|
||||
privileged = 'plinth.modules.gitweb.privileged'
|
||||
with patch('plinth.modules.gitweb.get_repo_list') as get_repo_list, \
|
||||
patch('plinth.app.App.get') as app_get, \
|
||||
patch(f'{privileged}.create_repo'), \
|
||||
patch(f'{privileged}.repo_exists') as repo_exists, \
|
||||
patch(f'{privileged}.repo_info') as repo_info, \
|
||||
patch(f'{privileged}.rename_repo'), \
|
||||
patch(f'{privileged}.set_repo_description'), \
|
||||
patch(f'{privileged}.set_repo_owner'), \
|
||||
patch(f'{privileged}.set_repo_access'), \
|
||||
patch(f'{privileged}.set_default_branch'), \
|
||||
patch(f'{privileged}.delete_repo'), \
|
||||
patch(f'{privileged}.get_branches') as get_branches:
|
||||
repo_exists.return_value = True
|
||||
repo_info.return_value = dict(EXISTING_REPOS[0])
|
||||
get_branches.return_value = {
|
||||
'default_branch': 'main',
|
||||
'branches': ['main', 'branch1']
|
||||
}
|
||||
get_repo_list.return_value = [{
|
||||
'name': EXISTING_REPOS[0]['name']
|
||||
}, {
|
||||
'name': EXISTING_REPOS[1]['name']
|
||||
}]
|
||||
app = Mock()
|
||||
app_get.return_value = app
|
||||
app.update_service_access.return_value = None
|
||||
|
||||
yield
|
||||
|
||||
|
||||
def make_request(request, view, **kwargs):
|
||||
"""Make request with a message storage."""
|
||||
setattr(request, 'session', 'session')
|
||||
messages = FallbackStorage(request)
|
||||
setattr(request, '_messages', messages)
|
||||
response = view(request, **kwargs)
|
||||
|
||||
return response, messages
|
||||
|
||||
|
||||
def test_repos_view(rf):
|
||||
"""Test that a repo list has correct view data."""
|
||||
with patch('plinth.views.AppView.get_context_data',
|
||||
return_value={'is_enabled': True}):
|
||||
view = views.GitwebAppView.as_view()
|
||||
response, _ = make_request(rf.get(''), view)
|
||||
|
||||
assert response.context_data['repos'] == [{
|
||||
'name': EXISTING_REPOS[0]['name']
|
||||
}, {
|
||||
'name': EXISTING_REPOS[1]['name']
|
||||
}]
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_create_repo_view(rf):
|
||||
"""Test that repo create view sends correct success message."""
|
||||
form_data = {
|
||||
'gitweb-name': 'something_other',
|
||||
'gitweb-description': 'test description',
|
||||
'gitweb-owner': 'test owner',
|
||||
'gitweb-is_private': True
|
||||
}
|
||||
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
|
||||
view = views.CreateRepoView.as_view()
|
||||
response, messages = make_request(request, view)
|
||||
|
||||
assert list(messages)[0].message == 'Repository created.'
|
||||
assert response.status_code == 302
|
||||
|
||||
|
||||
def test_create_repo_duplicate_name_view(rf):
|
||||
"""Test that repo create view shows correct error message."""
|
||||
form_data = {
|
||||
'gitweb-name': EXISTING_REPOS[0]['name'],
|
||||
'gitweb-description': '',
|
||||
'gitweb-owner': ''
|
||||
}
|
||||
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
|
||||
view = views.CreateRepoView.as_view()
|
||||
response, _ = make_request(request, view)
|
||||
|
||||
assert response.context_data['form'].errors['name'][
|
||||
0] == 'A repository with this name already exists.'
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_create_repo_invalid_name_view(rf):
|
||||
"""Test that repo create view shows correct error message."""
|
||||
form_data = {
|
||||
'gitweb-name': '.something_other',
|
||||
'gitweb-description': '',
|
||||
'gitweb-owner': ''
|
||||
}
|
||||
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
|
||||
view = views.CreateRepoView.as_view()
|
||||
response, _ = make_request(request, view)
|
||||
|
||||
assert response.context_data['form'].errors['name'][
|
||||
0] == 'Invalid repository name.'
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_create_repo_failed_view(rf):
|
||||
"""Test that repo creation failure sends correct error message."""
|
||||
general_error_message = "An error occurred while creating the repository."
|
||||
error_description = 'some error'
|
||||
with patch('plinth.modules.gitweb.create_repo',
|
||||
side_effect=PermissionError(error_description)):
|
||||
form_data = {
|
||||
'gitweb-name': 'something_other',
|
||||
'gitweb-description': '',
|
||||
'gitweb-owner': ''
|
||||
}
|
||||
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
|
||||
view = views.CreateRepoView.as_view()
|
||||
response, messages = make_request(request, view)
|
||||
|
||||
assert list(messages)[0].message == '{0} {1}'.format(
|
||||
general_error_message, error_description)
|
||||
assert response.status_code == 302
|
||||
|
||||
|
||||
def test_clone_repo_view(rf):
|
||||
"""Test that cloning repo sends correct succcess message."""
|
||||
form_data = {
|
||||
'gitweb-name': 'https://example.com/test.git',
|
||||
'gitweb-description': '',
|
||||
'gitweb-owner': ''
|
||||
}
|
||||
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
|
||||
view = views.CreateRepoView.as_view()
|
||||
response, messages = make_request(request, view)
|
||||
|
||||
with pytest.raises(AttributeError):
|
||||
getattr(response.context_data['form'], 'errors')
|
||||
|
||||
assert list(messages)[0].message == 'Repository created.'
|
||||
assert response.status_code == 302
|
||||
|
||||
|
||||
def test_clone_repo_missing_remote_view(rf):
|
||||
"""Test that cloning non-existing repo shows correct error message."""
|
||||
with patch('plinth.modules.gitweb.privileged.repo_exists',
|
||||
return_value=False):
|
||||
form_data = {
|
||||
'gitweb-name': 'https://example.com/test.git',
|
||||
'gitweb-description': '',
|
||||
'gitweb-owner': ''
|
||||
}
|
||||
request = rf.post(urls.reverse('gitweb:create'), data=form_data)
|
||||
view = views.CreateRepoView.as_view()
|
||||
response, _ = make_request(request, view)
|
||||
|
||||
assert response.context_data['form'].errors['name'][
|
||||
0] == 'Remote repository is not available.'
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_edit_repository_view(rf):
|
||||
"""Test that editing repo sends correct success message."""
|
||||
form_data = {
|
||||
'gitweb-name': 'something_other.git',
|
||||
'gitweb-description': 'test-description',
|
||||
'gitweb-owner': 'test-owner',
|
||||
'gitweb-is_private': True,
|
||||
'gitweb-default_branch': 'branch1',
|
||||
}
|
||||
url = urls.reverse('gitweb:edit',
|
||||
kwargs={'name': EXISTING_REPOS[0]['name']})
|
||||
request = rf.post(url, data=form_data)
|
||||
view = views.EditRepoView.as_view()
|
||||
response, messages = make_request(request, view,
|
||||
name=EXISTING_REPOS[0]['name'])
|
||||
|
||||
assert list(messages)[0].message == 'Repository edited.'
|
||||
assert response.status_code == 302
|
||||
|
||||
|
||||
def test_edit_nonexisting_repository_view(rf):
|
||||
"""Test that trying to edit non-existing repository raises 404."""
|
||||
non_existing_repo = {'name': 'something_other'}
|
||||
request = rf.post(urls.reverse('gitweb:edit', kwargs=non_existing_repo),
|
||||
data={})
|
||||
view = views.EditRepoView.as_view()
|
||||
|
||||
with pytest.raises(Http404):
|
||||
make_request(request, view, **non_existing_repo)
|
||||
|
||||
|
||||
def test_edit_repository_duplicate_name_view(rf):
|
||||
"""Test that renaming to already existing repo name shows correct error
|
||||
message.
|
||||
|
||||
"""
|
||||
form_data = {
|
||||
'gitweb-name': EXISTING_REPOS[1]['name'],
|
||||
'gitweb-description': 'test-description',
|
||||
'gitweb-owner': 'test-owner'
|
||||
}
|
||||
url = urls.reverse('gitweb:edit',
|
||||
kwargs={'name': EXISTING_REPOS[0]['name']})
|
||||
request = rf.post(url, data=form_data)
|
||||
view = views.EditRepoView.as_view()
|
||||
response, _ = make_request(request, view, **EXISTING_REPOS[0])
|
||||
|
||||
assert response.context_data['form'].errors['name'][
|
||||
0] == 'A repository with this name already exists.'
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_edit_repository_invalid_name_view(rf):
|
||||
"""Test that renaming repo to invalid name shows correct error message."""
|
||||
form_data = {
|
||||
'gitweb-name': '.something',
|
||||
'gitweb-description': 'test-description',
|
||||
'gitweb-owner': 'test-owner'
|
||||
}
|
||||
url = urls.reverse('gitweb:edit',
|
||||
kwargs={'name': EXISTING_REPOS[0]['name']})
|
||||
request = rf.post(url, data=form_data)
|
||||
view = views.EditRepoView.as_view()
|
||||
response, _ = make_request(request, view, **EXISTING_REPOS[0])
|
||||
|
||||
assert response.context_data['form'].errors['name'][
|
||||
0] == 'Invalid repository name.'
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_edit_repository_no_change_view(rf):
|
||||
"""Test that not changing any values don't edit the repo."""
|
||||
with patch('plinth.modules.gitweb.edit_repo') as edit_repo:
|
||||
form_data = {
|
||||
'gitweb-name': EXISTING_REPOS[0]['name'],
|
||||
'gitweb-description': EXISTING_REPOS[0]['description'],
|
||||
'gitweb-owner': EXISTING_REPOS[0]['owner'],
|
||||
'gitweb-default_branch': EXISTING_REPOS[0]['default_branch'],
|
||||
}
|
||||
request = rf.post(
|
||||
urls.reverse('gitweb:edit',
|
||||
kwargs={'name': EXISTING_REPOS[0]['name']}),
|
||||
data=form_data)
|
||||
view = views.EditRepoView.as_view()
|
||||
response, _ = make_request(request, view, **EXISTING_REPOS[0])
|
||||
|
||||
assert not edit_repo.called, 'method should not have been called'
|
||||
assert response.status_code == 302
|
||||
|
||||
|
||||
def test_edit_repository_failed_view(rf):
|
||||
"""Test that failed repo editing sends correct error message."""
|
||||
with patch('plinth.modules.gitweb.edit_repo',
|
||||
side_effect=PermissionError('Error')):
|
||||
form_data = {
|
||||
'gitweb-name': 'something_other',
|
||||
'gitweb-description': 'test-description',
|
||||
'gitweb-owner': 'test-owner',
|
||||
'gitweb-default_branch': 'main',
|
||||
}
|
||||
request = rf.post(
|
||||
urls.reverse('gitweb:edit',
|
||||
kwargs={'name': EXISTING_REPOS[0]['name']}),
|
||||
data=form_data)
|
||||
view = views.EditRepoView.as_view()
|
||||
response, messages = make_request(request, view, **EXISTING_REPOS[0])
|
||||
|
||||
assert list(
|
||||
messages)[0].message == 'An error occurred during configuration.'
|
||||
assert response.status_code == 302
|
||||
|
||||
|
||||
def test_delete_repository_confirmation_view(rf):
|
||||
"""Test that repo deletion confirmation shows correct repo name."""
|
||||
response, _ = make_request(rf.get(''), views.delete,
|
||||
name=EXISTING_REPOS[0]['name'])
|
||||
|
||||
assert response.context_data['name'] == EXISTING_REPOS[0]['name']
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_delete_repository_view(rf):
|
||||
"""Test that repo deletion sends correct success message."""
|
||||
response, messages = make_request(rf.post(''), views.delete,
|
||||
name=EXISTING_REPOS[0]['name'])
|
||||
|
||||
assert list(messages)[0].message == '{} deleted.'.format(
|
||||
EXISTING_REPOS[0]['name'])
|
||||
assert response.status_code == 302
|
||||
|
||||
|
||||
def test_delete_repository_fail_view(rf):
|
||||
"""Test that failed repository deletion sends correct error message."""
|
||||
|
||||
with patch('plinth.modules.gitweb.privileged.delete_repo',
|
||||
side_effect=FileNotFoundError('Error')):
|
||||
response, messages = make_request(rf.post(''), views.delete,
|
||||
name=EXISTING_REPOS[0]['name'])
|
||||
|
||||
assert list(
|
||||
messages)[0].message == 'Could not delete {}: Error'.format(
|
||||
EXISTING_REPOS[0]['name'])
|
||||
assert response.status_code == 302
|
||||
|
||||
|
||||
def test_delete_non_existing_repository_view(rf):
|
||||
"""Test that deleting non-existing repository raises 404."""
|
||||
with pytest.raises(Http404):
|
||||
make_request(rf.post(''), views.delete, name='unknown_repo')
|
||||
Reference in new issue
Block a user