# Introduction to Momentum


# Overview

Hey there! Welcome to momentum docs. You can start by learning about how momentum can   be helpful in your software development process.

### What is momentum?

momentum is a code auditor that analyses the necessary code behavior and tests it at every git push to ensure the code is ready for production.

### Languages and Frameworks supported

**Python**

1. FastAPI
2. Django
3. Flask
4. Sanic

**Coming soon**

1. Javascript
2. Java


# How can momentum help you?

You should use momentum at every git push to ensure your code is ready for a pull request review.

**Here's what momentum will tell you at every push**

1. Blast radius detection - this will be a list of endpoints that could potentially be affected by the changes you made in your code. This will also be a starting point to decide what parts of your code need to be tested before shipping to production.
2. Visualization
3. Behaviour identification
4. Code generation to test functionality
5. Debugging (using stack trace)
6. Self-healing (simple cases)

**Coming soon**

1. Debugging (using visualization)
2. Self-healing (complex cases)
3. Test data setup
4. Code fixation


# Why is it open source

Momentum is open source as a way for us to give back to the community. By making the source code available, we empower our users to:

* [**View the Source Code**](https://github.com/getmomentum/momentum-core)**:** Understand how Momentum works under the hood.
* **Modify It:** Tailor Momentum to meet their specific needs.
* **Use It Freely:** Integrate Momentum into their projects without restrictions.
* **Contribute:** Improve Momentum by submitting pull requests with their enhancements, benefiting the entire community.

We believe that open collaboration leads to better software and a more vibrant, innovative community. Let's work together to make Momentum the best it can be!

Thank you for contributing to Momentum!


# Contributing to momentum

We welcome and deeply appreciate any contributions to momentum. No matter how small, every contribution is valuable!

Contributions can be of the form:

1. Documentation : Help improve our docs! If you fixed a problem, chances are others faced it too.
2. Code : Help us make improvements to existing features and build new features for momentum.
3. Tests : Help us make momentum resilient by contributing tests.

> Contributors should follow the [code of conduct](https://github.com/getmomentum/momentum-core/blob/main/docs/introduction-to-momentum/code_of_conduct.md)

When contributing to momentum, ensure that:

1. You have looked at [open issues](https://github.com/getmomentum/momentum-core/issues) to see if there's something you can do for us.
2. If there is a major feature you would like to work on that is not present on the issues page, before implementation [open an issue](https://github.com/getmomentum/momentum-core/issues/new) and discuss it with the core team.
3. Aim for 100% test coverage when contributing new features. Tests help verify your code and protect against future changes.
4. Ensure that all your changes run end to end locally, include screenshots of local test results wherever possible in your PR.
5. Once the code is ready, raise a pull request towards the main repo for peer review and acceptance.

To contribute:

1. Fork the repository.
2. Create a new branch (`git checkout -b feature-branch`).
3. Commit your changes (`git commit -am 'Add new feature'`).
4. Push to the branch (`git push origin feature-branch`).
5. Open a Pull Request.


# Troubleshooting & Feedback

For any bugs / feature improvements, please use [github issues](https://github.com/getmomentum/momentum-core/issues).\
\
For everything else, we encourage you to join the community on [discord](https://discord.gg/z6tj9Ufc) here for easier communication. We are also available on email at [support@momentum.sh](mailto:SUPPORT@MOMENTUM.SH)


# Getting Started


# Hers's what you will need

To get started with our product, you'll need the following:

1. **Docker and Docker Compose**: Ensure that Docker and Docker Compose are installed on your system. You can download and install them using any of the suggested ways [here](https://docs.docker.com/engine/install/) and [here](https://docs.docker.com/compose/install/).
2. **Git**: You'll need Git to clone our [repository](https://github.com/getmomentum/momentum-core). You can download and install Git from [here](https://git-scm.com/downloads).
3. **Python** (v3 onwards): Momentum is python based so you'll need the support for it running on your system. Usually it's supported by the OS out of the box - but do install if that's not the case.\
   \
   Once you have these up and running - we can proceed to installation.


# Installation

**Step 1: Clone the Repository**

First, clone our repository to your local machine using Git:

```bash
git clone https://github.com/getmomentum/momentum-core
cd momentum-core
```

**Step 2: Create a virutal enviorment**

We strongly recommend running the app in a virtual enviorment, if you want to have a look at multiple reasons of why that is the case, read this [reddit](https://www.reddit.com/r/learnpython/comments/15nuehj/why_do_i_need_a_virtual_environment/) thread.

How to create virtual enviorment

```
python3 -m venv venv
```

And activate it

```
source venv/bin/activate
```

If you replace the venv with any other folder name, please add it in .gitignore

**Step 3: Install the dependencies from requirements**

```
pip install requirements.txt
```

If you face any challenges here, check out [Known bugs & fixes](/getting-started/known-bugs-and-fixes) and [Troubleshooting & Feedback](/readme/troubleshooting-and-feedback)


# Cloud Integrations (Optional)

If you decide to run momentum outside development mode, you will ned to configure firebase and other cloud accounts, should be easy to do with attached references.

{% hint style="info" %}
Note : As of now, we only support google cloud and firebase, with support for other providers in future with the goal of being provider agnostic eventually.
{% endhint %}


# Portkey

We use portkey to have capabilities like observability and monitoring for AI Integration with momentum. This is not needed if you are running momentum in development mode.\
\
Sign up for a free account and keep the API Key handy. \
\
<https://app.portkey.ai/signup>


# Firebase

You will need a firebase project, add one from here : [https://console.firebase.google.com/](https://console.firebase.google.com/u/0/)

Once a project is created, do the following.\
\
1\. Click on Project overview from the sidebar.\
2\. Open Service accounts tab.\
3\. You will see the option to generate a new private key in the firebase admin sdk sub-section. Click on that.\
4\. Read the warning, and then generate the key. Rename the downloaded key to - firebase\_service\_account.json and move it to server folder in the root of momentum source code. \\

{% hint style="info" %}
Note: The file name 'firebase\_service\_account.json' is already part of .gitignore and should be safe to use. It never goes on git. But in case you loose it, you'll need a new one. So keep it secure and safe. (Repeating the warning that google gave you during key generation)
{% endhint %}


# Setting up Github App

We need to enable login via github, for that, we will create a github app. To do that,

1. Visit this url : <https://github.com/settings/apps/new>
2. Name your app in context of momentum (suggestion) , can be anything - for example momentum-auth.
3. We need to give the app following permissions:\
   (a) Repository permissions - **Contents** (Read Only), **Metadata** (Read Only), **Pull Requests** (Read and write), **Secrets** (Read Only), **Webhook** (Read only)\
   (b) Organisation permissions - None\
   (c) Account permissions - **Email Address** (Read Only)
4. Generate a private key of your github app, once downloaded and add it to launch.json in GITHUB\_PRIVATE\_KEY, add your app id to GITHUB\_APP\_ID sections.
5. Now from the left sidebar , select install app, and install it next to your org/ user account.


# Enabling Github Auth on Firebase

1. Open firebase, go to firebase authentication, and start with the github sign in capability.
2. Add a github oauth app from your account, it should give you a client secret and client id , add that to firebase.
3. Copy the callback url from firebase and add it to your github app.

Github Auth with Firebase is ready.


# Google Cloud

Momentum uses google secret manager to securely manage API keys.\
\
Since you have already created a firebase app, a linked google cloud account will automatically be created. You can use that or create a new one as per your convience.\
\
Use [these](https://cloud.google.com/python/docs/reference/secretmanager/latest) steps to setup secret manager, and setup [application default credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc#how-to) for momentum to use in your local system. (Alternative documentation [here](https://googleapis.dev/python/google-api-core/latest/auth.html))\
\
Once that is done - that's all you need to do for google account setup. Only a few more steps before you can get momentum up and running.


# Running Momentum

1. **Ensure Docker is Installed**: Verify that Docker is installed on your system.
2. **Set Up the Environment**: Configure your environment variables by creating a `.env` file based on the `.env.template`provided in the repository. This file should include all necessary configuration settings for the application.
3. **Development Mode**: If you want to run Momentum in development mode, ensure the `isDevelopmentMode` flag is enabled. \
   \
   This feature allows Momentum to operate without any additional configuration. You can then proceed directly to step 5. \
   \
   However, please note that this mode does not support GitHub-based repositories. To access these repositories, you will need to clone them locally or follow the cloud setup steps.<br>
4. **Google Cloud Authentication**: Log in to your Google Cloud account and set up Application Default Credentials (ADC). Detailed instructions can be found here.<br>
5. **Run Momentum**:

```bash
./run-momentum.sh
```

{% hint style="info" %}
(a) *You might need to make `run-momentum.sh` executable by running `chmod +x run-momentum.sh`.*
{% endhint %}


# Known bugs & fixes

If you encounter **psycopg2** related errors, particularly on macOS, it is typically due to the absence of PostgreSQL in the local system, which causes the driver to malfunction. For further reference, please consult the relevant Stack Overflow thread [here](https://stackoverflow.com/questions/33866695/error-installing-psycopg2-on-macos-10-9-5).

The recommended solution for now is to execute the following command to install PostgreSQL:

```
brew install postgresql
```

{% hint style="info" %}
With our ongoing efforts to streamline the setup process, we are working towards integrating Docker solutions. This enhancement is scheduled for inclusion in upcoming releases.
{% endhint %}


# Using Momentum


# Underlying API structure

Once the application is operational, the Swagger documentation will be accessible at `http://0.0.0.0:8001/docs`.

This documentation provides an overview of the system's contracts and APIs. However, it may not be comprehensive and enough for understanding intentions. It is recommended to review this documentation thoroughly to understand the context of these APIs before proceeding.

Assuming the application is currently running at `http://0.0.0.0:8001`, we can move forward with the next steps.


# Auth

There are currently two authentication related endpoints, for logging in and registering the user in internal database.


# Logging in

<mark style="color:green;">`POST`</mark> `/login`

This endpoint allows users to log in to the app using their email and password. The user must first be created in Firebase Authentication. Upon successful login, a token is returned, which is necessary for authentication in subsequent requests.

#### Steps to Create User in Firebase Authentication

1. **Go to your Firebase project.**
2. **Navigate to Authentication.**
3. **Click on "Add User".**
4. **Provide the email and password.**
5. **Add the user.**

#### **Headers**

| Name         | Value              |
| ------------ | ------------------ |
| Content-Type | `application/json` |

**Body**

| Name       | Type   | Description          |
| ---------- | ------ | -------------------- |
| `email`    | string | Email of the user    |
| `password` | string | Password of the user |

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
  "token":"bearertoken"
}
```

{% endtab %}

{% tab title="400" %}
{% code overflow="wrap" %}

```json
{
    "error": "ERROR: {'error': {'code': 400, 'message': 'INVALID_LOGIN_CREDENTIALS', 'errors': [{'message': 'INVALID_LOGIN_CREDENTIALS', 'domain': 'global', 'reason': 'invalid'}]}}"
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Notes

* Ensure that the email and password provided are correct and match the credentials used in Firebase Authentication.
* The token returned in the response is necessary for all subsequent requests to the API. Store it securely and include it in the `Authorization` header as `Bearer <token>` for authenticated endpoints.


# User Registration

<mark style="color:green;">`POST`</mark> `/`signup

This endpoint allows you to register an authenticated user in our local database. The user's details should be provided in the request payload. Upon successful registration, the user will be added to the local database, allowing for subsequent interactions with the app.

#### **Headers**

| Name         | Value              |
| ------------ | ------------------ |
| Content-Type | `application/json` |

**Body**

<table data-full-width="false"><thead><tr><th>Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>uid</code></td><td>String</td><td>Unique identifier for the user</td></tr><tr><td><code>email</code></td><td>String</td><td>Email address of the user</td></tr><tr><td><code>displayName</code></td><td>String</td><td>Display name of the user</td></tr><tr><td><code>emailVerified</code></td><td>Boolean</td><td>Indicates if the email is verified</td></tr><tr><td><code>createdAt</code></td><td>DateTime</td><td>Account creation date and time (ISO 8601)</td></tr><tr><td><code>lastLoginAt</code></td><td>DateTime</td><td>Last login date and time (ISO 8601)</td></tr><tr><td><code>providerData</code></td><td>Array</td><td>Array of provider data objects</td></tr><tr><td>├─ <code>providerId</code></td><td>String</td><td>Identifier for the authentication provider</td></tr><tr><td>└─ <code>providerName</code></td><td>String</td><td>Name of the authentication provider</td></tr><tr><td><code>providerUsername</code></td><td>String</td><td>Username provided by the authentication provider</td></tr></tbody></table>

#### Sample Request

```bash
curl -X POST https://server-ip:port/signup \
-H "Content-Type: application/json" \
-H "Authorization: Bearer {token}" \
-d '{
  "uid": "12345",
  "email": "testaccount@gmail.com",
  "displayName": "Sample User",
  "emailVerified": true,
  "createdAt": "2024-06-19T12:34:56Z",
  "lastLoginAt": "2024-06-19T12:34:56Z",
  "providerData": [
    {
      "providerId": "google.com",
      "providerName": "Google"
    }
  ],
  "providerUsername": "testaccount"
}'
```

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
  "uid": "12345",
}
```

{% endtab %}

{% tab title="400" %}

```json
{
  "error creating user"
}
```

{% endtab %}
{% endtabs %}

By following the above guidelines, you can seamlessly register users in the local database and proceed with further interactions within the app.


# Parsing codebase

{% hint style="info" %}
Reminder: The github app we created earlier will need access to the repo.

**Steps to Grant Access to Repositories**

1. **Go to your GitHub account.**
2. **Navigate to the GitHub app installation settings.**
3. **Select the app you created.**
4. **Update the repository access permission to repository you want to parse.**
   {% endhint %}

<mark style="color:green;">`POST`</mark> `/parse`

This endpoint allows you to parse the codebases that the GitHub app has access to. Ensure the app has the necessary permissions to access the repositories you want to parse. You can update the app's access permissions through the GitHub app installation settings.

**Headers**

| Name          | Value              |
| ------------- | ------------------ |
| Content-Type  | `application/json` |
| Authorization | `Bearer <token>`   |

**Body**

| Name          | Type   | Sample             |
| ------------- | ------ | ------------------ |
| `repo_name`   | string | username/repo-name |
| `branch_name` | string | feature            |

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
  "status": "success",
  "message": "The project has been parsed successfully"
}
```

{% endtab %}

{% tab title="400" %}

```json
{
    "detail": "Invalid authentication from Firebase. Token expired, 1718882208 < 1718886290"
}
```

{% endtab %}

{% tab title="400" %}
{% code overflow="wrap" %}

```json
{"detail":"Failed to get installation ID"}
```

{% endcode %}
{% endtab %}

{% tab title="500" %}
{% code overflow="wrap" %}

```json
{"detail":"404 Client Error: Not Found for url"}
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Notes

* Ensure that the `Authorization` header contains a valid token obtained during the login process.
* The `repo_name` should be in the format `username/repo-name` , do not use a complete url.
* The `branch_name` should be a valid branch in the specified repository.


# Getting list of all parsed projects

## Listing all parsed repos of a user

<mark style="color:green;">`GET`</mark> `/projects/list`

Get the list of all parsed repos of authenticated user.

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Response**

{% tabs %}
{% tab title="200" %}

```json
[
    {
        "project_id": 2,
        "branch_name": "main",
        "repo_name": "vineetshar/distributed-id-generator",
        "last_updated_at": "2024-06-19T14:27:03.599554",
        "is_default": true,
        "project_status": "ready"
    },
    {
        "project_id": 3,
        "branch_name": "main",
        "repo_name": "vineetshar/python-simple-rest-api-cline",
        "last_updated_at": "2024-06-20T08:48:09.417632",
        "is_default": true,
        "project_status": "ready"
    }
]
```

{% endtab %}

{% tab title="401" %}
{% code overflow="wrap" %}

```json
{
    "detail": "Invalid authentication from Firebase. Invalid base64-encoded string: number of data characters (101) cannot be 1 more than a multiple of 4"
}
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Getting list of all branches in a project

<mark style="color:green;">`GET`</mark> `/get-branch-list`

Use this endpoint to get list of all the available branches in a parsed repo

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Query Param**

| Name         | Type   | Description          |
| ------------ | ------ | -------------------- |
| repo\_`name` | string | username/branch-name |

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
    "branches": [
        "branch1",
        "main",
        "branch2"
    ]
}
```

{% endtab %}

{% tab title="404" %}
{% code overflow="wrap" %}

```json
{
    "detail": "Repository not found or error fetching branches: 400: Failed to get installation ID"
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
404 in this case would ususally mean that we do not have access to the codebase / github repo or it doesn't exist.
{% endhint %}


# Listing all endpoints of a branch

<mark style="color:green;">`GET`</mark> `/endpoints/list`

This api will list all the detected endpoints for the codebase that was parsed by momentum.

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Query Param**

| Name         | Type   | Description                                                |
| ------------ | ------ | ---------------------------------------------------------- |
| `project_id` | string | Project id that was generated when the project was parsed. |

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
    "/server.py": [
        {
            "entryPoint": "GET /",
            "identifier": "/server.py:index"
        },
        {
            "entryPoint": "GET /helloworld",
            "identifier": "/server.py:list"
        },
        {
            "entryPoint": "GET /search",
            "identifier": "/server.py:search"
        },
        {
            "entryPoint": "POST /add",
            "identifier": "/server.py:add"
        },
        {
            "entryPoint": "POST /delete",
            "identifier": "/server.py:delete"
        }
    ]
}
```

{% endtab %}

{% tab title="400" %}

```json
{
    "detail": "Project Details not found."
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
The success response will give an empty array in case the repo does not have any REST endpoints.
{% endhint %}


# Understanding Changes & Impacts

Once the codebase is parsed, it is time to understand what changes your branch is bringing in, and what are the possible impacts.


# Generating Blast Radius

<mark style="color:green;">`GET`</mark> endpoints/blast

Now that you'd like to compare the changes and understand the blast radius of the changes, between the main/master branch and the branch you're planning to merge - we use this endpoint.

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Query Params**

| Name          | Type   | Description                       |
| ------------- | ------ | --------------------------------- |
| `project_id`  | number | Generated project id during parse |
| `base_branch` | string | base branch name                  |

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
    "/server.py": [ //signifies the file in which it found the endpoint
        {
            "entryPoint": "GET /",
            "identifier": "/server.py:index"
        }
    ]
}
```

{% endtab %}

{% tab title="400" %}

```json
{
    "detail": "Project Details not found." //project id is incorrect
}
```

{% endtab %}
{% endtabs %}


# Get Flow Graph

<mark style="color:green;">`GET`</mark> `/endpoints/flow/graph`

This endpoint helps you understand the flow from the endpoint to further neighbours in code in a parent - child relationship.

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Query Params**

| Name          | Type   | Description                                                                              |
| ------------- | ------ | ---------------------------------------------------------------------------------------- |
| `project_id`  | string | The project id generated during parsing of the code                                      |
| `endpoint_id` | string | The endpoint identifier that points to the specific node you want to generate graph from |

**Response**

{% tabs %}
{% tab title="200" %}

```json
[
    {
        "function": "/server.py:list", //the function that was hit by the endpoint
        "params": "[{\"identifier\": \"_\", \"type\": null}]", // the parameters of the function
        "response_object": "", // response object attached to the function
        "children": [ //further nodes and flow
            {
                "function": "/server.py:API.get",
                "params": "[{\"identifier\": \"self\", \"type\": null}, {\"identifier\": \"path\", \"type\": null}]",
                "response_object": "",
                "children": []
            }
        ]
    }
]
```

{% endtab %}

{% tab title="400" %}

```json
{
    "status_code": 400,
    "detail": "Project Details not found."
}
```

{% endtab %}
{% endtabs %}


# Get Dependencies

<mark style="color:green;">`GET`</mark> `/endpoints/dependencies`

This helps you get list of all the dependencies of parsed code of a specific endpoint.

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Query Params**

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| `project_id`  | number | The project id generated during parsing of the code         |
| `endpoint_id` | string | The endpoint identifier you need to list dependencies from. |

**Response**

{% tabs %}
{% tab title="200" %}

```json
[ //array of dependencies of the endpoint
    "API.get"
]
```

{% endtab %}

{% tab title="400" %}

```json
{
    "status_code": 400,
    "detail": "Project Details not found."
}
```

{% endtab %}
{% endtabs %}


# Get More Dependencies (AI)

<mark style="color:green;">`POST`</mark> `/endpoints/dependencies/more`

This helps you get list of all the deeper linked dependencies of parsed code of a specific endpoint.

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Query Params**

| Name          | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| `project_id`  | number | The project id generated during parsing of the code         |
| `endpoint_id` | string | The endpoint identifier you need to list dependencies from. |

**Response**

{% tabs %}
{% tab title="200" %}

```json
[ //list of a sample deep dependency list of a get api endpoint
    "dict",
    "enumerate",
    "dict",
    "API.get"
]
```

{% endtab %}

{% tab title="400" %}

```json
{
    "status_code": 400,
    "detail": "Project Details not found."
}
```

{% endtab %}
{% endtabs %}


# Getting code of a specific node

<mark style="color:green;">`GET`</mark> `/code/node`

Get the code of a specific node in the parsed codebase. These nodes are typically your endpoints or their child functions that were listed as part of flow graph.

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Query Params**

| Name         | Type   | Description                                                          |
| ------------ | ------ | -------------------------------------------------------------------- |
| `project_id` | number | The project id generated during parsing of the code                  |
| `node_id`    | string | The node id that points to the specific node you want to get code of |

**Response**

{% tabs %}
{% tab title="200" %}
{% code overflow="wrap" %}

```json
{
    "code": "@api.get(\"/search\")\ndef search(args):\n    q = args.get(\"q\", None)\n\n    if q is None:\n        return { \"error\": \"q parameter required\" }\n    else:\n        results = []\n        for item in example_data[\"items\"]:\n            if item[\"name\"].count(q) > 0:\n                results.append(item)\n        return { \"count\": len(results), \"items\": results }",
    "file": "local-file-path/filename.py",
    "project_id": 4,
    "response": "",
    "start": 55,
    "end": 66,
    "id": "/server.py:search",
    "type": "function",
    "parameters": "[{\"identifier\": \"args\", \"type\": null}]"
}
```

{% endcode %}
{% endtab %}

{% tab title="200" %}

<pre class="language-json" data-overflow="wrap"><code class="lang-json"><strong>null //in case no node was found 
</strong></code></pre>

{% endtab %}

{% tab title="400" %}

```json
{
    "status_code": 400,
    "detail": "Project Details not found." //the project id is incorrect
}
```

{% endtab %}
{% endtabs %}


# Testing your code

Now that momentum has analysed your code, it is ready to generate, edit, debug and run the tests. Let's get started with creating a test plan.


# Generating a test plan

<mark style="color:green;">`GET`</mark> `/test/plan`

Get the test plan of a specific node in the parsed codebase.

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Query Params**

| Name         | Type   | Description                                                                                              |
| ------------ | ------ | -------------------------------------------------------------------------------------------------------- |
| `project_id` | number | The project id generated during parsing of the code                                                      |
| `identifier` | string | The node id that points to the specific endpoint you want to get test plan for, ex : `/server.py:search` |

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
    "happy_path": [
        "Search for a common term that matches multiple items",
        "Search for a unique term that matches exactly one item",
        "Search for a term that matches items with varying case sensitivity"
    ],
    "edge_case": [
        "Search with an empty string as the query",
        "Search with a query that matches no items",
        "Search with special characters in the query"
    ]
}
```

{% endtab %}

{% tab title="500" %}

```json
{
  Internal Server Error  //occours on incorrect query params value
}
```

{% endtab %}
{% endtabs %}


# Setting up the test plan

<mark style="color:green;">`PUT`</mark> `/test/plan`

Once the test plan is ready and you're good to go forward with it, it is time to let momentum set it up for execution.

**Headers**

| Name          | Value              |
| ------------- | ------------------ |
| Content-Type  | `application/json` |
| Authorization | `Bearer <token>`   |

**Body**

| Name         | Type                                                     | Description                                                                                         |
| ------------ | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `plan`       | Object of arrays, containing happy\_path and edge\_cases | The plans generated in the last step                                                                |
| `project_id` | number                                                   | The project id generated during parsing of the code                                                 |
| `identifier` | string                                                   | The id that points to the specific endpoint you want to set test plan for, ex : `/server.py:search` |

**Response**

{% tabs %}
{% tab title="200" %}
{% code overflow="wrap" %}

```json
null //empty response with 200 success code indicating the test plan has been set up
```

{% endcode %}
{% endtab %}

{% tab title="400" %}
{% code overflow="wrap" %}

```json
{  // Usually happens with invalid parameters
    "status_code": 400,
    "detail": "Project Details not found." 
}
```

{% endcode %}
{% endtab %}
{% endtabs %}


# Preferences

If you want to pre-set some preferences / instructions for your tests, like mocking database calls etc., you can use the given apis to set and check the preferences before generating code for your tests.


# Setting preferences of a specific endpoint

<mark style="color:green;">`PUT`</mark> `/endpoints/preferences`

Set preferences / custom instructions for test generation.

**Headers**

| Name          | Value              |
| ------------- | ------------------ |
| Content-Type  | `application/json` |
| Authorization | `Bearer <token>`   |

**Body**

<table><thead><tr><th width="249">Name</th><th width="212">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>identifier</code></td><td>string</td><td>The node id that points to the specific endpoint you want to target tests for, ex : <code>/server.py:search</code></td></tr><tr><td><code>project_id</code></td><td>number</td><td>Project id</td></tr><tr><td><code>preference</code></td><td>string</td><td>Test customisation / preferences that you'd like the system to adhere to.</td></tr></tbody></table>

**Response**

**Response**

{% tabs %}
{% tab title="200" %}

```json
null //the test preferences were saved to the database
```

{% endtab %}

{% tab title="400" %}

```json
{ //invalid project id
    "detail": "Project Details not found."
}
```

{% endtab %}
{% endtabs %}


# Getting preferences for specific endpoint

<mark style="color:green;">`GET`</mark> `/endpoints/preferences`

Check the configured preferences for a given endpoint

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Query Params**

| Name         | Type   | Description                                                                                                    |
| ------------ | ------ | -------------------------------------------------------------------------------------------------------------- |
| `project_id` | number | Project id                                                                                                     |
| `identifier` | string | The node id that points to the specific endpoint you want to confirm preferences for, ex : `/server.py:search` |

**Response**

{% tabs %}
{% tab title="200" %}

```json
Custom Instructions / Preferences instructions
```

{% endtab %}

{% tab title="400" %}

```json
{
    "detail": "Project Details not found."
}
```

{% endtab %}
{% endtabs %}


# Generating tests

<mark style="color:green;">`GET`</mark> `/test/generate`

Use momentum to generate tests for your

**Headers**

| Name          | Value            |
| ------------- | ---------------- |
| Authorization | `Bearer <token>` |

**Query Params**

| Name            | Type   | Description                                                                                               |
| --------------- | ------ | --------------------------------------------------------------------------------------------------------- |
| `project_id`    | number | The project id generated during parsing of the code                                                       |
| `identifier`    | string | The node id that points to the specific endpoint you want to generate tests for, ex : `/server.py:search` |
| `endpoint_path` | string | Complete path of the endpoint you want to test                                                            |

**Response**

{% tabs %}
{% tab title="200" %}

```json
Generated Tests Cases in form of python code
```

{% endtab %}

{% tab title="400" %}

```json
{
    "detail": "Project Details not found."
}
```

{% endtab %}

{% tab title="500" %}
{% code overflow="wrap" %}

```json
Internal Server Error //usually occours when the identifier is wrong
```

{% endcode %}
{% endtab %}
{% endtabs %}

You can use the generated tests from this endpoint to test relevant code.


# Using Momentum CLI

Momentum CLI is used in combination with **Momentum Pro / Enterprise** to run tests on your local IDE.\
\
This makes the flow of test planning -> test generation -> test integration -> test running really a matter of few simple clicks enhancing developer experience.

#### Installing the cli

```
pip3 install momentum-cli
```

#### Setting up the cli

Once the CLI is installed, for you to use it - there are some steps you'd need to take. The first thing is running the command to initialise it.

```
momentum init
```

When you run this command, this will ask you for two inputs :\
\
**(a) Path of virtual env** : Please enter the absolute path of your created virtual env at this point, for example "./users/fatman/projects/momentum/.venv"\
\
**(b) Path of directory where you want the tests to be generated** : Please provide the absolute path for the directory where you want the tests to be stored and run from. Ideally this is a subfolder inside your codebase which is called something like "tests", but you can customise this. For example the path could look like : "/users/fatman/projects/momentum/tests"\
\
Once you provide these inputs, the cli will automatically setup everything else and run momentum for you to interact with (via momentum pro / enterprise).

#### Stopping the cli

```
momentum stop
```

When you're done with momentum, simply stop the cli with this command.

#### Reconfiguring the variables

In case you want to reconfigure your virtual env / test directory path - you can run the following command which should help you with that.

```
momentum config
```

Once the reconfiguration is done, go ahead and run momentum with this command :

```
momentum run
```

Once your cli is correctly configured and running, momentum (pro/enterprise) can connect and run, modify, regenerate, fix & verify tests with your codebase easily.


