Skip to content

Commit

Permalink
[New Build] New job added to sync newly released gh-pages src files f…
Browse files Browse the repository at this point in the history
…rom website repo. (#27)

* added .idea and .vscode folder

* added  animated progress function

Prints animated progress bar as per the completed steps

* tests to check animated progress bar function added

Smoke test with comparison of output tests added in conjuncture

* File handler created

* tests for files handler class and its method added

passing all runs

* __init__.py files

* updated file path

Now starts from the current directory

* Create utils.py

* updated .idea and .vscode as folders

* src package initalised

* Initialization steps to run on environment changes or updates

* app entrypoint

* added files to create a container

* Docker patch 1 (#4)

* docker file updated.

-  enabled PYTHONUNBUFFERED var to true to get knative logs.

- pip installation of packages from requirement.txt without caching.

- project dir changed and stored in env var.

- entry-point for app.py updated.

* stable docker image with app entrypoint V0.2

- Changed copy requirements.txt file dir path.

- added new env var to store secretary app files and change `WORKDIR` to run the app.py.

- Corrected error from RUN --> CMD to run the app.py

* Create codeql-analysis.yml (#5)

- Security analysis to run weekly on every Saturday @23:59 UTC

* Added CodeCov Integration (#6)

* Codecov integration (#7)

* Added CodeCov Integration

* CHANGED PATH

* Quick fix1 (#9)

* deleted workflows

- Deleted workflow since the directory was wrong.

* Updated to not run on pull requests to master branch

* removed error causing keyword

-  Removed run: changed it with upload_coverage:

- Added name parameter to cloning repository step.

- Upload Coverage to Codecov step added new with parameters.

* Azure functions integreation (#10)

* funcitons initialised

- Azure functions initialized.

* Update __init__.py

* Revert "Update __init__.py"

This reverts commit ae4df7a.

* Updated .gitignore added ide config files

* Changed logging statement.

* Delete .idea directory

* Delete .vscode directory

* initalised authHandler

- Initialized authHandler to encode and decode keys.

* Update .coveragerc

* Codecov integration Patch (#13)

* Added CodeCov Integration

* CHANGED PATH

* Updated yaml structure

line 11 error causing keywords changed and updated

* Update .coveragerc

* Circleci project setup (#15)

* Add .circleci/config.yml

* Updated CricleCI config to run unit tests 

added steps to run all tests in `tests/` folder.

* Updated config.yml

* Pre build-patch 1a (still functionality is to be added) (#16)

* Back merge (#11)

* Merging to add docker file for Artifact Registry build (#3)

* added .idea and .vscode folder

* added  animated progress function

Prints animated progress bar as per the completed steps

* tests to check animated progress bar function added

Smoke test with comparison of output tests added in conjuncture

* File handler created

* tests for files handler class and its method added

passing all runs

* __init__.py files

* updated file path

Now starts from the current directory

* Create utils.py

* updated .idea and .vscode as folders

* src package initalised

* Initialization steps to run on environment changes or updates

* app entrypoint

* added files to create a container

* Docker patch 1 (#4)

* docker file updated.

-  enabled PYTHONUNBUFFERED var to true to get knative logs.

- pip installation of packages from requirement.txt without caching.

- project dir changed and stored in env var.

- entry-point for app.py updated.

* stable docker image with app entrypoint V0.2

- Changed copy requirements.txt file dir path.

- added new env var to store secretary app files and change `WORKDIR` to run the app.py.

- Corrected error from RUN --> CMD to run the app.py

* Create codeql-analysis.yml (#5)

- Security analysis to run weekly on every Saturday @23:59 UTC

* Added CodeCov Integration (#6)

* Codecov integration (#7)

* Added CodeCov Integration

* CHANGED PATH

* Quick fix1 (#9)

* deleted workflows

- Deleted workflow since the directory was wrong.

* Updated to not run on pull requests to master branch

* removed error causing keyword

-  Removed run: changed it with upload_coverage:

- Added name parameter to cloning repository step.

- Upload Coverage to Codecov step added new with parameters.

* Azure functions integreation (#10)

* funcitons initialised

- Azure functions initialized.

* Update __init__.py

* Revert "Update __init__.py"

This reverts commit ae4df7a.

* Updated .gitignore added ide config files

* Changed logging statement.

* Delete .idea directory

* Delete .vscode directory

* added .pem files

* source files added

* Class App initialized

* Update requirements.txt

- packages for pyjwt and cryptography added.
- version for azure-functions specified.

* added new auth functions

- get_hash_key function added.
- jwt token generator added.

* removed __inti__.py files from test folder

* directory structure changed

- multiple files comin in a single commit (I know the consequences)
 - @Maverick099

* removed importing handlers module file in __init___

- This will make us use handlers as submodule inside bin

* ignoring tests/*/res folders

* Update .gitignore

* updated bin module imports

* passing GithubAppApi tests

- passing tests since http response returning 401 error.

* Update gitignore (#17)

* Back merge (#11)

* Merging to add docker file for Artifact Registry build (#3)

* added .idea and .vscode folder

* added  animated progress function

Prints animated progress bar as per the completed steps

* tests to check animated progress bar function added

Smoke test with comparison of output tests added in conjuncture

* File handler created

* tests for files handler class and its method added

passing all runs

* __init__.py files

* updated file path

Now starts from the current directory

* Create utils.py

* updated .idea and .vscode as folders

* src package initalised

* Initialization steps to run on environment changes or updates

* app entrypoint

* added files to create a container

* Docker patch 1 (#4)

* docker file updated.

-  enabled PYTHONUNBUFFERED var to true to get knative logs.

- pip installation of packages from requirement.txt without caching.

- project dir changed and stored in env var.

- entry-point for app.py updated.

* stable docker image with app entrypoint V0.2

- Changed copy requirements.txt file dir path.

- added new env var to store secretary app files and change `WORKDIR` to run the app.py.

- Corrected error from RUN --> CMD to run the app.py

* Create codeql-analysis.yml (#5)

- Security analysis to run weekly on every Saturday @23:59 UTC

* Added CodeCov Integration (#6)

* Codecov integration (#7)

* Added CodeCov Integration

* CHANGED PATH

* Quick fix1 (#9)

* deleted workflows

- Deleted workflow since the directory was wrong.

* Updated to not run on pull requests to master branch

* removed error causing keyword

-  Removed run: changed it with upload_coverage:

- Added name parameter to cloning repository step.

- Upload Coverage to Codecov step added new with parameters.

* Azure functions integreation (#10)

* funcitons initialised

- Azure functions initialized.

* Update __init__.py

* Revert "Update __init__.py"

This reverts commit ae4df7a.

* Updated .gitignore added ide config files

* Changed logging statement.

* Delete .idea directory

* Delete .vscode directory

* added .pem files

* source files added

* Class App initialized

* Update requirements.txt

- packages for pyjwt and cryptography added.
- version for azure-functions specified.

* added new auth functions

- get_hash_key function added.
- jwt token generator added.

* removed __inti__.py files from test folder

* directory structure changed

- multiple files comin in a single commit (I know the consequences)
 - @Maverick099

* removed importing handlers module file in __init___

- This will make us use handlers as submodule inside bin

* ignoring tests/*/res folders

* Update .gitignore

* updated bin module imports

* passing GithubAppApi tests

- passing tests since http response returning 401 error.

* Update .gitignore

* Circle ci patch1 (#18)

* Updated config.yml

* Updated config.yml

* Updated config.yml

* Updated config.yml

* Config.py updated with for coverage generation

- coverage job updated with new "Install coverage.py and generate report" run.

* Added line to ignore /htmlcov folder

* updated import package name

* formatting changes

* commented unused imports

* corrected run statement

* updated import for bin

* Update setup.py

* updated to include source and omit all setup.py files

* packages updated

-  Think this is the problem causing area, since bin.handlers is pointed out to be partially insitalised.

* Update .gitignore

* Added missing project files manually. (#19)

* missing __init__.py added

* missing exception_handler.py added

* missing github_api_handler.py added

* missing response_handler.py added

* Circle ci patch (#20)

* Updated config.yml

* Updated config.yml

* Updated config.yml

* Updated config.yml

* Config.py updated with for coverage generation

- coverage job updated with new "Install coverage.py and generate report" run.

* Added line to ignore /htmlcov folder

* updated import package name

* formatting changes

* commented unused imports

* corrected run statement

* updated import for bin

* Update setup.py

* updated to include source and omit all setup.py files

* packages updated

-  Think this is the problem causing area, since bin.handlers is pointed out to be partially insitalised.

* config updated

 - as per issue #12  updated according to comments.

* Updated config.yml

* Updated config.yml

* Updated config.yml

* Updated config.yml

* Updated config.yml

* Lib and import changes (#21)

* deleted all bin files due to name change

* bin_tests -> lib_tests

* updated with new package name

* updated with new package name in imports

* changed package name to lib

* changed files moved to new folder

* bin files moved to lib

* updated pre-written .gitignore to not ignore lib/

* response_handler import changed

* authHanler imported directly instead of a package import.

* pep changes

* removed inverted commas from xml file name parameter

* added lines to report and generate xml file

* Readme (#22)

* readme file added

* Delete codecov.yml

* added Codacy badge

* New Api Methods Added (#23)

* pipe symbol added to end of table

* AccessTokenPermission class added with ENUM helper classes

This class is used to generate payload for permission parameter while posting new access token for repos.

* Tests added for AccessTokenPermission Class

- Passed while running all tests using terminal.

* Commendted since raising unwanted errors in CI

* GithubAccessToken class tests added

* Object to hold Github access token received from API

- Additional helper functions also added.

* spelling changes in comments

* commented unused imports

* checks if given requested permissions are empty or not

* function create_access_token now returns access token object GithubAccessToken

* posting tree.

* Added a HTTP patch module which returns a RESPONSE object

* Mocks tests added

* added release api

* tests for release api

* unclosed file closed

* setup updated for lib.data package

* moved data classes and imported the same

* Dataclass for GithubAPI added

* Update githubDataClass.py

* added trigger_workflow api

* success tests for trigger_api added with mocks

* added Repository data class

* new jobs_test package added

* test for Repository data class added

* Jobs addition: Add new Blog  (#24)

* imported only required class App

* package name changed to bot

* package removed

* All requests redirected to App

* checks the request body for JSON structure and keywords

* Azure Functions file for bot

* added where parameter to point current folder

* imports optimized

* removed unused imports

* Delete webhook.py

* added Message class to imports

* Added constants.py to hold constant data

* Added Webhook dataclass to hold incoming webhook data

* optimised import

* updated version

* removed webhook azure functions entry point

* updated ci for changed package name

* coverage ci updated with changed package name

* renamed to match semantic standard for test files

* added GithubTag dataclass

* added GithubTag as import

* added get_tag api function test and updates

- updated to use class parameters instead of function parameters increasing reusability.

* added get_tag api tests and updates

* github api tag mock added

* added GithubCommit data class

* added GithubCommit tests

* Github commit mocks added

* github commit test added

* gitub commit test added

* name change

* GithubCommit added to imports

* Push blog page routed

* renamed meta.json

* blog pages update job added

* config for paths and file named added

* env read added

* updates

* removed not required tests

* [Addition] Job to update blog repo gh-pages source code added. (#26)

- On new release from [coders-asylum.github.io](https://github.com/Coders-Asylum/coders-asylum.github.io)
  -  If `BlogPage.dart` or `BlogPostPage.dart` has changes then the files from [blog](https://github.com/Coders-Asylum/blog) will also be updated by a commit by the bot.

##Commits
* imported only required class App

* package name changed to bot

* package removed

* All requests redirected to App

* checks the request body for JSON structure and keywords

* Azure Functions file for bot

* added where parameter to point current folder

* imports optimized

* removed unused imports

* Delete webhook.py

* added Message class to imports

* Added constants.py to hold constant data

* Added Webhook dataclass to hold incoming webhook data

* optimised import

* updated version

* removed webhook azure functions entry point

* updated ci for changed package name

* coverage ci updated with changed package name

* renamed to match semantic standard for test files

* added GithubTag dataclass

* added GithubTag as import

* added get_tag api function test and updates

- updated to use class parameters instead of function parameters increasing reusability.

* added get_tag api tests and updates

* github api tag mock added

* added GithubCommit data class

* added GithubCommit tests

* Github commit mocks added

* github commit test added

* gitub commit test added

* name change

* GithubCommit added to imports

* Push blog page routed

* renamed meta.json

* blog pages update job added

* config for paths and file named added

* env read added

* updates

* removed not required tests

* added commit_files unit test

* updated to dynamic path for __config_file_path var

* env variable reading issue resolved

replaces environ.get string \\n  pattern with \n

* removed testing block

* bot folder tests initialized

* removed unused imports

* change permissions to  default parameter with default value as None

* src package tests added

* removed unused import

* Update jobs.py

* push_new_blog_page tests added with mocks

* changed payload type to list to append messages

* target path added

* path parameter updated for both files
  • Loading branch information
Maverick099 authored Apr 12, 2022
1 parent 8efa77b commit 6128914
Show file tree
Hide file tree
Showing 10 changed files with 938 additions and 316 deletions.
26 changes: 15 additions & 11 deletions bot/src/jobs.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from json import load
import os.path
from json import load, dumps
from logging import info
from os import environ
from lib import Response
Expand All @@ -9,23 +10,21 @@
class Jobs:
_webhook: Webhook
_response: Response
__config_file_path: str = './res/config.json'
__config_file_path: str = os.path.join(os.path.dirname(__file__), './res/config.json')

def __init__(self):
self._response = Response(status_code=202, status='Accepted', data=Message.no_processing_required)
config_file = open(self.__config_file_path)
self.config_data: dict = load(config_file)

def status(self):
pass
config_file.close()

def push_new_blog_page(self) -> Response:
""" Pushes the new blog-page code to blog repository src folder and then triggers the build workflow to build the new blog pages out of the new release build.
Returns:
"""
payload: dict = {"message": ''}
payload: list = []
# repos
website_repo: Repository = Repository(owner='Coders-Asylum', repo='coders-asylum.github.io', branch='production')
target_repos: Repository = Repository(owner='Coders-Asylum', repo='blog', branch='master')
Expand Down Expand Up @@ -53,21 +52,26 @@ def push_new_blog_page(self) -> Response:
# update blog page file
if f['filename'] == self.config_data['blog_page']['path']:
blog_page_file_content: str = github_api_website.get_raw_data(path=self.config_data['blog_page']['path'])
blog_page_tree: GitTree = GitTree(tree_type=TreeType.BLOB, path=self.config_data['blog_page']['path'], content=blog_page_file_content)
blog_page_tree: GitTree = GitTree(tree_type=TreeType.BLOB, path=self.config_data['blog_page']['target_path'], content=blog_page_file_content)
github_api_target.set_token(access_tkn=target_access_tkn)

target_ref = github_api_target.commit_files(files=[blog_page_tree], message=f'New Release: {release[0].tag} \n link: https://github.com/{website_repo.owner}/{website_repo.name}/releases/tag/{release[0].tag}')
info(f'[I] New Blog Page File Committed url:{target_ref.url}')
payload['message'] = payload['message'] + f'New Blog Page File Committed url:{target_ref.url}\n'
payload.append(f'New Blog Page File Committed url:{target_ref.url}')
self._response.status_code = 200

# update blog page file
elif f['filename'] == self.config_data['blog_post_page']['path']:
blog_post_page_file_content:str = github_api_website.get_raw_data(path=self.config_data['blog_post_page']['path'])
blog_post_page_tree: GitTree = GitTree(tree_type=TreeType.BLOB, path=self.config_data['blog_page']['path'], content=blog_post_page_file_content)
blog_post_page_file_content: str = github_api_website.get_raw_data(path=self.config_data['blog_post_page']['path'])
blog_post_page_tree: GitTree = GitTree(tree_type=TreeType.BLOB, path=self.config_data['blog_page']['target_path'], content=blog_post_page_file_content)
github_api_target.set_token(access_tkn=target_access_tkn)

target_ref = github_api_target.commit_files(files=[blog_post_page_tree], message=f'New Release: {release[0].tag} \n link: https://github.com/{website_repo.owner}/{website_repo.name}/releases/tag/{release[0].tag}')
info(f'[I] New Blog Post Page File Committed url:{target_ref.url}')
payload['message'] = payload['message'] + f'New Blog Post Page File Committed url:{target_ref.url}\n'
payload.append(f'New Blog Page File Committed url:{target_ref.url}')
self._response.status_code = 200

if payload:
self._response.data = dumps({"message": payload})

return self._response
6 changes: 4 additions & 2 deletions bot/src/res/config.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
{
"blog_page": {
"name": "BlogPage.dart",
"path": "lib/pages/BlogPage.dart"
"path": "lib/pages/BlogPage.dart",
"target_path": "src/pages/BlogPage.dart"
},
"blog_post_page": {
"name": "BlogPostPage.dart",
"path": "lib/pages/BlogPostPage.dart"
"path": "lib/pages/BlogPostPage.dart",
"target_path": "src/pages/BlogPostPage.dart"
}
}
2 changes: 1 addition & 1 deletion lib/handlers/authHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def get_hash_key(key: str, req: func.HttpRequest) -> str:


def generate_jwt_token(payload: dict) -> str:
key: str = environ.get('AUTH_KEY')
key: str = environ.get('AUTH_KEY').replace(r'\n', '\n')
key_bytes: bytes = bytes(key, 'UTF-8')
_pvt_key = serialization.load_pem_private_key(data=key_bytes, password=None, backend=default_backend)
return encode(payload=payload, key=_pvt_key, algorithm='RS256')
Expand Down
25 changes: 2 additions & 23 deletions lib/handlers/github_api_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,9 @@ def commit_files(self, files: list[GitTree], message: str = 'New commit') -> Git

# update branch ref
_ref: dict = {"sha": _commit.sha}
print(_commit.sha)
_r: Response = ResponseHandlers.http_patch(url=ref_url, headers=self._header, data=dumps(_ref))
if _r.status_code != 200:
print(f'[E] Error while updating ref: {_r.status_code} {_r.status} ')
print(_r.data)
return GithubRefObject(data=_r.data)

def get_release(self, latest: bool = True) -> list[GithubRelease]:
Expand Down Expand Up @@ -316,14 +314,14 @@ def get_app_installations(self) -> list[GithubAppInstallations]:

res = ResponseHandlers.curl_get_response(url, self.headers)
if res.status_code != 200:
print(f'App installation was not received: {res.status_code} {res.for_status} {res.data}')
print(f'App installation was not received: {res.status_code} {res.status} {res.data}')

_data: list = loads(res.data)
for d in _data:
_li.append(GithubAppInstallations(id=d['id'], org=d['account']['login'], tkn=d['access_tokens_url']))
return _li

def create_access_token(self, repos: list[str], permissions: AccessTokenPermission, org: str) -> GithubAccessToken:
def create_access_token(self, repos: list[str], org: str, permissions: AccessTokenPermission = None) -> GithubAccessToken:
"""
Creates access tokens for the app installations to authenticate as an app in a repo
Expand Down Expand Up @@ -356,22 +354,3 @@ def create_access_token(self, repos: list[str], permissions: AccessTokenPermissi

if __name__ == '__main__':
pass
# app = GithubAppApi(app_id=os.environ.get('APP_ID'))
# access_tkn1: AccessTokenPermission = AccessTokenPermission()
#
# access_tkn1.set(permission=GithubPermissions.CONTENTS, access=AccessType.READ)
#
# _access_tkn = app.create_access_token(repos=['fuzzy-train'], permissions=None, org='Coders-Asylum')
#
# _owner = 'Coders-Asylum'
# _repo = 'fuzzy-train'
# _branch = 'test_branch'
# api = GithubAPIHandler(owner=_owner, branch=_branch, repo=_repo)
# _expected_contents = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis at tellus at urna condimentum mattis pellentesque id. Lobortis elementum nibh tellus molestie nunc non. Vestibulum lectus mauris ultrices ' \
# 'eros in. Odio ut sem nulla pharetra. Aliquam nulla facilisi cras fermentum odio eu feugiat pretium. Nam libero justo laoreet sit amet cursus. Amet nulla facilisi morbi tempus iaculis urna. Massa id neque aliquam vestibulum morbi blandit cursus risus at. Mi in nulla ' \
# 'posuere sollicitudin aliquam ultrices sagittis orci. Lobortis feugiat vivamus at augue eget arcu dictum. Sit amet consectetur adipiscing elit pellentesque. Tortor posuere ac ut consequat semper viverra nam libero justo. Eu nisl nunc mi ipsum faucibus vitae. Semper ' \
# 'feugiat nibh sed pulvinar proin gravida hendrerit. Habitant morbi tristique senectus et netus et. Tempor orci dapibus ultrices in iaculis nunc. Amet risus nullam eget felis eget nunc lobortis mattis. Posuere sollicitudin aliquam ultrices sagittis orci. '
#
# new_file: GitTree = GitTree(path='custom_card_design/test/change_file_test.txt', tree_type=TreeType.BLOB, content=_expected_contents)
# api.set_token(access_tkn=_access_tkn)
# api.commit_files(files=[new_file], message='New test file')
Empty file added tests/bot_tests/__init__.py
Empty file.
Empty file.
117 changes: 117 additions & 0 deletions tests/bot_tests/src_tests/test_jobs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import os
from json import dumps
from unittest import TestCase, main, mock

from bot.src import Jobs
from lib import Response
from tests.mocks.mocked_classes import MockedGithubAPIHandler, MockedGithubAppApi


class TestJobs(TestCase):
g_api_mock = MockedGithubAPIHandler()
g_app_api_mock = MockedGithubAppApi()

@mock.patch('lib.handlers.GithubAppApi.__init__')
@mock.patch('lib.handlers.GithubAPIHandler.get_release')
@mock.patch('lib.handlers.GithubAPIHandler.get_tag')
@mock.patch('lib.handlers.GithubAPIHandler.get_commit')
@mock.patch('lib.handlers.GithubAppApi.create_access_token')
@mock.patch('lib.handlers.GithubAPIHandler.get_raw_data')
@mock.patch('lib.handlers.GithubAPIHandler.commit_files')
def test_push_new_blog_page_both_file_update(self, commit_files_mock, get_raw_data_mock, create_access_token_mock, get_commit_mock, get_tag_mock, get_releases_mock, mock_app_api):
# mocked patches
commit_files_mock.side_effect = self.g_api_mock.commit_files
get_raw_data_mock.side_effect = self.g_api_mock.get_raw_data
create_access_token_mock.side_effect = self.g_app_api_mock.create_access_token
get_commit_mock.side_effect = self.g_api_mock.get_commit_all_files
get_tag_mock.side_effect = self.g_api_mock.get_tag
get_releases_mock.side_effect = self.g_api_mock.get_release
mock_app_api.return_value = None

jobs = Jobs()
expected_response = Response(status_code=200, status='Accepted',
data=dumps({"message": ["New Blog Page File Committed url:https://api.github.com/repos/Coders-Asylum/fuzzy-train/git/refs/heads/test_branch", "New Blog Page File Committed url:https://api.github.com/repos/Coders-Asylum/fuzzy-train/git/refs/heads/test_branch"]}))
actual_res = jobs.push_new_blog_page()

self.assertEqual(actual_res.status_code, expected_response.status_code)
self.assertEqual(actual_res.status, expected_response.status)
self.assertEqual(actual_res.data, expected_response.data)

@mock.patch('lib.handlers.GithubAppApi.__init__')
@mock.patch('lib.handlers.GithubAPIHandler.get_release')
@mock.patch('lib.handlers.GithubAPIHandler.get_tag')
@mock.patch('lib.handlers.GithubAPIHandler.get_commit')
@mock.patch('lib.handlers.GithubAppApi.create_access_token')
@mock.patch('lib.handlers.GithubAPIHandler.get_raw_data')
@mock.patch('lib.handlers.GithubAPIHandler.commit_files')
def test_push_new_blog_page_blog_file_update(self, commit_files_mock, get_raw_data_mock, create_access_token_mock, get_commit_mock, get_tag_mock, get_releases_mock, mock_app_api):
# mocked patches
commit_files_mock.side_effect = self.g_api_mock.commit_files
get_raw_data_mock.side_effect = self.g_api_mock.get_raw_data
create_access_token_mock.side_effect = self.g_app_api_mock.create_access_token
get_commit_mock.side_effect = self.g_api_mock.get_commit_blog_file
get_tag_mock.side_effect = self.g_api_mock.get_tag
get_releases_mock.side_effect = self.g_api_mock.get_release
mock_app_api.return_value = None

jobs = Jobs()
expected_response = Response(status_code=200, status='Accepted', data=dumps({"message": ["New Blog Page File Committed url:https://api.github.com/repos/Coders-Asylum/fuzzy-train/git/refs/heads/test_branch"]}))
actual_res = jobs.push_new_blog_page()

self.assertEqual(actual_res.status_code, expected_response.status_code)
self.assertEqual(actual_res.status, expected_response.status)
self.assertEqual(actual_res.data, expected_response.data)

@mock.patch('lib.handlers.GithubAppApi.__init__')
@mock.patch('lib.handlers.GithubAPIHandler.get_release')
@mock.patch('lib.handlers.GithubAPIHandler.get_tag')
@mock.patch('lib.handlers.GithubAPIHandler.get_commit')
@mock.patch('lib.handlers.GithubAppApi.create_access_token')
@mock.patch('lib.handlers.GithubAPIHandler.get_raw_data')
@mock.patch('lib.handlers.GithubAPIHandler.commit_files')
def test_push_new_blog_page_blog_page_file_update(self, commit_files_mock, get_raw_data_mock, create_access_token_mock, get_commit_mock, get_tag_mock, get_releases_mock, mock_app_api):
# mocked patches
commit_files_mock.side_effect = self.g_api_mock.commit_files
get_raw_data_mock.side_effect = self.g_api_mock.get_raw_data
create_access_token_mock.side_effect = self.g_app_api_mock.create_access_token
get_commit_mock.side_effect = self.g_api_mock.get_commit_blog_page_file
get_tag_mock.side_effect = self.g_api_mock.get_tag
get_releases_mock.side_effect = self.g_api_mock.get_release
mock_app_api.return_value = None

jobs = Jobs()
expected_response = Response(status_code=200, status='Accepted', data=dumps({"message": ["New Blog Page File Committed url:https://api.github.com/repos/Coders-Asylum/fuzzy-train/git/refs/heads/test_branch"]}))
actual_res = jobs.push_new_blog_page()

self.assertEqual(actual_res.status_code, expected_response.status_code)
self.assertEqual(actual_res.status, expected_response.status)
self.assertEqual(actual_res.data, expected_response.data)

@mock.patch('lib.handlers.GithubAppApi.__init__')
@mock.patch('lib.handlers.GithubAPIHandler.get_release')
@mock.patch('lib.handlers.GithubAPIHandler.get_tag')
@mock.patch('lib.handlers.GithubAPIHandler.get_commit')
@mock.patch('lib.handlers.GithubAppApi.create_access_token')
@mock.patch('lib.handlers.GithubAPIHandler.get_raw_data')
@mock.patch('lib.handlers.GithubAPIHandler.commit_files')
def test_push_new_blog_page_no_file_update(self, commit_files_mock, get_raw_data_mock, create_access_token_mock, get_commit_mock, get_tag_mock, get_releases_mock, mock_app_api):
# mocked patches
commit_files_mock.side_effect = self.g_api_mock.commit_files
get_raw_data_mock.side_effect = self.g_api_mock.get_raw_data
create_access_token_mock.side_effect = self.g_app_api_mock.create_access_token
get_commit_mock.side_effect = self.g_api_mock.get_commit
get_tag_mock.side_effect = self.g_api_mock.get_tag
get_releases_mock.side_effect = self.g_api_mock.get_release
mock_app_api.return_value = None

jobs = Jobs()
expected_response = Response(status_code=202, status='Accepted', data=dumps({"message": "Current payload does not require any processing"}))
actual_res = jobs.push_new_blog_page()

self.assertEqual(actual_res.status_code, expected_response.status_code)
self.assertEqual(actual_res.status, expected_response.status)
self.assertEqual(actual_res.data, expected_response.data)


if __name__ == "__main__":
main()
27 changes: 25 additions & 2 deletions tests/lib_tests/handlers_test/test_github_api_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,31 @@ def test_post_blob(self, mock_func): # Data that will be posted to the Github s
# expected_tree_data = loads(posted_tree.tree)
# self.assertEqual(actual_tree_data, expected_tree_data)

def test_commit_files(self):
pass
@mock.patch('lib.handlers.ResponseHandlers.curl_get_response')
@mock.patch('lib.handlers.ResponseHandlers.curl_post_response')
@mock.patch('lib.handlers.ResponseHandlers.http_patch')
def test_commit_files(self,mock_patch, mock_post,mock_get ):
# mocks
mock_get.side_effect = self.mockedResponse.mocked_http_get_response
mock_post.side_effect = self.mockedResponse.mocked_http_post_response
mock_patch.side_effect = self.mockedResponse.mocked_http_patch_response

expected_ref = loads(self.g_mock_success.patch_git_ref().data)

posting_contents = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Duis at tellus at urna condimentum mattis pellentesque id. Lobortis elementum nibh tellus molestie nunc non. Vestibulum lectus mauris ultrices ' \
'eros in. Odio ut sem nulla pharetra. Aliquam nulla facilisi cras fermentum odio eu feugiat pretium. Nam libero justo laoreet sit amet cursus. Amet nulla facilisi morbi tempus iaculis urna. Massa id neque aliquam vestibulum morbi blandit cursus risus at. Mi in nulla ' \
'posuere sollicitudin aliquam ultrices sagittis orci. Lobortis feugiat vivamus at augue eget arcu dictum. Sit amet consectetur adipiscing elit pellentesque. Tortor posuere ac ut consequat semper viverra nam libero justo. Eu nisl nunc mi ipsum faucibus vitae. Semper ' \
'feugiat nibh sed pulvinar proin gravida hendrerit. Habitant morbi tristique senectus et netus et. Tempor orci dapibus ultrices in iaculis nunc. Amet risus nullam eget felis eget nunc lobortis mattis. Posuere sollicitudin aliquam ultrices sagittis orci. '

file: GitTree = GitTree(path='custom_card_design/test/change_file_test.txt', tree_type=TreeType.BLOB, content=posting_contents)
# setting a mock token
self.g.set_token(access_tkn=mocked_token())
actual: GithubRefObject = self.g.commit_files(files=[file], message='New test file')

self.assertEqual(actual.url, expected_ref['url'])
self.assertEqual(actual.ref, expected_ref['ref'])
self.assertEqual(actual.obj, expected_ref['object'])
self.assertEqual(actual.nodeId, expected_ref['node_id'])

@mock.patch('lib.handlers.ResponseHandlers.curl_get_response', side_effect=mockedResponse.mocked_http_get_response)
def test_get_latest_release(self, mock_func):
Expand Down
Loading

0 comments on commit 6128914

Please sign in to comment.