Can someone point me toward a sample launch.json file for JUnit 4 so I can run tests from Visual Studio Code? I am unable to find an example of this online and all attempts to create one have failed.
I am able to run tests manually from the command line. (FWIW, I'm using CentOS.) Here's what I do to run them:
cd /opt/ABBYY/FREngine12/Samples/Java/Hello_VSC/src/test/java
java -cp .:/opt/junit/junit-4.12.jar:/opt/junit/hamcrest-core-1.3.jar org.junit.runner.JUnitCore Hello.AppTest
My Java project is set up to support Maven (I'm not really using Maven -- I've only set it up with Maven because Java debugging in Visual Studio Code will not work without it). So in the .classpath file I've added the following entries, which should add the .jar files from my command line call to the code path:
<classpathentry kind="lib" path="/opt/junit/junit-4.12.jar" />
<classpathentry kind="lib" path="/opt/junit/hamcrest-core-1.3.jar" />
When I try to set up the launch.json file, I'm attempting to do something like this:
{
"type": "java",
"name": "Test-<Hello_VSC>",
"request": "launch",
"cwd": "/opt/ABBYY/FREngine12/Samples/Java/Hello_VSC/src/test/java/",
"console": "internalConsole",
"stopOnEntry": false,
"mainClass": "Hello.AppTest",
"projectName": "Hello_VSC",
"args": "org.junit.runner.JUnitCore Hello.AppTest",
},
However, I get this error message:
Error: Main method not found in class Hello.AppTest, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Even if I change cwd to a completely bogus directory, I get the same error message. I don't know if my type parameter is wrong, my cwd parameter is wrong, or if it's something else.
Any suggestions?
Never mind -- I figured it out. I guess I had everything set up correctly with my project, but didn't realize that the proper way to run tests with the Java extensions for Visual Studio Code was to simply click on the Explorer (file) icon, then expand the "Test Explorer" option, explore down to whatever test(s) you want to run, right-click, and then choose your testing options. There is no need to use the launch.json file to do this.
If you search for tasks.json (instead of launch.json), you will get this example
/*
Example for quick Java compilation and unit tests in VS Code.
Works well with simple BlueJ projects.
Hit Ctrl+Shift+B to compile currently open file with javac.
Hit Ctrl+Shift+T to test currently open test class.
See red wiggles for compilation errors / failed assertions or click exclamation mark in the status bar.
Uses a few workarounds for individual commands per task and filename without extension.
This is written for Windows but it should be easy to adopt for Linux and Mac.
*/
{
"version": "0.1.0",
"isShellCommand": true,
"suppressTaskName": true,
"showOutput": "silent",
"windows": {
"command": "powershell",
"args": ["-Command"],
"tasks": [
{
// tests the currently open test class. java has to be in %PATH% and the jUnit-jar in %CLASSPATH%.
"taskName": "junit",
"args": ["$env:CLASSPATH += ';${fileDirname}'; $class = [System.IO.Path]::GetFileNameWithoutExtension('${fileBasename}'); java org.junit.runner.JUnitCore $class | Select-String -NotMatch -Pattern 'at (?!.+${fileBasename})'"],
"isTestCommand": true,
"problemMatcher": {
"owner": "java",
"fileLocation": ["relative", "${fileDirname}"],
"pattern": [
{
"regexp": "^(.*)$",
"message": 1
},
{
"regexp": "^\\s*at .+\\((.+):([0-9]+)\\)$",
"file": 1,
"line": 2
}
]
}
},
]
}
}
But it is in "0.1.0", so you will have to convert it to 2.0.0 first.
Related
I am a complete beginner with C and to VSCode. I am trying to configure the task and launch jsons but have no idea where to begin. I have tried googling the answers but I keep getting the same errors. I want to be able to step through the code line by line so I can see what it is doing.
I haven't changed the tasks.json from the original that VSCode sets. The launch.json I have changed by putting in the debugger path and the path of the executable. I have included the task.json, launch.json and the error that keeps popping up. Any help is appreciated.
tasks.json
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc build active file",
"command": "/usr/bin/gcc",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
launch.json
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/scheduler.c",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
]
}
]
}
I've recently had the same issues. Here is the procedure that I follow, that seem to work:
Download and install msys2 (1)
Download MSYS2 from https://www.msys2.org/
Install folder is typically C:\msys64
Go to C:\msys64 and open mingw64.ini
Change ‘#MSYS2_PATH_TYPE=inherit’ to ‘MSYS2_PATH_TYPE=inherit’ i.e. enable PATH variable.
Add PATH environment variables (2)
Type “environment” in Windows search field, and select “Edit environment variables …”
Add path to gcc.exe and g++.exe:
— Add: “C:\msys64\mingw64\bin” to PATH variable.
Add path to VS Code to PATH variable as well:
— This is usually the folder:
C:\Users\<username>\AppData\Local\Programs\Microsoft VS Code\
Run “msys2 mingw64” and test access to compilers and debugger (3)
In Windows Search field, type “msys2” and select “msys2 mingw64” and run the following:
To install gcc, the Gnu C compiler: pacman -S mingw-w64-ucrt-x86_64-gcc
To install gdb, the Gnu GDB debugger:
pacman -S --needed base-devel mingw-w64-x86_64-toolchain
To test that you can run compilers and debugger, run:
gcc --version
g++ --version
gdb --version
Start development in VSC (4)
Open “msys mingw64” terminal and run:
cd <common projects folder>
mkdir <projname>
cd <projname>
Above changes current directory to a projects folder. I use C:\Users<username>\src\projects, i.e. this is my but you may want to use something else.
In the folder you can make a subfolder per C coding project you want to run. This is what “mkdir ” does.
You will need a little Unix Bash shell command skills here, here is an ultrashort summary:
cd – change directory to
mkdir – makes a new directory called
in the current folder.
cd .. – change directory one up.
_ cd ~ – changes directory to your home folder, I have C:\Users<username> where is my … username.
pwd – shows current directory.
Now, if you did above you are currently in the specific projects folder (you can verify this with pwd), and you should start VSC from there by typing:
code .
And accept Workspace trust.
Create a C source file (5)
Open folder view, click on + icon, and select ‘new file’, type “hello.c”, go into the file and add the contents:
include
int main() {
printf("Hello World\n");
return 0;
}
Configure VSC for building – tasks.json (6)
Press “ctrl+shift+B” to build target (or menu: -> Terminal -> Run Build Task… or press green play icon)
Select “C/C++: gcc.exe build and debug active file”
Now it tries to build, using an autogenerated tasks.json file, located in project-folder, in subfolder .vscode:
.vscode/tasks.json
An example of a tasks.json file is shown below:
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc.exe build active file",
"command": "C:\apps\msys64\mingw64\bin\gcc.exe",
"args": [
"-fdiagnostics-color=always",
"-Wall",
"-g",
"${file}",
"-o",
"${fileDirname}\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
The important section is:
"command": "C:\msys64\mingw64\bin\gcc.exe",
"args": [
"-fdiagnostics-color=always",
"-Wall",
"-g",
"${workspaceFolder}/*.c", OR TODO "${file}"
"-o",
"${fileDirname}\${fileBasenameNoExtension}.exe"
],
“command” is the Gnu C compiler, gcc.exe and the full path to it.
“args” are arguments for the compiler:
-Wall means warn about everyting.
-g means compiler must prepare for debugging.
“${file}” is current file.
-o is output file which is specified in the next line with .exe extension.
Sometimes we have to build multi-file projects and it will break the default build-functionality in tasks.json in VSC. In some cases this can be solved by changing:
${file},
to
"${workspaceFolder}/*.c",
Configure VSC for Debugging – launch.json (7)
Go to source file hello.c, and set a break point,
Click left to the line numbers to set red circle.
Select play/bug icon
Select “Debug C/C++ File”
Choose “C/C++ gcc build and debug active file” from list of automatically detected compilers.
This will autogenerate a file, launch.json in the projects folder, in subfolder .vscode:
.vscode/launch.json
An example of a launch.json file is shown below:
{
"configurations": [
{
"name": "C/C++: gcc.exe build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
]
}
],
"preLaunchTask": "C/C++: gcc.exe build active file"
}
The most important parts are:
"program": "${fileDirname}\${fileBasenameNoExtension}.exe",
and
"miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe",
The “program” is the program generated when building the project. I.e. the output from running the task as specified in Tasks.json.
The miDebuggerPath is the path to gdb, the GNU gdb debugger.
If these does not match with your Tasks.json settings and your installation chances are slim to make it work.
Test it by pressing the Play/Bug icon button and notice if there are errors. If not you should be able to step through the code and watch variables etc.
Configure VSC for intellisense (8)
Install extension: “C/C++ extension for VS Code” by Microsoft.
Now this extension will assist when you type code. By example you can type for to get the basics of a for-loop. Similar for if, while etc. Cool!
Save work when creating new projects (9)
Instead of having to create the tasks.json and launch.json files for each project, I copy them to a templates folder, say:
C:\Users\username\src\templates\.vscode\
Copy the newly created tasks.json and launch.json files to the .vscode subfolder.
Now, say you want to create a new project, e.g. hello2, and you create a folder for it:
C:\Users\<username>\src\projects\hello2\
Go to the templates folder by
cd C:\Users<username>\src\templates
and copy the .json files to the new project by:
cp -Rp .vscode/ ../hello2/
And now the new project has the .json files.
Optional (10)
Later you may want to update msys2. To do this, open “msys2 mingw64” and type
pacman -Suy
Done (11)
Finally done … Not the easiest thing to get going, but I still think it is worth it.
I want to set up VScode (OS: Windows 10) to create and then compile programs written in Fortran 90/95. I can do this by typing in the terminal : gfortran -o Example_exe Example.f90 and then ./Example_exe. I don't want to have to write these lines every time, so I tried to set up my tasks.json file to automate a build routine using gfortran as compiler.
I found this tutorial : https://titanwolf.org/Network/Articles/Article?AID=360e0bde-0507-4de4-960c-2eae8fa8c782#gsc.tab=0 but the tasks.json file given is unclear.
Can I have a tasks.json file setup to automate my build routine please ?
I have installed the following extensions : Modern Fortran, Fortran IntelliSense, Code Runner, Fortran Breakpoint Support
Yes you can. Assuming that you want to execute in debug mode, you should create a tasks.json and a launcher.json and place them in .vscode/ at the root of your workspace.
Assuming the following file structure and a debugging mode with GDB for the execution:
root/
.vscode/
code/
Example_exe
This is what your tasks.json should look like:
{
"version": "2.0.0",
"tasks": [
{
"label": "compile",
"type": "shell",
"command": "gfortran -o Example_exe Example.f90 -g",
"options": {
"cwd": "code/"
}
}
]
}
And then, the launch.json, which will identify tasks.json as a "preLaunchTask".
{
"version": "0.2.0",
"configurations":[
{
"name": "Run my example",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}\\code\\example_exe.exe",
"args": ["],
"stopAtEntry": false,
"cwd": "${workspaceFolder}\\code",
"miDebuggerPath": "gdb.exe",
"preLaunchTask": "compile",
}
]
}
Launch the debugger by pressing F5 (or in the Run menu).
If you don't want to run in debug mode, have a look at this issue.
Sources:
How to build and run C++ code in Visual Studio Code?
awesome tutorial (for ubuntu, working for me with VSCode-gfortran-Win10)
https://www.youtube.com/watch?v=Rj-kYb9nZ3g&ab_channel=LukasLamm.
i am new to Visual studio Code. I followed this tutorial to set up a Bazel build configuration in Visual studio code (I use Windows 10).
I created a simple task.json
{
"version": "2.0.0",
"tasks": [
{
"label": "Build Example (Debug)",
"type": "shell",
"command": "bazel build //main:hello-world -c dbg",
"windows": {
"command": "bazel build //main:hello-world --experimental_enable_runfiles -c dbg"
},
"osx": {
"command": "bazel build //main:hello-world -c dbg --spawn_strategy=standalone",
},
"group": {
"kind": "build",
"isDefault": true
},
}
]
}
and launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Example",
"type": "cppvsdbg",
"request": "launch",
"args": [],
"stopAtEntry": false,
"preLaunchTask": "Build Example (Debug)",
"cwd": "${workspaceFolder}/bazel-out/x64_windows-dbg/bin/example.exe.runfiles/__main__/",
"program": "${workspaceFolder}/bazel-out/x64_windows-dbg/bin/main/hello-world.exe",
"externalConsole": false,
"windows": {
"type": "cppdbg",
"type": "cppvsdbg",
"cwd": "${workspaceFolder}/bazel-out/x64_windows-dbg/bin",
"program": "${workspaceFolder}/bazel-out/x64_windows-dbg/bin/main/hello-world.exe",
},
},
}
]
}
In this way with run-> start debugging, I am able to debug and stop to breakpoins within the .cpp code of my project.
However, I read here, that is also possible to use the Starlark debugger to debug the .bzl files and Starlark rules.
According to the instructions in the same page I should be able to do this "by right-clicking a build target in the Bazel Build Targets view and selecting "Build Target with Starlark Debugger"". Unfortunately i can't see this option in my Bazel Build Targets view windows:
The Bazel Build Targets view is empty. and if i right click i can't see the "Build Target with Starlark Debugger" option. According to this link i should be able to see my targets listed below Bazel Build Targets view. I guess i am missing something in the configuration of the project or maybe some starlack extension?
Thanks for any help.
Bazel build targets does not work for me on windows either. When I run it, the extension outputs some error about bazel query. I haven't been on windows recently enough to remember the exact message, but I believe it is something along the lines of what is documented in this open issue.
Looks like there is a pull request open to solve it but no one has reviewed it yet. Best bet might be to weigh in over on either one of those after checking your extension output error log to see if it matches what is documented in there. Alternatively, you can check out the Clion with Bazel plugin, I have not tried that on windows yet though.
I'm unable to integrate my project's unit tests into VSCode. Test discovery fails because source files are not recognized by pytest.
(Just for clarification, this is a question about VSCode, not about pytest. I'm here because VSCode links its question section to SOF. Tests work fine if I run them manually.)
Tooling: pyenv, pipenv, pytest.
Project layout:
/src -> source code
/tests/unit -> test code
.vscode/settings.json:
{
"python.envFile": "${workspaceFolder}/.env",
"python.testing.pytestEnabled": true,
"python.testing.pytestArgs": [
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.nosetestsEnabled": false
[...]
}
.env:
PYTHONPATH=./src
(Note: I don't think .env matters here, as per this comment, under Use of the PYTHONPATH variable)
Test discovery fails with:
tests/unit/test_revoke_default_sg.py:7: in <module>
from revokedefaultsg.app import RevokeDefaultSg, UnknownEventException
E ModuleNotFoundError: No module named 'revokedefaultsg'
=========================== short test summary info ============================
ERROR tests/unit/test_revoke_default_sg.py
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 0.08s ===============================
This is caused by ./src not being part of the python path, so tests cannot import source code.
I can fix this on CLI/makefile level by adding to PYTHONPATH:
PYTHONPATH=./src pytest
This works as expected.
What's the correct setup for VSCode?
Am I supposed to create a launch configuration for testing? I've started to look into this, but couldn't get it to work nicely with pipenv.
(OP here)
I think the key to integrate into VSCode creating a specific launch configuration for pytest (before, I only had the default launch configuration that's been created with the Python extension).
I now have two configurations (.vscode/launch.json):
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Run Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"env": {
"PYTHONPATH": "./src"
}
},
{
"name": "Python: pytest",
"type": "python",
"request": "launch",
"module": "pytest",
"cwd": "${workspaceRoot}",
"env": {
"PYTHONPATH": "./src"
},
"envFile": "${workspaceRoot}/.env",
"console": "integratedTerminal",
}
]
}
(project on GitHub)
Running this configuration after launching VSCode discovers tests correctly, without raising errors. However, I have not tried it out in different projects yet.
Also, maybe I didn't find the right section of the VSCode documentation, but this feels heavily under-documented. I ended up searching GitHub for gists with launch configs and copied together whatever seemed vaguely helpful...
I would like to know if there is a way to define a default Build Task for VSCode depending on file extension.
When working in some folder of Python code, I define the following Build Task:
{
"version": "0.1.0",
"command": "python",
"isShellCommand": true,
"showOutput": "always",
"args": ["${file}"]
}
Then if next time I go to another Python folder, I have to redefine it again.
Is it possible to configure VSCode in such a way that if it detects the current file as a Python script, then it will automatically define the above Build Task?
Thank you in advance for your help!
Update for latest vscode
The following will create a default "build" script, so you can use the keyboard shortcut to build your project. (Below for a javascript project, but shows general outline for other languages/projects.)
(1) Assuming you have a script named "build.js" at the root of your project.
(2) Create a file named "tasks.json" in root of project (workspace) with the following contents:
// tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "mybuildscript", // use same name as in package.json
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
(3) In your package.json, add "scripts" as:
// package.json
{
"name": "my",
"version": "1.0.0",
"description": "",
"scripts": {
"mybuildscript": "node ./build.js"
},
"dependencies": {
"myfs": "^1.0.22"
}
}
I created a rudimentary vscode extension that does all this for you:
https://marketplace.visualstudio.com/items?itemName=gieson.make-build-task
The extension isn't perfect (doesn't cover all the possible ways a project/workspace can be configured), but it's a good starting point.
Here's the repo:
https://github.com/bobtherobot/make-build-task
This is possible, but it requires writing an extension (unless somebody has already written one with a tasks provider for Python). Since 1.14.0, there's a new API which allows extensions to dynamically provide tasks. Check out the Task Provider Example.
Alternatiely, the Code Runner extension probably does the trick in this case as well. It doesn't use the Tasks system though.