Store intermediate values into array with Ruby inject - inject

I want to store ruby inject values into array I found one good example (on site http://matthewcarriere.com/2008/06/23/using-select-reject-collect-inject-and-detect/) but its returning Fixnum instead of array.
[1,2,3,4].inject([]) {|acc,n| acc << n+n}
this is returning 262144. However I want array as [2, 4, 6, 8].
Any help is appreciated.

it works in my machine.
Have you tried it in a new irb session?
Which version of ruby are you using?
$ ruby --version
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]
$ irb --version
irb 0.9.6(09/06/30)
$ irb
irb(main):001:0> [1,2,3,4].inject([]) {|acc,n| acc << n+n}
=> [2, 4, 6, 8]
irb(main):002:0>

Related

AWS php sdk is not working with PHP 7

Following code works well in PHP 5.6.
require_once '../aws/aws-autoloader.php';
$config = [
'region' => 'ap-south-1',
'version' => 'latest',
'credentials' => [
'key' => '...',
'secret' => '...'
]
];
$sdk = new Aws\Sdk($config);
$client = $sdk->createS3();
But on PHP 7, it through error:
Fatal error: Uncaught TypeError: Argument 1 passed to Aws\Common\Client\AbstractClient::__construct() must be an instance of Aws\Common\Credentials\CredentialsInterface, array given, called in /var/www/html/webservice/vendor/aws3/Aws/Sdk.php on line 316 and defined in /var/www/html/aws-sdk/vendor/aws/aws-sdk-php/src/Aws/Common/Client/AbstractClient.php:75 Stack trace: #0 /var/www/html/webservice/vendor/aws3/Aws/Sdk.php(316): Aws\Common\Client\AbstractClient->__construct(Array) #1 /var/www/html/webservice/vendor/aws3/Aws/Sdk.php(291): Aws\Sdk->createClient('S3', Array) #2 index.php(14): Aws\Sdk->__call('createS3', Array) thrown in /var/www/html/aws-sdk/vendor/aws/aws-sdk-php/src/Aws/Common/Client/AbstractClient.php on line 75
Please suggest me how can I make it work on PHP 7.
Thanks.
UPDATE: I have both AWS SDK version 2 & 3 in my project. this might be a issue of conflict. Then how to solve the conflict?
This problem doesn't have any issue with PHP 7.0.
It's the case of conflict SDK ver 2 & 3.
This two sdk can't be used together. so I had to upgrade to sdk 3.

Rails 4.1, Guard 2.10, and Minitest 5.4.1 -- RuntimeError & Rails::Generators::TestCase

I'm trying to set up Guard with Minitest in a new Rails 4 project. I updated my Gemfile with the following:
group :development do
gem 'guard'
gem 'guard-minitest'
end
And then ran bundle exec guard init minitest.
I've got a pretty simple test like so:
require 'test_helper'
describe ClassToBeTested do
describe "#initialize" do
it "should return a ClassToBeTested object" do
obj = ClassToBeTested.new
obj.must_be_kind_of ClassToBeTested
end
end
end
The class being tested is in app/services/class_to_be_tested.rb.
When I run bundle exec guard -n f I get the following:
11:35:43 - INFO - Guard::Minitest 2.3.2 is running, with Minitest::Unit 5.4.1!
11:35:43 - INFO - Running: all tests
Run options: --seed 36837
# Running:
E
Finished in 0.005190s, 192.6728 runs/s, 0.0000 assertions/s.
1) Error:
ClassToBeTested::#initialize#test_0001_should return a ClassToBeTested object:
RuntimeError: You need to configure your Rails::Generators::TestCase destination root.
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
11:35:45 - INFO - Guard is now watching at '/home/sean/Code/Ruby/work/project'
Is there something I'm missing? Something in Guard/Minitest/Rails that needs to be configured to work properly?
Figured it out -- apparently it thought that the class was a generator. Adding the following line to test_helper.rb inside the class TestCase block fixed the issue:
register_spec_type(/ClassToBeTested/, Minitest::Spec)
Is there a way to have all the classes in test/services/ be subclassed under Minitest::Spec, and not the Generator test class?

Disable DB write in testing controller - injecting doctrine.orm.default_entity_manager throws "Fatal error" when activating FOSUser and HWIOAuth

