init commit

This commit is contained in:
2025-03-25 14:41:53 +01:00
parent dd619df7a2
commit 07d201d3ae
24 changed files with 411 additions and 303 deletions
+13 -11
View File
@@ -1,20 +1,22 @@
#!/usr/bin/env python3
import logging
import connexion
from openapi_server import encoder
from pymongo import MongoClient
client = MongoClient(host='mongodb://localhost:27017/')
db = client["MainDB"]
collection = db['patch_notes']
def main():
app = connexion.App(__name__, specification_dir='./openapi/')
app.app.json_encoder = encoder.JSONEncoder
app.add_api('openapi.yaml',
base_path='/api',
arguments={'title': 'announcementService'},
pythonic_params=True)
app.run(port=8080)
app = connexion.App(__name__, specification_dir='./openapi/')
app.app.logger.setLevel(logging.DEBUG)
app.app.json_encoder = encoder.JSONEncoder
app.add_api('openapi.yaml',
base_path='/api',
arguments={'title': 'announcementService'},
pythonic_params=True)
if __name__ == '__main__':
main()
app.run(port=8080, host='0.0.0.0')
@@ -1,25 +1,45 @@
import logging
import connexion
from typing import Dict
from typing import Tuple
from typing import Union
from bson import json_util
from flask import Response
from pymongo import MongoClient
from openapi_server.__main__ import collection
from openapi_server.models.patch_notes import PatchNotes # noqa: E501
from openapi_server import util
def get_patchnotes(): # noqa: E501
"""get_patchnotes
def patchnotes_date_get(date): # noqa: E501
"""patchnotes_date_get
returns list of all unseen Patch notes from the user # noqa: E501
:param date:
:type date: str
:rtype: Union[List[PatchNotes], Tuple[List[PatchNotes], int], Tuple[List[PatchNotes], int, Dict[str, str]]
"""
return 'do some magic!'
# TODO Implement this:
# try:
# formatted_date = response_data.strftime('%Y-%m-%d')
# logging.error(formatted_date)
# logging.info("valid date")
# except ValueError:
# logging.error("Not valid date")
return date
# _date = util.deserialize_date(date)
# return 'do some magic!'
def patch_note_delete(patch_id): # noqa: E501
"""patch_note_delete
def patchnotes_patch_iddelete(patch_id): # noqa: E501
"""patchnotes_patch_iddelete
deletes one Patch note # noqa: E501
@@ -32,8 +52,8 @@ def patch_note_delete(patch_id): # noqa: E501
return 'do some magic!'
def post_patchnotes(body=None): # noqa: E501
"""post_patchnotes
def patchnotes_post(body=None): # TODO done for now
"""patchnotes_post
creates new Patch notes # noqa: E501
@@ -43,9 +63,11 @@ def post_patchnotes(body=None): # noqa: E501
:rtype: Union[List[PatchNotes], Tuple[List[PatchNotes], int], Tuple[List[PatchNotes], int, Dict[str, str]]
"""
patch_notes = body
with conn.cursor() as cur:
player_name = player_post_request.name
player_id = uuid.uuid4()
cur.execute(f"INSERT INTO player VALUES ('{player_id}','{player_name}');")
conn.commit() # noqa: E501
return 'do some magic!'
logging.error('patch notes' + str(patch_notes))
if patch_notes is None:
return Response(json_util.dumps({'error': 'No patch notes provided'}), status=400)
# Insert the document into the MongoDB collection
posted_patch_id = collection.insert_one(patch_notes)
return Response(json_util.dumps(f'patch with ID: {posted_patch_id} was created'), mimetype='application/json',
status=200)
+3 -4
View File
@@ -1,9 +1,8 @@
from connexion.apps.flask_app import FlaskJSONEncoder
from connexion.jsonifier import JSONEncoder as ConnexionJSONEncoder
from openapi_server.models.base_model import Model
class JSONEncoder(FlaskJSONEncoder):
class JSONEncoder(ConnexionJSONEncoder):
include_nulls = False
def default(self, o):
@@ -16,4 +15,4 @@ class JSONEncoder(FlaskJSONEncoder):
attr = o.attribute_map[attr]
dikt[attr] = value
return dikt
return FlaskJSONEncoder.default(self, o)
return ConnexionJSONEncoder.default(self, o)
+17 -17
View File
@@ -12,21 +12,21 @@ class User(Model):
Do not edit the class manually.
"""
def __init__(self, last_note_checked=None): # noqa: E501
def __init__(self, last_seen_date=None): # noqa: E501
"""User - a model defined in OpenAPI
:param last_note_checked: The last_note_checked of this User. # noqa: E501
:type last_note_checked: str
:param last_seen_date: The last_seen_date of this User. # noqa: E501
:type last_seen_date: date
"""
self.openapi_types = {
'last_note_checked': str
'last_seen_date': date
}
self.attribute_map = {
'last_note_checked': 'lastNoteChecked'
'last_seen_date': 'lastSeenDate'
}
self._last_note_checked = last_note_checked
self._last_seen_date = last_seen_date
@classmethod
def from_dict(cls, dikt) -> 'User':
@@ -40,22 +40,22 @@ class User(Model):
return util.deserialize_model(dikt, cls)
@property
def last_note_checked(self) -> str:
"""Gets the last_note_checked of this User.
def last_seen_date(self) -> date:
"""Gets the last_seen_date of this User.
:return: The last_note_checked of this User.
:rtype: str
:return: The last_seen_date of this User.
:rtype: date
"""
return self._last_note_checked
return self._last_seen_date
@last_note_checked.setter
def last_note_checked(self, last_note_checked: str):
"""Sets the last_note_checked of this User.
@last_seen_date.setter
def last_seen_date(self, last_seen_date: date):
"""Sets the last_seen_date of this User.
:param last_note_checked: The last_note_checked of this User.
:type last_note_checked: str
:param last_seen_date: The last_seen_date of this User.
:type last_seen_date: date
"""
self._last_note_checked = last_note_checked
self._last_seen_date = last_seen_date
+37 -26
View File
@@ -4,31 +4,12 @@ info:
title: announcementService
version: 1.0.0
servers:
- url: /
- url: http://127.0.0.1:8080/api
paths:
/patchnotes:
get:
description: returns list of all unseen Patch notes from the user
operationId: get_patchnotes
responses:
"200":
content:
application/json:
schema:
items:
$ref: '#/components/schemas/patch_notes'
type: array
description: returns list of all unseen Patch notes from the user
"404":
description: no Patch notes found
"500":
description: "Internal Server error, Failed to get Patch Notes"
tags:
- Patchnotes
x-openapi-router-controller: openapi_server.controllers.patchnotes_controller
post:
description: creates new Patch notes
operationId: post_patchnotes
operationId: patchnotes_post
requestBody:
content:
application/json:
@@ -46,10 +27,40 @@ paths:
tags:
- Patchnotes
x-openapi-router-controller: openapi_server.controllers.patchnotes_controller
/patchnotes/{date}:
get:
description: returns list of all unseen Patch notes from the user
operationId: patchnotes_date_get
parameters:
- example: 2025-01-02
explode: false
in: path
name: date
required: true
schema:
format: date
type: string
style: simple
responses:
"200":
content:
application/json:
schema:
items:
$ref: '#/components/schemas/patch_notes'
type: array
description: returns list of all unseen Patch notes from the user
"404":
description: no Patch notes found
"500":
description: "Internal Server error, Failed to get Patch Notes"
tags:
- Patchnotes
x-openapi-router-controller: openapi_server.controllers.patchnotes_controller
/patchnotes/{patchID}:
delete:
description: deletes one Patch note
operationId: patch_note_delete
operationId: patchnotes_patch_iddelete
parameters:
- explode: false
in: path
@@ -76,7 +87,7 @@ components:
patchID: 29e80bcc-5981-4a52-99e1-373442dea9b9
title: Patch note 1
changes: changes
date: date
date: 2025-01-02
properties:
patchID:
format: uuid
@@ -94,9 +105,9 @@ components:
title: patch_notes
user:
example:
lastNoteChecked: f00fa08d-0cd8-4c05-9409-5e75aa2d4f68
lastSeenDate: 2025-01-02
properties:
lastNoteChecked:
format: uuid
lastSeenDate:
format: date
title: lastNoteChecked
type: string
+2 -2
View File
@@ -10,7 +10,7 @@ class BaseTestCase(TestCase):
def create_app(self):
logging.getLogger('connexion.operation').setLevel('ERROR')
app = connexion.App(__name__, specification_dir='../openapi/')
app = connexion.App(__name__ , specification_dir='../openapi/')
app.app.json_encoder = JSONEncoder
app.add_api('openapi.yaml', pythonic_params=True)
app.add_api('openapi.yaml', pythonic_params=True, base_path='/api')
return app.app
@@ -2,10 +2,12 @@ import unittest
from flask import json
import openapi_server
from openapi_server.models.patch_notes import PatchNotes # noqa: E501
from openapi_server.test import BaseTestCase
class TestDefaultController(BaseTestCase):
"""DefaultController integration test stubs"""
@@ -23,7 +25,8 @@ class TestDefaultController(BaseTestCase):
headers=headers)
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
response = self.client.get('/patchnotes',)
assert response.status_code == 200
def test_patch_note_delete(self):
"""Test case for patch_note_delete
@@ -1,62 +1,167 @@
import datetime
import logging
import unittest
import unittest.mock as mock
from datetime import datetime
from flask import json
from flask import json, url_for
import openapi_server
from openapi_server.models.patch_notes import PatchNotes # noqa: E501
import app
from openapi_server.test import BaseTestCase
logging.basicConfig(level=logging.DEBUG)
class TestPatchnotesController(BaseTestCase):
"""PatchnotesController integration test stubs"""
def test_get_patchnotes(self):
def setUp(self):
self.app = app.app
self.app.config['SERVER_NAME'] = '127.0.0.1:8080'
print('url map:' + str(self.app.url_map))
@unittest.mock.patch(
'openapi_server.controllers.patchnotes_controller.patchnotes_date_get')
def test_get_patchnotes(self, mock_get_patchnotes):
"""Test case for get_patchnotes
"""
headers = {
headers = {
'Accept': 'application/json',
}
logging.error('self client:' + str(self.client))
logging.error('mock get patchnotes' + str(mock_get_patchnotes))
response = self.client.open(
'/patchnotes',
'/patchnotes/2025-01-02',
method='GET',
headers=headers)
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
headers=headers
)
response_data = response.data.decode('utf-8').strip().strip('\"')
logging.error(response_data + "response_data")
response_data_type = type(response_data)
logging.error("response_data_type:" + str(response_data_type))
logging.error("response data" + response_data)
response_data = datetime.strptime(response_data, '%Y-%m-%d').date()
logging.error(str(response_data) + "response_data after format")
try:
formatted_date = response_data.strftime('%Y-%m-%d')
logging.error(formatted_date)
logging.info("valid date")
except ValueError:
logging.error("Not valid date")
self.assert200(response, 'Response body is : ' + response.data.decode('utf-8'))
@unittest.mock.patch('openapi_server.controllers.patchnotes_controller.patchnotes_date_get')
def test_get_patchnotes_404(self, mock_get_patchnotes): # DONE
"""Test case for get_patchnotes
"""
headers = {
'Accept': 'application/json',
}
with self.app.test_request_context():
full_url = url_for('get_patchnotes', date='2023-01-01', _external=True)
logging.error("Full URL: " + full_url)
url = '/api/patchnotes/{date}'.format(date='2023-01-01')
logging.error(f"request URL: {url}")
logging.error('self client:' + str(self.client))
logging.error('mock get patchnotes' + str(mock_get_patchnotes))
logging.error('self name stuff:' + str(self.app.config['SERVER_NAME']))
response = self.client.open(
url,
method='GET',
headers=headers
)
logging.error(f"Response Status Code: {response.status_code}")
logging.error(f"Response Data: {response.data.decode('utf-8')}")
self.assert404(response, 'Response body is : ' + response.data.decode('utf-8'))
@unittest.mock.patch('openapi_server.controllers.patchnotes_controller.patchnotes_patch_iddelete')
def test_patch_note_delete(self, balala):
def test_patch_note_delete(self):
"""Test case for patch_note_delete
"""
headers = {
headers = {
}
response = self.client.open(
'/patchnotes/{patch_id}'.format(patch_id='patch_id_example'),
method='DELETE',
headers=headers)
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
def test_post_patchnotes(self):
patch_note_mock = {
"changes": "test changes",
"date": "2025-01-02",
"patchID": "29e80bcc-5981-4a52-99e1-373442dea9b9",
"title": "test patch"
}
self.client.open(
'/patchnotes',
method='POST',
headers=headers,
data=json.dumps(patch_note_mock),
content_type='application/json'
)
response = self.client.open(
'/patchnotes/{patch_id}'.format(patch_id=patch_note_mock['patchID']),
method='DELETE',
headers=headers
)
self.assert200(response, 'Response body is : ' + response.data.decode('utf-8'))
@unittest.mock.patch('openapi_server.controllers.patchnotes_controller.patchnotes_patch_iddelete')
def test_patch_note_delete_not_found(self, balala):
"""Test case for patch_note_delete
"""
headers = {
}
patch_note_mock = {
"changes": "test changes",
"date": "2025-01-02",
"patchID": "29e80bcc-5981-4a52-99e1-373442dea9b9",
"title": "test patch"
}
response = self.client.open(
'/patchnotes/{patch_id}'.format(patch_id=''),
method='DELETE',
headers=headers
)
self.assert404(response, 'Response body is : ' + response.data.decode('utf-8'))
@unittest.mock.patch('openapi_server.controllers.patchnotes_controller.patchnotes_post')
def test_post_patchnotes(self, balala):
"""Test case for post_patchnotes
"""
patch_notes = openapi_server.PatchNotes()
headers = {
post_patchnotes_mock = {
"changes": "test changes",
"date": "2025-01-02",
"patchID": "29e80bcc-5981-4a52-99e1-373442dea9b9",
"title": "test patch"
}
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
response = self.client.open(
'/patchnotes',
method='POST',
headers=headers,
data=json.dumps(patch_notes),
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.decode('utf-8'))
data=json.dumps(post_patchnotes_mock),
content_type='application/json'
)
self.assert200(response, 'Response body is : ' + response.data.decode('utf-8'))
if __name__ == '__main__':