pynguin | PYthoN General UnIt Test geNerator is a test-generation tool | Unit Testing library

 by   se2p Python Version: 0.31.0 License: MIT

kandi X-RAY | pynguin Summary

pynguin is a Python library typically used in Testing, Unit Testing applications. pynguin has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. However pynguin build file is not available. You can install using 'pip install pynguin' or download it from GitHub, PyPI.
Pynguin (IPA: ˈpɪŋɡuiːn), the PYthoN General UnIt test geNerator, is a tool that allows developers to generate unit tests automatically. Testing software is often considered to be a tedious task. Thus, automated generation techniques have been proposed and mature tools exist—for statically typed languages, such as Java. There is, however, no fully-automated tool available that produces unit tests for general-purpose programs in a dynamically typed language. Pynguin is, to the best of our knowledge, the first tool that fills this gap and allows the automated generation of unit tests for Python programs. Pynguin is developed at the Chair of Software Engineering II of the University of Passau.
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        pynguin has a medium active ecosystem.
                        summary
                        It has 1019 star(s) with 51 fork(s). There are 26 watchers for this library.
                        summary
                        There were 5 major release(s) in the last 6 months.
                        summary
                        There are 7 open issues and 25 have been closed. On average issues are closed in 99 days. There are no pull requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of pynguin is 0.31.0
                        pynguin Support
                          Best in #Unit Testing
                            Average in #Unit Testing
                            pynguin Support
                              Best in #Unit Testing
                                Average in #Unit Testing

                                  kandi-Quality Quality

                                    summary
                                    pynguin has 0 bugs and 0 code smells.
                                    pynguin Quality
                                      Best in #Unit Testing
                                        Average in #Unit Testing
                                        pynguin Quality
                                          Best in #Unit Testing
                                            Average in #Unit Testing

                                              kandi-Security Security

                                                summary
                                                pynguin has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                pynguin code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                pynguin Security
                                                  Best in #Unit Testing
                                                    Average in #Unit Testing
                                                    pynguin Security
                                                      Best in #Unit Testing
                                                        Average in #Unit Testing

                                                          kandi-License License

                                                            summary
                                                            pynguin is licensed under the MIT License. This license is Permissive.
                                                            summary
                                                            Permissive licenses have the least restrictions, and you can use them in most projects.
                                                            pynguin License
                                                              Best in #Unit Testing
                                                                Average in #Unit Testing
                                                                pynguin License
                                                                  Best in #Unit Testing
                                                                    Average in #Unit Testing

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        pynguin releases are available to install and integrate.
                                                                        summary
                                                                        Deployable package is available in PyPI.
                                                                        summary
                                                                        pynguin has no build file. You will be need to create the build yourself to build the component from source.
                                                                        summary
                                                                        Installation instructions are not available. Examples and code snippets are available.
                                                                        summary
                                                                        It has 25294 lines of code, 2999 functions and 331 files.
                                                                        summary
                                                                        It has medium code complexity. Code complexity directly impacts maintainability of the code.
                                                                        pynguin Reuse
                                                                          Best in #Unit Testing
                                                                            Average in #Unit Testing
                                                                            pynguin Reuse
                                                                              Best in #Unit Testing
                                                                                Average in #Unit Testing
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi has reviewed pynguin and discovered the below as its top functions. This is intended to give you an instant insight into pynguin implemented functionality, and help decide if they suit your requirements.
                                                                                  • Gets the control flow distance between the given predicate
                                                                                    • Normalise a value
                                                                                    • Return the fitness for a predicate
                                                                                    • Return the node with the given predicate_id
                                                                                  • Computes ranking for given solutions
                                                                                    • Return non - dominated solutions
                                                                                    • Find the zero front of a set of solutions
                                                                                    • Extend the wrapped context
                                                                                  • Visit a Try node
                                                                                  • Build the graph
                                                                                  • Visit an exception assertion
                                                                                  • Generate test suite
                                                                                  • Expand command - line arguments
                                                                                  • After statement execution after statement
                                                                                  • Decorator for proxy methods
                                                                                  • Create an argument parser
                                                                                  • Write the statistics to the experiment
                                                                                  • Setup logging
                                                                                  • Runs all tests
                                                                                  • Create the full name
                                                                                  • Visit function definition
                                                                                  • Map a list of instructions to their corresponding lines
                                                                                  • Temporarily modify builtins
                                                                                  • Visit an Assertion
                                                                                  • Set the best individual for the given sample
                                                                                  • Return the stack effect
                                                                                  Get all kandi verified functions for this library.
                                                                                  Get all kandi verified functions for this library.

                                                                                  pynguin Key Features

                                                                                  The PYthoN General UnIt Test geNerator is a test-generation tool for Python

                                                                                  pynguin Examples and Code Snippets

                                                                                  No Code Snippets are available at this moment for pynguin.
                                                                                  Community Discussions

                                                                                  Trending Discussions on Unit Testing

                                                                                  Raven.Client.Exceptions.Database.DatabaseDoesNotExistException: 'Database '*****' does not exist
                                                                                  chevron right
                                                                                  Change jest mock on class for single test
                                                                                  chevron right
                                                                                  Skipping a method execution using Mockito
                                                                                  chevron right
                                                                                  Test functions cannot both take a 'done' callback
                                                                                  chevron right
                                                                                  Can not instantiate proxy of class: System.Net.HttpWebRequest. Could not find a parameterless constructor
                                                                                  chevron right
                                                                                  Azure, .Net, Cobertura - ##[warning]Multiple file or directory matches were found
                                                                                  chevron right
                                                                                  Is there a way to unit test top-level statements in C#?
                                                                                  chevron right
                                                                                  Gtest on new keyword
                                                                                  chevron right
                                                                                  How do I add a header to a Django RequestFactory request?
                                                                                  chevron right
                                                                                  How to add unit testing in strapi version 4 using jest?
                                                                                  chevron right

                                                                                  QUESTION

                                                                                  Raven.Client.Exceptions.Database.DatabaseDoesNotExistException: 'Database '*****' does not exist
                                                                                  Asked 2022-Apr-05 at 07:53

                                                                                  I am using RavenTestDriver for my .net core unit tests . Here is my configuration of my RavenTestDriver in my unit test solution :

                                                                                  public class TestHostBuilder : RavenTestDriver, IAsyncLifetime
                                                                                      {
                                                                                  
                                                                                  
                                                                                          public async Task InitializeAsync()
                                                                                          {
                                                                                  
                                                                                              ConfigureServer(new TestServerOptions
                                                                                              {
                                                                                  
                                                                                                  CommandLineArgs = new System.Collections.Generic.List { "--RunInMemory=true", },
                                                                                                  FrameworkVersion = null,
                                                                                              });
                                                                                  
                                                                                              var hostBuilder = easy.api.Program.CreateHostBuilder(new string[0])
                                                                                           .ConfigureWebHost(webHostBuilder =>
                                                                                           {
                                                                                               webHostBuilder.UseTestServer();
                                                                                           })
                                                                                          .ConfigureServices(services =>
                                                                                          {
                                                                                                 services.AddScoped();
                                                                                                  services.AddRavenDbAsyncSession(GetDocumentStore());
                                                                                                  services.AddScoped((c) =>
                                                                                              {
                                                                                                  return GetDocumentStore().OpenAsyncSession(new SessionOptions()
                                                                                                  {
                                                                                                      Database="test-server"
                                                                                                  });
                                                                                                  });
                                                                                          });
                                                                                  
                                                                                              var host = hostBuilder.Start();
                                                                                          }
                                                                                  
                                                                                      }
                                                                                  

                                                                                  But when I call my Repository to get the object I get this error :

                                                                                  Database 'test-server' does not exist.'
                                                                                     at Raven.Client.Exceptions.Database.DatabaseDoesNotExistException.Throw(String databaseName) in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Exceptions\Database\DatabaseDoesNotExistException.cs:line 35
                                                                                     at Raven.Client.Http.RequestExecutor.d__114`1.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 883
                                                                                     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                                                                                     at Raven.Client.Http.RequestExecutor.d__114`1.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 900
                                                                                     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                                                                                     at Raven.Client.Http.RequestExecutor.d__101.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 455
                                                                                     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                                                                                     at Raven.Client.Http.RequestExecutor.d__109.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 678
                                                                                     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                                                                                     at Raven.Client.Http.RequestExecutor.d__107.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 613
                                                                                     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                                                                                     at Raven.Client.Http.RequestExecutor.d__106`1.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Http\RequestExecutor.cs:line 583
                                                                                     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                                                                                     at Raven.Client.Documents.Session.AsyncDocumentSession.d__51`1.MoveNext() in C:\Builds\RavenDB-Stable-5.3\53009\src\Raven.Client\Documents\Session\AsyncDocumentSession.Load.cs:line 30
                                                                                     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
                                                                                     at infrastructure.Persistence.RavenDb.RavenRepository`1.d__6.MoveNext() in D:\gitProjects\Orbis\infrastructure\Persistence\RavenDb\RavenRepository.cs:line 83
                                                                                     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
                                                                                     at infrastructure.ApplicationCache.CacheableRepository`1.d__8.MoveNext() in D:\gitProjects\Orbis\infrastructure\ApplicationCache\CacheableRepository.cs:line 48
                                                                                     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
                                                                                     at easy.api.Application.Setting.Queries.GetClientAppSettingQueryHandler.d__4.MoveNext() in D:\gitProjects\**\***\Application\Setting\Queries\GetClientAppSettingQuery.cs:line 35
                                                                                     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                                                                                     at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
                                                                                     at api.common.Behaviors.UnhandledExceptionBehaviour`2.d__2.MoveNext() in D:\gitProjects\**\api.common\Behaviors\UnhandledExceptionBehaviour.cs:line 22
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2022-Apr-05 at 07:53

                                                                                  QUESTION

                                                                                  Change jest mock on class for single test
                                                                                  Asked 2022-Mar-24 at 14:16

                                                                                  I have an issue where I want to change what a class method returns for a single test while testing a different module. I have the following:

                                                                                  testingModule.test.js

                                                                                  const { testingModuleMethod } = require('../testingModule')
                                                                                  
                                                                                  jest.mock('../helperClass', () =>
                                                                                      jest.fn().mockImplementation(() => ({
                                                                                          helperClassMethod: jest.fn()
                                                                                      }))
                                                                                  );
                                                                                  
                                                                                  describe('testingModule.js', () => {
                                                                                  
                                                                                      describe('testingModuleMethod', () => {
                                                                                          describe('when errors', () => {
                                                                                              const consoleSpy = jest.spyOn(console, 'error');
                                                                                      
                                                                                              // SOMETHING NEEDS TO GO HERE TO CHANGE THE jest.mock ON LINE 3
                                                                                  
                                                                                              await expect(testingModuleMethod(data)).rejects.toThrow('Error');
                                                                                              expect(consoleSpy).toHaveBeenCalled();
                                                                                  
                                                                                              consoleSpy.mockRestore();
                                                                                          });
                                                                                      });
                                                                                  });
                                                                                  
                                                                                  

                                                                                  testingModule.js

                                                                                  const HelperClass = require('./helperClass');
                                                                                  
                                                                                  const testingModuleMethod = async (data, callback) => {
                                                                                      try {
                                                                                          const objectToEvaluate = data.object;
                                                                                  
                                                                                          const helperClassInstance = new HelperClass();
                                                                                  
                                                                                          await helperClassInstance.helperClassMethod(objectToEvaluate);
                                                                                          log('info', "Success!");
                                                                                          callback(null, {});
                                                                                      } catch(error) {
                                                                                          log('error', 'Something went wrong')
                                                                                      }
                                                                                  };
                                                                                  

                                                                                  No matter what I put in there I either get an error with the code (undefined) or it just ignores it and resolves due to the mock at the start. I have tried adding a spy as well as importing the class and using the prototype override.

                                                                                  I'm using node and "jest": "^27.0.6"

                                                                                  ANSWER

                                                                                  Answered 2022-Mar-24 at 14:16

                                                                                  I have managed to answer this by doing the following:

                                                                                  Firstly I discovered that to mock a class like that I have to add a jest function into the mock like so:

                                                                                      describe('testingModuleMethod', () => {
                                                                                          describe('when errors', () => {
                                                                                              const consoleSpy = jest.spyOn(console, 'error');
                                                                                      
                                                                                              HelperClass.mockImplementation(() => ({
                                                                                                      helperClassMethod: jest.fn(() => { throw new Error('Error') })
                                                                                                  }));
                                                                                  
                                                                                              await expect(testingModuleMethod(data)).rejects.toThrow('Error');
                                                                                              expect(consoleSpy).toHaveBeenCalled();
                                                                                  
                                                                                              consoleSpy.mockRestore();
                                                                                          });
                                                                                      });
                                                                                  

                                                                                  This also had a knock on effect to the rest of the tests though so I added a beforeEach at the start that looks like:

                                                                                          HelperClass.mockImplementation(
                                                                                              jest.fn().mockImplementation(() => ({
                                                                                                  helperClassMethod: jest.fn()
                                                                                              }))
                                                                                          );
                                                                                  

                                                                                  Finally I needed to require the class. The overall test looks like this now and works:

                                                                                  const { testingModuleMethod } = require('../testingModule');
                                                                                  const HelperClass = require('./helperClass');
                                                                                  
                                                                                  jest.mock('../helperClass', () =>
                                                                                      jest.fn().mockImplementation(() => ({
                                                                                          helperClassMethod: jest.fn()
                                                                                      }))
                                                                                  );
                                                                                  
                                                                                  describe('testingModule.js', () => {
                                                                                  
                                                                                      beforeEach(() => {
                                                                                          HelperClass.mockImplementation(
                                                                                              jest.fn().mockImplementation(() => ({
                                                                                                  helperClassMethod: jest.fn()
                                                                                              }))
                                                                                          );
                                                                                      });
                                                                                  
                                                                                      describe('testingModuleMethod', () => {
                                                                                          describe('when errors', () => {
                                                                                              const consoleSpy = jest.spyOn(console, 'error');
                                                                                      
                                                                                              HelperClass.mockImplementation(() => ({
                                                                                                      helperClassMethod: jest.fn(() => { throw new Error('Error') })
                                                                                                  }));
                                                                                  
                                                                                              await expect(testingModuleMethod(data)).rejects.toThrow('Error');
                                                                                              expect(consoleSpy).toHaveBeenCalled();
                                                                                  
                                                                                              consoleSpy.mockRestore();
                                                                                          });
                                                                                      });
                                                                                  });
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/71592182

                                                                                  QUESTION

                                                                                  Skipping a method execution using Mockito
                                                                                  Asked 2022-Mar-21 at 09:41

                                                                                  I’m using Mockito for unit testing and I want to skip the execution of a method.

                                                                                  I referred to this ticket Skip execution of a line using Mockito. Here, I assume doSomeTask() and createLink() methods are in different classes. But in my case, both the methods are in the same class (ActualClass.java).

                                                                                  //Actual Class
                                                                                  
                                                                                  public class ActualClass{
                                                                                      
                                                                                      //The method being tested
                                                                                      public void method(){
                                                                                          //some business logic
                                                                                          validate(param1, param2);
                                                                                  
                                                                                          //some business logic
                                                                                      }
                                                                                  
                                                                                      public void validate(arg1, arg2){
                                                                                          //do something
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  //Test class
                                                                                  
                                                                                  public class ActualClassTest{
                                                                                  
                                                                                      @InjectMocks
                                                                                      private ActualClass actualClassMock;
                                                                                  
                                                                                      @Test
                                                                                      public void test_method(){
                                                                                  
                                                                                          ActualClass actualClass = new ActualClass();
                                                                                          ActualClass spyActualClass = Mockito.spy(actualClass);
                                                                                  
                                                                                          // validate method creates a null pointer exception, due to some real time data fetch from elastic
                                                                                  
                                                                                          doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
                                                                                          actualClassMock.method();
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  Since there arises a null pointer exception when the validate method is executed, I’m trying to skip the method call by spying the ActualClass object as stated in the ticket I mentioned above. Still, the issue is not resolve. The validate method gets executed and creates a null pointer exception due to which the actual test method cannot be covered.

                                                                                  So, how do I skip the execution of the validate() method that is within the same class.

                                                                                  ANSWER

                                                                                  Answered 2022-Mar-04 at 09:36

                                                                                  You must always use your spy class when calling method().

                                                                                     @Test
                                                                                      public void test_method(){
                                                                                          ActualClass spyActualClass = Mockito.spy(actualClassMock);
                                                                                  
                                                                                          doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
                                                                                          spyActualClass.method();
                                                                                      }
                                                                                  

                                                                                  In practice, instead of

                                                                                  actualClassMock.method();
                                                                                  

                                                                                  you must use

                                                                                  spyActualClass.method();
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/71349090

                                                                                  QUESTION

                                                                                  Test functions cannot both take a 'done' callback
                                                                                  Asked 2022-Mar-12 at 12:09

                                                                                  I'm trying to create a simple test with nestjs, and I'm get this error

                                                                                  Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise.

                                                                                  Returned value: Promise {}

                                                                                  The unit test is so simple, but I get an error when I use done();

                                                                                  it('throws an error if user signs up with email that is in use', async (done) => {
                                                                                  fakeUsersService.find = () => Promise.resolve([{ id: 1, email: 'a', password: '1' } as User]);
                                                                                  try {
                                                                                    await service.signup('asdf@asdf.com', 'asdf');
                                                                                  } catch (err) {
                                                                                    done();
                                                                                  }
                                                                                  });
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-27 at 21:11

                                                                                  You are combining Async/Await and Done.

                                                                                  Either use asnyc/await, or done.

                                                                                  it('throws an error if user signs up with email that is in use', async () => {
                                                                                      try {
                                                                                          await service();
                                                                                          expect(...);
                                                                                      } catch (err) {
                                                                                      }
                                                                                  });
                                                                                  

                                                                                  or use the done format

                                                                                  it('throws an error if user signs up with email that is in use', (done) => {
                                                                                      ...
                                                                                      service()
                                                                                       .then( ...) {}
                                                                                       .catch( ...) {}
                                                                                      }
                                                                                      done();
                                                                                  });
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/70884240

                                                                                  QUESTION

                                                                                  Can not instantiate proxy of class: System.Net.HttpWebRequest. Could not find a parameterless constructor
                                                                                  Asked 2022-Feb-23 at 12:05

                                                                                  I am upgrading my C# function app from .net 3.1 to 6.0`.

                                                                                  When I run my test cases, I found that, 1 of my test case failed with the below error.

                                                                                  Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: System.Net.HttpWebRequest. Could not find a parameterless constructor.

                                                                                  Basically, I am trying to mock HttpWebRequest and below is my piece of code for that.

                                                                                  var httpWebRequest = new Mock();
                                                                                  

                                                                                  It is working fine in .Net 3.1. I am using Moq version 4.16.1 in both the projects.

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-23 at 10:53

                                                                                  Both HttpWebRequest constructors are obsolete and should not be used. You have to use the static function "Create" to create a new instance of the HttpWebRequest class:

                                                                                  HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/");

                                                                                  To solve your issue, use the HttpClient class instead. This class has a parameterless constructor.

                                                                                  Source https://stackoverflow.com/questions/71112932

                                                                                  QUESTION

                                                                                  Azure, .Net, Cobertura - ##[warning]Multiple file or directory matches were found
                                                                                  Asked 2022-Feb-16 at 10:41

                                                                                  Hi i am trying to get code coverage with .net5 in azure pipeline.

                                                                                  Run tests (not entire file)

                                                                                  Starting test execution, please wait...
                                                                                  A total of 1 test files matched the specified pattern.
                                                                                  Results File: /home/vsts/work/_temp/_fv-az43-964_2021-08-25_08_31_59.trx
                                                                                  
                                                                                  Attachments:
                                                                                    /home/vsts/work/_temp/f5dd5e9f-e260-437d-80ef-4fb917215b09/coverage.cobertura.xml
                                                                                  Passed!  - Failed:     0, Passed:    16, Skipped:     0, Total:    16, Duration: 732 ms - /home/vsts/work/1/s/sda2021_webapi/Test/sda2021_api.tests/bin/Release/net5.0/sda2021_webapi.tests.dll (net5.0)
                                                                                  Result Attachments will be stored in LogStore
                                                                                  Run Attachments will be stored in LogStore
                                                                                  Info: Azure Pipelines hosted agents have been updated and now contain .Net 5.x SDK/Runtime along with the older .Net Core version which are currently lts. Unless you have locked down a SDK version for your project(s), 5.x SDK might be picked up which might have breaking behavior as compared to previous versions. You can learn more about the breaking changes here: https://docs.microsoft.com/en-us/dotnet/core/tools/ and https://docs.microsoft.com/en-us/dotnet/core/compatibility/ . To learn about more such changes and troubleshoot, refer here: https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/build/dotnet-core-cli?view=azure-devops#troubleshooting
                                                                                  Async Command Start: Publish test results
                                                                                  Publishing test results to test run '5152'.
                                                                                  TestResults To Publish 16, Test run id:5152
                                                                                  Test results publishing 16, remaining: 0. Test run id: 5152
                                                                                  Published Test Run : https://dev.azure.com/sda-shs/Bratislava2021/_TestManagement/Runs?runId=5152&_a=runCharts
                                                                                  Async Command End: Publish test results
                                                                                  Finishing: Dotnet run tests
                                                                                  

                                                                                  Publish tests(not entire file)

                                                                                  ##[warning]Multiple file or directory matches were found. Using the first match: /home/vsts/work/_temp/_fv-az43-964_2021-08-25_08_31_59/In/fv-az43-964/coverage.cobertura.xml
                                                                                  /opt/hostedtoolcache/dotnet/dotnet /home/vsts/work/_tasks/PublishCodeCoverageResults_2a7ebc54-c13e-490e-81a5-d7561ab7cd97/1.189.0/netcoreapp2.0/ReportGenerator.dll -reports:/home/vsts/work/_temp/**/coverage.cobertura.xml -targetdir:/home/vsts/work/_temp/cchtml -reporttypes:HtmlInline_AzurePipelines
                                                                                  2021-08-25T08:32:03: Arguments
                                                                                  2021-08-25T08:32:03:  -reports:/home/vsts/work/_temp/**/coverage.cobertura.xml
                                                                                  

                                                                                  And of course my pipeline

                                                                                  task: DotNetCoreCLI@2
                                                                                              displayName: Dotnet run tests
                                                                                              inputs:
                                                                                                command: "test"
                                                                                                projects: "**/xxxxx/*.tests.csproj"
                                                                                                arguments: '--configuration Release /p:CoverletOutputFormat=cobertura --collect:"XPlat Code Coverage" --no-build'
                                                                                                testRunTitle: "xxxx"
                                                                                            - task: PublishCodeCoverageResults@1
                                                                                              displayName: "publish coverage results"
                                                                                              inputs:
                                                                                                codeCoverageTool: "Cobertura"
                                                                                                summaryFileLocation: "$(Agent.TempDirectory)/**/coverage.cobertura.xml"
                                                                                  

                                                                                  Why is more then one XML generated? I am basically balancing between no XML and more XML. I am just unable to generate one XML. (on my localhost it generates only one) Thanks for any tips.

                                                                                  ANSWER

                                                                                  Answered 2021-Aug-25 at 08:52

                                                                                  Please replace your PublishCodeCoverageResults with following steps:

                                                                                         - task: reportgenerator@4
                                                                                           displayName: 'Merge code coverage reports'
                                                                                           inputs:
                                                                                             reports: '$(Agent.TempDirectory)/**/coverage.cobertura.xml'
                                                                                             targetdir: '$(Pipeline.Workspace)/coverlet'
                                                                                             reporttypes: 'Cobertura'
                                                                                             verbosity: 'Verbose'
                                                                                       
                                                                                         - task: PublishCodeCoverageResults@1
                                                                                           displayName: 'Publish code coverage results'
                                                                                           inputs:
                                                                                             codeCoverageTool: Cobertura
                                                                                             summaryFileLocation: '$(Pipeline.Workspace)/coverlet/Cobertura.xml'
                                                                                  

                                                                                  And you have multiple files, because probably you have more than one test project.

                                                                                  Source https://stackoverflow.com/questions/68919661

                                                                                  QUESTION

                                                                                  Is there a way to unit test top-level statements in C#?
                                                                                  Asked 2022-Feb-10 at 13:00

                                                                                  I was fiddling with top-level statements as the entry point for a simple console app, since the new .NET 6 template use them as a default.

                                                                                  Yet, as the language specification very clearly states:

                                                                                  Note that the names "Program" and "Main" are used only for illustrations purposes, actual names used by compiler are implementation dependent and neither the type, nor the method can be referenced by name from source code.

                                                                                  So, if I can't reference the implicit Program class and it's Main() method, would it be possible to write unit tests to check the execution flow of the top-level statements themselves? If so, how?

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-10 at 13:00

                                                                                  Yes. One option (since .NET 6) is to make the tested project's internals visible to the test project for example by adding next property to csproj:

                                                                                  
                                                                                    
                                                                                  
                                                                                  

                                                                                  And then the Program class generated for top-level statement should be visible to the test project and you can run it next way:

                                                                                  var entryPoint = typeof(Program).Assembly.EntryPoint!;
                                                                                  entryPoint.Invoke(null, new object[] { Array.Empty() }); 
                                                                                  

                                                                                  Something like this is used internally to perform integration tests for ASP.NET Core 6 with minimal hosting model.

                                                                                  Note that generated Main method can return task if you are using await's in your top-level statement, so you possibly will need to capture the return of entryPoint.Invoke and test if it is a Task and await it.

                                                                                  Another approach is to explicitly declare Program class as partial (for example at the end of top-level statement and use it in testing project):

                                                                                  // ...
                                                                                  // your top-level statements
                                                                                  
                                                                                  public partial class Program { }
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/70645272

                                                                                  QUESTION

                                                                                  Gtest on new keyword
                                                                                  Asked 2022-Jan-31 at 18:10

                                                                                  new keyword in C++ will throw an exception if insufficient memory but below code trying to return "NO_MEMORY" when new failed. This is bad because it will raise std::bad_alloc exception .

                                                                                  I am writing a unit test(gtest). How to create a scenario to catch this problem.

                                                                                  class base{
                                                                                  
                                                                                  
                                                                                      public: base(){
                                                                                          std::cout<<"base\n";
                                                                                      }
                                                                                  };
                                                                                   
                                                                                  
                                                                                  std::string getInstance(base** obj){
                                                                                  
                                                                                      base *bObject = new base();
                                                                                      *obj = bObject; //updated
                                                                                       return (NULL == bObject) ? "NO_MEMORY" : "SUCCESS"; // here is problem if new fail it raise an exception. How to write unit test to catch this?
                                                                                  }
                                                                                  
                                                                                  int main()
                                                                                  {
                                                                                   
                                                                                   base *base_obj;
                                                                                   getInstance(&base_obj);
                                                                                  }
                                                                                   
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-31 at 14:36

                                                                                  First I think you need to catch the exception otherwise your program will never reach the point of returning NO_MEMORY:

                                                                                  std::string getInstance(base **obj) {
                                                                                      try {
                                                                                          if (!obj)
                                                                                              throw std::invalid_argument("");
                                                                                  
                                                                                          *obj = new base();
                                                                                          return "SUCCESS";
                                                                                      }
                                                                                      catch (const std::bad_alloc& e) {
                                                                                          return "NO_MEMORY";
                                                                                      }
                                                                                      catch (...) {
                                                                                          return "UNDEFINED_ERROR";
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  A quick and dirty way for testing this would be to make the constructor (or an overloaded new) to throw std::bad_alloc:

                                                                                  #ifdef UNIT_TESTING
                                                                                  // simulate there is no memory
                                                                                  base::base() { throw std::bad_alloc; }
                                                                                  #else
                                                                                  base::base() { }
                                                                                  #endif
                                                                                  

                                                                                  But I guess the proper way would be to use something like mockcpp

                                                                                  Edit: Since your are using gtest you might prefer using Google Mock to mock base with a constructor throwing bad_alloc instead of the dirty substitution of base::base

                                                                                  Source https://stackoverflow.com/questions/70925635

                                                                                  QUESTION

                                                                                  How do I add a header to a Django RequestFactory request?
                                                                                  Asked 2022-Jan-29 at 17:27

                                                                                  To manually send a GET request with a header, I do this with curl:

                                                                                  curl http://example.com/endpoint -H "Key: Value"
                                                                                  

                                                                                  I want to write a unit test that makes a request (using django.test.RequestFactory) containing a header. How can I add a header to the request?

                                                                                  For clarity, below is an example of what I'd like to be able to do, though what I have written below is not valid code because RequestFactory.get() does not have a headers parameter:

                                                                                  from django.test import TestCase, RequestFactory
                                                                                  
                                                                                  
                                                                                  class TestClassForMyDjangoApp(TestCase):
                                                                                      def test_for_my_app(self):
                                                                                          factory = RequestFactory()
                                                                                          
                                                                                          my_header = dict(key=value, another_key=another_value)
                                                                                          factory.get('/endpoint/', headers=my_header)
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Aug-10 at 15:27

                                                                                  You need to pass HTTP_* kwargs to the get(...) ( or any valid http methods) to pass a custom HTTP header in the request.

                                                                                  
                                                                                  class TestClassForMyDjangoApp(TestCase):
                                                                                      def test_for_my_app(self):
                                                                                          factory = RequestFactory()
                                                                                          my_header = {"HTTP_CUSTOM_KEY": "VALUE"}
                                                                                          request = factory.get("/some/url/", **my_header)
                                                                                          print(request.headers) # {'Custom-Key': 'VALUE'}

                                                                                  Source https://stackoverflow.com/questions/68729084

                                                                                  QUESTION

                                                                                  How to add unit testing in strapi version 4 using jest?
                                                                                  Asked 2022-Jan-25 at 19:26

                                                                                  I'm trying to add unit testing on a brand new strapi application. The official documentation is still in progress. So, until the documentation is being ready is there a way to add jest unit testing to strapi application ? i followed the approach in the v3 documentation with no luck.

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-25 at 19:26

                                                                                  There are quite a few changes from Strapi V3 to Strapi V4 when it comes to initializing a Strapi application's APIs. The most important changes are how Strapi populates the KOA routes, and how to make requests to the http server.

                                                                                  To populate the KOA routes use

                                                                                  await instance.server.mount();
                                                                                  

                                                                                  instead of

                                                                                  await instance.app
                                                                                         .use(instance.router.routes()) // populate KOA routes
                                                                                         .use(instance.router.allowedMethods()); // populate KOA methods
                                                                                  instance.server = http.createServer(instance.app.callback());
                                                                                  

                                                                                  To call the http server use

                                                                                   strapi.server.httpServer
                                                                                  

                                                                                  instead of

                                                                                   strapi.server
                                                                                  

                                                                                  You also need to use the new database configuration schema when defining your test database. You can use the following as an initial setup for your tests.

                                                                                  The following is an updated (and WIP) guide based on Strapi V3 Unit Testing guide.

                                                                                  First run

                                                                                   yarn add --dev jest supertest sqlite3
                                                                                  

                                                                                  or

                                                                                   npm install --save-dev jest supertest sqlite3
                                                                                  

                                                                                  Then add the following to your ./package.json scripts:

                                                                                  "scripts": {
                                                                                     // ...strapi scripts
                                                                                    "test": "jest --forceExit --detectOpenHandles", //add
                                                                                    "watch": "yarn test --watch", // optional
                                                                                  }
                                                                                  

                                                                                  Then add the following files:

                                                                                  ./jest.config.js

                                                                                  module.exports = {
                                                                                      verbose: true,
                                                                                      testPathIgnorePatterns: [
                                                                                          "/node_modules/",
                                                                                          ".tmp",
                                                                                          ".cache"
                                                                                      ],
                                                                                      modulePaths: [
                                                                                          "/node_modules/",
                                                                                      ],
                                                                                      testEnvironment: "node",
                                                                                  };
                                                                                  

                                                                                  ./config/env/test/database.json

                                                                                  {
                                                                                      "connection": {
                                                                                          "client": "sqlite",
                                                                                          "connection": {
                                                                                              "filename": ".tmp/test.db"
                                                                                          },
                                                                                          "useNullAsDefault": true,
                                                                                          "pool": {
                                                                                              "min": 0,
                                                                                              "max": 1
                                                                                          }
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  ./tests/helpers/strapi.js

                                                                                  const Strapi = require("@strapi/strapi");
                                                                                  const fs = require("fs");
                                                                                  
                                                                                  let instance;
                                                                                  
                                                                                  async function setupStrapi() {
                                                                                    if (!instance) {
                                                                                      await Strapi().load();
                                                                                      instance = strapi;
                                                                                      await instance.server.mount();
                                                                                    }
                                                                                    return instance;
                                                                                  }
                                                                                  
                                                                                  async function cleanupStrapi() {
                                                                                    const dbSettings = strapi.config.get("database.connection");
                                                                                    const tmpDbFile = dbSettings.connection.filename
                                                                                  
                                                                                    //close server to release the db-file
                                                                                    await strapi.server.httpServer.close();
                                                                                  
                                                                                    //delete test database after all tests
                                                                                    if (dbSettings && tmpDbFile) {
                                                                                      if (fs.existsSync(tmpDbFile)) {
                                                                                        fs.unlinkSync(tmpDbFile);
                                                                                      }
                                                                                    }
                                                                                    // close the connection to the database
                                                                                    await strapi.db.connection.destroy();
                                                                                  }
                                                                                  
                                                                                  module.exports = { setupStrapi, cleanupStrapi };
                                                                                  

                                                                                  Note that you need to have the /hello endpoint in your project as specified in the strapi docs for the next tests to pass.

                                                                                  ./tests/app.test.js

                                                                                  const { setupStrapi, cleanupStrapi } = require("./helpers/strapi");
                                                                                  
                                                                                  jest.setTimeout(15000);
                                                                                  
                                                                                  beforeAll(async () => {
                                                                                    await setupStrapi(); 
                                                                                  });
                                                                                  
                                                                                  afterAll(async () => {
                                                                                   await cleanupStrapi();
                                                                                  });
                                                                                  
                                                                                  it("strapi is defined", () => {
                                                                                    expect(strapi).toBeDefined();
                                                                                  });
                                                                                  
                                                                                  require('./hello')
                                                                                  

                                                                                  ./tests/hello/index.js

                                                                                  const request = require('supertest');
                                                                                  
                                                                                  it('should return hello world', async () => {
                                                                                    await request(strapi.server.httpServer) 
                                                                                      .get('/api/hello')
                                                                                      .expect(200) // Expect response http code 200
                                                                                  });
                                                                                  

                                                                                  I hope this helps anyone struggling with the same issues. I will update the answer as I progress.

                                                                                  Source https://stackoverflow.com/questions/70283992

                                                                                  Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                  Vulnerabilities

                                                                                  No vulnerabilities reported

                                                                                  Install pynguin

                                                                                  You can install using 'pip install pynguin' or download it from GitHub, PyPI.
                                                                                  You can use pynguin like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.

                                                                                  Support

                                                                                  For the development of Pynguin you will need the poetry dependency management and packaging tool. To start developing, follow these steps:.
                                                                                  Find more information at:
                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit
                                                                                  Install
                                                                                • PyPI

                                                                                  pip install pynguin

                                                                                • CLONE
                                                                                • HTTPS

                                                                                  https://github.com/se2p/pynguin.git

                                                                                • CLI

                                                                                  gh repo clone se2p/pynguin

                                                                                • sshUrl

                                                                                  git@github.com:se2p/pynguin.git

                                                                                • Share this Page

                                                                                  share link

                                                                                  Explore Related Topics

                                                                                  Consider Popular Unit Testing Libraries

                                                                                  googletest

                                                                                  by google

                                                                                  mocha

                                                                                  by mochajs

                                                                                  enzyme

                                                                                  by enzymejs

                                                                                  ava

                                                                                  by avajs

                                                                                  phpunit

                                                                                  by sebastianbergmann

                                                                                  Try Top Libraries by se2p

                                                                                  tool-competition-av

                                                                                  by se2pPython

                                                                                  LitterBox

                                                                                  by se2pJava

                                                                                  whisker

                                                                                  by se2pTypeScript

                                                                                  FlaPy

                                                                                  by se2pPython

                                                                                  whisker-main

                                                                                  by se2pTypeScript

                                                                                  Compare Unit Testing Libraries with Highest Support

                                                                                  robolectric

                                                                                  by robolectric

                                                                                  mockito

                                                                                  by mockito

                                                                                  junit5

                                                                                  by junit-team

                                                                                  mocha

                                                                                  by mochajs

                                                                                  spock

                                                                                  by spockframework

                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit