LevelBot / test.py
nroggendorff's picture
add tester
48b6be9 verified
import unittest
from unittest.mock import patch, MagicMock
import pandas as pd
import requests
import os
import asyncio
from app import (
calculate_level, calculate_xp, add_exp, update_google_sheet,
update_hub_stats, on_ready, DISCORD_TOKEN, bot, global_df, test_merge
)
class TestAppFunctions(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Set up any state needed before tests are run
cls.test_member_id = 123456789
cls.test_xp = 1000
cls.test_level = 10
def test_calculate_level(self):
level = calculate_level(self.test_xp)
self.assertEqual(level, int(self.test_xp ** (1.0 / 3.0)))
def test_calculate_xp(self):
xp = calculate_xp(self.test_level)
self.assertEqual(xp, int(self.test_level ** 3))
@patch('app.global_df', new_callable=pd.DataFrame)
@patch('app.update_google_sheet')
def test_add_exp(self, mock_update_google_sheet, mock_global_df):
# Mock the bot and guild setup
bot.get_guild.return_value.get_member.return_value = MagicMock()
# Add mock data to global_df
data = {'discord_user_id': ['L123456789L'], 'discord_exp': ['L1000L'], 'total_exp': ['L2000L'], 'hub_exp': ['L1000L']}
mock_global_df.return_value = pd.DataFrame(data)
# Run add_exp and assert it does not raise exceptions
try:
asyncio.run(add_exp(self.test_member_id))
success = True
except Exception as e:
success = False
self.assertTrue(success)
@patch('requests.get')
def test_update_hub_stats(self, mock_get):
# Set up mock response for requests.get
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = {
"numLikes": 10,
"numModels": 5,
"numDatasets": 3,
"numSpaces": 2,
"numDiscussions": 7,
"numPapers": 1,
"numUpvotes": 4
}
mock_get.return_value = mock_response
# Add mock data to global_df
data = {'hf_user_name': ['test_user'], 'discord_exp': ['L1000L'], 'total_exp': ['L2000L'], 'hub_exp': ['L1000L']}
global_df = pd.DataFrame(data)
try:
update_hub_stats()
success = True
except Exception as e:
success = False
self.assertTrue(success)
def test_on_ready(self):
# Test the real bot's on_ready method
async def run_on_ready():
await on_ready()
try:
asyncio.run(run_on_ready())
success = True
except Exception as e:
success = False
self.assertTrue(success)
def test_update_google_sheet(self):
# Mock gspread and related functions
with patch('app.set_with_dataframe') as mock_set_with_dataframe:
update_google_sheet()
mock_set_with_dataframe.assert_called()
def test_env_key_exists(self):
self.assertIn('KEY', os.environ, "The 'KEY' environment variable is not set.")
if __name__ == '__main__':
unittest.main()