title,body,link,tags,view_count,is_answered,score,answer_count
Selenium and Database testing,"<p>I am totally new to the web application and automation testing.
I am learning selenium from youtube videos and developing frameworks.
while looking into the videos most of them cover only testing the Application as such.</p>

<p>I found very few videos which state about interacting with the database and verifying them.
I just wanted to know how will this be in real time projects?
In real time projects will they automating scenarios like configuring something in the UI, then validating it in the database, coming back to the UI and continuing the UI flow or will it be simply only verifying the UI.</p>

<p>I want to know more about how to do database testing.</p>

<p>Any info here will be of great help</p>
",https://stackoverflow.com/questions/44086493/selenium-and-database-testing,"['selenium', 'testing', 'automation']",108,TRUE,1,1
Database testing in Selenium,"<p>I have a question like i have multiple tables in database and I'm fetching data from the db.
So for one table i would fetch record and save it in a list and use it.</p>

<p>So if i have more than one tables in my database shall i keep on storing them in different Result set objects and creating new list for every table accordingly?Also do i have use another loop for second result set object (rs1) as shown below:</p>

<pre><code>ResultSet rs=stm.executeQuery(""select * from logincred""); Table 1
ResultSet rs1=stm.executeQuery(""select * from home"");     Table 2


ResultSetMetaData metadata=rs.getMetaData();
            int colCount=metadata.getColumnCount();
            System.out.println(colCount);

            while(rs.next()){
                for(int i=1;i&lt;=colCount;i++){       
                    String result=rs.getString(i);
                    System.out.println(result + "" : "");
                    listOfLoginCred.add(result);
                    System.out.println(listOfLoginCred);
                }

            }
</code></pre>
",https://stackoverflow.com/questions/42043387/database-testing-in-selenium,"['java', 'database']",47,FALSE,0,0
Java Elasticsearch database testing,"<p>i'm currently using ES 5 and Jest in a project i'm working in, and i was assigned to to integration and unit testing on the classes that interact with the DB.</p>

<p>lets asume i have a method like this:</p>

