Effective way to debug a Google Apps Script Web App - debugging

I have had some experience writing container-bound scripts, but am totally new to web apps.
How do I debug (e.g. look at variable values, step through code etc) a web app? In a container bound script it was easy, because I could set breakpoints, use the apps script debugger - how do I go about this in a web page e.g. when I execute a doPost?

In his excellent book "Google Script", James Ferreira advocates setting up your own development environment with three browser windows; one for the code, one for the live view (in Publish, Deploy as web app, you are provided with a "latest code" link that will update the live view to the latest save when it is refreshed), and one for a spreadsheet that logs errors (using try/catch wrapped around bits of code you want to keep an eye on).

In Web Apps, even the most basic debugging of variables through Logger.log() does not work!
A great solution to have at least simple variable logging available is Peter Herrmann's BetterLog for Apps Script. It allows you to log into a spreadsheet (the same as your working spreadsheet or a separate one).
Installation is very simple - just add an external resource (see the Github readme) and a single line of code to override the standard Logger object:
Logger = BetterLog.useSpreadsheet('your-spreadsheet-key-goes-here');
Remember, that the spreedsheet that you give here as a parameter will be used for the logging output and thus must be writable by anybody!
BetterLog will create a new sheet called "Log" in the given spreadsheet and will write each log call into a separate row of that sheet.

So, for me, I debug the front-end using inspector, I haven't found a way to step through code yet, but you can use 'debugger' in your javascript (along with console.log) to stop the code and check variables.
to debug the backend, what I've been doing is to write my functions like
function test_doSomething(){
payload = "{item1: 100, item2: 200}" //<- copy paste from log file
backend_doSomething(payload)
}
function backend_doSomething(payload){
Logger.log(payload)
params = JSON.parse(payload)
...
}
Then after refreshing your project on the backend, you can look at executions, grab the payload from the log file, and paste it into your test_doSomething() function.
From there, you are re-creating the call that you want to debug and you can run that, stepping through the backend code as usual.

Related

Reuse Cucumber steps across features files in Cypress

Is there a way to reuse steps in our features from "other" step files?
I.e. I have a project with login page, and topbar that I want to test after login:
Got LoginPage.feature and LoginPage.js step file, everything works fine, all tests run correctly.
I would like reuse steps “Given user open TestPage login page” and “When user login using valid credentials” from LoginPage.js in TopBarCmp.feature:
But it always ends with error:
Long time ago I used Specflow(Cucumber for .net) and it was normal to ruse steps with same singatures across all features.
What is correct way of handling that kind of situations, where we would like to use some part that was already automated?
Looks like you can put them either on cypress/integration/common or in cypress/support/step_definitions and they will be available to share across features
this article explains it better https://www.linkedin.com/pulse/part-2-hands-on-test-automation-project-cypress-reis-fernandes

How to debug web development in Google Application Script?

