Unable to implement check in my integration, getting 'map undefined' for create method of checks - github

I am trying to implement Checks into my GitHub app. My App is built with probot.
I am just not able to implement the checks. I have tried going through the documentation which demonstrate ruby example that includes several different setups(not sure if required with probot).
I just got confused with the example there.
Below is the code that resides in my index.js :
app.on('check_suite.requested', async context =>{
console.log('************------------ check suite requested')
await context.github.checks.create({
mediaType:'application/vnd.github.antiope-preview+json',
name : 'test-check-1',
head_sha: context.payload.check_suite.after,
conclusion: "success"
})
})
I get below error
ERROR probot: Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined
The error log complains about index.js:24:35, which is precisely the createmethod in the line await context.github.checks.create
Is the above code sufficient to create the check test-check-1 or do I need to take care of other things too. I already have the "Required status checks to pass before merging" option enabled under the branch protection settings of my repo.
And that section displays Sorry, we couldn’t find any status checks in the last week for this repository.
Not sure how to connect everything.
EDIT 1 : START
Below is the code after including the required params as suggested by #OscarDOM :--
app.on('check_suite.requested', async context =>{
console.log('*****check suite requested*****')
context.github.checks.create({
owner:context.payload.repository.owner,
repo:context.payload.repository.name,
mediaType:'application/vnd.github.antiope-preview+json',
name : 'test-check-1',
head_sha: context.payload.check_suite.after,
conclusion: "success"
})
})
Unfortunately, I still get the same error at exact same line and column.
EDIT 1 : END
EDIT 2 : START
Below is the final working code after including corrections for the mediaType parameter :
Please note there was one more mistake I had to correct and that is the value owner param. The correct way is to specify context.payload.repository.owner.login and this was something I had recently learnt from this StackOverflow post
app.on('check_suite.requested', async context =>{
console.log('*****check suite requested*****')
context.github.checks.create({
owner:context.payload.repository.owner.login,
repo:context.payload.repository.name,
mediaType: { previews: ['antiope']},
name : 'test-check-1',
head_sha: context.payload.check_suite.after,
conclusion: "success"
})
})
EDIT 2 : END

Would it be possible you need to pass the owner and the repository to context.github.checks.create() method? I think they are required properties: https://octokit.github.io/rest.js/v17#checks
Also, make sure the Github App has the following permissions: checks:write(https://developer.github.com/v3/activity/events/types/#checkrunevent)
Also, checking your code snippet, seems that you are not using the mediaType properly. If you check the type definition, mediaType has the following structure:
mediaTypes: {
format?: string,
previews?: string[]
}
Reference here: https://octokit.github.io/rest.js/v17#previews
Can you try it with this?
app.on('check_suite.requested', async context =>{
console.log('************------------ check suite requested')
await context.github.checks.create({
owner: '<YOUR_ORGANIZATION>',
repo: '<YOUR_REPO>',
mediaType: { previews: ['antiope']},
name : 'test-check-1',
head_sha: context.payload.check_suite.after,
conclusion: "success"
})
})
As a general feedback, I suggest you to try TypeScript, these issues would have been spotted using it :)

Related

Why am I getting "Null check operator used on a null value" from using rootBundle.load during a Flutter test?

