vendredi 1 juillet 2016

How to mock an object attribute, I can't access?

I'm trying to mock the parser.html_source attribute of the following view in my unit test. I want to overwrite it with a former downloaded html of that page.

views.py:

    def parse_online_page(request):
        site_manager = SiteManager(Constants.LOGIN)
        site_manager.login()
        site_manager.change_to_frame(Constants.HEAD)

        parser = HeadParser(html_source=site_manager.page_source)
        parser.parse()

        return redirect('another_page')

Here's my unit test:

    TESTDATA_PATH = 'core/tests/assets'


    class TestSession(TestCase):
        def test_parser_view(self):
            with patch('core.parsers.HeadParser') as parser_mock:
                with open(os.path.join(TESTDATA_PATH, 'frame_head.html'), encoding='utf8') as f:
                    parser_mock.html_source = f.read()

                    response = self.client.get(reverse('core:parse_online_page'))
                    self.assertEqual(response.status_code, 302)

                    # assert that my html test asset was parsed correctly

Unfortunatly this does not overwrite the HeadParser's html_source attribute in all instances generated out of this class.

I don't even know if this is the right attribute to mock, I'm totally clueless.

How to test child class methods only without instantiating base class in Python?

I am a newbie of Python, I need to test the child class methods without initializing a base class instance because in the base class , there are lots of dependencies on network and some other components, my child class methods are standalone.

I tried to create a new child class by removing the base class methods from the child class,but it can't work. Here are the codes.

def remove_base(child_cls, base_cls):
    allmembers = inspect.getmembers(child_cls, predicate=inspect.ismethod)
    allmembers_dict = dict(allmembers)
    hbasemembers = inspect.getmembers(base_cls, predicate=inspect.ismethod)
    hbase_dict = dict(hbasemembers)
    child_class_member = set(allmembers_dict.keys()) - set(hbase_dict.keys())
    new_dict = {}
    for key in allmembers_dict.keys():
        for child_member in child_class_member:
            if key == child_member:
                new_dict[key] = allmembers_dict[key]
    return new_dict

class A:
    def add(self, i):
        print i + 1

class B(A):
    def sub(self, i):
        print i - 1

newB = type("newB", (object, ), remove_base(B, A))
b = newB()
b.sub(5)

The error message is :

TypeError: unbound method sub() must be called with B instance as first argument (got int instance instead)

I think the way of removing base class methods may be wrong. How to handle this problem?

Unit Testing code that creates directories

I have code that creates directories and transfer files to it. I want to unit test it. But the problem is when i run the unit test these directories are created but i don't want that. I want the code to create these directories only when its running a production environment. I have googled about this, but all search results suggest the JUnit class TemporaryFolder. But that is not what i want. I am not creating directories inside my test cases. I am just testing code that creates them. So am not sure how TemporaryFolder class can help me with that. say i have code like below

public class Util {

    public File getLocation(String location) {
        File result = new File(location);

        if (!result.exists()) {
            result.mkdirs(); 
        }
        return result;
    }
}

How do i unit test such code? Every time i call util.getLocation("base/location"); The directories base/location are been created but i don't want that. They should only be created when i run the code in production environment.

Error mocking Cipher in java

In order to do the test, I mock a Cipher object, but when I run the test, its fails because it's run the cipher code instead of the mock.

So, I write a very simple test and when I run it, fails always.

My test code is:

import javax.crypto.Cipher;

import org.junit.Test;
import org.mockito.Mockito;

public class SimpleTest {
    @Test
    public void simpleTest() throws Exception {
        Cipher cipher = Mockito.mock(Cipher.class);
        cipher.doFinal(null);
        assertTrue(true);
    }
}

And the exception who produces:

java.lang.IllegalStateException: Cipher not initialized
    at javax.crypto.Cipher.checkCipherState(Cipher.java:1750)
    at javax.crypto.Cipher.doFinal(Cipher.java:2157)
    at SimpleTest.simpleTest(SimpleTest.java:12)
    ...

Why is doFinal executed?

Using vstest.console.exe TestCategory with equals and not equals

I am using SpecFlow to write Gherkin for automated UI tests. We have multiple tags (@smoke, @on, @off, etc.).

Test A has tags @smoke Test B has tags @smoke @off

These are translated to vstest test categories and do not include the @ symbol.

I want to run test A but not test B.

This is what is not working. It runs all @smoke tests. Vstest.console.exe mytest.dll /TestCaseFilter:"TestCategory=smoke&TestCategory!=off"

Any ideas?

I had some big problems for test activiti deployment with testng

i use testng to test the concurrency of activiti 5.19. first i write a unit test to deploy my bpm file. the java code as blow:

@ContextConfiguration(value = { "classpath:springTypicalUsageTest-context.xml" })
public class TaskTestPerformance extends AbstractTestNGSpringContextTests{
private static final Logger log =  LoggerFactory.getLogger(TaskTestPerformance.class);
@Autowired
private ItsProcessInstanceImp itsProcessInstanceService;
@Autowired
private ItsDeploymentImp itsDeploymentService;
@Autowired
private ItsProcessDefinitionImp itsProcessDefinitionService;
@Autowired
private ItsTaskImp itsTaskService;

private static String bpmfile = "com/jsits/bpm/activiti/test/task/taskTest.bpmn";
private static String deploymentname = "taskTasks";

@Test(invocationCount=20,threadPoolSize=10,invocationTimeOut=60000)
public void testTaskId(){
    Deployment deployment = itsDeploymentService.deploy(deploymentname, bpmfile);
    log.info(deployment.getId());
}

}

Notes: shis method will exe 20 times and with 10 threads,and will timeout after 60 seconds,just like the upper code shows:

 (invocationCount=20,threadPoolSize=10,invocationTimeOut=60000)

I run the unit test with testNG runner,and the result is: ===============================================

Default test

Tests run: 20, Failures: 13, Skips: 0

===============================================

the error details are:

Caused by: org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "ACT_UNIQ_PROCDEF_INDEX_6 ON PUBLIC.ACT_RE_PROCDEF(KEY_, VERSION_, TENANT_ID_) VALUES ( /* key:7 */ 'tasktestid:5:69', 1, 'http://ift.tt/1lD0pq1', 'tasktestname', 'tasktestid', 5, '53', 'com/jsits/bpm/activiti/test/task/taskTest.bpmn', 'com/jsits/bpm/activiti/test/task/taskTest.tasktestid.png', NULL, FALSE, TRUE, 1, '')"; SQL statement:
insert into ACT_RE_PROCDEF(ID_, REV_, CATEGORY_, NAME_, KEY_, VERSION_, DEPLOYMENT_ID_, RESOURCE_NAME_, DGRM_RESOURCE_NAME_, DESCRIPTION_, HAS_START_FORM_KEY_, HAS_GRAPHICAL_NOTATION_ , SUSPENSION_STATE_, TENANT_ID_)
    values (?,
            1,
            ?,
            ?,
            ?, 
            ?,
            ?,
            ?,
            ?,
            ?,
            ?,
            ?,
            ?,
            ?) [23505-176]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:344)
    at org.h2.message.DbException.get(DbException.java:178)
    at org.h2.message.DbException.get(DbException.java:154)
    at org.h2.index.BaseIndex.getDuplicateKeyException(BaseIndex.java:103)
    at org.h2.index.TreeIndex.add(TreeIndex.java:69)
    at org.h2.table.RegularTable.addRow(RegularTable.java:120)
    at org.h2.command.dml.Insert.insertRows(Insert.java:157)
    at org.h2.command.dml.Insert.update(Insert.java:115)
    at org.h2.command.CommandContainer.update(CommandContainer.java:79)
    at org.h2.command.Command.executeUpdate(Command.java:254)
    at org.h2.jdbc.JdbcPreparedStatement.execute(JdbcPreparedStatement.java:199)
    at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:41)
    at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:66)
    at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:45)
    at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:100)
    at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:75)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:148)
    ... 36 more

all those errors!!

I change the database form mysql to h2, and change the invocationCount from 100 to 20, threadPoolSize from 10 to 100, the error is not changed.

but if i modify the threadPoolSize=1 ,error is gone.

Is this means activiti deploy bpm ,the concurrency is bad?

thanks all of you!

Segmentation fault - suspected die on fflush(STDOUT)

I am working on a unit test which will use FILE* stream to mimic STDIN. The function will get called everytime there's a need to input the value(In this case function get called for 3 times). The code works fine until 3rd call,where i got an error:

Received signal 11 (Segmentation fault)

Is anyone know why segmentation fault happened?

I tried to printf line by line & it seems like the code dead at fflush(stdout). Is anyone know what happened?

int readInput(char *prmt,char *defaultValue,char *input)
{
  char ch, inValue[200], tmpString[200];
  int  count;

  if (strcmp(defaultValue,"")){
    sprintf(tmpString,"%s (%s) ",prmt,defaultValue);
  }

  fprintf(stdout,"%s ",tmpString);
  ch=' ';
  count=0;
  while (ch!='\n') {
    ch = getc(stdin);
    if (feof(stdin) || ferror(stdin)) {
      inValue[0]='\0';
      exit(0);
    }
    inValue[count]=ch;
    count++;
  }

  fflush(stdout);

  inValue[count-1]='\0';
  if (strcmp(inValue,"") && (inValue[0]!=';')) {
    strcpy(input,inValue);
  } else {
    strcpy(input,defaultValue);
    if (inValue[0]==';')
      return(FALSE);
  }

  return(TRUE);
} 

The file that used to mimic for series of STDIN as below($ means endline)

john$
16$
student$