<pre><code> @Override
public Aptitude save(Aptitude aptitude) {
    Index index = new Index.Builder(aptitude).index(aptitudeIndexName).type(aptitudeTypeName).refresh(true).build();
    try {
        client.execute(index);
        return aptitude;
    } catch (IOException e) {
        logger.error(""The aptitude couldn't be saved in the data base "" + e.getMessage());
        throw new RuntimeException(e);
    }
}
</code></pre>

<p>or one like this:</p>

<pre><code>@Override
public List&lt;Aptitude&gt; findAll() {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    searchSourceBuilder.sort(""id"", SortOrder.ASC);

    Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(aptitudeIndexName).build();

    try {
        SearchResult result = client.execute(search);

        if (!result.isSucceeded()) {
            return null;
        }

        List&lt;Hit&lt;Aptitude, Void&gt;&gt; aptitudes = result.getHits(Aptitude.class);
        return aptitudes.stream().map(this::getAptitude).collect(Collectors.toList());
    } catch (IOException e) {
        logger.error(""The search couldn't be executed"" + e.getMessage());
        throw new RuntimeException(e);
    }
}
</code></pre>

<p>and my task is to write some test (unit and integration) to make sure all my classes are working correctly and to have better test coverage, i searched a bit online for ES testing but can quite grasp how im supposed to make the tests.</p>

<p>i made some tests that looked like this:</p>

<pre><code>@Test
public void aptitudeSaveDelete() {
    Aptitude aptitude = new Aptitude();
    aptitude.setId(1993L);
    aptitude.setEn(""ENaptitudeEN"");
    aptitude.setEs(""ESaptitudeES"");
    Aptitude aptitudeSaved = elasticsearchAptitudeRepository.save(aptitude);

    assertEquals(aptitude.getEs(), aptitudeSaved.getEs());
    assertEquals(aptitude.getEn(), aptitudeSaved.getEn());
    assertEquals(aptitude.getId(), aptitudeSaved.getId());

    Aptitude aptitudeFoundById = elasticsearchAptitudeRepository.findById(String.valueOf(aptitude.getId()));

    assertEquals(aptitude.getId(), aptitudeFoundById.getId());
    assertEquals(aptitude.getEn(), aptitudeFoundById.getEn());
    assertEquals(aptitude.getEs(), aptitudeFoundById.getEs());

    boolean wasDeleted;
    wasDeleted = elasticsearchAptitudeRepository.deleteAptitudeById(String.valueOf(aptitude.getId()));
    assertEquals(true, wasDeleted);
}
</code></pre>

<p>but my coworkers told me that this kind of test compromised the DB and that in case something went wrong with them then the DB would had to be repaired manually.</p>

<p>so that is why im at a loss here, any kind of help is apreciated</p>
",https://stackoverflow.com/questions/42653797/java-elasticsearch-database-testing,"['java', 'unit-testing', 'elasticsearch', 'integration-testing', 'elasticsearch-jest']",596,TRUE,0,1
How to Approach Database Testing,"<p>I am currently working on building a URL shortener using Flask. I feel fairly comfortable writing the code for the application, however, I am having a bit of trouble figuring out how to write the tests. </p>

<p>The MVP for the application does 2 functions:</p>

<p>(1) Given a long url in a post, returns a short url</p>

<p>(2) Given a short url in a get, redirects to the destination</p>

<p>My general code structure is as follows</p>

<pre><code>url_shortener
    url_shortener
       controller.py
       setup.sh # sets up virtual env, installs requirements, creates database if it doesn't exist, spins up application
       lib/ # contains functionality to shorten urls
       tests/ # Unit, integration, etc tests
</code></pre>

<p>From what I've read, I believe I would want to set up a fresh instance of a database for each unit test I have. For example, say I wanted to test that the first long url -> short url conversion yielded <a href=""http://myendpointurl/0"" rel=""nofollow noreferrer"">http://myendpointurl/0</a>. This wouldn't work if I used the application's ""real"" database if there was anything already in it. Conceptually, I understand what I need to do, however, I am getting confused as to how to put it into code. </p>

<p>I've tried looking around for a few examples but am having trouble finding ones that don't have a lot of new and unfamiliar technologies (example: <a href=""https://github.com/cgil/shortener"" rel=""nofollow noreferrer"">https://github.com/cgil/shortener</a> - I haven't worked with fab files, alembic, nose for testing (I use py.test), etc) or ones with tests (ex: <a href=""https://github.com/richyvk/flask-url-shortener"" rel=""nofollow noreferrer"">https://github.com/richyvk/flask-url-shortener</a>). </p>

<ul>
<li>Does anyone know if there is existing documentation that walks you through this at a somewhat beginner level? I'm pretty good with most non-web application Python, have built 1 flask endpoint before, and generally use py.test. </li>
<li>If not, if someone could help elaborate on how to approach this, that would be wonderful. </li>
</ul>
",https://stackoverflow.com/questions/43033829/how-to-approach-database-testing,"['python', 'unit-testing', 'flask']",89,FALSE,0,1
How to change database testing,"<p>I use spring boot 2.0 and use Postgres for database part.</p>

<p>Is there a way to use postgres database instead of memory database or something h2 or hsqldb for testing?</p>
",https://stackoverflow.com/questions/45215954/how-to-change-database-testing,['spring-boot'],1915,TRUE,0,2
Karate - Database testing - getting timestamp displayed as nano,"<p>I am trying to run some basic database tests using Karate and Spring JDBC ( as mentioned in DBUtils class in Demo Project).</p>

<p>Here is what I am doing:</p>

<pre><code> Background:
    # Read url/username/pwd and provide it to the class
    * def config = read('env_file.json')
    * def DbUtils = Java.type('DbConnection')
    * def db = new DbUtils(config)

 Scenario: Validate the modd_ts is present in lob table

    * def createdTs = db.readRows('SELECT crtd_ts FROM tableA ')
    * print createdTs
</code></pre>

<p>Here is what it returns:</p>

<pre><code>com.intuit.karate - [print] [{""crtd_ts"":{""nanos"":0}},{""crtd_ts"":{""nanos"":0}}
</code></pre>

<p>Not sure why it should return timestamp as ""nanos"":0 , seems a bug to me . Please confirm and I will open one in github.</p>
",https://stackoverflow.com/questions/46961265/karate-database-testing-getting-timestamp-displayed-as-nano,['karate'],1727,TRUE,1,1
Trouble with Slick/Postgres database testing in Play2/Specs2,"<p>I have been having a lot of trouble building an application test and was hoping someone with some more Scala experience could point me in the right direction.</p>

<p>I have a number of data models that reside in a Postgres database, mapped to case classes using Slick.  My Play app then provides JSON based REST endpoints to said data models.
Since most of the actual code is similar between each endpoint, most of the code is implemented as a trait which is mixed in to the actual controllers which over-ride the necessary bits.</p>

<p>This works fine, but when I try to run unit tests on each of them most controllers work then I end up with the error:</p>

<pre><code>[error] Can't find a constructor for class helpers.DatabaseHelper
[warn] c.z.h.HikariConfig - The jdbcConnectionTest property is now deprecated, see the documentation for connectionTestQuery
[error]
[error] cannot create an instance for class FileControllerSpec
[error]   caused by java.sql.SQLTransientConnectionException: db - Connection is not available, request timed out after 1005ms.
[error]   caused by org.postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication superuser connections
[error]
[error] STACKTRACE
[error]   sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[error]   sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[error]   sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[error]   java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[error]   org.specs2.reflect.Classes$$anonfun$org$specs2$reflect$Classes$$createInstanceForConstructor$1.apply(Classes.scala:104)
[error]   org.specs2.control.ActionT$$anonfun$safe$1.apply(ActionT.scala:88)
[error]   org.specs2.control.ActionT$$anonfun$reader$1$$anonfun$apply$6.apply(ActionT.scala:79)
[error]   org.specs2.control.Status$.safe(Status.scala:100)
[error]   org.specs2.control.StatusT$$anonfun$safe$1.apply(StatusT.scala:62)
[error]   org.specs2.control.StatusT$$anonfun$safe$1.apply(StatusT.scala:62)
[error]   scalaz.syntax.ToApplicativeOps$$anon$1.self$lzycompute(ApplicativeSyntax.scala:29)
[error]   scalaz.syntax.ToApplicativeOps$$anon$1.self(ApplicativeSyntax.scala:29)
[error]   scalaz.syntax.ToApplicativeOps$ApplicativeIdV$$anonfun$point$1.apply(ApplicativeSyntax.scala:33)
[error]   scalaz.WriterTApplicative$$anonfun$point$1.apply(WriterT.scala:282)
[error]   scalaz.WriterTApplicative$$anonfun$point$1.apply(WriterT.scala:282)
[error]   scalaz.effect.IO$$anonfun$apply$19$$anonfun$apply$20.apply(IO.scala:136)
[error]   scalaz.effect.IO$$anonfun$apply$19$$anonfun$apply$20.apply(IO.scala:136)
[error]   scalaz.FreeFunctions$$anonfun$return_$1.apply(Free.scala:326)
[error]   scalaz.FreeFunctions$$anonfun$return_$1.apply(Free.scala:326)
[error]   scalaz.std.FunctionInstances$$anon$1$$anonfun$map$1.apply(Function.scala:56)
[error]   scalaz.Free$$anonfun$run$1.apply(Free.scala:172)
[error]   scalaz.Free$$anonfun$run$1.apply(Free.scala:172)
[error]   scalaz.Free.go2$1(Free.scala:119)
[error]   scalaz.Free.go(Free.scala:122)
[error]   scalaz.Free.run(Free.scala:172)
[error]   scalaz.effect.IO$class.unsafePerformIO(IO.scala:22)
[error]   scalaz.effect.IOFunctions$$anon$6.unsafePerformIO(IO.scala:227)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1$$anonfun$3.apply(Classes.scala:37)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1$$anonfun$3.apply(Classes.scala:36)
[error]   scala.collection.immutable.List.map(List.scala:273)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1.apply(Classes.scala:36)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1.apply(Classes.scala:29)
[error]   scala.Function1$$anonfun$andThen$1.apply(Function1.scala:52)
[error]   org.specs2.control.Status$class.fold(Status.scala:30)
[error]   org.specs2.control.Ok.fold(Status.scala:95)
[error]   org.specs2.control.Status$class.flatMap(Status.scala:48)
[error]   org.specs2.control.Ok.flatMap(Status.scala:95)
[error]   org.specs2.control.Status$class.map(Status.scala:45)
[error]   org.specs2.control.Ok.map(Status.scala:95)
[error]   org.specs2.control.StatusT$$anonfun$map$1.apply(StatusT.scala:16)
[error]   org.specs2.control.StatusT$$anonfun$map$1.apply(StatusT.scala:16)
[error]   scalaz.WriterT$$anonfun$map$1.apply(WriterT.scala:46)
[error]   scalaz.WriterT$$anonfun$map$1.apply(WriterT.scala:46)
[error]   scalaz.effect.IO$$anonfun$map$1$$anonfun$apply$8.apply(IO.scala:56)
[error]   scalaz.effect.IO$$anonfun$map$1$$anonfun$apply$8.apply(IO.scala:55)
[error]   scalaz.Free$$anonfun$map$1.apply(Free.scala:52)
[error]   scalaz.Free$$anonfun$map$1.apply(Free.scala:52)
[error]   scalaz.Free$$anonfun$flatMap$1$$anonfun$apply$1.apply(Free.scala:60)
[error]   scalaz.Free$$anonfun$flatMap$1$$anonfun$apply$1.apply(Free.scala:60)
[error]   scalaz.Free.resume(Free.scala:72)
[error]   scalaz.Free.go2$1(Free.scala:118)
[error]   scalaz.Free.go(Free.scala:122)
[error]   scalaz.Free.run(Free.scala:172)
[error]   scalaz.effect.IO$class.unsafePerformIO(IO.scala:22)
[error]   scalaz.effect.IOFunctions$$anon$6.unsafePerformIO(IO.scala:227)
[error]   org.specs2.runner.SbtRunner$$anonfun$newTask$1$$anon$4.execute(SbtRunner.scala:37)
[error]   sbt.ForkMain$Run$2.call(ForkMain.java:294)
[error]   sbt.ForkMain$Run$2.call(ForkMain.java:284)
[error]   java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[error]   java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[error]   java.lang.Thread.run(Thread.java:745)
</code></pre>

<p>DatabaseHelper is an object that sets up my test data.</p>

<p>Reducing the number of specs makes the error go away, so I know that the issue is not with that particular test spec.</p>

<p>I am using runtime DI as recommended by the Play documentation and over-riding the database binding for testing to avoid blanking my development database.</p>

<p>I am using Play evolutions to manage the database schema, but intentionally blanking the database and re-setting it up during setup/teardown in order to ensure that it is pristine before each test spec.</p>

<p>I think that what is going on is that all of my test specs are being initialised at the same time, which means that they all try to connect to the database at the same time and it therefore runs out of connections.</p>

<p>I have tried using the parallelExecution and concurrentRestrictions settings in sbt to set only one process going at a time but this is to no avail.  I've tried setting each spec to run sequentially as well but this seems not to work.  I have also tried catching the exception and retrying the setup but this seems not to work either.</p>

<p>I am now at a loss as to what to try to make my tests work!  Please help.</p>

<p>Thanks a lot.</p>

<hr>

<p>Test case:</p>

<pre><code>@RunWith(classOf[JUnitRunner])
class FileControllerSpec extends GenericControllerSpec {
  sequential

  override val componentName: String = ""FileController""
  override val uriRoot: String = ""/file""

  override def testParsedJsonObject(checkdata: JsLookupResult, parsed_test_json: JsValue) = {
    val object_keys = Seq(""filepath"",""user"",""ctime"",""mtime"",""atime"")
    val object_keys_int = Seq(""storage"",""version"")

    object_keys.map(key=&gt;
      (checkdata \ key).as[String] must equalTo((parsed_test_json \ key).as[String])
    ) ++ object_keys_int.map(key=&gt;
      (checkdata \ key).as[Int] must equalTo((parsed_test_json \ key).as[Int])
    )
  }

  override val testGetId: Int = 3
  override val testGetDocument: String = """"""{""filepath"":""/path/to/a/video.mxf"",""storage"":1,""user"":""me"",""version"":1,""ctime"":""1970-01-01T04:25:45.678+0100"",""mtime"":""1970-01-01T04:25:45.678+0100"",""atime"":""1970-01-01T04:25:45.678+0100""}""""""
  override val testCreateDocument: String =  """"""{""filepath"":""/path/to/some/other.project"",""storage"":1,""user"":""test"",""version"":3,""ctime"":""2017-03-17T13:51:00.123+0000"",""mtime"":""2017-03-17T13:51:00.123+0000"",""atime"":""2017-03-17T13:51:00.123+0000""}""""""
  override val minimumNewRecordId = 3
  override val testDeleteId: Int = 2
  override val testConflictId: Int = -1
}
</code></pre>

<p>GenericControllerSpec:</p>

<pre><code>@RunWith(classOf[JUnitRunner])
trait GenericControllerSpec extends Specification with BeforeAfterAll {
  //can over-ride bindings here. see https://www.playframework.com/documentation/2.5.x/ScalaTestingWithGuice
  val application:Application = new GuiceApplicationBuilder()
    .overrides(bind[DatabaseConfigProvider].to[TestDatabase.testDbProvider])
    .build

  val injector:Injector = new GuiceApplicationBuilder()
      .overrides(bind[DatabaseConfigProvider].to[TestDatabase.testDbProvider])
      .injector()

  def inject[T : ClassTag]: T = injector.instanceOf[T]

  //needed for body.consumeData
  implicit val system = ActorSystem(""storage-controller-spec"")
  implicit val materializer = ActorMaterializer()

  protected val databaseHelper:DatabaseHelper = inject[DatabaseHelper]

  val logger: Logger = Logger(this.getClass)

  override def beforeAll(): Unit ={
    logger.warn(""&gt;&gt;&gt;&gt; before all &lt;&lt;&lt;&lt;"")
    val theFuture = databaseHelper.setUpDB().map({
      case Success(result)=&gt;logger.info(""DB setup successful"")
      case Failure(error)=&gt;logger.error(s""DB setup failed: $error"")
    })

    Await.result(theFuture, 10.seconds)
  }

  override def afterAll(): Unit ={
    logger.warn(""&lt;&lt;&lt;&lt; after all &gt;&gt;&gt;&gt;"")
    Await.result(databaseHelper.teardownDB(), 10.seconds)
  }

  val componentName:String
  val uriRoot:String

  def testParsedJsonObject(checkdata:JsLookupResult,test_parsed_json:JsValue):Seq[MatchResult[Any]]

  val testGetId:Int
  val testGetDocument:String
  val testCreateDocument:String
  val testDeleteId:Int
  val testConflictId:Int
  val minimumNewRecordId:Int

  def bodyAsJsonFuture(response:Future[play.api.mvc.Result]) = response.flatMap(result=&gt;
    result.body.consumeData.map(contentBytes=&gt; {
      logger.debug(contentBytes.decodeString(""UTF-8""))
      Json.parse(contentBytes.decodeString(""UTF-8""))
    }
    )
  )

  componentName should {

    ""return 400 on a bad request"" in {
      logger.debug(s""$uriRoot/boum"")
      val response = route(application,FakeRequest(GET, s""$uriRoot/boum"")).get
      status(response) must equalTo(BAD_REQUEST)
    }

    ""return valid data for a valid record"" in  {
      logger.warn(s""Test URL is $uriRoot/1"")
      val response:Future[play.api.mvc.Result] = route(application, FakeRequest(GET, s""$uriRoot/1"")).get

      status(response) must equalTo(OK)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ ""status"").as[String] must equalTo(""ok"")
      (jsondata \ ""result"" \ ""id"").as[Int] must equalTo(1)
      testParsedJsonObject(jsondata \ ""result"", Json.parse(testGetDocument))
    }

    ""accept new data to create a new record"" in {
      val response = route(application, FakeRequest(
        method=""PUT"",
        uri=uriRoot,
        headers=FakeHeaders(Seq((""Content-Type"", ""application/json""))),
        body=testCreateDocument)
      ).get

      status(response) must equalTo(OK)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ ""status"").as[String] must equalTo(""ok"")
      (jsondata \ ""detail"").as[String] must equalTo(""added"")
      (jsondata \ ""id"").as[Int] must greaterThanOrEqualTo(minimumNewRecordId) //if we re-run the tests without blanking the database explicitly this goes up

      val newRecordId = (jsondata \ ""id"").as[Int]
      val checkResponse = route(application, FakeRequest(GET, s""$uriRoot/$newRecordId"")).get
      val checkdata = Await.result(bodyAsJsonFuture(checkResponse), 5.seconds)


      (checkdata \ ""status"").as[String] must equalTo(""ok"")
      (checkdata \ ""result"" \ ""id"").as[Int] must equalTo(newRecordId)
      testParsedJsonObject(checkdata \ ""result"", Json.parse(testCreateDocument))
    }

    ""delete a record"" in {
      val response = route(application, FakeRequest(
        method=""DELETE"",
        uri=s""$uriRoot/$testDeleteId"",
        headers=FakeHeaders(),
        body="""")
      ).get

      status(response) must equalTo(OK)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ ""status"").as[String] must equalTo(""ok"")
      (jsondata \ ""detail"").as[String] must equalTo(""deleted"")
      (jsondata \ ""id"").as[Int] must equalTo(testDeleteId)
    }

    ""return conflict (409) if attempting to delete something with sub-objects"" in {
      val response = route(application, FakeRequest(
        method = ""DELETE"",
        uri = s""$uriRoot/$testConflictId"",
        headers = FakeHeaders(),
        body = """")
      ).get

      status(response) must equalTo(CONFLICT)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ ""status"").as[String] must equalTo(""error"")
      (jsondata \ ""detail"").as[String] must equalTo(""This is still referenced by sub-objects"")
    }
  }
}
</code></pre>

<p>DatabaseHelper:</p>

<pre><code>class DatabaseHelper @Inject()(configuration: Configuration, dbConfigProvider: DatabaseConfigProvider) {

  private val dbConfig = dbConfigProvider.get[JdbcProfile]
  private val logger: Logger = Logger(this.getClass)

  def setUpDB():Future[Try[Unit]] = {
    logger.warn(""In setUpDB"")
    dbConfig.db.run(
      DBIO.seq(
        (TableQuery[FileAssociationRow].schema ++
          TableQuery[FileEntryRow].schema ++
          TableQuery[ProjectEntryRow].schema ++
          TableQuery[ProjectTemplateRow].schema ++
          TableQuery[ProjectTypeRow].schema ++
          TableQuery[StorageEntryRow].schema
        ).create,
        TableQuery[StorageEntryRow] += StorageEntry(None,None,""filesystem"",Some(""me""),None,None,None),
        TableQuery[StorageEntryRow] += StorageEntry(None,None,""omms"",Some(""you""),None,None,None),
        TableQuery[FileEntryRow] += FileEntry(None,""/path/to/a/video.mxf"",1,""me"",1,new Timestamp(12345678),new Timestamp(12345678),new Timestamp(12345678)),
        TableQuery[FileEntryRow] += FileEntry(None,""/path/to/secondtestfile"",1,""tstuser"",1,new Timestamp(123456789),new Timestamp(123456789),new Timestamp(123456789)),
        //""""""{""name"": ""Premiere test template 1"",""projectTypeId"": 1,""filepath"", ""storageId"": 1}""""""
        //""{""name"":,""opensWith"":""AdobePremierePro.app"",""targetVersion"":""14.0""}""
        TableQuery[ProjectTypeRow] += ProjectType(None,""Premiere 2014 test"",""AdobePremierePro.app"",""14.0""),
        TableQuery[ProjectTypeRow] += ProjectType(None,""Cubase 7.0 test"",""Cubase.app"",""7.0""),
        TableQuery[ProjectTemplateRow] += ProjectTemplate(Some(1),""Premiere test template 1"",1,""/srv/projectfiles/ProjectTemplatesDev/Premiere/premiere_template_2014.prproj"",1)

      ).asTry
    )
  }

  def teardownDB():Future[Try[Unit]] = {
    logger.warn(""In teardownDB"")
    dbConfig.db.run(
      DBIO.seq(
        (
          TableQuery[FileAssociationRow].schema ++
            TableQuery[FileEntryRow].schema ++
            TableQuery[ProjectEntryRow].schema ++
            TableQuery[ProjectTemplateRow].schema ++
            TableQuery[ProjectTypeRow].schema ++
            TableQuery[StorageEntryRow].schema
        ).drop
      ).asTry
    )
  }
}
</code></pre>

<p>build.sbt settings:</p>

<pre><code>concurrentRestrictions in Global := Seq(
  Tags.limit(Tags.Test, 1),
  Tags.limitAll(1)
)

parallelExecution in Test := false
</code></pre>
",https://stackoverflow.com/questions/44968782/trouble-with-slick-postgres-database-testing-in-play2-specs2,"['postgresql', 'scala', 'slick', 'specs2']",656,TRUE,0,1
PHPUnit Database Testing: How To Use Dataset Per Test?,"<p>I want to seed a database table(s) with data, perform some operations using the library I'm building, and finally test those table(s) against another dataset of expected values. I'm using yaml files.</p>

<p>So far I can get this working with this code:</p>

<pre><code>/* ... */

public function getDataSet() {
  return new \PHPUnit_Extensions_Database_DataSet_YamlDataSet('path/to/yaml/data');
}

/* ... */

public function testFoo() {
  // setup state and run operations

  // load expected data to test against
  $expected = new \PHPUnit_Extensions_Database_DataSet_YamlDataSet('path/to/expected/yaml');
  static::assertTablesEqual($expected-&gt;getTable('foo'), $this-getConnection()-&gt;createDataSet('foo'));
}
</code></pre>

<p>I would like to just be able to do</p>

<pre><code>// fooSeedData.yml
foo:
  - id: 1
  # ...


// fooExpectedData.yml
foo_test1:
# ...

foo_test2:
# ...

// fooTest.php
public function foo_test1() {
  /* ... */
  $expected-&gt;getTable('foo_test1')
  /* ... */
}

public function foo_test2() {
  /* ... */
  $expected-&gt;getTable('foo_test2')
  /* ... */
}
</code></pre>

<p>but <code>static::assertTablesEqual($expected, $actual);</code> compares table names along with the data. Requiring a dataset file per test. Having numerous dataset files seems excessive which makes me think I'm doing something wrong.</p>

<p>Is there a way to do this? Am I using phpunit/dbunit wrong? If so how should I be doing this? Any help is appreciated!</p>
",https://stackoverflow.com/questions/47291001/phpunit-database-testing-how-to-use-dataset-per-test,"['php', 'unit-testing', 'phpunit', 'dbunit']",728,TRUE,0,1
Should Protractor can also be used for database testing directly?,"<p>As protractor is primarily for end-to-end testing, so to cover user like high level scenarios on the UI level, </p>

<blockquote>
  <p>should we use it to test database directly as well?</p>
</blockquote>

<p>by establishing db connectivity and firing queries to verify the database states may be before &amp; after the user actions in the UI ?</p>

<p>or </p>

<p>for plain direct db testing to check stored procedures to test business rules/functionality? </p>

<p>which one is the correct one, and what is the right way to use it with protractor?</p>
",https://stackoverflow.com/questions/41527135/should-protractor-can-also-be-used-for-database-testing-directly,"['database', 'protractor']",1657,TRUE,1,1
How to make unit test data dynamic for sql database testing via sqlalchemy and py.test?,"<p>I'm developing unit test for CRUD operation on my database via py.test. </p>

<p>The issue is creating test data is becoming a hassle as the database keep growing. I'm currently making dictionaries manually and checking values. </p>

<p>My concern is, this may not be the proper way going forward. 
How can I make mock data for CRUD operation more dynamic?</p>
",https://stackoverflow.com/questions/43145623/how-to-make-unit-test-data-dynamic-for-sql-database-testing-via-sqlalchemy-and-p,"['mysql', 'python-2.7', 'unit-testing', 'sqlalchemy', 'pytest']",404,FALSE,0,0
Connect to Microsoft SQL Server Management using Selenium (Java),"<p>In my project we are using Microsoft SQL Server Management Studio for database testing and now we need to automate some flows that involves database testing. Below is the pre-login screenshot where we used to enter the servername as required, authentication as ""Windows authentication"". Then the username will automatically populate and there is no need to enter the password.</p>

<p><a href=""https://i.stack.imgur.com/CeHkF.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/CeHkF.png"" alt=""enter image description here""></a></p>

<p>So to connect to the database I am using the below code but while executing I am getting error as ""Login failed for user PILOTCORP\chatterp"".</p>

<pre><code>Class.forName(""com.microsoft.sqlserver.jdbc.SQLServerDriver"");
Connection con=DriverManager.getConnection(""jdbc:sqlserver://ipaddress:portnumber;Databases=knxfpdbscrum\\FuelPact"",""username"",""password"");
Statement st= con.createStatement();
</code></pre>

<p>In the code I have entered the database name as ""knxfpdbscrum\FuelPact"" since we need to select Database name as FuelPact.</p>

<p><a href=""https://i.stack.imgur.com/ESaxq.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ESaxq.png"" alt=""enter image description here""></a></p>

<p>Please help me.</p>
",https://stackoverflow.com/questions/46400698/connect-to-microsoft-sql-server-management-using-selenium-java,"['java', 'sql-server', 'selenium', 'jdbc']",2113,FALSE,0,0
Querying multiple values,"<p>I'm trying to filter by multiple values however I can't seem to get an and clause to work (e.g. filter1 and filter 2 ... etc.):</p>

<p>Show me snapshots where the database name is 'testing'</p>

<p></p>

<pre><code>aws rds describe-db-snapshots --include-shared --query 'DBSnapshots[?DBInstanceIdentifier==`testing`].{DBNAME:DBInstanceIdentifier,SNAPSHOT:DBSnapshotIdentifier}'
[
    {
        ""SNAPSHOT"": ""test1"",
        ""DBNAME"": ""testing""
    },
    {
        ""SNAPSHOT"": ""test2"",
        ""DBNAME"": ""testing""
    },
    {
        ""SNAPSHOT"": ""test3"",
        ""DBNAME"": ""testing""
    },
    {
        ""SNAPSHOT"": ""test4"",
        ""DBNAME"": ""testing""
    }
]
</code></pre>



<p>Show me snapshots named 'test1' </p>

<p></p>

<pre><code>$ aws rds describe-db-snapshots --include-shared --query 'DBSnapshots[?DBSnapshotIdentifier==`test1`].{DBNAME:DBInstanceIdentifier,SNAPSHOT:DBSnapshotIdentifier}'
[
    {
        ""SNAPSHOT"": ""test1"",
        ""DBNAME"": ""testing""
    },
        {
        ""SNAPSHOT"": ""test1"",
        ""DBNAME"": ""testing2""
    }
]
</code></pre>



<p>Show me snapshots from the database testing that are named test1</p>

<p></p>

<pre><code>aws rds describe-db-snapshots --include-shared --query 'DBSnapshots[?DBInstanceIdentifier==`testing`][?DBSnapshotIdentifier==`test1`].{DBNAME:DBInstanceIdentifier,SNAPSHOT:DBSnapshotIdentifier}'
[]
</code></pre>



<p>How can this be achieved?</p>
",https://stackoverflow.com/questions/47163478/querying-multiple-values,"['aws-cli', 'jmespath']",16372,TRUE,12,1
Database with PHPUnit -Selenium Framework,"<p>Can anyone provide me a good and complete source for Database Testing with PHPUnit?
Currently I am referring to this
<a href=""https://www.sitepoint.com/bulletproofing-database-interactions/"" rel=""nofollow noreferrer"">Source</a></p>

<p>By Doing in that manner I got this error:</p>

<pre><code>PHP Warning:  require_once(ArticleDAO.php): failed to open stream: No such file or directory in /var/www/html/testing/ArticleDAOTest.php on line 3
PHP Stack trace:
PHP   1. {main}() /var/www/html/testing/vendor/phpunit/phpunit/phpunit:0
PHP   2. PHPUnit_TextUI_Command::main() /var/www/html/testing/vendor/phpunit/phpunit/phpunit:52
PHP   3. PHPUnit_TextUI_Command-&gt;run() /var/www/html/testing/vendor/phpunit/phpunit/src/TextUI/Command.php:100
PHP   4. PHPUnit_Runner_BaseTestRunner-&gt;getTest() /var/www/html/testing/vendor/phpunit/phpunit/src/TextUI/Command.php:123
PHP   5. PHPUnit_Runner_BaseTestRunner-&gt;loadSuiteClass() /var/www/html/testing/vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php:67
PHP   6. PHPUnit_Runner_StandardTestSuiteLoader-&gt;load() /var/www/html/testing/vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php:123
PHP   7. PHPUnit_Util_Fileloader::checkAndLoad() /var/www/html/testing/vendor/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php:39
PHP   8. PHPUnit_Util_Fileloader::load() /var/www/html/testing/vendor/phpunit/phpunit/src/Util/Fileloader.php:38
PHP   9. include_once() /var/www/html/testing/vendor/phpunit/phpunit/src/Util/Fileloader.php:56
PHP Fatal error:  require_once(): Failed opening required 'ArticleDAO.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/html/testing/ArticleDAOTest.php on line 3
PHP Stack trace:
PHP   1. {main}() /var/www/html/testing/vendor/phpunit/phpunit/phpunit:0
PHP   2. PHPUnit_TextUI_Command::main() /var/www/html/testing/vendor/phpunit/phpunit/phpunit:52
PHP   3. PHPUnit_TextUI_Command-&gt;run() /var/www/html/testing/vendor/phpunit/phpunit/src/TextUI/Command.php:100
PHP   4. PHPUnit_Runner_BaseTestRunner-&gt;getTest() /var/www/html/testing/vendor/phpunit/phpunit/src/TextUI/Command.php:123
PHP   5. PHPUnit_Runner_BaseTestRunner-&gt;loadSuiteClass() /var/www/html/testing/vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php:67
PHP   6. PHPUnit_Runner_StandardTestSuiteLoader-&gt;load() /var/www/html/testing/vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php:123
PHP   7. PHPUnit_Util_Fileloader::checkAndLoad() /var/www/html/testing/vendor/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php:39
PHP   8. PHPUnit_Util_Fileloader::load() /var/www/html/testing/vendor/phpunit/phpunit/src/Util/Fileloader.php:38
PHP   9. include_once() /var/www/html/testing/vendor/phpunit/phpunit/src/Util/Fileloader.php:56
</code></pre>

<p>Although I have included the file on line number 3.
My Complete Source Code is:</p>

<pre><code>&lt;?php
require_once ""PHPUnit/Autoload.php"";
require_once ""ArticleDAO.php"";

class ArticleDAOTest extends PHPUnit_Extensions_Database_TestCase implements IArticleDAO
{
    public function getConnection() {
        $db = new PDO(
            ""mysql:host=localhost;dbname=bulletproof"", 
            ""root"", ""password"");
        return $this-&gt;createDefaultDBConnection($db, ""bulletproof"");
    }

    public function getDataSet() {
        return $this-&gt;createXMLDataSet(""seed.xml"");
    }
    public function getArticles($sectionId, $isHome) {
        $db = new PDO(
            ""mysql:host=localhost;dbname=bulletproof"", 
            ""root"", ""password"");

        $result = $db-&gt;query(""SELECT a.id, a.title FROM features f LEFT JOIN articles a ON f.article_id = a.id AND f.section_id = 1"");
        $articles = array();
        while ($row = $result-&gt;fetch(PDO::FETCH_ASSOC)) {
            $articles[] = $row;
        }
        $result-&gt;closeCursor();

        return $articles;
    }
    public function testGetArticlesNonHome() {
        $articleDAO = new ArticleDAO();
        $articles = $articleDAO-&gt;getArticles(1, false);
        $this-&gt;assertEquals(
            array(
                array(""id"" =&gt; 1, ""title"" =&gt; ""Android vs iOS""),
                array(""id"" =&gt; 2, ""title"" =&gt; ""Android vs Wp7""),
                array(""id"" =&gt; 3, ""title"" =&gt; ""iOS 5"")),
            $articles);
    }
}
</code></pre>

<p>My ArticleDAO.php file</p>

<pre><code>&lt;?php
interface IArticleDAO
{
    public function getArticles($sectionId, $isHome);
}
</code></pre>
",https://stackoverflow.com/questions/41565248/database-with-phpunit-selenium-framework,"['php', 'phpunit']",41,FALSE,0,0
Nested relationships with Laravel faker - laravel seeder,"<p>
I wanted to make a post seeder with users and comments as mentioned in the relationship section in the laravel documentation <a href=""https://laravel.com/docs/5.5/database-testing"" rel=""nofollow noreferrer"">https://laravel.com/docs/5.5/database-testing</a> </p>



<pre><code>  $users = factory(App\User::class, 3)
     -&gt;create()
     -&gt;each(function ($u) {
          $u-&gt;posts()-&gt;save(factory(App\Post::class)
            -&gt;create()
            -&gt;each(function($p){
                $p-&gt;comments()-&gt;save(factory(App\Comment::class,5)
                  -&gt;create()
                  -&gt;each(function($c){
                      $c-&gt;user()-&gt;save(factory(App\User::class)
                        -&gt;make()
                      );
                  })
                );
              })
            );
        }
    );
</code></pre>

<p>
Expected output was to have 3 users having posts with 5 comments each.</p>

<p>
But error occurred:</p>

<blockquote>
  <p>In Builder.php line 2459: Call to undefined method
  Illuminate\Database\Query\Builder::save()</p>
</blockquote>
",https://stackoverflow.com/questions/47775412/nested-relationships-with-laravel-faker-laravel-seeder,"['php', 'laravel', 'factories', 'eloquent-relationship']",3294,TRUE,3,3
Factories in Laravel?,"<p>It appear you can write Factories in Laravel.</p>

<p>According to doumentation: 
<a href=""https://laravel.com/docs/5.3/database-testing#writing-factories"" rel=""nofollow noreferrer"">https://laravel.com/docs/5.3/database-testing#writing-factories</a></p>

<p>It appear Factories for the model/database related.</p>

<p>Is it possible to write Factories for non model related?</p>

<p>For example of two classes:</p>

<pre><code>class Car {
  public function drive() { }
} 

Class Bike {
 public function ride() { }
}
</code></pre>

<p>Rather than using <code>(new Car)-&gt;drive()</code> I would like to use <code>Transport</code> Factory to class the class.</p>
",https://stackoverflow.com/questions/41653372/factories-in-laravel,"['php', 'laravel', 'laravel-5.3']",362,FALSE,0,2
PHP- Unable to Access Data from DB in dropdown menu,"<p>I am trying to create a drop down menu that will display Project Names off all Projects present in  the table Project in the database Testing... The drop down is created but it is not accessing the database and retrieving the required data...
The code is as follows:</p>

<pre><code>&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Dynamic Drop Down List&lt;/title&gt;
&lt;/head&gt;

    &lt;form id=""form1"" name=""form1"" method=""post"" action=""&lt;?php echo $PHP_SELF; ?&gt;""&gt;
        Project List :
        &lt;select Project Name='NEW'&gt;
        &lt;option value=""""&gt;--- Select ---&lt;/option&gt;
        &lt;?
            $serverName = ""Swagatha-PC""; 
            $connectionInfo = array( ""Database""=&gt;""Testing"");
            $conn = sqlsrv_connect( $serverName, $connectionInfo);

            if( $conn ) 
            {
            echo ""Connection established.&lt;br /&gt;"";
            }
            else
            {
            echo ""Connection could not be established.&lt;br /&gt;"";
            die( print_r( sqlsrv_errors(), true));
            }
            if (isset ($select)&amp;&amp;$select!="""")
            {
            $select=$_POST ['NEW'];
        }
        ?&gt;
        &lt;?
            $query=mysql_query(""select ProjectName from dbo.Project"");
            $menu="" "";
            while($row = sqlsrv_fetch_array($query))
            {
               $menu =""&lt;option&gt;"" . $row[""ProjectName""] . ""&lt;/option&gt;"";
            }


            ?&gt;
        &lt;/select&gt;
        &lt;input type=""submit"" name=""Next"" value=""Select"" /&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p><a href=""https://i.stack.imgur.com/MrdUJ.jpg"" rel=""nofollow noreferrer"">Dropdown Error</a></p>

<p>What Do i do to fix this??</p>
",https://stackoverflow.com/questions/44418530/php-unable-to-access-data-from-db-in-dropdown-menu,['php'],46,TRUE,0,2
PHPUnit assertDatabaseHas() returning TypeError,"<p>Trying to test a model here, but every time that I try to use the assertDatabaseHas method it gives me the type error. Laravel 5.4 and PHPUnit 6.</p>

<pre><code>    PHPUnit 6.1.4 by Sebastian Bergmann and contributors.

..E                                                                 3 / 3 (100%)

Time: 815 ms, Memory: 10.00MB

There was 1 error:

1) Tests\Unit\ModelTest::test_model_creation
TypeError: Argument 2 passed to PHPUnit\Framework\Assert::assertThat() must be an instance of PHPUnit\Framework\Constraint\Constraint, instance of Illuminate\Foundation\Testing\Constraints\HasInDatabase given, called in /home/vagrant/domains-api/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php on line 22

/home/vagrant/domains-api/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php:22
/home/vagrant/domains-api/tests/Unit/ModelTest.php:36

ERRORS!
Tests: 3, Assertions: 2, Errors: 1.
</code></pre>

<p>Code inside the test class:</p>

<pre><code>$this-&gt;assertDatabaseHas('domains', [
            'domain' =&gt; $domain,
            'domain_type' =&gt; 'full_domain',
        ]);
</code></pre>

<p>I using the laravel docs as reference and the syntax seems to be correct (at least for me).
<a href=""https://laravel.com/docs/5.4/database-testing#introduction"" rel=""nofollow noreferrer"">https://laravel.com/docs/5.4/database-testing#introduction</a></p>

<p>Thanks in advance for any help.</p>
",https://stackoverflow.com/questions/44251941/phpunit-assertdatabasehas-returning-typeerror,"['php', 'laravel', 'phpunit']",1779,TRUE,1,1
How does the static password work in the default Laravel user factory?,"<p>Per this link, <a href=""https://laravel.com/docs/5.4/database-testing#writing-factories"" rel=""noreferrer"">https://laravel.com/docs/5.4/database-testing#writing-factories</a>, the default Laravel user factory tests the value of a static <code>$password</code> variable.  If it is falsey, it bcrypts 'secret' and uses that.</p>

<p>How does one go about setting the value of the static variable <code>$password</code>?  Obviously I don't want to import it at the time the function is declared (since that would defeat the purpose of making it variable).  I realise that I can override the value of password by passing an array to the <code>make()</code> method, but this is a different thing altogether.</p>
",https://stackoverflow.com/questions/44037895/how-does-the-static-password-work-in-the-default-laravel-user-factory,"['php', 'laravel', 'static']",8020,TRUE,16,1
Laravel Seeding using Factory for one to one relation,"<p>I want to create a test data using laravel seed. I can seed for one table. Here is :</p>

<p><strong>ModelFactory.php:</strong></p>

<pre><code>/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory-&gt;define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'email' =&gt; $faker-&gt;unique()-&gt;safeEmail,
        'password' =&gt; $password ?: $password = bcrypt('secret'),
        'remember_token' =&gt; str_random(10),
        'type' =&gt; '0'
    ];
});
</code></pre>

