import khoury.EnabledTest import khoury.fileExists import khoury.fileReadAsString import khoury.fileWrite import khoury.isAnInteger import khoury.runEnabledTests import khoury.testSame val fileBad = "test-bad-run-times.txt" val fileGood = "test-good-run-times.txt" val fileGoodValue = 42 // gets the past runs from a supplied file // (assumes the entire file is just a number) fun getPastRuns(fname: String): Int { val fileText: String = if (fileExists(fname)) fileReadAsString(fname) else "" val pastRuns: Int = if (isAnInteger(fileText)) fileText.toInt() else 0 return pastRuns } @EnabledTest fun testGetPastRuns() { testSame( getPastRuns("BAD-FILE-DOES-NOT-EXIST"), 0, "file does not exist", ) testSame( getPastRuns(fileBad), 0, "bad file contents", ) testSame( getPastRuns(fileGood), fileGoodValue, "good file", ) } // saves the number to the supplied filename fun saveNewPastRuns( filename: String, valueToSave: Int, ) { fileWrite(filename, "$valueToSave") } @EnabledTest fun testSaveNewPastRuns() { // notice: having to "setup" (more later!) saveNewPastRuns(fileGood, fileGoodValue) // notice: not actually calling the function // we are trying to test (more later!) testSame( getPastRuns(fileGood), fileGoodValue, "good file", ) } fun main() { val pastRunsFilename = "run-times.txt" val timesInThePast = getPastRuns(pastRunsFilename) println("This program has been run $timesInThePast time(s) in the past.") saveNewPastRuns(pastRunsFilename, timesInThePast + 1) } runEnabledTests(this) main()