I want to disable the DB writing when functional testing a controller in phpunit.
In a project in Symfony2, I use phpunit to test a POST call to an API endpoint that saves to database. This worked and I now have a regression problem when activating FOSUser + HWIOAuth.
To avoid the phpunit writing dummy data to the database, I use this trick here: Testing Controllers in Symfony2 with Doctrine to mock the entity manager, then inject the mocked service into the container of the testing system.
This way when you run the test, the DB endpoint is mocked and it is only tested that a flush() is called thanks to the $entityManagerMock->expects($this->once())->method('flush'); that you can see in that question and in the code below.
This used to work.
This test gave green bar, POST calls were tested and no data was saved to the database.
public function testPostCreatesIssue()
{
$client = static::createClient();
$entityManagerMock = $this->getMockBuilder( 'Doctrine\ORM\EntityManager' )
->setMethods( array( 'persist', 'flush' ) )
->disableOriginalConstructor()
->getMock();
$entityManagerMock->expects( $this->once() )
->method( 'flush' );
$client->getContainer()->set( 'doctrine.orm.default_entity_manager', $entityManagerMock );
$postData = array
(
'title' => 'Issues controller test, post creates issue',
'body' => 'The test tests that a post call' . PHP_EOL . 'creates a new issue' . PHP_EOL . 'in the database.' . PHP_EOL . 'UTF8: áéíóú àèìòù ñç',
'pageUrl' => 'file://Xmontero/AntiqueCrayon/MainBundle/Tests/Controller/IssuesControllerTest.php'
);
$crawler = $client->request( 'POST', '/issues/', $postData );
$response = $client->getResponse();
$this->assertEquals( Response::HTTP_CREATED, $response->getStatusCode() );
$this->assertEquals( 'application/json', $response->headers->get( 'content-type' ) );
}
At that moment, I only had the default bundles + my own bundles in the AppKernel.php
The problem
When I activate those bundles in the AppKernel.php
new FOS\UserBundle\FOSUserBundle(),
new HWI\Bundle\OAuthBundle\HWIOAuthBundle(),
and after configuration, everything works properly testing manually in my browser, including the ajax call that does the POST tested above. That controller has nothing to do with the FOSUser and HWIOAuth as that controller worked before I activated those bundles in the kernel.
But despite the manual test did work, the automated test started to fail giving Call to a member function getRepository() on a non-object not in a line of my code but in the very internals of the FOS and the Doctrine - here's the full output:
xavi#bromo:/files/custom_www/antique-crayon/preproduction$ phpunit -c app --filter Post src/Xmontero/AntiqueCrayon/MainBundle/Tests/Controller/IssuesControllerTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.
Configuration read from /files/custom_www/antique-crayon/preproduction/app/phpunit.xml.dist
PHP Fatal error: Call to a member function getRepository() on a non-object in /files/custom_www/antique-crayon/preproduction/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php on line 759
PHP Stack trace:
PHP 1. {main}() /usr/bin/phpunit:0
PHP 2. PHPUnit_TextUI_Command::main() /usr/bin/phpunit:46
PHP 3. PHPUnit_TextUI_Command->run() /usr/share/php/PHPUnit/TextUI/Command.php:130
PHP 4. PHPUnit_TextUI_TestRunner->doRun() /usr/share/php/PHPUnit/TextUI/Command.php:192
PHP 5. PHPUnit_Framework_TestSuite->run() /usr/share/php/PHPUnit/TextUI/TestRunner.php:325
PHP 6. PHPUnit_Framework_TestSuite->runTest() /usr/share/php/PHPUnit/Framework/TestSuite.php:745
PHP 7. PHPUnit_Framework_TestCase->run() /usr/share/php/PHPUnit/Framework/TestSuite.php:772
PHP 8. PHPUnit_Framework_TestResult->run() /usr/share/php/PHPUnit/Framework/TestCase.php:751
PHP 9. PHPUnit_Framework_TestCase->runBare() /usr/share/php/PHPUnit/Framework/TestResult.php:649
PHP 10. PHPUnit_Framework_TestCase->runTest() /usr/share/php/PHPUnit/Framework/TestCase.php:804
PHP 11. ReflectionMethod->invokeArgs() /usr/share/php/PHPUnit/Framework/TestCase.php:942
PHP 12. Xmontero\AntiqueCrayon\MainBundle\Tests\Controller\IssuesControllerTest->testPostCreatesIssue() /files/custom_www/antique-crayon/preproduction/src/Xmontero/AntiqueCrayon/MainBundle/Tests/Controller/IssuesControllerTest.php:0
PHP 13. Symfony\Component\BrowserKit\Client->request() /files/custom_www/antique-crayon/preproduction/src/Xmontero/AntiqueCrayon/MainBundle/Tests/Controller/IssuesControllerTest.php:41
PHP 14. Symfony\Bundle\FrameworkBundle\Client->doRequest() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php:327
PHP 15. Symfony\Component\HttpKernel\Client->doRequest() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php:111
PHP 16. Symfony\Component\HttpKernel\Kernel->handle() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Client.php:81
PHP 17. Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2330
PHP 18. Symfony\Component\HttpKernel\HttpKernel->handle() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:3080
PHP 19. Symfony\Component\HttpKernel\HttpKernel->handleRaw() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2931
PHP 20. Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher->dispatch() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2958
PHP 21. Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher->preProcess() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php:107
PHP 22. Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher->getListeners() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php:215
PHP 23. Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher->lazyLoad() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php:128
PHP 24. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php:188
PHP 25. appTestDebugProjectContainer->getProfilerListenerService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 26. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:2251
PHP 27. appTestDebugProjectContainer->getProfilerService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 28. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:2234
PHP 29. appTestDebugProjectContainer->getSecurity_ContextService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 30. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:2374
PHP 31. appTestDebugProjectContainer->getSecurity_Authentication_ManagerService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 32. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:3941
PHP 33. appTestDebugProjectContainer->getFosUser_UserProvider_UsernameEmailService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 34. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:3885
PHP 35. appTestDebugProjectContainer->getFosUser_UserManagerService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 36. FOS\UserBundle\Doctrine\UserManager->__construct() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:1657
PHP 37. Doctrine\ORM\EntityManager->getRepository() /files/custom_www/antique-crayon/preproduction/vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Doctrine/UserManager.php:40
xavi#bromo:/files/custom_www/antique-crayon/preproduction$
Narrowing down the problem
The problem is the service doctrine.orm.default_entity_manager for which I inject a mock during the test phase, this is why the manual test in the browser does not fail: No mocks, there.
If I edit my test to do not use any mock, just write to the real DB, it then works:
To test without mock I just comment out the ->set() in the container. And to avoid an Method was expected to be called 1 times, actually called 0 times. I also comment out the ->expects():
//$entityManagerMock->expects( $this->once() )
// ->method( 'flush' );
//
//$client->getContainer()->set( 'doctrine.orm.default_entity_manager', $entityManagerMock );
then the tests greenbars:
xavi#bromo:/files/custom_www/antique-crayon/preproduction$ phpunit -c app --filter Post src/Xmontero/AntiqueCrayon/MainBundle/Tests/Controller/IssuesControllerTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.
Configuration read from /files/custom_www/antique-crayon/preproduction/app/phpunit.xml.dist
.
Time: 0 seconds, Memory: 32.50Mb
OK (1 test, 2 assertions)
xavi#bromo:/files/custom_www/antique-crayon/preproduction$
Conclusions
Injecting a mock in doctrine.orm.default_entity_manager pre-activating FOSUser and HWIOAuth, works fine
When activating these bundles in the AppKernel the trick does not work.
I then only can test allowing to write real data to a database, which is not desired when testing.
Question
How can I disable the writing to the DataBase when calling a controller from a test in phpunit, when FOSUserBundle and HWIOAuthBundle are activated in the kernel?
Thanks!
Xavi.
I'm not proud about it but I haven't done so many test with phpUnit to answer your question with a 100% of security on the answer, but here is my opinion.
I think that the solution is to mock the entityManager, as you are doing yet, but you are moking only the persist() and flush() method.
->setMethods( array( 'persist', 'flush' ) )
->disableOriginalConstructor()
Without the code you are trying to test I can't know it for sure, but it seems that in any part of your controller you're using de FOSUserBundle or the HWIOAuthBundle and one or both of them is using at least the getRepository() method and you need to mock at least all the methods that can be used via FOSUserBundle and HWIOAuthBundle.
If you don't indicate the methods with the setMethods() all of them are mocked, and you can still have controll with the number of times a method is called or not as in the code example below.
$mockObjectManager = $this->getMockBuilder('Doctrine\ORM\EntityManager')
->disableOriginalConstructor()
->getMock();
$mockObjectManager->expects($this->any())
->method('persist');
$mockObjectManager->expects($this->atLeastOnce())
->method('flush');
If the FOSUserBundle is trying to get the repository, as it seems, you will have to mock the return of that call, if you don't do that it will probably end with an error at the next call, an example:
$this->em->expects($this->any())
->method('getRepository')
->with('FOSUserBundle:XXXXX')
->will($this->returnValue($this->getMockedClassWithFind('\Doctrine\ORM\EntityRepository')));
I think the best solution is to start resolving this first error, you will see another error because the object the FosUserBundle is expecting will be null, and mock that one, and maybe expects another object or maybe you're done.
Hope is helpful.