I am testing/learning webhook. How to send, receive it. So I thought I would use GAS.
I have this simple script and I wonder why Logger does not work. In Projects/Executions I can see that the script doPost was executed but no logs. Email was sent and the script returned the value.
using old, Legacy Editor (no idea how to get the new one)
in Menu-Resources-Cloud Platform Project is said "This script has an Apps Script-managed Cloud Platform project."
when I open the project in editor I get this message "This project is running on our new Apps Script runtime powered by Chrome V8."
exception logging set to "exceptionLogging": "STACKDRIVER" is set to default
I tried console.log(e); but it did not work for me.
function doPost(e) {
Logger.log("I was called")
if(typeof e !== 'undefined'){
Logger.log(e.parameter);
Logger.log("I was called 2")
MailApp.sendEmail({
to: "radek#gmail.com",
subject: "Call Sucessful",
htmlBody: "I am your <br>" +
JSON.stringify(e)+ "<br><br>" +
JSON.stringify(e.parameters)
});
}
return ContentService.createTextOutput(JSON.stringify(e))
}
Question1: Can I make Logger work?
Question2: I would like to see accepted data in Debugger, is that possible?
Question3: Is there any way the GAS pushes the data it received to my web browser. Of course the browser is NOT sending the data.
Question4: No related to the topic but ... Would you know what I need to do in order to be able to use new Editor?
If you want your own custom log information to go to Stackdriver, then you need to create a Google Cloud Platform project, and associate that GCP project with your Apps Script project.
First create a new GCP Project:
Go to your GCP dashboard:
https://console.cloud.google.com/home/dashboard?authuser=0
In the blue bar at the top, there is a drop down menu for project names. Click that, and a dialog should appear with a button to create a new project.
Create a new Google Cloud Platform project.
Copy the Project Number.
Go back to the Apps Script editor.
From the legacy Apps Script editor, click the "Resources" menu.
Click Cloud Platform project.
Paste in the Project Number and click the button.
Now, any console.log() statements you have will send the logs to Stackdriver.
And Stackdriver can be viewed in your browser.
Note: Some people set up their own logging system to log information from server side Apps Script code to a Google Sheet. There are some open source repos that are available.
The new code editor does have a "built-in" way to log server side information to a log pane code editor window. But, of course this assumes that you are running code from the code editor. This new feature avoids the need for changing browser tabs to see your logging output. I don't know of any way to log server side info to your browser console. You could save log info into an object, and then send it back to the client after the server code completed, and then log everything in the console.
The way that it might be possible to get logging information depends on how the code was originally triggered.
From code editor
From a user using your app
From a Http Request to your Web App
Logging in Apps Script works differently depending upon:
run time version being used - V8 or DEPRECATED_ES5 - Set in appsscript.json file or through the "Run" menu in the Legacy editor, Set in "Settings" in new IDE - New Apps Script projects default to V8 so chances are your project is using V8.
Is your Apps Script project associated with a Google Cloud Platform
(GCP) default or standard project
Is exception logging set to "exceptionLogging": "STACKDRIVER" - Set in appsscript.json file - Default is always to include it - Probably already correct unless you deleted it.
Using either Logger.log or console.log
Using console.log in the server ".gs" file or client side ".html"
file. console.log can be used in both server and client side code
but the log print out goes to different places. You can't see logs
in the browser dev tools from a console.log statement in your
server code. If you use console.log in server side .gs files, and the Apps Script project is not associated with a standard GCP project, then the log only gets sent to your "Executions." I believe that the only way that you can get your logs sent to Stackdriver is by using a standard GCP project. The problem with that, is that you only have so many GCP projects that you can use without requesting an increase in your quota.
Plus there may be issues (bugs) depending upon how you have logging set up and other factors.
For example:
https://issuetracker.google.com/issues/134374008
As lots of people specified, you can use console.log for this.
However, I also work with webhooks from time to time. And I find it much more comfortable to debug directly into google spreadsheets, using code like this
function doPost(e) {
log('# doPost', JSON.stringify(e));
try {
// Some webhook-processing logic here
if(e.parameter.action == 'test-error') {
item.something = nothing;
}
if(e.parameter.action == 'test-log') {
log('# custom log', 'Some data');
}
} catch(error) {
log('# error', JSON.stringify([error, error.stack]));
}
}
function log(event, message){
SpreadsheetApp.getActive().getSheetByName('Log').appendRow([new Date(), event, message])
}
Example spreadsheet:
https://docs.google.com/spreadsheets/d/144i9pxDIB_C8ZRZ-6vd9DiPIw8Rt85hTtVoqk7dtHQg/edit?usp=sharing
You can trigger logging by something like this
curl -X POST https://script.google.com/macros/s/AKfycby3EoaQ8DOt8H_Mc4vjH6JZkhsaAwYHk_sa9HE5Be3qVo0Ym0b2/exec?action=test-error
or
curl -X POST https://script.google.com/macros/s/AKfycby3EoaQ8DOt8H_Mc4vjH6JZkhsaAwYHk_sa9HE5Be3qVo0Ym0b2/exec?action=test-log
You can use same log for your custom logging of some intermediate variable during webhook resolution.
The reason I prefer this over standard stackdriver logging is that google sheets are more explicit and easier to manage.
You can use console.log() to see things within "My Executions".

Issues with Swashbuckle