I searched for quite a while and didn't find a clear solution to this issue on SO or other sites.
I have a Flutter test:
test('Create Repo and Read JSON', () {
Repository repository = CreateRepository();
...
}
CreateRepository() eventually calls a method with the following code:
var jsonString = await rootBundle.loadString(vendorDataFilePath);
This results in the error: Null check operator used on a null value
None of my executed code was using a null check operator (!) so where is this error coming from and how do I fix it?
After running the test in Debug mode, I found the error is actually in asset_bundle.dart within Flutter itself, not from my code.
final ByteData? asset =
await ServicesBinding.instance!.defaultBinaryMessenger.send('flutter/assets', encoded.buffer.asByteData());
It's the instance! that causes the error because instance is actually null at this point, so the null check operator (!) fails.
Unfortunately, rather than a nice descriptive error message like we normally get from Flutter, this results in a more cryptic error description directly from Dart. The root cause in my case was that an extra call is required in the test to make sure instance gets initialized.
test('Create Repo and Read JSON', () {
// Add the following line to the top of the test
TestWidgetsFlutterBinding.ensureInitialized(); // <--
Repository repository = CreateRepository();
...
}

Stop huge error output from testing-library

I love testing-library, have used it a lot in a React project, and I'm trying to use it in an Angular project now - but I've always struggled with the enormous error output, including the HTML text of the render. Not only is this not usually helpful (I couldn't find an element, here's the HTML where it isn't); but it gets truncated, often before the interesting line if you're running in debug mode.
I simply added it as a library alongside the standard Angular Karma+Jasmine setup.
I'm sure you could say the components I'm testing are too large if the HTML output causes my console window to spool for ages, but I have a lot of integration tests in Protractor, and they are SO SLOW :(.
I would say the best solution would be to use the configure method and pass a custom function for getElementError which does what you want.
You can read about configuration here: https://testing-library.com/docs/dom-testing-library/api-configuration
An example of this might look like:
configure({
getElementError: (message: string, container) => {
const error = new Error(message);
error.name = 'TestingLibraryElementError';
error.stack = null;
return error;
},
});
You can then put this in any single test file or use Jest's setupFiles or setupFilesAfterEnv config options to have it run globally.
I am assuming you running jest with rtl in your project.
I personally wouldn't turn it off as it's there to help us, but everyone has a way so if you have your reasons, then fair enough.
1. If you want to disable errors for a specific test, you can mock the console.error.
it('disable error example', () => {
const errorObject = console.error; //store the state of the object
console.error = jest.fn(); // mock the object
// code
//assertion (expect)
console.error = errorObject; // assign it back so you can use it in the next test
});
2. If you want to silence it for all the test, you could use the jest --silent CLI option. Check the docs
The above might even disable the DOM printing that is done by rtl, I am not sure as I haven't tried this, but if you look at the docs I linked, it says
"Prevent tests from printing messages through the console."
Now you almost certainly have everything disabled except the DOM recommendations if the above doesn't work. On that case you might look into react-testing-library's source code and find out what is used for those print statements. Is it a console.log? is it a console.warn? When you got that, just mock it out like option 1 above.
UPDATE
After some digging, I found out that all testing-library DOM printing is built on prettyDOM();
While prettyDOM() can't be disabled you can limit the number of lines to 0, and that would just give you the error message and three dots ... below the message.
Here is an example printout, I messed around with:
TestingLibraryElementError: Unable to find an element with the text: Hello ther. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
...
All you need to do is to pass in an environment variable before executing your test suite, so for example with an npm script it would look like:
DEBUG_PRINT_LIMIT=0 npm run test
Here is the doc
UPDATE 2:
As per the OP's FR on github this can also be achieved without injecting in a global variable to limit the PrettyDOM line output (in case if it's used elsewhere). The getElementError config option need to be changed:
dom-testing-library/src/config.js
// called when getBy* queries fail. (message, container) => Error
getElementError(message, container) {
const error = new Error(
[message, prettyDOM(container)].filter(Boolean).join('\n\n'),
)
error.name = 'TestingLibraryElementError'
return error
},
The callstack can also be removed
You can change how the message is built by setting the DOM testing library message building function with config. In my Angular project I added this to test.js:
configure({
getElementError: (message: string, container) => {
const error = new Error(message);
error.name = 'TestingLibraryElementError';
error.stack = null;
return error;
},
});
This was answered here: https://github.com/testing-library/dom-testing-library/issues/773 by https://github.com/wyze.

Meteor Blaze Templates Data Context in onCreated

I am reading in several places that I should be able to get the data context of the current template with Template.currentData();
I found that it seems to only work within an autorun. But after logging the data as a variable there, first it logs null, then it logs the data in the console.
When I try to use the data, like for example trying to pass data._id into a subscription, I get a TypeError in the console. TypeError: Cannot read property '_id' of null. So for some reason, the data is null and I am struggling to find out why.
I have the data context set within my routes using Iron Router:
Router.route('/stock/:stockNumber', {
name: 'stock.detail',
template: 'StockDetail',
data: function () {
return Stock.findOne({
stockNumber: this.params.stockNumber*1
});
}
});
What I am trying to do is get access to the data context so that I can pass some things from it, such as the '_id' into some other subscriptions. What am I doing wrong?
The template is otherwise correctly displaying the data on the page as expected, and I can use Spacebars to show things like {{_id}} for example. But again, I seem to be unable to get access to the data context in Template.StockDetail.onCreated
Ok, so here's what I ended up doing...
Apparently the data context is just simply not available in the onCreated, period. What I had to do was do a Collection.findOne() within the autorun to find the stockItem and set the result to a variable, then use the stockItem._id as the parameter in the new subscription IF the item was found. With both of these things, it seems to work just fine.
Template.StockDetail.onCreated(function () {
let instance = this;
instance.autorun(function () {
instance.subscribe('stock_item', Router.current().params.stockNumber);
let stockItem = Stock.findOne({ // This is what was needed for some reason...
stockNumber: Router.current().params.stockNumber*1
});
if (stockItem) { // ...and, also, this was needed
instance.subscribe('stock_item_scan_log', stockItem._id);
}
});
});
I just don't understand why I can't just easily get the _id some other way. This way just feels incorrect and I don't like it.

Why do I get "Could not push back" error when trying to use the IBM Bluemix Document Conversion service?

I am trying to convert documents using the Bluemix Document Conversion service with a Node.js application. I am getting nothing but errors in my app, but the test document I'm using converts fine using the demo page. Below is a minimal app that demonstrates the problem (Note that, while this app is converting a PDF from disk, the "real" app can't do that, hence the Buffer object).
'use strict';
var fs = require('fs');
var DocumentConversionV1 = require('watson-developer-cloud/document-conversion/v1');
var bluemix=require('./my_bluemix');
var extend=require('util')._extend; //Node.js' built-in object extend function
var dcCredentials = extend({
url: '<url>',
version: 'v1',
username: '<username>',
password: '<password>'
}, bluemix.getServiceCreds('document_conversion')); // VCAP_SERVICES
var document_conversion = new DocumentConversionV1(dcCredentials);
var contents = fs.readFileSync('./testdoc.pdf', 'utf8');
var parms={
file: new Buffer(contents,'utf8'),
conversion_target: 'ANSWER_UNITS', // (JSON) ANSWER_UNITS, NORMALIZED_HTML, or NORMALIZED_TEXT
content_type:'application/pdf',
contentType:'application/pdf', //don't know which of these two works, seems to be inconsistent so I include both
html_to_answer_units: {selectors: [ 'h1', 'h2','h3', 'h4']},
};
console.log('First 100 chars of file:\n******************\n'+contents.substr(0,100)+'\n******************\n');
document_conversion.convert(parms, function(err,answerUnits)
{
if (!err)
console.log('Returned '+answerUnits.length);
else
console.log('Error: '+JSON.stringify(err));
});
The results from running this program against the test PDF (782K) is:
$ node test.js
[DocumentConversion] WARNING: No version_date specified. Using a (possibly old) default. e.g. watson.document_conversion({ version_date: "2015-12-15" })
[DocumentConversion] WARNING: No version_date specified. Using a (possibly old) default. e.g. watson.document_conversion({ version_date: "2015-12-15" })
First 100 chars of file:
******************
%PDF-1.5
%����
1 0 obj
<</Type/Catalog/Pages 2 0 R/Lang(en-US) /StructTreeRoot 105 0 R/MarkInfo<<
******************
Error: {"code":400,"error":"Could not push back 82801 bytes in order to reparse stream. Try increasing push back buffer using system property org.apache.pdfbox.baseParser.pushBackSize"}
$
Can someone tell me
How to get rid of the warning messages
Why the document is not getting converted
How do I "increase the push back buffer"
Other documents give different errors, but I'm hoping if I can make this one work then the other errors will go away too.
You can get rid of the warning message by specifying a version date in your configuration. See the tests for an example. 1
If the document converted through the demo but failed to convert when using your application, it is likely an error with how the binary data is passed to the service. (For example, it's getting corrupted or truncated.) You can see the Node.js source code for the demo here 2. It may help you figure out the mistake or give you a different approach to loading/sending the file.
That is an error from one of the underlying libraries used by the service. Unfortunately, it's not something that a caller can adjust at this point.

How to fix type error while using gulp-filter?

I am mimicking the code from John Papa's outstanding Pluralsight course on Gulp.
When I use the code as shown in John's course:
.pipe(jsFilter)
.pipe($.uglify())
.pipe(jsFilter.restore())
I get an error on the 3rd line of code:
TypeError: Object #<StreamFilter> has no method 'restore'
When I use the code as shown in the readme from gulp-filter
.pipe(jsFilter)
.pipe($.uglify())
.pipe(jsFilter.restore)
I get an error that it can't pipe to undefined.
Based on what I can find online, both of these patterns are working for others. Any clues as to why this might be happening?
Here is the whole task, if that helps and the console logging indicates that everything if fine until the filter restore call.
Here is the entire task if that helps:
gulp.task('build-dist', ['inject', 'templatecache'], function() {
log('Building the distribution files in the /dist folder');
var assets = $.useref.assets({searchPath: './'});
var templateCache = config.temp + config.templateCache.file;
var jsFilter = $.filter('**/*.js');
return gulp
.src(config.index)
.pipe($.plumber({errorHandler: onError}))
.pipe($.inject(gulp.src(templateCache, {read: false}), {
starttag: '<!-- inject:templates:js -->'
}))
.pipe(assets)
.pipe(jsFilter)
.pipe($.uglify())
.pipe(jsFilter.restore())
.pipe(assets.restore())
.pipe($.useref())
.pipe(gulp.dest(config.dist));
});
The way restore works has changed between the 2.x and 3.x release of gulp-filter.
It seems you're using the 3.x branch, so in order to use restore you'll have to set the restore option to true when defining the filter:
var jsFilter = $.filter('**/*.js', {restore: true});
Then you'll be able to do
.pipe(jsFilter.restore)
For more information, check out this section of the documentation for the latest version of gulp-filter:
https://github.com/sindresorhus/gulp-filter/tree/v3.0.1#restoring-filtered-files