How to Debug Amplify JavaScript functions in VS Code - visual-studio-code

How can I debug Amplify JavaScript functions on VS Code on Windows 10?
This issue came up on github under How to debug amplify function using visual studio code during invocation?, but it's closed and quite old. For example, amplify invoke function is deprecated in favor of amplify mock function.
I've tried this launch.config:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Create Reort",
"type": "node",
"request": "launch",
"program": "${env:APPDATA}/npm/node_modules/#aws-amplify/cli/bin/amplify",
"args": [
"mock",
"function",
"sayhello",
"--event",
"src/event.json",
"--timeout",
"0"
],
"console": "integratedTerminal"
}
]
}
Which will log the output, but doesn't hit any breakpoints inside the function being executed:
Setup steps:
Install amplify cli
npm install -g #aws-amplify/cli
Initialize amplify. Choose JavaScript with any framework.
amplify init
# Choose your default editor: Visual Studio Code
# Choose the type of app that you're building: javascript
# What javascript framework are you using: none
Add function
amplify add function SayHello
# Choose the runtime that you want to use: NodeJS
# Choose the function template that you want to use: Hello World

Here's a kinda hacky workaround.
As far as I can tell there isn't that much magic to lambdas for a single execution (The special sauce in the runtime environment, event handling, and auto scalability). The Amplify CLI passes in the event object from event.json and calls the function defined as the handler. You can do that in vanilla node js as well.
Create a file like debug.js - you can put it anywhere you want, but mine is in the .vscode directory
const { handler } = require("../amplify/backend/function/sayHello/src")
const event = require("../amplify/backend/function/sayHello/src/event.json")
(async function(){
// invoke
const response = await handler(event)
console.log(response)
})()
Then you can use a normal node js debug launch configuration like this:
{
"name": "Debug Function",
"program": "${workspaceFolder}/.vscode/debug.js",
"request": "launch",
"skipFiles": ["<node_internals>/**"],
"type": "pwa-node"
}
Something a little friendlier / out-of-the-box would be nice, but this at least allows step through debugging without too much extra work.

This used to work in an older version of VS Code. I opened https://github.com/aws-amplify/amplify-cli/issues/6894 to hopefully address the issue.
Meanwhile, here's another hacky workaround suggested here that uses Node's injector. Add this code to the top of your handler method (making sure you remove it before committing):
require('inspector').open(9229, '127.0.0.1', true);
debugger;
Be sure to set a long enough timeout in the amplify mock command in launch.json. To step through the code, you can use Chrome's Node debugger by navigating to about:inspect and clicking on "Open dedicated DevTools for Node".

Related

Can I run and debug deno project in VSCode?

I'm new to both typescript and deno, also vscode.
Firstly, I tried it with vscode and failed, and then tried with IntelliJ.
I can run and debug simple .ts file in Intellij with deno plugin.
But I want to know how to do this in vscode(also installed deno plugin, https://marketplace.visualstudio.com/items?itemName=denoland.vscode-deno).
My settings are...
.vscode/settings.json
{
"deno.enable": true,
"deno.lint": true,
"deno.unstable": true
}
.vscode/launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"request": "launch",
"name": "Launch Program",
"type": "pwa-node",
"program": "${workspaceFolder}/main.ts",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "deno",
"runtimeArgs": [
"run",
"--unstable",
"--inspect",
"--allow-all"
],
"attachSimplePort": 9229
}
]
}
Example code
console.log("Hello, World!");
When I run this using by Run without Debugging
just shows like below image but expected to output Hello, World!.
and also seems debugging is not working.
Please help.
Debugging with --inspect does not work for relatively short programs, because it does not wait for the debugger to connect. So when running short programs the execution finishes before VS Code connects to the inspector. On larger programs this won't be an issue.
For debugging Deno programs that are only a couple of lines long, two options are given in this thread:
Use --inspect-brk instead of --inspect, this should allow enough time for the debugger to connect and hit breakpoints
Add some time delay to the code when debugging, for example:
const _sleep = async () => {
await new Promise(resolve => setTimeout(resolve, 2000));
}
await _sleep();
console.log("Hello World!"); <-- Here, you could add a breakpoint
To Run without Debugging, you can also either add --inspect-brk, but you will have to press F5 or click 'Continue' once the session has started. Or, you can use --inspect and add the sleep function

Why does R Debugger fail to verify all breakpoints (Vscode)

I am using R Debugger in Vscode to develop an RShiny app while using SSH to connect to the remote.
My launch.json file looks like this:
{
"version": "0.2.0",
"configurations": [
{
"type": "R-Debugger",
"name": "Launch R-Workspace",
"request": "launch",
"debugMode": "workspace",
"workingDirectory": "", // If I put my actual path here, it changes nothing
"allowGlobalDebugging":true
}
]
}
For the purposes of this topic, I have these folders/files:
src/www/uis
src/server.R
I set breakpoints in files within src/www/uis as well as within src/server.R.
When I use Launch R-Workspace, the breakpoints at src/www/uis will trigger but within src/server.r they turn into "unverified breakpoints".
What I've tried:
Reading through similar questions and findings answers that did not seem relevant. Reading through the documentation where I did not see anything useful to me.
Any insight?
Thanks

How to fix vscode GnuCOBOL setup "configuration error: default.conf: No such file or directory"

we are using cobol now, but this config error keeps on appearing and I do not know how to fix this thing. Any help would really mean alot. (Just a beginner and trying to learn vscode)
Late, but perhaps worth it. Currently there is a cobenv.bat or .sh (if you are on linux). The whole path to the file may differ for me is this:
C:\msys64\mingw64\bin\cobenv.cmd
You'll notice that if you execute the file and run the compiler everything works fine, but once you close that bash the error shows up again.
That's because the scope of those variables was just that session. You may execute it every time you run the compiler or you can make those variables to persist on your system. In my case I did the later, modifying cobenv.cmd
But not those lines with the variable PATH.
So this lines, i.e., whenever we encounter this same three variables. For instance, after a certain if in that file we encounter:
setx "COB_LIBRARY_PATH" "%MINGW_ROOT_PATH%lib\gnucobol%COB_LIBRARY_PATH%"
setx "COB_COPY_DIR" "%MINGW_ROOT_PATH%share\gnucobol\copy"
setx "COB_CONFIG_DIR" "%MINGW_ROOT_PATH%share\gnucobol\config"
Default value: set.
New value: setx.
Delete the = to comply with the correct syntax. Check the compiler with different new session.
This message is only presented in vscode's Terminal after you've entered a command there, it is actually not related to vscode.
The "common" way with vscode would be to create a vscode task for the compilation and configure a problem matcher, too, so vscode is able to parse the messages. For details see vscode docs "Integrate with External Tools via Tasks".
As the message is coming from the GnuCOBOL compiler it may be reasonable to check in its discussion board, which also includes a note how to use your setup of vscode with GnuCOBOL MinGW package, this would be your starting point, assuming D:\COBOL is the place where you have your sources (and this is the alos the workspaceFolder as in your screenshot), D:\COBOL\copy where your copybook reside and D:\GnuCOBOL where the MinGW package is:
{
"version": "2.0.0",
"tasks": [
{
"label": "GnuCOBOL - cobc (compile single file)",
"type": "shell",
"command": "cobc",
"args": [
"-I${workspaceFolder}\\copy",
"${file}"
],
"problemMatcher": "$gnucobol3-cobc",
"options": {
"env": {
"COB_CFLAGS": "-I\"D:\\GnuCOBOL\\include\"",
"COB_CONFIG_DIR": "D:\\GnuCOBOL\\config",
"COB_COPY_DIR": "D:\\GnuCOBOL\\copy",
"COB_LDFLAGS": "-L\"D:\\GnuCOBOL\\lib\"",
"COB_LIBRARY_PATH": "D:\\GnuCOBOL\\extras",
"PATH": "D:\\GnuCOBOL\\bin:${env:PATH}"
}
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
Instead of directly calling cobc you could also call cobc.bat or similar, then create it with all your default options set there (or, if you use the official mingw packages, just call the set_env.cmd) then call the compiler.
Concerning "how to fix that message" - make sure you have the "config" directory of GnuCOBOL and have COB_CONFIG_DIR set to it either in the task definition or outside of vscode (for example by starting vscode from the "Developer prompt for GnuCOBOL MinGW" (which is the set_env.cmd distributed with it).

How to configure VS code for pytest with environment variable

I am trying to debug pytest. I would like to inject an environment variable. Here is how I have set launch.json
{
"type": "python",
"request": "test",
"name": "pytest",
"console": "integratedTerminal",
"env": {
"ENV_VAR":"RandomStuff"
}
},
But it seems when I start debugging. I do not see the env variable injected, as a result my test which expects that env variable fails.
Also I notice error
Could not load unit test config from launch.json
pytest-env
Install
Per https://stackoverflow.com/a/39162893/13697228:
conda install -c conda-forge pytest-env
Or:
pip install pytest-env
pytest.ini
Create pytest.ini file in project directory:
[pytest]
env =
ENV_VAR=RandomStuff
Python
In your code, load environment variables as you normally would:
import os
env_var = os.environ["ENV_VAR"]
pytest / VS Code
Either run:
pytest
(Notice how it says configfile: pytest.ini)
C:\Users\sterg\Documents\GitHub\sparks-baird\mp-time-split> pytest
==================================== test session starts ===================================== platform win32 -- Python 3.9.12, pytest-7.1.1, pluggy-1.0.0 rootdir:
C:\Users\sterg\Documents\GitHub\sparks-baird\mp-time-split,
configfile: pytest.ini plugins: anyio-3.6.1, cov-3.0.0, env-0.6.2
collecting ...
Or:
This only seems to work with breakpoints that have manually been set, I'm guessing some other change is needed to pause on errors.
Python for VS Code Extension
Apparently the Python for VS Code extension recognizes a .env file automatically. E.g.
.env file:
ENV_VAR=RandomStuff
Haven't verified, but I'd assume this has the same behavior as using pytest-env with a pytest.ini file.
When all else fails
When I don't feel like dealing with the strange hackery necessary to get VS Code, Anaconda environments, and pytest playing nicely together (and/or forget how I fixed it before), I call my tests manually and run it like a normal script (see below). This may not work with more advanced pytest trickery using fixtures for example. At the end of your Python script, you can add something like:
if __name__ == "__main__":
my_first_test()
my_second_test()
and run it in debug mode (F5) as normal.
Could not really figure out how to fix "unit" test debugging with Vscode. But with Pytest one can call tests like python -m pytest <test file>(https://docs.pytest.org/en/stable/usage.html#cmdline)
That means Vscode can be configured like a module
"configurations": [
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "pytest",
"args": ["--headful","--capture=no", "--html=report.html"],
}
This is good enough to do debugging of python tests. Also you can then insert environment variables
"env": {
"ENV_VAR":"RandomStuff"
}
This works in v 1.72.2
Create in the workspace folder:
.vscode/launch.json
Similar to the OP, but using "module"
{
"version": "0.2.0",
"configurations": [
{
"name": "Pytest",
"type": "python",
"request": "launch",
"module": "pytest",
"console": "integratedTerminal",
"env": {
"testy": "someval"
}
}
]
}
Try some breakpoints (either in test files or app code)
Start the debugger
Watch the os.environ['testy'] value (must import os where the breakpoint is of course)

Node debugging, make `${file}` dynamic?

With the right debug config file I can make VSCode run the currently focussed file through Mocha. However, I find it frustrating that if I am working on the actual code, rather than the spec file and I press F5, it tries to run the actual code as a spec file through Mocha.
So, my question is; given a file structure like this:
Folder
File.js
File.spec.js
And a debug config (.vscode/launch.json) like this:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Unit Tests: Current File",
"program": "${workspaceRoot}/node_modules/.bin/_mocha",
"cwd": "${workspaceRoot}",
"args": [
"-u", "tdd",
"--timeout=999999",
"--colors",
"--opts", "${workspaceRoot}/mocha.opts",
"${file}" // I want to make this dynamic
],
}
]
}
Is it possible to get VSCode to debug the spec file whether the spec file (File.spec.js) or it's subject (File.js) are selected?
You can introduce a new dynamic variable by writing a simple extension that just defines one command, e.g. a smartFile command.
Then you can refer to that command in your launch config as ${command:smartFile}.
For the implementation of the command you can use everything available in VS Code extension API. So you can not only calculate a path based on your folder structure, but you can even pop-up UI. E.g. you could use QuickPick to select a test case from the list of all tests.