
import pytest
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
from qc_functions import *
from analysis_functions import *
from plotting import *

import unittest
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from unittest.mock import patch
# Import the functions from your file


class TestPlotPositionalVulnerability(unittest.TestCase):

    def setUp(self):
        """Create mock data for testing with multiple rows per miRNA."""
        self.group_1_list = ['V1', 'V2']
        self.group_2_list = ['K1', 'K2']

        # miR-1 has 3 rows: A perfect match, a G>T at pos 5, and a G>T at pos 12
        self.mismatch_df = pd.DataFrame({
            'miRNA name': ['miR-1', 'miR-1', 'miR-1', 'miR-2', 'miR-3'],
            'pos:mut': ['PM', '5:G>T', '12:G>T', '18:G>T', 'PM'],
            'V1': [100, 1, 2, 2, 50],
            'V2': [100, 2, 1, 1, 50],
            'K1': [100, 5, 4, 10, 50],
            'K2': [100, 4, 5, 12, 50]
        })

    @patch('matplotlib.pyplot.show')  # Prevent plot from opening
    @patch('seaborn.lineplot')
    def test_multi_row_execution(self, mock_lineplot, mock_show):
        """Test if the function handles multiple rows per miRNA correctly."""

        # The function should run without throwing a length mismatch error
        pos_data = plot_positional_vulnerability(
            self.mismatch_df,
            self.group_1_list,
            self.group_2_list,
            condition="Test"
        )

        self.assertTrue(mock_show.called)

        # Verify that positions 5, 12, and 18 were successfully extracted
        self.assertIn(5, pos_data.index)
        self.assertIn(12, pos_data.index)
        self.assertIn(18, pos_data.index)

        # Verify the calculation logic for miR-1 at position 5 in V1
        # miR-1 Total V1 = 100(PM) + 1(5:G>T) + 2(12:G>T) + 1(pseudocount) = 104
        # miR-1 V1 rate at pos 5 = 1 / 104 = 0.009615
        expected_rate = 1 / 104
        self.assertAlmostEqual(pos_data.loc[5, 'V1'], expected_rate, places=3)