<p><strong>UsersTableSeeder.php :</strong></p>

<pre><code>&lt;?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() {
        factory(App\User::class, 50)-&gt;create()-&gt;each(function ($u) {
            $u-&gt;posts()-&gt;save(factory(App\Post::class)-&gt;make());
        });
    }
}
</code></pre>

<p>I have two tables which are users and user_information. They have one-to-one relation. I want to seed user_information with users. But i have no idea, how i can do...</p>

<p>My models relation functions :</p>

<p>User.php</p>

<pre><code>public function userInformation() {
        return $this-&gt;hasOne('App\UserInformation', 'user_id', 'id');
    }
</code></pre>

<p>UserInformation.php</p>

<pre><code>public function users() {
        return $this-&gt;belongsTo('App\User', 'user_id', 'id');
    }
</code></pre>

<p>Laravel version is 5.3</p>

<p>I followed these docs : </p>

<p><a href=""https://laravel.com/docs/5.3/seeding"" rel=""nofollow noreferrer"">https://laravel.com/docs/5.3/seeding</a></p>

<p><a href=""https://laravel.com/docs/5.3/database-testing#writing-factories"" rel=""nofollow noreferrer"">https://laravel.com/docs/5.3/database-testing#writing-factories</a></p>
",https://stackoverflow.com/questions/44670392/laravel-seeding-using-factory-for-one-to-one-relation,['php'],7279,TRUE,2,3
Property type is not a type of overriden,"<p>Sorry for not specific title, I don't really know how to name it better.<br>
I have the following example:</p>

