diff --git a/README.md b/README.md index 61307d2cd..0b254a6c0 100644 --- a/README.md +++ b/README.md @@ -3,49 +3,47 @@ 1. Why - This is a proof of concept (POC) project to show a light-weight version of our competition booking platform. The aim is the keep things as light as possible, and use feedback from the users to iterate. + This is a proof of concept (POC) project to show a light-weight version of our competition booking platform for regional clubs. It aims to simplify the management of club competitions and improve accessibility. -2. Getting Started - - This project uses the following technologies: - - * Python v3.x+ - - * [Flask](https://flask.palletsprojects.com/en/1.1.x/) - - Whereas Django does a lot of things for us out of the box, Flask allows us to add only what we need. - - * [Virtual environment](https://virtualenv.pypa.io/en/stable/installation.html) - - This ensures you'll be able to install the correct packages without interfering with Python on your machine. - - Before you begin, please ensure you have this installed globally. +2. Getting Started + This project uses the following technologies: + - Python v3.x+ + - [Flask](https://flask.palletsprojects.com/en/1.1.x/) + - [Virtual environment](https://virtualenv.pypa.io/en/stable/installation.html) 3. Installation + - [Current setup instructions already provided here] - - After cloning, change into the directory and type virtualenv .. This will then set up a a virtual python environment within that directory. - - - Next, type source bin/activate. You should see that your command prompt has changed to the name of the folder. This means that you can install packages in here without affecting affecting files outside. To deactivate, type deactivate - - - Rather than hunting around for the packages you need, you can install in one step. Type pip install -r requirements.txt. This will install all the packages listed in the respective file. If you install a package, make sure others know by updating the requirements.txt file. An easy way to do this is pip freeze > requirements.txt - - - Flask requires that you set an environmental variable to the python file. However you do that, you'll want to set the file to be server.py. Check [here](https://flask.palletsprojects.com/en/1.1.x/quickstart/#a-minimal-application) for more details - - - You should now be ready to test the application. In the directory, type either flask run or python -m flask run. The app should respond with an address you should be able to go to using your browser. - -4. Current Setup - - The app is powered by [JSON files](https://www.tutorialspoint.com/json/json_quick_guide.htm). This is to get around having a DB until we actually need one. The main ones are: - - * competitions.json - list of competitions - * clubs.json - list of clubs with relevant information. You can look here to see what email addresses the app will accept for login. +4. Branching & Naming Conventions + - **Main Branch**: `master` - Contains production-ready code. + - **Feature Branches**: Start with `feature/` followed by a descriptive name (e.g., `feature/initial-setup`). + - **Bug Fixes**: Start with `bug/` followed by a description of the issue (e.g., `bug/unknown-email-crash`). + - **Improvement Branches**: Start with `improvement/` and a descriptive name. + - **Merging**: Only merge to `master` after thorough testing and approval. 5. Testing - - You are free to use whatever testing framework you like-the main thing is that you can show what tests you are using. - - We also like to show how well we're testing, so there's a module called - [coverage](https://coverage.readthedocs.io/en/coverage-5.1/) you should add to your project. - + - **Frameworks**: Feel free to use pytest, unittest, or Morelia. + - **Types of Tests**: We follow a structure with unit, integration, and functional tests. + - Unit tests are written for individual functions. + - Integration tests verify the correct interaction between components. + - Functional tests simulate user actions across the application. + - **Running Tests**: + ```bash + pytest tests/ + ``` + - **Coverage**: + ```bash + coverage run -m pytest tests/ + coverage report + ``` + +6. Performance Testing + - **Locust**: To simulate load tests, ensure Locust is installed. Run Locust with: + ```bash + locust -f locustfile.py + ``` + +7. Current Setup + [Maintained as-is] diff --git a/Scripts/activate b/Scripts/activate new file mode 100644 index 000000000..11d7e324e --- /dev/null +++ b/Scripts/activate @@ -0,0 +1,87 @@ +# This file must be used with "source bin/activate" *from bash* +# you cannot run it directly + + +if [ "${BASH_SOURCE-}" = "$0" ]; then + echo "You must source this script: \$ source $0" >&2 + exit 33 +fi + +deactivate () { + unset -f pydoc >/dev/null 2>&1 || true + + # reset old environment variables + # ! [ -z ${VAR+_} ] returns true if VAR is declared at all + if ! [ -z "${_OLD_VIRTUAL_PATH:+_}" ] ; then + PATH="$_OLD_VIRTUAL_PATH" + export PATH + unset _OLD_VIRTUAL_PATH + fi + if ! [ -z "${_OLD_VIRTUAL_PYTHONHOME+_}" ] ; then + PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME" + export PYTHONHOME + unset _OLD_VIRTUAL_PYTHONHOME + fi + + # The hash command must be called to get it to forget past + # commands. Without forgetting past commands the $PATH changes + # we made may not be respected + hash -r 2>/dev/null + + if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then + PS1="$_OLD_VIRTUAL_PS1" + export PS1 + unset _OLD_VIRTUAL_PS1 + fi + + unset VIRTUAL_ENV + unset VIRTUAL_ENV_PROMPT + if [ ! "${1-}" = "nondestructive" ] ; then + # Self destruct! + unset -f deactivate + fi +} + +# unset irrelevant variables +deactivate nondestructive + +VIRTUAL_ENV='C:\Users\heric\OPC_PROJETS\P11_DebugTest\Python_Testing' +if ([ "$OSTYPE" = "cygwin" ] || [ "$OSTYPE" = "msys" ]) && $(command -v cygpath &> /dev/null) ; then + VIRTUAL_ENV=$(cygpath -u "$VIRTUAL_ENV") +fi +export VIRTUAL_ENV + +_OLD_VIRTUAL_PATH="$PATH" +PATH="$VIRTUAL_ENV/Scripts:$PATH" +export PATH + +if [ "x" != x ] ; then + VIRTUAL_ENV_PROMPT="" +else + VIRTUAL_ENV_PROMPT=$(basename "$VIRTUAL_ENV") +fi +export VIRTUAL_ENV_PROMPT + +# unset PYTHONHOME if set +if ! [ -z "${PYTHONHOME+_}" ] ; then + _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME" + unset PYTHONHOME +fi + +if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then + _OLD_VIRTUAL_PS1="${PS1-}" + PS1="(${VIRTUAL_ENV_PROMPT}) ${PS1-}" + export PS1 +fi + +# Make sure to unalias pydoc if it's already there +alias pydoc 2>/dev/null >/dev/null && unalias pydoc || true + +pydoc () { + python -m pydoc "$@" +} + +# The hash command must be called to get it to forget past +# commands. Without forgetting past commands the $PATH changes +# we made may not be respected +hash -r 2>/dev/null || true diff --git a/Scripts/activate.bat b/Scripts/activate.bat new file mode 100644 index 000000000..a111d282e --- /dev/null +++ b/Scripts/activate.bat @@ -0,0 +1,52 @@ +@REM This file is UTF-8 encoded, so we need to update the current code page while executing it +@echo off +@for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do ( + @set _OLD_CODEPAGE=%%a +) +@if defined _OLD_CODEPAGE ( + "%SystemRoot%\System32\chcp.com" 65001 > nul +) + +@set "VIRTUAL_ENV=C:\Users\heric\OPC_PROJETS\P11_DebugTest\Python_Testing" + +@set "VIRTUAL_ENV_PROMPT=" +@if NOT DEFINED VIRTUAL_ENV_PROMPT ( + @for %%d in ("%VIRTUAL_ENV%") do @set "VIRTUAL_ENV_PROMPT=%%~nxd" +) + +@if defined _OLD_VIRTUAL_PROMPT ( + @set "PROMPT=%_OLD_VIRTUAL_PROMPT%" +) else ( + @if not defined PROMPT ( + @set "PROMPT=$P$G" + ) + @if not defined VIRTUAL_ENV_DISABLE_PROMPT ( + @set "_OLD_VIRTUAL_PROMPT=%PROMPT%" + ) +) +@if not defined VIRTUAL_ENV_DISABLE_PROMPT ( + @set "PROMPT=(%VIRTUAL_ENV_PROMPT%) %PROMPT%" +) + +@REM Don't use () to avoid problems with them in %PATH% +@if defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME + @set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%" +:ENDIFVHOME + +@set PYTHONHOME= + +@REM if defined _OLD_VIRTUAL_PATH ( +@if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH1 + @set "PATH=%_OLD_VIRTUAL_PATH%" +:ENDIFVPATH1 +@REM ) else ( +@if defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH2 + @set "_OLD_VIRTUAL_PATH=%PATH%" +:ENDIFVPATH2 + +@set "PATH=%VIRTUAL_ENV%\Scripts;%PATH%" + +@if defined _OLD_CODEPAGE ( + "%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul + @set _OLD_CODEPAGE= +) diff --git a/Scripts/activate.fish b/Scripts/activate.fish new file mode 100644 index 000000000..387c33fbc --- /dev/null +++ b/Scripts/activate.fish @@ -0,0 +1,103 @@ +# This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*. +# Do not run it directly. + +function _bashify_path -d "Converts a fish path to something bash can recognize" + set fishy_path $argv + set bashy_path $fishy_path[1] + for path_part in $fishy_path[2..-1] + set bashy_path "$bashy_path:$path_part" + end + echo $bashy_path +end + +function _fishify_path -d "Converts a bash path to something fish can recognize" + echo $argv | tr ':' '\n' +end + +function deactivate -d 'Exit virtualenv mode and return to the normal environment.' + # reset old environment variables + if test -n "$_OLD_VIRTUAL_PATH" + # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling + if test (echo $FISH_VERSION | head -c 1) -lt 3 + set -gx PATH (_fishify_path "$_OLD_VIRTUAL_PATH") + else + set -gx PATH $_OLD_VIRTUAL_PATH + end + set -e _OLD_VIRTUAL_PATH + end + + if test -n "$_OLD_VIRTUAL_PYTHONHOME" + set -gx PYTHONHOME "$_OLD_VIRTUAL_PYTHONHOME" + set -e _OLD_VIRTUAL_PYTHONHOME + end + + if test -n "$_OLD_FISH_PROMPT_OVERRIDE" + and functions -q _old_fish_prompt + # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`. + set -l fish_function_path + + # Erase virtualenv's `fish_prompt` and restore the original. + functions -e fish_prompt + functions -c _old_fish_prompt fish_prompt + functions -e _old_fish_prompt + set -e _OLD_FISH_PROMPT_OVERRIDE + end + + set -e VIRTUAL_ENV + set -e VIRTUAL_ENV_PROMPT + + if test "$argv[1]" != 'nondestructive' + # Self-destruct! + functions -e pydoc + functions -e deactivate + functions -e _bashify_path + functions -e _fishify_path + end +end + +# Unset irrelevant variables. +deactivate nondestructive + +set -gx VIRTUAL_ENV 'C:\Users\heric\OPC_PROJETS\P11_DebugTest\Python_Testing' + +# https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling +if test (echo $FISH_VERSION | head -c 1) -lt 3 + set -gx _OLD_VIRTUAL_PATH (_bashify_path $PATH) +else + set -gx _OLD_VIRTUAL_PATH $PATH +end +set -gx PATH "$VIRTUAL_ENV"'/Scripts' $PATH + +# Prompt override provided? +# If not, just use the environment name. +if test -n '' + set -gx VIRTUAL_ENV_PROMPT '' +else + set -gx VIRTUAL_ENV_PROMPT (basename "$VIRTUAL_ENV") +end + +# Unset `$PYTHONHOME` if set. +if set -q PYTHONHOME + set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME + set -e PYTHONHOME +end + +function pydoc + python -m pydoc $argv +end + +if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" + # Copy the current `fish_prompt` function as `_old_fish_prompt`. + functions -c fish_prompt _old_fish_prompt + + function fish_prompt + # Run the user's prompt first; it might depend on (pipe)status. + set -l prompt (_old_fish_prompt) + + printf '(%s) ' $VIRTUAL_ENV_PROMPT + + string join -- \n $prompt # handle multi-line prompts + end + + set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV" +end diff --git a/Scripts/activate.nu b/Scripts/activate.nu new file mode 100644 index 000000000..e5ebb9431 --- /dev/null +++ b/Scripts/activate.nu @@ -0,0 +1,96 @@ +# virtualenv activation module +# Activate with `overlay use activate.nu` +# Deactivate with `deactivate`, as usual +# +# To customize the overlay name, you can call `overlay use activate.nu as foo`, +# but then simply `deactivate` won't work because it is just an alias to hide +# the "activate" overlay. You'd need to call `overlay hide foo` manually. + +export-env { + def is-string [x] { + ($x | describe) == 'string' + } + + def has-env [...names] { + $names | each {|n| + $n in $env + } | all {|i| $i == true} + } + + # Emulates a `test -z`, but better as it handles e.g 'false' + def is-env-true [name: string] { + if (has-env $name) { + # Try to parse 'true', '0', '1', and fail if not convertible + let parsed = (do -i { $env | get $name | into bool }) + if ($parsed | describe) == 'bool' { + $parsed + } else { + not ($env | get -i $name | is-empty) + } + } else { + false + } + } + + let virtual_env = 'C:\Users\heric\OPC_PROJETS\P11_DebugTest\Python_Testing' + let bin = 'Scripts' + + let is_windows = ($nu.os-info.family) == 'windows' + let path_name = (if (has-env 'Path') { + 'Path' + } else { + 'PATH' + } + ) + + let venv_path = ([$virtual_env $bin] | path join) + let new_path = ($env | get $path_name | prepend $venv_path) + + # If there is no default prompt, then use the env name instead + let virtual_env_prompt = (if ('' | is-empty) { + ($virtual_env | path basename) + } else { + '' + }) + + let new_env = { + $path_name : $new_path + VIRTUAL_ENV : $virtual_env + VIRTUAL_ENV_PROMPT : $virtual_env_prompt + } + + let new_env = (if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') { + $new_env + } else { + # Creating the new prompt for the session + let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) ' + + # Back up the old prompt builder + let old_prompt_command = (if (has-env 'PROMPT_COMMAND') { + $env.PROMPT_COMMAND + } else { + '' + }) + + let new_prompt = (if (has-env 'PROMPT_COMMAND') { + if 'closure' in ($old_prompt_command | describe) { + {|| $'($virtual_prefix)(do $old_prompt_command)' } + } else { + {|| $'($virtual_prefix)($old_prompt_command)' } + } + } else { + {|| $'($virtual_prefix)' } + }) + + $new_env | merge { + PROMPT_COMMAND : $new_prompt + VIRTUAL_PREFIX : $virtual_prefix + } + }) + + # Environment variables that will be loaded as the virtual env + load-env $new_env +} + +export alias pydoc = python -m pydoc +export alias deactivate = overlay hide activate diff --git a/Scripts/activate.ps1 b/Scripts/activate.ps1 new file mode 100644 index 000000000..46171cf9c --- /dev/null +++ b/Scripts/activate.ps1 @@ -0,0 +1,61 @@ +$script:THIS_PATH = $myinvocation.mycommand.path +$script:BASE_DIR = Split-Path (Resolve-Path "$THIS_PATH/..") -Parent + +function global:deactivate([switch] $NonDestructive) { + if (Test-Path variable:_OLD_VIRTUAL_PATH) { + $env:PATH = $variable:_OLD_VIRTUAL_PATH + Remove-Variable "_OLD_VIRTUAL_PATH" -Scope global + } + + if (Test-Path function:_old_virtual_prompt) { + $function:prompt = $function:_old_virtual_prompt + Remove-Item function:\_old_virtual_prompt + } + + if ($env:VIRTUAL_ENV) { + Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue + } + + if ($env:VIRTUAL_ENV_PROMPT) { + Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue + } + + if (!$NonDestructive) { + # Self destruct! + Remove-Item function:deactivate + Remove-Item function:pydoc + } +} + +function global:pydoc { + python -m pydoc $args +} + +# unset irrelevant variables +deactivate -nondestructive + +$VIRTUAL_ENV = $BASE_DIR +$env:VIRTUAL_ENV = $VIRTUAL_ENV + +if ("" -ne "") { + $env:VIRTUAL_ENV_PROMPT = "" +} +else { + $env:VIRTUAL_ENV_PROMPT = $( Split-Path $env:VIRTUAL_ENV -Leaf ) +} + +New-Variable -Scope global -Name _OLD_VIRTUAL_PATH -Value $env:PATH + +$env:PATH = "$env:VIRTUAL_ENV/Scripts;" + $env:PATH +if (!$env:VIRTUAL_ENV_DISABLE_PROMPT) { + function global:_old_virtual_prompt { + "" + } + $function:_old_virtual_prompt = $function:prompt + + function global:prompt { + # Add the custom prefix to the existing prompt + $previous_prompt_value = & $function:_old_virtual_prompt + ("(" + $env:VIRTUAL_ENV_PROMPT + ") " + $previous_prompt_value) + } +} diff --git a/Scripts/activate_this.py b/Scripts/activate_this.py new file mode 100644 index 000000000..276debd2a --- /dev/null +++ b/Scripts/activate_this.py @@ -0,0 +1,38 @@ +""" +Activate virtualenv for current interpreter: + +import runpy +runpy.run_path(this_file) + +This can be used when you must use an existing Python interpreter, not the virtualenv bin/python. +""" # noqa: D415 + +from __future__ import annotations + +import os +import site +import sys + +try: + abs_file = os.path.abspath(__file__) +except NameError as exc: + msg = "You must use import runpy; runpy.run_path(this_file)" + raise AssertionError(msg) from exc + +bin_dir = os.path.dirname(abs_file) +base = bin_dir[: -len("Scripts") - 1] # strip away the bin part from the __file__, plus the path separator + +# prepend bin to PATH (this file is inside the bin directory) +os.environ["PATH"] = os.pathsep.join([bin_dir, *os.environ.get("PATH", "").split(os.pathsep)]) +os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directory +os.environ["VIRTUAL_ENV_PROMPT"] = "" or os.path.basename(base) # noqa: SIM222 + +# add the virtual environments libraries to the host python import mechanism +prev_length = len(sys.path) +for lib in "..\\Lib\\site-packages".split(os.pathsep): + path = os.path.realpath(os.path.join(bin_dir, lib)) + site.addsitedir(path.decode("utf-8") if "" else path) +sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length] + +sys.real_prefix = sys.prefix +sys.prefix = base diff --git a/Scripts/deactivate.bat b/Scripts/deactivate.bat new file mode 100644 index 000000000..8939c6c0d --- /dev/null +++ b/Scripts/deactivate.bat @@ -0,0 +1,18 @@ +@set VIRTUAL_ENV= +@set VIRTUAL_ENV_PROMPT= + +@REM Don't use () to avoid problems with them in %PATH% +@if not defined _OLD_VIRTUAL_PROMPT @goto ENDIFVPROMPT + @set "PROMPT=%_OLD_VIRTUAL_PROMPT%" + @set _OLD_VIRTUAL_PROMPT= +:ENDIFVPROMPT + +@if not defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME + @set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%" + @set _OLD_VIRTUAL_PYTHONHOME= +:ENDIFVHOME + +@if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH + @set "PATH=%_OLD_VIRTUAL_PATH%" + @set _OLD_VIRTUAL_PATH= +:ENDIFVPATH diff --git a/Scripts/flask.exe b/Scripts/flask.exe new file mode 100644 index 000000000..2e3f6f706 Binary files /dev/null and b/Scripts/flask.exe differ diff --git a/Scripts/locust.exe b/Scripts/locust.exe new file mode 100644 index 000000000..6424c164d Binary files /dev/null and b/Scripts/locust.exe differ diff --git a/Scripts/normalizer.exe b/Scripts/normalizer.exe new file mode 100644 index 000000000..6145c6e4e Binary files /dev/null and b/Scripts/normalizer.exe differ diff --git a/Scripts/pip-3.9.exe b/Scripts/pip-3.9.exe new file mode 100644 index 000000000..e6145caf9 Binary files /dev/null and b/Scripts/pip-3.9.exe differ diff --git a/Scripts/pip.exe b/Scripts/pip.exe new file mode 100644 index 000000000..e6145caf9 Binary files /dev/null and b/Scripts/pip.exe differ diff --git a/Scripts/pip3.9.exe b/Scripts/pip3.9.exe new file mode 100644 index 000000000..e6145caf9 Binary files /dev/null and b/Scripts/pip3.9.exe differ diff --git a/Scripts/pip3.exe b/Scripts/pip3.exe new file mode 100644 index 000000000..e6145caf9 Binary files /dev/null and b/Scripts/pip3.exe differ diff --git a/Scripts/py.test.exe b/Scripts/py.test.exe new file mode 100644 index 000000000..881b0fd0b Binary files /dev/null and b/Scripts/py.test.exe differ diff --git a/Scripts/pydoc.bat b/Scripts/pydoc.bat new file mode 100644 index 000000000..3d46a231a --- /dev/null +++ b/Scripts/pydoc.bat @@ -0,0 +1 @@ +python.exe -m pydoc %* diff --git a/Scripts/pytest.exe b/Scripts/pytest.exe new file mode 100644 index 000000000..881b0fd0b Binary files /dev/null and b/Scripts/pytest.exe differ diff --git a/Scripts/python.exe b/Scripts/python.exe new file mode 100644 index 000000000..96b8f3453 Binary files /dev/null and b/Scripts/python.exe differ diff --git a/Scripts/pythonw.exe b/Scripts/pythonw.exe new file mode 100644 index 000000000..35e700572 Binary files /dev/null and b/Scripts/pythonw.exe differ diff --git a/Scripts/pywin32_postinstall.py b/Scripts/pywin32_postinstall.py new file mode 100644 index 000000000..a9dd85645 --- /dev/null +++ b/Scripts/pywin32_postinstall.py @@ -0,0 +1,778 @@ +# postinstall script for pywin32 +# +# copies pywintypesXX.dll and pythoncomXX.dll into the system directory, +# and creates a pth file +import argparse +import glob +import os +import shutil +import sys +import sysconfig +import tempfile # Send output somewhere so it can be found if necessary... +import winreg + +tee_f = open(os.path.join(tempfile.gettempdir(), "pywin32_postinstall.log"), "w") + + +class Tee: + def __init__(self, file): + self.f = file + + def write(self, what): + if self.f is not None: + try: + self.f.write(what.replace("\n", "\r\n")) + except OSError: + pass + tee_f.write(what) + + def flush(self): + if self.f is not None: + try: + self.f.flush() + except OSError: + pass + tee_f.flush() + + +# For some unknown reason, when running under bdist_wininst we will start up +# with sys.stdout as None but stderr is hooked up. This work-around allows +# bdist_wininst to see the output we write and display it at the end of +# the install. +if sys.stdout is None: # pyright: ignore[reportUnnecessaryComparison] + sys.stdout = sys.stderr + +sys.stderr = Tee(sys.stderr) +sys.stdout = Tee(sys.stdout) + +com_modules = [ + # module_name, class_names + ("win32com.servers.interp", "Interpreter"), + ("win32com.servers.dictionary", "DictionaryPolicy"), + ("win32com.axscript.client.pyscript", "PyScript"), +] + +# Is this a 'silent' install - ie, avoid all dialogs. +# Different than 'verbose' +silent = 0 + +# Verbosity of output messages. +verbose = 1 + +root_key_name = "Software\\Python\\PythonCore\\" + sys.winver + +try: + # When this script is run from inside the bdist_wininst installer, + # file_created() and directory_created() are additional builtin + # functions which write lines to PythonXX\pywin32-install.log. This is + # a list of actions for the uninstaller, the format is inspired by what + # the Wise installer also creates. + file_created # type: ignore[used-before-def] + # 3.10 stopped supporting bdist_wininst, but we can still build them with 3.9. + # This can be kept until Python 3.9 or exe installers support is dropped. + is_bdist_wininst = True +except NameError: + is_bdist_wininst = False # we know what it is not - but not what it is :) + + def file_created(file): + pass + + def directory_created(directory): + pass + + def get_root_hkey(): + try: + winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, root_key_name, 0, winreg.KEY_CREATE_SUB_KEY + ) + return winreg.HKEY_LOCAL_MACHINE + except OSError: + # Either not exist, or no permissions to create subkey means + # must be HKCU + return winreg.HKEY_CURRENT_USER + + +try: + create_shortcut # type: ignore[used-before-def] +except NameError: + # Create a function with the same signature as create_shortcut provided + # by bdist_wininst + def create_shortcut( + path, description, filename, arguments="", workdir="", iconpath="", iconindex=0 + ): + import pythoncom + from win32com.shell import shell + + ilink = pythoncom.CoCreateInstance( + shell.CLSID_ShellLink, + None, + pythoncom.CLSCTX_INPROC_SERVER, + shell.IID_IShellLink, + ) + ilink.SetPath(path) + ilink.SetDescription(description) + if arguments: + ilink.SetArguments(arguments) + if workdir: + ilink.SetWorkingDirectory(workdir) + if iconpath or iconindex: + ilink.SetIconLocation(iconpath, iconindex) + # now save it. + ipf = ilink.QueryInterface(pythoncom.IID_IPersistFile) + ipf.Save(filename, 0) + + # Support the same list of "path names" as bdist_wininst. + def get_special_folder_path(path_name): + from win32com.shell import shell, shellcon + + for maybe in """ + CSIDL_COMMON_STARTMENU CSIDL_STARTMENU CSIDL_COMMON_APPDATA + CSIDL_LOCAL_APPDATA CSIDL_APPDATA CSIDL_COMMON_DESKTOPDIRECTORY + CSIDL_DESKTOPDIRECTORY CSIDL_COMMON_STARTUP CSIDL_STARTUP + CSIDL_COMMON_PROGRAMS CSIDL_PROGRAMS CSIDL_PROGRAM_FILES_COMMON + CSIDL_PROGRAM_FILES CSIDL_FONTS""".split(): + if maybe == path_name: + csidl = getattr(shellcon, maybe) + return shell.SHGetSpecialFolderPath(0, csidl, False) + raise ValueError(f"{path_name} is an unknown path ID") + + +def CopyTo(desc, src, dest): + import win32api + import win32con + + while 1: + try: + win32api.CopyFile(src, dest, 0) + return + except win32api.error as details: + if details.winerror == 5: # access denied - user not admin. + raise + if silent: + # Running silent mode - just re-raise the error. + raise + full_desc = ( + f"Error {desc}\n\n" + "If you have any Python applications running, " + f"please close them now\nand select 'Retry'\n\n{details.strerror}" + ) + rc = win32api.MessageBox( + 0, full_desc, "Installation Error", win32con.MB_ABORTRETRYIGNORE + ) + if rc == win32con.IDABORT: + raise + elif rc == win32con.IDIGNORE: + return + # else retry - around we go again. + + +# We need to import win32api to determine the Windows system directory, +# so we can copy our system files there - but importing win32api will +# load the pywintypes.dll already in the system directory preventing us +# from updating them! +# So, we pull the same trick pywintypes.py does, but it loads from +# our pywintypes_system32 directory. +def LoadSystemModule(lib_dir, modname): + # See if this is a debug build. + import importlib.machinery + import importlib.util + + suffix = "_d" if "_d.pyd" in importlib.machinery.EXTENSION_SUFFIXES else "" + filename = "%s%d%d%s.dll" % ( + modname, + sys.version_info.major, + sys.version_info.minor, + suffix, + ) + filename = os.path.join(lib_dir, "pywin32_system32", filename) + loader = importlib.machinery.ExtensionFileLoader(modname, filename) + spec = importlib.machinery.ModuleSpec(name=modname, loader=loader, origin=filename) + mod = importlib.util.module_from_spec(spec) + loader.exec_module(mod) + + +def SetPyKeyVal(key_name, value_name, value): + root_hkey = get_root_hkey() + root_key = winreg.OpenKey(root_hkey, root_key_name) + try: + my_key = winreg.CreateKey(root_key, key_name) + try: + winreg.SetValueEx(my_key, value_name, 0, winreg.REG_SZ, value) + if verbose: + print(f"-> {root_key_name}\\{key_name}[{value_name}]={value!r}") + finally: + my_key.Close() + finally: + root_key.Close() + + +def UnsetPyKeyVal(key_name, value_name, delete_key=False): + root_hkey = get_root_hkey() + root_key = winreg.OpenKey(root_hkey, root_key_name) + try: + my_key = winreg.OpenKey(root_key, key_name, 0, winreg.KEY_SET_VALUE) + try: + winreg.DeleteValue(my_key, value_name) + if verbose: + print(f"-> DELETE {root_key_name}\\{key_name}[{value_name}]") + finally: + my_key.Close() + if delete_key: + winreg.DeleteKey(root_key, key_name) + if verbose: + print(f"-> DELETE {root_key_name}\\{key_name}") + except OSError as why: + winerror = getattr(why, "winerror", why.errno) + if winerror != 2: # file not found + raise + finally: + root_key.Close() + + +def RegisterCOMObjects(register=True): + import win32com.server.register + + if register: + func = win32com.server.register.RegisterClasses + else: + func = win32com.server.register.UnregisterClasses + flags = {} + if not verbose: + flags["quiet"] = 1 + for module, klass_name in com_modules: + __import__(module) + mod = sys.modules[module] + flags["finalize_register"] = getattr(mod, "DllRegisterServer", None) + flags["finalize_unregister"] = getattr(mod, "DllUnregisterServer", None) + klass = getattr(mod, klass_name) + func(klass, **flags) + + +def RegisterHelpFile(register=True, lib_dir=None): + if lib_dir is None: + lib_dir = sysconfig.get_paths()["platlib"] + if register: + # Register the .chm help file. + chm_file = os.path.join(lib_dir, "PyWin32.chm") + if os.path.isfile(chm_file): + # This isn't recursive, so if 'Help' doesn't exist, we croak + SetPyKeyVal("Help", None, None) + SetPyKeyVal("Help\\Pythonwin Reference", None, chm_file) + return chm_file + else: + print("NOTE: PyWin32.chm can not be located, so has not been registered") + else: + UnsetPyKeyVal("Help\\Pythonwin Reference", None, delete_key=True) + return None + + +def RegisterPythonwin(register=True, lib_dir=None): + """Add (or remove) Pythonwin to context menu for python scripts. + ??? Should probably also add Edit command for pys files also. + Also need to remove these keys on uninstall, but there's no function + like file_created to add registry entries to uninstall log ??? + """ + import os + + if lib_dir is None: + lib_dir = sysconfig.get_paths()["platlib"] + classes_root = get_root_hkey() + ## Installer executable doesn't seem to pass anything to postinstall script indicating if it's a debug build, + pythonwin_exe = os.path.join(lib_dir, "Pythonwin", "Pythonwin.exe") + pythonwin_edit_command = pythonwin_exe + ' -edit "%1"' + + keys_vals = [ + ( + "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Pythonwin.exe", + "", + pythonwin_exe, + ), + ( + "Software\\Classes\\Python.File\\shell\\Edit with Pythonwin", + "command", + pythonwin_edit_command, + ), + ( + "Software\\Classes\\Python.NoConFile\\shell\\Edit with Pythonwin", + "command", + pythonwin_edit_command, + ), + ] + + try: + if register: + for key, sub_key, val in keys_vals: + ## Since winreg only uses the character Api functions, this can fail if Python + ## is installed to a path containing non-ascii characters + hkey = winreg.CreateKey(classes_root, key) + if sub_key: + hkey = winreg.CreateKey(hkey, sub_key) + winreg.SetValueEx(hkey, None, 0, winreg.REG_SZ, val) + hkey.Close() + else: + for key, sub_key, val in keys_vals: + try: + if sub_key: + hkey = winreg.OpenKey(classes_root, key) + winreg.DeleteKey(hkey, sub_key) + hkey.Close() + winreg.DeleteKey(classes_root, key) + except OSError as why: + winerror = getattr(why, "winerror", why.errno) + if winerror != 2: # file not found + raise + finally: + # tell windows about the change + from win32com.shell import shell, shellcon + + shell.SHChangeNotify( + shellcon.SHCNE_ASSOCCHANGED, shellcon.SHCNF_IDLIST, None, None + ) + + +def get_shortcuts_folder(): + if get_root_hkey() == winreg.HKEY_LOCAL_MACHINE: + try: + fldr = get_special_folder_path("CSIDL_COMMON_PROGRAMS") + except OSError: + # No CSIDL_COMMON_PROGRAMS on this platform + fldr = get_special_folder_path("CSIDL_PROGRAMS") + else: + # non-admin install - always goes in this user's start menu. + fldr = get_special_folder_path("CSIDL_PROGRAMS") + + try: + install_group = winreg.QueryValue( + get_root_hkey(), root_key_name + "\\InstallPath\\InstallGroup" + ) + except OSError: + install_group = "Python %d.%d" % ( + sys.version_info.major, + sys.version_info.minor, + ) + return os.path.join(fldr, install_group) + + +# Get the system directory, which may be the Wow64 directory if we are a 32bit +# python on a 64bit OS. +def get_system_dir(): + import win32api # we assume this exists. + + try: + import pythoncom + import win32process + from win32com.shell import shell, shellcon + + try: + if win32process.IsWow64Process(): + return shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_SYSTEMX86) + return shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_SYSTEM) + except (pythoncom.com_error, win32process.error): + return win32api.GetSystemDirectory() + except ImportError: + return win32api.GetSystemDirectory() + + +def fixup_dbi(): + # We used to have a dbi.pyd with our .pyd files, but now have a .py file. + # If the user didn't uninstall, they will find the .pyd which will cause + # problems - so handle that. + import win32api + import win32con + + pyd_name = os.path.join(os.path.dirname(win32api.__file__), "dbi.pyd") + pyd_d_name = os.path.join(os.path.dirname(win32api.__file__), "dbi_d.pyd") + py_name = os.path.join(os.path.dirname(win32con.__file__), "dbi.py") + for this_pyd in (pyd_name, pyd_d_name): + this_dest = this_pyd + ".old" + if os.path.isfile(this_pyd) and os.path.isfile(py_name): + try: + if os.path.isfile(this_dest): + print( + f"Old dbi '{this_dest}' already exists - deleting '{this_pyd}'" + ) + os.remove(this_pyd) + else: + os.rename(this_pyd, this_dest) + print(f"renamed '{this_pyd}'->'{this_pyd}.old'") + file_created(this_pyd + ".old") + except OSError as exc: + print(f"FAILED to rename '{this_pyd}': {exc}") + + +def install(lib_dir): + import traceback + + # The .pth file is now installed as a regular file. + # Create the .pth file in the site-packages dir, and use only relative paths + # We used to write a .pth directly to sys.prefix - clobber it. + if os.path.isfile(os.path.join(sys.prefix, "pywin32.pth")): + os.unlink(os.path.join(sys.prefix, "pywin32.pth")) + # The .pth may be new and therefore not loaded in this session. + # Setup the paths just in case. + for name in "win32 win32\\lib Pythonwin".split(): + sys.path.append(os.path.join(lib_dir, name)) + # It is possible people with old versions installed with still have + # pywintypes and pythoncom registered. We no longer need this, and stale + # entries hurt us. + for name in "pythoncom pywintypes".split(): + keyname = "Software\\Python\\PythonCore\\" + sys.winver + "\\Modules\\" + name + for root in winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER: + try: + winreg.DeleteKey(root, keyname + "\\Debug") + except OSError: + pass + try: + winreg.DeleteKey(root, keyname) + except OSError: + pass + LoadSystemModule(lib_dir, "pywintypes") + LoadSystemModule(lib_dir, "pythoncom") + import win32api + + # and now we can get the system directory: + files = glob.glob(os.path.join(lib_dir, "pywin32_system32\\*.*")) + if not files: + raise RuntimeError("No system files to copy!!") + # Try the system32 directory first - if that fails due to "access denied", + # it implies a non-admin user, and we use sys.prefix + for dest_dir in [get_system_dir(), sys.prefix]: + # and copy some files over there + worked = 0 + try: + for fname in files: + base = os.path.basename(fname) + dst = os.path.join(dest_dir, base) + CopyTo("installing %s" % base, fname, dst) + if verbose: + print(f"Copied {base} to {dst}") + # Register the files with the uninstaller + file_created(dst) + worked = 1 + # Nuke any other versions that may exist - having + # duplicates causes major headaches. + bad_dest_dirs = [ + os.path.join(sys.prefix, "Library\\bin"), + os.path.join(sys.prefix, "Lib\\site-packages\\win32"), + ] + if dest_dir != sys.prefix: + bad_dest_dirs.append(sys.prefix) + for bad_dest_dir in bad_dest_dirs: + bad_fname = os.path.join(bad_dest_dir, base) + if os.path.exists(bad_fname): + # let exceptions go here - delete must succeed + os.unlink(bad_fname) + if worked: + break + except win32api.error as details: + if details.winerror == 5: + # access denied - user not admin - try sys.prefix dir, + # but first check that a version doesn't already exist + # in that place - otherwise that one will still get used! + if os.path.exists(dst): + msg = ( + "The file '%s' exists, but can not be replaced " + "due to insufficient permissions. You must " + "reinstall this software as an Administrator" % dst + ) + print(msg) + raise RuntimeError(msg) + continue + raise + else: + raise RuntimeError( + "You don't have enough permissions to install the system files" + ) + + # Pythonwin 'compiles' config files - record them for uninstall. + pywin_dir = os.path.join(lib_dir, "Pythonwin", "pywin") + for fname in glob.glob(os.path.join(pywin_dir, "*.cfg")): + file_created(fname[:-1] + "c") # .cfg->.cfc + + # Register our demo COM objects. + try: + try: + RegisterCOMObjects() + except win32api.error as details: + if details.winerror != 5: # ERROR_ACCESS_DENIED + raise + print("You do not have the permissions to install COM objects.") + print("The sample COM objects were not registered.") + except Exception: + print("FAILED to register the Python COM objects") + traceback.print_exc() + + # There may be no main Python key in HKCU if, eg, an admin installed + # python itself. + winreg.CreateKey(get_root_hkey(), root_key_name) + + chm_file = None + try: + chm_file = RegisterHelpFile(True, lib_dir) + except Exception: + print("Failed to register help file") + traceback.print_exc() + else: + if verbose: + print("Registered help file") + + # misc other fixups. + fixup_dbi() + + # Register Pythonwin in context menu + try: + RegisterPythonwin(True, lib_dir) + except Exception: + print("Failed to register pythonwin as editor") + traceback.print_exc() + else: + if verbose: + print("Pythonwin has been registered in context menu") + + # Create the win32com\gen_py directory. + make_dir = os.path.join(lib_dir, "win32com", "gen_py") + if not os.path.isdir(make_dir): + if verbose: + print(f"Creating directory {make_dir}") + directory_created(make_dir) + os.mkdir(make_dir) + + try: + # create shortcuts + # CSIDL_COMMON_PROGRAMS only available works on NT/2000/XP, and + # will fail there if the user has no admin rights. + fldr = get_shortcuts_folder() + # If the group doesn't exist, then we don't make shortcuts - its + # possible that this isn't a "normal" install. + if os.path.isdir(fldr): + dst = os.path.join(fldr, "PythonWin.lnk") + create_shortcut( + os.path.join(lib_dir, "Pythonwin\\Pythonwin.exe"), + "The Pythonwin IDE", + dst, + "", + sys.prefix, + ) + file_created(dst) + if verbose: + print("Shortcut for Pythonwin created") + # And the docs. + if chm_file: + dst = os.path.join(fldr, "Python for Windows Documentation.lnk") + doc = "Documentation for the PyWin32 extensions" + create_shortcut(chm_file, doc, dst) + file_created(dst) + if verbose: + print("Shortcut to documentation created") + else: + if verbose: + print(f"Can't install shortcuts - {fldr!r} is not a folder") + except Exception as details: + print(details) + + # importing win32com.client ensures the gen_py dir created - not strictly + # necessary to do now, but this makes the installation "complete" + try: + import win32com.client # noqa + except ImportError: + # Don't let this error sound fatal + pass + print("The pywin32 extensions were successfully installed.") + + if is_bdist_wininst: + # Open a web page with info about the .exe installers being deprecated. + import webbrowser + + try: + webbrowser.open("https://mhammond.github.io/pywin32_installers.html") + except webbrowser.Error: + print("Please visit https://mhammond.github.io/pywin32_installers.html") + + +def uninstall(lib_dir): + # First ensure our system modules are loaded from pywin32_system, so + # we can remove the ones we copied... + LoadSystemModule(lib_dir, "pywintypes") + LoadSystemModule(lib_dir, "pythoncom") + + try: + RegisterCOMObjects(False) + except Exception as why: + print(f"Failed to unregister COM objects: {why}") + + try: + RegisterHelpFile(False, lib_dir) + except Exception as why: + print(f"Failed to unregister help file: {why}") + else: + if verbose: + print("Unregistered help file") + + try: + RegisterPythonwin(False, lib_dir) + except Exception as why: + print(f"Failed to unregister Pythonwin: {why}") + else: + if verbose: + print("Unregistered Pythonwin") + + try: + # remove gen_py directory. + gen_dir = os.path.join(lib_dir, "win32com", "gen_py") + if os.path.isdir(gen_dir): + shutil.rmtree(gen_dir) + if verbose: + print(f"Removed directory {gen_dir}") + + # Remove pythonwin compiled "config" files. + pywin_dir = os.path.join(lib_dir, "Pythonwin", "pywin") + for fname in glob.glob(os.path.join(pywin_dir, "*.cfc")): + os.remove(fname) + + # The dbi.pyd.old files we may have created. + try: + os.remove(os.path.join(lib_dir, "win32", "dbi.pyd.old")) + except OSError: + pass + try: + os.remove(os.path.join(lib_dir, "win32", "dbi_d.pyd.old")) + except OSError: + pass + + except Exception as why: + print(f"Failed to remove misc files: {why}") + + try: + fldr = get_shortcuts_folder() + for link in ("PythonWin.lnk", "Python for Windows Documentation.lnk"): + fqlink = os.path.join(fldr, link) + if os.path.isfile(fqlink): + os.remove(fqlink) + if verbose: + print(f"Removed {link}") + except Exception as why: + print(f"Failed to remove shortcuts: {why}") + # Now remove the system32 files. + files = glob.glob(os.path.join(lib_dir, "pywin32_system32\\*.*")) + # Try the system32 directory first - if that fails due to "access denied", + # it implies a non-admin user, and we use sys.prefix + try: + for dest_dir in [get_system_dir(), sys.prefix]: + # and copy some files over there + worked = 0 + for fname in files: + base = os.path.basename(fname) + dst = os.path.join(dest_dir, base) + if os.path.isfile(dst): + try: + os.remove(dst) + worked = 1 + if verbose: + print("Removed file %s" % (dst)) + except Exception: + print(f"FAILED to remove {dst}") + if worked: + break + except Exception as why: + print(f"FAILED to remove system files: {why}") + + +# NOTE: If this script is run from inside the bdist_wininst created +# binary installer or uninstaller, the command line args are either +# '-install' or '-remove'. + +# Important: From inside the binary installer this script MUST NOT +# call sys.exit() or raise SystemExit, otherwise not only this script +# but also the installer will terminate! (Is there a way to prevent +# this from the bdist_wininst C code?) + + +def verify_destination(location): + if not os.path.isdir(location): + raise argparse.ArgumentTypeError(f'Path "{location}" does not exist!') + return location + + +def main(): + parser = argparse.ArgumentParser( + formatter_class=argparse.RawDescriptionHelpFormatter, + description="""A post-install script for the pywin32 extensions. + + * Typical usage: + + > python pywin32_postinstall.py -install + + If you installed pywin32 via a .exe installer, this should be run + automatically after installation, but if it fails you can run it again. + + If you installed pywin32 via PIP, you almost certainly need to run this to + setup the environment correctly. + + Execute with script with a '-install' parameter, to ensure the environment + is setup correctly. + """, + ) + parser.add_argument( + "-install", + default=False, + action="store_true", + help="Configure the Python environment correctly for pywin32.", + ) + parser.add_argument( + "-remove", + default=False, + action="store_true", + help="Try and remove everything that was installed or copied.", + ) + parser.add_argument( + "-wait", + type=int, + help="Wait for the specified process to terminate before starting.", + ) + parser.add_argument( + "-silent", + default=False, + action="store_true", + help='Don\'t display the "Abort/Retry/Ignore" dialog for files in use.', + ) + parser.add_argument( + "-quiet", + default=False, + action="store_true", + help="Don't display progress messages.", + ) + parser.add_argument( + "-destination", + default=sysconfig.get_paths()["platlib"], + type=verify_destination, + help="Location of the PyWin32 installation", + ) + + args = parser.parse_args() + + if not args.quiet: + print(f"Parsed arguments are: {args}") + + if not args.install ^ args.remove: + parser.error("You need to either choose to -install or -remove!") + + if args.wait is not None: + try: + os.waitpid(args.wait, 0) + except OSError: + # child already dead + pass + + silent = args.silent + verbose = not args.quiet + + if args.install: + install(args.destination) + + if args.remove: + if not is_bdist_wininst: + uninstall(args.destination) + + +if __name__ == "__main__": + main() diff --git a/Scripts/pywin32_testall.py b/Scripts/pywin32_testall.py new file mode 100644 index 000000000..2aa92098c --- /dev/null +++ b/Scripts/pywin32_testall.py @@ -0,0 +1,125 @@ +"""A test runner for pywin32""" + +import os +import site +import subprocess +import sys + +# locate the dirs based on where this script is - it may be either in the +# source tree, or in an installed Python 'Scripts' tree. +this_dir = os.path.dirname(__file__) +site_packages = [ + site.getusersitepackages(), +] + site.getsitepackages() + +failures = [] + + +# Run a test using subprocess and wait for the result. +# If we get an returncode != 0, we know that there was an error, but we don't +# abort immediately - we run as many tests as we can. +def run_test(script, cmdline_extras): + dirname, scriptname = os.path.split(script) + # some tests prefer to be run from their directory. + cmd = [sys.executable, "-u", scriptname] + cmdline_extras + print("--- Running '%s' ---" % script) + sys.stdout.flush() + result = subprocess.run(cmd, check=False, cwd=dirname) + print(f"*** Test script '{script}' exited with {result.returncode}") + sys.stdout.flush() + if result.returncode: + failures.append(script) + + +def find_and_run(possible_locations, extras): + for maybe in possible_locations: + if os.path.isfile(maybe): + run_test(maybe, extras) + break + else: + raise RuntimeError( + "Failed to locate a test script in one of %s" % possible_locations + ) + + +def main(): + import argparse + + code_directories = [this_dir] + site_packages + + parser = argparse.ArgumentParser( + description="A script to trigger tests in all subprojects of PyWin32." + ) + parser.add_argument( + "-no-user-interaction", + default=False, + action="store_true", + help="(This is now the default - use `-user-interaction` to include them)", + ) + + parser.add_argument( + "-user-interaction", + action="store_true", + help="Include tests which require user interaction", + ) + + parser.add_argument( + "-skip-adodbapi", + default=False, + action="store_true", + help="Skip the adodbapi tests; useful for CI where there's no provider", + ) + + args, remains = parser.parse_known_args() + + # win32, win32ui / Pythonwin + + extras = [] + if args.user_interaction: + extras.append("-user-interaction") + extras.extend(remains) + scripts = [ + "win32/test/testall.py", + "Pythonwin/pywin/test/all.py", + ] + for script in scripts: + maybes = [os.path.join(directory, script) for directory in code_directories] + find_and_run(maybes, extras) + + # win32com + maybes = [ + os.path.join(directory, "win32com", "test", "testall.py") + for directory in [ + os.path.join(this_dir, "com"), + ] + + site_packages + ] + extras = remains + ["1"] # only run "level 1" tests in CI + find_and_run(maybes, extras) + + # adodbapi + if not args.skip_adodbapi: + maybes = [ + os.path.join(directory, "adodbapi", "test", "adodbapitest.py") + for directory in code_directories + ] + find_and_run(maybes, remains) + # This script has a hard-coded sql server name in it, (and markh typically + # doesn't have a different server to test on) but there is now supposed to be a server out there on the Internet + # just to run these tests, so try it... + maybes = [ + os.path.join(directory, "adodbapi", "test", "test_adodbapi_dbapi20.py") + for directory in code_directories + ] + find_and_run(maybes, remains) + + if failures: + print("The following scripts failed") + for failure in failures: + print(">", failure) + sys.exit(1) + print("All tests passed \\o/") + + +if __name__ == "__main__": + main() diff --git a/Scripts/wheel-3.9.exe b/Scripts/wheel-3.9.exe new file mode 100644 index 000000000..dd4c0ebed Binary files /dev/null and b/Scripts/wheel-3.9.exe differ diff --git a/Scripts/wheel.exe b/Scripts/wheel.exe new file mode 100644 index 000000000..dd4c0ebed Binary files /dev/null and b/Scripts/wheel.exe differ diff --git a/Scripts/wheel3.9.exe b/Scripts/wheel3.9.exe new file mode 100644 index 000000000..dd4c0ebed Binary files /dev/null and b/Scripts/wheel3.9.exe differ diff --git a/Scripts/wheel3.exe b/Scripts/wheel3.exe new file mode 100644 index 000000000..dd4c0ebed Binary files /dev/null and b/Scripts/wheel3.exe differ diff --git a/pyvenv.cfg b/pyvenv.cfg new file mode 100644 index 000000000..d7153c05d --- /dev/null +++ b/pyvenv.cfg @@ -0,0 +1,8 @@ +home = C:\Users\heric\AppData\Local\Programs\Python\Python39 +implementation = CPython +version_info = 3.9.2.final.0 +virtualenv = 20.26.4 +include-system-site-packages = false +base-prefix = C:\Users\heric\AppData\Local\Programs\Python\Python39 +base-exec-prefix = C:\Users\heric\AppData\Local\Programs\Python\Python39 +base-executable = C:\Users\heric\AppData\Local\Programs\Python\Python39\python.exe diff --git a/server.py b/server.py index 4084baeac..6d59bf167 100644 --- a/server.py +++ b/server.py @@ -26,8 +26,12 @@ def index(): @app.route('/showSummary',methods=['POST']) def showSummary(): - club = [club for club in clubs if club['email'] == request.form['email']][0] - return render_template('welcome.html',club=club,competitions=competitions) + club = next((club for club in clubs if club['email'] == request.form['email']), None) + if club: + return render_template('welcome.html', club=club, competitions=competitions) + else: + flash("The entered email is unknown. Please try again with a valid email.") + return redirect(url_for('index')) @app.route('/book//') @@ -41,19 +45,42 @@ def book(competition,club): return render_template('welcome.html', club=club, competitions=competitions) -@app.route('/purchasePlaces',methods=['POST']) +@app.route('/purchasePlaces', methods=['POST']) def purchasePlaces(): - competition = [c for c in competitions if c['name'] == request.form['competition']][0] - club = [c for c in clubs if c['name'] == request.form['club']][0] - placesRequired = int(request.form['places']) - competition['numberOfPlaces'] = int(competition['numberOfPlaces'])-placesRequired - flash('Great-booking complete!') + competition = next((c for c in competitions if c['name'] == request.form['competition']), None) + club = next((c for c in clubs if c['name'] == request.form['club']), None) + placesRequested = int(request.form['places']) + + # Convertir les valeurs en entiers + club_points = int(club['points']) + available_places = int(competition['numberOfPlaces']) + + # Vérification des points et des places disponibles + if placesRequested > club_points: + flash("You don't have enough points to complete this booking.") + elif placesRequested > available_places: + flash("Not enough places available for this competition.") + else: + # Mise à jour des places et des points + competition['numberOfPlaces'] = str(available_places - placesRequested) + club['points'] = str(club_points - placesRequested) + flash(f'Great, {placesRequested} places successfully booked!') + return render_template('welcome.html', club=club, competitions=competitions) + + + + + # TODO: Add route for points display @app.route('/logout') def logout(): - return redirect(url_for('index')) \ No newline at end of file + return redirect(url_for('index')) + + +if __name__ == '__main__': + app.run(debug=True) diff --git a/templates/index.html b/templates/index.html index 926526b7d..49bdb8c9d 100644 --- a/templates/index.html +++ b/templates/index.html @@ -6,7 +6,15 @@

Welcome to the GUDLFT Registration Portal!

- Please enter your secretary email to continue: + {% with messages = get_flashed_messages() %} + {% if messages %} + + {% endif %} + {% endwith %}
diff --git a/templates/welcome.html b/templates/welcome.html index ff6b261a2..471fa9605 100644 --- a/templates/welcome.html +++ b/templates/welcome.html @@ -5,32 +5,37 @@ Summary | GUDLFT Registration -

Welcome, {{club['email']}}

Logout +

Welcome, {{club['name']}}

Logout {% with messages = get_flashed_messages()%} {% if messages %}
    {% for message in messages %} -
  • {{message}}
  • +
  • {{message}}
  • {% endfor %}
{% endif%} - Points available: {{club['points']}} -

Competitions:

-
    - {% for comp in competitions%} + {%endwith%} + + + +

    Points available: {{club['points']}}

    +

    Competitions:

    +
      + {% for competition in competitions %}
    • - {{comp['name']}}
      - Date: {{comp['date']}}
      - Number of Places: {{comp['numberOfPlaces']}} - {%if comp['numberOfPlaces']|int >0%} - Book Places - {%endif%} + {{ competition['name'] }} - Date: {{ competition['date'] }} - Places: {{ competition['numberOfPlaces'] }} + + + + + + +
    • -
      - {% endfor %} -
    - {%endwith%} + {% endfor %} +
+ \ No newline at end of file