mercredi 1 mai 2019

Perl6 generic code to test if modules load

This is a generic code code in /t to test if .pm6 modules in /lib load.

use lib $*PROGRAM.sibling('../lib');
use Test;

my @dir = dir($*PROGRAM.sibling('../lib'), test => { $_ ~~ /.*pm6/  } );
plan @dir.elems;

sub module( IO $dir ) {
  $dir.basename.Str ~~ /(\w+)\.pm6/;
  return $0.Str;
}

for  @dir.map(&module) -> $module {
  use-ok $module, "This module loads: $module";
}

Before going any further (recursively looking at lib sub-folders ), I wonder in this is the right approach.

Thanks!

Java JUnit Testing guidance needed

I am trying to run create some tests for the program I have. I am still new to Java and programming as a whole so I am unsure what to do. I have a .csv file lets just call it testdata.csv and I want to look for certain words within that test file for a test. So for example a test that can display multiple strings from within that file and say they are in there.

I have tried using assert.that but it didn't work for me I probably did it wrong. Was just searching online and trying to piece things together. The code I had included was the last attempt I had done and I know it isn't right...


@org.junit.Test
    public void testAssets (){

        String fileName;

        fileName = "testdata.csv";

        Assert.that(fileName, hasItems);


For the test to fail if it doesn't have the string "UDP,TCP,ICMP"

How can I click/target at a pseudo element with Selenium IDE for Chrome?

I'm currently trying to click at a pseudo element of a search icon on a customers website. Sadly, I've found now way how to do this. I've started with trying to click the parent element with:

enter image description here

But this ends up in a timeout because the element can't be found (before element). The structure of the element is following:

<span id="et_search_icon">
    ::before
</span>

So is there any way to target the pseudo element within Selenium IDE for Chrome?

how to implement a component in java

so i am a bit not good at programming. i want to implement a memory stack.

i have already written some methods and i need help or guides for the implementations. i will give the classes below

/** * This MemoryStackService is an interface to help memorize information * through stacks of index cards. */

public interface MemoryStackService {

/**
 * Returns a list of available index card stacks.
 *
 * @return List of index card stacks
 */
List<MemoryStackDescriptor> getMemoryStacks();

/**
 * Returns the descriptor of the memory stack with the given id.
 *
 * @param id id of the memory stack
 * @return descriptor of the memory stack
 * @throws IllegalParameterException if the id does not exist
 */
MemoryStackDescriptor getMemoryStack(int id) throws IllegalParameterException;


List<IndexCard> getCards(int stackId, boolean randomized) throws IllegalParameterException;

/**
 * stages index cards which were not answered correctly to be asked again.
 *
 * @param id
 * @throws IllegalParameterException if the id does not exist
 */
void addWrongAnsweredCards(int id) throws IllegalParameterException;

void addCorrectAnsweredCards(int id) throws IllegalParameterException;

List<IndexCard> getWrongAnsweredCards();

void resetWrondAnsweredCards();

int createMemoryStack(String name) throws IllegalParameterException;

int addCard(int stackId, IndexCard card) throws IllegalParameterException;

}

public class IndexCard {

private int id;
private String content;
private String solution;
private boolean knewAnswer;

public int getCardId()
{
    return id;
}

public String getCardContent() {

    return content;
}

public String getSolution() {

    return solution;
}

public void SetKnewAnswer(boolean knewAnswer) {
    this.knewAnswer = knewAnswer;
}

public boolean GetKnewAnswer() {

    return knewAnswer;
}

}

public class MemoryStackServiceMain implements MemoryStackService {

/**
 * Returns a list of available index card stacks.
 *
 * @return List of index card stacks
 */
@Override
public List<MemoryStackDescriptor> getMemoryStacks() {
    List<MemoryStackDescriptor> results = new ArrayList<>();

    return results;

}

/**
 * Returns the descriptor of the memory stack with the given id.
 *
 * @param id id of the memory stack
 * @return descriptor of the memory stack
 * @throws IllegalParameterException if the id does not exist
 */
@Override

public MemoryStackDescriptor getMemoryStack(int id) throws IllegalParameterException { return null; }

@Override
public List<IndexCard> getCards(int stackId, boolean randomized) throws IllegalParameterException
{
    return null;
}

/**
 * stages index cards which were not answered correctly to be asked again.
 *
 * @param id
 * @throws IllegalParameterException if the id does not exist
 */
@Override
public void addWrongAnsweredCards(int id) throws IllegalParameterException {}

@Override
public void addCorrectAnsweredCards(int id) throws IllegalParameterException {}

@Override
public List<IndexCard> getWrongAnsweredCards(){
    return null;
}

@Override
public void resetWrondAnsweredCards() {}

@Override
public int createMemoryStack(String name) throws IllegalParameterException {
    return 0;
}

@Override
public int addCard(int stackId, IndexCard card) throws IllegalParameterException {
    return 0;
}

}

With Memory Stack a user for example a student is able to create stacks of index cards.With those cards which contain a question and corresponding answer the student can study for an upcoming exam or learn anything else that they need to memorize.

How to perform POST request in Axios with the given headers, auth (username, password) & data(payload)?

I am generating access token from Authorization-(Type: OAuth 2.0) in Postman and with that token i am able to get the response by passing the headers, payload in body for my POST request But the same is not working in Javascript code using Axios for my protractor test? Below is my code:

this.postAxiosReq = function(){
    var headers = {
        'Authorization': 'Bearer myTokenWhichIsGeneratedInPostman',
        'Accept': 'application/json',
        'Content-Type' : 'application/json'
    }

//this data is the Body (raw) in JSON which i am passing in Postman as a Payload

    var data = {
        "from": "2019-04-18T18:30:00.000Z", "to": "2019-04-26T18:29:59.999Z", "countries": ["India"],"timeFrame": "Last7Days"
    }

/this is app uername and password,

    var auth= {
        username: "username@test.com",
        password: "somepassword"
    }



    const url = 'https:/myapiUrl';
    console.log('start post req:::::')

    axios.post(url,{
        headers,
        auth, 
        data })
    .then(res =>{
        console.log('NEED RES:::::',res)
        return res.data;
    })
    .then(response =>{
        console.log('FINAL RESPONSE::::::::',response.data);
    })
    .catch(err =>{
        console.log(err);
    })
}

I am using Axios to perform POST request but in this case i am not getting any response in console for the above code. Also i want to tell that i need to generate access Token first to perform the Request, the same is working in Postman no issue. So first i am using the same generated token (hardcoded) here in my Authorization': 'Bearer myTokenWhichIsGeneratedInPostman, just to check whether i m able to get response or not. Plz tell me guys where i am doing mistake. Explain me if possible. Please answer Thanks in advance

How do I / Should I unit test a wrapper class for Log4Net?

I have two applications that are currently using a logging service that has been duplicated across both code bases. I am in the process of creating a small library that contains only the logging functionality so I can easily publish it as a NuGet package and use the shared logging library across both projects without duplicating my code.

My problem is the following: I have no idea how, or whether I should, test the basic functionality of the logger I have implemented.

My instinct was to start by unit testing the constructors, but because so much of the logic of configuring an instance of Log4NetLogger is actually part of log4net, I felt as though I was unit testing their code rather than my own. As for the Write functions, is it really necessary that I test if Log4Net actually writes to a file or console? It feels like I will end up testing an infinite number of use cases related to potential log4net configurations.

public interface ILogger
{
    void Write(LogLevel level, string message);
    void Write(LogLevel level, string message, object obj);
}

public class Log4NetLogger : ILogger
{
    private ILog Logger { get; }
    private readonly string InitializationMessage = "Initializing logger...";

    public Log4NetLogger()
    {
        BasicConfigurator.Configure();
        Logger = LogManager.GetLogger(typeof(Log4NetLogger));
        Write(LogLevel.Debug, InitializationMessage);
    }

    public Log4NetLogger(string configurationFile)
    {    
XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), new FileInfo(configurationFile));
            Logger = LogManager.GetLogger(typeof(Log4NetLogger));
            Write(LogLevel.Debug, InitializationMessage);
    }

    public void Write(LogLevel level, string message, object obj)
    {
        var serialized = JsonConvert.SerializeObject(obj);

        Write(level, $"message: {message} object:{serialized}");
    }

    public void Write(LogLevel level, string message)
    {
        switch (level)
        {
            case LogLevel.Debug: Logger.Debug(message); break;
            case LogLevel.Information: Logger.Info(message); break;
            case LogLevel.Warning: Logger.Warn(message); break;
            case LogLevel.Error: Logger.Error(message); break;
            case LogLevel.Fatal: Logger.Fatal(message); break;
         }
     }
}

The point of the ILogger interface is to enable me to do Dependency Injection, so I can inject mocks into consumers of the service, enabling me to test them without having the need for a dependency on log4net.

If anyone can tell me if this is actually testable and how you might approach testing this yourself if it is indeed worth testing. Any guidance or resources relating to this would be hugely appreciated.

list index out of range when performing database queries in Hypothesis function

I'm using Python Hypothesis to write random tests for database. After 1-2 loops of insert the given values to the table I get list index out of range and @seed to reproduce. There is nothing that suppose to fail, I'm not asserting anything yet. How can I debug this?

Thanks

        run_statement("create table t (x int)")
        @given(st.integers(1,10), st.integers(1,10))
        def insert_select(x):
            assume(x)
            run_statement("insert into t values ({})".format(x))
            select_results = run_statement_with_results("select * from t")
            print select_results

        insert_select()


results:

You can add @seed(257907719204305935240373390472712621009) to this test to reproduce this failure.
timeout
error: list index out of range