<commit_before>/*
 Copyright 2013 Twitter, Inc.

 Licensed 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.
 */

package com.twitter.summingbird.storm

import backtype.storm.{ Config => BacktypeStormConfig, LocalCluster, Testing }
import backtype.storm.generated.StormTopology
import backtype.storm.testing.{ CompleteTopologyParam, MockedSources }
import com.twitter.algebird.{ MapAlgebra, Semigroup }
import com.twitter.storehaus.{ ReadableStore, JMapStore }
import com.twitter.storehaus.algebra.MergeableStore
import com.twitter.summingbird._
import com.twitter.summingbird.batch.{ BatchID, Batcher }
import com.twitter.summingbird.storm.spout.TraversableSpout
import com.twitter.summingbird.storm.option._
import com.twitter.summingbird.online._
import com.twitter.summingbird.memory._
import com.twitter.summingbird.planner._
import com.twitter.tormenta.spout.Spout
import com.twitter.util.Future
import java.util.{ Collections, HashMap, Map => JMap, UUID }
import java.util.concurrent.atomic.AtomicInteger
import org.scalatest.WordSpec
import org.scalacheck._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scala.collection.JavaConverters._
import scala.collection.mutable.{
  ArrayBuffer,
  HashMap => MutableHashMap,
  Map => MutableMap,
  SynchronizedBuffer,
  SynchronizedMap
}
import java.security.Permission

/**
 * Tests for Summingbird's Storm planner.
 */
class StormLaws extends WordSpec {
  import MapAlgebra.sparseEquiv

  // This is dangerous, obviously. The Storm platform graphs tested
  // here use the UnitBatcher, so the actual time extraction isn't
  // needed.
  implicit def extractor[T]: TimeExtractor[T] = TimeExtractor(_ => 0L)
  implicit val batcher = Batcher.unit

  val testFn = sample[Int => List[(Int, Int)]]

  implicit val storm = Storm.local(Map())

  def sample[T: Arbitrary]: T = Arbitrary.arbitrary[T].sample.get

