Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, February 6, 2014

Python unittest

Прочитав замечательную статью http://gahcep.github.io/blog/2013/02/10/qa-in-python-unittest/ для себя сделал пометки - может кому понадобятся, просто копируем в файл и компилируем смотрим результат.

import unittest
def setUpModule():
     #Инициализация переменных для всего модуля
     print ("In setUpModule()")
def tearDownModule():
     #Удаление всех переменных инициализированных в модуле
     print ("In tearDownModule()")
class BaseTestClass(unittest.TestCase):
     def test_add(self):
          #проверка того что внутри функции будет False
          self.assertFalse(10 > 20)
          #проверка того что внутри функции оба значения равны
          self.assertAlmostEqual(30, 30)
          #проверка того что первое значение больше второго
          self.assertGreater(120, 100)
          #проверка того что в первом масиве такие же как во втором
          first=[1,5,6]
          second=[5,6,1]
          self.assertCountEqual(first, second, 'msg')
          #проверка обих частей выражения на верность условий
          first=1
          second=2
          self.assertIs(first==1, second==2, 'msg')
          #проверка того что внутри функции будет True
          self.assertTrue(100 < 200, 'msg')
          #вызов исключительной ситуации найден еррор.
          #self.fail('all is bed')

class SecondClass(unittest.TestCase):
     #Задание переменных для класса тестов
     @staticmethod
     def setUpClass():
          print ("In setUpClass()")

     def setUp(self):
         #Задание переменной val для теста test_sub
         self.val = 220
         print ("In tearUp()")

     def test_sub(self):
          self.assertEquals(220, self.val)

     #Обнуление переменных для теста test_sub
     def tearDown(self):
          self.val
          print ("In tearDown()")

     #Обнуление переменных для класса тестов
     @staticmethod
     def tearDownClass():
          print ("In tearDownClass()")

 #Показаны все возможные ошибки возбуждаемые при проходе тестов
 class ThirdTestClass(unittest.TestCase):
    def test_ok(self):
        #Если тест проходит успешно
        self.assertEquals(210, 110 * 2 - 10)

    @unittest.skip('not supported')
    def test_skip(self):
        #Если тест помечен как - пропусить тест
        self.assertEquals(1000, 10 * 10 * 10)

    def test_fail(self):
        #Если тест заваливается
        self.assertEquals(420, 210 * 2.1)

    def test_error(self):
        #Если в тесте возникает ошибка
        raise ZeroDivisionError('Error! Division by zero')

    @unittest.expectedFailure
    def test_expected(self):
        #Если в тесте возникает ошибка которую програмист отловил с помошью try except
        raise ZeroDivisionError('Error! Division by zero')

unittest.main()


Short variant as I use this module

import unittest
import time
import Promwadserial


class Turin_Test(unittest.TestCase):

    def setUp(self):
        Promwadserial.try_connect_to_board(115200, 5)
        Promwadserial.sendCmd('root' + '\r\n')
        time.sleep(3)
        Promwadserial.sendCmd('root' + '\r\n')

    #@unittest.skip("skipping") 
def test_pwd(self):
        """pwd operation test""" 
        print("id: " + self.id())
        time.sleep(3)
        self.assertEqual(Promwadserial.sendCmd('pwd' + '\r\n'), ['/root'])


def suite():
    suite = unittest.TestSuite()
    suite.addTest(Turin_Test('test_pwd'))
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite())
    Promwadserial.Close_serial_board()

Tuesday, November 20, 2012

Python work with Flash drive

Задача:
1. Написать функцию которая записывает на Flash Disk в NAND определенную информацию( set_information_on_flash('/dev/sdb1', 'inputBuffer') )
2. Написать функцию которая считывает с Flash Disk файл определенную информацию(get_information_from_flash('/dev/sdb1', 'outputBuffer') )
3. Написать функцию которая сравнивает записанную информацию на Flash Disk в NAND с считанной информации с Flash Disk.(compare_information_in_out_file('outputBuffer','inputBuffer') )

#!/usr/bin/python

import commands
import re
import os
import csv

def main():

  set_information_on_flash('/dev/sdb1', 'inputBuffer')
  get_information_from_flash('/dev/sdb1', 'outputBuffer')
  compare_information_in_out_file('outputBuffer','inputBuffer')
 
def get_information_from_flash(devise, fileOutput):
    if os.path.exists('./%s' % (fileOutput)) == True:
        cmd = "dd if=%s of=%s bs=1 count=10 skip=1000" % (devise, fileOutput)
        output = commands.getoutput(cmd)
        print "Information getted"
    else:
        cmd = "touch ./%s" % (fileOutput)
        output = commands.getoutput(cmd)
        print "Please restart program, file %s is created" % (fileOutput)

def set_information_on_flash(devise, fileInput):
    if os.path.exists('./%s' % (fileInput)) == True:
        cmd = "dd if=%s of=%s bs=1 count=10 seek=1000 conv=notrunc" % (fileInput, devise)
        print cmd
        output = commands.getoutput(cmd)
        print "Information writed"
    else:
        cmd = "touch ./%s" % (fileInput)
        cmd1 = "echo 'AaBbCcDdEe' > ./%s" % (fileInput)
        output = commands.getoutput(cmd)
        output = commands.getoutput(cmd1)
        print "Please restart program, file %s is created" % (fileInput)

def compare_information_in_out_file(fileOutput,fileInput):
        fo = open(fileOutput, 'r')
        checkFile = fo.read(10)
        fo1 = open(fileInput, 'r')
        checkFile1 = fo1.read(10)
        print "Read from Outputfile = " + checkFile
        print "Read from Input file = " + checkFile1
        if checkFile != checkFile1:
            print "Reading is false"
        else:
            print "Reading is true both file is equal"
        fo.close()
        fo1.close()

if __name__ == '__main__':
  main()