Codebase revamp
This commit is contained in:
parent
c88d52da3d
commit
e01017dfcd
44 changed files with 2273 additions and 1294 deletions
65
Dockerfile
65
Dockerfile
|
|
@ -1,65 +0,0 @@
|
|||
# This will produce an image to be used in Openshift
|
||||
# Build should be triggered from repo root like:
|
||||
# podman build -f Dockerfile --tag <IMAGE_TAG>
|
||||
# Don't forget to mount persistent volume for development
|
||||
# podman run --volume hostdir:/testdays -ti -u 0 -p 5001:5001 <IMAGE_TAG>
|
||||
|
||||
# On OpenShift, edit Deployment Configs, add:
|
||||
# spec:
|
||||
# volumes:
|
||||
# - name: run-volume
|
||||
# emptyDir: {}
|
||||
# containers:
|
||||
# volumeMounts:
|
||||
# - name: run-volume
|
||||
# mountPath: /run
|
||||
|
||||
FROM fedora:32
|
||||
LABEL \
|
||||
name="Testdays application" \
|
||||
vendor="Fedora QE" \
|
||||
license="GPLv2+" \
|
||||
description="Web front end to the currently proposed blocker and freeze exception bugs for Fedora releases under development." \
|
||||
usage="" \
|
||||
build-date=""
|
||||
|
||||
USER root
|
||||
COPY ./testdays.spec /opt/app-root/src/testdays/testdays.spec
|
||||
|
||||
# install dependencies defined in RPM spec file
|
||||
RUN dnf -y install findutils rpm-build python3-pip python3-mod_wsgi python3-psycopg2 \
|
||||
&& rpm --query --requires --specfile /opt/app-root/src/testdays/testdays.spec | xargs -d '\n' dnf -y install
|
||||
|
||||
COPY . /opt/app-root/src/testdays/
|
||||
# install using --no-deps option to ensure nothing comes from PyPi
|
||||
RUN pip3 install --no-deps /opt/app-root/src/testdays/
|
||||
|
||||
# fix apache config for container use
|
||||
RUN sed -i 's#^WSGISocketPrefix .*#WSGISocketPrefix /tmp/wsgi#' /opt/app-root/src/testdays/conf/testdays.conf
|
||||
|
||||
# install launch script
|
||||
RUN install -p -m 0755 /opt/app-root/src/testdays/container_start.sh /usr/bin/container_start
|
||||
|
||||
# config files
|
||||
RUN install -d /usr/share/testdays/conf \
|
||||
&& install -p -m 0644 /opt/app-root/src/testdays/conf/testdays.conf /usr/share/testdays/conf/ \
|
||||
&& install -p -m 0644 /opt/app-root/src/testdays/conf/testdays.wsgi /usr/share/testdays/ \
|
||||
&& install -d /etc/testdays \
|
||||
&& install -p -m 0644 /opt/app-root/src/testdays/conf/testdays.conf /etc/httpd/conf.d/
|
||||
|
||||
# alembic
|
||||
RUN install -p -m 0644 /opt/app-root/src/testdays/alembic.ini /usr/share/testdays/alembic.ini
|
||||
RUN cp -a /opt/app-root/src/testdays/alembic /usr/share/testdays/alembic
|
||||
RUN chmod -R 0755 /usr/share/testdays/alembic
|
||||
|
||||
# clean up
|
||||
RUN rm -rf /opt/app-root/src/testdays \
|
||||
&& dnf -y autoremove rpm-build \
|
||||
&& dnf clean all
|
||||
|
||||
# EXPOSE 5001/tcp
|
||||
EXPOSE 5001
|
||||
|
||||
CMD [ "runserver" ]
|
||||
ENTRYPOINT [ "/usr/bin/container_start" ]
|
||||
USER 1001:0
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
recursive-include testdays/templates *
|
||||
recursive-include testdays/static *
|
||||
88
Makefile
88
Makefile
|
|
@ -1,88 +0,0 @@
|
|||
#
|
||||
# Copyright 2013, Red Hat, Inc.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
#
|
||||
|
||||
.PHONY: test test-ci pylint pep8 docs clean virtualenv
|
||||
|
||||
# general variables
|
||||
VENV=test_env
|
||||
SRC=testdays
|
||||
|
||||
# Variables used for packaging
|
||||
SPECFILE=$(SRC).spec
|
||||
BASEARCH:=$(shell uname -i)
|
||||
DIST:=$(shell rpm --eval '%{dist}')
|
||||
VERSION:=$(shell rpmspec -q --queryformat="%{VERSION}\n" $(SPECFILE) | uniq)
|
||||
RELEASE:=$(subst $(DIST),,$(shell rpmspec -q --queryformat="%{RELEASE}\n" $(SPECFILE) | uniq))
|
||||
NVR:=$(SRC)-$(VERSION)-$(RELEASE)
|
||||
GITBRANCH:=$(shell git rev-parse --abbrev-ref HEAD)
|
||||
TARGETVER:=$(shell lsb_release -r |grep -o '[0-9]*')
|
||||
TARGETDIST:=fc$(TARGETVER)
|
||||
BUILDTARGET:=fedora-$(TARGETVER)-x86_64
|
||||
|
||||
test: $(VENV)
|
||||
sh -c "TEST='true' . $(VENV)/bin/activate; py.test --cov $(SRC) testing/; deactivate"
|
||||
|
||||
test-ci: $(VENV)
|
||||
sh -c "TEST='true' . $(VENV)/bin/activate; py.test --cov-report xml --cov $(SRC) testing/; deactivate"
|
||||
|
||||
pylint:
|
||||
pylint -f parseable $(SRC) | tee pylint.out
|
||||
|
||||
pep8:
|
||||
pep8 $(SRC)/*.py $(SRC)/*/*.py | tee pep8.out
|
||||
|
||||
ci: test-ci pylint pep8
|
||||
|
||||
docs:
|
||||
sphinx-build -b html -d docs/_build/doctrees docs/source docs/_build/html
|
||||
|
||||
clean:
|
||||
rm -rf dist
|
||||
rm -rf testdays.egg-info
|
||||
rm -rf build
|
||||
rm -f pep8.out
|
||||
rm -f pylint.out
|
||||
|
||||
archive: $(SRC)-$(VERSION).tar.gz
|
||||
|
||||
$(SRC)-$(VERSION).tar.gz:
|
||||
git archive $(GITBRANCH) --prefix=$(SRC)-$(VERSION)/ | gzip -c9 > $@
|
||||
|
||||
mocksrpm: archive
|
||||
mock -r $(BUILDTARGET) --buildsrpm --spec $(SPECFILE) --sources .
|
||||
cp /var/lib/mock/$(BUILDTARGET)/result/$(NVR).$(TARGETDIST).src.rpm .
|
||||
|
||||
mockbuild: mocksrpm
|
||||
mock -r $(BUILDTARGET) --no-clean --rebuild $(NVR).$(TARGETDIST).src.rpm
|
||||
cp /var/lib/mock/$(BUILDTARGET)/result/$(NVR).$(TARGETDIST).noarch.rpm .
|
||||
|
||||
#kojibuild: mocksrpm
|
||||
# koji build --scratch dist-6E-epel-testing-candidate $(NVR).$(TARGETDIST).src.rpm
|
||||
|
||||
nvr:
|
||||
@echo $(NVR)
|
||||
|
||||
cleanvenv:
|
||||
rm -rf $(VENV)
|
||||
|
||||
virtualenv: $(VENV)
|
||||
|
||||
$(VENV):
|
||||
virtualenv --distribute --system-site-packages $(VENV)
|
||||
sh -c ". $(VENV)/bin/activate; pip install --force-reinstall -r requirements.txt; deactivate"
|
||||
|
||||
56
README.md
56
README.md
|
|
@ -1,14 +1,52 @@
|
|||
# testdays
|
||||
= TestdayApp Metadata =
|
||||
|
||||
# Building testdays
|
||||
The new TestdayApp's metadata define the testdays' structure, testcases and possibly the `Profile` column name override.
|
||||
|
||||
You can use provided Makefile in order to build testdays. By default, it'll use buildroot equal to your current OS. You can override this behaviour by sepcifiyng variables for Make manually.
|
||||
Only lines starting (disregarding whitespace) with `=`, `*` or `! ProfileText:` are considered data, rest is discarded.
|
||||
|
||||
To build testdays:
|
||||
`make mockbuild`
|
||||
Lines starting with `=` denote sections;
|
||||
Lines starting with `*` represent testcases within the section, and must be formatted as `* testcase name; testcase url`
|
||||
|
||||
To build testdays for Fedora 27:
|
||||
`make BUILDTARGET=fedora-27-x86_64 TARGETDIST=fc27 mocksrpm`
|
||||
A line like `! ProfileText: Foobar` can be used to change that section's Profile column name to `Foobar`
|
||||
|
||||
A basic tesday's structure could look like this:
|
||||
<pre>
|
||||
= Basic Tests
|
||||
* pm-suspendr; https://fedoraproject.org/wiki/QA:Testcase_Power_Management_pm_suspend
|
||||
* Tuned disabled idle; http://fedoraproject.org/wiki/QA:Testcase_Power_Management_tuned_off_idle
|
||||
|
||||
= Other Tests
|
||||
! ProfileText: libvirt-version
|
||||
* Virtualization libvirt connections; https://fedoraproject.org/wiki/QA:Testcase_Virtualization_libvirt_connections
|
||||
</pre>
|
||||
|
||||
== Editing existing Testdays
|
||||
|
||||
Whenever you edit an existing testday, you will notice that the testcase lines also contain an ULID at the end. For example:
|
||||
<pre>
|
||||
= Basic Tests
|
||||
* pm-suspendr; https://fedoraproject.org/wiki/QA:Testcase_Power_Management_pm_suspend; 01JR2VGYFAWA5F7EHCZ3C6FXK2
|
||||
* Tuned disabled idle; http://fedoraproject.org/wiki/QA:Testcase_Power_Management_tuned_off_idle; 01JR2VGYFAW3E05JVGT452QQXP
|
||||
|
||||
= Other Tests
|
||||
! ProfileText: libvirt-version
|
||||
* Virtualization libvirt connections; https://fedoraproject.org/wiki/QA:Testcase_Virtualization_libvirt_connections; 01JR2VGYFAG2Y7K5C6Z9DCG3MY
|
||||
</pre>
|
||||
|
||||
This is an unique id assigned to the specific "column" within the Testday, and as long as you keep it intact, you can move the testcases around, change the name or the url part, and any results that are already entered will be still correctly linked.
|
||||
|
||||
For example:
|
||||
<pre>
|
||||
= Basic Tests
|
||||
* Tuned disabled idle; http://fedoraproject.org/wiki/QA:Testcase_Power_Management_tuned_off_idle; 01JR2VGYFAW3E05JVGT452QQXP
|
||||
|
||||
= Other Tests
|
||||
! ProfileText: libvirt-version
|
||||
* Virtualization libvirt connections; https://fedoraproject.org/wiki/QA:Testcase_Virtualization_libvirt_connections; 01JR2VGYFAG2Y7K5C6Z9DCG3MY
|
||||
* Another name; https://another.url; 01JR2VGYFAWA5F7EHCZ3C6FXK2
|
||||
</pre>
|
||||
|
||||
Here, we moved the `pm-suspendr` testcase identified by ULID `01JR2VGYFAWA5F7EHCZ3C6FXK2` from the `Basic Tests` section to the `Other Tests section`, changed the name to `Another name` and the url to `https://another.url`, but since we kept the ULID reference intact, alle the results previously entered into the `pm-suspendr` column will be correctly shown in the new location.
|
||||
|
||||
[[Category:TestdayApp]]
|
||||
|
||||
To build testdays for CentOS 7:
|
||||
`make BUILDTARGET=epel-7-x86_64 TARGETDIST=el7 mocksrpm`
|
||||
|
|
|
|||
77
alembic/versions/24c09add0da1_revamp_testdays_step_2.py
Normal file
77
alembic/versions/24c09add0da1_revamp_testdays_step_2.py
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
"""Revamp testdays step 2
|
||||
|
||||
Revision ID: 24c09add0da1
|
||||
Revises: 615057ee3945
|
||||
Create Date: 2025-04-01 13:57:06.985259
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '24c09add0da1'
|
||||
down_revision = '615057ee3945'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('testday',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.Text(), nullable=True),
|
||||
sa.Column('testday_url', sa.Text(), nullable=True),
|
||||
sa.Column('start', sa.DateTime(), nullable=True),
|
||||
sa.Column('end', sa.DateTime(), nullable=True),
|
||||
sa.Column('is_draft', sa.Boolean(), nullable=True),
|
||||
sa.Column('history', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_table('users',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.String(length=265), nullable=False),
|
||||
sa.Column('displayname', sa.String(length=80), nullable=False),
|
||||
sa.Column('role', sa.Enum('none', 'user', 'admin', name='userroles'), nullable=True),
|
||||
sa.Column('disabled', sa.Boolean(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('username')
|
||||
)
|
||||
op.create_table('testcase',
|
||||
sa.Column('ulid', sa.String(length=26), nullable=False),
|
||||
sa.Column('url', sa.Text(), nullable=True),
|
||||
sa.Column('testday_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['testday_id'], ['testday.id'], ),
|
||||
sa.PrimaryKeyConstraint('ulid')
|
||||
)
|
||||
op.create_table('result',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('testday_id', sa.Integer(), nullable=True),
|
||||
sa.Column('testcase_ulid', sa.String(length=26), nullable=True),
|
||||
sa.Column('user_id', sa.Integer(), nullable=True),
|
||||
sa.Column('profile', sa.Text(), nullable=True),
|
||||
sa.Column('result', sa.Text(), nullable=True),
|
||||
sa.Column('bugs', sa.Text(), nullable=True),
|
||||
sa.Column('comment', sa.Text(), nullable=True),
|
||||
sa.Column('removed', sa.Boolean(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['testcase_ulid'], ['testcase.ulid'], ),
|
||||
sa.ForeignKeyConstraint(['testday_id'], ['testday.id'], ),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index('result_fk_testcase_ulid', 'result', ['testcase_ulid'], unique=False)
|
||||
op.create_index('result_fk_testday_id', 'result', ['testday_id'], unique=False)
|
||||
op.create_index('result_fk_user_id', 'result', ['user_id'], unique=False)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index('result_fk_user_id', table_name='result')
|
||||
op.drop_index('result_fk_testday_id', table_name='result')
|
||||
op.drop_index('result_fk_testcase_ulid', table_name='result')
|
||||
op.drop_table('result')
|
||||
op.drop_table('testcase')
|
||||
op.drop_table('users')
|
||||
op.drop_table('testday')
|
||||
# ### end Alembic commands ###
|
||||
|
|
@ -12,8 +12,8 @@ import datetime
|
|||
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from testdays.models.testday import Event
|
||||
from testdays.lib import wiki
|
||||
#from testdays.models.testday import Event
|
||||
#from testdays.lib import wiki
|
||||
|
||||
Session = sessionmaker()
|
||||
|
||||
|
|
@ -26,45 +26,45 @@ depends_on = None
|
|||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
def process_past_event_dates():
|
||||
|
||||
connection = op.get_bind()
|
||||
session = Session(bind=connection)
|
||||
events = session.query(Event).order_by(Event.created_at.desc())
|
||||
for event in events:
|
||||
print("Processing TD %s" % event.name)
|
||||
|
||||
# Some testdays urls are redirect, follow and clean target
|
||||
# Eg. http://fedoraproject.org/wiki/Test_Day:F33_SwapOnZRAM
|
||||
# to
|
||||
# https://fedoraproject.org/wiki/Test_Day:2020-07-06_Swap_on_ZRAM?rd=Test_Day:F33_SwapOnZRAM
|
||||
r = requests.get(event.testday_url)
|
||||
|
||||
# Urls after redirects contain unnecessary ?rd=someting parameter, our code would crash on that, purge it
|
||||
# Eg. https://fedoraproject.org/wiki/Test_Day:2020-07-06_Swap_on_ZRAM?rd=Test_Day:F33_SwapOnZRAM
|
||||
# to https://fedoraproject.org/wiki/Test_Day:2020-07-06_Swap_on_ZRAM
|
||||
to_clean = re.findall(r'\?rd.*', r.url)
|
||||
if len(to_clean) == 1:
|
||||
cleaned_url = r.url.replace(re.findall(r'\?rd.*', r.url)[0], "")
|
||||
else:
|
||||
cleaned_url = r.url
|
||||
|
||||
# Some more cleaning
|
||||
# https://fedoraproject.org/w/index.php?title=Test_Day:2018-04-11_Cloud-Atomic_Testday
|
||||
# to
|
||||
# https://fedoraproject.org/Wiki/Test_Day:2018-04-11_Cloud-Atomic_Testday
|
||||
cleaned_url = cleaned_url.replace("fedoraproject.org/w/index.php?title=", "fedoraproject.org/wiki/")
|
||||
|
||||
# Parse dates
|
||||
start, end = wiki.get_td_dates(cleaned_url)
|
||||
|
||||
if start == datetime.datetime(1900, 1, 1, 0, 0):
|
||||
print("Could not parse event's date, using default")
|
||||
|
||||
event.testday_start = start
|
||||
event.testday_end = end
|
||||
session.commit()
|
||||
session.commit()
|
||||
# def process_past_event_dates():
|
||||
#
|
||||
# connection = op.get_bind()
|
||||
# session = Session(bind=connection)
|
||||
# events = session.query(Event).order_by(Event.created_at.desc())
|
||||
# for event in events:
|
||||
# print("Processing TD %s" % event.name)
|
||||
#
|
||||
# # Some testdays urls are redirect, follow and clean target
|
||||
# # Eg. http://fedoraproject.org/wiki/Test_Day:F33_SwapOnZRAM
|
||||
# # to
|
||||
# # https://fedoraproject.org/wiki/Test_Day:2020-07-06_Swap_on_ZRAM?rd=Test_Day:F33_SwapOnZRAM
|
||||
# r = requests.get(event.testday_url)
|
||||
#
|
||||
# # Urls after redirects contain unnecessary ?rd=someting parameter, our code would crash on that, purge it
|
||||
# # Eg. https://fedoraproject.org/wiki/Test_Day:2020-07-06_Swap_on_ZRAM?rd=Test_Day:F33_SwapOnZRAM
|
||||
# # to https://fedoraproject.org/wiki/Test_Day:2020-07-06_Swap_on_ZRAM
|
||||
# to_clean = re.findall(r'\?rd.*', r.url)
|
||||
# if len(to_clean) == 1:
|
||||
# cleaned_url = r.url.replace(re.findall(r'\?rd.*', r.url)[0], "")
|
||||
# else:
|
||||
# cleaned_url = r.url
|
||||
#
|
||||
# # Some more cleaning
|
||||
# # https://fedoraproject.org/w/index.php?title=Test_Day:2018-04-11_Cloud-Atomic_Testday
|
||||
# # to
|
||||
# # https://fedoraproject.org/Wiki/Test_Day:2018-04-11_Cloud-Atomic_Testday
|
||||
# cleaned_url = cleaned_url.replace("fedoraproject.org/w/index.php?title=", "fedoraproject.org/wiki/")
|
||||
#
|
||||
# # Parse dates
|
||||
# start, end = wiki.get_td_dates(cleaned_url)
|
||||
#
|
||||
# if start == datetime.datetime(1900, 1, 1, 0, 0):
|
||||
# print("Could not parse event's date, using default")
|
||||
#
|
||||
# event.testday_start = start
|
||||
# event.testday_end = end
|
||||
# session.commit()
|
||||
# session.commit()
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
|
|
@ -73,7 +73,7 @@ def upgrade():
|
|||
# ### end Alembic commands ###
|
||||
|
||||
# Process data changes
|
||||
process_past_event_dates()
|
||||
#process_past_event_dates()
|
||||
|
||||
|
||||
|
||||
|
|
|
|||
29
alembic/versions/615057ee3945_revamp_testdays_step_1.py
Normal file
29
alembic/versions/615057ee3945_revamp_testdays_step_1.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
"""Revamp testdays step 1
|
||||
|
||||
Revision ID: 615057ee3945
|
||||
Revises: 31a71e8c7dfa
|
||||
Create Date: 2025-04-01 13:51:43.718589
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '615057ee3945'
|
||||
down_revision = '31a71e8c7dfa'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
def upgrade():
|
||||
#op.drop_index('category_fk_event_id', table_name='category')
|
||||
op.drop_constraint('testcase_category_id_fkey', 'testcase', type_='foreignkey')
|
||||
op.drop_table('category')
|
||||
op.drop_table('user')
|
||||
op.drop_table('event')
|
||||
op.drop_table('testcase')
|
||||
|
||||
|
||||
def downgrade():
|
||||
raise Exception("Downgrade not possible")
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
#!/usr/bin/bash
|
||||
if [[ $1 == runserver ]]; then
|
||||
testdays init_db
|
||||
mod_wsgi-express-3 start-server /usr/share/testdays/testdays.wsgi --user apache --group apache \
|
||||
--port 5001 --threads 5 --include-file /etc/httpd/conf.d/testdays.conf --log-level info \
|
||||
--log-to-terminal --access-log --startup-log
|
||||
else
|
||||
testdays "$@"
|
||||
fi
|
||||
|
|
@ -1,14 +1,19 @@
|
|||
werkzeug == 2.2.3
|
||||
Flask == 2.2.3
|
||||
Flask-SQLAlchemy ~= 2.5
|
||||
SQLAlchemy ~= 1.4
|
||||
WTForms
|
||||
Flask-WTF
|
||||
Flask-Login
|
||||
Flask-Caching
|
||||
alembic
|
||||
resultsdb-api
|
||||
python-fedora
|
||||
# Requirements - only for s2i support
|
||||
gunicorn == 20.1.0
|
||||
psycopg2
|
||||
|
||||
|
||||
# Keep only direct requirements here, not dependencies
|
||||
alembic==1.13.1
|
||||
Flask==3.0.3
|
||||
Flask-Login==0.6.3
|
||||
flask-oidc==2.1.1
|
||||
flask-simple-captcha==5.5.5
|
||||
Flask-SQLAlchemy==3.1.1
|
||||
Flask-WTF==1.2.1
|
||||
jinjax==0.35
|
||||
python-ulid==3.0.0
|
||||
# This is only required for the Openshift deployment
|
||||
gunicorn==22.0.0
|
||||
psycopg2-binary==2.9.10
|
||||
psycopg2-pool==1.2
|
||||
|
|
|
|||
32
setup.py
32
setup.py
|
|
@ -1,32 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
|
||||
from setuptools import setup
|
||||
import codecs
|
||||
import re
|
||||
import os
|
||||
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
def read(*parts):
|
||||
return codecs.open(os.path.join(here, *parts), 'r').read()
|
||||
|
||||
|
||||
def find_version(*file_paths):
|
||||
version_file = read(*file_paths)
|
||||
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
|
||||
version_file, re.M)
|
||||
if version_match:
|
||||
return version_match.group(1)
|
||||
raise RuntimeError("Unable to find version string.")
|
||||
|
||||
setup(name='testdays',
|
||||
version=find_version('testdays', '__init__.py'),
|
||||
description='',
|
||||
author='Josef Skladanka',
|
||||
author_email='jskladan@redhat.com',
|
||||
license='GPLv2+',
|
||||
packages=['testdays', 'testdays.controllers', 'testdays.models', 'testdays.lib'],
|
||||
package_dir={'testdays':'testdays'},
|
||||
entry_points=dict(console_scripts=['testdays=testdays.cli:main']),
|
||||
include_package_data=True,
|
||||
)
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
%if ! (0%{?fedora} > 12 || 0%{?rhel} > 5)
|
||||
%{!?python_sitelib: %global python_sitelib %(%{__python} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")}
|
||||
%{!?python_sitearch: %global python_sitearch %(%{__python} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib(1))")}
|
||||
%endif
|
||||
|
||||
Name: testdays
|
||||
# NOTE: if you update version, *make sure* to also update testdays/__init__.py
|
||||
Version: 0.0.4
|
||||
Release: 1%{?dist}
|
||||
Summary: Simple app to help record results from Fedora testdays
|
||||
|
||||
License: GPLv2+
|
||||
URL: https://bitbucket.org/fedoraqa/testdays
|
||||
Source0: https://qadevel.cloud.fedoraproject.org/releases/%{name}/%{name}-%{version}.tar.gz
|
||||
|
||||
BuildArch: noarch
|
||||
|
||||
Requires: python3-flask
|
||||
Requires: python3-flask-sqlalchemy
|
||||
Requires: python3-flask-wtf
|
||||
Requires: python3-flask-login
|
||||
Requires: python3-flask-caching
|
||||
Requires: python3-alembic
|
||||
Requires: python3-fedora
|
||||
Requires: python3-resultsdb_api
|
||||
BuildRequires: python3-devel python3-setuptools
|
||||
|
||||
%description
|
||||
Simple app to help record results from Fedora testdays
|
||||
|
||||
%prep
|
||||
%setup -q
|
||||
|
||||
%build
|
||||
%{__python3} setup.py build
|
||||
|
||||
%install
|
||||
%{__python3} setup.py install --skip-build --root %{buildroot}
|
||||
|
||||
# apache and wsgi settings
|
||||
mkdir -p %{buildroot}%{_datadir}/testdays/conf
|
||||
cp conf/testdays.conf %{buildroot}%{_datadir}/testdays/conf/.
|
||||
cp conf/testdays.wsgi %{buildroot}%{_datadir}/testdays/.
|
||||
|
||||
# alembic config and data
|
||||
cp -r alembic %{buildroot}%{_datadir}/testdays/.
|
||||
install alembic.ini %{buildroot}%{_datadir}/testdays/.
|
||||
|
||||
mkdir -p %{buildroot}%{_sysconfdir}/testdays
|
||||
install conf/settings.py.example %{buildroot}%{_sysconfdir}/testdays/settings.py.example
|
||||
|
||||
%files
|
||||
%doc README.md conf/*
|
||||
%{python3_sitelib}/testdays
|
||||
%{python3_sitelib}/*.egg-info
|
||||
|
||||
%attr(755,root,root) %{_bindir}/testdays
|
||||
%dir %{_sysconfdir}/testdays
|
||||
%{_sysconfdir}/testdays/*
|
||||
%dir %{_datadir}/testdays
|
||||
%{_datadir}/testdays/*
|
||||
|
||||
%changelog
|
||||
* Fri Jun 15 2018 Frantisek Zatloukal <fzatlouk@redhat.com> - 0.0.4-1
|
||||
- Use latest ResutlsDB API
|
||||
- Update Makefile
|
||||
|
||||
* Thu Sep 10 2015 Tim Flink <tflink@fedoraproject.org> - 0.0.3-1
|
||||
- fixed alembic path in cli
|
||||
- added alembic files so migrations work
|
||||
|
||||
* Wed Sep 9 2015 Tim Flink <tflink@fedoraproject.org> - 0.0.2-1
|
||||
- updated summary and description
|
||||
- included testdays.lib in setup.py
|
||||
|
||||
* Thu Feb 6 2014 Josef Skladanka <jskladan@redhat.com> - 0.0.1-1
|
||||
- initial packaging
|
||||
|
|
@ -1,126 +1,185 @@
|
|||
# Copyright 2014, Red Hat, Inc
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
#
|
||||
# Authors:
|
||||
# Josef Skladanka <jskladan@redhat.com>
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
|
||||
from flask import Flask, render_template
|
||||
from flask_login import LoginManager
|
||||
import jinjax
|
||||
from flask import Flask
|
||||
from flask_login import LoginManager, current_user
|
||||
from flask_oidc import OpenIDConnect
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_simple_captcha import CAPTCHA
|
||||
|
||||
from . import config
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
|
||||
# the version as used in setup.py
|
||||
__version__ = "0.0.4"
|
||||
|
||||
__version__ = "2.0.0"
|
||||
|
||||
# Flask App
|
||||
app = Flask(__name__)
|
||||
app.secret_key = 'not-really-a-secret'
|
||||
app = Flask(
|
||||
__name__,
|
||||
static_url_path="",
|
||||
static_folder="static",
|
||||
)
|
||||
app.jinja_env.trim_blocks = True
|
||||
app.jinja_env.lstrip_blocks = True
|
||||
|
||||
# Is this an OpenShift deployment?
|
||||
openshift = os.getenv('OPENSHIFT_PROD')
|
||||
# Load default config (Production)
|
||||
# * update with values from a config file
|
||||
# * update with values from environment variables
|
||||
config_obj = config.Production()
|
||||
config_file = "/etc/testdays/settings.py"
|
||||
|
||||
# Load default config, then override that with a config file
|
||||
if os.getenv('PROD') == 'true' or openshift == "1":
|
||||
default_config_obj = 'testdays.config.ProductionConfig'
|
||||
default_config_file = '/etc/testdays/settings.py'
|
||||
elif os.getenv('TEST') == 'true' or openshift == "0":
|
||||
default_config_obj = 'testdays.config.TestingConfig'
|
||||
default_config_file = os.getcwd() + '/conf/settings.py'
|
||||
else:
|
||||
default_config_obj = 'testdays.config.DevelopmentConfig'
|
||||
default_config_file = os.getcwd() + '/conf/settings.py'
|
||||
if os.getenv("RUNMODE") == "dev" or os.getenv("DEV") == "true":
|
||||
config_obj = config.Development()
|
||||
config_file = f"{os.getcwd()}/conf/settings.py"
|
||||
|
||||
app.config.from_object(default_config_obj)
|
||||
|
||||
if openshift:
|
||||
config.openshift_config(app.config, openshift)
|
||||
|
||||
config_file = os.environ.get('TESTDAYS_CONFIG', default_config_file)
|
||||
elif os.getenv("RUNMODE") == "test" or os.getenv("TEST") == "true":
|
||||
config_obj = config.Production()
|
||||
config_file = None
|
||||
|
||||
config_file = os.environ.get("FORCE_CONFIG_FILE", config_file)
|
||||
if os.path.exists(config_file):
|
||||
app.config.from_pyfile(config_file)
|
||||
config_obj.update_from_pyfile(config_file)
|
||||
|
||||
if app.config['PRODUCTION']:
|
||||
if app.secret_key == 'not-really-a-secret':
|
||||
|
||||
# Is this an OpenShift deployment?
|
||||
if os.getenv("IS_OPENSHIFT"):
|
||||
config.check_required_openshift_envvars()
|
||||
config_obj.OIDC_CLIENT_SECRETS = "/opt/app-root/secret/client_secrets.json"
|
||||
config_obj.OIDC_SCOPES = [
|
||||
"openid",
|
||||
"email",
|
||||
"profile",
|
||||
"https://id.fedoraproject.org/scope/fas-attributes",
|
||||
]
|
||||
|
||||
config_obj.update_from_envvars()
|
||||
|
||||
app.config.from_object(config_obj)
|
||||
|
||||
app.secret_key = app.config["SECRET_KEY"]
|
||||
if app.config["PRODUCTION"]:
|
||||
if app.secret_key == "not-really-a-secret":
|
||||
raise Warning("You need to change the app.secret_key value for production")
|
||||
|
||||
# setup logging
|
||||
fmt = '[%(filename)s:%(lineno)d] ' if app.debug else '%(module)-12s '
|
||||
fmt += '%(asctime)s %(levelname)-7s %(message)s'
|
||||
datefmt = '%Y-%m-%d %H:%M:%S'
|
||||
loglevel = logging.DEBUG if app.debug else logging.INFO
|
||||
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
|
||||
oidc = OpenIDConnect(app, prefix="/flask_oidc")
|
||||
|
||||
# JinjaX components
|
||||
catalog = jinjax.Catalog(jinja_env=app.jinja_env, root_url="/components/")
|
||||
catalog.add_folder("testdays/components")
|
||||
catalog.jinja_env.globals.update({"current_user": current_user})
|
||||
|
||||
# Whitenoise middleware to serve the components' js and css files
|
||||
app.wsgi_app = catalog.get_middleware(
|
||||
app.wsgi_app,
|
||||
autorefresh=app.debug,
|
||||
max_age=None if app.debug else 60,
|
||||
allowed_ext=[".css", ".js"],
|
||||
)
|
||||
|
||||
|
||||
@app.context_processor
|
||||
def jinjax_components_in_jinja():
|
||||
def C(name, **kwargs):
|
||||
return catalog.render(name, **kwargs)
|
||||
|
||||
return {"C": C}
|
||||
|
||||
|
||||
class ReverseProxied(object):
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
scheme = environ.get("HTTP_X_FORWARDED_PROTO")
|
||||
|
||||
# For some reason, the current Openshift/Proxy setup is weird, and instead of
|
||||
# "https" the X-Forwarded-Proto header is set to "https,https"
|
||||
# This works around it, while (hopefully) not fucking up the other instances
|
||||
# where the value is either unset, or set properly.
|
||||
scheme = scheme.split(",")[0].strip() if scheme and "," in scheme else scheme
|
||||
if scheme:
|
||||
environ["wsgi.url_scheme"] = scheme
|
||||
|
||||
return self.app(environ, start_response)
|
||||
|
||||
|
||||
# Openshift is reverse-proxied. Maybe change this to: https://werkzeug.palletsprojects.com/en/3.0.x/middleware/proxy_fix/
|
||||
if os.getenv("IS_OPENSHIFT"):
|
||||
app.wsgi_app = ReverseProxied(app.wsgi_app)
|
||||
|
||||
|
||||
# Logging
|
||||
def setup_logging():
|
||||
root_logger = logging.getLogger('')
|
||||
root_logger.setLevel(logging.DEBUG)
|
||||
fmt = "[%(filename)s:%(lineno)d] " if app.debug else "%(module)-12s "
|
||||
fmt += "%(asctime)s %(levelname)-7s %(message)s"
|
||||
datefmt = "%Y-%m-%d %H:%M:%S"
|
||||
loglevel = logging.DEBUG if app.debug else logging.INFO
|
||||
formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
|
||||
|
||||
if app.config['STREAM_LOGGING']:
|
||||
print("doing stream logging")
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.handlers.clear()
|
||||
# root_logger.setLevel(logging.DEBUG)
|
||||
|
||||
if app.config["STREAM_LOGGING"]:
|
||||
print("Enabled stream logging")
|
||||
stream_handler = logging.StreamHandler()
|
||||
stream_handler.setLevel(loglevel)
|
||||
stream_handler.setFormatter(formatter)
|
||||
root_logger.addHandler(stream_handler)
|
||||
app.logger.addHandler(stream_handler)
|
||||
|
||||
if app.config['SYSLOG_LOGGING']:
|
||||
print("doing syslog logging")
|
||||
syslog_handler = logging.handlers.SysLogHandler(address='/dev/log',
|
||||
facility=logging.handlers.SysLogHandler.LOG_LOCAL4)
|
||||
if app.config["SYSLOG_LOGGING"]:
|
||||
print("Enabled syslog logging")
|
||||
syslog_handler = logging.handlers.SysLogHandler(
|
||||
address="/dev/log", facility=logging.handlers.SysLogHandler.LOG_LOCAL4
|
||||
)
|
||||
syslog_handler.setLevel(loglevel)
|
||||
syslog_handler.setFormatter(formatter)
|
||||
root_logger.addHandler(syslog_handler)
|
||||
app.logger.addHandler(syslog_handler)
|
||||
|
||||
if app.config['FILE_LOGGING'] and app.config['LOGFILE']:
|
||||
print("doing file logging to %s" % app.config['LOGFILE'])
|
||||
file_handler = logging.handlers.RotatingFileHandler(app.config['LOGFILE'], maxBytes=500000, backupCount=5)
|
||||
if app.config["FILE_LOGGING"] and app.config["LOGFILE"]:
|
||||
print("Enabled file logging to %s" % app.config["LOGFILE"])
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
app.config["LOGFILE"], maxBytes=500000, backupCount=5
|
||||
)
|
||||
file_handler.setLevel(loglevel)
|
||||
file_handler.setFormatter(formatter)
|
||||
root_logger.addHandler(file_handler)
|
||||
app.logger.addHandler(file_handler)
|
||||
|
||||
|
||||
setup_logging()
|
||||
|
||||
if app.config['SHOW_DB_URI']:
|
||||
app.logger.debug('using DBURI: %s' % app.config['SQLALCHEMY_DATABASE_URI'])
|
||||
if app.config["SHOW_DB_URI"]:
|
||||
app.logger.debug("using DBURI: %s" % app.config["SQLALCHEMY_DATABASE_URI"])
|
||||
|
||||
|
||||
|
||||
CAPTCHA_CONFIG = {
|
||||
'SECRET_CAPTCHA_KEY': app.config["SECRET_KEY"],
|
||||
'CAPTCHA_LENGTH': 6,
|
||||
'CAPTCHA_DIGITS': False,
|
||||
'EXPIRE_SECONDS': 600,
|
||||
}
|
||||
SIMPLE_CAPTCHA = CAPTCHA(config=CAPTCHA_CONFIG)
|
||||
app = SIMPLE_CAPTCHA.init_app(app)
|
||||
|
||||
# database
|
||||
# app.config['SQLALCHEMY_ECHO'] = True
|
||||
db = SQLAlchemy(app)
|
||||
|
||||
# setup login manager
|
||||
# flask-login
|
||||
login_manager = LoginManager()
|
||||
login_manager.setup_app(app)
|
||||
login_manager.login_view = 'login_page.login'
|
||||
login_manager.init_app(app)
|
||||
login_manager.session_protection = "strong"
|
||||
login_manager.login_view = "login_page.login"
|
||||
login_manager.login_message_category = "info"
|
||||
|
||||
from .controllers.admin import admin
|
||||
|
||||
# register blueprints
|
||||
from testdays.controllers.main import main
|
||||
from .controllers.main import main
|
||||
from .controllers.login_page import login_page
|
||||
|
||||
app.register_blueprint(main)
|
||||
|
||||
from testdays.controllers.login_page import login_page
|
||||
app.register_blueprint(login_page)
|
||||
app.register_blueprint(admin, url_prefix="/admin")
|
||||
|
||||
from testdays.controllers.admin import admin
|
||||
app.register_blueprint(admin)
|
||||
|
|
|
|||
242
testdays/cli.py
242
testdays/cli.py
|
|
@ -1,32 +1,16 @@
|
|||
# Copyright 2014, Red Hat, Inc
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
#
|
||||
# Authors:
|
||||
# Josef Skladanka <jskladan@redhat.com>
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
from optparse import OptionParser
|
||||
|
||||
from alembic.config import Config
|
||||
from alembic import command as al_command
|
||||
from alembic.config import Config
|
||||
from alembic.migration import MigrationContext
|
||||
|
||||
from testdays import app, db
|
||||
from testdays.models.user import User
|
||||
from . import app, db
|
||||
from .models import *
|
||||
|
||||
|
||||
def get_alembic_config():
|
||||
# the location of the alembic ini file and alembic scripts changes when
|
||||
|
|
@ -34,11 +18,17 @@ def get_alembic_config():
|
|||
if os.path.exists("./alembic.ini"):
|
||||
alembic_cfg = Config("./alembic.ini")
|
||||
else:
|
||||
alembic_cfg = Config("/usr/share/testdays/alembic.ini",
|
||||
ini_section='alembic-packaged')
|
||||
alembic_cfg = Config(
|
||||
"/usr/share/testdays/alembic.ini", ini_section="alembic-packaged"
|
||||
)
|
||||
return alembic_cfg
|
||||
|
||||
def upgrade_db(*args):
|
||||
|
||||
def CMD_upgrade_db(destructive, **kwargs):
|
||||
if destructive:
|
||||
CMD_init_db(destructive)
|
||||
return
|
||||
|
||||
alembic_cfg = get_alembic_config()
|
||||
|
||||
context = MigrationContext.configure(db.engine.connect())
|
||||
|
|
@ -47,7 +37,8 @@ def upgrade_db(*args):
|
|||
|
||||
al_command.upgrade(alembic_cfg, "head")
|
||||
|
||||
def init_alembic(*args):
|
||||
|
||||
def CMD_init_alembic(**kwargs):
|
||||
alembic_cfg = get_alembic_config()
|
||||
|
||||
# check to see if the db has already been initialized by checking for an
|
||||
|
|
@ -62,10 +53,12 @@ def init_alembic(*args):
|
|||
else:
|
||||
print("Alembic already initialized")
|
||||
|
||||
def initialize_db(destructive):
|
||||
|
||||
def CMD_init_db(destructive, **kwargs):
|
||||
alembic_cfg = get_alembic_config()
|
||||
|
||||
print("Initializing database")
|
||||
CMD_init_alembic()
|
||||
if destructive:
|
||||
print(" - Dropping all tables")
|
||||
db.drop_all()
|
||||
|
|
@ -74,16 +67,138 @@ def initialize_db(destructive):
|
|||
print(" - Stamping alembic's current version to 'head'")
|
||||
al_command.stamp(alembic_cfg, "head")
|
||||
|
||||
init_alembic()
|
||||
upgrade_db()
|
||||
CMD_upgrade_db(destructive=False)
|
||||
|
||||
|
||||
def mock_data(destructive):
|
||||
print("Populating tables with mock-data")
|
||||
def CMD_alembic_recreate(destructive, **kwargs):
|
||||
if not destructive:
|
||||
print("This needs to be deliberatly executed in destructive mode")
|
||||
return
|
||||
|
||||
print("Dropping all and creating via alembic")
|
||||
db.drop_all()
|
||||
CMD_init_alembic()
|
||||
CMD_upgrade_db(destructive=False)
|
||||
|
||||
|
||||
def CMD_mock_data(destructive, **kwargs):
|
||||
if not destructive:
|
||||
print("Must be ran as destructive")
|
||||
return
|
||||
print("Mocking data")
|
||||
Testday.query.delete()
|
||||
Testcase.query.delete()
|
||||
Result.query.delete()
|
||||
structure = {
|
||||
"Sections": [
|
||||
{
|
||||
"Name": "Section #0",
|
||||
"ProfileText": "",
|
||||
"Testcases": [
|
||||
{
|
||||
"Ulid": "0-0-0",
|
||||
"Name": "Testcase_2",
|
||||
"Url": "http://example.com/tc_2",
|
||||
},
|
||||
{
|
||||
"Ulid": "0-0-1",
|
||||
"Name": "Testcase_3",
|
||||
"Url": "http://example.com/tc_3",
|
||||
},
|
||||
{
|
||||
"Ulid": "0-0-2",
|
||||
"Name": "Testcase_6",
|
||||
"Url": "http://example.com/tc_6",
|
||||
},
|
||||
{
|
||||
"Ulid": "0-0-3",
|
||||
"Name": "Testcase_6",
|
||||
"Url": "http://example.com/tc_6",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"Name": "Section #1",
|
||||
"ProfileText": "Alternate",
|
||||
"Testcases": [
|
||||
{
|
||||
"Ulid": "0-1-0",
|
||||
"Name": "Testcase_1",
|
||||
"Url": "http://example.com/tc_1",
|
||||
},
|
||||
{
|
||||
"Ulid": "0-1-1",
|
||||
"Name": "Testcase_4",
|
||||
"Url": "http://example.com/tc_4",
|
||||
},
|
||||
{
|
||||
"Ulid": "0-1-2",
|
||||
"Name": "Testcase_6",
|
||||
"Url": "http://example.com/tc_6",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"Name": "Section #2",
|
||||
"ProfileText": "",
|
||||
"Testcases": [
|
||||
{
|
||||
"Ulid": "0-2-0",
|
||||
"Name": "Testcase_3",
|
||||
"Url": "http://example.com/tc_3",
|
||||
},
|
||||
{
|
||||
"Ulid": "0-2-1",
|
||||
"Name": "Testcase_4",
|
||||
"Url": "http://example.com/tc_4",
|
||||
},
|
||||
{
|
||||
"Ulid": "0-2-2",
|
||||
"Name": "Testcase_9",
|
||||
"Url": "http://example.com/tc_9",
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
}
|
||||
td = Testday("Mock Testday #1", structure)
|
||||
td.is_draft = False
|
||||
db.session.add(td)
|
||||
tcs = {}
|
||||
for s in structure["Sections"]:
|
||||
for tc in s["Testcases"]:
|
||||
if tc["Ulid"] in tcs:
|
||||
continue
|
||||
t = Testcase(tc["Url"], td.id, ulid=tc["Ulid"])
|
||||
tcs[tc["Ulid"]] = t
|
||||
for tc in tcs.values():
|
||||
db.session.add(tc)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
for i in range(3):
|
||||
u = User(f"anon:Rando_{i}", f"Rando {i}")
|
||||
db.session.add(u)
|
||||
for tc in random.sample(list(tcs.keys()), 3):
|
||||
r = Result(
|
||||
td.id,
|
||||
tc,
|
||||
u,
|
||||
random.choice(["Foo", "Bar"]),
|
||||
random.choice(["PASS", "FAIL", "INFO"]),
|
||||
)
|
||||
db.session.add(r)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def CMD_mock_db_users(destructive, **kwargs):
|
||||
if destructive or not db.session.query(User).count():
|
||||
print(" - User")
|
||||
data_users = [('admin', 'admin'), ('user', 'user')]
|
||||
data_users = [
|
||||
("admin", "admin", UserRoles.admin),
|
||||
("user", "user", UserRoles.none),
|
||||
]
|
||||
|
||||
for d in data_users:
|
||||
u = User(*d)
|
||||
|
|
@ -93,37 +208,56 @@ def mock_data(destructive):
|
|||
else:
|
||||
print(" - skipped User")
|
||||
|
||||
def main():
|
||||
possible_commands = ['init_db', 'mock_data', 'upgrade_db', 'init_alembic']
|
||||
|
||||
usage = 'usage: [DEV=true] %prog ' + "(%s)" % ' | '.join(possible_commands)
|
||||
def CMD_set_user_role(value, **kwargs):
|
||||
"""Accepts username:rolename as value"""
|
||||
username, role = value.rsplit(":", 1)
|
||||
user = User.query.filter(User.username == username).first()
|
||||
if not user:
|
||||
print("User not found")
|
||||
return
|
||||
|
||||
role = UserRoles.get_by_name(role)
|
||||
if not role:
|
||||
print("Role not found")
|
||||
return
|
||||
|
||||
user.role = role
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def main():
|
||||
possible_commands = [s[len("CMD_") :] for s in globals() if s.startswith("CMD_")]
|
||||
|
||||
usage = f"usage: [RUNMODE=dev|prod|test] %prog " + " | ".join(possible_commands)
|
||||
parser = OptionParser(usage=usage)
|
||||
parser.add_option("-d", "--destructive",
|
||||
action="store_true", dest="destructive", default=False,
|
||||
help="Drop tables in `init_db`; Store data in `mock_data` "
|
||||
"even if the tables are not empty")
|
||||
parser.add_option(
|
||||
"-d",
|
||||
"--destructive",
|
||||
action="store_true",
|
||||
dest="destructive",
|
||||
default=False,
|
||||
)
|
||||
parser.add_option(
|
||||
"-v",
|
||||
"--value",
|
||||
action="store",
|
||||
dest="value",
|
||||
default=None,
|
||||
)
|
||||
|
||||
(options, args) = parser.parse_args()
|
||||
|
||||
if len(args) != 1 or args[0] not in possible_commands:
|
||||
print(usage)
|
||||
print
|
||||
print('Please use one of the following commands: %s' % str(possible_commands))
|
||||
print("Please use one of the following commands: %s" % str(possible_commands))
|
||||
sys.exit(1)
|
||||
|
||||
command = {
|
||||
'init_db': initialize_db,
|
||||
'mock_data': mock_data,
|
||||
'upgrade_db': upgrade_db,
|
||||
'init_alembic': init_alembic,
|
||||
}[args[0]]
|
||||
|
||||
if not options.destructive:
|
||||
print("Proceeding with non-destructive init. To perform destructive "\
|
||||
"steps use -d option.")
|
||||
|
||||
command = globals()[f"CMD_{args[0]}"]
|
||||
with app.app_context():
|
||||
command(options.destructive)
|
||||
command(destructive=options.destructive, value=options.value)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
|
|||
81
testdays/components/Admin/CreateTestday.jinja
Normal file
81
testdays/components/Admin/CreateTestday.jinja
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
{# def form #}
|
||||
<Root>
|
||||
|
||||
{# djlint:off #}
|
||||
<Navbar.Navbar>
|
||||
</Navbar.Navbar>
|
||||
{# djlint:on #}
|
||||
|
||||
<div class="container">
|
||||
<form action="" method="post" novalidate>
|
||||
{{ form.hidden_tag() }}
|
||||
<div class="field">
|
||||
<label class="label">{{ form.name.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.name(size=32, class_="input") }}</div>
|
||||
{% if form.name.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.name.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ form.url.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.url(size=32, class_="input") }}</div>
|
||||
{% if form.url.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.url.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ form.start.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.start(size=32, class_="input") }}</div>
|
||||
{% if form.start.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.start.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ form.end.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.end(size=32, class_="input") }}</div>
|
||||
{% if form.end.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.end.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ form.structure.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.structure(class_="textarea", rows=20) }}</div>
|
||||
{% if form.structure.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.structure.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ form.draft.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.draft() }}</div>
|
||||
{% if form.draft.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.draft.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">{{ form.submit(class_="button is-link", value="Submit") }}</div>
|
||||
</form>
|
||||
|
||||
</Root>
|
||||
6
testdays/components/Admin/Index.jinja
Normal file
6
testdays/components/Admin/Index.jinja
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<Root>
|
||||
<div class="content" style="margin: 1em">
|
||||
<a href="{{url_for('admin.create_testday')}}">New Testday</a></br />
|
||||
<a href="{{url_for('admin.users')}}">Manage users</a></br />
|
||||
</div>
|
||||
</Root>
|
||||
69
testdays/components/Admin/Users.jinja
Normal file
69
testdays/components/Admin/Users.jinja
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
{#def users=[] #}
|
||||
{#js js/NotificationOnHtmxResponseError.js, js/inputs.js #}
|
||||
|
||||
<Root>
|
||||
<div class="content">
|
||||
<h1>Users</h1>
|
||||
<table id="users_table" class="table is-striped is-bordered">
|
||||
<style>
|
||||
:scope table tr.htmx-swapping td {
|
||||
opacity: 0;
|
||||
transition: opacity 300ms ease-out;
|
||||
}
|
||||
</style>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Displayname</th>
|
||||
<th>Role</th>
|
||||
<th>Disabled</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<!--
|
||||
hx-target="closest tr" is propagated to all the child-elements (if not overrideen)
|
||||
so the hx-responses will replace the "closest ancestor tr element"
|
||||
in relation to "the element which triggered the hx-event"
|
||||
(in our case the Add/Submit buttons)
|
||||
-->
|
||||
<tbody hx-target="closest tr" hx-swap="outerHTML">
|
||||
{% for user in users %}
|
||||
<!--
|
||||
Given the way server responds right now, this hx-select could also be set to
|
||||
"#pagure_repos_table>tbody>tr:nth-of-type(2)"
|
||||
to select "the second <tr> element of the table data. And we could ditch the id="pagure_repo_..."
|
||||
But this is easier to read, and future-proof...
|
||||
-->
|
||||
<tr id="user_{{ user.id }}" hx-select="#user_{{ user.id }}">
|
||||
<td>
|
||||
[{{user.id}}] {{ user.displayname }}
|
||||
{% if user.username.startswith("anon:") %}<span class="has-text-warning">[ANON]</span>{%endif%}
|
||||
</td>
|
||||
<td>
|
||||
<span class="select">
|
||||
<select
|
||||
name="role"
|
||||
class="input highlight_changed"
|
||||
data-orig_value="{{user.role.name}}">
|
||||
<option value="none" {%if user.role.name=="none"%}selected="selected"{%endif%}>none</option>
|
||||
<option value="admin" {%if user.role.name=="admin"%}selected="selected"{%endif%}>admin</option>
|
||||
</select>
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<input class="input highlight_changed"
|
||||
name="disabled"
|
||||
data-orig_value="{{ user.disabled }}"
|
||||
value="{{ user.disabled }}"
|
||||
{% if not current_user.has_role("admin") %}disabled{% endif %} />
|
||||
</td>
|
||||
<td>
|
||||
<button class="button"
|
||||
hx-put="/admin/users/{{ user.id }}"
|
||||
hx-include="closest tr">Submit</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Root>
|
||||
|
||||
26
testdays/components/EditProfile.jinja
Normal file
26
testdays/components/EditProfile.jinja
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
{#def form #}
|
||||
<Root>
|
||||
{# djlint:off #}
|
||||
<Navbar.Navbar>
|
||||
</Navbar.Navbar>
|
||||
{# djlint:on #}
|
||||
|
||||
<div class="container">
|
||||
<form action="" method="post" novalidate>
|
||||
{{ form.hidden_tag() }}
|
||||
<div class="field">
|
||||
<label class="label">{{ form.displayname.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.displayname(size=32, class_="input") }}</div>
|
||||
{% if form.displayname.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.displayname.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">{{ form.submit(class_="button is-link", value="Submit") }}</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
</Root>
|
||||
49
testdays/components/EventList.jinja
Normal file
49
testdays/components/EventList.jinja
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
{#def current, past #}
|
||||
<Root>
|
||||
{# djlint:off #}
|
||||
<Navbar.Navbar>
|
||||
<Navbar.Item>
|
||||
<div class="content">
|
||||
<h1 style="margin-left: 5px">
|
||||
<span class="icon">
|
||||
<i class="fas fa-vial" aria-hidden="true"></i>
|
||||
</span>
|
||||
|
||||
Fedora Testdays
|
||||
</h1>
|
||||
</div>
|
||||
</Navbar.Item>
|
||||
</Navbar.Navbar>
|
||||
{# djlint:on #}
|
||||
|
||||
<div class="content" style="margin-left: 1em; margin-right: 1em">
|
||||
<table class="table is-fullwidth">
|
||||
<tr><td colspan="2"><h2>Upcoming and current events</h2></td></tr>
|
||||
{% for td in current %}
|
||||
<tr>
|
||||
<td>
|
||||
<a href="/testday/{{td.id}}">{{td.name}}</a>
|
||||
{% if td.is_draft %}<span class="has-text-warning">[DRAFT!]</span>{%endif%}
|
||||
</td>
|
||||
<td>
|
||||
{{td.start.isoformat()[:10]}} - {{td.end.isoformat()[:10]}}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
|
||||
<tr><td colspan="2"><br /><h2>Past events</h2></td></tr>
|
||||
{% for td in past %}
|
||||
<tr>
|
||||
<td>
|
||||
<a href="/testday/{{td.id}}">{{td.name}}</a>
|
||||
{% if td.is_draft %}<span class="has-text-warning">[DRAFT!]</span>{%endif%}
|
||||
</td>
|
||||
<td>
|
||||
{{td.start.isoformat()[:10]}} - {{td.end.isoformat()[:10]}}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
<tr><td colspan="2" /></tr>
|
||||
</table>
|
||||
</div>
|
||||
</Root>
|
||||
17
testdays/components/Index.jinja
Normal file
17
testdays/components/Index.jinja
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<Root>
|
||||
{# djlint:off #}
|
||||
<Navbar.Navbar>
|
||||
<Navbar.Item>
|
||||
<a role="button" class="button is-primary js-toggler" data-target="push_button">Toggle 'Push me!' visibilty</a>
|
||||
</Navbar.Item>
|
||||
</Navbar.Navbar>
|
||||
{# djlint:on #}
|
||||
|
||||
{% if current_user.is_authenticated %}
|
||||
Welcome {{ current_user.username}}
|
||||
<input id="some_data" class="input highlight_changed" type="text" name="some_data"
|
||||
data-orig_value="Try and change this value" value="Try and change this value" />
|
||||
{% endif %}
|
||||
<button id="push_button" class="button" hx-post="{{url_for('main.http403')}}" hx-include="#some_data">Push me!</button>
|
||||
|
||||
</Root>
|
||||
37
testdays/components/Login.jinja
Normal file
37
testdays/components/Login.jinja
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
{#def form,next, captcha #}
|
||||
|
||||
<Root>
|
||||
<div class="container">
|
||||
<form action="" method="post" novalidate>
|
||||
{{ form.hidden_tag() }}
|
||||
{{ form.captcha_hash() }}
|
||||
<div class="field">
|
||||
<label class="label">{{ form.displayname.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.displayname(size=32, class_="input") }}</div>
|
||||
{% if form.displayname.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.displayname.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">
|
||||
<img src="data:image/png;base64, {{captcha['img']}}" alt='captcha' />
|
||||
<label class="label">{{ form.captcha.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.captcha(size=32, class_="input") }}</div>
|
||||
{% if form.captcha.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.captcha.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">{{ form.submit(class_="button is-link", value="Anonymous Login") }}</div>
|
||||
</form>
|
||||
<hr />
|
||||
<a class="button is-link is-fullwidth"
|
||||
href="{{ url_for("login_page.oidc_login_or_register") }}?next={{next}}">Login via OIDC</a>
|
||||
</div>
|
||||
</Root>
|
||||
3
testdays/components/Navbar/Item.jinja
Normal file
3
testdays/components/Navbar/Item.jinja
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<div class="navbar-item">
|
||||
{{ content }}
|
||||
</div>
|
||||
48
testdays/components/Navbar/Navbar.jinja
Normal file
48
testdays/components/Navbar/Navbar.jinja
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
{#js Navbar/js/Navbar.js #}
|
||||
<header>
|
||||
<nav class="navbar" role="navigation" aria-label="main navigation">
|
||||
<div class="navbar-brand">
|
||||
<a role="button"
|
||||
class="navbar-burger"
|
||||
data-target="navMenu"
|
||||
aria-label="menu"
|
||||
aria-expanded="false">
|
||||
<span aria-hidden="true"></span>
|
||||
<span aria-hidden="true"></span>
|
||||
<span aria-hidden="true"></span>
|
||||
<span aria-hidden="true"></span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div id="navMenu" class="navbar-menu">
|
||||
<div class="navbar-start">
|
||||
{{ content }}
|
||||
</div>
|
||||
|
||||
<div class="navbar-end">
|
||||
<Navbar.ThemeSwitcher />
|
||||
{% if not current_user.is_anonymous %}
|
||||
<div class="navbar-item">
|
||||
<a class="button " href="{{ url_for("main.edit_profile", user_id=current_user.id) }}">
|
||||
<span class="icon">
|
||||
<i class="fas fa-user" aria-hidden="true"></i>
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if current_user.has_role("admin") %}
|
||||
<div class="navbar-item">
|
||||
<a class="button is-primary" href="{{ url_for("admin.index") }}">Admin</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="navbar-item">
|
||||
{% if current_user.is_anonymous %}
|
||||
<a class="button is-primary" href="{{ url_for("login_page.login") }}">Login</a>
|
||||
{% else %}
|
||||
<a class="button is-danger" href="{{ url_for("login_page.logout") }}">Logout</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
38
testdays/components/Navbar/ThemeSwitcher.jinja
Normal file
38
testdays/components/Navbar/ThemeSwitcher.jinja
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
{#js Navbar/js/ThemeSwitcher.js #}
|
||||
|
||||
<div class="navbar-item has-dropdown is-hoverable">
|
||||
<a class="navbar-link is-arrowless">
|
||||
<span class="icon">
|
||||
<i class="fas fa-circle-half-stroke" aria-hidden="true"></i>
|
||||
</span>
|
||||
</a>
|
||||
<div class="navbar-dropdown is-right">
|
||||
<div class="js-themes">
|
||||
<a data-scheme="light"
|
||||
class="navbar-item is-danger"
|
||||
aria-label="Light mode">
|
||||
<span class="icon has-text-warning">
|
||||
<i class="fas fa-sun" aria-hidden="true">
|
||||
</i>
|
||||
</span>
|
||||
<span>Light</span>
|
||||
</a>
|
||||
|
||||
<a data-scheme="dark" class="navbar-item" aria-label="Dark mode">
|
||||
<span class="icon has-text-link">
|
||||
<i class="fas fa-moon" aria-hidden="true">
|
||||
</i>
|
||||
</span>
|
||||
<span>Dark</span>
|
||||
</a>
|
||||
|
||||
<a data-scheme="system" class="navbar-item" aria-label="System mode">
|
||||
<span class="icon has-text-primary">
|
||||
<i class="fas fa-desktop" aria-hidden="true">
|
||||
</i>
|
||||
</span>
|
||||
<span>System</span>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
20
testdays/components/Navbar/js/Navbar.js
Normal file
20
testdays/components/Navbar/js/Navbar.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
htmx.onLoad(function(content) {
|
||||
// NAVBAR HAMBURGER
|
||||
|
||||
// Get all "navbar-burger" elements
|
||||
const $navbarBurgers = content.querySelectorAll('.navbar-burger');
|
||||
|
||||
// Add a click event on each of them
|
||||
$navbarBurgers.forEach(el => {
|
||||
el.addEventListener('click', () => {
|
||||
|
||||
// Get the target from the "data-target" attribute
|
||||
const $target = document.getElementById(el.dataset.target);
|
||||
|
||||
// Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
|
||||
el.classList.toggle('is-active');
|
||||
$target.classList.toggle('is-active');
|
||||
|
||||
});
|
||||
});
|
||||
});
|
||||
100
testdays/components/Navbar/js/ThemeSwitcher.js
Normal file
100
testdays/components/Navbar/js/ThemeSwitcher.js
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
|
||||
htmx.onLoad(function(content) {
|
||||
const STORAGE_KEY = "bulma-theme";
|
||||
const SYSTEM_THEME = "system";
|
||||
const DEFAULT_THEME = "light";
|
||||
|
||||
const state = {
|
||||
chosenTheme: SYSTEM_THEME, // light|dark|system
|
||||
appliedTheme: DEFAULT_THEME, // light|dark
|
||||
OSTheme: null, // light|dark|null
|
||||
};
|
||||
|
||||
const $themeSwitchers = content.querySelectorAll(".js-themes a");
|
||||
|
||||
const updateThemeUI = () => {
|
||||
|
||||
$themeSwitchers.forEach((el) => {
|
||||
const swatchTheme = el.dataset.scheme;
|
||||
|
||||
if (state.chosenTheme === swatchTheme) {
|
||||
el.classList.add("has-text-text-light");
|
||||
el.classList.add("has-background-text-light-invert");
|
||||
} else {
|
||||
el.classList.remove("has-text-text-light");
|
||||
el.classList.remove("has-background-text-light-invert");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const setTheme = (theme, save = true) => {
|
||||
state.chosenTheme = theme;
|
||||
state.appliedTheme = theme;
|
||||
|
||||
if (theme === SYSTEM_THEME) {
|
||||
state.appliedTheme = state.OSTheme;
|
||||
document.documentElement.removeAttribute("data-theme");
|
||||
window.localStorage.removeItem(STORAGE_KEY);
|
||||
} else {
|
||||
document.documentElement.setAttribute("data-theme", theme);
|
||||
|
||||
if (save) {
|
||||
window.localStorage.setItem(STORAGE_KEY, theme);
|
||||
}
|
||||
}
|
||||
|
||||
updateThemeUI();
|
||||
};
|
||||
|
||||
const toggleTheme = () => {
|
||||
if (state.appliedTheme === "light") {
|
||||
setTheme("dark");
|
||||
} else {
|
||||
setTheme("light");
|
||||
}
|
||||
};
|
||||
|
||||
const detectOSTheme = () => {
|
||||
if (!window.matchMedia) {
|
||||
// matchMedia method not supported
|
||||
return DEFAULT_THEME;
|
||||
}
|
||||
|
||||
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
|
||||
// OS theme setting detected as dark
|
||||
return "dark";
|
||||
} else if (window.matchMedia("(prefers-color-scheme: light)").matches) {
|
||||
return "light";
|
||||
}
|
||||
|
||||
return DEFAULT_THEME;
|
||||
};
|
||||
|
||||
// On load, check if any preference was saved
|
||||
const localTheme = window.localStorage.getItem(STORAGE_KEY);
|
||||
state.OSTheme = detectOSTheme();
|
||||
|
||||
if (localTheme) {
|
||||
setTheme(localTheme, false);
|
||||
} else {
|
||||
setTheme(SYSTEM_THEME);
|
||||
}
|
||||
|
||||
// Event listeners
|
||||
$themeSwitchers.forEach((el) => {
|
||||
el.addEventListener("click", () => {
|
||||
const theme = el.dataset.scheme;
|
||||
setTheme(theme);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
window
|
||||
.matchMedia("(prefers-color-scheme: dark)")
|
||||
.addEventListener("change", (event) => {
|
||||
const theme = event.matches ? "dark" : "light";
|
||||
state.OSTheme = theme;
|
||||
setTheme(theme);
|
||||
});
|
||||
|
||||
});
|
||||
7
testdays/components/Notification.jinja
Normal file
7
testdays/components/Notification.jinja
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{#def message #}
|
||||
|
||||
<div class="notification is-primary">
|
||||
<button class="delete"
|
||||
onclick="this.parentElement.parentElement.removeChild(this.parentElement)"></button>
|
||||
<span>{{ message }}</span>
|
||||
</div>
|
||||
40
testdays/components/Root.jinja
Normal file
40
testdays/components/Root.jinja
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
{#js js/Toggler.js, js/NotificationOnHtmxResponseError.js, js/Inputs.js #}
|
||||
{# def page_title="Testdays" #}
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<title>{{page_title}}</title>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
|
||||
<!-- Bulma -->
|
||||
<link rel="stylesheet" href="https://bulma.io/vendor/fontawesome-free-6.5.2-web/css/all.min.css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@1.0.0/css/bulma.min.css">
|
||||
|
||||
<!-- HTMX -->
|
||||
<script src="https://unpkg.com/htmx.org@1.9.8"
|
||||
integrity="sha384-rgjA7mptc2ETQqXoYC3/zJvkU7K/aP44Y+z7xQuJiVnB/422P/Ak+F/AqFR7E4Wr"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="https://unpkg.com/htmx.org/dist/ext/loading-states.js"></script>
|
||||
|
||||
<!-- JinjaX Components -->
|
||||
{{ catalog.render_assets() }}
|
||||
</head>
|
||||
|
||||
<body hx-ext="loading-states">
|
||||
<div class="container">
|
||||
<div id="flash_message_template" hidden>
|
||||
<Notification message="Template" />
|
||||
</div>
|
||||
{% with messages = get_flashed_messages() %}
|
||||
{% for message in messages %}
|
||||
<Notification message={message} />{% endfor %}
|
||||
{% endwith %}
|
||||
</div>
|
||||
|
||||
{{ content }}
|
||||
</body>
|
||||
|
||||
</html>
|
||||
61
testdays/components/SubmitResult.jinja
Normal file
61
testdays/components/SubmitResult.jinja
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
{#def form, testday_id=None #}
|
||||
|
||||
<Root>
|
||||
<Navbar.Navbar>
|
||||
</Navbar.Navbar>
|
||||
<div class="container">
|
||||
<form action="" method="post" novalidate>
|
||||
{{ form.hidden_tag() }}
|
||||
<div class="field">
|
||||
<label class="label">{{ form.profile.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.profile(size=32, class_="input") }}</div>
|
||||
{% if form.profile.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.profile.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ form.result.label(class_="label") }}</label>
|
||||
<div class="select">{{form.result()}}</div>
|
||||
{% if form.result.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.result.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ form.comment.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.comment(size=32, class_="input") }}</div>
|
||||
{% if form.comment.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.comment.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="label">{{ form.bugs.label(class_="label") }}</label>
|
||||
<div class="control">{{ form.bugs(rows=5, class_="textarea", placeholder="One URL per line.\nAllowed TLDs: redhat.com, pagure.io, github.com, gitlab.com, forgejo.org, gitea.com") }}</div>
|
||||
{% if form.bugs.errors %}
|
||||
<ul class="errors">
|
||||
{% for error in form.bugs.errors %}
|
||||
<li>{{ error }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="field">
|
||||
{{ form.submit(class_="button is-link", value="Submit") }}
|
||||
{%if testday_id%}
|
||||
<a class="button is-warning"href="{{ url_for("main.show_testday", testday_id=testday_id) }}">Cancel</a>
|
||||
{%endif%}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</Root>
|
||||
117
testdays/components/Testday.jinja
Normal file
117
testdays/components/Testday.jinja
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
{#def testday, results, users #}
|
||||
|
||||
<Root page_title={testday.name}>
|
||||
{# djlint:off #}
|
||||
<Navbar.Navbar>
|
||||
<Navbar.Item>
|
||||
<div class="content"><h1>
|
||||
{{testday.name}}
|
||||
{% if current_user.has_role("admin") %}
|
||||
<a href="{{ url_for("admin.edit_testday", td_id=testday.id) }}">
|
||||
<span class="icon">
|
||||
<i class="fas fa-edit" aria-hidden="true"></i>
|
||||
</span>
|
||||
</a>
|
||||
{% endif %}
|
||||
</h1></div>
|
||||
</Navbar.Item>
|
||||
</Navbar.Navbar>
|
||||
{# djlint:on #}
|
||||
|
||||
<div class="content" style="margin-left: 1em; margin-right: 1em">
|
||||
More information about the event can be found here: <a href="{{testday.testday_url}}">{{testday.testday_url}}</a><br />
|
||||
Go back to <a href="/">List of Events</a>.
|
||||
|
||||
{% for section in testday.structure["Sections"] %}
|
||||
<h2>{{section["Name"]}}</h2>
|
||||
<table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Username</th>
|
||||
<th>{{ section["ProfileText"] if section["ProfileText"] else "Profile"}}</th>
|
||||
{% for tc in section["Testcases"] %}
|
||||
<th><a href="{{tc["Url"]}}">{{tc["Name"]}}</a></th>
|
||||
{% endfor %}
|
||||
<th>Comments</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
||||
<tr>
|
||||
<td></td>
|
||||
<td></td>
|
||||
{% for testcase in section["Testcases"] %}
|
||||
<td><a href="/testday/{{testday.id}}/submit_result/{{testcase["Ulid"]}}">Submit Result</a></td>
|
||||
{% endfor %}
|
||||
<td></td>
|
||||
</tr>
|
||||
{% set data_index = loop.index - 1 %}
|
||||
{% for user_selector in range(2) %}
|
||||
{% for usr, result_tds in results[user_selector][data_index].items() %}
|
||||
<tr>
|
||||
{% set comments = namespace(idx=1, text=[], bugs=[]) %}
|
||||
{% set helpers = namespace(had_result=False) %}
|
||||
<td>{{users[usr.id].displayname}}</td>
|
||||
<td>{{usr.profile}}</td>
|
||||
{% for rtd in result_tds %}
|
||||
<td>
|
||||
{% set helpers.had_result = False %}
|
||||
{% for r in rtd %}
|
||||
{{ r.result }}
|
||||
{% set helpers.had_result = True %}
|
||||
{% if r.comment or r.bugs %}
|
||||
<sup>[{{comments.idx}}]</sup>
|
||||
{% set comments.idx = comments.idx + 1 %}
|
||||
{% set tmp = comments.text.append(r.comment) %}
|
||||
{% set tmp = comments.bugs.append(r.bugs) %}
|
||||
{%endif %}
|
||||
|
||||
{% if current_user.id == usr.id %}
|
||||
<a href="/testday/{{testday.id}}/edit_result/{{r.testcase_ulid}}/{{r.id}}">
|
||||
<span class="icon">
|
||||
<i class="fas fa-edit" aria-hidden="true"></i>
|
||||
</span>
|
||||
</a>
|
||||
{% endif %}
|
||||
{% if not loop.last %}
|
||||
<br />
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% if not helpers.had_result and usr.id == current_user.id %}
|
||||
<!-- + -->
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endfor %}
|
||||
<td>
|
||||
{% for c in comments.text %}
|
||||
[{{loop.index}}]
|
||||
{% set bbb = [] %}
|
||||
{{c}}
|
||||
{% if comments.bugs[loop.index - 1] %}
|
||||
{% set bbb = comments.bugs[loop.index -1 ].split('\n') %}
|
||||
{% if c %}<br />{% endif%}
|
||||
Bugs:
|
||||
{% endif %}
|
||||
{% for bb in bbb %}
|
||||
<a href="{{bb}}">#{{loop.index}}</a>{%if not loop.last%},{%endif%}
|
||||
{% endfor %}
|
||||
{% if not loop.last %}<br />{% endif %}
|
||||
{% endfor %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% if user_selector == 0 and results[user_selector][data_index] %}
|
||||
<tr>
|
||||
<td colspan="{{3 + section["Testcases"]|count}}"> </td>
|
||||
</tr>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{% endfor %}
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
</Root>
|
||||
18
testdays/components/js/Inputs.js
Normal file
18
testdays/components/js/Inputs.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
htmx.onLoad(function(content) {
|
||||
const $inputs = content.querySelectorAll('.input.highlight_changed');
|
||||
|
||||
$inputs.forEach(el => {
|
||||
el.addEventListener('input', () => {
|
||||
|
||||
const orig_value = el.dataset.orig_value;
|
||||
const new_value = el.value;
|
||||
if (orig_value === new_value) {
|
||||
el.classList.remove("is-warning");
|
||||
} else {
|
||||
el.classList.add("is-warning");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
10
testdays/components/js/NotificationOnHtmxResponseError.js
Normal file
10
testdays/components/js/NotificationOnHtmxResponseError.js
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
document.addEventListener('htmx:responseError', e => {
|
||||
console.log(e);
|
||||
const errorBanner = document.getElementById("flash_message_template");
|
||||
const peb = errorBanner.parentElement;
|
||||
const clone = errorBanner.firstElementChild.cloneNode(true);
|
||||
clone.classList.remove('is-primary');
|
||||
clone.classList.add('is-danger');
|
||||
clone.getElementsByTagName('span')[0].innerText = e.detail.xhr.responseText;
|
||||
peb.appendChild(clone);
|
||||
});
|
||||
12
testdays/components/js/Toggler.js
Normal file
12
testdays/components/js/Toggler.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
htmx.onLoad(function(content) {
|
||||
const $togglers = content.querySelectorAll('.js-toggler');
|
||||
|
||||
$togglers.forEach(el => {
|
||||
el.addEventListener('click', () => {
|
||||
const $target=document.getElementById(el.dataset.target);
|
||||
$target.classList.toggle('is-hidden');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
|
|
@ -1,30 +1,21 @@
|
|||
# Copyright 2014, Red Hat, Inc
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
#
|
||||
# Authors:
|
||||
# Josef Skladanka <jskladan@redhat.com>
|
||||
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
|
||||
|
||||
class Config(object):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite://'
|
||||
DEBUG = False
|
||||
|
||||
LOGFILE = '/var/log/testdays/testdays.log'
|
||||
DB_URI = ""
|
||||
DB_DRIVER = ""
|
||||
DB_USER = ""
|
||||
DB_PASSWORD = ""
|
||||
DB_HOST = ""
|
||||
DB_PORT = ""
|
||||
DB_DATABASE = ""
|
||||
|
||||
SECRET_KEY = "not-really-a-secret"
|
||||
|
||||
LOGFILE = "/var/log/testdays.log"
|
||||
FILE_LOGGING = False
|
||||
SYSLOG_LOGGING = False
|
||||
STREAM_LOGGING = True
|
||||
|
|
@ -32,48 +23,117 @@ class Config(object):
|
|||
RUN_HOST = None
|
||||
RUN_PORT = None
|
||||
|
||||
PRODUCTION = False
|
||||
PRODUCTION = True
|
||||
DEVELOPMENT = False
|
||||
TESTING = False
|
||||
|
||||
SHOW_DB_URI = False
|
||||
|
||||
RESULTSDB_URL = 'http://localhost:5001/api/v2.0'
|
||||
OIDC_CLIENT_SECRETS = None
|
||||
OIDC_SCOPES = [
|
||||
"openid",
|
||||
"email",
|
||||
"profile",
|
||||
]
|
||||
|
||||
@property
|
||||
def SQLALCHEMY_DATABASE_URI(self):
|
||||
if self.DB_URI:
|
||||
return self.DB_URI
|
||||
|
||||
return f"{self.DB_DRIVER}://{self.DB_USER}:{self.DB_PASSWORD}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_DATABASE}"
|
||||
|
||||
@SQLALCHEMY_DATABASE_URI.setter
|
||||
def SQLALCHEMY_DATABASE_URI(self, value):
|
||||
pass
|
||||
|
||||
def update_from_object(self, obj):
|
||||
for key in dir(obj):
|
||||
if key.isupper():
|
||||
setattr(self, key, getattr(obj, key))
|
||||
|
||||
def update_from_pyfile(self, filename):
|
||||
"""Updates the values in the config from a Python file"""
|
||||
d = types.ModuleType("config")
|
||||
d.__file__ = filename
|
||||
try:
|
||||
with open(filename) as config_file:
|
||||
exec(compile(config_file.read(), filename, "exec"), d.__dict__)
|
||||
except IOError as e:
|
||||
e.strerror = "Unable to load configuration file (%s)" % e.strerror
|
||||
raise
|
||||
self.update_from_object(d)
|
||||
return True
|
||||
|
||||
def update_from_envvars(self):
|
||||
for key in dir(self):
|
||||
if key.isupper():
|
||||
setattr(self, key, os.environ.get(key, getattr(self, key)))
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
class Production(Config):
|
||||
RUNMODE = "Production"
|
||||
PRODUCTION = True
|
||||
DEVELOPMENT = False
|
||||
TESTING = False
|
||||
|
||||
DEBUG = False
|
||||
|
||||
FILE_LOGGING = False
|
||||
SYSLOG_LOGGING = True
|
||||
STREAM_LOGGING = True
|
||||
|
||||
DB_URI = ""
|
||||
DB_DRIVER = "postgresql+psycopg2"
|
||||
SHOW_DB_URI = False
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
class Development(Config):
|
||||
RUNMODE = "Development"
|
||||
PRODUCTION = False
|
||||
DEVELOPMENT = True
|
||||
TESTING = False
|
||||
|
||||
DEBUG = True
|
||||
|
||||
FILE_LOGGING = False
|
||||
SYSLOG_LOGGING = False
|
||||
STREAM_LOGGING = True
|
||||
|
||||
TRAP_BAD_REQUEST_ERRORS = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/testdays_db.sqlite'
|
||||
|
||||
RUN_HOST = '0.0.0.0'
|
||||
RUN_PORT = 5000
|
||||
DB_URI = "sqlite:////tmp/testdays_db.sqlite"
|
||||
|
||||
RUN_HOST = "0.0.0.0"
|
||||
RUN_PORT = 5050
|
||||
SHOW_DB_URI = True
|
||||
|
||||
|
||||
class TestingConfig(Config):
|
||||
TRAP_BAD_REQUEST_ERRORS = True
|
||||
|
||||
class Testing(Config):
|
||||
RUNMODE = "Testing"
|
||||
PRODUCTION = False
|
||||
DEVELOPMENT = False
|
||||
TESTING = True
|
||||
|
||||
def openshift_config(config_object, openshift_production):
|
||||
config_object["SHOW_DB_URI"] = True
|
||||
# First, get db details from env
|
||||
try:
|
||||
config_object["SQLALCHEMY_DATABASE_URI"] = "postgresql+psycopg2://%s:%s@%s:%s/%s" % (
|
||||
os.environ["POSTGRESQL_USER"],
|
||||
os.environ["POSTGRESQL_PASSWORD"],
|
||||
os.environ["POSTGRESQL_SERVICE_HOST"],
|
||||
os.environ["POSTGRESQL_SERVICE_PORT"],
|
||||
os.environ["POSTGRESQL_DATABASE"]
|
||||
)
|
||||
config_object["SECRET_KEY"] = os.environ["SECRET_KEY"]
|
||||
config_object["RESULTSDB_URL"] = os.environ["RESULTSDB_URL"]
|
||||
config_object["SHOW_DB_URI"] = False
|
||||
except(KeyError):
|
||||
print("OpenShift mode enabled but required values couldn't be fetched. "
|
||||
"Check, if you have these variables defined in you env: "
|
||||
"(POSTGRESQL_[USER, PASSWORD, DATABASE, SERVICE_HOST, SERVICE_PORT], SECRET_KEY, RESULTSDB_URL)", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
DEBUG = True
|
||||
|
||||
FILE_LOGGING = False
|
||||
SYSLOG_LOGGING = False
|
||||
STREAM_LOGGING = True
|
||||
|
||||
TRAP_BAD_REQUEST_ERRORS = True
|
||||
SHOW_DB_URI = True
|
||||
|
||||
|
||||
|
||||
def check_required_openshift_envvars():
|
||||
# First, get db details from env
|
||||
missing = []
|
||||
for key in ["DB_DRIVER", "DB_USER", "DB_PASSWORD", "DB_HOST", "DB_PORT", "DB_DATABASE"]:
|
||||
if not os.environ.get(key):
|
||||
missing.append(key)
|
||||
if missing:
|
||||
missing = "\n".join(missing)
|
||||
message = f"OpenShift mode enabled but some required environment variables are missing:\n{missing}"
|
||||
raise RuntimeError(message)
|
||||
|
|
|
|||
|
|
@ -1,219 +1,260 @@
|
|||
# Copyright 2014, Red Hat, Inc
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
#
|
||||
# Authors:
|
||||
# Josef Skladanka <jskladan@redhat.com>
|
||||
import datetime
|
||||
import json
|
||||
|
||||
import re
|
||||
import wtforms
|
||||
from flask import Blueprint, Response, abort, flash, redirect, request, url_for
|
||||
from flask_login import current_user, login_required
|
||||
from flask_wtf import FlaskForm
|
||||
from ulid import ULID
|
||||
from wtforms import (
|
||||
BooleanField,
|
||||
DateField,
|
||||
PasswordField,
|
||||
SelectField,
|
||||
StringField,
|
||||
SubmitField,
|
||||
TextAreaField,
|
||||
ValidationError,
|
||||
validators,
|
||||
)
|
||||
|
||||
from flask import Blueprint, render_template, flash, url_for, redirect, make_response
|
||||
from flask_login import login_required
|
||||
from sqlalchemy.orm.exc import NoResultFound
|
||||
from .. import catalog, db
|
||||
from ..models import *
|
||||
from ..utils.authorization import admin_required
|
||||
|
||||
from resultsdb_api import ResultsDBapi
|
||||
|
||||
from testdays import app, db
|
||||
from testdays.controllers.main import preparse_results
|
||||
import testdays.lib.wiki as wiki
|
||||
from testdays.lib.forms import AddEventForm
|
||||
from testdays.models.testday import Event, Category, Testcase, TESTCASE_TYPES
|
||||
|
||||
import uuid
|
||||
|
||||
admin = Blueprint('admin', __name__)
|
||||
|
||||
RDB_API = None
|
||||
UUID_NS = uuid.uuid5(uuid.NAMESPACE_DNS, 'Testdays Frontend')
|
||||
|
||||
@app.before_first_request
|
||||
def before_first_request():
|
||||
global RDB_API
|
||||
RDB_API = ResultsDBapi(app.config['RESULTSDB_URL'])
|
||||
# /admin prefix set in ../__init__.py
|
||||
admin = Blueprint("admin", __name__)
|
||||
|
||||
|
||||
@admin.route('/admin')
|
||||
@admin.route('/admin/')
|
||||
#@login_required
|
||||
def admin_index():
|
||||
return render_template('admin/index.html')
|
||||
@admin.route("/")
|
||||
@login_required
|
||||
@admin_required
|
||||
def index():
|
||||
return catalog.render("Admin.Index")
|
||||
|
||||
def event_from_metadata(url):
|
||||
|
||||
# grab the respective section from wikipage
|
||||
data = wiki.get_page_section(url, "TestdayApp Metadata").decode('utf-8')
|
||||
@admin.route("/users", methods=["GET", "POST"])
|
||||
@login_required
|
||||
@admin_required
|
||||
def users():
|
||||
users = User.query.order_by(User.id).all()
|
||||
return catalog.render("Admin.Users", users=users)
|
||||
|
||||
|
||||
# matches text from lines enclosed in '=' characters
|
||||
re_groupname = re.compile("^=+\s*(.*?)\s*=*$")
|
||||
@admin.route("/users/<int:id_>", methods=["GET", "PUT", "DELETE"])
|
||||
@login_required
|
||||
@admin_required
|
||||
def users_id(id_=None):
|
||||
user = User.query.filter(User.id == id_).first()
|
||||
if not user:
|
||||
return Response("User not found", 404, mimetype="text/plain")
|
||||
|
||||
td = {"name":"", "url":"", "categories": []}
|
||||
category = {"name":"", "testcases": []}
|
||||
testcase = {"name":"", "url":"", "type":""}
|
||||
if not current_user.has_role('admin') and user.id != current_user.id:
|
||||
return Response(status=403)
|
||||
|
||||
# splits text on newlines, strips whitespaces and filters relevant lines
|
||||
# the first line is deemed irrelevant, as it is just the name of the section
|
||||
data = [line.strip() for line in data.split('\n')[1:]]
|
||||
data = [line for line in data if line.startswith("*") or line.startswith("=")]
|
||||
|
||||
# Testday Name & URL
|
||||
# the first line must contain testday's name and URL in the '*name;url' format
|
||||
name_url = data.pop(0)
|
||||
if not name_url.startswith("*"):
|
||||
return (False, "Missing Testday name & URL")
|
||||
try:
|
||||
# remove * at the beginning, split by ';' in two parts, and strip whitespaces
|
||||
td_name, td_url = [part.strip() for part in name_url[1:].split(';', 2)]
|
||||
except ValueError: # split failed
|
||||
return (False, "Testday name or URL missing")
|
||||
if request.method == "DELETE":
|
||||
db.session.delete(user)
|
||||
db.session.commit()
|
||||
return Response(status=200)
|
||||
|
||||
# sanity check
|
||||
if len(td_name) < 5:
|
||||
return (False, "Testday name must be longer than 5 characters")
|
||||
if not td_url.startswith("http"):
|
||||
return (False, "Testday URL must start with 'http'")
|
||||
if request.method == "PUT":
|
||||
role = UserRoles.get_by_name(request.form["role"].strip())
|
||||
if not role:
|
||||
return Response("Invalid role", 422)
|
||||
|
||||
if td_url.startswith("https"):
|
||||
td_url = td_url.replace("https", "http", 1)
|
||||
if user.username.startswith("anon:") and role == UserRoles.admin:
|
||||
return Response("Anonymous users can not be admins", 422)
|
||||
|
||||
start, end = wiki.get_td_dates(td_url)
|
||||
event = Event(td_name, url, td_url, start, end)
|
||||
user.role = role
|
||||
should_disable = request.form["disabled"].lower().strip() == "true"
|
||||
if current_user.id == user.id and should_disable:
|
||||
return Response("You can not disable your own account", 422)
|
||||
user.disabled = should_disable
|
||||
|
||||
# Testcase Sections
|
||||
category = None
|
||||
for line in data:
|
||||
# Create a new category, when we encounter category metadata
|
||||
if line.startswith("="):
|
||||
name = re_groupname.findall(line)[0]
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
return catalog.render("Admin.Users", users=[user])
|
||||
|
||||
|
||||
|
||||
class TDMetadataField(TextAreaField):
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.JSONDATA = dict()
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
|
||||
def human_structure_to_dict(form, field):
|
||||
value = field.data
|
||||
sections = []
|
||||
ln = 0
|
||||
for l in value.split("\n"):
|
||||
ln += 1
|
||||
l = l.strip()
|
||||
if l.startswith("="):
|
||||
name = l.strip("=").strip()
|
||||
if not name:
|
||||
return (False, "Category name must be at least 1 character long at line %r" % line)
|
||||
category = Category(name, event)
|
||||
raise ValidationError(f"Line #{ln}: Empty section name")
|
||||
sections.append({"Name": name, "ProfileText": "", "Testcases": list()})
|
||||
continue
|
||||
|
||||
# skip until we get a category
|
||||
if category is None:
|
||||
continue
|
||||
# skip until we get a testcase
|
||||
if not line.startswith("*"):
|
||||
if l.startswith("! ProfileText:"):
|
||||
if not sections:
|
||||
raise ValidationError(f"Line #{ln}: `{l}` must be within a section")
|
||||
sections[-1]["ProfileText"] = l[len("! ProfileText:") :].strip()
|
||||
continue
|
||||
|
||||
# Parse the testcase metadata
|
||||
|
||||
# remove * at the beginning, split by ';' and strip whitespaces
|
||||
l = [part.strip() for part in line[1:].split(';')]
|
||||
# append default testcase result type (pass/fail/info)
|
||||
l.append('tc')
|
||||
|
||||
if len(l) < 3:
|
||||
return (False, "Testcase name or url missing on line %r" % line)
|
||||
|
||||
testcase = Testcase(l[0], l[1], l[2].lower(), category)
|
||||
|
||||
if len(testcase.name) < 1:
|
||||
return (False, "Testcase name must be at least 1 character long at line %r" % line)
|
||||
if not testcase.url.startswith('http'):
|
||||
return (False, "Testcase url does not start with 'http' on line %r" % line)
|
||||
|
||||
# convert unknown types to the default "testcase" type
|
||||
if testcase.type not in TESTCASE_TYPES:
|
||||
testcase.type = 'tc'
|
||||
|
||||
# change https to http
|
||||
testcase.url = testcase.url.replace("https", "http", 1)
|
||||
|
||||
return(True, event)
|
||||
|
||||
|
||||
@admin.route('/admin/add_event', methods=['GET', 'POST'])
|
||||
def add_event():
|
||||
form_ = AddEventForm()
|
||||
|
||||
if form_.validate_on_submit():
|
||||
was_ok, data = event_from_metadata(form_.metadata_url.data)
|
||||
if was_ok:
|
||||
event = data
|
||||
if l.startswith("*"):
|
||||
if not sections:
|
||||
raise ValidationError(f"Line #{ln}: `{l}` must be within a section")
|
||||
l = l.strip("*").strip(";").split(";")
|
||||
try:
|
||||
old_event = db.session.query(Event).filter(Event.metadata_url == event.metadata_url).one()
|
||||
# Event with this metadata url not found -> create new event
|
||||
except NoResultFound:
|
||||
db.session.add(event)
|
||||
db.session.commit()
|
||||
db.session.add(event)
|
||||
name, url, ulid = l
|
||||
ulid = ulid.strip()
|
||||
if not ulid:
|
||||
ulid = None
|
||||
except ValueError:
|
||||
ulid = None
|
||||
try:
|
||||
name, url = l
|
||||
except ValueError:
|
||||
raise ValidationError(f"Line #{ln}: `{';'.join(l)}` is malformed")
|
||||
name = name.strip()
|
||||
url = url.strip()
|
||||
if not name:
|
||||
raise ValidationError(f"Line #{ln}: Name can not be empty")
|
||||
if not url:
|
||||
raise ValidationError(f"Line #{ln}: Url can not be empty")
|
||||
sections[-1]["Testcases"].append({"Ulid": ulid, "Name": name, "Url": url})
|
||||
|
||||
# create resultsdb group
|
||||
ref_url = url_for('main.show_event', event_id=event.id)
|
||||
rdb_job = RDB_API.create_group(
|
||||
uuid=str(uuid.uuid5(UUID_NS, ref_url)),
|
||||
ref_url=ref_url,
|
||||
description="Testday - %s" % event.testday_url.split('/')[-1],
|
||||
)
|
||||
event.resultsdb_job_uuid = rdb_job['uuid']
|
||||
db.session.add(event)
|
||||
db.session.commit()
|
||||
flash('Event was successfully created')
|
||||
# Event with this metadata url found -> update
|
||||
else:
|
||||
# Remove old categories and testcases
|
||||
for category in old_event.categories:
|
||||
for testcase in category.testcases:
|
||||
db.session.delete(testcase)
|
||||
db.session.delete(category)
|
||||
|
||||
event.id = old_event.id
|
||||
event.resultsdb_job_uuid = old_event.resultsdb_job_uuid
|
||||
# Update start/end
|
||||
start, end = wiki.get_td_dates(event.testday_url)
|
||||
event.testday_start = start
|
||||
event.testday_end = end
|
||||
|
||||
db.session.merge(event)
|
||||
db.session.commit()
|
||||
flash('Event was successfully updated')
|
||||
|
||||
return redirect(url_for('main.show_event', event_id = event.id))
|
||||
|
||||
# an error was encountered, flash the error and show the add_event form
|
||||
flash(data, 'error')
|
||||
|
||||
return render_template('admin/add_event.html',
|
||||
form = form_,
|
||||
form_action = url_for(".add_event"),
|
||||
header = u"Add/Edit Event",
|
||||
for s in sections:
|
||||
if not s["Testcases"]:
|
||||
raise ValidationError(
|
||||
f"Section `{s['Name']}` does not contain any testcases"
|
||||
)
|
||||
|
||||
@admin.route('/admin/export_event', methods=['GET', 'POST'])
|
||||
def export_event():
|
||||
form_ = AddEventForm()
|
||||
field.JSONDATA = {"Sections": sections}
|
||||
|
||||
if form_.validate_on_submit():
|
||||
|
||||
def dict_structure_to_human(structure):
|
||||
lines = []
|
||||
for section in structure["Sections"]:
|
||||
lines.append(f"= {section['Name']}")
|
||||
if section["ProfileText"]:
|
||||
lines.append(f"! ProfileText: {section['ProfileText']}")
|
||||
for tc in section["Testcases"]:
|
||||
lines.append(f"* {tc['Name']};\t\t{tc['Url']};\t\t{tc['Ulid']}")
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
class TestdayForm(FlaskForm):
|
||||
name = StringField("Name", validators=[validators.InputRequired()])
|
||||
url = StringField(
|
||||
"Url", validators=[validators.InputRequired()]
|
||||
) # , validators.URL()])
|
||||
start = DateField("Start", validators=[validators.InputRequired()])
|
||||
end = DateField("End", validators=[validators.InputRequired()])
|
||||
structure = TDMetadataField(
|
||||
"Testday structure definition",
|
||||
validators=[validators.InputRequired(), human_structure_to_dict],
|
||||
)
|
||||
|
||||
draft = BooleanField("Draft", default=True)
|
||||
submit = SubmitField("Submit")
|
||||
|
||||
|
||||
@admin.route("/create_testday", methods=["POST", "GET"])
|
||||
@login_required
|
||||
@admin_required
|
||||
def create_testday():
|
||||
form = TestdayForm()
|
||||
if form.validate_on_submit():
|
||||
|
||||
td = Testday(form.name.data.strip())
|
||||
for s in form.structure.JSONDATA["Sections"]:
|
||||
for tc_m in s["Testcases"]:
|
||||
t = Testcase(tc_m["Url"], td)
|
||||
tc_m["Ulid"] = t.ulid
|
||||
|
||||
td.structure = form.structure.JSONDATA
|
||||
td.testday_url = form.url.data.strip()
|
||||
td.start = form.start.data
|
||||
td.end = form.end.data
|
||||
td.is_draft = form.draft.data
|
||||
db.session.add(td)
|
||||
db.session.commit()
|
||||
return redirect(url_for("main.show_testday", testday_id=td.id))
|
||||
|
||||
return catalog.render("Admin.CreateTestday", form=form)
|
||||
|
||||
|
||||
|
||||
def perform_testcase_changes(td, form_structure):
|
||||
sections = form_structure.JSONDATA["Sections"]
|
||||
ulids = set()
|
||||
known_tcs = dict([(tc.ulid, tc) for tc in td.testcases])
|
||||
for s in sections:
|
||||
for m_tc in s["Testcases"]:
|
||||
ulid = m_tc["Ulid"]
|
||||
if not ulid:
|
||||
t = Testcase(m_tc["Url"], td)
|
||||
m_tc["Ulid"] = t.ulid
|
||||
db.session.add(t)
|
||||
ulids.add(t.ulid)
|
||||
continue
|
||||
if ulid in ulids:
|
||||
db.session.rollback()
|
||||
raise ValueError(f"Duplicate testcase ulid `{ulid}`")
|
||||
ulids.add(ulid)
|
||||
if ulid not in known_tcs:
|
||||
db.session.rollback()
|
||||
raise ValueError(
|
||||
f"Testcase with ulid `{ulid}` does not exist in this testday"
|
||||
)
|
||||
d_tc = known_tcs[ulid]
|
||||
d_tc.url = m_tc["Url"]
|
||||
db.session.add(d_tc)
|
||||
|
||||
for tc in known_tcs.values():
|
||||
if tc.ulid not in ulids:
|
||||
if len(tc.results) == 0:
|
||||
td.testcases.pop(td.testcases.index(tc))
|
||||
db.session.delete(tc)
|
||||
|
||||
|
||||
@admin.route("/edit_testday/<int:td_id>", methods=["POST", "GET"])
|
||||
@login_required
|
||||
@admin_required
|
||||
def edit_testday(td_id):
|
||||
td = Testday.query.filter(Testday.id == td_id).first()
|
||||
if not td:
|
||||
return Response("Not Found", 404, mimetype="text/plain")
|
||||
|
||||
form = TestdayForm()
|
||||
if form.validate_on_submit():
|
||||
try:
|
||||
event = db.session.query(Event).filter(Event.metadata_url == form_.metadata_url.data).one()
|
||||
perform_testcase_changes(td, form.structure)
|
||||
except ValueError as e:
|
||||
form.structure.errors.append(str(e))
|
||||
return catalog.render("Admin.CreateTestday", form=form)
|
||||
|
||||
except NoResultFound:
|
||||
flash('Event not found', 'error')
|
||||
td.name = form.name.data.strip()
|
||||
td.testday_url = form.url.data.strip()
|
||||
td.structure = form.structure.JSONDATA
|
||||
td.start = form.start.data
|
||||
td.end = form.end.data
|
||||
td.is_draft = form.draft.data
|
||||
db.session.add(td)
|
||||
db.session.commit()
|
||||
return redirect(url_for("main.show_testday", testday_id=td.id))
|
||||
|
||||
results = preparse_results(event)
|
||||
output = render_template('admin/export_event.txt', event=event, results=results)
|
||||
response = make_response(output)
|
||||
response.headers["Content-Type"] = "text/plain; charset=utf-8"
|
||||
return response
|
||||
|
||||
|
||||
return render_template('admin/add_event.html',
|
||||
form = form_,
|
||||
form_action = url_for(".export_event"),
|
||||
header = u"Export Event",
|
||||
)
|
||||
if request.method == "GET":
|
||||
form.name.data = td.name
|
||||
form.url.data = td.testday_url
|
||||
form.structure.data = dict_structure_to_human(td.structure)
|
||||
form.start.data = td.start
|
||||
form.end.data = td.end
|
||||
form.draft.data = td.is_draft
|
||||
|
||||
return catalog.render("Admin.CreateTestday", form=form)
|
||||
|
|
|
|||
14
testdays/controllers/api.py
Normal file
14
testdays/controllers/api.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import datetime
|
||||
|
||||
from flask import Blueprint, Response, flash, jsonify, redirect, request, url_for
|
||||
from flask_login import login_required
|
||||
|
||||
from ..models import *
|
||||
|
||||
# /api/0 prefix set in ../__init__.py
|
||||
api = Blueprint("api", __name__)
|
||||
|
||||
|
||||
@api.route("/probe")
|
||||
def probe():
|
||||
return jsonify({"now": datetime.datetime.now().isoformat()})
|
||||
|
|
@ -1,80 +1,150 @@
|
|||
# Copyright 2014, Red Hat, Inc
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
#
|
||||
# Authors:
|
||||
# Josef Skladanka <jskladan@redhat.com>
|
||||
import urllib.parse
|
||||
|
||||
from flask import Blueprint, render_template, redirect, flash, url_for, request
|
||||
from flask import (
|
||||
Blueprint,
|
||||
Response,
|
||||
flash,
|
||||
make_response,
|
||||
redirect,
|
||||
request,
|
||||
session,
|
||||
url_for,
|
||||
)
|
||||
from flask_login import current_user, login_required, login_user, logout_user
|
||||
from flask_wtf import FlaskForm
|
||||
from wtforms import StringField, PasswordField, HiddenField, RadioField
|
||||
from wtforms.validators import InputRequired
|
||||
from flask_login import login_user, logout_user, login_required, current_user, AnonymousUserMixin
|
||||
from ulid import ULID
|
||||
from werkzeug.security import check_password_hash, generate_password_hash
|
||||
from wtforms import (
|
||||
BooleanField,
|
||||
HiddenField,
|
||||
PasswordField,
|
||||
StringField,
|
||||
SubmitField,
|
||||
ValidationError,
|
||||
validators,
|
||||
)
|
||||
|
||||
from .. import SIMPLE_CAPTCHA, app, catalog, db, oidc
|
||||
from ..models import *
|
||||
from ..models.user import user_displayname_validator
|
||||
|
||||
login_page = Blueprint("login_page", __name__)
|
||||
|
||||
|
||||
from testdays import app, login_manager
|
||||
from testdays.models.user import User
|
||||
|
||||
login_page = Blueprint('login_page', __name__)
|
||||
def captcha_validator(form, field):
|
||||
text = field.data.strip().upper()
|
||||
hash = form.captcha_hash.data
|
||||
ok = check_password_hash(hash, text)
|
||||
if not ok:
|
||||
raise ValidationError("Mismatched captcha")
|
||||
|
||||
|
||||
class LoginForm(FlaskForm):
|
||||
username = StringField(u'Username', validators = [InputRequired()])
|
||||
password = PasswordField(u'Password', validators = [InputRequired()])
|
||||
next_page = HiddenField()
|
||||
class DisplayNameForm(FlaskForm):
|
||||
displayname = StringField(
|
||||
"Displayname",
|
||||
validators=[
|
||||
validators.InputRequired(),
|
||||
validators.Length(max=80),
|
||||
user_displayname_validator,
|
||||
],
|
||||
)
|
||||
captcha_hash = HiddenField()
|
||||
captcha = StringField(
|
||||
"Captcha",
|
||||
validators=[
|
||||
validators.InputRequired(),
|
||||
captcha_validator,
|
||||
],
|
||||
)
|
||||
submit = SubmitField("Submit")
|
||||
|
||||
|
||||
# handle login stuff
|
||||
@login_manager.user_loader
|
||||
def load_user(userid):
|
||||
app.logger.debug("getting info for user %s" % str(userid))
|
||||
user = User.query.get(userid)
|
||||
if user:
|
||||
return user
|
||||
else:
|
||||
return AnonymousUserMixin
|
||||
@login_page.route("/")
|
||||
def index():
|
||||
return catalog.render("Index")
|
||||
|
||||
|
||||
@login_page.route('/login', methods=['GET', 'POST'])
|
||||
@login_page.route("/http403", methods=["GET", "POST"])
|
||||
def http403():
|
||||
return Response("How about no?", 403, mimetype="text/plain")
|
||||
|
||||
|
||||
@login_page.route("/login", methods=["GET", "POST"])
|
||||
def login():
|
||||
login_form = LoginForm()
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for("main.index"))
|
||||
|
||||
if login_form.validate_on_submit():
|
||||
user = User.query.filter_by(username = login_form.username.data).first()
|
||||
if user and user.check_password(login_form.password.data):
|
||||
login_user(user)
|
||||
next_page = request.args.get("next")
|
||||
if not next_page or urllib.parse.urlsplit(next_page).netloc != "":
|
||||
next_page = url_for("main.index")
|
||||
|
||||
app.logger.info('Successful login for user %s' % login_form.username.data)
|
||||
flash('Logged In Successfully!')
|
||||
form = DisplayNameForm()
|
||||
if form.validate_on_submit():
|
||||
# login code goes here
|
||||
displayname = request.form.get("displayname")
|
||||
|
||||
return redirect(login_form.next_page.data)
|
||||
else:
|
||||
app.logger.info('FAILED login for user %s' % login_form.username.data)
|
||||
flash('Login Failed! Please Try again!')
|
||||
try:
|
||||
user = User(f"anon:{ULID()}", displayname)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
except:
|
||||
flash(message="Login unsuccessfull")
|
||||
return catalog.render("Login", form=form)
|
||||
|
||||
login_form.next_page.data = request.args.get('next') or url_for('main.index')
|
||||
return render_template('login.html', form = login_form)
|
||||
login_user(user)
|
||||
|
||||
return redirect(next_page)
|
||||
|
||||
captcha = SIMPLE_CAPTCHA.create()
|
||||
print(", ".join(captcha.keys()))
|
||||
form.captcha_hash.data = generate_password_hash(captcha["text"])
|
||||
c = {"img": captcha["img"], "text": captcha["text"]}
|
||||
|
||||
return catalog.render("Login", form=form, next=next_page, captcha=c)
|
||||
|
||||
|
||||
@login_page.route('/logout')
|
||||
@login_page.route("/oidc_login")
|
||||
@oidc.require_login
|
||||
def oidc_login_or_register():
|
||||
oidc_data = session["oidc_auth_profile"]
|
||||
import pprint
|
||||
|
||||
pprint.pprint(oidc_data)
|
||||
|
||||
sub = oidc_data["sub"]
|
||||
displayname = oidc_data["email"]
|
||||
|
||||
if ".fedoraproject.org" in oidc.client_secrets["auth_uri"]:
|
||||
sub = "fedora:" + sub
|
||||
displayname = oidc_data["sub"]
|
||||
elif ".google.com" in oidc.client_secrets["auth_uri"]:
|
||||
sub = "google:" + sub
|
||||
displayname = oidc_data.get("name", "").strip() or oidc_data["email"]
|
||||
|
||||
user = User.query.filter(User.username == sub).first()
|
||||
if not user:
|
||||
user = User(sub, displayname)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
print(user.id, user.username, user.displayname)
|
||||
|
||||
login_user(user)
|
||||
next = request.args.get("next")
|
||||
if next:
|
||||
return redirect(next)
|
||||
return redirect(url_for("main.index"))
|
||||
|
||||
|
||||
@login_page.route("/cclean")
|
||||
def cclean():
|
||||
res = make_response(redirect(url_for("main.index")))
|
||||
res.set_cookie("session", "", expires=0)
|
||||
res.set_cookie("profile", "", expires=0)
|
||||
return res
|
||||
|
||||
|
||||
@login_page.route("/logout")
|
||||
@login_required
|
||||
def logout():
|
||||
app.logger.info('logout for user %s' % current_user.username)
|
||||
logout_user()
|
||||
flash('Logged Out Successfully!')
|
||||
return redirect(url_for('main.index'))
|
||||
|
||||
|
||||
|
||||
return redirect(url_for("login_page.cclean"))
|
||||
|
|
|
|||
|
|
@ -1,364 +1,283 @@
|
|||
# Copyright 2014, Red Hat, Inc
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
#
|
||||
# Authors:
|
||||
# Josef Skladanka <jskladan@redhat.com>
|
||||
|
||||
import re
|
||||
import html
|
||||
import json
|
||||
import datetime
|
||||
from flask import Blueprint, render_template, redirect, url_for, flash, session
|
||||
from sqlalchemy.orm.exc import NoResultFound
|
||||
import pprint
|
||||
from collections import namedtuple
|
||||
from os import wait
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import resultsdb_api
|
||||
import requests
|
||||
from flask import (Blueprint, Response, after_this_request, flash, redirect,
|
||||
request, session, url_for)
|
||||
from flask_login import current_user, login_required, login_user, logout_user
|
||||
from flask_wtf import FlaskForm
|
||||
from jinja2.nodes import Test
|
||||
from ulid import ULID
|
||||
from wtforms import (BooleanField, PasswordField, SelectField, StringField,
|
||||
SubmitField, TextAreaField, ValidationError, validators)
|
||||
|
||||
from testdays import app, db
|
||||
from testdays.models.testday import Event, Category, Testcase
|
||||
from testdays.lib.forms import EnterResultForm
|
||||
from alembic.command import current
|
||||
|
||||
main = Blueprint('main', __name__)
|
||||
from .. import app, catalog, db, oidc
|
||||
from ..models import *
|
||||
from ..models.user import user_displayname_validator
|
||||
from .login_page import DisplayNameForm
|
||||
|
||||
RDB_API = None
|
||||
TESTCASES = []
|
||||
RE_TESTCASE_NAME_NORMALIZE = re.compile(r'[^a-zA-Z0-9_]')
|
||||
main = Blueprint("main", __name__)
|
||||
|
||||
@app.before_first_request
|
||||
def before_first_request():
|
||||
global RDB_API
|
||||
RDB_API = resultsdb_api.ResultsDBapi(app.config['RESULTSDB_URL'])
|
||||
|
||||
@main.route('/')
|
||||
@main.route('/index')
|
||||
@main.route("/")
|
||||
def index():
|
||||
return redirect(url_for('.events'))
|
||||
if current_user.has_role("admin"):
|
||||
tds = Testday.query.order_by(Testday.end).all()
|
||||
else:
|
||||
tds = Testday.query.filter(Testday.is_draft == False).order_by(Testday.end).all()
|
||||
|
||||
@main.route('/events')
|
||||
def events():
|
||||
events = db.session.query(Event).order_by(Event.created_at.desc())
|
||||
processed_events = []
|
||||
upcoming_or_active_events = []
|
||||
for event in events:
|
||||
single_event = {"name": event.name, "id": event.id, "dates": "N/A", "active": False, "upcoming_or_active": False}
|
||||
if not event.testday_start == datetime.datetime(1900, 1, 1, 0, 0):
|
||||
start = str(event.testday_start.date().strftime("%b %d, %Y"))
|
||||
end = str(event.testday_end.date().strftime("%b %d, %Y"))
|
||||
single_event["dates"] = "%s - %s" % (start, end) if start != end else "%s" % start
|
||||
date_now = datetime.datetime.utcnow().date()
|
||||
if date_now <= event.testday_end.date():
|
||||
single_event["upcoming_or_active"] = True
|
||||
if date_now >= event.testday_start.date():
|
||||
single_event["active"] = True
|
||||
upcoming_or_active_events.append(single_event)
|
||||
processed_events.append(single_event)
|
||||
now = datetime.datetime.now()
|
||||
|
||||
return render_template('list_events.html', events=processed_events, upcoming_or_active_events=upcoming_or_active_events)
|
||||
current = [t for t in tds if t.end >= now]
|
||||
past = reversed([t for t in tds if t.end < now])
|
||||
return catalog.render("EventList", current=current, past=past)
|
||||
|
||||
|
||||
# TODO: use Memcached instead of SimpleCache
|
||||
from flask_caching import Cache
|
||||
CACHE = Cache(app, config={'CACHE_TYPE': 'simple'})
|
||||
CACHE_TIMEOUT = 10
|
||||
|
||||
def preparse_results(event):
|
||||
global CACHE
|
||||
cached = CACHE.get("event_%s_matrix" % event.id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
def validate_bugs_field(form, field):
|
||||
value = field.data
|
||||
try:
|
||||
results_count = RDB_API.get_group(event.resultsdb_job_uuid)['results_count']
|
||||
results = RDB_API.get_results(groups=[event.resultsdb_job_uuid], limit=results_count)['data']
|
||||
except (resultsdb_api.ResultsDBapiException, requests.exceptions.ConnectionError):
|
||||
results = []
|
||||
# results is a list of dicts like this:
|
||||
# {
|
||||
# "href": "http://taskotron-local/resultsdb_api/api/v1.0/results/1510407",
|
||||
# "id": 1510407,
|
||||
# "groups": ["uuid"],
|
||||
# "ref_url": null,
|
||||
# "outcome": "PASSED",
|
||||
# "data": {
|
||||
# "bugs": [
|
||||
# ""
|
||||
# ],
|
||||
# "col_1": [
|
||||
# "Fedora 19"
|
||||
# ],
|
||||
# "result": [
|
||||
# "cats!"
|
||||
# ],
|
||||
# "username": [
|
||||
# "jskladan"
|
||||
# ]
|
||||
# },
|
||||
# "submit_time": "2015-05-14T09:20:36.392351",
|
||||
# "note": "Comment number 4",
|
||||
# "testcase": {
|
||||
# "href": "http://taskotron-local/resultsdb_api/api/v1.0/testcases/testdays_QA_Testcase_Power_Management_tuned_off_idle",
|
||||
# "name": "testdays_QA_Testcase_Power_Management_tuned_off_idle",
|
||||
# "ref_url": "http://fedoraproject.org/wiki/QA:Testcase_Power_Management_tuned_off_idle"
|
||||
# }
|
||||
# }
|
||||
value = value.strip()
|
||||
except AttributeError:
|
||||
raise ValidationError("Bugs must be string")
|
||||
|
||||
# The following code will rearrange the results into structure like this one:
|
||||
#
|
||||
# {$username: {$col_1: {$tcurl: [{'bugs': $bugs.split(';'),
|
||||
# 'comment': $summary,
|
||||
# 'result': $result,
|
||||
# }]}}}
|
||||
#
|
||||
# Where $username, $col_1, and $result are from ['data'],
|
||||
# $tcurl is the testcase url from ['testcase']['ref_url']
|
||||
if not value:
|
||||
return ""
|
||||
|
||||
by_user = {}
|
||||
for result in results:
|
||||
data = result['data']
|
||||
ln = 0
|
||||
links = []
|
||||
for l in value.split("\n"):
|
||||
ln += 1
|
||||
l = l.strip()
|
||||
|
||||
username = data['username'][0]
|
||||
col_1 = data['col_1'][0]
|
||||
tcurl = result['testcase']['ref_url']
|
||||
if not l:
|
||||
continue
|
||||
|
||||
outcome = data['result'][0]
|
||||
bugs = []
|
||||
if data['bugs'][0]:
|
||||
bugs = data['bugs'][0].split(';')
|
||||
comment = result['note']
|
||||
|
||||
by_user.setdefault(username, {})
|
||||
by_user[username].setdefault(col_1, {})
|
||||
by_user[username][col_1].setdefault(tcurl, [])
|
||||
|
||||
by_user[username][col_1][tcurl].append(
|
||||
dict(
|
||||
result = outcome,
|
||||
bugs = bugs,
|
||||
comment = comment
|
||||
)
|
||||
)
|
||||
|
||||
# At this point, by_user contains something like this:
|
||||
# {'usr1': {'moofoo': {'http://test2': [{'bugs': [],
|
||||
# 'comment': '',
|
||||
# 'result': 'INFO',
|
||||
# }]}},
|
||||
# 'usr2': {(foobar': {'http://test1': [{'bugs': [],
|
||||
# 'comment': None,
|
||||
# 'result': 'FAILED',
|
||||
# }],
|
||||
# 'http://test2': [{'bugs': ['12345',
|
||||
# '6431'],
|
||||
# 'comment': 'Does not work!',
|
||||
# 'result': 'PASSED',
|
||||
# }]}}}
|
||||
|
||||
# We'll prepare the data even further - the event's
|
||||
# testcases are split into categories. We'll prepare the by-category
|
||||
# matrix, se the template to show the results can stay fairly simple
|
||||
# The result of the transformation is:
|
||||
# {1: [{
|
||||
# 'username': u'jskladan',
|
||||
# 'profile': u'Ubuntu 4.1',
|
||||
# 'results': [[(u'FAILED', 1), (u'PASSED', 2)], []],
|
||||
# 'comments': [([u'123', u'456'], u'Comment number 2'),
|
||||
# ([], u'Comment number 1')],
|
||||
# },
|
||||
# {
|
||||
# 'username': u'jskladan',
|
||||
# 'profile': u'Fedora 19',
|
||||
# 'results': [[(u'INFO', False), (u'PASSED', 1)], [(u'cats!', 2)]],
|
||||
# 'comments': [([], u'Comment number 3'), ([], u'Comment number 4')],
|
||||
# }],
|
||||
# 2: []}
|
||||
#
|
||||
# $results represents the results per testcase - each sublist of the top list
|
||||
# 'maps' (positionaly) to the Testcase in the respective Category. It can
|
||||
# contain multiple tuples, each representing one result (one user with one
|
||||
# profile can submit multiple results per Testcase). The first item in the
|
||||
# tuple is the actual result. The second item is either False or Int.
|
||||
# False means that the result has no bugs/comment associated with it.
|
||||
# Int is the index+1 of the comment in the $comments field. This way
|
||||
# it is very simple to create link-references from result to comment/bugs
|
||||
#
|
||||
# $comments is a list of tuples, each tuple represents bugs/comment for the
|
||||
# respective result (see above).
|
||||
# First item in the tuple is a list of BUG numbers
|
||||
# Second item is the comment itself.
|
||||
|
||||
matrix = {}
|
||||
# We want to have the users sorted alphabetically in the table
|
||||
users = sorted(by_user.keys())
|
||||
|
||||
# Create per-category pre-parsed lines of results
|
||||
for category in event.categories:
|
||||
matrix[category.id] = []
|
||||
relevant_testcases = set([tc.url for tc in category.testcases])
|
||||
|
||||
# Create a line-of-results per each user's profile
|
||||
for user in users:
|
||||
# Also, sort by the profile-info alphabetically
|
||||
user_profiles = sorted(by_user[user].keys())
|
||||
for profile in user_profiles:
|
||||
data = by_user[user][profile]
|
||||
# Check whether this user-profile set any results
|
||||
# for testcases from this category
|
||||
if not relevant_testcases.intersection(data.keys()):
|
||||
continue
|
||||
|
||||
# Prepare the per-line data
|
||||
# see the explanation of the structure above
|
||||
line = dict(
|
||||
username=user,
|
||||
profile=profile,
|
||||
results=[],
|
||||
comments=[])
|
||||
|
||||
comment_id = 0
|
||||
for testcase in category.testcases:
|
||||
# Append new results-container for the respective
|
||||
# testcase.
|
||||
results_by_tc = []
|
||||
line['results'].append(results_by_tc)
|
||||
|
||||
# If the user-profile did not fill any result for this
|
||||
# specific testcase, go to the next one.
|
||||
# The "no results filled" state is represented by the empty
|
||||
# list.
|
||||
if testcase.url not in data:
|
||||
continue
|
||||
|
||||
# Go through all the details of the results for this
|
||||
# user-profile-testcase combination
|
||||
for detail in data[testcase.url]:
|
||||
has_comment = bool(detail['bugs'] or detail['comment'])
|
||||
# If there are bugs and/or comments for the result,
|
||||
# add them to the line container
|
||||
if has_comment:
|
||||
comment_id += 1
|
||||
line['comments'].append((detail['bugs'], detail['comment']))
|
||||
has_comment = comment_id
|
||||
results_by_tc.append((detail['result'], has_comment))
|
||||
matrix[category.id].append(line)
|
||||
|
||||
CACHE.set("event_%s_matrix" % event.id, matrix, CACHE_TIMEOUT)
|
||||
return matrix
|
||||
|
||||
|
||||
@main.route('/events/<int:event_id>')
|
||||
def show_event(event_id):
|
||||
try:
|
||||
event = db.session.query(Event).filter(Event.id == event_id).one()
|
||||
except NoResultFound:
|
||||
return render_template('404.html'), 404
|
||||
results = preparse_results(event)
|
||||
|
||||
prof = json.loads(session.get('profile', '{}'))
|
||||
username = prof.get('username')
|
||||
col_1 = prof.get('col_1')
|
||||
filled = prof.get('filled', {}).get(username, {}).get(col_1, [])
|
||||
profile = dict(username=username, col_1=col_1, filled=filled)
|
||||
|
||||
return render_template('show_event.html', event=event, results=results,
|
||||
profile=profile)
|
||||
|
||||
def testcase_to_name(testcase):
|
||||
prefix = "apps.testdays."
|
||||
name = testcase.url.strip().rstrip("/").split('/')[-1]
|
||||
if 'fedoraproject.org/wiki/' in testcase.url:
|
||||
name = testcase.url.split('fedoraproject.org/wiki/', 1)[-1]
|
||||
name = RE_TESTCASE_NAME_NORMALIZE.sub('_', name)
|
||||
return "%s%s" % (prefix, name)
|
||||
|
||||
def ensure_testcase(testcase):
|
||||
global TESTCASES
|
||||
|
||||
name = testcase_to_name(testcase)
|
||||
if name not in TESTCASES:
|
||||
try:
|
||||
RDB_API.get_testcase(name)
|
||||
except resultsdb_api.ResultsDBapiException:
|
||||
try:
|
||||
RDB_API.create_testcase(name, testcase.url)
|
||||
except resultsdb_api.ResultsDBapiException:
|
||||
raise
|
||||
TESTCASES.append(name)
|
||||
return name
|
||||
prsd = urlparse(l)
|
||||
except:
|
||||
raise ValidationError(f"Line #{ln}: Invalid URL")
|
||||
|
||||
if prsd.scheme not in ("http", "https"):
|
||||
raise ValidationError(f"Line #{ln}: Only http/https is allowed")
|
||||
|
||||
def update_profile_cookies(username, col_1, profile=None):
|
||||
if not profile:
|
||||
profile = json.loads(session.get('profile', '{}'))
|
||||
profile['username'] = username
|
||||
profile['col_1'] = col_1
|
||||
filled = profile.setdefault('filled', {})
|
||||
filled.setdefault(username, {})
|
||||
filled[username].setdefault(col_1, [])
|
||||
|
||||
session['profile'] = json.dumps(profile)
|
||||
return profile
|
||||
|
||||
def update_filled_cookies(username, col_1, testcase_name, profile=None):
|
||||
profile = update_profile_cookies(username, col_1, profile)
|
||||
profile['filled'][username][col_1].append(testcase_name)
|
||||
|
||||
session['profile'] = json.dumps(profile)
|
||||
return profile
|
||||
|
||||
|
||||
@main.route('/events/<int:event_id>/enter_result/<int:tc_id>', methods=['GET', 'POST'])
|
||||
def enter_result(event_id, tc_id):
|
||||
testcase = db.session.query(Testcase).filter(Testcase.id == tc_id).one()
|
||||
form_ = EnterResultForm(testcase)
|
||||
|
||||
session_profile = json.loads(session.get('profile', '{}'))
|
||||
|
||||
if form_.validate_on_submit():
|
||||
outcome = form_.result.data
|
||||
if testcase.type == 'txt':
|
||||
outcome = 'PASSED'
|
||||
|
||||
testcase_name = ensure_testcase(testcase)
|
||||
|
||||
result_dict = dict(
|
||||
outcome=outcome,
|
||||
testcase=testcase_name,
|
||||
groups=[testcase.category.event.resultsdb_job_uuid],
|
||||
note=form_.comment.data,
|
||||
result=form_.result.data,
|
||||
col_1=form_.col_1.data,
|
||||
username=form_.username.data,
|
||||
bugs=form_.bugs.data,
|
||||
)
|
||||
try:
|
||||
r = RDB_API.create_result(**result_dict)
|
||||
flash("Result Saved")
|
||||
update_filled_cookies(form_.username.data, form_.col_1.data, testcase.name, session_profile)
|
||||
return redirect(url_for('.show_event', event_id=event_id))
|
||||
except resultsdb_api.ResultsDBapiException as e:
|
||||
update_profile_cookies(form_.username.data, form_.col_1.data, session_profile)
|
||||
flash("There was an error when saving the result (%s)" % e.message, 'error')
|
||||
tld = ".".join(prsd.netloc.rsplit(":", 1)[0].rsplit(".", 2)[-2:]).lower()
|
||||
tld = tld.rsplit("@", 1)[-1]
|
||||
except:
|
||||
raise ValidationError(f"Line #{ln}: Could not parse TLD from the URL")
|
||||
|
||||
if not form_.errors:
|
||||
if not form_.username.data:
|
||||
form_.username.data = session_profile.get('username', '')
|
||||
if not form_.col_1.data:
|
||||
form_.col_1.data = session_profile.get('col_1', '')
|
||||
if "@" in prsd.netloc:
|
||||
raise ValidationError(f"Line #{ln}: Do not share URLs with user/login data")
|
||||
|
||||
return render_template('enter_result.html',
|
||||
form = form_,
|
||||
form_action = url_for('.enter_result', event_id=event_id, tc_id=tc_id),
|
||||
header = "Enter result",
|
||||
# FIXME: make configurable...
|
||||
allowed_tlds = (
|
||||
"redhat.com",
|
||||
"pagure.io",
|
||||
"github.com",
|
||||
"gitlab.com",
|
||||
"forgejo.org",
|
||||
"gitea.com",
|
||||
)
|
||||
if tld not in allowed_tlds:
|
||||
raise ValidationError(
|
||||
f"Line #{ln}: Invalid TLD, must be one of {allowed_tlds}"
|
||||
)
|
||||
|
||||
links.append(l)
|
||||
|
||||
field.data = "\n".join(links)
|
||||
|
||||
|
||||
class ResultForm(FlaskForm):
|
||||
profile = StringField("Profile", validators=[validators.InputRequired()])
|
||||
result = SelectField(
|
||||
"Result",
|
||||
choices=[
|
||||
("", "-- Select Result --"),
|
||||
("PASS", "PASS"),
|
||||
("FAIL", "FAIL"),
|
||||
("INFO", "INFO"),
|
||||
],
|
||||
validators=[validators.InputRequired()],
|
||||
)
|
||||
bugs = TextAreaField("Bug URLs", default="", validators=[validate_bugs_field])
|
||||
comment = StringField("Comment", default="")
|
||||
submit = SubmitField("Submit")
|
||||
|
||||
|
||||
@main.route(
|
||||
"/testday/<int:testday_id>/submit_result/<testcase_ulid>", methods=["GET", "POST"]
|
||||
)
|
||||
@login_required
|
||||
def submit_result(testday_id, testcase_ulid):
|
||||
profile_cookie = request.cookies.get("profile", "")
|
||||
|
||||
@after_this_request
|
||||
def set_cookie(response):
|
||||
if profile_cookie:
|
||||
response.set_cookie("profile", profile_cookie)
|
||||
return response
|
||||
|
||||
tc = Testcase.query.filter(
|
||||
db.and_(Testcase.ulid == testcase_ulid, Testcase.testday_id == testday_id)
|
||||
).first()
|
||||
if not tc:
|
||||
return Response("Not Found", 404, mimetype="text/plain")
|
||||
|
||||
form = ResultForm()
|
||||
if form.validate_on_submit():
|
||||
profile = form.profile.data.strip()
|
||||
result = form.result.data.strip()
|
||||
bugs = form.bugs.data.strip()
|
||||
comment = html.escape(form.comment.data.strip())
|
||||
|
||||
r = Result(
|
||||
testday_id, testcase_ulid, current_user, profile, result, bugs, comment
|
||||
)
|
||||
db.session.add(r)
|
||||
db.session.commit()
|
||||
|
||||
profile_cookie = profile
|
||||
return redirect(f"/testday/{testday_id}")
|
||||
|
||||
form.profile.data = profile_cookie
|
||||
return catalog.render("SubmitResult", form=form, testday_id=testday_id)
|
||||
|
||||
|
||||
@main.route(
|
||||
"/testday/<int:testday_id>/edit_result/<testcase_ulid>/<result_id>",
|
||||
methods=["GET", "POST"],
|
||||
)
|
||||
@login_required
|
||||
def edit_result(testday_id, testcase_ulid, result_id):
|
||||
result = Result.query.filter(
|
||||
db.and_(
|
||||
Result.id == result_id,
|
||||
Result.testcase_ulid == testcase_ulid,
|
||||
Result.testday_id == testday_id,
|
||||
)
|
||||
).first()
|
||||
if not result:
|
||||
return Response("Not Found", 404, mimetype="text/plain")
|
||||
if result.user != current_user:
|
||||
return Response("Not Allowed", 405, mimetype="text/plain")
|
||||
|
||||
form = ResultForm()
|
||||
if form.validate_on_submit():
|
||||
result.profile = form.profile.data.strip()
|
||||
result.result = form.result.data.strip()
|
||||
result.bugs = form.bugs.data.strip()
|
||||
result.comment = html.escape(form.comment.data.strip())
|
||||
|
||||
db.session.add(result)
|
||||
db.session.commit()
|
||||
return redirect(f"/testday/{testday_id}")
|
||||
|
||||
if request.method == "GET":
|
||||
form.profile.data = result.profile
|
||||
form.result.data = result.result
|
||||
form.bugs.data = result.bugs or ""
|
||||
form.comment.data = html.unescape(result.comment or "")
|
||||
|
||||
return catalog.render("SubmitResult", form=form, testday_id=testday_id)
|
||||
|
||||
|
||||
@main.route("/http403", methods=["GET", "POST"])
|
||||
def http403():
|
||||
return Response("How about no?", 403, mimetype="text/plain")
|
||||
|
||||
|
||||
@main.route("/edit_profile/<int:user_id>", methods=["GET", "POST"])
|
||||
@login_required
|
||||
def edit_profile(user_id):
|
||||
if user_id != current_user.id:
|
||||
return Response("How about no?", 403, mimetype="text/plain")
|
||||
|
||||
form = DisplayNameForm()
|
||||
if form.validate_on_submit():
|
||||
current_user.displayname = form.displayname.data
|
||||
db.session.add(current_user)
|
||||
db.session.commit()
|
||||
return redirect(f"/")
|
||||
|
||||
if request.method == "GET":
|
||||
form.displayname.data = html.unescape(current_user.displayname)
|
||||
|
||||
return catalog.render("EditProfile", form=form)
|
||||
|
||||
|
||||
@main.route("/testday/<int:testday_id>")
|
||||
def show_testday(testday_id):
|
||||
testday = Testday.query.filter(Testday.id == testday_id).first()
|
||||
if not testday:
|
||||
return Response("Not found", 404, mimetype="text/plain")
|
||||
|
||||
# I think it might make sense to allow viewing-drafts to non-admins
|
||||
# Let's be ok with just not listing them on the main page for now
|
||||
#if testday.is_draft and not current_user.has_role("admin"):
|
||||
# return Response("Not allowed", 404, mimetype="text/plain")
|
||||
|
||||
UserProfile = namedtuple("UserProfile", ["id", "profile"])
|
||||
|
||||
users = dict()
|
||||
results_by_section = [
|
||||
[dict() for _ in testday.structure["Sections"]],
|
||||
[dict() for _ in testday.structure["Sections"]],
|
||||
]
|
||||
|
||||
for i, section in enumerate(testday.structure["Sections"]):
|
||||
# INFO: Alternative way of doing this would be:
|
||||
# testcase_order = [testcase["Ulid"] for testcase in section["Testcases"]]
|
||||
#
|
||||
# and then getting the idx as
|
||||
# try:
|
||||
# idx = testcase_order.index(result.testcase_ulid)
|
||||
# except ValueError:
|
||||
# continue
|
||||
#
|
||||
# I just felt like dict...
|
||||
testcase_order = dict()
|
||||
for j, testcase in enumerate(section["Testcases"]):
|
||||
testcase_order[testcase["Ulid"]] = j
|
||||
|
||||
result_lines_current = dict()
|
||||
result_lines_others = dict()
|
||||
for result in testday.results:
|
||||
try:
|
||||
idx = testcase_order[result.testcase_ulid]
|
||||
except KeyError:
|
||||
continue
|
||||
|
||||
if result.user.id == current_user.id:
|
||||
result_lines = result_lines_current
|
||||
else:
|
||||
result_lines = result_lines_others
|
||||
userprofile = UserProfile(result.user.id, result.profile)
|
||||
users[result.user.id] = result.user
|
||||
if result_lines.get(userprofile) is None:
|
||||
result_lines[userprofile] = [
|
||||
list() for _ in testday.structure["Sections"][i]["Testcases"]
|
||||
]
|
||||
result_lines[userprofile][idx].append(result)
|
||||
results_by_section[0][i] = dict(
|
||||
sorted(result_lines_current.items(), key=lambda x: x[0][1].lower())
|
||||
)
|
||||
results_by_section[1][i] = dict(
|
||||
sorted(
|
||||
result_lines_others.items(),
|
||||
key=lambda x: (
|
||||
users[x[0].id].displayname.lower(),
|
||||
x[0].id,
|
||||
x[0][1].lower(),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
return catalog.render(
|
||||
"Testday", testday=testday, results=results_by_section, users=users
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,2 @@
|
|||
from .user import *
|
||||
from .testday import *
|
||||
|
|
@ -18,67 +18,117 @@
|
|||
# Josef Skladanka <jskladan@redhat.com>
|
||||
|
||||
import datetime
|
||||
import json
|
||||
|
||||
from ulid import ULID
|
||||
|
||||
from testdays import db
|
||||
from flask_login import current_user
|
||||
from copy import deepcopy
|
||||
|
||||
TESTCASE_TYPES = ('tc', 'txt')
|
||||
|
||||
class Event(db.Model):
|
||||
class Testday(db.Model):
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
name = db.Column(db.Text)
|
||||
metadata_url = db.Column(db.Text)
|
||||
testday_url = db.Column(db.Text)
|
||||
testday_start = db.Column(db.DateTime)
|
||||
testday_end = db.Column(db.DateTime)
|
||||
resultsdb_job_id = db.Column(db.Integer)
|
||||
resultsdb_job_uuid = db.Column(db.String(36))
|
||||
created_at = db.Column(db.DateTime, default = datetime.datetime.utcnow)
|
||||
start = db.Column(db.DateTime)
|
||||
end = db.Column(db.DateTime)
|
||||
is_draft = db.Column(db.Boolean, default=True)
|
||||
# created_at = db.Column(db.DateTime, default = datetime.datetime.utcnow)
|
||||
_history_col = db.Column("history", db.Text, default="[]")
|
||||
_history = None
|
||||
results = db.relation("Result", backref="testday") # , order_by='Result.id')
|
||||
|
||||
categories = db.relation('Category', backref='event', order_by='Category.id')
|
||||
@property
|
||||
def structure(self):
|
||||
if self._history_col is None:
|
||||
self._history_col = "[]"
|
||||
if self._history is None:
|
||||
try:
|
||||
self._history = json.loads(self._history_col)
|
||||
except (json.decoder.JSONDecodeError, TypeError, ValueError):
|
||||
self._history = []
|
||||
if not self._history:
|
||||
return {"Sections": [], "Timestamp": "", "Author": ""}
|
||||
return self._history[-1]
|
||||
|
||||
def __init__(self, name, metadata_url, testday_url=None, testday_start=None, testday_end=None, resultsdb_job_uuid=None):
|
||||
@structure.setter
|
||||
def structure(self, value):
|
||||
value["Timestamp"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
value["Author"] = {"id": current_user.id, "username": current_user.username}
|
||||
|
||||
if self._history_col is None:
|
||||
self._history_col = "[]"
|
||||
if self._history is None:
|
||||
try:
|
||||
self._history = json.loads(self._history_col)
|
||||
except (json.decoder.JSONDecodeError, TypeError, ValueError):
|
||||
self._history = []
|
||||
|
||||
if self.structure["Sections"] != value["Sections"]:
|
||||
self._history.append(value)
|
||||
self._history_col = json.dumps(self._history)
|
||||
|
||||
def __init__(self, name, structure=None, testday_url=None, start=None, end=None):
|
||||
self.name = name
|
||||
self.metadata_url = metadata_url
|
||||
self.testday_url = testday_url
|
||||
self.testday_start = testday_start
|
||||
self.testday_end = testday_end
|
||||
self.resultsdb_job_uuid = resultsdb_job_uuid
|
||||
self.start = start
|
||||
self.end = end
|
||||
if structure is not None:
|
||||
self.structure = structure
|
||||
|
||||
class Category(db.Model):
|
||||
|
||||
__table_args__ = (
|
||||
db.Index('category_fk_event_id', 'event_id'),
|
||||
)
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
event_id = db.Column(db.Integer, db.ForeignKey('event.id'))
|
||||
name = db.Column(db.Text)
|
||||
col_1_name = db.Column(db.Text)
|
||||
|
||||
testcases = db.relation('Testcase', backref='category', order_by='Testcase.id')
|
||||
|
||||
def __init__(self, name, event=None):
|
||||
self.name = name
|
||||
if event is not None:
|
||||
self.event = event
|
||||
|
||||
class Testcase(db.Model):
|
||||
|
||||
__table_args__ = (
|
||||
db.Index('testcase_fk_category_id', 'category_id'),
|
||||
)
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
|
||||
name = db.Column(db.Text)
|
||||
ulid = db.Column(db.String(26), primary_key=True)
|
||||
url = db.Column(db.Text)
|
||||
type = db.Column(db.Enum(*TESTCASE_TYPES, name='testcase_type'))
|
||||
testday_id = db.Column(db.Integer, db.ForeignKey("testday.id"))
|
||||
|
||||
def __init__(self, name, url, type, category=None):
|
||||
self.name = name
|
||||
self.type = type
|
||||
results = db.relation("Result", backref="testcase") # , order_by='Result.id')
|
||||
testday = db.relation("Testday", backref="testcases") # , order_by='Result.id')
|
||||
|
||||
def __init__(self, url, testday, ulid=None):
|
||||
self.url = url
|
||||
if category is not None:
|
||||
self.category = category
|
||||
self.testday = testday
|
||||
self.ulid = str(ULID())
|
||||
if ulid is not None:
|
||||
self.ulid = ulid
|
||||
|
||||
|
||||
class Result(db.Model):
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
testday_id = db.Column(db.Integer, db.ForeignKey("testday.id"))
|
||||
testcase_ulid = db.Column(db.String(26), db.ForeignKey("testcase.ulid"))
|
||||
user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
|
||||
# FIXME: set max lenght for these...
|
||||
profile = db.Column(db.Text)
|
||||
result = db.Column(db.Text)
|
||||
bugs = db.Column(db.Text)
|
||||
comment = db.Column(db.Text)
|
||||
removed = db.Column(db.Boolean, default=False)
|
||||
|
||||
user = db.relation("User", backref="results") # , order_by='Result.id')
|
||||
|
||||
def __init__(self, testday_id, testcase_ulid, user, profile, result, bugs="", comment=""):
|
||||
self.testday_id = testday_id
|
||||
self.testcase_ulid = testcase_ulid
|
||||
self.user = user
|
||||
self.profile = profile
|
||||
self.result = result
|
||||
if bugs:
|
||||
self.bugs = bugs
|
||||
if comment:
|
||||
self.comment = comment
|
||||
|
||||
__table_args__ = (
|
||||
db.Index("result_fk_testday_id", "testday_id"),
|
||||
db.Index("result_fk_testcase_ulid", "testcase_ulid"),
|
||||
db.Index("result_fk_user_id", "user_id"),
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return(self.__repr__())
|
||||
|
||||
def __repr__(self):
|
||||
return f"[{self.id}] {self.testcase_ulid} - {self.user_id}/{self.profile} - {self.result}"
|
||||
|
|
|
|||
|
|
@ -1,42 +1,83 @@
|
|||
# Copyright 2014, Red Hat, Inc
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
#
|
||||
# Authors:
|
||||
# Josef Skladanka <jskladan@redhat.com>
|
||||
import enum
|
||||
|
||||
from testdays import db
|
||||
from flask_login import UserMixin
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
from flask_login import AnonymousUserMixin, UserMixin
|
||||
from werkzeug.security import check_password_hash, generate_password_hash
|
||||
|
||||
class User(db.Model, UserMixin):
|
||||
from .. import catalog, db, login_manager
|
||||
from wtforms import ValidationError
|
||||
import html
|
||||
|
||||
|
||||
@login_manager.user_loader
|
||||
def load_user(id):
|
||||
user = User.query.get(int(id))
|
||||
if not user or user.disabled:
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
__all__ = ["User", "UserRoles"]
|
||||
|
||||
|
||||
class UserRoles(enum.Enum):
|
||||
none = "None"
|
||||
user = "User"
|
||||
admin = "Admin"
|
||||
|
||||
@classmethod
|
||||
def choices(cls):
|
||||
return [(r.name, r.value) for r in cls]
|
||||
|
||||
@classmethod
|
||||
def get_by_name(cls, name):
|
||||
try:
|
||||
return UserRoles.__getitem__(name)
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
# FIXME - maybe not required, but usefull?
|
||||
catalog.jinja_env.globals.update({"UserRoles": UserRoles})
|
||||
|
||||
class User(UserMixin, db.Model):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
username = db.Column(db.String(80), unique=True)
|
||||
pw_hash = db.Column(db.String(120), unique=False)
|
||||
username = db.Column(db.String(265), nullable=False, unique=True)
|
||||
displayname = db.Column(db.String(80), nullable=False, unique=False)
|
||||
role = db.Column(db.Enum(UserRoles), default=UserRoles.none)
|
||||
disabled = db.Column(db.Boolean, default=False)
|
||||
|
||||
def __init__(self, username, password):
|
||||
def __init__(self, username, displayname=None, role=None):
|
||||
self.username = username
|
||||
self.set_password(password)
|
||||
if displayname is None:
|
||||
displayname = username
|
||||
self.displayname = displayname
|
||||
if not role:
|
||||
role = UserRoles.none
|
||||
self.role = role
|
||||
|
||||
def has_role(self, role_name):
|
||||
return self.role == UserRoles.get_by_name(role_name)
|
||||
|
||||
def __repr__(self):
|
||||
return '<User %r>' % self.username
|
||||
return f"<User {self.username}, disabled:{self.disabled}, role: {self.role}>"
|
||||
|
||||
def set_password(self, password):
|
||||
self.pw_hash = generate_password_hash(password)
|
||||
class __Anon(AnonymousUserMixin):
|
||||
id = None
|
||||
username = "None"
|
||||
displayname = "None"
|
||||
role = "None"
|
||||
disabled = False
|
||||
|
||||
def check_password(self, password):
|
||||
return check_password_hash(self.pw_hash, password)
|
||||
def has_role(self, *_):
|
||||
return False
|
||||
|
||||
login_manager.anonymous_user = __Anon
|
||||
|
||||
|
||||
|
||||
def user_displayname_validator(form, field):
|
||||
if len(field.data.strip()) == 0:
|
||||
raise ValidationError('Must contain some non-whitespace characters')
|
||||
|
||||
field.data = html.escape(field.data.strip())
|
||||
|
|
|
|||
|
|
@ -1,55 +0,0 @@
|
|||
<!-- inspired by https://gist.github.com/maximebf/3986659 -->
|
||||
{% macro form_field(field) -%}
|
||||
{% set with_label = kwargs.pop('with_label', False) -%}
|
||||
{% set inline_ = '' -%}
|
||||
|
||||
{% if field.type == 'BooleanField' %}
|
||||
<div class="checkbox">
|
||||
<label>
|
||||
{{ field(**kwargs) }}
|
||||
{{ field.label.text|safe }}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{% elif field.type == 'RadioField' %}
|
||||
{% for subfield in field %}
|
||||
<div class="radio">
|
||||
<label>
|
||||
{{ subfield(**kwargs) }}
|
||||
{{ subfield.label.text|safe }}
|
||||
</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
{% else -%}
|
||||
<div class="form-group {% if field.errors %}has-error{% endif %}">
|
||||
{% set placeholder = '' -%}
|
||||
{% if not with_label -%}
|
||||
{% set placeholder = field.label.text -%}
|
||||
{% endif -%}
|
||||
|
||||
{% set class_ = 'form-control' -%}
|
||||
{% if field.type == 'FileField' -%}
|
||||
{% set class_ = class_ + ' input-file' %}
|
||||
{% endif -%}
|
||||
|
||||
|
||||
{% if with_label -%}
|
||||
<label for="{{ field.id }}">
|
||||
{{ field.label.text }}{% if field.flags.required %} *{% endif %}:
|
||||
</label>
|
||||
{% endif -%}
|
||||
|
||||
{{ field(class_=class_, placeholder=placeholder, **kwargs) }}
|
||||
|
||||
{% if field.errors -%}
|
||||
<span class="help-block">{{ field.errors|join(', ') }}</span>
|
||||
{% endif -%}
|
||||
|
||||
{% if field.description -%}
|
||||
<p class="help-block">{{ field.description|safe }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% endif -%}
|
||||
{% endmacro -%}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
{% extends "layout.html" %}
|
||||
|
||||
{% from "_formhelpers.html" import form_field %}
|
||||
|
||||
{% block body %}
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<form method="post" action="login">
|
||||
{{ form.csrf_token }}
|
||||
{{ form.next_page }}
|
||||
{{ form_field(form.username) }}
|
||||
{{ form_field(form.password) }}
|
||||
<input type="submit" class="btn btn-success" value="Login"/>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
4
testdays/utils/__init__.py
Normal file
4
testdays/utils/__init__.py
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import datetime
|
||||
|
||||
def utcnow():
|
||||
return datetime.datetime.now(datetime.timezone.utc)
|
||||
24
testdays/utils/authorization.py
Normal file
24
testdays/utils/authorization.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
from functools import wraps
|
||||
|
||||
from flask import abort
|
||||
from flask_login import current_user
|
||||
|
||||
from ..models import UserRoles
|
||||
|
||||
def role_required(role):
|
||||
"""Restrict a view to users with the given role."""
|
||||
|
||||
def decorator(f):
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if not current_user.role == role:
|
||||
abort(403)
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def admin_required(f):
|
||||
return role_required(UserRoles.admin)(f)
|
||||
Loading…
Add table
Add a link
Reference in a new issue