<pre><code>class User

interface Repository&lt;T, ID&gt;

interface UserRepository : Repository&lt;User, Long&gt;

abstract class RepositoryTest&lt;T, ID&gt; {

    abstract var repository: Repository&lt;T, ID&gt;

}

class UserRepositoryTest : RepositoryTest&lt;User, Long&gt;() {

    //Error: Var-property type is ""UserRepository"", which is not a type of overriden 
    lateinit override var repository: UserRepository

}
</code></pre>

<p>I need this architecture for the database testing. <code>Repository</code> have methods like insert, save, delete etc. I want to use this abstraction in <code>RepositoryTest</code> to delete all entries and insert needed data before each test. In <code>UserRepositoryTest</code> I want to specify the repository as <code>UserRepository</code> (it's a child of <code>Repository</code>), but I take an error mentioned in the example.<br>Why it gives me the error? I thought I can pass a subtype`s type.    </p>
",https://stackoverflow.com/questions/43389976/property-type-is-not-a-type-of-overriden,['kotlin'],1774,TRUE,6,1
Migrate only once with Laravel dusk,"<p>According <a href=""https://laravel.com/docs/5.4/database-testing#resetting-the-database-after-each-test"" rel=""nofollow noreferrer"">to the ""Database Testing"" documentation</a> I can reset the database after each test (first option). Second option is to run test using Transactions. It seems a better approach to me, but if I want to run with transaction, the migration does not run. </p>

<p>Is there any way to <strong>run the migration once</strong> for all the test process?</p>

<p>In other words, I want to run the migration, run every tests with transaction, then rollback. I tried with what the documentation says, but I think something is missing.</p>
",https://stackoverflow.com/questions/41980432/migrate-only-once-with-laravel-dusk,"['php', 'laravel', 'unit-testing', 'laravel-5.4', 'laravel-dusk']",3370,TRUE,6,4
Is there anyway to retrieve direct parent of a child item in JPA?,"<p>I'm creating a simple REST server using Spring framework.
One of the class needs to have a self join one to many relationship to retrieve the data about it's parents object. The class looks like this;</p>

<pre><code>@Entity
@Table(name = ""item"", schema = ""tmp"", uniqueConstraints = {
    @UniqueConstraint(columnNames = ""item_id""), @UniqueConstraint(columnNames = ""item_name"")})
public class Item implements Serializable {

  private static final long serialVersionUID = 1L;

  private Integer itemId;
  private String itemName;
  private String itemDescription;
  private Item itemParent;
  private boolean isEndItem;
  private List&lt;Item&gt; childrenItems;


  public Item() {}

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = ""item_id"", unique = true, nullable = false)
  public Integer getItemId() {
    return itemId;
  }

  public void setItemId(final Integer itemId) {
    this.itemId = itemId;
  }

  @Column(name = ""item_name"", unique = true, nullable = false)
  public String getItemName() {
    return itemName;
  }

  public void setItemName(final String itemName) {
    this.itemName = itemName;
  }

  @Column(name = ""item_description"", unique = false, nullable = false)
  public String getItemDescription() {
    return itemDescription;
  }

  public void setItemDescription(final String itemDescription) {
    this.itemDescription = itemDescription;
  }

  @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  @JsonManagedReference(value = ""item-item"")
  @JoinColumn(name=""item_parentid"")
  public Item getParentItem() {
    return this.itemParent;
  }

  public void setParentItem(final Item itemParent){
    this.itemParent = itemParent;
  }

  @OneToMany(mappedBy=""childrenItems"", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  @JsonBackReference(value = ""item-item"")
  public List&lt;Item&gt; getChildrenItems(){
    return this.childrenItems;
  }

  public void setChildrenItems(final List&lt;Item&gt; childrenItems){
    this.childrenItems = childrenItems;
  }

  @Column(name = ""item_isendproduct"", unique = false, nullable = false)
  public boolean isEndItem() {
    return isEndItem;
  }

  public void setEndItem(final boolean isEndItem) {
    this.isEndItem = isEndItem;
  }
}
</code></pre>

<p>In my database, testing data is saved in this hierarchy:</p>

<p><strong>Entry > Salad > House Salad</strong></p>

<pre><code>[  
   {  
      ""itemId"":1,
      ""itemName"":""Entry"",
      ""itemDescription"":""Entry Menu"",
      ""endItem"":false,
      ""parentItem"":null
   },
   {  
      ""itemId"":2,
      ""itemName"":""Salad"",
      ""itemDescription"":""Salad Menu"",
      ""endItem"":false,
      ""parentItem"":{  
         ""itemId"":1,
         ""itemName"":""Entry"",
         ""itemDescription"":""Entry Menu"",
         ""endItem"":false,
         ""parentItem"":null
      }
   },
   {  
      ""itemId"":3,
      ""itemName"":""House Salad"",
      ""itemDescription"":""House Salad"",
      ""endItem"":true,
      ""parentItem"":{  
         ""itemId"":2,
         ""itemName"":""Salad"",
         ""itemDescription"":""Salad Menu"",
         ""endItem"":false,
         ""parentItem"":{  
            ""itemId"":1,
            ""itemName"":""Entry"",
            ""itemDescription"":""Entry Menu"",
            ""endItem"":false,
            ""parentItem"":null
         }
      }
   }
]
</code></pre>

<p>But I don't want to know the information about the parent's parent object.
Is there any annotations that I can use to achieve this?</p>

<p>Thank in advance</p>
",https://stackoverflow.com/questions/42917803/is-there-anyway-to-retrieve-direct-parent-of-a-child-item-in-jpa,"['java', 'spring', 'jpa']",38,FALSE,0,0
Selenium web driver. how o test,"<p>Iam very new to selenium. So here I have few doubts about working with Selenium.We are following <em>keyword driven test</em> in selenium,reading test from excel and object.property file exist for mapping of data from excel and program.Reports are generating using ExtentReport.</p>

<blockquote>
  <p>The doubts are, my web application includes saving of Data,that got
  reflected to many pages based on different criteria.For example
  Administrator can add the assets,that means he is the custodian of
  that asset.The saved asset got populated to a a table below, with a
  unique number asset number. He can transfer his asset to any of the
  employee in his office or another office.If he tranfer aseet to an
  employee of his office a OTP is generated to him, that he have to
  enter for approval.If it belongs to employee of different office,
  admin do not have the privilage to approve. OTP will be generated to
  the employee of other office. This is bit complication. Really what
  Iam facing is how to automate this scenario using webdriver .</p>
</blockquote>

<p>Second is How database testing done.Is database testing is used for the above scenario.How to compare data in the below table with excel data.</p>

<p>Kindly suggest. Pls forgive if any mistake asked</p>
",https://stackoverflow.com/questions/42617878/selenium-web-driver-how-o-test,"['java', 'selenium', 'selenium-webdriver']",159,FALSE,0,0
How can I get the elements from a mongodb subdocument in java?,"<p>I have a mongodb database (""testing"") which has some collections. I use one named ""Pelis3"" which contains documents. The documents contains the typical elements and a subdocument named ""belongs to collection"" where i will to access. The problem is that I only can print the 1st level elements and the subdocument like a document.</p>

<p>How can I get one by one the elements of the subdocument ""belongs_to_collection""?</p>

<p>This is my java code. I call the function saveJson:</p>

<pre><code>public class mongoDB {

    private MongoClient mongoClient;
    private MongoDatabase mongodb;
    private MongoCollection&lt;Document&gt; collection;

    public MongoDatabase selectDatabase() {
        setMongoClient(new MongoClient());
        setMongodb(getMongoClient().getDatabase(""testing""));
        return getMongodb();
    }

    public MongoClient getMongoClient() {
        return mongoClient;
    }

    public void setMongoClient(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
    }

    public MongoDatabase getMongodb() {
        return mongodb;
    }

    public void setMongodb(MongoDatabase mongodb) {
        this.mongodb = mongodb;
    }

    public MongoCollection&lt;Document&gt; getCollection() {
        return collection;
    }

    public void setCollection(String col) {
        this.collection = (selectDatabase().getCollection(col));
    }

    public void saveJson(JsonObject json) {
        setCollection(""Pelis3"");
        Document document = Document.parse(json.toString());
        getCollection().insertOne(document);

        for (Document doc : getCollection().find()) {

            System.out.println(doc.getBoolean(""adult""));
            Object ob = doc.get(""belongs_to_collection"");
            System.out.println(ob);


        }
    }
}
</code></pre>

<p>This is the content of the collection:</p>

<pre><code>{
  ""adult"": false,
  ""backdrop_path"": ""/8SqBiesvo1rh9P1hbJTmnVum6jv.jpg"",
  ""belongs_to_collection"": {
    ""id"": 304378,
    ""name"": ""Independence Day Collection"",
    ""poster_path"": ""/diCxphvzqas0Tr5eq7tLUzg5M7d.jpg"",
    ""backdrop_path"": ""/p7oqa94XgNGVMazXwR49QfyGgtx.jpg""
  },
  ""budget"": 165000000,
  ""genres"": [
    {
      ""id"": 28,
      ""name"": ""Action""
    },
    {
      ""id"": 12,
      ""name"": ""Adventure""
    },
    {
      ""id"": 878,
      ""name"": ""Science Fiction""
    }
  ],
  ""homepage"": ""http://www.warof1996.com"",
  ""id"": 47933,
  ""imdb_id"": ""tt1628841"",
  ""original_language"": ""en"",
  ""original_title"": ""Independence Day: Resurgence"",
  ""overview"": ""We always knew they were coming back. Using recovered alien technology, the nations of Earth have collaborated on an immense defense program to protect the planet. But nothing can prepare us for the aliens’ advanced and unprecedented force. Only the ingenuity of a few brave men and women can bring our world back from the brink of extinction."",
  ""popularity"": 5.163195,
  ""poster_path"": ""/5CHJs479xWnm3zMDOl94VkKS7MZ.jpg"",
  ""production_companies"": [
    {
      ""name"": ""Twentieth Century Fox Film Corporation"",
      ""id"": 306
    },
    {
      ""name"": ""Centropolis Entertainment"",
      ""id"": 347
    },
    {
      ""name"": ""TSG Entertainment"",
      ""id"": 22213
    },
    {
      ""name"": ""Stereo D"",
      ""id"": 86561
    }
  ],
  ""production_countries"": [
    {
      ""iso_3166_1"": ""US"",
      ""name"": ""United States of America""
    }
  ],
  ""release_date"": ""2016-06-22"",
  ""revenue"": 389681935,
  ""runtime"": 120,
  ""spoken_languages"": [
    {
      ""iso_639_1"": ""en"",
      ""name"": ""English""
    }
  ],
  ""status"": ""Released"",
  ""tagline"": ""We had twenty years to prepare. So did they."",
  ""title"": ""Independence Day: Resurgence"",
  ""video"": false,
  ""vote_average"": 4.9,
  ""vote_count"": 2236
}
</code></pre>

<p>And this is the exit when I execute de program:</p>

<pre><code>jfx-project-run:
Executing /media/daniel/WD_1TB/Programación/proyectos personales/Gestor de colecciones/dist/run1943415091/Gestor de colecciones.jar using platform /usr/lib/jvm/java-8-oracle/jre/bin/java
jul 02, 2017 5:51:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMACIÓN: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
jul 02, 2017 5:51:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMACIÓN: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
jul 02, 2017 5:51:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMACIÓN: Opened connection [connectionId{localValue:1, serverValue:50}] to 127.0.0.1:27017
jul 02, 2017 5:51:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMACIÓN: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[2, 6, 10]}, minWireVersion=0, maxWireVersion=2, maxDocumentSize=16777216, roundTripTimeNanos=579216}
jul 02, 2017 5:51:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFORMACIÓN: Opened connection [connectionId{localValue:2, serverValue:51}] to 127.0.0.1:27017
false
Document{{id=304378, name=Independence Day Collection, poster_path=/diCxphvzqas0Tr5eq7tLUzg5M7d.jpg, backdrop_path=/p7oqa94XgNGVMazXwR49QfyGgtx.jpg}}
false
Document{{id=304378, name=Independence Day Collection, poster_path=/diCxphvzqas0Tr5eq7tLUzg5M7d.jpg, backdrop_path=/p7oqa94XgNGVMazXwR49QfyGgtx.jpg}}
Java Result: 1
Deleting directory /media/daniel/WD_1TB/Programación/proyectos personales/Gestor de colecciones/dist/run1943415091
jfxsa-run:
BUILD SUCCESSFUL (total time: 3 seconds)
</code></pre>
",https://stackoverflow.com/questions/44875711/how-can-i-get-the-elements-from-a-mongodb-subdocument-in-java,"['java', 'mongodb', 'subdocument', 'mongo-java-driver']",489,FALSE,0,0
Testing packages that depend upon Eloquent,"<p>This is my scenario: I have two Laravel apps that both depend on a set of custom (in-house) components. These components sit in a separate git repository and are packaged as a Composer package <code>C</code>, which I include in my Laravel apps. </p>