phpunit error with app helper in laravel 4

I try to start using phpunit on my laravel project.
I call "phpunit" and got this error:
$ phpunit
PHPUnit 3.6.10 by Sebastian Bergmann.
Configuration read from /home/bee/www/postaler/phpunit.xml
EPHP Fatal error: Cannot redeclare Helper\isMenuActive() (previously declared in /home/bee/www/postaler/app/helpers.php:4) in /home/bee/www/postaler/app/helpers.php on line 6
PHP Stack trace:
PHP 1. {main}() /usr/bin/phpunit:0
PHP 2. PHPUnit_TextUI_Command::main() /usr/bin/phpunit:46
PHP 3. PHPUnit_TextUI_Command->run() /usr/share/php/PHPUnit/TextUI/Command.php:130
PHP 4. PHPUnit_TextUI_TestRunner->doRun() /usr/share/php/PHPUnit/TextUI/Command.php:192
PHP 5. PHPUnit_Framework_TestSuite->run() /usr/share/php/PHPUnit/TextUI/TestRunner.php:325
PHP 6. PHPUnit_Framework_TestSuite->run() /usr/share/php/PHPUnit/Framework/TestSuite.php:705
PHP 7. PHPUnit_Framework_TestSuite->runTest() /usr/share/php/PHPUnit/Framework/TestSuite.php:745
PHP 8. PHPUnit_Framework_TestCase->run() /usr/share/php/PHPUnit/Framework/TestSuite.php:772
PHP 9. PHPUnit_Framework_TestResult->run() /usr/share/php/PHPUnit/Framework/TestCase.php:751
PHP 10. PHPUnit_Framework_TestCase->runBare() /usr/share/php/PHPUnit/Framework/TestResult.php:649
PHP 11. Illuminate\Foundation\Testing\TestCase->setUp() /usr/share/php/PHPUnit/Framework/TestCase.php:801
PHP 12. Illuminate\Foundation\Testing\TestCase->refreshApplication() /home/bee/www/postaler/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:31
PHP 13. Illuminate\Foundation\Application->boot() /home/bee/www/postaler/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:48
PHP 14. Illuminate\Foundation\Application->bootApplication() /home/bee/www/postaler/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:552
PHP 15. Illuminate\Foundation\Application->fireAppCallbacks() /home/bee/www/postaler/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:569
PHP 16. call_user_func:{/home/bee/www/postaler/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:792}() /home/bee/www/postaler/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:792
PHP 17. TestCase->{closure:/home/bee/www/postaler/vendor/laravel/framework/src/Illuminate/Foundation/start.php:223-271}() /home/bee/www/postaler/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:792
PHP 18. require() /home/bee/www/postaler/vendor/laravel/framework/src/Illuminate/Foundation/start.php:239
my helper code
<?php namespace Helper;
//app/helpers.php
function isMenuActive($url_segment) {
if (\Request::segment(1) == $url_segment) { return " active"; }
}
I included the helper file in app/start/global.php
require app_path().'/helpers.php'
my test script
<?php
// app/tests/FromTest.php
class FromTest extends TestCase {
public function testFrom()
{
$response = $this->call('GET', 'user/profile');
$this->assertTrue(true);
}
}
app/start/global.php is executed once for each request and should not be used for class/function/constant definitions. Instead, add a files autoload rule to your composer.json.
"files": ["src/functions.php"],

Python indexing a list

I have a list as below: How do I do index in python. I want to fetch a value for "OS"? Please let me know.
[{'UserName': 'd699a1f25d9a3', 'BrowserVersion': None, 'PasswordMinLength': 0, 'SystemAutoLock': 0, 'OS': 'Windows 7 6.1 Build 7601 : Service Pack 1 64bit'}]
mylist = [{'UserName': 'd699a1f25d9a3', 'BrowserVersion': None, 'PasswordMinLength': 0, 'SystemAutoLock': 0, 'OS': 'Windows 7 6.1 Build 7601 : Service Pack 1 64bit'}]
OS = mylist[0]['OS']
print OS
Let's say your list is stored in variable my_list:
mylist = [{'UserName': 'd699a1f25d9a3', 'BrowserVersion': None, 'PasswordMinLength': 0, 'SystemAutoLock': 0, 'OS': 'Windows 7 6.1 Build 7601 : Service Pack 1 64bit'}]
Since the dictionary is the first element of the list, you can access to it using indexing. Remember that indexes start with 0:
my_list[0] # first element
Then you can access to a key in the dictionarie by its corresponding value: my_dict[key]. In your case:
my_list[0]['OS']