Skip to content
Snippets Groups Projects
Commit d668518a authored by tuhe's avatar tuhe
Browse files

updates

parent 67d23a27
Branches
No related tags found
No related merge requests found
LICENSE 0 → 100644
Copyright (c) 2018 The Python Packaging Authority
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
\ No newline at end of file
# coursebox_testing
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://lab.compute.dtu.dk/tuhe/coursebox_testing.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://lab.compute.dtu.dk/tuhe/coursebox_testing/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
# Coursebox DTU (testing tools)
DTU course management software (testing plugins)
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
```terminal
pip install git+https://gitlab.compute.dtu.dk/tuhe/coursebox_testing
```
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
## Citing
```bibtex
@online{coursebox,
title={Coursebox (0.1.1): \texttt{pip install coursebox}},
url={https://lab.compute.dtu.dk/tuhe/coursebox},
urldate = {2021-09-07},
month={9},
publisher={Technical University of Denmark (DTU)},
author={Tue Herlau},
year={2023},
}
```
# Coursebox DTU
DTU course management software.
## Installation
```terminal
pip install coursebox
```
## What it can do
- Single semester-dependent configuration file
- Integrates with DTU Inside/DTU Learn
- Distribution/evalauation of project reports in Learn-compatible format
- Quiz-generation in DTU Learn/Beamer friendly format
- Automatic website/syllabus generation
- Automatic generation of lectures handouts/exercises (you don't have to track dynamic content like dates/lecture titles; it is all in the configuration)
- Easy compilation to 2/5 day formats (Continuous education)
## Usage
Coursebox requires a specific directory structure. It is easier to start with an existing course and adapt to your needs. Please contact me at tuhe@dtu.dk for more information.
## Citing
```bibtex
{{bibtex}}
```
\ No newline at end of file
import jinja2
if __name__ == "__main__":
from jinjafy.bibliography_maker import make_bibliography
bib = make_bibliography("../setup.py", "./")
data = {'bibtex': bib}
with open("README.jinja.md", 'r') as f:
s = jinja2.Environment().from_string(f.read()).render(data)
with open("../README.md", 'w') as f:
f.write(s)
@online{coursebox,
title={Coursebox (0.1.1): \texttt{pip install coursebox}},
url={https://lab.compute.dtu.dk/tuhe/coursebox},
urldate = {2021-09-07},
month={9},
publisher={Technical University of Denmark (DTU)},
author={Tue Herlau},
year={2021},
}
\ No newline at end of file
[build-system]
requires = [
"setuptools>=42",
"wheel"
]
build-backend = "setuptools.build_meta"
\ No newline at end of file
setup.py 0 → 100644
# Use this guide:
# https://packaging.python.org/tutorials/packaging-projects/
# Use pipreqs.exe to get requirements list.
"""
Windows> py -m build && twine upload dist/*
Linux> python -m build && twine upload dist/*
"""
import setuptools
import pkg_resources
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
# beamer-slider
setuptools.setup(
name="coursebox_testing",
version="0.0.1",
author="Tue Herlau",
author_email="tuhe@dtu.dk",
description="A course management system currently used at DTU (testing software)",
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT",
url='https://lab.compute.dtu.dk/tuhe/coursebox_testing',
project_urls={
"Bug Tracker": "https://lab.compute.dtu.dk/tuhe/coursebox_testing/issues",
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
package_dir={"": "src"},
packages=setuptools.find_packages(where="src"),
python_requires=">=3.8",
install_requires=['unitgrade'],
)
##
import subprocess
import time
from collections import defaultdict
import glob
import tabulate
import sys
import warnings
def check_by_grade_script(student_dir, module):
"""
TH 2023: Must be runable on a minimal system, i.e. no unitgrade_private etc.
:param student_dir:
:param module:
:return:
"""
import sys
# from unitgrade.utils import
# from unitgrade_private.run import run # Don't use tihs as it is not available during test.
cmd = f"cd {student_dir} && {sys.executable} -m {module}"
# output = subprocess.check_output(f"cd {student_dir} && {sys.executable} -m {module}", shell=True, check=False)
from subprocess import run
print("Running command", cmd)
p = run(cmd, capture_output=True, check=False, shell=True)
print('exit status:', p.returncode)
out = p.stdout.decode()
stderr = p.stderr.decode()
# process = run(cmd, print_output=False, check=False)
# stderr = process.stderr.getvalue().strip()
if p.returncode != 0 and not (stderr == "Killed" or stderr == ""):
# print(.stdout.getvalue())
print(out)
print("-"*50)
print(stderr)
print("-"*50)
raise Exception("Run command gave error: " + cmd)
# out = process.stdout.getvalue()
# s = out[out.rfind("handin"):out.rfind(".token")]
# try:
# p = int(s.split("_")[1])
# total = int(s.split("_")[-1])
# except Exception as e:
# print("Encountered problem in", module)
# print(out)
# print(stderr)
# print(s)
# print(cmd)
# raise e
# out = out.decode("utf-8")
# print(out)
s = out[out.rfind("handin"):out.rfind(".token")]
# try:
# p = int(s.split("_")[1])
# total = int(s.split("_")[-1])
a, _, b = s.split("_")[-3:]
points = int(a), int(b)
# total = [l for l in out.splitlines() if l.strip().startswith("Total")].pop()
# total.split(" ")[1].split("/")
# points = total.split(" ")[-1]
# a, b = points.split("/")
# points = int(a), int(b)
# points =
return points, out
def check_py_script(student_dir, module):
cmd = f"cd {student_dir} && {sys.executable} -m {module} --unmute" # Don't hardcode 'python' bc. of 'python3' on mac/Linux.
try:
output = subprocess.check_output(cmd, shell=True)
except Exception as e:
print("command that failed was")
print(cmd)
# print("The std. out from the command was")
# print(output.decode("utf-8"))
raise e
out = output.decode("utf-8")
total = [l for l in out.splitlines() if l.strip().startswith("Total")].pop()
total.split(" ")[1].split("/")
points = total.split(" ")[-1]
a, b = points.split("/")
points = int(a), int(b)
return points, out
# def check_by_grade_script(student_dir, module):
# output = subprocess.check_output(f"cd {student_dir} && {sys.executable} -m {module}", shell=True)
# out = output.decode("utf-8")
# s = out[out.rfind("handin"):out.rfind(".token")]
# try:
# p = int(s.split("_")[1])
# total = int(s.split("_")[-1])
# except Exception as e:
# print("Encountered problem in", module)
# print(out)
# print(s)
# raise e
# return p, total, out
def check_pyhon_documentation_in_student_repo(student_dir_complete=None, package="cp"):
from interrogate import coverage
if student_dir_complete is None:
# It is important to not import cp_box here during CI/CD. The coursebox packages is not/should not be installed.
from cp_box import cp_main
from coursebox.core.info_paths import get_paths
paths = get_paths()
student_dir_complete = paths['02450students'] + "_complete"
# At this point, also set up the studnets_complete repo.
from cp_box.material.build_documentation import deploy_students_complete
deploy_students_complete()
from pydocstyle.checker import check
n = 0
files_ = glob.glob(f"{student_dir_complete}/{package}/ex*/*.py", recursive=True) + glob.glob(f"{student_dir_complete}/{package}/project*/*.py", recursive=True)
files_ = [f for f in files_ if not f.endswith("_grade.py")]
files = []
for f in files_:
with open(f, "r") as ff:
s = ff.read().splitlines()
if len([l for l in s if l.startswith("class ") and "(Report):" in l]) > 0:
print("Skipping report", f)
continue
files.append(f)
def _darglint_check(filename):
import darglint
from darglint import analysis
from darglint.config import get_config
from darglint.config import DocstringStyle
config = get_config()
# config = get_config()
from darglint.driver import parser, get_error_report
args = parser.parse_args()
config.style = DocstringStyle.SPHINX
# pass
raise_errors_for_syntax = args.raise_syntax or False
# for filename in files:
# filename = student_dir_base + "/cp/project0/fruit_homework.py"
error_report = get_error_report(
filename,
args.verbosity,
raise_errors_for_syntax,
message_template=args.message_template,
)
# print(error_report)
return error_report.splitlines()
def _pydocstyle_check(filename):
all_errs = []
n = 0
o = check([filename])
errs = [k for k in o]
for err in errs:
# print(f"{f}> ", err)
all_errs.append(str(err))
n += len(errs)
# if n > 0:
# print("Total problems", n)
return all_errs
print("="*80)
print("Summary of documentation style errors")
print("=" * 80)
n = 0
for file in files:
errs1 = _darglint_check(file)
errs2 = _pydocstyle_check(file)
if len(errs2) + len(errs1) > 0:
print(f"{file}> errors were:")
print(" - \n".join(errs1))
print(" * \n".join(errs2))
n += len(errs1) + len(errs2)
print("Total errors", n)
return n
def _run_student_tests(student_dir_base=None, weeks=None, projects=None, fail_if_no_projects=True,
fail_if_no_weeks=True):
"""
TODO: Refactor this function to accept full module paths of tests as input, and move the cp.* specific stuff out. Possibly alternative is to automatically search for tests
using conventions. The function should ultimately be moved to coursebox.
"""
# still got that common module. Eventually this should be an argument (probably).
from cp_box.common import projects_all
from cp_box.common import weeks_all
if projects is None:
projects = projects_all
else:
projects = {k: v for k, v in projects_all.items() if k in projects}
if weeks is None:
weeks = weeks_all
else:
weeks = {k: v for k, v in weeks_all.items() if k in weeks}
# if projects is None:
# from coursebox.core.info_paths import core_conf
# projects = list(core_conf['projects_all'].keys())
# if weeks is None:
# weeks_all = core_conf['weeks_all']
# weeks = weeks_all
# else:
# pass
# weeks = {k: weeks_all[k] for k in weeks}
if student_dir_base is None:
""" Only import this sometimes to avoid messing up the paths """
from coursebox.core.info_paths import get_paths
paths = get_paths()
student_dir_base = paths['02450students']
bases = {k: projects[k]['module_public'] for k in
projects} # f"cp.project{k}.project{k}_tests" for k in projects if True}
bases_weekly = [weeks[k]['module_public'] for k in weeks] # f'cp.tests.tests_week{k:02d}' for k in weeks]
if fail_if_no_weeks and len(bases_weekly) == 0:
raise Exception("No weeks found. Bad configuration.")
if fail_if_no_projects and len(bases) == 0:
raise Exception("No projects found. Bad configuration.")
# bases_weekly, bases = get_test_imports(weeks, projects)
rs = {}
for censor_files in [False, True]:
# if not censor_files:
# continue
student_dir = student_dir_base if censor_files else student_dir_base + "_complete"
for project_id, base in bases.items():
# student_dir = paths['02450students']
# print(">>> Checking tests...", base, "censor?", censor_files)
t0 = time.time()
(p1, t1), output1 = check_py_script(student_dir, base)
time1 = time.time() - t0
# print(">>> Checking grade script...")
t0 = time.time()
if base.endswith("_tests"):
base_grade = base[:-len("_tests")] + "_grade"
else:
base_grade = base + "_grade"
(p2, t2), output2 = check_by_grade_script(student_dir, base_grade)
time2 = time.time() - t0
if not censor_files:
tokens = glob.glob(student_dir + "/" + "/".join(base.split(".")[:-1]) + "/*.token")
assert len(tokens) == 1
rs[(base, censor_files)] = {'p1': p1, 'p2': p2, 't1': t1, 't2': t2, 'time1': time1, 'time2': time2}
"""
These values reflect
p1: Obtained points by project.py-script
t1: total points by project.py-script
p2: obtained points by project_grade.py-script
t2: Total points by project_grade.py-script
"""
if p1 != p2:
print(output1)
print("Obtained (i.e., from current code) points differ:", p1, p2)
assert False
if t1 != t2:
print("Total (obtainable) points differ:", t1, t2)
assert False
assert (t1 > 0)
if censor_files:
if p1 != 0:
print("Ran tests with code missing. The student should get 0 points, but instead got: ", p1, "of",
t1)
print(rs[(base, censor_files)])
assert p1 == 0
assert p2 == 0
else:
if p1 != t1:
print(base, "Wrong number of obtained points by regular check script. Output from script is:")
print(p1, t1)
print(output1)
assert False
if p2 != t2:
print(base, "Wrong number of obtained points by grade script. Output from grade script is:")
print(p2, t2)
print(output2)
assert False
for base in bases_weekly:
# if not weekly_tests:
# continue
# print(">>> Checking tests...", base)
t0 = time.time()
(p1, t1), output = check_py_script(student_dir, base)
time1 = time.time() - t0
rs[(base, censor_files)] = {'p1': p1, 't1': t1, 'time1': time1}
assert t1 > 0
if censor_files:
if p1 != 0:
print(p1, t1, base, "censor_files =", censor_files)
print(output)
assert p1 == 0
else:
if p1 != t1:
# import warnings
print("=" * 50)
print("Check of student files when files are NOT censored.")
print("p1, t1 are", p1, t1)
print("Base is", base)
print("Failed check for p1 == p2")
print(output)
print(p1, t1, base, censor_files)
print("=" * 50)
assert p1 == t1
print("Main check completed")
dd = defaultdict(list)
for (k, mode), val in rs.items():
# print(k, mode, val)
dd['Test'].append(k)
dd['censored'].append(mode)
dd['Points obtained'].append(val['p1'])
dd['Points total'].append(val['t1'])
dd['Time taken'].append(int(val['time1']))
print(tabulate.tabulate(dd, headers='keys'))
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment