Can't understand this mockito verify failure - mockito

verify(mockDao).updateExitStopLimitOrder(any(), eq(
ChartPatternSignal.Order.create(exitStopLossOrderStatus.getOrderId(),
0,
0, exitStopLossOrderStatus.getStatus())
));
assertThat(stopLossOrderStatusRequestCapture.getValue().getOrderId()).isEqualTo(2L);
verify(mockBinanceApiRestClient).cancelOrder(cancelOrderRequestCapture.capture());
assertThat(cancelOrderRequestCapture.getValue().getOrderId()).isEqualTo(2);
assertThat(cancelOrderRequestCapture.getValue().getSymbol()).isEqualTo("ETHUSDT");
verify(mockDao).cancelStopLimitOrder(eq(chartPatternSignal));
verify(mockBinanceApiRestClient).newOrder(newOrderCapture.capture());
assertThat(newOrderCapture.getValue().getSymbol()).isEqualTo("ETHUSDT");
assertThat(newOrderCapture.getValue().getSide()).isEqualTo(OrderSide.BUY);
assertThat(newOrderCapture.getValue().getType()).isEqualTo(OrderType.MARKET);
assertThat(newOrderCapture.getValue().getTimeInForce()).isNull();
assertThat(newOrderCapture.getValue().getQuantity()).isEqualTo("20.0301");
// Quantity that was buyback = 20.0301 (because 20.01 / 0.999) but exclude the synthetic 10.01
verify(mockDao).setExitOrder(chartPatternSignal,
ChartPatternSignal.Order.create(3L,
10.0201, 1.050075, OrderStatus.FILLED), TradeExitType.TARGET_TIME_PASSED);
The last verify statement above for setExitOrder fails, but it shows as expected every verify set on mockDao, even though it just ran through those verify statements:
Argument(s) are different! Wanted:
mockDao.setExitOrder(
CoinPair: ETHUSDT, SignalSource: PYTHON_SOURCE_SIGNALS, TimeFrame: FIFTEEN_MINUTES, TradeType: SELL, Pattern: Resistance, Time of signal: 2022-06-03 14:51, Attempt: 1, Price Target: 6000.000000 Price Target Time: 2022-06-03 18:11, Attempt: 1,
Order Id: 3 Executed Qty: 10.020100 Average Price: 1.050075 Order Status: FILLED.,
TARGET_TIME_PASSED
);
-> at com.binance.bot.trading.ExitPositionAtMarketPriceTest.sellTrade_minTradeValueNotMet_automaticallyHandleUsingSyntheticTrade(ExitPositionAtMarketPriceTest.java:705)
Actual invocations have different arguments:
mockDao.updateExitStopLimitOrder(
CoinPair: ETHUSDT, SignalSource: PYTHON_SOURCE_SIGNALS, TimeFrame: FIFTEEN_MINUTES, TradeType: SELL, Pattern: Resistance, Time of signal: 2022-06-03 14:51, Attempt: 1, Price Target: 6000.000000 Price Target Time: 2022-06-03 18:11, Attempt: 1,
Order Id: 1 Executed Qty: 0.000000 Average Price: 0.000000 Order Status: OPEN.
);
-> at com.binance.bot.trading.ExitPositionAtMarketPrice.cancelStopLimitOrder(ExitPositionAtMarketPrice.java:78)
mockDao.getChartPattern(
CoinPair: ETHUSDT, SignalSource: PYTHON_SOURCE_SIGNALS, TimeFrame: FIFTEEN_MINUTES, TradeType: SELL, Pattern: Resistance, Time of signal: 2022-06-03 14:51, Attempt: 1, Price Target: 6000.000000 Price Target Time: 2022-06-03 18:11, Attempt: 1
);
-> at com.binance.bot.trading.ExitPositionAtMarketPrice.cancelStopLimitOrder(ExitPositionAtMarketPrice.java:82)
mockDao.cancelStopLimitOrder(
CoinPair: ETHUSDT, SignalSource: PYTHON_SOURCE_SIGNALS, TimeFrame: FIFTEEN_MINUTES, TradeType: SELL, Pattern: Resistance, Time of signal: 2022-06-03 14:51, Attempt: 1, Price Target: 6000.000000 Price Target Time: 2022-06-03 18:11, Attempt: 1
);
-> at com.binance.bot.trading.ExitPositionAtMarketPrice.cancelStopLimitOrder(ExitPositionAtMarketPrice.java:93)
mockDao.setExitOrder(
CoinPair: ETHUSDT, SignalSource: PYTHON_SOURCE_SIGNALS, TimeFrame: FIFTEEN_MINUTES, TradeType: SELL, Pattern: Resistance, Time of signal: 2022-06-03 14:51, Attempt: 1, Price Target: 6000.000000 Price Target Time: 2022-06-03 18:11, Attempt: 1,
Order Id: 3 Executed Qty: 10.020100 Average Price: 1.050075 Order Status: FILLED.,
TARGET_TIME_PASSED
);
-> at com.binance.bot.trading.ExitPositionAtMarketPrice.exitPositionIfStillHeld(ExitPositionAtMarketPrice.java:229)
mockDao.writeAccountBalanceToDB(
);
-> at com.binance.bot.trading.ExitPositionAtMarketPrice.exitPositionIfStillHeld(ExitPositionAtMarketPrice.java:245)
at com.binance.bot.trading.ExitPositionAtMarketPriceTest.sellTrade_minTradeValueNotMet_automaticallyHandleUsingSyntheticTrade(ExitPositionAtMarketPriceTest.java:705)
I can't even make sense of what the error is all about. I have verified by stepping through the code that the actual arguments passed to setExitOrder are same as those expected in the test. Any help?

