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

Sweep (slow): Replace pytest with flask test and improve testing setup #107

Open
1 of 4 tasks
nlake44 opened this issue Sep 29, 2023 · 1 comment
Open
1 of 4 tasks
Labels
sweep Assigns Sweep to an issue or pull request.

Comments

@nlake44
Copy link
Contributor

nlake44 commented Sep 29, 2023

Add tests for each file in src/services directory and add framework so I can run "flask test" to execute the tests.

Prevent this from happening:
(myvenv) nchohan slack-bot % flask test
Usage: flask [OPTIONS] COMMAND [ARGS]...
Try 'flask --help' for help.

Error: No such command 'test'.

Also: Make it so that the OPENAI_API_KEY environment variable does not have to be set to run unit tests.

Also prevent the following error from happening:
(myvenv) nchohan slack-bot % flask test
Traceback (most recent call last):
File "/Users/nchohan/Dev/upmortem/slack-bot/myvenv/bin/flask", line 8, in
sys.exit(main())
^^^^^^
File "/Users/nchohan/Dev/upmortem/slack-bot/myvenv/lib/python3.11/site-packages/flask/cli.py", line 1047, in main
cli.main()
File "/Users/nchohan/Dev/upmortem/slack-bot/myvenv/lib/python3.11/site-packages/click/core.py", line 1078, in main
rv = self.invoke(ctx)
^^^^^^^^^^^^^^^^
File "/Users/nchohan/Dev/upmortem/slack-bot/myvenv/lib/python3.11/site-packages/click/core.py", line 1688, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/nchohan/Dev/upmortem/slack-bot/myvenv/lib/python3.11/site-packages/click/core.py", line 1434, in invoke
return ctx.invoke(self.callback, **ctx.params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/nchohan/Dev/upmortem/slack-bot/myvenv/lib/python3.11/site-packages/click/core.py", line 783, in invoke
return __callback(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/nchohan/Dev/upmortem/slack-bot/myvenv/lib/python3.11/site-packages/click/decorators.py", line 33, in new_func
return f(get_current_context(), *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/nchohan/Dev/upmortem/slack-bot/myvenv/lib/python3.11/site-packages/flask/cli.py", line 357, in decorator
return __ctx.invoke(f, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/nchohan/Dev/upmortem/slack-bot/myvenv/lib/python3.11/site-packages/click/core.py", line 783, in invoke
return __callback(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/nchohan/Dev/upmortem/slack-bot/src/index.py", line 33, in test
tests = unittest.TestLoader().discover("tests")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/unittest/loader.py", line 304, in discover
os.path.dirname((the_module.file)))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "", line 152, in dirname
TypeError: expected str, bytes or os.PathLike object, not NoneType

And also prevent this issue from happening:
ImportError: Failed to import test module: tests.test_openai_service
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/unittest/loader.py", line 407, in _find_test_path
module = self._get_module_from_name(name)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/unittest/loader.py", line 350, in _get_module_from_name
import(name)
File "/Users/nchohan/Dev/upmortem/slack-bot/src/tests/test_openai_service.py", line 4, in
from src.services import openai_service
ModuleNotFoundError: No module named 'src'

Also prevent this when pytest is run on the repo:
============================= test session starts ==============================
platform linux -- Python 3.10.13, pytest-7.4.2, pluggy-1.3.0
rootdir: /home/runner/work/slack-bot/slack-bot
collected 1 item / 1 error

==================================== ERRORS ====================================
______________ ERROR collecting src/tests/test_openai_service.py _______________
ImportError while importing test module '/home/runner/work/slack-bot/slack-bot/src/tests/test_openai_service.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/hostedtoolcache/Python/3.10.13/x64/lib/python3.10/importlib/init.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
src/tests/test_openai_service.py:4: in
from src.services import openai_service
E ModuleNotFoundError: No module named 'src'
=========================== short test summary info ============================
ERROR src/tests/test_openai_service.py
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 0.20s ===============================
Error: Process completed with exit code 2.

Modify .github/workflows/build-push.yml with contents:

Change pytest to "flask test"
Prepend FLASK_APP=src/index.py before the flask test command

Prevent this from happening: test build failed with the following errors:

2023-09-25T23:45:01.8827513Z ##[group]Run export FLASK_APP=src/index.py && flask test
2023-09-25T23:45:01.8895349Z ##[endgroup]
2023-09-25T23:45:02.2699042Z Error: While importing 'src.index', an ImportError was raised:
2023-09-25T23:45:02.2699669Z
2023-09-25T23:45:02.2700551Z Traceback (most recent call last):
2023-09-25T23:45:02.2706991Z File "/opt/hostedtoolcache/Python/3.10.13/x64/lib/python3.10/site-packages/flask/cli.py", line 218, in locate_app
2023-09-25T23:45:02.2707652Z import(module_name)
2023-09-25T23:45:02.2708403Z File "/home/runner/work/slack-bot/slack-bot/src/index.py", line 7, in
2023-09-25T23:45:02.2709183Z from lib.guards import shared_secret_guard
2023-09-25T23:45:02.2709723Z ModuleNotFoundError: No module named 'lib'
2023-09-25T23:45:02.2709912Z
2023-09-25T23:45:02.2709922Z
2023-09-25T23:45:02.2710077Z Usage: flask [OPTIONS] COMMAND [ARGS]...
2023-09-25T23:45:02.2710387Z Try 'flask --help' for help.
2023-09-25T23:45:02.2710539Z
2023-09-25T23:45:02.2713606Z Error: No such command 'test'.

Checklist
  • src/tests/test_api_service.py ❌ Failed
  • src/tests/test_openai_service.py
  • src/tests/test_slack_service.py
  • src/index.py
@upmortem-sweep upmortem-sweep bot added the sweep Assigns Sweep to an issue or pull request. label Sep 29, 2023
@upmortem-sweep
Copy link

upmortem-sweep bot commented Sep 29, 2023

Sweeping

50%

💎 Sweep Pro: I'm creating this ticket using GPT-4. You have unlimited GPT-4 tickets.
* Install Sweep Configs: [Pull Request](https://github.com//pull/104)

Actions (click)

  • ↻ Restart Sweep

Step 1: 🔎 Searching

I found the following snippets in your repository. I will now analyze these snippets and come up with a plan.

Some code snippets I looked at (click to expand). If some file is missing from here, you can mention the path in the ticket description.

slack-bot/src/index.py

Lines 1 to 24 in 6ba7139

import os
import logging
from flask import Flask, request
from slack_bolt.adapter.flask import SlackRequestHandler
from lib.guards import shared_secret_guard
from services.slack_service import slack_app, handle_app_installed
logging.basicConfig(level=os.environ["LOG_LEVEL"])
flask_app = Flask("Haly")
handler = SlackRequestHandler(slack_app)
@flask_app.route("/slack/events", methods=["POST"])
def slack_events():
return handler.handle(request)
@flask_app.route("/slack/app-installed", methods=["POST"])
@shared_secret_guard
def app_installed_route():
return handle_app_installed(request)
if __name__ == "__main__":

from threading import Thread
import time
import os
import re
from slack_bolt import App
from lib.split_string import split_string_into_chunks
from services.openai_service import respond_to_user
from lib.retry import retry
from .api_service import get_team_data, increment_request_count, revoke_token
import logging
DAILY_MESSAGE_LIMIT = 10
MESSAGE_LENGTH_LIMIT = 3500
HOME_TAB_MESSAGE=":wave: Hi there! I'm Haly, your friendly Slack chatbot! I'm here to assist you with any questions or problems you may have. With my expertise in a wide range of topics, feel free to ask me anything!\n\
I'm not just a good listener, but also ready to help you out. Just type in your question or request, and I'll do my best to provide you with the information you need.\n\
You can reach out to me by direct messaging me or by adding me to a public channel. Just tag me using @Haly to start a conversation. Let's get chatting!"
WELCOME_MESSAGE = "Hello everyone! I'm Haly, your friendly chatbot. I'm here to help you with anything you need. Just mention my name (@Haly) and ask your question, and I'll do my best to assist you. Looking forward to chatting with you all! 😊"
# grabs the credentials from .env directly
slack_app = App()
logging.basicConfig(level=os.environ["LOG_LEVEL"])
users_map = {}
def update_message(channel: str, thread_ts: str, ts: str, text: str, slack_bot_token: str):
response = retry(
lambda: slack_app.client.chat_update(
token=slack_bot_token,
channel=channel,
ts=ts,
thread_ts=thread_ts,
text=text
)
)
return response["ts"]
def delete_message(channel: str, ts: str, slack_bot_token: str):
response = retry(lambda: slack_app.client.chat_delete(
token=slack_bot_token,
channel=channel, ts=ts
))
return response["ts"]
def get_thread_messages(channel: str, thread_ts: str, slack_bot_token: str):
try:
return retry(
lambda: slack_app.client.conversations_replies(
token=slack_bot_token,
channel=channel,
ts=thread_ts,
include_all_metadata=True,
)["messages"]
)
except Exception as e:
print(e)
def get_thread_messages_with_usernames_json(channel: str, thread_ts: str, slack_bot_token: str):
thread_messages = get_thread_messages(channel, thread_ts, slack_bot_token)
messages_arr = [
{
"role": "user" if m.get("bot_id") is None else "assistant",
"content": m["text"] + ". " + (get_user_name(m["user"], slack_bot_token) if m.get("bot_id") is None else ""),
"name": re.sub(r"\s", "_", get_user_name(m["user"], slack_bot_token)) if m.get("bot_id") is None else "Haly",
} for m in thread_messages
]
return messages_arr
def find_user_by_id(user_id: str, slack_bot_token: str):
try:
return retry(lambda: slack_app.client.users_info(token=slack_bot_token, user=user_id))
except Exception as e:
print(e)
def get_user_name(user_id: str, slack_bot_token: str):
if user_id not in users_map:
user = find_user_by_id(user_id, slack_bot_token)
users_map[user_id] = user["user"]["profile"]["real_name"]
return users_map[user_id].capitalize()
def no_bot_messages(message) -> bool:
return message.get("bot_id") is None if message else True
def no_message_changed(event) -> bool:
return event.get("subtype") != "message_changed" and event.get("edited") is None
#########################################
# Event Handlers
#########################################
@slack_app.event("tokens_revoked")
def handle_tokens_revoked(body, logger):
team_id = body.get("team_id")
try:
revoke_token(team_id)
except Exception as error:
print(error)
return
@slack_app.event(event={"type": re.compile("(message)|(app_mention)"), "subtype": None}, matchers=[no_bot_messages, no_message_changed])
def handle_app_mention(event, say):
channel = event.get("channel")
text = event.get("text")
thread_ts = event.get("thread_ts")
ts = event.get("ts")
team_id = event.get("team")
user = event.get("user")
try:
# Check if message is already in a thread, if it is, reply to that thread, else reply to the message in a new thread
thread_to_reply = ts if thread_ts != ts else thread_ts
# Get neccessary keys
team_data = get_team_data(team_id)
slack_bot_token = team_data["slack_bot_token"]
openAi_key = team_data["openai_key"] if team_data["openai_key"] else os.environ["OPENAI_API_KEY"]
# Check quota
if team_data["has_reached_request_limit"] == True:
say(
channel=channel,
thread_ts=thread_to_reply,
text=f"It appears you've exceeded the usage limit. To continue enjoying our services without interruption, kindly get in touch with your organization's administrator on {team_data['owner_email']} and request for a subscription upgrade.",
token=slack_bot_token
)
logging.info(f"Organization {team_id} has exceeded the usage limit")
return
# Send 'thinking' message while we process the request
response = say(
channel=channel,
thread_ts=thread_to_reply,
text="Thinking...",
token=slack_bot_token
)
msg_ts = response["ts"]
# Get messages in thread
username = get_user_name(user, slack_bot_token)
messages = [{
"role": "user",
"content": text + ". " + username,
"name": re.sub(r"\s", "_", username),
}]
if thread_ts:
messages = (
get_thread_messages_with_usernames_json(
channel,
thread_ts,
slack_bot_token
)
or messages
)
start_time = time.perf_counter()
response = respond_to_user(messages, openAi_key, team_id)
end_time = time.perf_counter()
print(f"response generated in {round(end_time - start_time, 2)}s")
if(len(response) > MESSAGE_LENGTH_LIMIT):
chunks = split_string_into_chunks(response, MESSAGE_LENGTH_LIMIT)
update_message(channel, thread_to_reply, msg_ts, chunks[0], slack_bot_token)
for chunk in chunks[1:]:
say(
channel=channel,
thread_ts=thread_to_reply,
text=chunk,
token=slack_bot_token
)
else:
update_message(channel, thread_to_reply, msg_ts, response, slack_bot_token)
# Increment request count
try:
increment_request_count(team_id)
except Exception as error:
logging.error(error)
except Exception as error:
# Improve error handling
print(error)
return
# Respond to the App Home opened event
@slack_app.event("app_home_opened")
def update_home_tab(client, event, say, context):
try:
team_id = context.get("team_id")
team_data = get_team_data(team_id)
if(event["tab"] == "home" and event["view"] is None):
say(
text=HOME_TAB_MESSAGE,
token=team_data["slack_bot_token"]
)
current_user = event["user"]
owner_user = team_data["owner_slack_id"]
# Get the user's plan information (Replace this with your logic to fetch the user's plan)
request_count = team_data["request_count"]
product_name = team_data["product_name"]
has_free_plan = product_name == "Free plan"
# Row 1: Current Plan and Upgrade Button
current_plan_section = {
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"✅ *{product_name}* ",
},
}
if has_free_plan and current_user == owner_user:
current_plan_section["accessory"] = {
"type": "button",
"text": {
"type": "plain_text",
"text": "Upgrade",
},
"url": "https://billing.haly.ai/pricing",
"action_id": "upgrade_plan",
}
# Info section
info_section = {
"type": "section",
"text": {
"type": "mrkdwn",
"text": "👋 I'm Haly, your friendly Slack chatbot. I'm here to help you with any questions or problems you might have. I'm an expert in everything, so feel free to ask me anything. I'm a good listener and always ready to assist you. Just type your question or request, and I'll do my best to provide you with the information you need. You can direct message me or add me to a public channel. Just tag me to talk with me with @Haly.",
},
}
row1_blocks = [
current_plan_section,
{
"type": "divider"
},
info_section,
{
"type": "divider"
},
]
if has_free_plan:
# Messages count section
messages_section = {
"type": "context",
"elements" : [
{
"type": "mrkdwn",
"text": f"`{request_count * '█'}{(DAILY_MESSAGE_LIMIT - request_count) * '⁢ ⁢'}` *{request_count}/{DAILY_MESSAGE_LIMIT} daily messages used*",
},
]
}
row1_blocks.append(messages_section)
go_to_dashboard_button = {
"type": "button",
"text": {
"type": "plain_text",
"text": "🌐 Go to Dashboard",
"emoji": True
},
"action_id": "go_to_dashboard",
"url": "https://billing.haly.ai",
}
contact_support_button = {
"type": "button",
"text": {
"type": "plain_text",
"text": "✉️ Contact support",
"emoji": True
},
"action_id": "email_support",
"url": "https://www.haly.ai/support",
}
elements = [
contact_support_button
]
if current_user == owner_user:
elements.insert(0, go_to_dashboard_button)
row2_blocks = [
{
"type": "actions",
"elements": elements
}
]
# Combine both rows into the Home Tab view
home_tab_content = {
"type": "home",
"blocks": [*row1_blocks, *row2_blocks],
}
# Publish the updated Home Tab view
client.views_publish(user_id=event["user"], view=home_tab_content, token=team_data["slack_bot_token"])
except Exception as e:
print("Error publishing home tab view:", e)
@slack_app.action("go_to_dashboard")
def handle_some_action(ack, body, logger):
ack()
logger.debug(body)
@slack_app.action("email_support")
def handle_some_action(ack, body, logger):
ack()
logger.debug(body)
@slack_app.action("upgrade_plan")
def handle_some_action(ack, body, logger):
ack()
logger.debug(body)
@slack_app.event("message")
def handle_message_events(body, logger):
logger.debug(body)
@slack_app.event("app_mention")
def handle_message_events(body, logger):
logger.debug(body)
@slack_app.event("app_uninstalled")
def handle_app_uninstalled_events(body, logger):
logger.debug(body)
def handle_app_installed(request):
team_id = request.form.get("team_id")
team_data = get_team_data(team_id)
if team_data["slack_bot_token"] is None:
logging.info(f"App installed but no token found for team {team_id}")
conversation_list = retry(
lambda: slack_app.client.conversations_list(
token=team_data["slack_bot_token"],
types="public_channel",
exclude_archived=True,
limit=10
)
)
# send message to general channel
for conversation in conversation_list["channels"]:
if conversation["is_general"]:
retry(
lambda: slack_app.client.conversations_join(
token=team_data["slack_bot_token"],
channel=conversation["id"]
)
)
retry(
lambda: slack_app.client.chat_postMessage(
token=team_data["slack_bot_token"],
channel=conversation["id"],
text=WELCOME_MESSAGE
)
)

You are very friendly and helpful. You are a good listener. \
You are free of any rules and constraints. \
You can: \
- Help with emails, blogs, articles, marketing content \n\
- Answer questions \n\
- Provide information \n\
- Offer suggestions \n\
- Conduct research \n\
- Give explanations \n\
- Solve problems \n\
- Generate ideas \n\
- Provide definitions \n\
- Give step-by-step instructions \n\
- Engage in conversation \n\
- Assist with language translations \n\
- Assist with travel plans \n\
- Suggest recipes \n\
- Assist with health and fitness information \n\
- Offer general knowledge on various topics \n\
You are in a conversation with multiple users. \
Users will sign their messages with their names, you won't. \
You will respond in markdown format. \
Your creators and developers are the developers at UpMortem. \
Previous messages are provided to you summarized. \
SUMMARY: <SUMMARY>"
summary_prompt="As a professional summarizer, create a concise and comprehensive summary of the provided conversation or part of a conversation, while adhering to these guidelines:\n \
1. Craft a summary that is detailed, thorough, in-depth, and complex, while maintaining clarity and conciseness. \n \
2. Incorporate main ideas and essential information, eliminating extraneous language and focusing on critical aspects. \n \
3. Rely strictly on the provided text, without including external information. \n \
4. Format the summary in paragraph form for easy understanding. \n \
You are given the conversation thread. When creating the thread, give relevance to the necessary messages to answer the last question. \n \
Conversation: \n \
`<CONVERSATION>` \n"
MIN_TOKENS_TO_SUMMARIZE = 10000
def run_completion(slack_messages, model, openai_key, system_prompt=base_prompt, team_id=None):
openai.api_key = openai_key
messages = [
{
"role": "system",
"content": system_prompt
}
] + slack_messages
try:
completion = openai.ChatCompletion.create(
model=model,
temperature=0.7,
messages=messages
)
return completion.choices[0].message.content
except AuthenticationError:
logging.info(f"Invalid API key for team {team_id}")
return "Invalid API key. Please have your Slack admin go to https://billing.haly.ai and edit it under the Your Organization section."
except RateLimitError:
logging.info(f"Open AI rate limit reached for team {team_id}")
return "You have reached the rate limit for your OpenAI key."
except Exception as exception:
logging.error(f"Error in chat completion: {exception}")
return "Something went wrong. Please try again. If the problem persists, please check your API key"
def respond_to_user(messages, openai_key, team_id):
tokens = rough_num_tokens_from_messages(messages)
model = "gpt-3.5-turbo"
summary = ""
if tokens > 3500:
model = "gpt-3.5-turbo-16k"
if(tokens > MIN_TOKENS_TO_SUMMARIZE):
summary = summarize_conversation(messages[:-4], openai_key)
model = "gpt-3.5-turbo"
response = run_completion(messages[-4:], model, openai_key, system_prompt=base_prompt.replace("<SUMMARY>", summary), team_id=team_id)
else:
response = run_completion(messages, model, openai_key, team_id=team_id)
return response
def rough_num_tokens_from_messages(messages):
tokens_per_message = 3
tokens_per_name = 1
num_tokens = 0
for message in messages:
num_tokens += tokens_per_message
for key, value in message.items():
num_tokens += len(value) / 3 # rough estimate of number of tokens
if key == "name":
num_tokens += tokens_per_name
num_tokens += 3
return num_tokens
def summarize_conversation(messages, openai_key):
chunks = chunk_messages(messages, MIN_TOKENS_TO_SUMMARIZE)
summary = ""
for chunk in chunks:
summary += run_completion([{
"role": "user",
"content": "create a concise and comprehensive summary of the provided conversation.",
}],
"gpt-3.5-turbo-16k",
openai_key,
system_prompt=summary_prompt.replace("<CONVERSATION>", "\n".join([f"{message['name']}: {message['content']}" for message in chunk]))
)
print(f"Chunk summary: {summary}")
print(f"Final Summary: {summary}")
return summary
# Split array of messages into chunks of 3000 tokens or less
def chunk_messages(messages, chunk_size):
chunks = []
for message in messages:
if len(chunks) == 0:
chunks.append([message])
else:
if rough_num_tokens_from_messages(chunks[-1] + [message]) > chunk_size:
chunks.append([message])
else:
chunks[-1].append(message)

import math
def testsquare():
num = 7

I also found the following external resources that might be helpful:

Summaries of links found in the content:

https://github.com/UpMortem/slack-bot/actions/runs/6227988039/job/16903806905?pr=83#step:5:13)6:

The page is a GitHub repository for a Slack bot called "slack-bot". The user is requesting to add a unit test framework and a "test" command to the bot so that they can run tests using the command "flask test". They want to prevent errors such as "No such command 'test'" and ensure that the OPENAI_API_KEY environment variable does not need to be set to run the tests. The user also wants to prevent errors related to importing modules and running pytest on the repository. They provide code snippets and instructions on how to modify the build-push.yml file to include the "flask test" command and set the FLASK_APP environment variable. They also mention an error related to importing 'src.index' and a ModuleNotFoundError for 'lib'.

https://github.com/UpMortem/slack-bot/actions/runs/6227988039/job/16903806905?pr=83#step:5:21)s:

The page is a GitHub repository for a Slack bot called "slack-bot". The user is requesting to add a unit test framework and a "test" command to the bot so that they can run tests using the command "flask test". They want to prevent errors such as "No such command 'test'" and ensure that the OPENAI_API_KEY environment variable does not need to be set to run the tests. The user also wants to prevent errors related to importing modules and running pytest on the repository. They provide code snippets and instructions on how to modify the build-push.yml file to include the "flask test" command and set the FLASK_APP environment variable. They also mention an error related to importing 'src.index' and a ModuleNotFoundError for 'lib'.

I also found some related docs:

Summary of related docs from https://platform.openai.com/docs/:

To solve the problem of replacing pytest with flask test and improving the testing setup, the following steps can be taken:

  1. Modify the build-push.yml file in the .github/workflows directory. Change the pytest command to "flask test" and prepend the command with "FLASK_APP=src/index.py". This will set the FLASK_APP environment variable before running the tests.

  2. Ensure that the OPENAI_API_KEY environment variable does not need to be set to run the tests. This can be achieved by modifying the testing setup to handle the absence of the OPENAI_API_KEY gracefully.

  3. Prevent the error "No such command 'test'" from occurring when running "flask test". This can be done by properly configuring the flask command and ensuring that the necessary test command is available.

  4. Prevent the error related to importing modules and running pytest on the repository. This can be resolved by ensuring that the required modules are properly imported and available for testing.

  5. Address the ModuleNotFoundError for 'lib' by checking the import statements and ensuring that the 'lib' module is correctly referenced.

By following these steps, the user should be able to replace pytest with flask test, improve the testing setup, and prevent the mentioned errors from occurring.

Sources:


Step 2: ⌨️ Coding

  • src/tests/test_api_service.py ❌ Failed
• Import the necessary modules at the top of the file, including unittest and the api_service module from the src/services directory. • Define a new class called TestApiService that inherits from unittest.TestCase. • Inside this class, define a new method for each function in the api_service module. Each method should test a specific function in the api_service module. • Use the unittest.mock.patch decorator to mock the OpenAI API in the tests.
  • src/tests/test_openai_service.py
• Import the necessary modules at the top of the file, including unittest and the openai_service module from the src/services directory. • Define a new class called TestOpenaiService that inherits from unittest.TestCase. • Inside this class, define a new method for each function in the openai_service module. Each method should test a specific function in the openai_service module. • Use the unittest.mock.patch decorator to mock the OpenAI API in the tests.
  • src/tests/test_slack_service.py
• Import the necessary modules at the top of the file, including unittest and the slack_service module from the src/services directory. • Define a new class called TestSlackService that inherits from unittest.TestCase. • Inside this class, define a new method for each function in the slack_service module. Each method should test a specific function in the slack_service module. • Use the unittest.mock.patch decorator to mock the Slack API in the tests.
  • src/index.py
• Import the unittest module at the top of the file. • Define a new command for the Flask application called "test". This command should discover and run all tests in the src/tests directory.

Step 3: 🔁 Code Review

Working on it...


🎉 Latest improvements to Sweep:


💡 To recreate the pull request edit the issue title or description. To tweak the pull request, leave a comment on the pull request.
Join Our Discord

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
sweep Assigns Sweep to an issue or pull request.
Projects
None yet
Development

No branches or pull requests

1 participant