Skip to content

Commit

Permalink
Merge branch 'main' into update-SDK
Browse files Browse the repository at this point in the history
  • Loading branch information
Bishoy-at-pieces authored May 20, 2024
2 parents 4c02bfc + 3917a80 commit 779988e
Show file tree
Hide file tree
Showing 10 changed files with 172 additions and 97 deletions.
4 changes: 2 additions & 2 deletions src/pieces/copilot/ask_command.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pieces.settings import Settings
from pieces.copilot.pieces_ask_websocket import AskWebsocketWS
from pieces.copilot.pieces_ask_websocket import AskWebsocket
import os
from pieces.gui import show_error
from pieces.assets.assets_api import AssetsCommandsApi
Expand All @@ -9,7 +9,7 @@
from pieces_os_client.models.qgpt_relevance_input import QGPTRelevanceInput
from pieces_os_client.api.qgpt_api import QGPTApi

ask_websocket = AskWebsocketWS()
ask_websocket = AskWebsocket()
def ask(query, **kwargs):
relevant = {"iterable":[]}
files = kwargs.get("files",None)
Expand Down
4 changes: 2 additions & 2 deletions src/pieces/copilot/pieces_ask_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@



class AskWebsocketWS:
class AskWebsocket:

def __new__(cls,*args,**kwargs):
if not hasattr(cls, 'instance'):
cls.instance = super(AskWebsocketWS, cls).__new__(cls)
cls.instance = super(AskWebsocket, cls).__new__(cls)
return cls.instance

def __init__(self):
Expand Down
14 changes: 10 additions & 4 deletions tests/ask_command_test.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import unittest
from unittest.mock import patch, MagicMock
from pieces.commands.commands_functions import ask,startup
from pieces.copilot import ask
from pieces.settings import Settings
import sys
from io import StringIO
from pieces.copilot.conversations import conversation_handler

class TestAskCommand(unittest.TestCase):
@patch('pieces.commands.commands_functions.ask')
def test_ask_command(self, mock_ask_question):
startup()
@patch('pieces.copilot.ask')
@patch('builtins.input', return_value='y')
def test_ask_command(self, mock_input,mock_ask_question):
Settings.startup()

stdout = sys.stdout
sys.stdout = StringIO()
Expand All @@ -25,6 +28,9 @@ def test_ask_command(self, mock_ask_question):

# Check if the function prints a string
self.assertIsInstance(result, str)

# delete the conversation created
conversation_handler(delete=True)


if __name__ == '__main__':
Expand Down
47 changes: 31 additions & 16 deletions tests/autocommit_command_test.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,31 @@
import unittest
from unittest.mock import patch
from pieces.commands.autocommit.autocommit import git_commit
from pieces.commands import startup
from unittest.mock import patch,MagicMock
from pieces.autocommit.autocommit import git_commit
from pieces.settings import Settings

class TestGitCommit(unittest.TestCase):
@patch('pieces.commands.autocommit.autocommit.subprocess.run')
@patch('pieces.commands.autocommit.autocommit.get_current_working_changes')
@patch('pieces.commands.autocommit.autocommit.get_repo_issues')
@patch('pieces.commands.autocommit.autocommit.pos_client.QGPTApi')
@patch('pieces.commands.autocommit.autocommit.get_git_repo_name')
@patch('pieces.autocommit.autocommit.subprocess.run')
@patch('pieces.autocommit.autocommit.get_current_working_changes')
@patch('pieces.autocommit.autocommit.get_repo_issues')
@patch('pieces_os_client.QGPTApi')
@patch('pieces.autocommit.autocommit.get_git_repo_name')
@patch('builtins.input', return_value='y')
def test_git_commit(self,mock_input,mock_qgpt_api, mock_get_repo_name, mock_get_issues, mock_get_changes, mock_subprocess):
# TODO: Fix this test to give better results and test the commit command

# Setup
startup()
# TODO: Fix the return value of the qgpt api
# Setup
mock_qgpt_api.return_value.relevance.return_value.answer.answers.iterable[0].text = 'test: implement changes according to summary'
Settings.startup()

# Setup mock answer
mock_answer = MagicMock()
mock_answer.text = 'The message is: test: this is an autocommit message'

# Setup mock api response
mock_api_response = MagicMock()
mock_api_response.answer.answers.iterable = [mock_answer]