Related

Test API toMatchObject() jest expect function

I'm trying to check if a response from the body matches partially an object of data "partialLaunchData" . I'm surprised to get this error:
● Test POST /launches › It should respond with 201 success created
expect(received).toMatchObject(expected)
- Expected - 3
+ Received + 13
Object {
- "mission": "Kepler_155",
- "rocket": "Explorer IS1",
- "target": "Kepler-186 f",
+ "launch": Object {
+ "customer": Array [
+ "SAFTA",
+ "NASA",
+ ],
+ "flightNumber": 101,
+ "launchDate": "2022-10-13T21:24:59.189Z",
+ "mission": "Kepler Exploration x",
+ "rocket": " Explorer IS1",
+ "success": true,
+ "target": "Kepler-442",
+ "upcoming": true,
+ },
}
42 | const responseDate= Date(response.body.launchDate).valueOf();
43 | expect(responseDate).toBe(requestDate);
> 44 | expect(response.body).toMatchObject(partialLaunchData);
| ^
45 | })
46 | //tests on the propreties sent
47 | test('It should catch missing required propreties', ()=>{});
at Object.toMatchObject (src/routes/launches/launches.test.js:44:31)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 3 passed, 4 total
Snapshots: 0 total
Time: 3.452 s
Ran all test suites.
This is my Code in the launches.test.js file describing a post Test on launches path "/launches" .
describe( 'Test POST /launches ', ()=> {
// test the response
const completeLaunchData={
// flightNumber: 100,
mission: 'Kepler Exploration x',
rocket: ' Explorer IS1',
launchDate: new Date(),
target: 'Kepler-442',
// customer: ['SpaceX, NASA'],
// upcoming: true,
}
const partialLaunchData={
// flightNumber: 100,
mission: 'Kepler_155',
rocket: 'Explorer IS1',
target: 'Kepler-186 f',
// upcoming: true,
}
test('It should respond with 201 success created', async()=>{
const response = await request(app).post('/launches')
// comparing two dates and joining them in one format : we will compare the value of the two dates
.send(
completeLaunchData
)
.expect('Content-Type',/json/)
.expect(201);
const requestDate = Date(completeLaunchData.launchDate).valueOf();
const responseDate= Date(response.body.launchDate).valueOf();
expect(responseDate).toBe(requestDate);
expect(response.body).toMatchObject(partialLaunchData);
})
Who has an idea about the issue ? I need help please.

How do I format [future, non-current] dates in Eleventy + Nunjucks?

I'm building a site with a CMS (Netlify) for a local band, and they have future gig dates they will put on the site. So far the dates show up as very long non-formatted strings that include the time and time zone. I'm trying to figure out how to format the dates to be simpler (day, date, time for example).
I've tried plugins like nunjucks-date but I'm a little confused about how to use a plugin (and filters) in this case.
My repo: https://github.com/mollycarroll/serapis-eleventy-2
Example gig entry:
---
layout: gig
venue: Cedar Lake Cellars
date: 2022-05-28
time: 6pm
city: Wright City, MO
---
Gig template:
<h2>{{ venue }}</h2>
<h4>{{ city }} {{ date }} {{ time }}</h4>
config.yml for the CMS:
- name: 'gigs'
label: 'Shows'
folder: 'src/gigs'
create: true
slug: '{{month}}-{{day}}-{{venue}}'
fields:
- { label: 'Layout', name: 'layout', widget: 'hidden', default: '_includes/gig.njk' }
- { label: 'Date', name: 'date', widget: 'date', default: '' }
- { label: 'Time', name: 'time', widget: 'string', default: '' }
- { label: 'Venue', name: 'venue', widget: 'string', default: '' }
- { label: 'City', name: 'city', widget: 'string', default: '' }
Thanks for any help.
First, you should create a filter, let's say src/filters/date.js with the following content:
const { DateTime } = require("luxon");
// Add a friendly date filter to nunjucks.
// Defaults to format of LLLL d, y unless an
// alternate is passed as a parameter.
// {{ date | friendlyDate('OPTIONAL FORMAT STRING') }}
// List of supported tokens: https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens
module.exports = (dateObj, format = 'LLLL d, y') => {
return DateTime.fromISO(dateObj, { zone: "Europe/Amsterdam", locale: "en" }).toFormat(format);
};
Make sure you check Luxon documentation for details. Then add the filter in .eleventy.js:
module.exports = function(eleventyConfig) {
...
eleventyConfig.addFilter("date", require("./src/filters/date.js"));
...
};
Now you can use it in Nunjacks with a default value {{ date }}, in this example 'LLLL d, y', or any value you need at a certain position on your website {{ date | date('dd. LLLL yyyy.') }}. This can be very useful if you need at some point just month and year or just day and month.
You can even create multiple language filters, like dateEn.js and dateDe.js, and format each to its own language if you have a multilingual site.
Hope this helps.
EDIT: In order for this filter to work the dateObj should be in ISO 8601 format.

Calculate sum of object array field

Working on a Node App with Express as the web framework and Mongo as the backend. Currently, I have a Mongoose data schema with players and associated statistics. Here's an anonymized example of the structure:
name: 'Player Name',
image: 'image-location',
position: 'Guard',
description: 'Player Detail',
__v: 6,
weight: 200,
dob: 1993-08-03T05:00:00.000Z,
hometown: 'town-name',
country: 'country-name',
height_feet: 6,
height_inches: 4,
season: [
{
year: '2012-2013',
grade: 'Freshman',
gp: 18,
gs: 0,
mpg: 6.9,
fg: 0.348,
tp: 0.278,
ft: 1,
rpg: 0.8,
apg: 1,
spg: 0.3,
bpg: 0,
ppg: 1.4
},
{
year: '2013-2014',
grade: 'Sophomore',
gp: 36,
gs: 7,
mpg: 20.3,
fg: 0.432,
tp: 0.4,
ft: 0.643,
rpg: 1.6,
apg: 1.1,
spg: 0.2,
bpg: 0.1,
ppg: 7.1
},
{
year: '2014-2015',
grade: 'Junior',
gp: 34,
gs: 33,
mpg: 27.5,
fg: 0.449,
tp: 0.391,
ft: 0.755,
rpg: 2.9,
apg: 2,
spg: 0.8,
bpg: 0.1,
ppg: 10.1
},
{
year: '2015-2016',
grade: 'R. Senior',
gp: 8,
gs: 8,
mpg: 31.6,
fg: 0.425,
tp: 0.291,
ft: 0.6,
rpg: 2.9,
apg: 1.9,
spg: 0.6,
bpg: 0.3,
ppg: 12
},
{
year: '2016-2017',
grade: 'Senior',
gp: 35,
gs: 35,
mpg: 33.3,
fg: 0.473,
tp: 0.384,
ft: 0.795,
rpg: 4.6,
apg: 2.7,
spg: 1.2,
bpg: 0,
ppg: 15.1
}
]
}
I'm still fairly new to Mongo and Node as a whole, so pardon the elementary question. How would I be able to calculate the average of a particular statistic for the total number of seasons (e.g. 4 year average of points per game)?
The goal here is to calculate the value and have it available and passed on the GET route for the player page. Here's the route I have for the player page:
router.get("/:id", function(req, res){
Player.findById(req.params.id).populate("comments").exec(function(err, foundPlayer){
if(err){
console.log(err);
} else {
console.log(foundPlayer)
res.render("players/show", {player: foundPlayer});
}
});
});
What can I do to both calculate this value and have it available for use on the player page?
You have to iterate over seasons array and find the average. For example:
const { season } = <.........your MongoDB response>
let average = 0;
if(season.length){
let total = 0
season.map(({ gp }) => (total += gp))
average = total / season.length
}
The variable average will give you the answer. I've shown an example to calculate average of gp
we can use aggregate pipeline to calculate the average directly within the query
db.collection.aggregate([
{
$match: {
_id: "playerId1" // this needs to be of type ObjectId, it should be something like mongoose.Types.ObjectId(req.params.id) in your case
}
},
{
$unwind: "$season" // unwind the season array to get a stream of documents, and to be able to calculate the average of ppg
},
{
$group: { // then group them again
_id: "$_id",
averagePointsPerGame: {
$avg: "$season.ppg"
},
season: {
$push: "$season"
}
}
}
])
you can test it here Mongo Playground
hope it helps

Sequelize, how to use Op.contains to find models that have certain values

I'm working on some project about renting houses and appartments and I've reached the point when i need to implement filtering houses based on features they have(wifi, security and other staff). In the beginning I decided to try Sequelize ORM for the first time. Stuff like adding, creating, editing is working fine, but the filtering part is where I have some problems.
I'm working with nodejs,express and postgresql.
I need to find all houses that have features listed in the array of features IDs. Here is what I've tried. In this example I'm trying to get houses which have features with ids 1, 2 and 4.
db.House.findAll({
include: [{
model: db.HouseFeature,
as: 'HouseFeatures',
where: {
featureId: {
[Op.contains]: [1, 2, 4] //<- array of featuresIds
}
}
}]
})
Fetching houses by single feature id works fine because i don't use Op.contains there.
Here are some relations related to this case:
House.hasMany(models.HouseFeature, { onDelete: 'CASCADE' });
HouseFeature.belongsTo(models.House);
HouseFeature contains featureId field.
Here is the error I get:
error: оператор не существует: integer #> unknown
at Connection.parseE (C:\***\server\node_modules\pg\lib\connection.js:601:11)
at Connection.parseMessage (C:\***\server\node_modules\pg\lib\connection.js:398:19)
at Socket.<anonymous> (C:\***\server\node_modules\pg\lib\connection.js:120:22)
at Socket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
at Socket.Readable.push (_stream_readable.js:219:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'error',
length: 397,
severity: 'ОШИБКА',
code: '42883',
detail: undefined,
hint:
'Оператор с данными именем и типами аргументов не найден. Возможно, вам следует добавить явные приведения типов.',
position: '851',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file:
'd:\\pginstaller.auto\\postgres.windows-x64\\src\\backend\\parser\\parse_oper.c',
line: '731',
routine: 'op_error',
sql:
'SELECT "House"."id", "House"."title", "House"."description", "House"."price", "House"."address", "House"."lat", "House"."lon", "House"."kitchen", "House"."bathrooms", "House"."floor", "House"."totalFloors", "House"."people", "House"."area", "House"."bedrooms", "House"."trusted", "House"."createdAt", "House"."updatedAt", "House"."CityId", "House"."ComplexId", "House"."OwnerProfileId", "House"."HouseTypeId", "House"."RentTypeId", "HouseFeatures"."id" AS "HouseFeatures.id", "HouseFeatures"."featureId" AS "HouseFeatures.featureId", "HouseFeatures"."createdAt" AS "HouseFeatures.createdAt", "HouseFeatures"."updatedAt" AS "HouseFeatures.updatedAt", "HouseFeatures"."HouseId" AS "HouseFeatures.HouseId" FROM "Houses" AS "House" INNER JOIN "HouseFeatures" AS "HouseFeatures" ON "House"."id" = "HouseFeatures"."HouseId" AND "HouseFeatures"."featureId" #> \'1,2\';'
Sorry for some russian there.
UPDATE:
I've managed to do what i needed by changing each House relating only to one HouseFeature, and by changing that HouseFeature model to store array of featureIds. Op.contains works fine.
db.House.findAll({
include: [{
model: db.HouseFeature,
as: 'HouseFeature',
where: {
features: {
[Op.contains]: req.body.features
}
},
}]
})
// Associations
HouseFeature.belongsTo(models.House);
House.hasOne(models.HouseFeature, { onDelete: 'CASCADE' });
const HouseFeature = sequelize.define('HouseFeature', {
features: {
type: DataTypes.ARRAY(DataTypes.INTEGER)
}
}, {});
Now i have one little issue. Can I somehow link HouseFeature model with Feature model to fetch feature icon images and name later on? With Feature ids being stored inside HouseFeature array.
Please check the difference between Op.in and Op.contains:
[Op.in]: [1, 2], // IN [1, 2]
[Op.contains]: [1, 2] // #> [1, 2] (PG array contains operator)
It looks like HouseFeatures.featureId is a PK with type integer, not a postgres array.
Please try:
db.House.findAll({
include: [{
model: db.HouseFeature,
as: 'HouseFeatures',
where: {
featureId: {
[Op.in]: [1, 2, 3]
}
}
}]
})
or even
db.House.findAll({
include: [{
model: db.HouseFeature,
as: 'HouseFeatures',
where: {
featureId: [1, 2, 3]
}
}]
})
instead

No UiSlider remove decimal?

How to remove decimals digit from linked output
I am using this code
$("#slider_01").noUiSlider({
start: [2000, 24000],
connect: true,
step: 0.01,
range: {
'min': 0,
'max': 28500
},
format: wNumb({
decimals: false,
thousand: ',',
prefix: '$ ',
})
});
$('#slider_01').Link('lower').to($('#value-lower_1'));
$('#slider_01').Link('upper').to($('#value-upper_1'));
I didn't have access to the wNumb library in the environment I was working with.
Had a look under the hood in the library and this also works:
$("#slider_01").noUiSlider({
...
format: {
to: (v) => parseFloat(v).toFixed(0),
from: (v) => parseFloat(v).toFixed(0)
}
});
Decimals decimals: false is invalid, use decimals: 0. Also, you are setting formatting for the .val() method. Use it like this:
$('#slider_01').Link('lower').to($('#value-lower_1'), null, wNumb({
decimals: 0,
thousand: ',',
prefix: '$ ',
}));
Change the step from 0.01 to 1.
I know it's a very old question, but I did not want to include another library Wnumb just to remove the decimal from one place. Here is my solution without using the wnumb.
var slider = document.getElementById('prcsldr');
noUiSlider.create(slider, {
start: [10000],
range: {
min: 1000,
max: 50000
},
step: 1000,
format:{
to: (v) => v | 0,
from: (v) => v | 0
}
});

Resources