jeudi 1 octobre 2015

How to make a system time independent timer in Java?

I am attempting to create a System Time Independent timer. In order to do this I have created an extension of the Timer object which overwrites the schedule methods and uses them as adapters to the schedule methods of the new TimerObject. The new Timer schedules Tasks which are of a local duplicate of the base TimerTask class to allow for access to the package private fields of TimerTask. This new TimerTask class includes a field for a base TimerTask object and behaves as a wrapper, the run method of the containing TimerTask calls the run method of the contained TimerTask to maintain the expected behavior. The problem I have encountered is with rescheduling, cancellation and repeated events. The new Timer is unable to access the nextExecutionTime and status fields of the inner TimerTask and so is unable to detect when the inner TimerTask has been cancelled and so events are executed regardless of whether or not they have been cancelled or experienced other status changes.

This is relevant because this class is meant to be swapped in for testing purposes and should not require modifications to the class it is testing, the new Timer is passed in in place of a standard timer and appears to behave as such from the application perspective however I am unable to achieve this without access to the fields of the contained TimerTask with which the class being tested interacts.

The present state of the code below is attempting only to make single executions work with all repeating schedule throwing a runtime error although the original code from each is present but commented out. As an attempted workaround for the one-time execution case The run method of the containing TimerTask calls the cancel method of the contained task which should return true if the contained task was scheduled and had not beed previously cancelled however the inner tasks state remains VIRGIN (read 0) and so this method does not work either.

Can anyone suggest a way of fixing this problem either by gaining access or through another design?

The code is in the following gitHub repo:

http://ift.tt/1JGWtty

I have renamed the files and removed packages, in the working code they are both done according to convention.

Meteor Velocity/Jasmine fails to start Karma through proxy

I am attempting to test a meteor application using Jasmine built on Velocity. When I test the application behind our corporate proxy, Karma does not start, the tests don't run, and I get this error in my Jasmine logs:

stream error Error during WebSocket handshake: Unexpected response code: 301

Presumably because it cannot connect to Karma.

I have tried this outside of our intranet (with no proxy), and it works just fine. Unfortunately, it isn't really feasible to run tests outside of our network.

Is there a setting that I am missing that would make this work?

Is the java code for this method correct?

For an assignment, I am told to write two methods--incrementDay() and incrementMonth().

I was hoping you guys could tell me if the code/logic is correct? Also, I would like to know if my test is thorough enough?

Thanks in advance! I know this is a long post--I apologize, and I won't do this often.

Assignment:

"incrementDay()

This method takes no input and returns nothing. If the previous month's balance was not paid in full, the credit card charges interest on the current balance after each day. To do this, the class will need two additional fields, a variable that keeps track of the interest charged so far and a boolean variable that is a paid-in-full flag that keeps track of whether the user has paid the balance in full.

incrementDay works as follows: If the paid-in-full flag is false then sum the account balance and the interest charged so far, then multiply this sum by the interest rate divided by 365, and add this value to the interest charged so far.

If the paid-in-full flag is true, then there is nothing to do.

incrementMonth()

This method takes no input and returns nothing. Add the interest charged so far to the account balance. Reset the interest charged so far to 0.

If the total payment this month is greater than or equal to the monthly payment, set the paid-in-full flag to true, otherwise set the flag to false.

If the minimum monthly payment is smaller than the monthly payment and the total payment this month is less than the minimum monthly payment, add the late payment penalty to the current balance.

Set the total payment this month to 0.

Set the monthly payment equal to the current balance."

Code:

public void incrementDay()
  {
    if(!paidInFullFlag)
    {
      interestCharged += (this.balance + interestCharged) * (interestRate/365);
    }
  }

  /*Method adds interestCharged to balance and checks whether or not account has been paid in full for month*/
  public void incrementMonth()
  {
    this.balance += interestCharged;
    this.interestCharged = 0;
    if(this.sumPayment >= this.monthlyPayment)
    {
      this.paidInFullFlag = true;
    }
    else 
    {
      this.paidInFullFlag = false;
    }

    if(minMonthly < monthlyPayment && sumPayment < minMonthly)
    {
      this.balance += latePaymentPenalty;
    }
    this.sumPayment = 0;
    this.monthlyPayment = this.balance;
  }

