Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added sanic + mongo application #17

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions sanic-mongo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
keploy-logs.txt
keploy
122 changes: 122 additions & 0 deletions sanic-mongo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
This application is a simple movie management API built using Python's Sanic framework and MongoDB for data storage. It allows you to perform basic CRUD (Create, Read, Update, Delete) operations on Movie records.

## Table of Contents

# Introduction

🪄 Dive into the world of Movie CRUD Apps and see how seamlessly Keploy integrated with [Sanic](hhttps://sanic.dev/en/) and [MongoDB](https://www.mongodb.com/). Buckle up, it's gonna be a fun ride! 🎢

## Pre-Requisite 🛠️

- Install WSL (`wsl --install`) for <img src="https://keploy.io/docs/img/os/windows.png" alt="Windows" width="3%" /> Windows.

## Optional 🛠️

- Install Colima( `brew install colima && colima start` ) for <img src="https://keploy.io/docs/img/os/macos.png" alt="MacOS" width="3%" /> MacOs.

## Installation 📥

Depending on your OS, choose your adventure:


Alright, let's equip ourselves with the **latest Keploy binary**:

```bash
curl --silent --location "https://github.com/keploy/keploy/releases/latest/download/keploy_linux_amd64.tar.gz" | tar xz -C /tmp

sudo mkdir -p /usr/local/bin && sudo mv /tmp/keploy /usr/local/bin && keploy
```

#### Add alias for Keploy:

```bash
alias keploy='sudo docker run --pull always --name keploy-v2 -p 16789:16789 --privileged --pid=host -it -v "$(pwd)":/files -v /sys/fs/cgroup:/sys/fs/cgroup -v /sys/kernel/debug:/sys/kernel/debug -v /sys/fs/bpf:/sys/fs/bpf -v /var/run/docker.sock:/var/run/docker.sock -v '"$HOME"'/.keploy-config:/root/.keploy-config -v '"$HOME"'/.keploy:/root/.keploy --rm ghcr.io/keploy/keploy'
```

Now head to the folder of the application and run
```
pip3 install requirements.txt
```

### Lights, Camera, Record! 🎥


Capture the test-cases-

```shell
keploy record -c "python server.py"
```

🔥**Make some API calls**. Postman, Hoppscotch or even curl - take your pick!

Let's make URLs short and sweet:

### Generate testcases

To generate testcases we just need to **make some API calls.**

**1. Make a POST requests**

```bash
curl -X "POST" "http://127.0.0.1:8000/add_movie" \
-H 'Accept: application/json' \
-H 'Content-Type: application/json; charset=utf-8' \
-d '{
"name": "Whiplash"
}'
```

```bash
curl -X "POST" "http://127.0.0.1:8000/add_movie" \
-H 'Accept: application/json' \
-H 'Content-Type: application/json; charset=utf-8' \
-d '{
"name": "Chappie"
}'
```

```bash
curl -X "POST" "http://127.0.0.1:8000/add_movie" \
-H 'Accept: application/json' \
-H 'Content-Type: application/json; charset=utf-8' \
-d '{
"name": "Titanic"
}'
```

**2. Make a GET request**

In order to see all the movies added to the database, run:

```
curl -X "GET" "http://127.0.0.1:8000/movies" \
-H 'Accept: application/json' \
-H 'Content-Type: application/json; charset=utf-8'
```

**3. Make a DELETE request**

In order to delete all the movies, run:

```bash
curl -X "DELETE" "http://127.0.0.1:8000/movies" \
-H 'Accept: application/json' \
-H 'Content-Type: application/json; charset=utf-8'
```
You will now see a folder named `keploy` with your recorded tests.

#### Run Tests

Time to put things to the test 🧪

```shell
keploy test -c "python server.py"
```

## Wrapping it up 🎉

Congrats on the journey so far! You've seen Keploy's power, flexed your coding muscles, and had a bit of fun too! Now, go out there and keep exploring, innovating, and creating! Remember, with the right tools and a sprinkle of fun, anything's possible.😊🚀

Happy coding! ✨👩‍💻👨‍💻✨

<br/>
3 changes: 3 additions & 0 deletions sanic-mongo/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pymongo==4.6.3
sanic==23.12.1
sanic_motor==0.7.0
60 changes: 60 additions & 0 deletions sanic-mongo/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from sanic import Sanic, text
from sanic.response import json as json_response
from sanic.exceptions import NotFound
from sanic_motor import BaseModel
from bson import ObjectId

app = Sanic(__name__)

settings = dict(
MOTOR_URI='mongodb://localhost:27017/myapp', LOGO=None
)

app.config.update(settings)

BaseModel.init_app(app)

class Movie(BaseModel):
__coll__ = "movies"

@app.route("/add_movie", methods=["POST"])
async def add_movie(request):
movie = request.json
movie["_id"] = str(ObjectId())

new_movie = await Movie.insert_one(movie)
created_movie = await Movie.find_one({"_id": new_movie.inserted_id}, as_raw=True)
return json_response(created_movie)


@app.route("/movies", methods=["GET"])
async def list_movies(request):
movies = await Movie.find(as_raw=True)
return json_response(movies.objects)



@app.route("/movies/<id>", methods=["GET"])
async def get_movie(request, id):
if (movies := await Movie.find_one({"_id": id}, as_raw=True)) is not None:
return json_response(movies)

raise NotFound(f"Movie {id} not found")


@app.route("/movies/<id>", methods=["DELETE"])
async def delete_movie(request, id):
delete_result = await Movie.delete_one({"_id": id})

if delete_result.deleted_count == 1:
return json_response({}, status=204)

raise NotFound(f"Movie {id} not found")

@app.route("/movies", methods=["DELETE"])
async def delete_all_movies(request):
await Movie.delete_many({})
return json_response({}, status=204)

if __name__ == "__main__":
app.run(host="127.0.0.1", port=8000, debug=True)