I have a WebAPI service, written in ASP.NET (not Core), for which I am trying to generate documentation, in order to allow other devs to use it. I found Swashbuckle, and installed it. Then, since I also use OData for some of my services, I added Swashbuckle.OData. Then, I modified the CustomProvider setting in SwaggerConfig to use the ODataSwaggerProvider. I also set ResolveConflictingActions(apiDescriptions => apiDescriptions.First()) because I had a few Actions with the same URL path, differing only by query string (I'll need to address that later). So far so good.
Then, I tested it. I started my web app, then added "/swagger/" to then end. I got a message stating that it was loading the resource info. However, after several minutes, I got a browser error debug popup, stating "Error: Not enough storage is available to complete this operation." It asks if I want to debug, and if I do, it takes me to the debugger in IE (the browser I'm using). The only code in the stack is either from jquery-1-8-0-min-js or swagger-ui-min-js (this part confuses me, as there is no "swagger-ui-min-js" file in my project; I'm assuming it's embedded in the dll). There is no part of the stack trace that floats back up to my code, and all the code there is minified, so it's very difficult to debug.
However, I do know that it is at least partially working, as three of the controllers do show up in the resulting page after you close the error popup. You can navigate through them, and all the GETs, POSTs, PUTs, and DELETEs seem to be there, and you can test them.
Is it the case that whenever you navigate to the "/swagger/" url, Swagger hits all the URLs in the service, in order to generate the documentation? I'm wondering if maybe it is hitting an action that is taking a particularly long time to run, or possibly its generated documentation is taking too much disk space (I have plenty of space on my disk, but maybe it is referring to RAM?).
Anyway, even if that were not an issue, how can I get it to generate something, some kind of document file, that I can send off to someone? I see no new files added to my folders, so it would seem that it re-does the whole process every time you navigate to the swagger URL.
When I tried the Chrome browser, I no longer had the issue (I was using IE11 before). Not sure what the problem was, but this was the workaround.

Play! Framework 2.1.3 pdf problems

so I am working on a school project in which we have designed a web application that takes in much user info and creates a pdf then should display that pdf to the user so they can print it off or save it. We are using Play! Framework 2.1.3 as our framework and server and Java for the server side. I create the pdf with Apache's PDFbox library. Every thing works as it should in development mode ie launching it on a localhost with plays run command. the issue is when we put it up to the server and launch with plays start command I it seems to take a snapshot of the directory (or at least the assets/public folder) which is where I am housing the output.pdf file/s (i have attempted to move the file elsewhere but that still seems to result in a 404 error). Initially I believed this to be something with liunx machine we were deploying to which was creating a caching problem and have tried many of the tricks to defeat the browser from caching the pdf
like using javascript to append on a time stamp to the filename,
using this cache-control directive in the play! documentation,
"assets.cache./public/stylesheets/output.pdf"="max-age=0",
then I tried to just save the pdf as a different filename each time and pass back the name of that file and call it directly through the file structure in the HTML
which also works fine with the run command but not the start.
finally I came to the conclusion that when the start command is issued it balls up the files so only the files that are there when the start command is issued can be seen.
I read the documentation here
http://www.playframework.com/documentation/2.1.x/Production
which then I noticed this part
When you run the start command, Play forks a new JVM and runs the
default Netty HTTP server. The standard output stream is redirected to
the Play console, so you can monitor its status.
so it looks like the fact that it forks a new JVM is what is causing my pain.
so my question really is can this be gotten around in some way that a web app can create and display a pdf form? (if I cannot get this to work my only solution
that I can see is that I will have to simulate the form with HTML and fill it out from there) --which I really think is a bad way to do this.
this seems like something that should have a solution but I cannot seem to find or come up with one please help.
i have looked here:
http://www.playframework.com/documentation/2.1.x/JavaStream
the answer may be in there but Im not getting it to work I am pretty novice with this Play! Framework still
You are trying to deliver the generated PDF file to the user by placing it in the assets directory, and putting a link to it in the HTML. This works in development mode because Play finds the assets in the directory. It won't work in production because the project is wrapped up into a jar file when you do play dist, and the contents of the jar file can't be modified by the Play application. (In dev mode, Play has a classpath entry for the directory. In production, the classpath points to the jar file).
You are on the right lines with JavaStream. The way forward is:
Generate the PDF somewhere in your local filesystem (I recommend the temp directory).
Write a new Action in your Application object that opens the file you generated, and serves it instead of a web page.
Check out the Play docs for serving files. This approach also has the advantage that you can specify the filename that the user sees. There is an overloaded function Controller.ok(File file, String filename) for doing this. (When you generate the file, you should give it a unique name, otherwise each request will overwrite the file from a previous request. But you don't want the user to see the unique name).

4GL and Magento SOAP API. Need a simple example

My company runs a 4GL application internally. It's very old and no one really knows how to improve/develop for it since the developers are long gone.
I need to make a simple SOAP call to my Magento web store. There are tons of examples online in a multitude of languages, but I can't find a single 4GL (OpenEdege ABL) example.
I'm trying to set SKU's to Out of stock status.
Does anyone have a simple example that I can look at, or at least a starting point since there seems to be so little information on 4GL on the web.
Example of the call I need in PHP:
<?php
$proxy = new SoapClient('http://www.domain.com/api/soap/?wsdl');
$sessionId = $proxy->login('admin', 'password');
$proxy->call($sessionId, 'product_stock.update', array('sku123', array('qty'=>50, 'is_in_stock'=>1)));
For version 10.2B there's built in support for consuming web services in Progress ABL.
This is a basic tutorial of how to create a client for a SOAP-based web service in ABL. It's not best practices or in any way complete. Just a quick guide to get started.
1. Analyse the WSDL
There's a built in tool available via command line that lets you analyse a WSDL and create documentation about available services, datatypes, syntax etc. Invoke it on your wsdl like this:
proenv> bprowsdldoc yourwsdl-file c:\temp\docs
The wsdl can be local or remote. If its remote you specify the URL, if it's local you can specify just the local complete path. Documentation in html format will end up in c:\temp\docs. Open up index.html in that folder.
2. Create a basic client
In the index.html document there's a number of headings. Click the link under "Port types". In the Port Type document you will find some useful data.
Copy-and-paste the example in "Connection Details" into your Progress Editor. It should look something like this (names of services and procedures will be different - they are defined in the wsdl):
DEFINE VARIABLE hWebService AS HANDLE NO-UNDO.
DEFINE VARIABLE hYYY AS HANDLE NO-UNDO.
CREATE SERVER hWebService.
hWebService:CONNECT("-WSDL 'file_or_url_to_wsdl.wsdl'").
RUN XXX SET hYYY ON hWebService.
If you run this code your client is connected to the web service but it's still not doing anything.
Further down the same document there's a heading called "Operation (internal procedure) details". This is where the actual web service is invoked. It will look something like the code below. It actually show two ways of making the same call, one functional call and one procedural so choose whatever you prefer and insert it into your editor (I'm usually using the procedural for no real reason other than old habits):
DEFINE VARIABLE strXMLRequest AS CHARACTER NO-UNDO.
DEFINE VARIABLE ProcessXMLResult AS CHARACTER NO-UNDO.
FUNCTION ProcessXML RETURNS CHARACTER
(INPUT strXMLRequest AS CHARACTER)
IN hYYY.
/* Function invocation of ProcessXML operation. */
ProcessXMLResult = ProcessXML(strXMLRequest).
/* Procedure invocation of ProcessXML operation. */
RUN ProcessXML IN hYYY (INPUT strXMLRequest, OUTPUT ProcessXMLResult).
Now all you need to end your program is disconnecting and cleaning up. So insert:
hWebService:DISCONNECT().
DELETE OBJECT hWebService.
If you've followed all steps you should have a skeleton for invoking a web service. The only problem is that you need to handle the in- and out-data.
3. Handle the answer and the request
Depending on how the web service is built this can be easy (if you only input and output simple data like strings and numbers) or quite complicated (if you input and output entire xml-documents). The documentation you created in step one lists all datatypes (in the index.html document) but it doesn't offer any support in how you create any needed xml documents. There's specific Progress documentation available on how to work with xml...
The better approach is to take a look at the official documentation. There you will find everything above and more - how to handle errors etc.
Here is an overview of all 10.2B documentation and here is the PDF named Web Services.
Here is a link to a complete (but actually not so good) example in the Progress KnowledgeBase where a client and corresponding request/response xml is created and handled.
Look at these chapters:
6 - Creating an ABL Client from WSDL
7 - Connecting to Web Services from ABL
8 - Invoking Web Service Operations from ABL
That will basically take you through the entire process from start to beginning.

Resources