<p>Now my package <code>C</code> makes heavy use of Eloquent to do database operations. I would like to unit-test <code>C</code> wit Laravel's PHPUnit testing environment, but without bloating <code>C</code> to a whole Laravel installation. </p>

<p>As a first step, I Composer-required <code>laravel</code>, <code>phpunit</code> and some other packages that seemed relevant, but it still looks like a long way to do actual database testing (where would I, for instance, specify my database connection?). </p>

<p>Could anyone point me in the right direction? Thanks!</p>
",https://stackoverflow.com/questions/45570070/testing-packages-that-depend-upon-eloquent,"['php', 'laravel', 'unit-testing', 'eloquent', 'phpunit']",37,FALSE,2,0
Test RxJava2 Flowable Query Room,"<p>I've been trying to write unit tests for my Room database, which I've done in the past when I have queries return a list and I create a database that allows main thread queries, but now that I'm trying to test with RxJava values I have no luck.</p>

<p>Here is my DAO code:</p>

<pre><code>@Dao
interface AccountDAO {
    @Query(""SELECT * FROM account"")
    fun getAll(): Flowable&lt;List&lt;Account&gt;&gt;

    @Insert
    fun insert(accounts: List&lt;Account&gt;): List&lt;Long&gt;

    //...
}
</code></pre>

