CppUMockGen | Mock generator for CppUTest/CppUMock | Mock library
kandi X-RAY | CppUMockGen Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
CppUMockGen Key Features
CppUMockGen Examples and Code Snippets
Trending Discussions on Mock
Trending Discussions on Mock
QUESTION
Say that I have the following interface:
public interface ITeam
{
bool HasPlayer(IPlayer player);
void AddPlayer(IPlayer player);
}
I currently have a test that looks something along the lines of (using AutoMoq):
[Theory]
[MyAutoData]
public void ShouldRosterToTeamWhenPlayerIsNotRostered(Player player, Mock mockedTeam)
{
player.RosterToTeam(mockedTeam.Object);
mockedTeam.Verify(team => team.AddPlayer(player), Times.Once);
}
However, a precondition in my code is that HasPlayer
must return false for the test to pass when RosterToTeam
is called.
This can be solved by creating a ICustomization
and directly composing the correct behaviour, for example:
public class TeamCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize>(composer =>
composer.Do(mock =>
mock.Setup(team => team.HasPlayer(It.IsAny()))
.Returns(false)));
}
}
However, I'd like my tests always to assume that the boolean methods have a default value of false. I've tried looking into ISpecimenBuilder
, but couldn't see a way to achieve this, as it seems to only work on properties, parameters, etc.
Is anyone able to recommend me a way of generically setting up all boolean methods to return false by default when created in this fashion?
Edit: The culprit behind the behaviour change is when ConfigureMembers = true
is set for AutoMoqCustomization
.
This is what my MyAutoDataAttribute
currently looks like:
public class MyAutoDataAttribute : AutoDataAttribute
{
public MyAutoDataAttribute() : base(Create)
{
}
private static IFixture Create()
{
var fixture = new Fixture();
fixture.Customize(new AutoMoqCustomization
{
ConfigureMembers = true
});
fixture.Customize(new TeamCustomization());
return fixture;
}
}
For my use case, ConfigureMembers = true
is still needed (and would like to remove the TeamCustomization
).
ANSWER
Answered 2022-Mar-26 at 16:40First of all, you may want to use AutoMoqDataAttribute to create a mock of the ITeam
interface:
public class AutoMoqDataAttribute : AutoDataAttribute
{
public AutoMoqDataAttribute()
: base(new Fixture().Customize(new AutoMoqCustomization()))
{
}
}
There is no need in cusomizing fixture to configure your mocks. You'd better do that in the tests itself (the arrange section):
[Theory, AutoMoqData]
public void ShouldRosterToTeamWhenPlayerIsNotRostered(Player player, Mock mockedTeam)
{
mockedTeam.Setup(t => t.HasPlayer(player)).Returns(false);
player.RosterToTeam(mockedTeam.Object);
mockedTeam.Verify(team => team.AddPlayer(player), Times.Once);
}
[Theory, AutoMoqData]
public void ShouldNotRosterToTeamWhenPlayerIsRostered(Player player, Mock mockedTeam)
{
mockedTeam.Setup(t => t.HasPlayer(player)).Returns(true);
player.RosterToTeam(mockedTeam.Object);
mockedTeam.Verify(team => team.AddPlayer(player), Times.Never);
}
and, finaly, the simplified RoastToTeam implementation:
public class Player
{
public void RosterToTeam(ITeam team)
{
if (team.HasPlayer(this))
{
return;
}
team.AddPlayer(this);
}
}
QUESTION
I have been using github actions for quite sometime but today my deployments started failing. Below is the error from github action logs
Command: git
Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
Directory: /home/runner/work/stackstream-fe/stackstream-fe
Output:
fatal: remote error:
The unauthenticated git protocol on port 9418 is no longer supported.
Upon investigation, it appears that below section in my yml file is causing the issue.
- name: Installing modules
run: yarn install
I have looked into this change log but can't seem to comprehend the issue.
Additional Details: Server: EC2 Instance Github actions steps:
steps:
- name: Checkout
uses: actions/checkout@v2
- id: vars
run: |
if [ '${{ github.ref }}' == 'refs/heads/master' ]; then echo "::set-output name=environment::prod_stackstream" ; echo "::set-output name=api-url::api" ; elif [ '${{ github.ref }}' == 'refs/heads/staging' ]; then echo "::set-output name=environment::staging_stackstream" ; echo "::set-output name=api-url::stagingapi" ; else echo "::set-output name=environment::dev_stackstream" ; echo "::set-output name=api-url::devapi" ; fi
- uses: pCYSl5EDgo/cat@master
id: slack
with:
path: .github/workflows/slack.txt
- name: Slack Start Notification
uses: 8398a7/action-slack@v3
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
ENVIRONMENT: '`${{ steps.vars.outputs.environment }}`'
COLOR: good
STATUS: '`Started`'
with:
status: custom
fields: workflow,job,commit,repo,ref,author,took
custom_payload: |
${{ steps.slack.outputs.text }}
- name: Installing modules
env:
REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
run: yarn install
- name: Create Frontend Build
env:
REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
run: yarn build
- name: Deploy to Frontend Server DEV
if: ${{ contains(github.ref, 'dev') }}
uses: easingthemes/ssh-deploy@v2.1.5
env:
SSH_PRIVATE_KEY: ${{ secrets.DEV_KEY }}
ARGS: '-rltgoDzvO --delete'
SOURCE: 'deploy/'
REMOTE_HOST: ${{ secrets.DEV_HOST }}
REMOTE_USER: plyfolio-dev
TARGET: '/home/plyfolio-dev/${{ steps.vars.outputs.environment }}/fe/deploy'
package.json file
{
"name": "stackstream-fe",
"version": "1.0.0",
"authors": [
"fayyaznofal@gmail.com"
],
"private": true,
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.34",
"@fortawesome/free-solid-svg-icons": "^5.15.2",
"@fortawesome/react-fontawesome": "^0.1.14",
"@fullcalendar/bootstrap": "^5.5.0",
"@fullcalendar/core": "^5.5.0",
"@fullcalendar/daygrid": "^5.5.0",
"@fullcalendar/interaction": "^5.5.0",
"@fullcalendar/react": "^5.5.0",
"@lourenci/react-kanban": "^2.1.0",
"@redux-saga/simple-saga-monitor": "^1.1.2",
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^11.2.3",
"@testing-library/user-event": "^12.6.0",
"@toast-ui/react-chart": "^1.0.2",
"@types/jest": "^26.0.14",
"@types/node": "^14.10.3",
"@types/react": "^16.9.49",
"@types/react-dom": "^16.9.8",
"@vtaits/react-color-picker": "^0.1.1",
"apexcharts": "^3.23.1",
"availity-reactstrap-validation": "^2.7.0",
"axios": "^0.21.1",
"axios-mock-adapter": "^1.19.0",
"axios-progress-bar": "^1.2.0",
"bootstrap": "^5.0.0-beta2",
"chart.js": "^2.9.4",
"chartist": "^0.11.4",
"classnames": "^2.2.6",
"components": "^0.1.0",
"dotenv": "^8.2.0",
"draft-js": "^0.11.7",
"echarts": "^4.9.0",
"echarts-for-react": "^2.0.16",
"firebase": "^8.2.3",
"google-maps-react": "^2.0.6",
"history": "^4.10.1",
"i": "^0.3.6",
"i18next": "^19.8.4",
"i18next-browser-languagedetector": "^6.0.1",
"jsonwebtoken": "^8.5.1",
"leaflet": "^1.7.1",
"lodash": "^4.17.21",
"lodash.clonedeep": "^4.5.0",
"lodash.get": "^4.4.2",
"metismenujs": "^1.2.1",
"mkdirp": "^1.0.4",
"moment": "2.29.1",
"moment-timezone": "^0.5.32",
"nouislider-react": "^3.3.9",
"npm": "^7.6.3",
"prop-types": "^15.7.2",
"query-string": "^6.14.0",
"react": "^16.13.1",
"react-apexcharts": "^1.3.7",
"react-auth-code-input": "^1.0.0",
"react-avatar": "^3.10.0",
"react-bootstrap": "^1.5.0",
"react-bootstrap-editable": "^0.8.2",
"react-bootstrap-sweetalert": "^5.2.0",
"react-bootstrap-table-next": "^4.0.3",
"react-bootstrap-table2-editor": "^1.4.0",
"react-bootstrap-table2-paginator": "^2.1.2",
"react-bootstrap-table2-toolkit": "^2.1.3",
"react-chartist": "^0.14.3",
"react-chartjs-2": "^2.11.1",
"react-color": "^2.19.3",
"react-confirm-alert": "^2.7.0",
"react-content-loader": "^6.0.1",
"react-countdown": "^2.3.1",
"react-countup": "^4.3.3",
"react-cropper": "^2.1.4",
"react-data-table-component": "^6.11.8",
"react-date-picker": "^8.0.6",
"react-datepicker": "^3.4.1",
"react-dom": "^16.13.1",
"react-draft-wysiwyg": "^1.14.5",
"react-drag-listview": "^0.1.8",
"react-drawer": "^1.3.4",
"react-dropzone": "^11.2.4",
"react-dual-listbox": "^2.0.0",
"react-facebook-login": "^4.1.1",
"react-flatpickr": "^3.10.6",
"react-google-login": "^5.2.2",
"react-hook-form": "^7.15.2",
"react-i18next": "^11.8.5",
"react-icons": "^4.2.0",
"react-image-lightbox": "^5.1.1",
"react-input-mask": "^2.0.4",
"react-jvectormap": "^0.0.16",
"react-leaflet": "^3.0.5",
"react-meta-tags": "^1.0.1",
"react-modal-video": "^1.2.6",
"react-notifications": "^1.7.2",
"react-number-format": "^4.7.3",
"react-perfect-scrollbar": "^1.5.8",
"react-rangeslider": "^2.2.0",
"react-rating": "^2.0.5",
"react-rating-tooltip": "^1.1.6",
"react-redux": "^7.2.1",
"react-responsive-carousel": "^3.2.11",
"react-router-dom": "^5.2.0",
"react-script": "^2.0.5",
"react-scripts": "3.4.3",
"react-select": "^4.3.1",
"react-sparklines": "^1.7.0",
"react-star-ratings": "^2.3.0",
"react-super-responsive-table": "^5.2.0",
"react-switch": "^6.0.0",
"react-table": "^7.6.3",
"react-toastify": "^7.0.3",
"react-toastr": "^3.0.0",
"react-twitter-auth": "0.0.13",
"reactstrap": "^8.8.1",
"recharts": "^2.0.8",
"redux": "^4.0.5",
"redux-saga": "^1.1.3",
"reselect": "^4.0.0",
"sass": "^1.37.5",
"simplebar-react": "^2.3.0",
"styled": "^1.0.0",
"styled-components": "^5.2.1",
"toastr": "^2.1.4",
"typescript": "^4.0.2",
"universal-cookie": "^4.0.4"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^2.27.0",
"@typescript-eslint/parser": "^2.27.0",
"@typescript-eslint/typescript-estree": "^4.15.2",
"eslint-config-prettier": "^6.10.1",
"eslint-plugin-prettier": "^3.1.2",
"husky": "^4.2.5",
"lint-staged": "^10.1.3",
"prettier": "^1.19.1",
"react-test-renderer": "^16.13.1",
"redux-devtools-extension": "^2.13.8",
"redux-mock-store": "^1.5.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build && mv build ./deploy/build",
"build-local": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,ts,tsx}": [
"eslint --fix"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
ANSWER
Answered 2022-Mar-16 at 07:01First, this error message is indeed expected on Jan. 11th, 2022.
See "Improving Git protocol security on GitHub".
January 11, 2022 Final brownout.
This is the full brownout period where we’ll temporarily stop accepting the deprecated key and signature types, ciphers, and MACs, and the unencrypted Git protocol.
This will help clients discover any lingering use of older keys or old URLs.
Second, check your package.json
dependencies for any git://
URL, as in this example, fixed in this PR.
As noted by Jörg W Mittag:
For GitHub Actions:There was a 4-month warning.
The entire Internet has been moving away from unauthenticated, unencrypted protocols for a decade, it's not like this is a huge surprise.Personally, I consider it less an "issue" and more "detecting unmaintained dependencies".
Plus, this is still only the brownout period, so the protocol will only be disabled for a short period of time, allowing developers to discover the problem.
The permanent shutdown is not until March 15th.
As in actions/checkout issue 14, you can add as a first step:
- name: Fix up git URLs
run: echo -e '[url "https://github.com/"]\n insteadOf = "git://github.com/"' >> ~/.gitconfig
That will change any git://github.com/
into https://github.com/
.
For all your repositories, you can set:
git config --global url."https://github.com/".insteadOf git://github.com/
You can also use SSH, but GitHub Security reminds us that, as of March 15th, 2022, GitHub stopped accepting DSA keys. RSA keys uploaded after Nov 2, 2021 will work only with SHA-2 signatures.
The deprecated MACs, ciphers, and unencrypted Git protocol are permanently disabled.
So this (with the right key) would work:
git config --global url."git@github.com:".insteadOf git://github.com/
That will change any git://github.com/
(unencrypted Git protocol) into git@github.com:
(SSH URL).
QUESTION
Wondering if anybody has some good suggestions on how to crack this. Got this test helper utils I have added some types to:
import { jest } from '@jest/globals'
import React from 'react'
// https://learn.reactnativeschool.com/courses/781007/lectures/14173979
export function mockComponent(moduleName: string, propOverrideFn = (props: Record) => ({})) {
const RealComponent = jest.requireActual(moduleName) as React.ComponentType
const CustomizedComponent = (props: Record) => {
return React.createElement(
'CustomizedComponent',
{
...props,
...propOverrideFn(props),
},
props.children
)
}
CustomizedComponent.propTypes = RealComponent.propTypes
return CustomizedComponent
}
So currently I can call it like this
jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
return mockComponent('react-native/Libraries/Components/Touchable/TouchableOpacity', (props) => {
return {
onPress: props.disabled ? () => {} : props.onPress
}
})
})
But I would like to be able to call it more like
jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
return props.disabled ? () => {} : props.onPress}
/>
})
or
jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
return ({onPress: props.disabled ? () => {} : props.onPress, ...props})}
/>
})
ANSWER
Answered 2022-Mar-20 at 22:37If you look at React without JSX, you'll see that the XML-inspired syntax () is just short for
React.createElement('MockComponent')
.
Right now, if you renamed mockComponent
to MockComponent
and tried using the angle bracket syntax, the first issue is that your function receives two arguments. React components are either class components that take one constructor argument (props) or functional components that take one argument (again, props). The second issue is that your function returns a React functional component, when it needs to return a rendered React element.
One way to fix this issue is to convert mockComponent
into a React functional component and make module
and propOverride
props of the FC.
// https://learn.reactnativeschool.com/courses/781007/lectures/14173979
export function MockComponent(props) {
const { moduleName, propOverrideFn, ...customComponentProps } = props;
const RealComponent = jest.requireActual(moduleName) as React.ComponentType
const CustomizedComponent = (props: Record) => {
return React.createElement(
'CustomizedComponent',
{
...props,
...propOverrideFn(props),
},
props.children
)
}
CustomizedComponent.propTypes = RealComponent.propTypes
return
}
The differences are subtle but important. Here I modified MockComponent
to take in a singular prop
argument to be compatible with React.createElement()
. This leads to the issue of how to differentiate props that are meant for the CustomizedComponent
and what used to be arguments for mockComponent()
. Here, I use the JavaScript destructuring and spread operators to separate module
and propOverride
from the props intended from CustomizedComponent
.
Lastly, I use the JSX spread syntax to pass the arbitrary props intended for CustomizedComponent
into CustomizedComponent
, and I use angle brackets to render it (instead of returning a function).
I'll leave as an exercise for you to come up with the appropriate TypeScript definition for MockComponent's props. You can simply define it as the union of Record and module
and propOverride
. However, you can get fancy and use a template definition so MockComponent
is a union of module
and propOverride
and Toolbar
's props.
Oh, and I almost forgot. Your Jest call would look like
jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
(props) => {
return props.disabled ? () => {} : props.onPress}
{...props}
/>
}
})
QUESTION
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:53Both 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.
QUESTION
I'm currently building PoC Apache Beam pipeline in GCP Dataflow. In this case, I want to create streaming pipeline with main input from PubSub and side input from BigQuery and store processed data back to BigQuery.
Side pipeline code
side_pipeline = (
p
| "periodic" >> PeriodicImpulse(fire_interval=3600, apply_windowing=True)
| "map to read request" >>
beam.Map(lambda x:beam.io.gcp.bigquery.ReadFromBigQueryRequest(table=side_table))
| beam.io.ReadAllFromBigQuery()
)
Function with side input code
def enrich_payload(payload, equipments):
id = payload["id"]
for equipment in equipments:
if id == equipment["id"]:
payload["type"] = equipment["type"]
payload["brand"] = equipment["brand"]
payload["year"] = equipment["year"]
break
return payload
Main pipeline code
main_pipeline = (
p
| "read" >> beam.io.ReadFromPubSub(topic="projects/my-project/topics/topiq")
| "bytes to dict" >> beam.Map(lambda x: json.loads(x.decode("utf-8")))
| "transform" >> beam.Map(transform_function)
| "timestamping" >> beam.Map(lambda src: window.TimestampedValue(
src,
dt.datetime.fromisoformat(src["timestamp"]).timestamp()
))
| "windowing" >> beam.WindowInto(window.FixedWindows(30))
)
final_pipeline = (
main_pipeline
| "enrich data" >> beam.Map(enrich_payload, equipments=beam.pvalue.AsIter(side_pipeline))
| "store" >> beam.io.WriteToBigQuery(bq_table)
)
result = p.run()
result.wait_until_finish()
After deploy it to Dataflow, everything looks fine and no error. But then I noticed that enrich data
step has two nodes instead of one.
And also, the side input stuck as you can see it has Elements Added
with 21 counts in Input Collections and -
value in Elements Added
in Output Collections.
You can find the full pipeline code here and mock pubsub publisher here
I already follow all instruction in these documentations:
- https://beam.apache.org/documentation/patterns/side-inputs/
- https://beam.apache.org/releases/pydoc/2.35.0/apache_beam.io.gcp.bigquery.html
Yet still found this error. Please help me. Thanks!
ANSWER
Answered 2022-Jan-12 at 13:12Here you have a working example:
mytopic = ""
sql = "SELECT station_id, CURRENT_TIMESTAMP() timestamp FROM `bigquery-public-data.austin_bikeshare.bikeshare_stations` LIMIT 10"
def to_bqrequest(e, sql):
from apache_beam.io import ReadFromBigQueryRequest
yield ReadFromBigQueryRequest(query=sql)
def merge(e, side):
for i in side:
yield f"Main {e.decode('utf-8')} Side {i}"
pubsub = p | "Read PubSub topic" >> ReadFromPubSub(topic=mytopic)
side_pcol = (p | PeriodicImpulse(fire_interval=300, apply_windowing=False)
| "ApplyGlobalWindow" >> WindowInto(window.GlobalWindows(),
trigger=trigger.Repeatedly(trigger.AfterProcessingTime(5)),
accumulation_mode=trigger.AccumulationMode.DISCARDING)
| "To BQ Request" >> ParDo(to_bqrequest, sql=sql)
| ReadAllFromBigQuery()
)
final = (pubsub | "Merge" >> ParDo(merge, side=beam.pvalue.AsList(side_pcol))
| Map(logging.info)
)
p.run()
Note this uses a GlobalWindow
(so that both inputs have the same window). I used a processing time trigger so that the pane contains multiple rows. 5
was chosen arbitrarily, using 1
would work too.
Please note matching the data between side and main inputs is non deterministic, and you may see fluctuating values from older fired panes.
In theory, using FixedWindows
should fix this, but I cannot get the FixedWindows
to work.
QUESTION
I created an extension method to add all JSON configuration files to the IConfigurationBuilder
public static class IConfigurationBuilderExtensions
{
public static IConfigurationBuilder AddJsonFilesFromDirectory(
this IConfigurationBuilder configurationBuilder,
IFileSystem fileSystem,
string pathToDirectory,
bool fileIsOptional,
bool reloadConfigurationOnFileChange,
string searchPattern = "*.json",
SearchOption directorySearchOption = SearchOption.AllDirectories)
{
var jsonFilePaths = fileSystem.Directory.EnumerateFiles(pathToDirectory, searchPattern, directorySearchOption);
foreach (var jsonFilePath in jsonFilePaths)
{
configurationBuilder.AddJsonFile(jsonFilePath, fileIsOptional, reloadConfigurationOnFileChange);
}
return configurationBuilder;
}
}
and want to create tests for it using xUnit. Based on
How do you mock out the file system in C# for unit testing?
I installed the packages System.IO.Abstractions and System.IO.Abstractions.TestingHelpers and started to test that JSON files from directories have been added
public sealed class IConfigurationBuilderExtensionsTests
{
private const string DirectoryRootPath = "./";
private readonly MockFileSystem _fileSystem;
public IConfigurationBuilderExtensionsTests()
{
_fileSystem = new MockFileSystem(new[]
{
"text.txt",
"config.json",
"dir/foo.json",
"dir/bar.xml",
"dir/sub/deeper/config.json"
}
.Select(filePath => Path.Combine(DirectoryRootPath, filePath))
.ToDictionary(
filePath => filePath,
_ => new MockFileData(string.Empty)));
}
[Theory]
[InlineData("*.json", SearchOption.AllDirectories)]
[InlineData("*.json", SearchOption.TopDirectoryOnly)]
// ... more theories go here ...
public void ItShouldAddJsonFilesFromDirectory(string searchPattern, SearchOption searchOption)
{
var addedJsonFilePaths = new ConfigurationBuilder()
.AddJsonFilesFromDirectory(_fileSystem, DirectoryRootPath, true, true, searchPattern, searchOption)
.Sources
.OfType()
.Select(jsonConfigurationSource => jsonConfigurationSource.Path)
.ToArray();
var jsonFilePathsFromTopDirectory = _fileSystem.Directory.GetFiles(DirectoryRootPath, searchPattern, searchOption);
Assert.True(addedJsonFilePaths.Length == jsonFilePathsFromTopDirectory.Length);
for (int i = 0; i < addedJsonFilePaths.Length; i++)
{
Assert.Equal(
jsonFilePathsFromTopDirectory[i],
Path.DirectorySeparatorChar + addedJsonFilePaths[i]);
}
}
}
The tests are passing but I would like to know if I could get in trouble when prepending Path.DirectorySeparatorChar
to addedJsonFilePaths[i]
.
The problem is that
jsonFilePathsFromTopDirectory[i]
returns "/config.json"addedJsonFilePaths[i]
returns "config.json"
so I have to prepend a slash at the beginning. Do you have any suggestions how to improve this / avoid later problems?
ANSWER
Answered 2021-Dec-19 at 09:24The logic of comparing files seems alright, I don't find any outstanding problem with it, it is ok to prepend the "/" to match what you need. Could be even better if you could use the System.IO.Path.DirectorySeparatorChar
for the directory root path as well, so if you run on windows or Linux you will have no issues.
But there may be a conceptual problem with what you are doing. To my understanding you aim to verify existence of specific configuration files required for your program to work right, if those files are missing than the program should fail. But that kind of failure due to missing configuration files, is an expected and valid result of your code. Yet, you unit-test this as if missing files should fail the test, as if missing files are an indication that something wrong with your code, this is wrong.
Missing files are not indication of your code not working correct and Unit-test should not be used as a validator to make sure the files exist prior executing the program, you will likely agree that unit-test is not part of the actual process and it should only aim to test your code and not preconditions, the test should compare an expected result (mock result of your code) vs. actual result and certainly not meant to become part of the code. That unit test looks like a validator that should be in the code.
So unless those files are produced by your specific code (and not the deployment) there is no sense testing that. In such case you need to create a configuration validator code - and your unit test could test that instead. So it will test that the validator expected result with a mock input you provide. But the thing here is that you would know that you only testing the validation logic and not the actual existence of the files.
QUESTION
I would like to have the preview of my HomeScreen
composable function in my HomeScreenPrevieiw
preview function. However this is not being possible to do because I am getting the following error:
java.lang.IllegalStateException: ViewModels creation is not supported in Preview
at androidx.compose.ui.tooling.ComposeViewAdapter$FakeViewModelStoreOwner$1.getViewModelStore(ComposeViewAdapter.kt:709)
at androidx.lifecycle.ViewModelProvider.(ViewModelProvider.kt:105)
at androidx.lifecycle.viewmodel.compose.ViewModelKt.get(ViewModel.kt:82)
at androidx.lifecycle.viewmodel.compose.ViewModelKt.viewModel(ViewModel.kt:72)
at com.example.crud.ui.screens.home.HomeScreenKt.HomeScreen(HomeScreen.kt:53)
at com.example.crud.ui.screens.home.HomeScreenKt.HomeScreenPreview(HomeScreen.kt:43)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
...
This is my HomeScreen
code:
@Composable
fun HomeScreen(
viewModel: HomeViewModel = hiltViewModel(),
navigateToDetailsAction: () -> Unit,
openCardDetailsAction: (Int) -> Unit
) {
val cities = viewModel.cities.observeAsState(listOf())
Scaffold(
topBar = { HomeAppBar() },
floatingActionButton = { HomeFab(navigateToDetailsAction) }
) {
HomeContent(cities) { id -> openCardDetailsAction(id) }
}
}
This is the code for my preview function:
@Preview
@Composable
private fun HomeScreenPreview() {
HomeScreen(navigateToDetailsAction = {}, openCardDetailsAction = {})
}
My view model:
@HiltViewModel
class HomeViewModel @Inject constructor(repository: CityRepository) : ViewModel() {
val cities: LiveData> = repository.allCities.asLiveData()
}
Repository:
@ViewModelScoped
class CityRepository @Inject constructor(appDatabase: AppDatabase) {
private val dao by lazy { appDatabase.getCityDao() }
val allCities by lazy { dao.getAllCities() }
suspend fun addCity(city: City) = dao.insert(city)
suspend fun updateCity(city: City) = dao.update(city)
suspend fun deleteCity(city: City) = dao.delete(city)
suspend fun getCityById(id: Int) = dao.getCityById(id)
}
AppDatabase:
@Database(entities = [City::class], version = 2, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun getCityDao() : CityDao
}
I thought it might be a problem with the view model being passed as the default parameter of my HomeScreen
and so I decided to do it this way:
@Composable
fun HomeScreen(
navigateToDetailsAction: () -> Unit,
openCardDetailsAction: (Int) -> Unit
) {
val viewModel: HomeViewModel = hiltViewModel()
val cities = viewModel.cities.observeAsState(listOf())
Scaffold(
topBar = { HomeAppBar() },
floatingActionButton = { HomeFab(navigateToDetailsAction) }
) {
HomeContent(cities) { id -> openCardDetailsAction(id) }
}
}
But it still doesn't work (I keep getting the same error), and it's not good for testing as it would prevent me from testing my HomeScreen
with a mocked view model.
ANSWER
Answered 2021-Sep-07 at 16:48This is exactly one of the reasons why the view model is passed with a default value. In the preview, you can pass a test object:
@Preview
@Composable
private fun HomeScreenPreview() {
val viewModel = HomeViewModel()
// setup viewModel as you need it to be in the preview
HomeScreen(viewModel = viewModel, navigateToDetailsAction = {}, openCardDetailsAction = {})
}
Since you have a repository, you can do the same thing you would do to test the view model.
- Create interface for
CityRepository
interface CityRepositoryI {
val allCities: List
suspend fun addCity(city: City)
suspend fun updateCity(city: City)
suspend fun deleteCity(city: City)
suspend fun getCityById(id: Int)
}
- Implement it for
CityRepository
:
@ViewModelScoped
class CityRepository @Inject constructor(appDatabase: AppDatabase) : CityRepositoryI {
private val dao by lazy { appDatabase.getCityDao() }
override val allCities by lazy { dao.getAllCities() }
override suspend fun addCity(city: City) = dao.insert(city)
override suspend fun updateCity(city: City) = dao.update(city)
override suspend fun deleteCity(city: City) = dao.delete(city)
override suspend fun getCityById(id: Int) = dao.getCityById(id)
}
- Create
FakeCityRepository
for testing purposes:
class FakeCityRepository : CityRepositoryI {
// predefined cities for testing
val cities = listOf(
City(1)
).toMutableStateList()
override val allCities by lazy { cities }
override suspend fun addCity(city: City) {
cities.add(city)
}
override suspend fun updateCity(city: City){
val index = cities.indexOfFirst { it.id == city.id }
cities[index] = city
}
override suspend fun deleteCity(city: City) {
cities.removeAll { it.id == city.id }
}
override suspend fun getCityById(id: Int) = cities.first { it.id == id }
}
So you can pass it into your view model: HomeViewModel(FakeCityRepository())
You can do the same with AppDatabase
instead of a repository, it all depends on your needs. Check out more about Hilt testing
p.s. I'm not sure if this will build, since I don't have some of your classes, but you should have caught the idea.
QUESTION
I get a error when i change the version to 0.8 , but works fine with 0.6, how i see the most recent version? , i tried downloaded from npm install @chainlink/contracts --save, but only works with mock mode.
This is my repo: https://github.com/irwingtello/lottery
Compiling contracts... Solc version: 0.8.9 Optimizer: Enabled Runs: 200 EVM Version: Istanbul CompilerError: solc returned the following errors:
ParserError: Source "C:/Users/irwin/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@1.1.1/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol" not found: File not found. --> contracts/Lottery.sol:4:1: | 4 | import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ERROR: Unable to load project
ANSWER
Answered 2021-Nov-05 at 21:48"As of 1.2.0 and onward all the releases of this package are going to match the @chainlink/contracts
NPM tags So it will look backwards
, but we are starting with 0.2.1
"
Change: @chainlink=smartcontractkit/chainlink-brownie-contracts@1.1.1
To: @chainlink=smartcontractkit/chainlink-brownie-contracts@0.2.1
https://github.com/smartcontractkit/chainlink-brownie-contracts/tree/v0.2.1
QUESTION
I have a custom hook as below
export const useUserSearch = () => {
const [options, setOptions] = useState([]);
const [searchString, setSearchString] = useState("");
const [userSearch] = useUserSearchMutation();
useEffect(() => {
if (searchString.trim().length > 3) {
const searchParams = {
orgId: "1",
userId: "1",
searchQuery: searchString.trim(),
};
userSearch(searchParams)
.then((data) => {
setOptions(data);
})
.catch((err) => {
setOptions([]);
console.log("error", err);
});
}
}, [searchString, userSearch]);
return {
options,
setSearchString,
};
};
and I want to test this hook but am not able to mock userSearch
function which is being called inside useEffect. can anybody help? this is my test
it('should set state and test function', async () => {
const wrapper = ({ children }) => (
{children}
)
const { result } = renderHook(
() => useUserSearch(),
{ wrapper }
)
await act(async () => {
result.current.setSearchString('abc5')
})
expect(result.current.options).toEqual(expected)
})
useUserSearchMutation
import {createApi, fetchBaseQuery} from '@reduxjs/toolkit/query/react';
export const userSearchAPI = createApi({
reducerPath: 'userSearchResult',
baseQuery: fetchBaseQuery({baseUrl: process.env.REACT_APP_BASE_URL}),
tagTypes: ['Users'],
endpoints: build => ({
userSearch: build.mutation({
query: body => ({url: '/org/patient/search', method: 'POST', body}),
invalidatesTags: ['Users'],
}),
}),
});
export const {useUserSearchMutation} = userSearchAPI;
ANSWER
Answered 2021-Oct-13 at 05:27Because it's a named export you should return an object in the mock
it("should set state and test function", async () => {
jest.mock("./useUserSearchMutation", () => ({
useUserSearchMutation: () => [jest.fn().mockResolvedValue(expected)],
}));
const wrapper = ({ children }) => (
...
});
QUESTION
Given a folder structure like such:
dags/
**/
code.py
tests/
dags/
**/
test_code.py
conftest.py
Where dags serves as the root of the src files, with 'dags/a/b/c.py' imported as 'a.b.c'.
I want to test the following function in code.py:
from dag_common.connections import get_conn
from utils.database import dbtypes
def select_records(
conn_id: str,
sql: str,
bindings,
):
conn: dbtypes.Connection = get_conn(conn_id)
with conn.cursor() as cursor:
cursor.execute(
sql, bindings
)
records = cursor.fetchall()
return records
But I am faced with the issue that I fail to find a way to patch the get_conn
from dag_common.connections
. I attempted the following:
import os
import sys
# adds dags to sys.path for tests/*.py files to be able to import them
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "dags"))
{{fixtures}}
Where I have tested the following replacements for {{fixtures}}
:
(1.a) - default
@pytest.fixture(autouse=True, scope="function")
def mock_get_conn():
with mock.patch("dag_common.connections.get_conn") as mock_getter:
yield mock_getter
(1.b) - prefixing path with dags
@pytest.fixture(autouse=True, scope="function")
def mock_get_conn():
with mock.patch("dags.dag_common.connections.get_conn") as mock_getter:
yield mock_getter
(1.c) - 1.a, with scope="session"
(1.d) - 1.b, with scope="session"
(1.e) - object patching the module itself
@pytest.fixture(autouse=True, scope="function")
def mock_get_conn():
import dags.dag_common.connections
mock_getter = mock.MagicMock()
with mock.patch.object(dags.dag_common.connections, 'get_conn', mock_getter):
yield mock_getter
(1.f) - 1.a, but using pytest-mock fixture
@pytest.fixture(autouse=True, scope="function")
def mock_get_conn(mocker):
with mocker.patch("dag_common.connections.get_conn") as mock_getter:
yield mock_getter
(1.g) - 1.b, but using pytest-mock fixture
(1.h) - 1.a, but using pytest's monkeypatch
@pytest.fixture(autouse=True, scope="function")
def mock_get_conn(mocker, monkeypatch):
import dags.dag_common.connections
mock_getter = mocker.MagicMock()
monkeypatch.setattr(dags.dag_common.connections, 'get_conn', mock_getter)
yield mock_getter
(2.a) - decorator @mock.patch("dag_common.connections.get_conn")
@mock.patch("dag_common.connections.get_conn")
def test_executes_sql_with_default_bindings(mock_getter, mock_context):
# arrange
sql = "SELECT * FROM table"
records = [RealDictRow(col1=1), RealDictRow(col1=2)]
mock_conn = mock_getter.return_value
mock_cursor = mock_conn.cursor.return_value
mock_cursor.execute.return_value = records
# act
select_records(conn_id="orca", sql=sql, ) # ...
# assert
mock_cursor.execute.assert_called_once_with(
sql, # ...
)
(2.b) - (2.a) but with "dags." prefix
(2.c) - context manager
def test_executes_sql_with_default_bindings(mock_context):
# arrange
sql = "SELECT * FROM table"
records = [RealDictRow(col1=1), RealDictRow(col1=2)]
with mock.patch("dag_common.connections.get_conn") as mock_getter:
mock_conn = mock_getter.return_value
mock_cursor = mock_conn.cursor.return_value
mock_cursor.execute.return_value = records
# act
select_records(conn_id="orca", sql=sql, ) # ...
# assert
mock_cursor.execute.assert_called_once_with(
sql, # ...
)
(2.d) - (2.c) but with "dags." prefix
ConclusionBut alas, no matter what solution I pick, the function-to-be-mocked still gets called. I made sure to attempt each solution separatedly from each other, and to kill/clear/restart my pytest-watch process in between attempts.
I feel like this may be related to me meddling with sys.path in conftest.py, because outside of this I feel like I have exhausted all possibilities.
Any idea how I can solve this?
ANSWER
Answered 2021-Sep-22 at 07:06Yeah. I also fought with this initially when I learned patching and mocking and know how frustrating it is as you seem to be doing everything right, but it does not work. I sympathise with you!
This is actually how mocking of imported stuff works, and once you realise it, it actually makes sense.
The problem is that import works in the way that it makes the imported module available in the context of where your import is.
Lets' assume your code.py
module is in 'my_package' folder. Your code is available then as my_package.code
. And once you use from dag_common.connections import get_conn
in code
module - the imported get_conn
becomes available as .... my_package.code.get_conn
And in this case you need to patch my_package.code.get_conn
not the original package you imported get_conn from.
Once you realise this, patching becomes much easier.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install CppUMockGen
| OPTION | Description | | - | - | | -i, --input <input> ` | Input file path | | `-m, --mock-output <mock-output> | Mock output directory or file path | | -e, --expect-output <expect-output> | Expectation output directory or file path | | -x, --cpp | Force interpretation of the input file as C++ | | -s, --std | Set language standard (c+\+14, c\+\+17, etc.)| | -I, --include-path <path> | Include path | | -B, --base-directory <path> | Base directory path | | -t, --type-override <expr> | Override generic type | | -f, --config-file <file> | Configuration file to be parsed for options | | -v, --version | Print version | | -h, --help | Print help |. To generate a mock from a header file containing the functions that you want to mock, just pass the path to the header file as input in the first non-option argument or explicitly with the -i / --input option, and the path where you want the file with the mocked functions to be generated as output using the -m / --mock-output option. To generate expectations, pass the path where you want the files with the expectation to be generated as output using the -e / --expect-output option (additionally to or instead of the -m option). CppUMockGen, just as any C/C++ compiler, needs to know where to find other include files referenced by the input file in order to interpret it properly. Pass the paths to the necessary include directories by using the -I / --include-path option. Like with most compilers, you may use this option several times to indicate multiple include directories. Mocks and expectations generated by CppUMockGen need to include the mocked header file. By default, the mocked header file will be referenced with a relative path from the directory where the mocks/expectations are generated. This behavior may be overriden using the -B / --base-directory option to set a base directory to reference included mocked headers (e.g., set it to a directory that is in the include path when compiling tests). CppUMockGen deduces the data types to use with CppUMock from the actual function parameters and return types. If the API that you are mocking is well designed (e.g. pointers to non-const values are not used for input parameters), CppUMockGen will guess properly in most cases the correct types. Nevertheless, mocked data types can be overridden by using -t / --type-override options to indicate the type of function parameters or function returns. Type overriding can be defined in generic form, which apply to any function parameter or return types that match the specified type, or can be defined in function-specific form, which apply to parameters and return types of the specified function. Since complex mocks will require a lot of override options, and many of them can be reused to generate mocks for other files, you can store options in a text file and load that file using the -f / --config-file option.
To build CppUMockGen first clone this repository on your machine, and in the directory where you cloned it (top directory) execute the following commands:.
To build CppUMockGen first clone this repository on your machine, and in the directory where you cloned it (top directory) execute the following commands (where <Visual Studio XX 20YY> is a cmake generator for visual studio, e.g., "Visual Studio 16 2019", "Visual Studio 17 2022"):. Eventually open the CppUMockGen.Top.sln VS solution generated in the build_vs directory, then compile the solution. To execute the tests, compile the run_tests project. If coverage is enabled, to generate the coverage report compile the run_coverage project, and the report will be generated in the coverage_msvc directory under the top directory.
To build CppUMockGen first clone this repository on your machine, and in the directory where you cloned it (top directory) execute the following commands:.
The following build types are supported: - Release - Debug - RelWithDebInfo (Release build with debug information) - MinSizeRel (Release with executable size minimization) - Coverage (Only GCC/MinGW). When using Visual Studio, the available build types are available as project configurations. Coverage is enabled by default, to disable it pass the option -DCOVERAGE=OFF to CMake. When using GCC/MinGW, the default build type is Release. To select a different build type pass the option -DCMAKE_BUILD_TYPE=<Build Type> to CMake. If during configuration CMake cannot find some dependencies, their installation paths can be indicated by passing one of the following options to CMake: - libClang: -DLibClang_HOME=<Path to LLVM top directory> - CppUTest: -DCppUTest_HOME=<Path to CppUTest top directory> - LCOV: -Dlcov_HOME=<Path to LCOV top directory>.
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page