{"meta":{"title":"Testing custom queries","intro":"Verify your custom CodeQL queries and catch breaking changes before they affect your code scanning results following new releases of the CodeQL CLI.","product":"Security and code quality","breadcrumbs":[{"href":"/en/code-security","title":"Security and code quality"},{"href":"/en/code-security/how-tos","title":"How-tos"},{"href":"/en/code-security/how-tos/find-and-fix-code-vulnerabilities","title":"Find and fix code vulnerabilities"},{"href":"/en/code-security/how-tos/find-and-fix-code-vulnerabilities/scan-from-the-command-line","title":"Scan from the command line"},{"href":"/en/code-security/how-tos/find-and-fix-code-vulnerabilities/scan-from-the-command-line/testing-custom-queries","title":"Test custom queries"}],"documentType":"article"},"body":"# Testing custom queries\n\nVerify your custom CodeQL queries and catch breaking changes before they affect your code scanning results following new releases of the CodeQL CLI.\n\n## Testing custom queries\n\nCodeQL provides a simple test framework for automated regression testing\nof queries. Test your queries to ensure that they behave as expected.\n\nDuring a query test, CodeQL compares the results the user expects\nthe query to produce with those actually produced. If the expected and\nactual results differ, the query test fails. To fix the test, you should iterate\non the query and the expected results until the actual results and the expected\nresults exactly match. This topic shows you how to create test files and execute\ntests on them using the `test run` subcommand.\n\n## Setting up a test CodeQL pack for custom queries\n\nAll CodeQL tests must be stored in a special \"test\" CodeQL pack. That is, a directory for test files with a `qlpack.yml` file that defines:\n\n```yaml\nname: <name-of-test-pack>\nversion: 0.0.0\ndependencies:\n  <codeql-libraries-and-queries-to-test>: \"*\"\nextractor: <language-of-code-to-test>\n```\n\nThe `dependencies` value specifies the CodeQL packs containing queries to test.\nTypically, these packs will be resolved from source, and so it is not necessary\nto specify a fixed version of the pack. The `extractor` defines which language the CLI will use to create test databases from the code files stored in this CodeQL pack. For more information, see [Customizing analysis with CodeQL packs](/en/code-security/codeql-cli/getting-started-with-the-codeql-cli/customizing-analysis-with-codeql-packs).\n\nYou may find it useful to look at the way query tests are organized in the [CodeQL repository](https://github.com/github/codeql). Each language has a `src` directory, `ql/<language>/ql/src`, that contains libraries and queries for analyzing codebases. Alongside the `src` directory, there is a `test` directory with tests for\nthese libraries and queries.\n\nEach `test` directory is configured as a test CodeQL pack with two subdirectories:\n\n* `query-tests` a series of subdirectories with tests for queries stored in the `src` directory. Each subdirectory contains test code and a QL reference file that specifies the query to test.\n* `library-tests` a series of subdirectories with tests for QL library files. Each subdirectory contains test code and queries that were written as unit tests for a library.\n\nAfter creating the `qlpack.yml` file, you need to make sure that all of the dependencies are downloaded and available to the CLI. Do this by running the following command in the same directory as the `qlpack.yml` file:\n\n```shell\ncodeql pack install\n```\n\nThis will generate a `codeql-pack.lock.yml` file that specifies all of the transitive dependencies required to run queries in this pack. This file should be checked in to source control.\n\n## Setting up the test files for a query\n\nFor each query you want to test, you should create a sub-directory in the test CodeQL pack.\nThen add the following files to the subdirectory before you run the test command:\n\n* A query reference file (`.qlref` file) defining the location of the query to test. The location is defined relative to the root of the CodeQL pack that contains the query. Usually, this is a CodeQL pack specified in the `dependencies` block of the test pack. For more information, see [Query reference files](/en/code-security/codeql-cli/using-the-advanced-functionality-of-the-codeql-cli/query-reference-files).\n\n  You do not need to add a query reference file if the query you want to test is stored in the test directory, but it is generally good practice to store queries separately from tests. The only exception is unit tests for QL libraries, which tend to be stored in test packs, separate from queries that generate alerts or paths.\n\n* The example code you want to run your query against. This should consist of one or more files containing examples of the code the query is designed to identify.\n\nYou can also define the results you expect to see when you run the query against\nthe example code, by creating a file with the extension `.expected`. Alternatively, you can leave the test command to create the `.expected` file for you.\n\nFor an example showing how to create and test a query, see the [example](#example) below.\n\n> \\[!NOTE]\n> Your `.ql`, `.qlref`, and `.expected` files must have consistent names:\n>\n> * If you want to directly specify the `.ql` file itself in the test command, it must have the same base name as the corresponding `.expected` file. For example, if the query is `MyJavaQuery.ql`, the expected results file must be `MyJavaQuery.expected`.\n> * If you want to specify a `.qlref` file in the command, it must have the same base name as the corresponding `.expected` file, but the query itself may have a different name.\n> * The names of the example code files don’t have to be consistent with the other test files. All example code files found next to the `.qlref` (or `.ql`) file and in any subdirectories will be used to create a test database. Therefore, for simplicity, we recommend you don’t save test files in directories that are ancestors of each other.\n\n## Running `codeql test run`\n\nCodeQL query tests are executed by running the following command:\n\n```shell\ncodeql test run <test|dir>\n```\n\nThe `<test|dir>` argument can be one or more of the following:\n\n* Path to a `.ql` file.\n* Path to a `.qlref` file that references a `.ql` file.\n* Path to a directory that will be searched recursively for `.ql` and `.qlref` files.\n\nYou can also specify:\n\n* `--threads:` optionally, the number of threads to use when running queries. The default option is `1`. You can specify more threads to speed up query execution. Specifying `0` matches the number of threads to the number of logical processors.\n\nFor full details of all the options you can use when testing queries, see [test run](/en/code-security/codeql-cli/codeql-cli-manual/test-run).\n\n## Example\n\nThe following example shows you how to set up a test for a query that searches\nJava code for `if` statements that have empty `then` blocks. It includes\nsteps to add the custom query and corresponding test files to separate CodeQL packs\noutside your checkout of the CodeQL repository. This ensures when you update the\nCodeQL libraries, or check out a different branch, you won’t overwrite your\ncustom queries and tests.\n\n### Prepare a query and test files\n\n1. Develop the query. For example, the following simple query finds empty `then`\n   blocks in Java code:\n\n   ```shell\n   import java\n\n   from IfStmt ifstmt\n   where ifstmt.getThen() instanceof EmptyStmt\n   select ifstmt, \"This if statement has an empty then.\"\n   ```\n\n2. Save the query to a file named `EmptyThen.ql` in a directory with your\n   other custom queries. For example, `custom-queries/java/queries/EmptyThen.ql`.\n\n3. If you haven’t already added your custom queries to a CodeQL pack, create a CodeQL pack now. For example, if your custom Java queries are stored in `custom-queries/java/queries`, add a `qlpack.yml` file with the following contents to `custom-queries/java/queries`:\n\n   ```yaml\n   name: my-custom-queries\n   dependencies:\n     codeql/java-queries: \"*\"\n   ```\n\n   For more information about CodeQL packs, see [Customizing analysis with CodeQL packs](/en/code-security/codeql-cli/getting-started-with-the-codeql-cli/customizing-analysis-with-codeql-packs).\n\n4. Create a CodeQL pack for your Java tests by adding a `qlpack.yml` file with the following contents to `custom-queries/java/tests`, updating the `dependencies` to match the name of your CodeQL pack of custom queries:\n\n   The following `qlpack.yml` file states that `my-github-user/my-query-tests` depends on `my-github-user/my-custom-queries` at a version greater than or equal to 1.2.3 and less than 2.0.0. It also declares that the CLI should use the Java `extractor` when creating test databases. The `tests: .` line declares that all `.ql` files in the pack should be run as tests when `codeql test run` is run with the `--strict-test-discovery` option. Typically, test packs do not contain a `version` property. This prevents you from accidentally publishing them.\n\n   ```yaml\n   name: my-github-user/my-query-tests\n   dependencies:\n     my-github-user/my-custom-queries: ^1.2.3\n   extractor: java-kotlin\n   tests: .\n   ```\n\n5. Run `codeql pack install` in the root of the test directory. This generates a `codeql-pack.lock.yml` file that specifies all of the transitive dependencies required to run queries in this pack.\n\n6. Within the Java test pack, create a directory to contain the test files\n   associated with `EmptyThen.ql`. For example, `custom-queries/java/tests/EmptyThen`.\n\n7. In the new directory, create `EmptyThen.qlref` to define the location of `EmptyThen.ql`. The path to the query must be specified relative to the root of\n   the CodeQL pack that contains the query. In this case, the query is in the\n   top level directory of the CodeQL pack named `my-custom-queries`,\n   which is declared as a dependency for `my-query-tests`. Therefore, `EmptyThen.qlref` should simply contain `EmptyThen.ql`.\n\n8. Create a code snippet to test. The following Java code contains an empty `if` statement on the third line. Save it in `custom-queries/java/tests/EmptyThen/Test.java`.\n\n   ```java\n   class Test {\n     public void problem(String arg) {\n       if (arg.isEmpty())\n         ;\n       {\n         System.out.println(\"Empty argument\");\n       }\n     }\n\n     public void good(String arg) {\n       if (arg.isEmpty()) {\n         System.out.println(\"Empty argument\");\n       }\n     }\n   }\n   ```\n\n### Execute the test\n\nTo execute the test, move into the `custom-queries` directory and run `codeql\ntest run java/tests/EmptyThen`.\n\nWhen the test runs, it:\n\n1. Finds one test in the `EmptyThen` directory.\n\n2. Extracts a CodeQL database from the `.java` files stored in the `EmptyThen` directory.\n\n3. Compiles the query referenced by the `EmptyThen.qlref` file.\n\n   If this step fails, it’s because the CLI can’t find your custom CodeQL pack. Re-run the command and specify the location of your custom CodeQL pack, for example:\n\n   `codeql test run --search-path=java java/tests/EmptyThen`\n\n   For information about saving the search path as part of your configuration, see [Specifying command options in a CodeQL configuration file](/en/code-security/codeql-cli/using-the-advanced-functionality-of-the-codeql-cli/specifying-command-options-in-a-codeql-configuration-file).\n\n4. Executes the test by running the query and generating an `EmptyThen.actual` results file.\n\n5. Checks for an `EmptyThen.expected` file to compare with the `.actual` results file.\n\n6. Reports the results of the test — in this case, a failure: `0 tests passed; 1 tests failed:`. The test failed because we haven’t yet added a file with the expected results of the query.\n\n### View the query test output\n\nCodeQL generates the following files in the `EmptyThen` directory:\n\n* `EmptyThen.actual`, a file that contains the actual results generated by the\n  query.\n* `EmptyThen.testproj`, a test database that you can load into VS Code and use to debug failing tests. When tests complete successfully, this database is deleted in a housekeeping step. You can override this step by running `test run` with the `--keep-databases` option.\n\nIn this case, the failure was expected and is easy to fix. If you open the `EmptyThen.actual` file, you can see the results of the test:\n\n```shell\n\n| Test.java:3:5:3:22 | stmt | This if statement has an empty then. |\n\n```\n\nThis file contains a table, with a column for the location of the result,\nalong with separate columns for each part of the `select` clause the query outputs.\nSince the results are what we expected, we can update the file extension to define\nthis as the expected result for this test (`EmptyThen.expected`).\n\nIf you rerun the test now, the output will be similar but it will finish by reporting: `All 1 tests passed.`.\n\nIf the results of the query change, for example, if you revise the `select` statement for the query, the test will fail. For failed results, the CLI output includes a unified diff of the `EmptyThen.expected` and `EmptyThen.actual` files.\nThis information may be sufficient to debug trivial test failures.\n\nFor failures that are harder to debug, you can import `EmptyThen.testproj`\ninto CodeQL for VS Code, execute `EmptyThen.ql`, and view the results in the\n`Test.java` example code. For more information, see [Managing CodeQL databases](/en/code-security/codeql-for-vs-code/getting-started-with-codeql-for-vs-code/managing-codeql-databases#choosing-a-database-to-analyze).\n\n## Further reading\n\n* [CodeQL queries](https://codeql.github.com/docs/writing-codeql-queries/codeql-queries/#codeql-queries)\n* [Testing CodeQL queries in Visual Studio Code](/en/code-security/codeql-for-vs-code/using-the-advanced-functionality-of-the-codeql-for-vs-code-extension/testing-codeql-queries-in-vs-code)."}