<p>And here is my database testing code, where I've tried a few things to get it to pass:</p>

<pre><code>@RunWith(AndroidJUnit4::class)
class CCDatabaseTest {
    //...

    @JvmField @Rule val mainActivity = ActivityTestRule&lt;MainActivity&gt;(MainActivity::class.java)

    @Before
    fun setUp() {
        val context = mainActivity.activity
        database = Room.inMemoryDatabaseBuilder(context, CCDatabase::class.java).allowMainThreadQueries().build()
        accountDao = database.accountDao()
        transactionDao = database.transactionDao()
    }

    //...

    @Test
    fun testWriteReadAccount() {
        val testAccount = Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_BALANCE)

        val ids = accountDao.insert(listOf(testAccount))
        assertEquals(1, ids.size)

        val accountsFlowable = accountDao.getAll()
        val testSubscriber = TestSubscriber&lt;List&lt;Account&gt;&gt;()
        accountsFlowable.subscribe(testSubscriber)

        testSubscriber.assertNoErrors()
        // Fails: testSubscriber.assertValueCount(1)
        // Fails: testSubscriber.assertValue(listOf(testAccount))
        // Fails: testSubscriber.assertResult(listOf(testAccount))
    }

    //...
}
</code></pre>

<p>If anyone would actually like to see or test run the code, please check out the app-refresh module of this repository: <a href=""https://github.com/adammc331/cashcaretaker"" rel=""noreferrer"">https://github.com/adammc331/cashcaretaker</a></p>