Test:

> CreditCardAccount c = new CreditCardAccount()
> c.setCreditLimit(100)
> c.setInterestRate(.08)
> c.setLatePaymentPenalty(3)
> c.setMinMonthlyPayment(20)
> c.charge(30)
true
> c.getBalance()
30.0
> c.payment(5) //pay 5 dollars towards balance
> c.incrementDay() 
> c.incrementMonth()
> c.getBalance() //flag is initially set to true, so no late payment penalty or interest is charged, but flag is set to false for next month
25.0
> c.payment(5)
> c.charge(20)
true
> c.getBalance()
40.0
> c.incrementMonth() //late payment penalty is charged
> c.getBalance() 
43.0
> c.incrementDay()
> c.getBalance()
43.0
> c.incrementMonth()
> c.getBalance() //interest AND late payment penalty is added
46.00942465753425

UITesting Xcode 7, unable to tell if UIButton is visible within UIScrollView

I am automating an app using UI Testing in Xcode 7. I have a scrollview with buttons all the way down it. Sometimes the buttons are visible sometimes they hidden too far up or down the scrollview (depending on where I am on the scrollview).

Is there a way to scroll items into view or maybe tell if they are visible or not?

Thanks

Custom django management command with appended parameters

My team runs a custom test suite pretty regularly. When we want to run the whole thing, we do

./manage.py test --keepdb --failfast --settings=AE.test_settings

When we want to run tests on a specific app, we do the same, but with the app name include.

I'd like to make a custom management command that, when called, will run the default test suite, but append the --keepdb, --failfast, and --settings=AE.test_settings params. Ideally something like

./manage.py aetest

That can also be run with app names, such that

./manage.py aetest registration

Would be the same as running

./manage.py test registration --keepdb --failfast --settings=AE.test_settings

My attempt so far is

from django.core.management.base import BaseCommand, CommandError
from django.core import management

class Command(BaseCommand):

    def handle(self, *args, **kwargs):
        positional_arguments = [
            '--keepdb',
            '--failfast',
            '--settings=NJ.test_settings',
        ]
        for item in args:
            positional_arguments.append(item)
        keyword_arguments = {
            'settings': "AE.test_setings",  
        }
        keyword_arguments.update(kwargs)
        management.call_command("test", *positional_arguments, **keyword_arguments)

If I try to pass further positional arguments, my command errors out in such a way as to imply they were never passed. And the keyword argument never makes it to the call_command (the command runs with my default settings.py file)

Any idea how I can have this management command accept additional positional and keyword parameters, but append the desired ones automatically?

Thanks!

PHPUnit testing file_get_contents

I have a class which has a method that makes use of PHP's global file_get_contents function. I need to test the method on the class, without actually calling the global function.

I know that I could use namespaces to override what gets returned from file_get_contents, however my tests are in a separate namespace already so I cannot simply match namespaces with the class.

Here's some code:

The class

<?php
namespace MyVendor\MyProject;

class MyClass
{

public function myMethod()
{
    $request = 'http://domain.com';
    $response = $this->someMethodUsingGlobals($request);
    // Do something with the response..
}
private function someMethodUsingGlobals($url)
{
    return json_decode(file_get_contents($url),true)['results'][0];
}

}

The test

<?php
namespace MyProjectTests;

public function test_it_does_something_with_the_response()
{
    $sut = new MyClass();

    $response = $sut->myMethod();

    $this->assertEquals('Some expectation', $response);
}

I need to mock the someMethodUsingGlobals() method on the class, but not entirely sure how to go about this.

Protractor - count elements in xpath and store it to var

I need to store the value of number of records from the table in some variable in order to use it lately. For now tried to simple print number of records like this:

    var rows = element.all(by.xpath('//*[@id="content"]/div/div/table/tbody/tr'));
    var sum = rows.count();
    console.log(sum.getText());

or like that:

element.all(by.xpath('//*[@id="content"]/div/div/table/tbody/tr')).count().then(function(count) { console.log(count); });

but each time I am getting Failed: object is not a function. Anyone could help with that ?

Tried solutions from this thread: Protractor - count elements in repeater and print it - but did not work.