# Set the return value for the relevance method
mock_qgpt_api.return_value.relevance.return_value = mock_api_response


# Rest of your test code
mock_get_repo_name.return_value = ('username', 'repo')
Expand All @@ -31,16 +40,16 @@ def test_git_commit(self,mock_input,mock_qgpt_api, mock_get_repo_name, mock_get_
mock_get_issues.assert_not_called()

# Check that the subprocess.run was called with the expected arguments
mock_subprocess.assert_called_once_with(["git", "commit", "-m", 'test: implement changes according to summary'], check=True)
mock_subprocess.assert_called_once_with(["git", "commit", "-m", 'test: this is an autocommit message'], check=True)

# Call the function with issue_flag=True, push=False
git_commit(issue_flag=True, push=False)

# Check that the get_repo_issues was called
mock_get_issues.assert_called_once_with('username', 'repo')
mock_get_issues.assert_called_once_with()

# Check that the subprocess.run was called with the expected arguments
mock_subprocess.assert_called_with(["git", "commit", "-m", 'Test changes summary (issue: #1)'], check=True)
mock_subprocess.assert_called_with(["git", "commit", "-m", 'test: this is an autocommit message (issue: #1)'], check=True)

# Call the function with issue_flag=False, push=True
git_commit(issue_flag=False, push=True)
Expand All @@ -54,5 +63,11 @@ def test_git_commit(self,mock_input,mock_qgpt_api, mock_get_repo_name, mock_get_
# Check that the subprocess.run was called with the expected arguments for git push
mock_subprocess.assert_called_with(["git", "push"], check=True)

# Test with no issues
mock_get_issues.return_value = []
git_commit(issue_flag=True, push=False)
mock_get_issues.assert_called_once_with()
mock_subprocess.assert_called_with(["git", "commit", "-m", 'test: this is an autocommit message'], check=True)

if __name__ == '__main__':
unittest.main()
25 changes: 12 additions & 13 deletions tests/create_and_delete_test.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
import unittest
from unittest.mock import patch
from pieces.commands import create_asset, delete_asset,startup
from pieces.commands import commands_functions
from pieces.api.assets import get_asset_by_id
from pieces.assets import AssetsCommands, AssetsCommandsApi
from pieces.settings import Settings
from pieces_os_client.models.asset import Asset

class TestAssetFunctions(unittest.TestCase):
class TestCreateDeleteFunctions(unittest.TestCase):

@patch('builtins.input', side_effect=['y', 'y'])
@patch('pyperclip.paste', return_value='print("Hello, World!")')
def test_create_and_delete_asset(self, mock_paste, mock_input):
startup()
Settings.startup()
# Call create_asset and store the returned asset
create_asset()
AssetsCommands.create_asset()

# Ensure that it is correctly assigned to the current asset
new_asset=list(commands_functions.current_asset)[0]
new_asset=AssetsCommands.current_asset


asset_object = get_asset_by_id(new_asset)
asset_object = AssetsCommandsApi.get_asset_snapshot(new_asset)

get_asset_by_id(new_asset) # Checks that the asset was created with no errors
self.assertIsInstance(asset_object,Asset)

# Call delete_asset
delete_asset()
AssetsCommands.delete_asset()

# Check that the asset was deleted
try:
get_asset_by_id(new_asset)
except Exception:
AssetsCommandsApi.get_asset_snapshot(new_asset)
except: # Asset not found!
self.assertTrue(True)


if __name__ == '__main__':
unittest.main()
30 changes: 30 additions & 0 deletions tests/edit_command_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import unittest
from unittest.mock import patch
from pieces.assets import AssetsCommands,AssetsCommandsApi
from pieces.settings import Settings

class TestEditCommand(unittest.TestCase):
@patch('builtins.input', side_effect='y')
@patch('pyperclip.paste', return_value='print("Hello, World!")')
def test_edit_command(self,mock_paste,mock_buildins):
Settings.startup()

NAME = "TEST"
CLASSIFICATION = "java"

AssetsCommands.create_asset() # create new asset to test on

AssetsCommands.edit_asset(name = NAME, classification=CLASSIFICATION) # change some asset meta data


asset = AssetsCommandsApi.update_asset_snapshot(AssetsCommands.current_asset)

self.assertEqual(asset.name,NAME)
self.assertEqual(asset.formats.iterable[0].classification.specific.value.lower(),CLASSIFICATION.lower())

AssetsCommands.delete_asset() # Delete the created asset


if __name__ == '__main__':
unittest.main()

10 changes: 5 additions & 5 deletions tests/list_command_test.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import unittest
from unittest.mock import patch, MagicMock,Mock
from pieces.commands import list_command,startup
from pieces.commands import commands_functions
from pieces.commands.list_command import ListCommand
from pieces.settings import Settings
from io import StringIO
import sys

class TestListCommand(unittest.TestCase):
def test_list_command(self):
startup()
Settings.startup()
for i in ["models","assets","apps"]:
# Redirect stdout to a buffer
stdout = sys.stdout
sys.stdout = StringIO()

# Call the function that prints to stdout
list_command(type = i)
ListCommand.list_command(type = i)

# Get the output and restore stdout
assets = sys.stdout.getvalue()
Expand All @@ -31,7 +31,7 @@ def test_list_command(self):
if i == "models":
model = assets_list[-1]
assets_list = assets_list[:-1] # Remove the line which conatin the current model text
self.assertEqual(model,f"Currently using: {change_model.get_current_model_name()} with uuid {change_model.model_id}")
self.assertEqual(model,f"Currently using: {Settings.model_name} with uuid {Settings.model_id}")

# Check if the string represents a numbered list
self.assertTrue(all(line.strip().startswith(str(i+1)) for i, line in enumerate(assets_list) if line.strip()))
Expand Down
78 changes: 78 additions & 0 deletions tests/open_and_save_command_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import unittest
from unittest.mock import patch
from pieces.assets import AssetsCommands,AssetsCommandsApi
from pieces.settings import Settings
import sys
from io import StringIO
import random,os
import json
from pieces.utils import sanitize_filename

class TestOpenSaveCommand(unittest.TestCase):
def test_open_command(self,ITEM_INDEX=None):
Settings.startup()
stdout = sys.stdout
sys.stdout = StringIO()


assets_length = len(AssetsCommandsApi.get_assets_snapshot())


sys.stdout = StringIO()
if not ITEM_INDEX:
ITEM_INDEX = random.randint(1,assets_length)

# Act
AssetsCommands.open_asset(ITEM_INDEX = ITEM_INDEX)

result_open = sys.stdout.getvalue()

sys.stdout = stdout # Reset sys.stdout to its original state

result_list = result_open.strip().split('\n')

name = result_list[-6].removeprefix('Name: ')
created_readable = result_list[-5].removeprefix('Created: ')
updated_readable = result_list[-4].removeprefix('Updated: ')
type = result_list[-3].removeprefix('Type: ')
language = result_list[-2].removeprefix('Language: ')
code_snippet_path = result_list[-1].removeprefix('Code: ')


with open(Settings.extensions_dir) as f:
language_extension_mapping = json.load(f)
self.assertTrue(os.path.exists(code_snippet_path)) # assert that the code snippet file exists
self.assertEqual(os.path.splitext(code_snippet_path)[-1], language_extension_mapping[language]) # assert that the file extension matches the language
self.assertEqual(os.path.splitext(os.path.basename(code_snippet_path))[0], sanitize_filename(name))

return code_snippet_path # Return the code path to be tested for the save command

@patch('builtins.input', side_effect=['y','y'])
@patch('pyperclip.paste', return_value='print("Hello, World!")')
def test_save_command(self, mock_paste,mock_buildins):
Settings.startup()
TEXT = "TEST SNIPPET CODE"
# Call create_asset to create a new asset to test on
AssetsCommands.create_asset() # Create a hello world asset

AssetsCommandsApi.assets_snapshot = {AssetsCommands.current_asset:None} # Update the asset cache

code_snippet_path = self.test_open_command(ITEM_INDEX=1) # Open the created asset

with open(code_snippet_path,'w') as f:
f.write(TEXT)

AssetsCommands.update_asset() # Run the save


code = AssetsCommandsApi.update_asset_snapshot(AssetsCommands.current_asset).formats.iterable[0].fragment.string.raw

self.assertEqual(code, TEXT) # Check if the code was saved

AssetsCommands.delete_asset() # Delete the asset



if __name__ == '__main__':
unittest.main()

52 changes: 0 additions & 52 deletions tests/open_command_test.py

This file was deleted.

Loading

0 comments on commit 779988e

Please sign in to comment.