  def genStore: (String, Storm#Store[Int, Int]) = TestStore.createStore[Int, Int]()

  def genSink: () => ((Int) => Future[Unit]) = () => { x: Int =>
    append(x)
    Future.Unit
  }

  def memoryPlanWithoutSummer(original: List[Int])(mkJob: (Producer[Memory, Int], Memory#Sink[Int]) => TailProducer[Memory, Int]): List[Int] = {
    val memory = new Memory
    val outputList = ArrayBuffer[Int]()
    val sink: (Int) => Unit = { x: Int => outputList += x }

    val job = mkJob(
      Memory.toSource(original),
      sink
    )
    val topo = memory.plan(job)
    memory.run(topo)
    outputList.toList
  }

  val outputList = new ArrayBuffer[Int] with SynchronizedBuffer[Int]

  def append(x: Int): Unit = {
    StormLaws.outputList += x
  }

  def runWithOutSummer(original: List[Int])(mkJob: (Producer[Storm, Int], Storm#Sink[Int]) => TailProducer[Storm, Int]): List[Int] = {
    val cluster = new LocalCluster()

    val job = mkJob(
      Storm.source(TraversableSpout(original)),
      Storm.sink[Int]({ (x: Int) => append(x); Future.Unit })
    )

    StormTestRun(job)
    StormLaws.outputList.toList
  }

  val nextFn = { pair: ((Int, (Int, Option[Int]))) =>
    val (k, (v, joinedV)) = pair
    List((k -> joinedV.getOrElse(10)))
  }

  val nextFn1 = { pair: ((Int, Option[Int])) =>
    val (v, joinedV) = pair
    List((joinedV.getOrElse(10)))
  }

  val serviceFn = sample[Int => Option[Int]]
  val service = ReadableServiceFactory[Int, Int](() => ReadableStore.fromFn(serviceFn))
  // ALL TESTS START AFTER THIS LINE

  "StormPlatform matches Scala for single step jobs" in {
    val original = sample[List[Int]]
    val returnedState =
      StormTestRun.simpleRun[Int, Int, Int](original,
        TestGraphs.singleStepJob[Storm, Int, Int, Int](_, _)(testFn)
      )

    assert(Equiv[Map[Int, Int]].equiv(
      TestGraphs.singleStepInScala(original)(testFn),
      returnedState.toScala
    ) == true)
  }

  "FlatMap to nothing" in {
    val original = sample[List[Int]]
    val fn = { (x: Int) => List[(Int, Int)]() }
    val returnedState =
      StormTestRun.simpleRun[Int, Int, Int](original,
        TestGraphs.singleStepJob[Storm, Int, Int, Int](_, _)(fn)
      )

    assert(Equiv[Map[Int, Int]].equiv(<commit_msg>Fix storm tests<commit_after>/*
 Copyright 2013 Twitter, Inc.

 Licensed 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.
 */

package com.twitter.summingbird.storm

import backtype.storm.{ Config => BacktypeStormConfig, LocalCluster, Testing }
import backtype.storm.generated.StormTopology
import backtype.storm.testing.{ CompleteTopologyParam, MockedSources }
import com.twitter.algebird.{ MapAlgebra, Semigroup }
import com.twitter.storehaus.{ ReadableStore, JMapStore }
import com.twitter.storehaus.algebra.MergeableStore
import com.twitter.summingbird._
import com.twitter.summingbird.batch.{ BatchID, Batcher }
import com.twitter.summingbird.storm.spout.TraversableSpout
import com.twitter.summingbird.storm.option._
import com.twitter.summingbird.online._
import com.twitter.summingbird.memory._
import com.twitter.summingbird.planner._
import com.twitter.tormenta.spout.Spout
import com.twitter.util.Future
import java.util.{ Collections, HashMap, Map => JMap, UUID }
import java.util.concurrent.atomic.AtomicInteger
import org.scalatest.WordSpec
import org.scalacheck._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scala.collection.JavaConverters._
import scala.collection.mutable.{
  ArrayBuffer,
  HashMap => MutableHashMap,
  Map => MutableMap,
  SynchronizedBuffer,
  SynchronizedMap
}
import java.security.Permission

/**
 * Tests for Summingbird's Storm planner.
 */
object StormLaws {
  val outputList = new ArrayBuffer[Int] with SynchronizedBuffer[Int]

  // This is dangerous, obviously. The Storm platform graphs tested
  // here use the UnitBatcher, so the actual time extraction isn't
  // needed.
  implicit def extractor[T]: TimeExtractor[T] = TimeExtractor(_ => 0L)
  implicit val batcher = Batcher.unit

  val testFn = sample[Int => List[(Int, Int)]]

  implicit val storm = Storm.local(Map())

  def sample[T: Arbitrary]: T = Arbitrary.arbitrary[T].sample.get

  def genStore: (String, Storm#Store[Int, Int]) = TestStore.createStore[Int, Int]()

  def genSink: () => ((Int) => Future[Unit]) = () => { x: Int =>
    append(x)
    Future.Unit
  }

  def memoryPlanWithoutSummer(original: List[Int])(mkJob: (Producer[Memory, Int], Memory#Sink[Int]) => TailProducer[Memory, Int]): List[Int] = {
    val memory = new Memory
    val outputList = ArrayBuffer[Int]()
    val sink: (Int) => Unit = { x: Int => outputList += x }

    val job = mkJob(
      Memory.toSource(original),
      sink
    )
    val topo = memory.plan(job)
    memory.run(topo)
    outputList.toList
  }

  def append(x: Int): Unit = {
    StormLaws.outputList += x
  }

  def runWithOutSummer(original: List[Int])(mkJob: (Producer[Storm, Int], Storm#Sink[Int]) => TailProducer[Storm, Int]): List[Int] = {
    val cluster = new LocalCluster()

    val job = mkJob(
      Storm.source(TraversableSpout(original)),
      Storm.sink[Int]({ (x: Int) => append(x); Future.Unit })
    )

    StormTestRun(job)
    StormLaws.outputList.toList
  }

  val nextFn = { pair: ((Int, (Int, Option[Int]))) =>
    val (k, (v, joinedV)) = pair
    List((k -> joinedV.getOrElse(10)))
  }

  val nextFn1 = { pair: ((Int, Option[Int])) =>
    val (v, joinedV) = pair
    List((joinedV.getOrElse(10)))
  }

  val serviceFn = sample[Int => Option[Int]]
  val service = ReadableServiceFactory[Int, Int](() => ReadableStore.fromFn(serviceFn))

}

// ALL TESTS START GO IN THE CLASS NOT OBJECT

class StormLaws extends WordSpec {
  import StormLaws._
  import MapAlgebra.sparseEquiv

  "StormPlatform matches Scala for single step jobs" in {
    val original = sample[List[Int]]
    val returnedState =
      StormTestRun.simpleRun[Int, Int, Int](original,
        TestGraphs.singleStepJob[Storm, Int, Int, Int](_, _)(testFn)
      )

    assert(Equiv[Map[Int, Int]].equiv(
      TestGraphs.singleStepInScala(original)(testFn),
      returnedState.toScala
    ) == true)
  }

  "FlatMap to nothing" in {
    val original = sample[List[Int]]
    val fn = { (x: Int) => List[(Int, Int)]() }
    val returnedState =
      StormTestRun.simpleRun[Int, Int, Int](original,
        TestGraphs.singleStepJob[Storm, Int, Int, Int](_, _)(fn)
      )

    assert(Equiv[Map[Int, Int]].equiv(
{'fraction_non_alphanumeric': 0.12214154112929446, 'fraction_numerical': 0.0030345724504172535, 'mean_word_length': 4.007053716766142, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 45, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5531450', 'n_tokens_mistral': 3002, 'n_tokens_neox': 2932, 'n_words': 780}