From f6c305c80640212aca95cd89d00ad2d90e91b2f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bir=C3=B3=20Bence?= Date: Wed, 30 Oct 2024 08:31:31 +0100 Subject: [PATCH] Initial commit --- .github/workflows/jacoco.yml | 77 +++++ .github/workflows/maven.yml | 23 ++ .gitignore | 24 ++ .mvn/wrapper/maven-wrapper.properties | 18 + LICENSE | 21 ++ README.md | 40 +++ mvnw | 308 ++++++++++++++++++ mvnw.cmd | 205 ++++++++++++ pom.xml | 92 ++++++ .../mit/spaceship/CommandLineInterface.java | 201 ++++++++++++ .../java/hu/bme/mit/spaceship/FiringMode.java | 8 + .../java/hu/bme/mit/spaceship/GT4500.java | 105 ++++++ .../java/hu/bme/mit/spaceship/SpaceShip.java | 23 ++ .../hu/bme/mit/spaceship/TorpedoStore.java | 67 ++++ .../java/hu/bme/mit/spaceship/GT4500Test.java | 38 +++ .../hu/bme/mit/spaceship/SystemTests.java | 105 ++++++ .../bme/mit/spaceship/TorpedoStoreTest.java | 20 ++ test-data/input-0.txt | 3 + test-data/output-0.txt | 2 + 19 files changed, 1380 insertions(+) create mode 100644 .github/workflows/jacoco.yml create mode 100644 .github/workflows/maven.yml create mode 100644 .gitignore create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100644 LICENSE create mode 100644 README.md create mode 100755 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/hu/bme/mit/spaceship/CommandLineInterface.java create mode 100644 src/main/java/hu/bme/mit/spaceship/FiringMode.java create mode 100644 src/main/java/hu/bme/mit/spaceship/GT4500.java create mode 100644 src/main/java/hu/bme/mit/spaceship/SpaceShip.java create mode 100644 src/main/java/hu/bme/mit/spaceship/TorpedoStore.java create mode 100644 src/test/java/hu/bme/mit/spaceship/GT4500Test.java create mode 100644 src/test/java/hu/bme/mit/spaceship/SystemTests.java create mode 100644 src/test/java/hu/bme/mit/spaceship/TorpedoStoreTest.java create mode 100644 test-data/input-0.txt create mode 100644 test-data/output-0.txt diff --git a/.github/workflows/jacoco.yml b/.github/workflows/jacoco.yml new file mode 100644 index 0000000..ed276c7 --- /dev/null +++ b/.github/workflows/jacoco.yml @@ -0,0 +1,77 @@ +--- +name: Measure coverage + +on: + workflow_dispatch: + pull_request: + branches: [main] + +env: + COVERAGE_THRESHOLD: 0.8 + +permissions: + contents: read + pull-requests: write + +jobs: + test: + name: Coverage with JaCoCo + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: temurin + cache: maven + + - name: Evaluate coverage + run: mvn -B verify + + - name: Create filtered JaCoCo CSV that contains only GT4500 results + run: > + > jacoco-gt4500.csv awk + 'NR==1{print;next}/GT4500/{print}' + target/site/jacoco/jacoco.csv + + - name: Generate JaCoCo badges + id: jacoco + uses: cicirello/jacoco-badge-generator@v2 + with: + jacoco-csv-file: jacoco-gt4500.csv + generate-coverage-badge: false + generate-branches-badge: false + workflow-summary-heading: JaCoCo Test Coverage Summary (GT4500) + + - name: Log coverage metrics + run: | + echo "GT4500 instruction coverage = ${{ steps.jacoco.outputs.coverage }}" + echo "GT4500 branch coverage = ${{ steps.jacoco.outputs.branches }}" + + - name: Add PR comment with coverage metrics + uses: mshick/add-pr-comment@v2 + with: + message: | + ### JaCoCo Coverage Report (GT4500) + + | Coverage Metric | Value | Threshold (Minimum) | | + | --- | --- | --- | --- | + | 👉 Instruction Coverage | ${{ steps.jacoco.outputs.coverage }} | ${{ env.COVERAGE_THRESHOLD }} | ${{ steps.jacoco.outputs.coverage < env.COVERAGE_THRESHOLD && '❌' || '✅' }} | + | 🌳 Decision/Branch Coverage | ${{ steps.jacoco.outputs.branches }} | ${{ env.COVERAGE_THRESHOLD }} | ${{ steps.jacoco.outputs.branches < env.COVERAGE_THRESHOLD && '❌' || '✅' }} | + allow-repeats: true + + - name: Upload coverage report + uses: actions/upload-artifact@v4 + with: + name: jacoco-report + path: target/site/jacoco/ + + - name: Fail job unless requirements are met + if: ${{ steps.jacoco.outputs.coverage < env.COVERAGE_THRESHOLD || steps.jacoco.outputs.branches < env.COVERAGE_THRESHOLD }} + uses: actions/github-script@v7 + with: + script: core.setFailed('Coverage metrics do not meet requirements') + diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 0000000..c8caba3 --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,23 @@ +--- +name: Java CI with Maven + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + build: + name: Build with Maven + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: temurin + cache: maven + - name: Build with Maven + run: mvn -B package --file pom.xml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1e1575b --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# ignore target from Maven +target/ + +# IntelliJ folder +.idea/ + +# Visual Studio Code files +*.classpath +*.project +.settings/ +.vscode/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..6d3a566 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4793e03 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Budapest University of Technology and Economics + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..957bc25 --- /dev/null +++ b/README.md @@ -0,0 +1,40 @@ +# SE Spaceship + +This is a sample application for the [Software Engineering](http://www.mit.bme.hu/oktatas/targyak/vimiab04) course at BME MIT. + +The application is simplified and deliberately contains bugs. + +## Getting started + +- The project is implemented in Java 11. +- The project can be built using [Maven](https://maven.apache.org/). +- [JUnit](https://junit.org/junit5/) is used for tests, and [Mockito](https://site.mockito.org/) for isolating dependencies. + +Clone the repository and execute Maven to build the application: + +``` +mvn compile +``` + +To compile and run tests also execute: + +``` +mvn test +``` + +(That will be enough to know for the current exercises. If you are more interested, see [this](https://github.com/ftsrg-edu/swsv-labs/wiki/0b-Build-tools) short guide about Maven.) + +As this is a really simple project, you can use the command-line build tools or a light-weight IDE like [Visual Studio Code](https://code.visualstudio.com/). + +## Overview + +The project represents an alpha version of a spaceship. + +- The ship (`SpaceShip` interface) can fire one or more lasers or torpedos. +- We have only one spaceship as of now (`GT4500`). +- Currently two firing modes (`FiringMode`) are supported: firing only one or all instances of a given weapon type. +- Lasers are not yet implemented, but the code for torpedo stores are ready (`TorpedoStore`). +- For the GT4500 ship the rules for firing torpedoes can be found in the Javadoc comment of method `fireTorpedos`. They are already partially implemented. +- There are currently two tests (`GT4500Test`), but be aware that they are not proper unit tests, as they do not isolate the dependencies of the tested class. + +The code can be built, but due to missing features one of the tests fails. The first exercise will be to fix this. diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..8d937f4 --- /dev/null +++ b/mvnw @@ -0,0 +1,308 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.2.0 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "$(uname)" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then + if $darwin ; then + javaHome="$(dirname "\"$javaExecutable\"")" + javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" + else + javaExecutable="$(readlink -f "\"$javaExecutable\"")" + fi + javaHome="$(dirname "\"$javaExecutable\"")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=$(cd "$wdir/.." || exit 1; pwd) + fi + # end of workaround + done + printf '%s' "$(cd "$basedir" || exit 1; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" +else + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; + esac + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget > /dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + fi + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi +fi + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +# shellcheck disable=SC2086 # safe args +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..c4586b5 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,205 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..b775e10 --- /dev/null +++ b/pom.xml @@ -0,0 +1,92 @@ + + 4.0.0 + hu.bme.mit.spaceship + hu.bme.mit.spaceship + 0.5.0-SNAPSHOT + + + UTF-8 + ${project.groupId}.CommandLineInterface + + + + + org.junit.jupiter + junit-jupiter + 5.8.2 + test + + + org.mockito + mockito-core + 4.4.0 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.10.1 + + 11 + + + + + + maven-surefire-plugin + 3.0.0 + + + me.fabriciorby + maven-surefire-junit5-tree-reporter + 0.1.0 + + + + plain + + true + + + + + + + org.jacoco + jacoco-maven-plugin + 0.8.12 + + + start-agent + + prepare-agent + + + + generate-report + + report + + + Coverage with JaCoCo and Maven + + + + + + + org.codehaus.mojo + exec-maven-plugin + 3.1.0 + + ${mainClass} + + + + + diff --git a/src/main/java/hu/bme/mit/spaceship/CommandLineInterface.java b/src/main/java/hu/bme/mit/spaceship/CommandLineInterface.java new file mode 100644 index 0000000..0b05c13 --- /dev/null +++ b/src/main/java/hu/bme/mit/spaceship/CommandLineInterface.java @@ -0,0 +1,201 @@ +package hu.bme.mit.spaceship; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Scanner; +import java.util.function.BiFunction; + +/** + * Minimal command line interface (CLI) to initialize and use spaceships. + */ +public class CommandLineInterface { + + private static Map handlers = Map.of( + "HELP", CommandLineInterface::handleHelp, + "GT4500", CommandLineInterface::handleGT4500, + "TORPEDO", CommandLineInterface::handleTorpedo, + "EXIT", CommandLineInterface::handleExit + ); + + public static void main(String[] args) { + run(System.in, System.out, new OptionalOutput(System.err)); + } + + /** + * Read and handle commands from an input stream, writing output to another stream. + * + * The optional err stream receives output only useful in an interactive session. + * + * @param in The input stream to read commands from + * @param out The output stream to write results to + * @param err Optional stream to write interactive session feedback to + */ + public static void run(InputStream in, OutputStream out, OptionalOutput err) { + Context ctx = new Context(); + ctx.out = new PrintStream(out); + + err.println("Welcome to the console interface. Available commands: " + + handlers.keySet().toString()); + try (Scanner scanner = new Scanner(in)) { + CommandResult result = CommandResult.CONTINUE; + do { + err.print("> "); + try { + result = handle(ctx, scanner.nextLine()); + } catch (NoSuchElementException e) { + result = CommandResult.EXIT; + } + } while (result == CommandResult.CONTINUE); + } + } + + public static void run(InputStream in, OutputStream out) { + run(in, out, new OptionalOutput(null)); + } + + /** + * Handle a command. + * + * @param ctx The current CLI context + * @param command The command as a list of comma-separated tokens + * @return whether execution should continue + */ + private static CommandResult handle(Context ctx, String command) { + if (command.stripLeading().startsWith("#")) { + return CommandResult.CONTINUE; + } + + command = command.replaceAll("#.*$", "").strip(); + if (command.isEmpty()) { + return CommandResult.CONTINUE; + } + + String[] parts = command.split(","); + String mainCommand = parts[0].toUpperCase(); + + CommandResult result = CommandResult.CONTINUE; + try { + Handler handler = handlers.get(mainCommand); + if (handler == null) { + ctx.out.printf("Unknown command: '%s'%n", mainCommand); + } else { + result = handler.apply(ctx, parts); + } + } catch (IllegalArgumentException e) { + ctx.out.println(e.getLocalizedMessage()); + } + + return result; + } + + /** + * Handle the HELP command. + */ + private static CommandResult handleHelp(Context ctx, String[] params) { + ctx.out.println("Available commands: " + handlers.keySet()); + ctx.out.println("Generally, commands receive parameters; refer to the documentation"); + ctx.out.println( + "Before firing torpedoes using the TORPEDO command, you must initialize a ship (eg. a GT4500) using its name as a command"); + return CommandResult.CONTINUE; + } + + /** + * Handle the GT4500 command. + */ + private static CommandResult handleGT4500(Context ctx, String[] params) { + if (params.length != 5) { + throw new IllegalArgumentException( + "usage: GT4500,,,,"); + } + + int primaryCount; + int secondaryCount; + double primaryFailRate; + double secondaryFailRate; + try { + primaryCount = Integer.parseInt(params[1]); + primaryFailRate = Double.parseDouble(params[2]); + secondaryCount = Integer.parseInt(params[3]); + secondaryFailRate = Double.parseDouble(params[4]); + } catch (NumberFormatException e) { + throw new IllegalArgumentException( + "Invalid numerical arguments passed: " + e.getLocalizedMessage(), e); + } + + ctx.ship = new GT4500(primaryCount, primaryFailRate, secondaryCount, secondaryFailRate); + ctx.out.println("SUCCESS"); + return CommandResult.CONTINUE; + } + + /** + * Handle the TORPEDO command. + */ + private static CommandResult handleTorpedo(Context ctx, String[] params) { + if (ctx.ship == null) { + throw new IllegalArgumentException("No ship has been initialized"); + } + if (params.length != 2) { + throw new IllegalArgumentException("usage: TORPEDO,"); + } + + FiringMode firingMode; + try { + firingMode = FiringMode.valueOf(params[1].toUpperCase()); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + String.format("Unknown firing mode: '%s'", params[1].toUpperCase()), e); + } + boolean success = ctx.ship.fireTorpedo(firingMode); + ctx.out.println(success ? "SUCCESS" : "FAIL"); + return CommandResult.CONTINUE; + } + + /** + * Handle the EXIT command. + */ + private static CommandResult handleExit(Context ctx, String[] params) { + return CommandResult.EXIT; + } + + private static class Context { + SpaceShip ship; + PrintStream out; + } + + private static interface Handler extends BiFunction {} + + /** + * Rudimentary PrintStream-like interface that silently ignores if the underlying PrintStream is + * null. + */ + private static class OptionalOutput { + + private PrintStream out; + + OptionalOutput(OutputStream out) { + if (out != null) { + this.out = new PrintStream(out); + } + } + + public void print(String message) { + if (out != null) { + out.print(message); + } + } + + public void println(String message) { + print(message + "\n"); + } + } + + /** + * More readable enumeration for command results. + */ + private enum CommandResult { + CONTINUE, EXIT + } +} diff --git a/src/main/java/hu/bme/mit/spaceship/FiringMode.java b/src/main/java/hu/bme/mit/spaceship/FiringMode.java new file mode 100644 index 0000000..aa682ee --- /dev/null +++ b/src/main/java/hu/bme/mit/spaceship/FiringMode.java @@ -0,0 +1,8 @@ +package hu.bme.mit.spaceship; + +/** + * Weapon firing mode enumeration + */ +public enum FiringMode { + SINGLE, ALL +} diff --git a/src/main/java/hu/bme/mit/spaceship/GT4500.java b/src/main/java/hu/bme/mit/spaceship/GT4500.java new file mode 100644 index 0000000..4071c72 --- /dev/null +++ b/src/main/java/hu/bme/mit/spaceship/GT4500.java @@ -0,0 +1,105 @@ +package hu.bme.mit.spaceship; + +/** + * A simple spaceship with two proton torpedo stores and four lasers + */ +public class GT4500 implements SpaceShip { + + private TorpedoStore primaryTorpedoStore; + private TorpedoStore secondaryTorpedoStore; + + private boolean wasPrimaryFiredLast = false; + + public GT4500() { + this.primaryTorpedoStore = new TorpedoStore(10); + this.secondaryTorpedoStore = new TorpedoStore(10); + } + + public GT4500(int primaryCount, double primaryFailRate, int secondaryCount, + double secondaryFailRate) { + this.primaryTorpedoStore = new TorpedoStore(primaryCount, primaryFailRate); + this.secondaryTorpedoStore = new TorpedoStore(secondaryCount, secondaryFailRate); + } + + public boolean fireLaser(FiringMode firingMode) { + // TODO not implemented yet + return false; + } + + /** + * Tries to fire the torpedo stores of the ship. + * + * @param firingMode how many torpedo bays to fire + * SINGLE: fires only one of the bays. + * - For the first time the primary store is fired. + * - To give some cooling time to the torpedo stores, torpedo stores are fired + * alternating. + * - But if the store next in line is empty, the ship tries to fire the other + * store. + * - If the fired store reports a failure, the ship does not try to fire the + * other one. + * ALL: tries to fire both of the torpedo + * stores. + * + * @return whether at least one torpedo was fired successfully + */ + @Override + public boolean fireTorpedo(FiringMode firingMode) { + + boolean firingSuccess = false; + + switch (firingMode) { + case SINGLE: + if (wasPrimaryFiredLast) { + // try to fire the secondary first + if (!secondaryTorpedoStore.isEmpty()) { + firingSuccess = secondaryTorpedoStore.fire(1); + wasPrimaryFiredLast = false; + } else { + // although primary was fired last time, but the secondary is empty + // thus try to fire primary again + if (!primaryTorpedoStore.isEmpty()) { + firingSuccess = primaryTorpedoStore.fire(1); + wasPrimaryFiredLast = true; + } + + // if both of the stores are empty, nothing can be done, return failure + } + } else { + // try to fire the primary first + if (!primaryTorpedoStore.isEmpty()) { + firingSuccess = primaryTorpedoStore.fire(1); + wasPrimaryFiredLast = true; + } else { + // although secondary was fired last time, but primary is empty + // thus try to fire secondary again + if (!secondaryTorpedoStore.isEmpty()) { + firingSuccess = secondaryTorpedoStore.fire(1); + wasPrimaryFiredLast = false; + } + + // if both of the stores are empty, nothing can be done, return failure + } + } + break; + + case ALL: + // try to fire both of the torpedo stores + boolean primarySuccess = false; + boolean secondarySuccess = false; + + if (!primaryTorpedoStore.isEmpty()) { + primarySuccess = primaryTorpedoStore.fire(1); + } + if (!secondaryTorpedoStore.isEmpty()) { + secondarySuccess = secondaryTorpedoStore.fire(1); + } + + firingSuccess = primarySuccess || secondarySuccess; + break; + } + + return firingSuccess; + } + +} diff --git a/src/main/java/hu/bme/mit/spaceship/SpaceShip.java b/src/main/java/hu/bme/mit/spaceship/SpaceShip.java new file mode 100644 index 0000000..f3d51b1 --- /dev/null +++ b/src/main/java/hu/bme/mit/spaceship/SpaceShip.java @@ -0,0 +1,23 @@ +package hu.bme.mit.spaceship; + +/** + * Defines basic spaceship functionality (collects just the most important ones currently) + */ +public interface SpaceShip { + + /** + * Fires the laser or lasers of the ship + * + * @param firingMode how many lasers to fire + * @return was the firing successful + */ + public boolean fireLaser(FiringMode firingMode); + + /** + * Fires the torpedo stores of the ship + * + * @param firingMode how many torpedo stores to fire + * @return whether the fire command was successful + */ + public boolean fireTorpedo(FiringMode firingMode); +} diff --git a/src/main/java/hu/bme/mit/spaceship/TorpedoStore.java b/src/main/java/hu/bme/mit/spaceship/TorpedoStore.java new file mode 100644 index 0000000..0f18fbb --- /dev/null +++ b/src/main/java/hu/bme/mit/spaceship/TorpedoStore.java @@ -0,0 +1,67 @@ +package hu.bme.mit.spaceship; + +import java.util.Random; + +/** + * Class storing and managing the torpedoes of a ship + * + * (Deliberately contains bugs.) + */ +public class TorpedoStore { + + private Random generator = new Random(); + + // rate of failing to fire torpedos [0.0, 1.0] + private double FAILURE_RATE = 0.0; // NOSONAR + + private int torpedoCount = 0; + + public TorpedoStore(int numberOfTorpedos) { + this.torpedoCount = numberOfTorpedos; + + // update failure rate if it was specified in an environment variable + String failureEnv = System.getenv("IVT_RATE"); + if (failureEnv != null) { + try { + FAILURE_RATE = Double.parseDouble(failureEnv); + } catch (NumberFormatException nfe) { + FAILURE_RATE = 0.0; + } + } + } + + public TorpedoStore(int numberOfTorpedos, double failureRate) { + this(numberOfTorpedos); + this.FAILURE_RATE = failureRate; + } + + public boolean fire(int numberOfTorpedos) { + if (numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount) { + throw new IllegalArgumentException("numberOfTorpedos"); + } + + boolean success = false; + + // simulate random overheating of the launcher bay which prevents firing + double r = generator.nextDouble(); + + if (r >= FAILURE_RATE) { + // successful firing + this.torpedoCount -= numberOfTorpedos; + success = true; + } else { + // simulated failure + success = false; + } + + return success; + } + + public boolean isEmpty() { + return this.torpedoCount <= 0; + } + + public int getTorpedoCount() { + return this.torpedoCount; + } +} diff --git a/src/test/java/hu/bme/mit/spaceship/GT4500Test.java b/src/test/java/hu/bme/mit/spaceship/GT4500Test.java new file mode 100644 index 0000000..2450d75 --- /dev/null +++ b/src/test/java/hu/bme/mit/spaceship/GT4500Test.java @@ -0,0 +1,38 @@ +package hu.bme.mit.spaceship; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class GT4500Test { + + private GT4500 ship; + + @BeforeEach + public void init() { + this.ship = new GT4500(); + } + + @Test + void fireTorpedo_Single_Success() { + // Arrange + + // Act + boolean result = ship.fireTorpedo(FiringMode.SINGLE); + + // Assert + assertEquals(true, result); + } + + @Test + void fireTorpedo_All_Success() { + // Arrange + + // Act + boolean result = ship.fireTorpedo(FiringMode.ALL); + + // Assert + assertEquals(true, result); + } +} diff --git a/src/test/java/hu/bme/mit/spaceship/SystemTests.java b/src/test/java/hu/bme/mit/spaceship/SystemTests.java new file mode 100644 index 0000000..5ad2701 --- /dev/null +++ b/src/test/java/hu/bme/mit/spaceship/SystemTests.java @@ -0,0 +1,105 @@ +package hu.bme.mit.spaceship; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Named; + +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.FileSystems; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.PathMatcher; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +class SystemTests { + + /** + * Test the ship using the command line interface. + * + * Input commands are provided as a parameter. Expected outputs may be provided in another file. + * In case the output file does not exist, it is simply ignored and the test is inconclusive. + */ + @ParameterizedTest + @MethodSource("provideTestFilePaths") + void runCommandsFromFile_Success(Path input, Path output) throws IOException { + // Arrange + InputStream in = new FileInputStream(input.toFile()); + OutputStream actualOut = new ByteArrayOutputStream(); + + // Act + CommandLineInterface.run(in, actualOut); + + // Assert + if (!Files.exists(output)) { + // No output file was provided; test is inconclusive but we + // still get coverage metrics for the execution + inconclusive(); + } else { + String expected = normalizeString(Files.readString(output)); + String actual = normalizeString(actualOut.toString()); + assertEquals(expected, actual, output.toString()); + } + } + + private static Stream provideTestFilePaths() { + PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**/input*"); + + List args = new ArrayList<>(); + try { + Files.walkFileTree(Paths.get("test-data/"), new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) + throws IOException { + if (matcher.matches(path)) { + Path in = path; + Path out = Path.of(path.toString().replace("input", "output")); + args.add(Arguments.of(Named.of(in.toString(), in), + Named.of(out.toString(), out))); + } + return FileVisitResult.CONTINUE; + } + }); + } catch (IOException e) { + System.err.println("Unexpected IO exception thrown by file visitor"); + e.printStackTrace(); + } + + return args.stream(); + } + + /** + * Utility method to force a test result to be 'inconclusive'. + */ + private static void inconclusive() { + Assumptions.assumeTrue(false, "Inconclusive"); + } + + /** + * Normalize a string. + * + * This function does the following: + *
    + *
  1. remove comment characters (#) and any characters that follow them in the + * same line + *
  2. replace all remaining consecutive whitespace with single spaces + *
  3. strip all leading and trailing whitespace + *
+ */ + private static String normalizeString(String s) { + return s.replaceAll("#.*", "").replaceAll("\\s+", " ").strip(); + } +} diff --git a/src/test/java/hu/bme/mit/spaceship/TorpedoStoreTest.java b/src/test/java/hu/bme/mit/spaceship/TorpedoStoreTest.java new file mode 100644 index 0000000..5df1009 --- /dev/null +++ b/src/test/java/hu/bme/mit/spaceship/TorpedoStoreTest.java @@ -0,0 +1,20 @@ +package hu.bme.mit.spaceship; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class TorpedoStoreTest { + + @Test + void fire_Success() { + // Arrange + TorpedoStore store = new TorpedoStore(1); + + // Act + boolean result = store.fire(1); + + // Assert + assertEquals(true, result); + } +} diff --git a/test-data/input-0.txt b/test-data/input-0.txt new file mode 100644 index 0000000..4f679e3 --- /dev/null +++ b/test-data/input-0.txt @@ -0,0 +1,3 @@ +# Create a ship with stocked torpedo stores that never fail +GT4500,10,0,10,0 +TORPEDO,SINGLE # should have fired from the primary store \ No newline at end of file diff --git a/test-data/output-0.txt b/test-data/output-0.txt new file mode 100644 index 0000000..506c839 --- /dev/null +++ b/test-data/output-0.txt @@ -0,0 +1,2 @@ +SUCCESS # <- GT4500 +SUCCESS # <- TORPEDO \ No newline at end of file