Sunday, July 28, 2019

Testing with Scala / SBT


Testing with Scala / SBT


Pre-Req :
Os - Linux ubuntu / debian
Java /jdk 1.8 +
scala 2.11 +
Intellij
Install sbt plugin in Intelli
Create an scala project in Intelli using sbt

Commands:
scala -version
sbt sbtVersion

----build.sbt (add below line)--------
scalaVersion := "2.xx.0"
libraryDependencies += "org.scalatest" % "scalatest_2.xx" % "3.0.8" % "test"
libraryDependencies +="org.pegdown" % "pegdown" % "1.4.2" % "test"
libraryDependencies += "org.mockito" % "mockito-all" % "1.8.4"
libraryDependencies += "org.scalamock" %% "scalamock" % "4.3.0" % "test"
testOptions in Test += Tests.Argument(TestFrameworks.ScalaTest, "-h", "target/test-reports")
(click on auto-import link when it appears)


--- install sbt----
open terminal
echo "deb https://dl.bintray.com/sbt/debian /" | sudo tee -a /etc/apt/sources.list.d/sbt.list
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2EE0EA64E40A89B84B2DF73499E82A75642AC823
sudo apt-get update
sudo apt-get install sbt

---- Config sbt in IntelliJ----
to Debug/Run test in sbt:
1. Edit Configurations
2. "+" Add Scala Test
3. In the new file , Select the test file (test.scala)
4. Check "use sbt"
5. Apply and OK
6. rt ck on test file in File structure/ editor / tool bar - ck run/Debug
-----Run Sbt in terminal -----
cd to  projects >
run command "sbt test"
---------------------

Src File : src/main/scala/sqCalculator.scala
object sqCalculator extends App {
  def sq(x: Int) = {
    x * x
  }
}

Test File : test/scala/sqCalculatorTest.scala
import org.scalatest.FunSuite
class sqCalculatorTest extends FunSuite {
  test("sqCalculator.cube") {
    if(sqCalculator.sq(3) === 9){
      println ("passed")
      assert (true)
    }
    else{println (false)}
  }
}
---------------------//Mockito----------------------------
//test/scala/LoginService.scala 

trait LoginService {
  def login(name: String, password: String): String
}

//test/scala/LoginServiceTest.scala
import org.scalatest.FunSuite
import org.scalatest.BeforeAndAfter
import org.scalatestplus.mockito.MockitoSugar
import org.mockito.Mockito._

class LoginServiceTest extends FunSuite with BeforeAndAfter with MockitoSugar {
  before {
    println("Start")
  }
  after {
  println("Ends")
  }

  test ("test login service"){
    val service = mock[LoginService]
    when(service.login("johndoe", "secret")).thenReturn(("johndoe"))
    when(service.login("joehacker", "secret")).thenReturn("an")
    val johndoe = service.login("johndoe", "secret")
    val joehacker = service.login("joehacker", "secret")
    if(johndoe == "johndoe"){
      assert(true)
    }
    if(joehacker == None)
      assert(false)
    else
        assert(true)
  }
}

----------------ScalaMock--------------------------------
//test/scala/LoginServiceTest2.scala
import org.scalatest.{BeforeAndAfter, FunSpec, FunSuite}
import org.scalamock.scalatest.MockFactory

class LoginServiceTest2 extends FunSpec with BeforeAndAfter with MockFactory  {
  before{
    println("LoginServiceTest2 - start")
  }
  it("val test") {
  val any_name: LoginService = mock[LoginService]
    (any_name.login _) expects("a","a") returning "hi"
    println(any_name.login("a","a"))
  }
  after{
    println("LoginServiceTest2 - end")
  }
}

Monday, July 8, 2019

Python : Pytest-selenium without setup/installation of driver

Python : Pytest-selenium without setup/installation of driver

project/requirements.txt
pandas >= 0.24.2
numpy >= 1.16.3
pytest >= 3.10.1
pytest-html >= 1.20.0
pytest-metadata >= 1.8.0
pytest-profiling >= 1.6.0
pyderman >= 1.3.0
pytest-selenium >= 1.16.0


project/tests/test_case1.py
import pytest
from lib import csv_reader
import os
import pyderman as dr
from pathlib import Path



link="https://www.stats.govt.nz/assets/Uploads/Electronic-card-transactions/Electronic-card-transactions-May-2019/Download-data/electronic-card-transaction-may-2019-csv.zip"
import pytest
@pytest.fixturedef firefox_options(firefox_options):
    #firefox_options.binary = '/path/to/firefox-bin'    
       destination = str(Path(__file__).resolve().parents[1]) + "/temp/"    destination="/home/deepak/PycharmProjects/csv_test/temp"    
   if(os.path.exists(destination)):
        print(destination)
        print("paht exists")
    destination=destination.replace("\\","\\\\")
    firefox_options.add_argument('-foreground')
    firefox_options.set_preference('browser.download.folderList', 2)  # custom location    firefox_options.set_preference('browser.download.manager.showWhenStarting', False)
    firefox_options.set_preference('browser.download.dir', destination)
    firefox_options.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/zip")
    return firefox_options

def test_deep():
    if(1==1):
        path = dr.install(browser=dr.firefox)
        print('Installed geckodriver driver to path: %s' % path)
        print("yes")
        assert True    else:
        print("no")
        assert False

def test_example(selenium):
    selenium.get(link)

--------------------------
To RUn :
1. open terminal
2. cd inside project
3. pip install requirements.txt
4. pytest

Python : Pytest logger


 Python : Pytest logger


Create file : /project/pytest.ini

[pytest]

testpaths = tests/
python_paths = ./

console_output_style = progress
addopts = -rsxX -q

log_cli = 1
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_cli_date_format=%Y-%m-%d %H:%M:%S

log_file_date_format = %Y-%m-%d %H:%M:%S
log_file_format = %(asctime)s %(levelname)s %(message)s
log_date_format = %Y-%m-%d %H:%M:%S
log_file=simple_logger.log
log_print = True

python_files =
    test_*.py
    *_test.py
 
 


Using without class :
LOGGER = logging.getLogger(__name__) #Decalared as a global
LOGGER.error("Unable to make connection to DB")#to log fails inside/ouside def

Usage in a class :
self.LOGGER = logging.getLogger(__name__)#inside a constructor
self.LOGGER.error("Unable to make connection to DB")#to log fails

Thursday, July 4, 2019

Python : Config /Properties/ ini file



Python : Config/ini/Properties file

-----------credentials.config-----------

[db]
dbname= dbname
hostname= host_anme
port= 1234
username= usr_name
password= pass

----------------------

Python : Config /Properties/ ini file


from configparser import RawConfigParser

config_path = os.getcwd()+'/properties/credentials.config'
confparser = RawConfigParser()
with open(config_path, "r") as config_file:
    confparser.read_file(config_file)

KWARGS = {
    "dbname": confparser["db"]["dbname"],
    "hostname": confparser["db"]["hostname"],
    "port":confparser["db"]["port"],
    "username": confparser["db"]["username"],
    "password": confparser["db"]["password"]
        }
"""