<p>DAO: <a href=""https://github.com/AdamMc331/CashCaretaker/blob/develop/app-refresh/src/main/java/com/adammcneilly/cashcaretaker/daos/AccountDAO.kt"" rel=""noreferrer"">https://github.com/AdamMc331/CashCaretaker/blob/develop/app-refresh/src/main/java/com/adammcneilly/cashcaretaker/daos/AccountDAO.kt</a></p>

<p>Test class: <a href=""https://github.com/AdamMc331/CashCaretaker/blob/develop/app-refresh/src/androidTest/java/com/adammcneilly/cashcaretaker/data/CCDatabaseTest.kt"" rel=""noreferrer"">https://github.com/AdamMc331/CashCaretaker/blob/develop/app-refresh/src/androidTest/java/com/adammcneilly/cashcaretaker/data/CCDatabaseTest.kt</a></p>
",https://stackoverflow.com/questions/45897104/test-rxjava2-flowable-query-room,"['kotlin', 'rx-java2', 'android-room']",2702,TRUE,8,2
JDBC SQLite ATTACH Query while using C3P0,"<p>I recently implemented C3P0 in my database testing program (i'm using it to test different queries on our data in different DB formats... sqlite, mariadb, etc). The program was initially set up using a single sustained connection to do all queries. This worked fine with SQLite as I had to do an initial ATTACH on another table. When moving to C3P0 where it is necessary to open and close the connection on every query, how can one issue an ATTACH command and have it apply to subsequent queries? In my failure I did notice that the first query after the attach it seemed to apply. </p>

<p>Do I really need to interlace ATTACH test as TESTDB for EVERY query???</p>

<p>Running into a similar issue with setCatalog() for MariaDB. I get a ""No Database selected"" for every subsequent query after the first.</p>
",https://stackoverflow.com/questions/45924693/jdbc-sqlite-attach-query-while-using-c3p0,"['java', 'sqlite', 'jdbc', 'c3p0']",339,TRUE,2,1
How can I use PHPUnit&#39;s DBUnit with a Microsoft SQL Server database?,"<p>I'm using PHPUnit and DBUnit to create tests for a PHP application that runs on the commandline and inserts data into a Microsoft SQL Server database.</p>

<p>The DBUnit documentation (<a href=""https://phpunit.de/manual/current/en/database.html#database.supported-vendors-for-database-testing"" rel=""nofollow noreferrer"">https://phpunit.de/manual/current/en/database.html#database.supported-vendors-for-database-testing</a>) states that Microsoft SQL Server is not supported but is accessible through the Zend Framework or Doctrine 2.</p>

<p>When I attempt:</p>

<pre><code> $pdo = new PDO( ""odbc:Driver={ODBC Driver 13 for SQL Server};Server=redacted"", $user, $passwd );

 $this-&gt;createDefaultDBConnection($pdo, $db);
</code></pre>

<p>I get, not surprisingly, the following error:</p>

<pre><code>PHPUnit_Extensions_Database_Exception: Could not find a meta data driver for odbc pdo driver.
</code></pre>

<p>I found Zend Framework documentation that shows how to use PHPUnit to write tests related to relational databases (<a href=""https://framework.zend.com/manual/1.10/en/zend.test.phpunit.db.html"" rel=""nofollow noreferrer"">https://framework.zend.com/manual/1.10/en/zend.test.phpunit.db.html</a>), and I think I could get that to work if I understood Zend better, so it's possible what I need is some help understanding how to get access to the Zend classes w/out writing an entire Zend application.</p>

<p>But maybe there's some non-Zend way to do it.</p>
",https://stackoverflow.com/questions/43505154/how-can-i-use-phpunits-dbunit-with-a-microsoft-sql-server-database,"['php', 'sql-server', 'zend-framework', 'phpunit', 'dbunit']",451,FALSE,0,1
"Application status down, when mongo is down with spring boot actuator","<p>I have created sample project for spring boot actuator with database testing. After running the application when I hit the URL </p>

<ul>
<li>When Mongo DB is running</li>
<li>URL: <a href=""http://localhost:8080/health"" rel=""noreferrer"">http://localhost:8080/health</a> </li>
<li>Response :
`{""status"":""UP"",""diskSpace"":{""status"":""UP"",""total"":493767094272,""free"":404928278528,""threshold"":10485760},""mongo"":{""status"":""UP"",""version"":""3.0.2""}}</li>
</ul>

<p>`</p>

<ul>
<li>When Mongo DB is not running </li>
<li>URL:
<a href=""http://localhost:8080/health"" rel=""noreferrer"">http://localhost:8080/health</a></li>
<li><p>Response:</p>

<p>{""status"":""DOWN"",""diskSpace"":{""status"":""UP"",""total"":493767094272,""free"":404929720320,""threshold"":10485760},""mongo"":{""status"":""DOWN"",""error"":""org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]""}}</p></li>
</ul>

<p><strong>Question:</strong> Why application status is ""DOWN"" when my mongodb is not running. I want my application status ""UP"" weather mongodb is ""DOWN"" or ""UP"".</p>

<p>Below is my Main class for spring boot application.</p>

<pre><code>package com.company.testing;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code></pre>

<p><strong>pom.xml</strong></p>

<pre><code>&lt;project xmlns=""http://maven.apache.org/POM/4.0.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;artifactId&gt;SpringBootSample&lt;/artifactId&gt;
    &lt;version&gt;0.0.1&lt;/version&gt;
    &lt;name&gt;Spring Boot Sample&lt;/name&gt;
    &lt;description&gt;Spring Boot Sample for spring boot actuator&lt;/description&gt;
    &lt;groupId&gt;com.company.testing&lt;/groupId&gt;

    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;1.4.3.RELEASE&lt;/version&gt;
    &lt;/parent&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-mongodb&lt;/artifactId&gt;
        &lt;/dependency&gt;


    &lt;/dependencies&gt;

    &lt;properties&gt;
        &lt;java.version&gt;1.8&lt;/java.version&gt;
    &lt;/properties&gt;

    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;
&lt;/project&gt;
</code></pre>
",https://stackoverflow.com/questions/41803253/application-status-down-when-mongo-is-down-with-spring-boot-actuator,"['java', 'mongodb', 'maven', 'spring-boot', 'spring-boot-actuator']",7542,TRUE,5,2
&quot;developer/test&quot; mode for SQL Databases,"<p>I am new to a relatively large project using a Microsoft SQL server database with C# and the Entity Framework. </p>

<p>The current development process is like this:</p>

<ul>
<li>Code some feature/intend to fix a bug</li>
<li>Start the application</li>
<li>Make some changes via GUI to the database testing the coded functionality/testing if the bug was fixed</li>
<li>In case of failure -> run SQL scripts to delete the complete database changes and repeat the whole procedure</li>
</ul>

<p>I am wondering if there is any ""test/developer""-mode for SQL databases that could automatically revert the applied changes. Basically, while the program is running, everything should be inserted/updated/deleted to the actual database, but afterwards all changes should automatically be reverted. Is my thought completely unreasonable? Is our procedure with the SQL scripts more or less state of the art for database development? </p>

<p>Thanks in advance!</p>

<p><em>Edit</em> : We are using a developer database and the code first approach of Entity. It is still very annoying to me to run SQL scripts every time to keep my developer database ""clean/usable/free from corrupt data"". Also sometimes you code functionality that is supposed to work only once in production and coding that feature, requires you to test it a couple of times which means you need to reset the database once/times tested.</p>
",https://stackoverflow.com/questions/45995922/developer-test-mode-for-sql-databases,"['c#', 'sql-server', 'database', 'entity-framework', 'testing']",474,TRUE,1,1
Keeping a single background thread through a Parallel.ForEach,"<p>(Ok, I've made a total mess of this, so I'm going to clean it up and provide all the information I can here.  Please see the bottom of this post for a better explanation of what I'm trying to do.  I'm leaving the rest here in the hopes that someone will see the mess I made and learn how to make a better post from my mistakes. :))</p>

<p>Please see the section entitled ""A Better Explanation"" for, well, a better explanation.</p>

<hr>

<p><strong>EDIT 2</strong>: My apologies for being unclear.  <code>ItemStore</code> is not a collection in this case, it's a DB-backed service.  I've updated my code.</p>

<hr>

<p><strong>EDIT</strong>: Additional information.</p>

<ul>
<li><p>The backing store is going to be a DB.  This means that we can persist items in the queue without worrying about losing items if the application dies.  This also means that adding/retrieving items from the DB could be slowish.  (i.e., not as fast as in-memory).</p></li>
<li><p>Because of this, it also means that we don't want to hold a collection in memory the whole time.  The preference is to go back to the DB for the next item, again for persistence safety.</p></li>
<li><p>Ultimately, items are coming in from web service calls.  Essentially, Enqueue will be a WebAPI route that a browser will do an HTTP POST to.</p></li>
<li><p>Finally, the central problem we're trying to solve is to funnel potentially a bunch of requests into a single, FIFO queue, basically due to a limitation in a third-party library we're using.  So the goal is to get, say, 10 simultaneous requests and process them one-by-one.</p></li>
</ul>

<p>I don't know how much that additional information helps, but there it is. :)</p>

<hr>

<p>I'm trying to create a simple processing queue.  On <code>Enqueue</code>, it adds an item to a store, then checks to see if the processing thread is already running or not.  If it is, it's done; if not, it kicks off the thread that runs the queue.</p>

<p>The queue thread itself queries the store for its next item and process it.  Then it queries the store for its next item, and keeps going until it runs out of items.  Then it stops processing and shuts down until the next item is enqueued.</p>

<p>The code basically looks like this:</p>

<pre><code>// Service that saves and retrieves items from a database
private IItemService _service;

// Item processor
private IItemProcessor _itemProcessor;

public void Enqueue(object item)
{
   _service.Save(item);
   if (_isRunning)
   {
      // If the queue is processing, the item just gets added to the DB and
      // the processing function will pull it off of the DB when needed.
      return;
   }

   // If it's not already running, process whatever queue items are in the DB.
   ProcessQueue();
}

private void ProcessQueue()
{
   _workerThread = new ThreadStart(ProcessQueueInternal);
   _workerThread.Start();
}

private void ProcessQueueInternal()
{
   // _service.GetNextItem() retrieves an item from the DB based on several
   // factors, including whether another instance of a queue has claimed it,
   // priority, etc.
   object item;
   while (item = _service.GetNextItem()) != null)
   {
      _itemProcessor.ProcessItem(item);
   }

   // No more items in the DB, so the queue should sit idle until a new
   // item is enqueued.
   _isRunning = false;
}
</code></pre>

