Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • lamp/cs206
  • bwermeil/cs206-2020
  • zabifade/cs206-2020
  • cauderan/cs206-2020
  • malonga/cs206-2020
  • dumoncel/cs206
  • bounekhe/cs206
  • bergerault/cs206
  • flealsan/cs206
  • hsu/cs206
  • mouchel/cs206
  • vebraun/cs206
  • vcanard/cs206
  • ybelghmi/cs206
  • belghmi/cs206
  • bousbina/cs206
  • waked/cs206
  • gtagemou/cs206
  • arahmoun/cs206
  • elhachem/cs206
  • benrahha/cs206
  • benslima/cs206
22 results
Show changes
Showing
with 0 additions and 1068 deletions
package f1
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
case class Grade(sciper: Int, grade: Double)
trait F1 {
/**
* Retrieve the list of student grades, sorted such that maximum grades
* appear at the head of the list.
*/
def leaderboard(): Future[List[Grade]] =
getScipers().flatMap { scipers =>
Future.sequence(scipers.map(getGrade))
}.map(_.flatten.sortBy(_.grade).reverse)
/**
* Retrieve a student's grade using GitLab's API.
* The result is wrapped in an option, where `Future(None)` indicates either:
* - the student is not registered to the class
* - the student did not push his/her solution to GitLab
*/
def getGrade(sciper: Int): Future[Option[Grade]]
/**
* Retrieve the list of enrolled students from IS-academia
*/
def getScipers(): Future[List[Int]]
}
package f1
import play.api.{ApplicationLoader, BuiltInComponentsFromContext}
import play.api.mvc.Results.Ok
import play.api.routing.sird._
import play.api.routing.Router
import play.api.ApplicationLoader.Context
import play.filters.HttpFiltersComponents
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.Random
class MyApplicationLoader extends ApplicationLoader {
def load(context: Context) =
new MyComponents(context).application
}
class MyComponents(context: Context)
extends BuiltInComponentsFromContext(context)
with HttpFiltersComponents {
lazy val router = Router.from {
case GET(p"/") =>
Action.async {
(new F1MockData).leaderboard().map(leaderboardHTML).map(Ok(_).as("text/html"))
}
}
def leaderboardHTML(data: List[Grade]): String =
s"""
|<!DOCTYPE html>
|<html>
| <head>
| <title>Leaderboard</title>
| </head>
| <body>
| <h1>Leaderboard:</h1>
| <ul>
| ${data.map { case Grade(sciper, g) =>
val grade = "%1.2f".format(g)
s"<li>$sciper : $grade</li>"
}.mkString("\n ")}
| </ul>
| </body>
|</html>
""".trim.stripMargin
}
class F1MockData extends F1 {
def getGrade(sciper: Int): Future[Option[Grade]] =
Future {
// In an actual implementation, this is where we would make a call to
// the GitLab APIs. This mock returns a random grade after a short delay.
Thread.sleep(15) // GitLab is pretty fast today...
val rand = new Random(sciper)
val grade = rand.nextInt(6).toDouble + rand.nextDouble()
if (sciper < 100000 || sciper > 999999 || sciper % 10 == 0) None
else Some(Grade(sciper, grade))
}
/**
* Retrieve the list of enrolled students from IS-academia
*/
def getScipers(): Future[List[Int]] =
Future {
Thread.sleep(100)
List( // A fake list of SCIPER numbers
301425, 207372, 320658, 300217, 224523, 301068, 331020, 331095, 320270,
320742, 299310, 300974, 322202, 343357, 302632, 343366, 320229, 269364,
320004, 321830, 219188, 300834, 320992, 299237, 298016, 300397, 269857,
300492, 300481, 279254, 320967, 300443, 300329, 300305, 331158, 310402,
279067, 300682, 259825, 351616, 310869, 301215, 299481, 269375, 351249,
310866, 351141, 301530, 361378, 351661, 351524, 311081, 331137, 332319,
301045, 300393, 300308, 310889, 310064, 310841, 351333, 310382, 333887,
333837, 320832, 321397, 351691, 269125, 312732, 351546, 301783, 351698,
310775, 331388, 311139, 301992, 301578, 361760, 351174, 310298, 300666,
259778, 301554, 301278, 301669, 321372, 311347, 321129, 351490, 321189,
301336, 341560, 331220, 331129, 333927, 279186, 310596, 299135, 279226,
310507, 269049, 300309, 341524, 351143, 300785, 310612, 320338, 259980,
269952, 310397, 320246, 310959, 301454, 301835, 301802, 301649, 301170,
301908, 351708, 321046, 361490, 311070, 351830, 311054, 311912, 301913,
361232, 301030, 351723, 311472, 311166, 321057, 310793, 269462, 311948,
321693, 321056, 361765, 301453, 321626, 341490, 320892, 269871, 269580,
320199, 320908, 320830, 269071, 380542, 253768, 311204, 269127, 351073,
341327, 301792, 299789, 361424, 301525, 311637, 321423, 279111, 330126,
310371, 259888, 269525, 299585, 300147, 341402, 330067, 311796, 279037,
248517, 301436, 269965, 259963, 320720, 248583, 259709, 361204, 341500,
311803, 299981, 311832, 301088, 259649, 279183, 341760, 311844, 279079,
390997, 311917, 390999, 361122, 301208, 311538, 272943, 361570, 390959)
}
}
package f1
import play.api.test._
import play.api.test.Helpers._
import scala.concurrent.duration._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
class F1Suite extends munit.FunSuite {
test("Retrieves grades at the end of the exam (everyone pushed something) (10pts)") {
class F1Done extends F1 {
override def getGrade(sciper: Int): Future[Option[Grade]] =
Future {
Thread.sleep(100)
Some(Grade(sciper, sciper))
}
override def getScipers(): Future[List[Int]] =
Future {
Thread.sleep(100)
List(1, 2, 3, 4)
}
}
val expected: List[Grade] =
List(Grade(1, 1.0), Grade(2, 2.0), Grade(3, 3.0), Grade(4, 4.0))
(new F1Done).leaderboard().map { grades =>
assertEquals(grades.toSet, expected.toSet)
}
}
test("Retrieves grades mid exam (some students didn't push yet) (10pts)") {
class F1Partial extends F1 {
override def getGrade(sciper: Int): Future[Option[Grade]] =
Future {
Thread.sleep(100)
if (sciper % 2 == 0) None
else Some(Grade(sciper, sciper))
}
override def getScipers(): Future[List[Int]] =
Future {
Thread.sleep(100)
List(1, 2, 3, 4)
}
}
val expected: List[Grade] =
List(Grade(1, 1.0), Grade(3, 3.0))
(new F1Partial).leaderboard().map { grades =>
assertEquals(grades.toSet, expected.toSet)
}
}
test("The output list is sorted by grade (10pts)") {
(new F1MockData).leaderboard().map { grades =>
assert(grades.size >= 176)
assert(grades.zipWithIndex.forall { case (g, i) =>
grades.drop(i).forall(x => g.grade >= x.grade)
})
}
}
test("GitLab API calls are done in parallel (2pts)") {
var inParallel: Boolean = false
class F1Par extends F1MockData {
var in: Boolean = false
override def getGrade(sciper: Int): Future[Option[Grade]] = {
Future {
if (in) inParallel = true
in = true
val out = super.getGrade(sciper)
in = false
concurrent.Await.result(out, Duration(10, SECONDS))
}
}
}
(new F1Par).leaderboard().map { grades =>
assert(grades.size >= 176)
assert(inParallel)
}
}
test("The IS-academia API is called exactly once (2pts)") {
var called: Int = 0
class F1Once extends F1MockData {
override def getScipers(): Future[List[Int]] = {
called += 1
super.getScipers()
}
}
(new F1Once).leaderboard().map { grades =>
assert(grades.size >= 176)
assert(called == 1)
}
}
}
# General
*.DS_Store
*.swp
*~
# Dotty
*.class
*.tasty
*.hasTasty
# sbt
target/
# IDE
.bsp
.bloop
.metals
.vscode
# datasets
stackoverflow-grading.csv
wikipedia-grading.dat
// Student tasks (i.e. submit, packageSubmission)
enablePlugins(StudentTasks)
course := "final"
assignment := "f2"
scalaVersion := "3.0.0-RC1"
scalacOptions ++= Seq("-language:implicitConversions", "-deprecation")
val akkaVersion = "2.6.0"
libraryDependencies += "org.scalameta" %% "munit" % "0.7.22"
libraryDependencies += ("com.typesafe.akka" %% "akka-actor" % akkaVersion).withDottyCompat(scalaVersion.value)
libraryDependencies += ("com.typesafe.akka" %% "akka-testkit" % akkaVersion).withDottyCompat(scalaVersion.value)
val MUnitFramework = new TestFramework("munit.Framework")
testFrameworks += MUnitFramework
// Decode Scala names
testOptions += Tests.Argument(MUnitFramework, "-s")
testSuite := "f2.F2Suite"
File deleted
package sbt // To access the private[sbt] compilerReporter key
package filteringReporterPlugin
import Keys._
import ch.epfl.lamp._
object FilteringReporterPlugin extends AutoPlugin {
override lazy val projectSettings = Seq(
// Turn off warning coming from scalameter that we cannot fix without changing scalameter
compilerReporter in (Compile, compile) ~= { reporter => new FilteringReporter(reporter) }
)
}
class FilteringReporter(reporter: xsbti.Reporter) extends xsbti.Reporter {
def reset(): Unit = reporter.reset()
def hasErrors: Boolean = reporter.hasErrors
def hasWarnings: Boolean = reporter.hasWarnings
def printSummary(): Unit = reporter.printSummary()
def problems: Array[xsbti.Problem] = reporter.problems
def log(problem: xsbti.Problem): Unit = {
if (!problem.message.contains("An existential type that came from a Scala-2 classfile cannot be"))
reporter.log(problem)
}
def comment(pos: xsbti.Position, msg: String): Unit =
reporter.comment(pos, msg)
override def toString = s"CollectingReporter($reporter)"
}
package ch.epfl.lamp
import sbt._
import sbt.Keys._
/**
* Coursera uses two versions of each assignment. They both have the same assignment key and part id but have
* different item ids.
*
* @param key Assignment key
* @param partId Assignment partId
* @param itemId Item id of the non premium version
* @param premiumItemId Item id of the premium version (`None` if the assignment is optional)
*/
case class CourseraId(key: String, partId: String, itemId: String, premiumItemId: Option[String])
/**
* Settings shared by all assignments, reused in various tasks.
*/
object MOOCSettings extends AutoPlugin {
override def requires = super.requires && filteringReporterPlugin.FilteringReporterPlugin
object autoImport {
val course = SettingKey[String]("course")
val assignment = SettingKey[String]("assignment")
val options = SettingKey[Map[String, Map[String, String]]]("options")
val courseraId = settingKey[CourseraId]("Coursera-specific information identifying the assignment")
val testSuite = settingKey[String]("Fully qualified name of the test suite of this assignment")
.withRank(KeyRanks.Invisible)
// Convenient alias
type CourseraId = ch.epfl.lamp.CourseraId
val CourseraId = ch.epfl.lamp.CourseraId
}
import autoImport._
override val globalSettings: Seq[Def.Setting[_]] = Seq(
// supershell is verbose, buggy and useless.
useSuperShell := false
)
override val projectSettings: Seq[Def.Setting[_]] = Seq(
parallelExecution in Test := false,
// Report test result after each test instead of waiting for every test to finish
logBuffered in Test := false,
name := s"${course.value}-${assignment.value}"
)
}
package ch.epfl.lamp
import sbt._
import Keys._
// import scalaj.http._
import java.io.{File, FileInputStream, IOException}
import org.apache.commons.codec.binary.Base64
// import play.api.libs.json.{Json, JsObject, JsPath}
import scala.util.{Failure, Success, Try}
/**
* Provides tasks for submitting the assignment
*/
object StudentTasks extends AutoPlugin {
override def requires = super.requires && MOOCSettings
object autoImport {
val packageSourcesOnly = TaskKey[File]("packageSourcesOnly", "Package the sources of the project")
val packageBinWithoutResources = TaskKey[File]("packageBinWithoutResources", "Like packageBin, but without the resources")
val packageSubmissionZip = TaskKey[File]("packageSubmissionZip")
val packageSubmission = inputKey[Unit]("package solution as an archive file")
lazy val Grading = config("grading") extend(Runtime)
}
import autoImport._
import MOOCSettings.autoImport._
override lazy val projectSettings = Seq(
packageSubmissionSetting,
fork := true,
connectInput in run := true,
outputStrategy := Some(StdoutOutput),
) ++
packageSubmissionZipSettings ++
inConfig(Grading)(Defaults.testSettings ++ Seq(
unmanagedJars += file("grading-tests.jar"),
definedTests := (definedTests in Test).value,
internalDependencyClasspath := (internalDependencyClasspath in Test).value
))
/** **********************************************************
* SUBMITTING A SOLUTION TO COURSERA
*/
val packageSubmissionZipSettings = Seq(
packageSubmissionZip := {
val submission = crossTarget.value / "submission.zip"
val sources = (packageSourcesOnly in Compile).value
val binaries = (packageBinWithoutResources in Compile).value
IO.zip(Seq(sources -> "sources.zip", binaries -> "binaries.jar"), submission, None)
submission
},
artifactClassifier in packageSourcesOnly := Some("sources"),
artifact in (Compile, packageBinWithoutResources) ~= (art => art.withName(art.name + "-without-resources"))
) ++
inConfig(Compile)(
Defaults.packageTaskSettings(packageSourcesOnly, Defaults.sourceMappings) ++
Defaults.packageTaskSettings(packageBinWithoutResources, Def.task {
val relativePaths =
(unmanagedResources in Compile).value.flatMap(Path.relativeTo((unmanagedResourceDirectories in Compile).value)(_))
(mappings in (Compile, packageBin)).value.filterNot { case (_, path) => relativePaths.contains(path) }
})
)
val maxSubmitFileSize = {
val mb = 1024 * 1024
10 * mb
}
/** Check that the jar exists, isn't empty, isn't crazy big, and can be read
* If so, encode jar as base64 so we can send it to Coursera
*/
def prepareJar(jar: File, s: TaskStreams): String = {
val errPrefix = "Error submitting assignment jar: "
val fileLength = jar.length()
if (!jar.exists()) {
s.log.error(errPrefix + "jar archive does not exist\n" + jar.getAbsolutePath)
failSubmit()
} else if (fileLength == 0L) {
s.log.error(errPrefix + "jar archive is empty\n" + jar.getAbsolutePath)
failSubmit()
} else if (fileLength > maxSubmitFileSize) {
s.log.error(errPrefix + "jar archive is too big. Allowed size: " +
maxSubmitFileSize + " bytes, found " + fileLength + " bytes.\n" +
jar.getAbsolutePath)
failSubmit()
} else {
val bytes = new Array[Byte](fileLength.toInt)
val sizeRead = try {
val is = new FileInputStream(jar)
val read = is.read(bytes)
is.close()
read
} catch {
case ex: IOException =>
s.log.error(errPrefix + "failed to read sources jar archive\n" + ex.toString)
failSubmit()
}
if (sizeRead != bytes.length) {
s.log.error(errPrefix + "failed to read the sources jar archive, size read: " + sizeRead)
failSubmit()
} else encodeBase64(bytes)
}
}
/** Task to package solution to a given file path */
lazy val packageSubmissionSetting = packageSubmission := {
val args: Seq[String] = Def.spaceDelimited("[path]").parsed
val s: TaskStreams = streams.value // for logging
val jar = (packageSubmissionZip in Compile).value
val base64Jar = prepareJar(jar, s)
val path = args.headOption.getOrElse((baseDirectory.value / "submission.jar").absolutePath)
scala.tools.nsc.io.File(path).writeAll(base64Jar)
}
/*
/** Task to submit a solution to coursera */
val submit = inputKey[Unit]("submit solution to Coursera")
lazy val submitSetting = submit := {
// Fail if scalafix linting does not pass.
scalafixLinting.value
val args: Seq[String] = Def.spaceDelimited("<arg>").parsed
val s: TaskStreams = streams.value // for logging
val jar = (packageSubmissionZip in Compile).value
val assignmentDetails =
courseraId.?.value.getOrElse(throw new MessageOnlyException("This assignment can not be submitted to Coursera because the `courseraId` setting is undefined"))
val assignmentKey = assignmentDetails.key
val courseName =
course.value match {
case "capstone" => "scala-capstone"
case "bigdata" => "scala-spark-big-data"
case other => other
}
val partId = assignmentDetails.partId
val itemId = assignmentDetails.itemId
val premiumItemId = assignmentDetails.premiumItemId
val (email, secret) = args match {
case email :: secret :: Nil =>
(email, secret)
case _ =>
val inputErr =
s"""|Invalid input to `submit`. The required syntax for `submit` is:
|submit <email-address> <submit-token>
|
|The submit token is NOT YOUR LOGIN PASSWORD.
|It can be obtained from the assignment page:
|https://www.coursera.org/learn/$courseName/programming/$itemId
|${
premiumItemId.fold("") { id =>
s"""or (for premium learners):
|https://www.coursera.org/learn/$courseName/programming/$id
""".stripMargin
}
}
""".stripMargin
s.log.error(inputErr)
failSubmit()
}
val base64Jar = prepareJar(jar, s)
val json =
s"""|{
| "assignmentKey":"$assignmentKey",
| "submitterEmail":"$email",
| "secret":"$secret",
| "parts":{
| "$partId":{
| "output":"$base64Jar"
| }
| }
|}""".stripMargin
def postSubmission[T](data: String): Try[HttpResponse[String]] = {
val http = Http("https://www.coursera.org/api/onDemandProgrammingScriptSubmissions.v1")
val hs = List(
("Cache-Control", "no-cache"),
("Content-Type", "application/json")
)
s.log.info("Connecting to Coursera...")
val response = Try(http.postData(data)
.headers(hs)
.option(HttpOptions.connTimeout(10000)) // scalaj default timeout is only 100ms, changing that to 10s
.asString) // kick off HTTP POST
response
}
val connectMsg =
s"""|Attempting to submit "${assignment.value}" assignment in "$courseName" course
|Using:
|- email: $email
|- submit token: $secret""".stripMargin
s.log.info(connectMsg)
def reportCourseraResponse(response: HttpResponse[String]): Unit = {
val code = response.code
val respBody = response.body
/* Sample JSON response from Coursera
{
"message": "Invalid email or token.",
"details": {
"learnerMessage": "Invalid email or token."
}
}
*/
// Success, Coursera responds with 2xx HTTP status code
if (response.is2xx) {
val successfulSubmitMsg =
s"""|Successfully connected to Coursera. (Status $code)
|
|Assignment submitted successfully!
|
|You can see how you scored by going to:
|https://www.coursera.org/learn/$courseName/programming/$itemId/
|${
premiumItemId.fold("") { id =>
s"""or (for premium learners):
|https://www.coursera.org/learn/$courseName/programming/$id
""".stripMargin
}
}
|and clicking on "My Submission".""".stripMargin
s.log.info(successfulSubmitMsg)
}
// Failure, Coursera responds with 4xx HTTP status code (client-side failure)
else if (response.is4xx) {
val result = Try(Json.parse(respBody)).toOption
val learnerMsg = result match {
case Some(resp: JsObject) =>
(JsPath \ "details" \ "learnerMessage").read[String].reads(resp).get
case Some(x) => // shouldn't happen
"Could not parse Coursera's response:\n" + x
case None =>
"Could not parse Coursera's response:\n" + respBody
}
val failedSubmitMsg =
s"""|Submission failed.
|There was something wrong while attempting to submit.
|Coursera says:
|$learnerMsg (Status $code)""".stripMargin
s.log.error(failedSubmitMsg)
}
// Failure, Coursera responds with 5xx HTTP status code (server-side failure)
else if (response.is5xx) {
val failedSubmitMsg =
s"""|Submission failed.
|Coursera seems to be unavailable at the moment (Status $code)
|Check https://status.coursera.org/ and try again in a few minutes.
""".stripMargin
s.log.error(failedSubmitMsg)
}
// Failure, Coursera repsonds with an unexpected status code
else {
val failedSubmitMsg =
s"""|Submission failed.
|Coursera replied with an unexpected code (Status $code)
""".stripMargin
s.log.error(failedSubmitMsg)
}
}
// kick it all off, actually make request
postSubmission(json) match {
case Success(resp) => reportCourseraResponse(resp)
case Failure(e) =>
val failedConnectMsg =
s"""|Connection to Coursera failed.
|There was something wrong while attempting to connect to Coursera.
|Check your internet connection.
|${e.toString}""".stripMargin
s.log.error(failedConnectMsg)
}
}
*/
def failSubmit(): Nothing = {
sys.error("Submission failed")
}
/**
* *****************
* DEALING WITH JARS
*/
def encodeBase64(bytes: Array[Byte]): String =
new String(Base64.encodeBase64(bytes))
}
sbt.version=1.4.7
// Used for Coursera submission (StudentPlugin)
// libraryDependencies += "org.scalaj" %% "scalaj-http" % "2.4.2"
// libraryDependencies += "com.typesafe.play" %% "play-json" % "2.7.4"
// Used for Base64 (StudentPlugin)
libraryDependencies += "commons-codec" % "commons-codec" % "1.10"
// addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.28")
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.8.8")
addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.5.3")
package f2
import akka.actor._
import scala.collection.mutable
import akka.testkit.*
object F2 {
//////////////////////////////
// NOTIFICATION SERVICE //
//////////////////////////////
object NotificationService {
enum Protocol:
/** Notify all registered actors */
case NotifyAll
/** Register the actor that sent the `Register` request */
case Register //
/** Un-register the actor that sent the `Register` request */
case UnRegister
enum Responses:
/** Message sent to an actor when it is notified */
case Notification
/** Response sent to an actor after a `Register` or `UnRegister` */
case Registered(registered: Boolean)
}
class NotificationService extends Actor {
import NotificationService.Protocol.*
import NotificationService.Responses.*
private val registeredUsers = mutable.Set.empty[ActorRef]
def receive: Receive = {
case Register =>
registeredUsers += sender
sender ! Registered(true)
case UnRegister =>
registeredUsers -= sender
sender ! Registered(false)
case NotifyAll =>
for user <- registeredUsers do
user ! Notification
}
}
/////////////////////////
// DISCORD CHANNEL //
/////////////////////////
object DiscordChannel {
enum Protocol:
/** Post a message in the channel */
case Post(msg: String)
/** Ask for the list of most recent posts starting from the most recent one.
* The list must have at most `limit` posts.
*/
case GetLastPosts(limit: Int)
/** Activates the service channel using the provided notification service. */
case Init(notificationService: ActorRef)
enum Responses:
/** Response to `GetLastPosts` if active */
case Posts(msgs: List[String])
/** Response after `Init` if non-active */
case Active
/** Response `Post` and `GetLastPosts` if non-active */
case NotActive
/** Response after `Init` if active */
case AlreadyActive
}
class DiscordChannel extends Actor {
import DiscordChannel.Protocol.*
import DiscordChannel.Responses.*
import NotificationService.Protocol.*
private var messages: List[String] = Nil
def receive: Receive = nonActive
def nonActive: Receive = {
case Init(service) =>
context.become(active(service))
sender ! Active
case Post(_) | GetLastPosts(_) =>
sender ! NotActive
}
def active(notificationService: ActorRef): Receive = {
case Post(msg) =>
messages = msg :: messages
notificationService ! NotifyAll
case GetLastPosts(limit) =>
sender ! Posts(messages.take(limit))
case Init(_) =>
sender ! AlreadyActive
}
}
}
/////////////////////////
// DEBUG //
/////////////////////////
/** Infrastructure to help debugging. In sbt use `run` to execute this code.
* The TestKit is an actor that can send messages and check the messages it receives (or not).
*/
@main def debug() = new TestKit(ActorSystem("DebugSystem")) with ImplicitSender {
import F2.*
import DiscordChannel.Protocol.*
import DiscordChannel.Responses.*
import NotificationService.Protocol.*
import NotificationService.Responses.*
import concurrent.duration.*
try
val notificationService = system.actorOf(Props[NotificationService])
val channel = system.actorOf(Props[DiscordChannel])
notificationService ! NotifyAll
expectNoMessage(200.millis) // expects no message is received in the next 200 milliseconds
notificationService ! Register
expectMsg(200.millis, Registered(true)) // expects to receive `Registered(true)` in the next 200 milliseconds
finally shutdown(system)
}
package f2
import akka.actor._
import akka.testkit.*
import scala.collection.mutable
import concurrent.duration.*
import F2.*
class F2Suite extends munit.FunSuite {
import NotificationService.Protocol.*
import NotificationService.Responses.*
import DiscordChannel.Protocol.*
import DiscordChannel.Responses.*
test("Notification register (1pts)") {
new MyTestKit {
def tests() = {
val actor = system.actorOf(Props[NotificationService])
actor ! Register
expectMsg(2.second, Registered(true))
}
}
}
test("Notification register and un-register (1pts)") {
new MyTestKit {
def tests() = {
val actor = system.actorOf(Props[NotificationService])
actor ! Register
expectMsg(2.second, Registered(true))
actor ! UnRegister
expectMsg(2.second, Registered(false))
actor ! UnRegister
expectMsg(2.second, Registered(false))
actor ! Register
expectMsg(2.second, Registered(true))
actor ! UnRegister
expectMsg(2.second, Registered(false))
}
}
}
test("Notification notify (1pts)") {
new MyTestKit {
def tests() = {
val actor = system.actorOf(Props[NotificationService])
actor ! Register
expectMsg(2.second, Registered(true))
actor ! NotifyAll
expectMsg(2.second, Notification)
actor ! NotifyAll
expectMsg(2.second, Notification)
actor ! UnRegister
expectMsg(2.second, Registered(false))
actor ! NotifyAll
expectNoMessage(500.millis)
actor ! Register
expectMsg(2.second, Registered(true))
actor ! NotifyAll
expectMsg(2.second, Notification)
actor ! UnRegister
expectMsg(2.second, Registered(false))
actor ! NotifyAll
expectNoMessage(500.millis)
}
}
}
test("NotifyAll from other actor (1pts)") {
new MyTestKit {
def tests() = {
val actor = system.actorOf(Props[NotificationService])
val otherActor = system.actorOf(Props[DummyActor])
def notifyFormAllFromOtherActor() = {
given ActorRef = otherActor
actor ! NotifyAll
}
expectNoMessage(500.millis)
actor ! Register
expectMsg(2.second, Registered(true))
notifyFormAllFromOtherActor()
expectMsg(2.second, Notification)
}
}
}
test("Channel init (1pts)") {
new MyTestKit {
def tests() = {
val notificationService = system.actorOf(Props[NotificationService])
val channel = system.actorOf(Props[DiscordChannel])
channel ! Init(notificationService)
expectMsg(2.second, Active)
}
}
}
test("Channel post and get post (1pts)") {
new MyTestKit {
def tests() = {
val notificationService = system.actorOf(Props[NotificationService])
val channel = system.actorOf(Props[DiscordChannel])
channel ! Init(notificationService)
expectMsg(2.second, Active)
channel ! Post("hello")
channel ! GetLastPosts(1)
expectMsg(2.second, Posts(List("hello")))
channel ! GetLastPosts(10)
expectMsg(2.second, Posts(List("hello")))
channel ! GetLastPosts(0)
expectMsg(2.second, Posts(Nil))
}
}
}
test("Channel multiple posts (1pts)") {
new MyTestKit {
def tests() = {
val notificationService = system.actorOf(Props[NotificationService])
val channel = system.actorOf(Props[DiscordChannel])
channel ! Init(notificationService)
expectMsg(2.second, Active)
channel ! Post("hello")
channel ! Post("world")
channel ! GetLastPosts(2)
channel ! GetLastPosts(1)
channel ! Post("!")
channel ! GetLastPosts(3)
expectMsg(2.second, Posts(List("world", "hello")))
expectMsg(2.second, Posts(List("world")))
expectMsg(2.second, Posts(List("!", "world", "hello")))
}
}
}
test("Channel posts and notify (1pts)") {
new MyTestKit {
def tests() = {
val notificationService = system.actorOf(Props[NotificationService])
val channel = system.actorOf(Props[DiscordChannel])
channel ! Init(notificationService)
expectMsg(2.second, Active)
notificationService ! Register
expectMsg(2.second, Registered(true))
channel ! Post("hello")
channel ! Post("world")
expectMsg(2.second, Notification)
expectMsg(2.second, Notification)
}
}
}
test("Channel init twice (1pts)") {
new MyTestKit {
def tests() = {
val notificationService = system.actorOf(Props[NotificationService])
val channel = system.actorOf(Props[DiscordChannel])
channel ! Init(notificationService)
expectMsg(2.second, Active)
channel ! Init(notificationService)
expectMsg(2.second, AlreadyActive)
channel ! Init(notificationService)
expectMsg(2.second, AlreadyActive)
}
}
}
test("Channel not active (1pts)") {
new MyTestKit {
def tests() = {
val channel1 = system.actorOf(Props[DiscordChannel])
channel1 ! Post("hello")
expectMsg(2.second, NotActive)
val channel2 = system.actorOf(Props[DiscordChannel])
channel2 ! GetLastPosts(0)
expectMsg(2.second, NotActive)
}
}
}
abstract class MyTestKit extends TestKit(ActorSystem("TestSystem")) with ImplicitSender {
def tests(): Unit
try tests() finally shutdown(system)
}
}
class DummyActor extends Actor {
def receive: Receive = {
case _ => ()
}
}
# General
*.DS_Store
*.swp
*~
# Dotty
*.class
*.tasty
*.hasTasty
# sbt
target/
# IDE
.bsp
.bloop
.metals
.vscode
# datasets
stackoverflow-grading.csv
wikipedia-grading.dat
// Student tasks (i.e. submit, packageSubmission)
enablePlugins(StudentTasks)
course := "final"
assignment := "f3"
scalaVersion := "3.0.0-RC1"
scalacOptions ++= Seq("-language:implicitConversions", "-deprecation")
libraryDependencies += "org.scalameta" %% "munit" % "0.7.22"
val MUnitFramework = new TestFramework("munit.Framework")
testFrameworks += MUnitFramework
// Decode Scala names
testOptions += Tests.Argument(MUnitFramework, "-s")
testSuite := "f3.F3Suite"
File deleted
package sbt // To access the private[sbt] compilerReporter key
package filteringReporterPlugin
import Keys._
import ch.epfl.lamp._
object FilteringReporterPlugin extends AutoPlugin {
override lazy val projectSettings = Seq(
// Turn off warning coming from scalameter that we cannot fix without changing scalameter
compilerReporter in (Compile, compile) ~= { reporter => new FilteringReporter(reporter) }
)
}
class FilteringReporter(reporter: xsbti.Reporter) extends xsbti.Reporter {
def reset(): Unit = reporter.reset()
def hasErrors: Boolean = reporter.hasErrors
def hasWarnings: Boolean = reporter.hasWarnings
def printSummary(): Unit = reporter.printSummary()
def problems: Array[xsbti.Problem] = reporter.problems
def log(problem: xsbti.Problem): Unit = {
if (!problem.message.contains("An existential type that came from a Scala-2 classfile cannot be"))
reporter.log(problem)
}
def comment(pos: xsbti.Position, msg: String): Unit =
reporter.comment(pos, msg)
override def toString = s"CollectingReporter($reporter)"
}