<p>I'm testing out this queue using a <code>Parallel.ForEach()</code> loop, like so:</p>

<pre><code>Parallel.ForEach(myItems, item =&gt; Enqueue(item));
</code></pre>

<p>The problem I'm running into is that occasionally the queue fires off twice, which I want to avoid.  Not regularly, but it happens enough that I want to prevent that from happening.</p>

<p>How can I get around this?  It's possible that multiple items will be enqueued simultaneously, and I need to make sure that there is only one background thread running at once.  Is the best way something simple, like this?</p>

<pre><code>private void ProcessQueue()
{
   if (_workerThread == null || (_workerThread != null &amp;&amp; _workerThread.IsAlive))
   {
      _workerThread = new ThreadStart(ProcessQueueInternal);
      _workerThread.Start();
   }
}
</code></pre>

<p>Or is there a better way?  Simplicity is the goal here, second only to effectiveness.</p>

<hr>

<p><strong>A Better Explanation</strong></p>

<p><strong>Goal</strong>: Funnel a bunch of HTTP requests that can trigger a long running process in such a way so that the process gets run on a single thread.  The workflow is as follows:</p>

<ol>
<li><p>User sends an HTTP POST (from an Angular site we're also developing) with all the information we need to execute it, including a route to execute.</p></li>
<li><p>The POST hits a WebAPI <code>ApiController</code>, which itself calls a service.</p>

<ul>
<li>The service itself is instantiated through Unity with a <code>ContainerControlledLifetimeManager</code>, so it's constantly running in the background.  (We've tested that this is the case.)</li>
</ul></li>
<li><p>The service adds the data that came in from the POST to a database table via EntityFramework.</p>

<ul>
<li>If the service is already processing items, it simply stops here.</li>
<li>If the service is not processing items, it starts to do so.</li>
</ul></li>
<li><p>The service processes items by retrieving them, one at a time, from the database.  Each item is processed by getting all of its data and sending off an HTTP POST to another service (which kicks off a process there that can't really be run concurrently, a limitation of a library we're using), then waiting for it to complete.  Once it's complete, it sets the state of that item to Success/Error, then gets the next item from the DB and repeats, until there are no more items in the DB to process.</p></li>
<li><p>Items are selected from the DB on the basis of priority and whether it's been run before or not (i.e., status is InQueue and not Success/Error).</p></li>
</ol>

<p>There are three benefits here that we're aiming for:</p>

<ol>
<li><p>With the DB as the backing store, we have some safety against the case where the application dies for some reason.</p></li>
<li><p>The queue doesn't need to keep polling the DB when it runs out of items to process.  It just sits there, idly, until a new item is enqueued, in which case the entire process starts up again.</p></li>
<li><p>With no backing collection internally, we don't need to worry about data loss when items are pulled out of the DB and the application dies for some reason.  This is related to #1.</p></li>
</ol>

<p>The biggest danger we have -- and the problem I'm running into -- is that the ultimate entry point here is a web site, and a button on that site.  So it's entirely possible that 100 people hit the button all at once, and ultimately the process that is at the end of this mess has to run in a serial manner.  So we need to funnel all of those requests down to a single-file line.  As a result, the entire queue should be processed by one thread.  Here I'm using a single thread named <code>_workerThread</code>.  The issue I'm having is ensuring that <code>_workerThread</code> is instantiated and started once for any cycle.  That is:</p>

<ul>
<li>Queue is being processed and a new item comes in: <em>do not start a new thread</em>.</li>
<li>Queue is not being processed and a new item comes in: <em>start a new thread</em>.</li>
</ul>

<p>The only way I could think of to simulate multiple users here is via <code>Parallel.ForEach</code>.  I'll explain my testing methodology below.</p>

<p><strong>Code:</strong> The updated code for the queue service is above.  Specifically, the <code>Enqueue</code>, <code>ProcessQueue</code>, and <code>ProcessQueueInternal</code> are the relevant portions that are causing my problems.  I have updated them to be as clear as possible.  Ultimately, they contain two major parts:</p>

<ul>
<li><p><code>_service</code> is a separate item service, responsible for the simple save, delete, and update methods, as well as pulling the next item off of the queue.  It is inserted into the queue via dependency injection.</p></li>
<li><p><code>_itemProcessor</code> is a separate class responsible for processing the item.  In the real world, it would create an <code>HttpClient</code> and fire off the request in the item data.  I split it out mostly so I could create a fake one for unit testing the queue without a database.</p></li>
</ul>

<p><strong>Testing</strong>: I'm trying to test this via unit tests, since we don't yet have the UI hooks necessary to test this in the real world.  To do this, I've made ""fake"" versions of the item service and the item processor:</p>

<ul>
<li><p>The fake item service just stores new queue items in a <code>List&lt;WebRequestQueueItem&gt;</code>.  This could be the cause of my problems right here, now that I think about it, but I'm not sure.  I'm a little afraid that using some sort of thread-safe collection for the fake service would be adding a ""fix"" for a real-world problem (since when the queue actually goes into use outside of unit tests, it will be using the DB as its backing store).</p></li>
<li><p>The fake item processor just does a <code>Thread.Sleep</code> for 1500ms.  It's there to simulate that the ultimate action that's being taken will take a while.</p></li>
</ul>

<p>To simulate multiple people hitting the server all at once, I'm using <code>Parallel.ForEach()</code>.  I don't know of a better way to simulate this.</p>

<p><strong>The Problem</strong>: Ultimately the problem is that the <code>Parallel.ForEach()</code> loop adds items all at once to the item service, but it's doing so quickly enough that the queue doesn't have time to realize that the items are already being processed.  So it starts off another <code>_workerThread</code>, which is exactly what I don't want it to do.</p>

<p>My suspicion is that it's the general process that's broken, not the fact that I'm using <code>List</code> as the backing store in this case.  Somehow, I need to make sure that if the item is added very quickly, or if dozens of people add items to the queue all at once, multiple instances of the queue don't get kicked off.  I have found that once the queue kicks off, everything works fine -- new items can be added to it and they'll just get processed when the service gets to it.  But it's that initial start that's causing me problems.</p>

<p>A note about the DB service itself: it's using EntityFramework, and the standard methods for adding/update/deleting items.  The patterns are identical across our entire product, and we've had no problems that I'm aware of yet.  Still, the methods look like this:</p>

<p><em>Add</em></p>

<pre><code>_context.WebRequestQueueItems.Add(someItemEntity);
_context.SaveChanges();
</code></pre>

<p><em>Update</em></p>

<pre><code>_context.WebRequestQueueItems.AddOrUpdate(someItemEntity);
_context.SaveChanges();
</code></pre>

<p><em>Remove</em></p>

<pre><code>_context.WebRequestQueueItems.Remove(someItemEntity);
_context.SaveChanges();
</code></pre>

<p><em>GetNextItem (roughly; the clauses are slightly more complicated than this, but you get the idea)</em></p>

<pre><code>return _context
       .WebRequestQueueItems
       .OrderByDescending(item =&gt; item.Priority)
       .FirstOrDefault();
</code></pre>
",https://stackoverflow.com/questions/45177868/keeping-a-single-background-thread-through-a-parallel-foreach,"['c#', 'multithreading']",350,TRUE,-1,1
,,,,,,,
