diff --git a/.github/workflows/pdf_builder.yaml b/.github/workflows/pdf_builder.yaml index 1b0cfa80..505faea0 100644 --- a/.github/workflows/pdf_builder.yaml +++ b/.github/workflows/pdf_builder.yaml @@ -30,7 +30,7 @@ jobs: if: steps.cache.outputs.cache-hit != 'true' run: | sudo apt-get update - sudo apt-get install texlive-latex-extra texlive-science latexmk + sudo apt-get install texlive-latex-extra texlive-fonts-extra texlive-science latexmk - name: Create app access token uses: actions/create-github-app-token@v1 @@ -76,6 +76,14 @@ jobs: cd - # Go back to root folder done git status + + - name: Build All Files + if: ${{ contains(github.event.head_commit.message, '[DOCS] [ALL]') }} + run: | + cd docs + make + cd .. + git status # Commit the generated PDF and formatted .tex files back to the repository - name: Commit & Push changes diff --git a/Final_Team_Contrib.pdf b/Final_Team_Contrib.pdf deleted file mode 100644 index a20c93d5..00000000 Binary files a/Final_Team_Contrib.pdf and /dev/null differ diff --git a/README.md b/README.md index 8af02ce4..1432dd0e 100644 --- a/README.md +++ b/README.md @@ -21,28 +21,9 @@ Date of project start: September 16th 2024 - Provides guidelines and transformations to minimise energy consumption while maintaining code compatibility. - Adapts to the unique performance and energy model of Python. -3. **Reinforcement Learning for Refactoring Preferences** - - Utilises reinforcement learning to adapt refactoring strategies based on past performance data. - - Continuously improves the refactoring process by learning which transformations lead to the greatest energy savings. - - Continuously improves the refactoring process by learning which transformations lead to most technically sustainable (readable) code. - -4. **DevOps GitHub Integration** - - Integrates with GitHub to automatically trigger energy-efficient refactoring as part of the CI/CD pipeline. - - Provides version control, ensuring that refactoring changes can be tracked, tested, and validated before deployment. - - Implements an automated feedback loop that records energy consumption data and feeds it back into the library's reinforcement learning model. - - Automates testing of source code within the DevOps workflow to ensure that behaviour is maintained. - -**Nice-to-Have Features:** - -1. **Library Plugin** +3. **Library Plugin** - Offers a plugin extension for popular IDEs and platforms, allowing developers to easily incorporate the refactoring library into their existing workflows. - Provides real-time suggestions and refactoring options within the development environment, enhancing usability and accessibility. - - Synchronizes plugin with website allowing developers to view measurements taken in a visual manner (i.e. graphs, tables). - -2. **Human-in-the-Loop Reinforcement Learning** - - Involves human feedback in the reinforcement learning process to guide the system's refactoring decisions based on developer expertise and preferences. - - Balances automated refactoring with human oversight to ensure that complex refactoring decisions align with the project's goals and constraints. - The folders and files for this project are as follows: @@ -52,6 +33,4 @@ refs - Reference material used for the project, including papers src - Source code -test - Test cases - -etc. +test - Test cases \ No newline at end of file diff --git a/docs/Design/README.md b/docs/Design/README.md index da725ccd..cb01a1ae 100644 --- a/docs/Design/README.md +++ b/docs/Design/README.md @@ -1,5 +1,40 @@ -# Design Documentation +# Design Documentation Directory -The folders and files for this folder are as follows: +This directory contains the design documentation for the Source Code Optimizer project, detailing both high-level architecture and low-level design specifications. -Describe ... +## Directory Contents + +### Files +- `README.md` - Documentation overview + +### Directories +- `SoftArchitecture/` - High-level system architecture documentation +- `SoftDetailedDes/` - Low-level detailed design specifications + +## Major Components + +1. System Architecture + - System Overview + - Component Architecture + - Design Patterns + - System Interfaces + +2. Detailed Design + - Module Specifications + - Class Designs + - Data Structures + - Algorithms + +## Documentation Guidelines + +1. Architecture Documentation + - System-level design decisions + - Component relationships + - Technology choices + - Integration points + +2. Detailed Design Documentation + - Module interfaces + - Class hierarchies + - Data flow + - Implementation details \ No newline at end of file diff --git a/docs/Design/SoftArchitecture/MG.pdf b/docs/Design/SoftArchitecture/MG.pdf index 31bad3ce..19459ba4 100644 Binary files a/docs/Design/SoftArchitecture/MG.pdf and b/docs/Design/SoftArchitecture/MG.pdf differ diff --git a/docs/Design/SoftArchitecture/MG.tex b/docs/Design/SoftArchitecture/MG.tex index 54ecf233..e9e88e71 100644 --- a/docs/Design/SoftArchitecture/MG.tex +++ b/docs/Design/SoftArchitecture/MG.tex @@ -4,6 +4,7 @@ \usepackage[round]{natbib} \usepackage{multirow} \usepackage{booktabs} +\usepackage{amssymb} \usepackage{tabularx} \usepackage{graphicx} \usepackage{float} @@ -15,6 +16,8 @@ linkcolor=red, urlcolor=blue } +\usepackage{amsmath} % For cases/aligned +\usepackage{enumitem} % For itemize formatting \input{../../Comments} \input{../../Common} @@ -44,9 +47,15 @@ \section{Revision History} \begin{tabularx}{\textwidth}{p{3cm}p{2cm}X} -\toprule {\bf Date} & {\bf Version} & {\bf Notes}\\ +\toprule {\bf Date} & {\bf Name} & {\bf Notes}\\ \midrule -January 17th, 2025 & 0.1 & Initial draft\\ +January 17th, 2025 & All & Initial draft\\ +March 24th, 2025 & Mya Hussain & Added formalization to multiple modules. \\ +March 24th, 2025 & Ayushi Amin & Added formalization to multiple modules. \\ +March 25th, 2025 & Ayushi Amin & Updated Trace for Functional Requirements. \\ +March 25th, 2025 & Tanveer Brar & Added new modules for plugin \\ +March 25th, 2025 & Ayushi Amin & Updates All Trace Tables. \\ +March 28th, 2025 & Tanveer Brar & Addressed TA and Peer Review Feedback Issues\\ \bottomrule \end{tabularx} @@ -164,7 +173,7 @@ \subsection{Anticipated Changes} \label{SecAchange} \begin{itemize} \item \textbf{Refactoring Suggestions Display}: Updates to how refactoring suggestions are presented, such as side-by-side views of original and refactored code. \item \textbf{Theme Support}: Adding compatibility with various VS Code themes, including light and dark modes. - \item \textbf{Visual Indicators}: Implementing color-coded indicators to highlight the impact of energy savings for each refactoring suggestion. + \item \textbf{Visual Indicators}: Implementing colour-coded indicators to highlight the impact of energy savings for each refactoring suggestion. \item \textbf{Interactive Elements}: Introducing interactive components like tooltips or progress indicators to guide users during the refactoring process. \item \textbf{Customization Options}: Allowing users to configure UI elements, such as adjusting the sensitivity of code smell detection or selecting preferred refactoring styles. \end{itemize} @@ -190,8 +199,8 @@ \subsection{Anticipated Changes} \label{SecAchange} \item \textbf{Long Message Chain} \label{acLongMessageChain}: Extending the module's ability to identify and refactor long message chains. \item \textbf{Member Ignoring Method} \label{acMemberIgnoringMethod}: Enhancements to the - module for detecting methods that ignore members, optimizing the code structure. - \item \textbf{Repeated Calls} \label{acRepeatedCalls}: Optimizing detection and handling + module for detecting methods that ignore members, optimising the code structure. + \item \textbf{Repeated Calls} \label{acRepeatedCalls}: Optimising detection and handling of repeated function calls to improve performance. \item \textbf{String Concatenation in Loop} \label{acStringConcatenationInLoop}: Adjusting the refactorer's logic to improve handling of string concatenation within loops. @@ -205,10 +214,6 @@ \subsection{Anticipated Changes} \label{SecAchange} \item[\refstepcounter{acnum} \actheacnum \label{acAnalyzer}:] The analyzers used to gather metrics and assess code quality. - \item[\refstepcounter{acnum} \actheacnum \label{acTesting}:] The testing module - responsible for ensuring the correct functionality of the refactorers. As new - features and code smells are added, this module may need updates to test these - changes thoroughly. \end{description} \wss{Anticipated changes relate to changes that would be made in requirements, @@ -255,45 +260,53 @@ \section{Module Hierarchy} \label{SecMH} \item [\refstepcounter{mnum} \mthemnum \label{mHov}:] Hover Manager Module \item [\refstepcounter{mnum} \mthemnum \label{mMeasure}:] Measurements Module \item [\refstepcounter{mnum} \mthemnum \label{mPyA}:] Pylint Analyzer Module - \item [\refstepcounter{mnum} \mthemnum \label{mTest}:] Testing Functionality Module \item [\refstepcounter{mnum} \mthemnum \label{mRef}:] Smell Refactorer Module \item [\refstepcounter{mnum} \mthemnum \label{mMan}:] Refactor Manager Module + \item [\refstepcounter{mnum} \mthemnum \label{mCac}:] Cache Manager Module + \item [\refstepcounter{mnum} \mthemnum \label{mFil}:] Filter Manager Module + \item [\refstepcounter{mnum} \mthemnum \label{mEne}:] Energy Metrics Module + \item [\refstepcounter{mnum} \mthemnum \label{mVie}:] View Provider Module + \item [\refstepcounter{mnum} \mthemnum \label{mEve}:] Event Manager Module \end{description} \begin{table}[h!] -\centering -\begin{tabular}{p{0.3\textwidth} p{0.6\textwidth}} -\toprule -\textbf{Level 1} & \textbf{Level 2}\\ -\midrule - -{Hardware-Hiding Module} & None \\ -\midrule - -\multirow{7}{0.3\textwidth}{Behaviour-Hiding Module} & Smell Module\\ -& BaseRefactorer Module\\ -& MakeStaticRefactorer Module\\ -& UseListAccumulationRefactorer Module\\ -& UseAGeneratorRefactorer Module\\ -& CacheRepeatedCallsRefactorer Module\\ -& LongElementChainRefactorer Module\\ -& LongParameterListRefactorer Module\\ -& LongMessageChainRefactorer Module\\ -& LongLambdaFunctionRefactorer Module\\ -& PluginInitiator Module\\ -& BackendCommunicator Module\\ -& SmellDetector Module\\ -& FileHighlighter Module\\ -& HoverManager Module\\ -\midrule + \centering + \begin{tabular}{p{0.3\textwidth} p{0.6\textwidth}} + \toprule + \textbf{Level 1} & \textbf{Level 2}\\ + \midrule + + {Hardware-Hiding Module} & None \\ + \midrule + + \multirow{7}{0.3\textwidth}{Behaviour-Hiding Module} & Smell Module\\ + & BaseRefactorer Module\\ + & MakeStaticRefactorer Module\\ + & UseListAccumulationRefactorer Module\\ + & UseAGeneratorRefactorer Module\\ + & CacheRepeatedCallsRefactorer Module\\ + & LongElementChainRefactorer Module\\ + & LongParameterListRefactorer Module\\ + & LongMessageChainRefactorer Module\\ + & LongLambdaFunctionRefactorer Module\\ + & PluginInitiator Module\\ + & BackendCommunicator Module\\ + & SmellDetector Module\\ + & FileHighlighter Module\\ + & HoverManager Module\\ + & CacheManager Module\\ + & FilterManager Module\\ + \midrule -\multirow{3}{0.3\textwidth}{Software Decision Module} & Measurements Module\\ + \multirow{3}{0.3\textwidth}{Software Decision Module} & Measurements Module\\ & PylintAnalyzer Module\\ -& Testing Functionality Module\\ & SmellRefactorer Module\\ & RefactorManager Module\\ +& EnergyMetrics Module\\ +& ViewProvider Module\\ +& EventManager Module\\ \bottomrule \end{tabular} @@ -305,7 +318,7 @@ \section{Connection Between Requirements and Design} \label{SecConnection} The design of the system is intended to satisfy the requirements developed in the SRS. In this stage, the system is decomposed into modules. The connection -between requirements and modules is listed in Table~\ref{TblRT}. +between requirements and modules is listed in Table~\ref{TblMH}. \wss{The intention of this section is to document decisions that are made ``between'' the requirements and the design. To satisfy some requirements, @@ -350,7 +363,7 @@ \subsubsection{Base Refactorer Module (\mref{mBR})} % [Record, Library, Abstract Object, or Abstract Data Type] \begin{description} - \item[Secrets:] None + \item[Secrets:] How to handle file I/O operations for reading and writing code. How to parse source code into AST/CST representation and convert modified AST/CST back to source code. How to traverse, analyze and modify AST/CST trees. \item[Services:] Offers an interface for other refactoring modules to implement. \item[Implemented By:] EcoOptimizer \end{description} @@ -359,56 +372,122 @@ \subsubsection{MakeStaticRefactorer Module (\mref{mMIMR})} % [Record, Library, Abstract Object, or Abstract Data Type] \begin{description} -\item[Secrets:] How to parse a given code file to its AST representation, how to traverse the AST tree, how to modify specific nodes in the AST tree, how to convert the modified AST tree back to source code and write it to an output file. +\item[Secrets:] How to identify method calls that don't use instance attributes, determine class hierarchies and inheritance relationships, transform instance method calls to static method calls and handle method annotations and type hints. \item[Services:] Refactors the \textit{\textbf{Member Ignoring Method (MIM)}} smell in a provided code file to improve energy efficiency. \item[Implemented By:] EcoOptimizer +\item[Type of Module:] Abstract Object: A transformation component that modifies Python source code to optimise method calls. \end{description} +\textbf{Formalization of MakeStaticRefactorer} + +\begin{enumerate} + \item \textbf{Definitions} + \begin{itemize} + \item \textit{Source Code}: A Python program \( D \) consisting of a set of statements \( S = \{ s_1, s_2, \dots, s_n \} \). + \item \textit{Member Ignoring Method (MIM)}: A function \( f \) defined inside a class \( C \) that does not use instance attributes or methods. + \item \textit{Static Method Transformation}: A function \( T \) that converts an instance method \( f \) into a static method \( f' \), where: + \[ + T(f) = f' \text{ such that } \forall x \in C, f(x) = f' + \] + \item \textit{Refactored Code}: The transformed version of \( D \), denoted as \( D' \), where all applicable \( f \) are replaced by \( f' \). + \end{itemize} + + \item \textbf{Transformation Process} + \begin{itemize} + \item Parse \( D \) into an AST representation. + \item Identify functions \( f \) where: + \begin{itemize} + \item \( f \in C \) (i.e., \( f \) is a method within a class). + \item \( f \) does not reference any instance variables. + \end{itemize} + \item Modify \( f \) by: + \begin{itemize} + \item Adding a `@staticmethod` decorator. + \item Removing the `self` parameter from its signature. + \end{itemize} + \item Update all relevant method calls in \( D \) to reflect the static method transformation. + \end{itemize} + + \item \textbf{Validation and Constraints} + \begin{itemize} + \item Ensure correctness by preserving method functionality. + \item Verify that method calls in \( D \) remain semantically valid after transformation. + \item Maintain compatibility with subclasses and inherited methods. + \end{itemize} +\end{enumerate} + \subsubsection{UseListAccumulationRefactorer Module (\mref{mSCLR})} % [Record, Library, Abstract Object, or Abstract Data Type] \begin{description} -\item[Secrets:] How to parse a given code file into its AST representation, how to traverse the AST tree, how to find the initializing variable of the string concatenation, how to find the scope of the concatenation, how to modify the given code file in plain text and write it back to an output file. +\item[Secrets:] How to identify string concatenation operations within loops and find the scope of the concatenation. How to track variable assignments and reassignments across scopes. How to transform string concatenations into list accumulation patterns. \item[Services:] Refactors the \textbf{\textit{String Concatenation Inside Loop (SCL)}} smell in a provided code file to improve energy efficiency. \item[Implemented By:] EcoOptimizer \end{description} \subsubsection{UseAGeneratorRefactorer Module (\mref{mUGENR})} \begin{description} - \item[Secrets:] How to parse a given code file to its AST representation, how to traverse the AST tree, how to modify specific nodes in the AST tree, how to convert the modified AST tree back to source code and write it to an output file. - \item[Services:] Refactors the \textit{List Comprehension Instead of a Generator} smell in a provided code file to improve energy efficiency. + \item[Secrets:] How to identify list comprehensions through operations. How to transform list comprehensions into generator expressions. How to preserve short-circuit evaluation behavior. + \item[Services:] Refactors the \textbf{\textit{List Comprehension Instead of a Generator}} smell in a provided code file to improve energy efficiency. \item[Implemented By:] EcoOptimizer \end{description} \subsubsection{CacheRepeatedCallsRefactorer Module (\mref{mCRC})} \begin{description} - \item[Secrets:] How to parse a given code file to its AST representation, how to traverse the AST tree, how to modify specific nodes in the AST tree, how to convert the modified AST tree back to source code and write it to an output file. - \item[Services:] Refactors the \textit{Repeated Function Calls} smell in a provided code file to improve energy efficiency and performance. + \item[Secrets:] How to identify repeated function calls with same arguments, how to determine appropriate scope for caching. How to implement memoization patterns and handle side effects in cached functions. + \item[Services:] Refactors the \textbf{\textit{Repeated Function Calls}} smell in a provided code file to improve energy efficiency and performance. \item[Implemented By:] EcoOptimizer \end{description} \subsubsection{Long Element Chain Module (\mref{mLEC})} -% [Record, Library, Abstract Object, or Abstract Data Type] - \begin{description} - \item[Secrets:] How to parse a given code file to its AST representation, traverse the - AST tree to identify dictionary assignments, analyze the structure of nested dictionaries, - and flatten them. Additionally, it identifies all access calls associated with these dictionaries - in the source code and determines how to update them to reflect the new flattened structure. + \item[Secrets:] How to identify dictionary assignments, analyze the structure of nested dictionaries, and flatten them. How to identify all access calls associated with these dictionaries in the source code and determines how to update them to reflect the new flattened structure. How to maintain data structure integrity during transformation. \item[Services:] Detects nested dictionaries in the source code using AST parsing, simplifies their structure by flattening them, and updates all associated access calls throughout the file. This improves code readability, reduces complexity, and ensures correctness while maintaining the program's intended behavior. \item[Implemented By:] EcoOptimizer + \item[Type of Module:] Library: provides functionality for refactoring nested dictionary structures in Python code. \end{description} +\textbf{Long Element Chain Formalization} +\begin{enumerate} + \item \textbf{Definitions} + \begin{itemize} + \item \textit{Nested Dictionary}: Dictionary \( D = \{k_1: \{k_2: \dots \{k_n: v\}\}\} \) + \item \textit{Flattened Dictionary}: \( D' = \{k_1\_k_2\_\dots\_k_n: v\} \) + \item \textit{Access Path}: Sequence \( P = [k_1, k_2, \dots, k_n] \) + \item \textit{Composite Key}: String \( c_k = \text{join}(P, "\_") \) + \item \textit{Indentation}: Leading whitespace \( W \) from original code + \end{itemize} + + \item \textbf{Refactoring Function} + \begin{itemize} + \item Dictionary Flattening: + \[ + \begin{aligned} + &\forall\ \text{nested path } P \in D,\ \exists\ c_k \in D' \\ + &D'[c_k] = D[P_1][P_2]\dots[P_n] \quad \text{(preserve } W\text{)} + \end{aligned} + \] + + \item Access Path Update: + \[ + \begin{aligned} + &\text{Original Access: } &D[P_1][P_2]\dots[P_n] \\ + &\text{Refactored Access: } &D'[c_k] \quad \text{where } c_k = \text{join}(P, "\_") + \end{aligned} + \] + \end{itemize} +\end{enumerate} + \subsubsection{Long Parameter List Module (\mref{mLPL})} % [Record, Library, Abstract Object, or Abstract Data Type] \begin{description} - \item[Secrets:] How to parse a given code file to its AST representation, traverse the AST tree to identify functions or methods with long parameter lists, and encapsulate related parameters into objects or structures. Additionally, it identifies all function or method calls associated with these functions and updates their arguments to align with the refactored signature. + \item[Secrets:] How to identify functions or methods with long parameter lists, and encapsulate related parameters into objects or structures. How to group related parameters into objects/structures. How to update all call sites with new parameter structures. How to identify all function or method calls associated with these functions and updates their arguments to align with the refactored signature. \item[Services:] Detects long parameter lists in functions or methods using AST parsing, simplifies their structure by grouping related parameters into objects or structures, and updates all associated function or method calls throughout the file. This improves code readability, reduces complexity, and ensures correctness while maintaining the program’s intended behavior. \item[Implemented By:] EcoOptimizer \end{description} @@ -417,8 +496,7 @@ \subsubsection{Long Message Chain Refactorer (\mref{mLMC})} \begin{description} - \item[Secrets:] Understanding the syntax and structure of Python code to identify/classify long message chains, including both f-strings and non-f-string chains. This involves parsing the target file, extracting method calls from identified long chains, and systematically breaking them into separate statements while preserving the original functionality and indentation. Additionally, it ensures unmatched brackets are corrected during refactoring. - + \item[Secrets:] How to analzye the syntax and structure of Python code to identify/classify long message chains, including both f-strings and non-f-string chains. How to extract method calls from identified long chains, and systematically break them into separate statements while preserving the original functionality and indentation. How to correct unmatched brackets during refactoring. \item[Services:] Detects long message chains in Python source code and refactors them by splitting the chain into intermediate variables and a final result. This improves code readability and maintainability while retaining the original program behavior. \item[Implemented By:] EcoOptimizer @@ -426,11 +504,45 @@ \subsubsection{Long Message Chain Refactorer (\mref{mLMC})} \end{description} +\textbf{Long Message Chain Formalization} +\begin{enumerate} + \item \textbf{Definitions} + \begin{itemize} + \item \textit{Input Line}: String \( L \) (e.g., \texttt{obj.a().b().c()}) + \item \textit{Method Chain}: Sequence \( M = [m_1, m_2, \dots, m_n] \), where \( m_i \) is a method call + \item \textit{Intermediate Variables}: Generated variables \( V = [v_0, v_1, \dots, v_{n-1}] \) + \item \textit{Indentation}: Leading whitespace \( W \) from \( L \) + \end{itemize} + + \item \textbf{Refactoring Function} + \begin{itemize} + \item For f-strings: + \[ + \begin{aligned} + &v_0 = f_{\text{str}} \quad \text{(preserve } W\text{)} \\ + &v_1 = v_0.m_1 \quad \text{(preserve } W\text{)} \\ + &\;\;\vdots \\ + &\text{result} = v_{n-1}.m_n \quad \text{(preserve } W\text{)} + \end{aligned} + \] + \item For regular chains: + \[ + \begin{aligned} + &v_0 = m_1 \quad \text{(preserve } W\text{)} \\ + &v_1 = v_0.m_2 \quad \text{(preserve } W\text{)} \\ + &\;\;\vdots \\ + &\text{result} = v_{n-1}.m_n \quad \text{(preserve } W\text{)} + \end{aligned} + \] + \end{itemize} +\end{enumerate} + + \subsubsection{Long Lambda Function Refactorer (\mref{mLLF})} \begin{description} - \item[Secrets:] Understanding the syntax and structure of Python code to identify long lambda functions. This includes parsing the target file to locate lambda expressions, extracting their arguments and bodies, and converting them into standard Python function definitions. The module ensures proper handling of nested structures (e.g., parentheses, brackets, and braces) within the lambda body, and truncates overly complex expressions at the first top-level comma for readability. + \item[Secrets:] How to analyze the syntax and structure of Python code to identify long lambda functions. How to locate lambda expressions, extract their arguments and bodies, and convert them into standard Python function definitions. How to properly handle nested structures (e.g., parentheses, brackets, and braces) within the lambda body, and truncates overly complex expressions at the first top-level comma for readability. \item[Services:] Detects components of long lambda functions in Python source code and refactors them by converting the lambda expression into a standalone function with a unique name. This improves code readability, debugging, and maintainability. The module inserts the newly defined function in the appropriate scope, updates the original lambda usage with a function call, and validates the refactored code by maintaining its functionality and measuring energy efficiency improvements. @@ -439,13 +551,89 @@ \subsubsection{Long Lambda Function Refactorer (\mref{mLLF})} \item[Type of Module:] Library: a reusable component that provides functionality for refactoring long lambda functions in Python code. \end{description} +\textbf{Long Lambda Function Formalization} +\begin{enumerate} + \item \textbf{Definitions} + \begin{itemize} + \item \textit{Lambda Expression}: String \( L = \text{``lambda'' }A\text{``:'' }B \) where: + \begin{itemize} + \item \( A = [a_1, \dots, a_n] \) : Formal parameters + \item \( B \) : Body expression + \end{itemize} + + \item \textit{Truncated Body}: \( B' = \begin{cases} + B[0:i] & \text{if top-level comma at } i \\ + B & \text{otherwise} + \end{cases} \) + + \item \textit{Function Name}: \( F = \text{``converted\_lambda\_''} + \text{line\_num} \) + + \item \textit{Indentation}: + \begin{itemize} + \item \( W \) : Original line's whitespace + \item \( W_c \) : Parent block indentation + \item \( D = 4 \) : Indentation delta (spaces) + \end{itemize} + \end{itemize} + + \item \textbf{Transformation Rules} + \begin{itemize} + \item \textbf{Function Generation}: + \[ + \begin{aligned} + &\textsc{Definition}: & W_c\text{``def ''}F(A)\text{``:''} \\ + &\textsc{Body}: & (W_c + D)\text{``result = ''}B' \\ + &\textsc{Return}: & (W_c + D)\text{``return result''} + \end{aligned} + \] + + \item \textbf{Lambda Replacement}: + \[ + W\text{``lambda ''}A\text{``: ''}B \quad \Rightarrow \quad W F + \] + \end{itemize} + + \item \textbf{Example} + \begin{itemize} + \item \textit{Before}: + \begin{verbatim} + # Original lambda (line 42) + result = map(lambda x: x**2, data) + \end{verbatim} + + \item \textit{After}: + \begin{verbatim} +def converted_lambda_42(x): # W_c = "" + result = x**2 # W_c + D (D=4) + return result + + result = map(converted_lambda_42, data) + \end{verbatim} + \end{itemize} +\end{enumerate} + +\textit{Key Relationships}: +\begin{itemize} + \item \( F \) uniqueness via \text{line\_num} + \item \( D = 4 \) ensures PEP8 compliance + \item \( W \) preservation maintains code structure +\end{itemize} + +\textit{Key Relationships}: +\begin{itemize} + \item \( F \) preserves lexical scope via \( W_c \) alignment + \item \( B' \) ensures syntactic validity through comma truncation + \item \( \Delta = 4 \) enforces PEP8 indentation rules + \item \( W \) retention maintains original code structure +\end{itemize} + \subsubsection{Plugin Initiator Module (\mref{mExe})} % [Record, Library, Abstract Object, or Abstract Data Type] \begin{description} - \item[Secrets:] How to initialize the plugin, set up the environment for interaction, and handle configurations for plugin commands. - \item[Services:] Initializes and manages the plugin's setup, enabling its functionality without exposing the underlying initialization logic. + \item[Secrets:] How to initialise the plugin, set up the environment for interaction, and handle configurations for plugin commands. + \item[Services:] Initialises and manages the plugin's setup including command registration, enabling its functionality without exposing the underlying initialisation logic. \item[Implemented By:] EcoOptimizer \end{description} @@ -455,7 +643,7 @@ \subsubsection{Backend Communicator (\mref{mBac})} \begin{description} \item[Secrets:] How to establish communication between the plugin and Source Code Optimizer, handle requests, and process responses. - \item[Services:] Provides an interface for sending requests to and receiving responses from Source Code Optimizer. Abstracts the communication details from modules within the plugin. + \item[Services:] Provides an interface for sending requests to and receiving responses from Source Code Optimizer. Abstracts the communication details from modules within the plugin. Managers server status checks and handles backend communication errors. \item[Implemented By:] EcoOptimizer \end{description} @@ -464,11 +652,51 @@ \subsubsection{Smell Detector (\mref{mDet})} % [Record, Library, Abstract Object, or Abstract Data Type] \begin{description} - \item[Secrets:] How to analyze Python code in active VS Code editor by accessing Source Code Optimizer endpoint. + \item[Secrets:] How to analyse Python code in active VS Code editor by accessing Source Code Optimizer endpoint. \item[Services:] Detects code smells in Python scripts using Source Code Optimizer and provides structured data for further processing based on received output. \item[Implemented By:] EcoOptimizer + \item[Type of Module:] Abstract Object: A component responsible for code smell detection and classification. \end{description} +\textbf{Smell Detection Formalization} +\begin{enumerate} + \item \textbf{Definitions} + \begin{itemize} + \item \textit{Source Code}: A document \( D \) containing a sequence of statements \( S = \{ s_1, s_2, \dots, s_n \} \). + \item \textit{Code Smell}: A property \( C_k \) that signifies a potential issue in \( D \), where: + \[ + C_k = \{ c_1, c_2, \dots, c_m \} + \] + represents a set of detectable code smells. + \item \textit{Detection Function}: A mapping \( F: D \to C_k \), which evaluates \( D \) and returns a set of identified smells. + \item \textit{Smell Report}: A structured output \( R \) summarizing detected smells and their locations in \( D \). + \end{itemize} + + \item \textbf{Detection Process} + \begin{itemize} + \item Extract syntactic and semantic features from \( D \). + \item Apply detection rules to identify instances of \( C_k \). + \item Generate a structured smell report \( R \) containing: + \begin{itemize} + \item Smell type \( c_i \) + \item Line number(s) \( L = \{ l_1, l_2, \dots, l_p \} \) + \item Severity level \( \sigma \) based on predefined metrics + \end{itemize} + \end{itemize} + + \item \textbf{Classification and Output} + \begin{itemize} + \item Structure \( R \) for further analysis by the refactoring module. + \item Ensure results are accessible to downstream processing components. + \end{itemize} + + \item \textbf{Validation and Adaptation} + \begin{itemize} + \item Maintain a feedback loop to refine detection accuracy. + \item Adapt detection parameters based on observed refactoring effectiveness. + \end{itemize} +\end{enumerate} + \subsubsection{File Highlighter Module (\mref{mHig})} % [Record, Library, Abstract Object, or Abstract Data Type] @@ -479,13 +707,61 @@ \subsubsection{File Highlighter Module (\mref{mHig})} \item[Implemented By:] EcoOptimizer \end{description} + \subsubsection{Hover Manager Module (\mref{mHov})} -% [Record, Library, Abstract Object, or Abstract Data Type] +\begin{description} + \item[Secrets:] Understanding how to detect hover events over source code, retrieve relevant contextual information dynamically, and generate structured hover content. This includes identifying code smells at a given position, constructing a `MarkdownString` representation, and embedding interactive refactoring commands. + + \item[Services:] Manages hover interactions within the VSCode extension. When a user hovers over a detected code smell, it dynamically provides a `MarkdownString` containing information about the smell and options to refactor it. The module supports both single-instance and type-wide refactoring actions. + + \item[Implemented By:] EcoOptimizer + \item[Type of Module:] Library: a reusable component responsible for handling hover events and providing interactive refactoring commands within the extension. +\end{description} + +\textbf{Hover Interaction Formalization} +\begin{enumerate} + \item \textbf{Definitions} + \begin{itemize} + \item \textit{Interaction Space}: A document \( D \) consisting of discrete positions \( P = \{ p_1, p_2, \dots, p_n \} \) where detected smells can be associated. + \item \textit{Smell Data}: A set \( S = \{ s_1, s_2, \dots, s_m \} \), where each \( s_i \) is a detected smell with: + \begin{itemize} + \item \( s_i.\text{location} \) — position range where the smell occurs + \item \( s_i.\text{description} \) — information about the smell + \end{itemize} + \item \textit{Response Function}: A mapping \( H: P \to S \) that associates positions in \( D \) with detected smells. + \end{itemize} + + \item \textbf{Interaction Model} + \[ + H(p) = + \begin{cases} + s_i, & \text{if } p \text{ corresponds to a detected smell} \\ + \varnothing, & \text{otherwise} + \end{cases} + \] + + \item \textbf{Contextual Response Construction} + \begin{itemize} + \item Given \( p \in P \), retrieve \( s_i \in S \). + \item Construct a structured response containing \( s_i.\text{description} \) and \( s_i.\text{transformationOptions} \). + \item Present the response in an interactive format that allows further refinement or transformation. + \end{itemize} +\end{enumerate} + +\subsubsection{Cache Manager Module (\mref{mCac})} \begin{description} - \item[Secrets:] How to detect hover events, retrieve relevant information dynamically, and present tooltips based on hovered elements. - \item[Services:] Manages hover interactions and displays contextual information for elements within the user interface. + \item[Secrets:] How to persist and retrieve smell detection results, manage cache invalidation, handle cache state transitions and synchronize cache with file system changes. + \item[Services:] Provides persistent storage for smell detection results and the ability to retrieve cached smell data, invalidate cache entries for specific files, clear entire cache. Coordinates cache updates with file system events. + \item[Implemented By:] EcoOptimizer +\end{description} + +\subsubsection{Filter Manager Module (\mref{mFil})} + +\begin{description} + \item[Secrets:] How to handle and respond to filter criteria across sessions. How to handle filter combinations concurrently with UI synchronization. + \item[Services:] Provides functionality to set and get filter criteria for different smell types and apply filters to smell data. This module can clear all active filters, save filter state to persistent storage, restore filter state from storage and validate filter criteria. \item[Implemented By:] EcoOptimizer \end{description} @@ -512,33 +788,88 @@ \subsubsection{Pylint Analyzer Module (\mref{mPyA})} \item[Implemented By:] \texttt{EcoOptimizer} \end{description} -\subsubsection{Testing Functionality Module (\mref{mTest})} + +\subsubsection{Smell Refactorer Module (\mref{mRef})} % [Record, Library, Abstract Object, or Abstract Data Type] \begin{description} - \item[Secrets:] Runs testing suites in a subprocess. - \item[Services:] Checks whether the functionality of a given source code has changed. + \item[Secrets:] How to utilise Source Code Optimizer endpoint for refactoring specific code smells, and how to sanitise received output. + \item[Services:] Refactors code smells in Python scripts using Source Code Optimizer and determines if received output is valid format. \item[Implemented By:] EcoOptimizer \end{description} -\subsubsection{Smell Refactorer Module (\mref{mRef})} -% [Record, Library, Abstract Object, or Abstract Data Type] +\subsubsection{Refactor Manager Module (\mref{mMan})} \begin{description} - \item[Secrets:] How to utilize Source Code Optimizer endpoint for refactoring specific code smells, and how to sanitize received output. - \item[Services:] Refactors code smells in Python scripts using Source Code Optimizer and determines if received output is valid format. + \item[Secrets:] How to coordinate the sequence of refactorings, apply transformations to source code while maintaining correctness, validate the impact of each step, and enable reversion when necessary. Ensures that refactoring operations preserve program behavior. + + \item[Services:] Manages the execution of refactorings, determines whether modifications should be committed to the source file, and allows users to revert changes if needed. + \item[Implemented By:] EcoOptimizer + \item[Type of Module:] Abstract Object: A conceptual entity that organizes and controls the refactoring process. \end{description} -\subsubsection{Refactor Manager Module (\mref{mMan})} +\textbf{Refactoring Execution Formalization} +\begin{enumerate} + \item \textbf{Definitions} + \begin{itemize} + \item \textit{Source Code}: A document \( D \) consisting of a sequence of statements \( S = \{ s_1, s_2, \dots, s_n \} \). + \item \textit{Code Smell}: An identified issue \( \sigma \) in \( D \) that may impact maintainability, readability, or performance. + \item \textit{Refactoring Rule}: A transformation function \( R: D \to D' \) that modifies \( S \) while improving energy consumption. + \item \textit{Refactoring Sequence}: An ordered set of transformations \( \mathcal{R} = [R_1, R_2, \dots, R_m] \) applied sequentially to \( D \). + \end{itemize} -% [Record, Library, Abstract Object, or Abstract Data Type] + \item \textbf{Refactoring Process} + \begin{itemize} + \item Given a detected smell \( \sigma \), identify the corresponding transformation \( R_{\sigma} \). + \item Apply \( R_{\sigma} \) to \( D \), producing \( D' \). + \item Track all modifications to ensure consistency and correctness. + \end{itemize} + + \item \textbf{Modification Tracking} + \begin{itemize} + \item Maintain a count of applied transformations per smell type: + \[ + C_{\sigma} = C_{\sigma} + 1 + \] + \item Store modified versions of \( D \) to enable rollback. + \item Generate output files when refactoring is applied. + \end{itemize} + + \item \textbf{Validation and Reversion} + \begin{itemize} + \item After applying \( R_{\sigma} \), verify correctness: + \[ + V(D') \to \{ \text{valid}, \text{invalid} \} + \] + \item If invalid, restore the previous state \( D \). + \item Allow user-driven reversion to the original state if necessary. + \end{itemize} +\end{enumerate} + +\subsubsection{Energy Metrics Module (\mref{mEne})} \begin{description} - \item[Secrets:] How to manage the sequence of refactorings, coordinate the application of refactoring techniques, validate results after each step and revert at any stage. - \item[Services:] Decides if refactored result of Python code should be updated in the code editor window. Determines if refactoring should be reverted if needed by user. + \item[Secrets:] How to collect and aggregate code metrics from backend output. How to handle metric collection errors and edge cases. How to manage metric data consistency across sessions + \item[Services:] Collects code metrics for specified files and outputs metrics data to suitable formats. Provides functionality to display metrics in the VS Code UI and save metrics data to persistent storage. + \item[Implemented By:] EcoOptimizer +\end{description} + +\subsubsection{View Provider Module (\mref{mVie})} + +\begin{description} + \item[Secrets:] How to implement IDE specific views for different data types. How to manage view state and updates efficiently across multiple views. How to handle dynamic content updates based on user interactions. How to coordinate between different views (smells, metrics, filters, refactoring) + \item[Services:] Provides view display of detected smells with hierarchical format. Provides energy metrics data visualization and updates. Provides filter selection and management interface. Provides refactoring details and preview display. Provides methods to refresh and update all views. + \item[Implemented By:] EcoOptimizer +\end{description} + +\subsubsection{Event Manager Module (\mref{mEve})} + +\begin{description} + \item[Secrets:] How to implement IDE event handling system. How to manage event propagation and subscription lifecycle. How to handle concurrent event processing and state updates and coordinate between different event types. + \item[Services:] Provides event subscription management for workspace changes, file system modifications and UI updates. Provides functionality to register and unregister event listeners, handle event propagation, manage event state and cleanup. \item[Implemented By:] EcoOptimizer \end{description} @@ -555,19 +886,23 @@ \section{Traceability Matrix} \label{SecTM} \toprule \textbf{Req.} & \textbf{Modules}\\ \midrule - FR1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - FR2 & \mref{mSmell}, \mref{mPyA}\\ - FR3 & \mref{mTest}\\ - FR4 & \mref{mTest}\\ - FR5 & \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}\\ - FR6 & \mref{mTest}\\ - FR7 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA},\\ - FR8 & \mref{mSmell}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - FR9 & To be removed\\ - FR10 & Not implemented in code\\ - FR11 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}\\ - FR12 & To be removed\\ - FR13 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}\\ + FR1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mRef}, \mref{mMan}, \mref{mEne}, \mref{mDet} \\ + FR2 & \mref{mSmell}, \mref{mPyA}, \mref{mDet} \\ + FR3 & \mref{mMan}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mRef}\\ + FR4 & \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMan} \\ + FR5 & \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}\\ + FR6 & \mref{mVie}, \mref{mEne}, \mref{mMeasure} \\ + FR7 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mVie}, \mref{mEve}\\ + FR8 & \mref{mMeasure}, \mref{mPyA}, \mref{mVie} \mref{mEne} \\ + FR9 & \mref{mFil}, \mref{mVie}\\ + FR10 & \mref{mHig}, \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHov} \\ + FR11 & \mref{mEve}, \mref{mExe}, \mref{mHig}, \mref{mVie} \\ + FR12 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mHov}, \mref{mBac}, \mref{mHig}, \mref{mRef} \\ + FR13 & \mref{mFil}, \mref{mEve}, \mref{mExe} \\ + FR14 & \mref{mEve}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mRef}, \mref{mMan}, \mref{mEne}, \mref{mDet} \\ + FR15 & \mref{mVie}, \mref{mEne}, \mref{mEve} \\ + FR16 & \mref{mEve}, \mref{mDet}, \mref{mExe} \\ + FR17 & \mref{mCac}\\ \bottomrule \end{tabular} \caption{Trace Between Functional Requirements and Modules} @@ -580,9 +915,9 @@ \section{Traceability Matrix} \label{SecTM} \toprule \textbf{Req.} & \textbf{Modules}\\ \midrule % Look and Feel - LFR-AP 1-4 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}\\ - LFR-AP 5 & To be removed\\ - LFR-ST 1-3 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}\\ + LFR-AP 1 & \mref{mExe}, \mref{mBac}, \mref{mRef}, \mref{mVie}, \mref{mEne} \\ + LFR-AP 2 & \mref{mExe}, \mref{mVie}, \mref{mEne} \mref{mHov}, \mref{mHig} \\ + LFR-ST 1 & \mref{mExe}, \mref{mHig}, \mref{mHov}, \mref{mVie}\\ \bottomrule \end{tabular} \caption{Trace Between Look \& Feel Requirements and Modules} @@ -595,13 +930,16 @@ \section{Traceability Matrix} \label{SecTM} \toprule \textbf{Req.} & \textbf{Modules}\\ \midrule % Usability and Humanity - UHR-PS1 1 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}\\ - UHR-PS1 2 & Not implemented in code\\ - UHR-LRN 1 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}\\ - UHR-LRN 2 & Not implemented in code\\ - UHR-ACS 1-2 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}\\ - UHR-EOU 1-2 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}\\ - UHR-UPL 1 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}\\ + UHR-EOU 1-2 & \mref{mExe}, \mref{mHig}, \mref{mHov}, \mref{mVie}, \mref{mFil} \\ + + UHR-PS1 1 & \mref{mhig}, \mref{mVie}, \mref{mExe} \\ + + UHR-LRN 1 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan} \\ + UHR-LRN 2 & Not implemented in code \\ + + UHR-UPL 1 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan} \\ + + UHR-ACS 1 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}, \mref{mVie} \\ \bottomrule \end{tabular} \caption{Trace Between Usability \& Humanity Requirements and Modules} @@ -614,17 +952,20 @@ \section{Traceability Matrix} \label{SecTM} \toprule \textbf{Req.} & \textbf{Modules}\\ \midrule % Performance - PR-SL 1 & \mref{mPyA}\\ - PR-SL 2 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}\\ - PR-CR 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - PR-SCR 1 \mref{mTest}& \\ - PR-PAR 1 & \mref{mTest}\\ - PR-PAR 2 & \mref{mPyA}\\ - PR-PAR 3 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}\\ - PR-RFT 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - PR-RFT 2 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}\\ - PR-SER 1 & \mref{mBR}\\ - PR-LR 1 & \mref{mSmell}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ + PR-SL 1 & \mref{mPyA}, \mref{mDet}\\ + PR-SL 2 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMan} \\ + + PR-SCR 1 & \mref{mVie}, \mref{mExe} \\ + + PR-PAR 1 & \mref{mPyA}, \mref{mDet} \\ + + PR-RFT 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}\\ + + PR-CR 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA} \\ + + PR-SER 1 & \mref{mBR}, \mref{mSmell}\\ + + PR-LR 1 & \mref{mSmell}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}\\ \bottomrule \end{tabular} \caption{Trace Between Performance Requirements and Modules} @@ -637,15 +978,13 @@ \section{Traceability Matrix} \label{SecTM} \toprule \textbf{Req.} & \textbf{Modules}\\ \midrule % Operational and Environmental - OER-EP 1 & N/A\\ - OER-EP 2 & N/A\\ - OER-WE 1 & \mref{mMeasure}\\ - OER-IAS 1 & To be removed\\ - OER-IAS 2 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}\\ - OER-IAS 3 & To be removed\\ - OER-PR 1 & \mref{mSmell}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - OER-RL 1 & \mref{mSmell}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - OER-RL 2 & N/A\\ + OER-EP 1 & Not implemented in code \\ + OER-EP 2 & Not implemented in code \\ + OER-IAS 1 & \mref{mExe}, \mref{mBac} \\ + OER-IAS 2 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}, \mref{mVie} \\ + OER-PR 1 & Not implemented in code \\ + OER-RL 1 & \mref{mSmell}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}\\ + OER-RL 2 & Not implemented in code \\ \bottomrule \end{tabular} \caption{Trace Between Operational \& Environmental Requirements and Modules} @@ -659,31 +998,45 @@ \section{Traceability Matrix} \label{SecTM} \midrule % Maintenance and Support MS-MNT 1 & \mref{mBR}\\ - MS-MNT 2 & Not implemented in code\\ - MS-MNT 3 & None \\ - MS-MNT 4 & N/A\\ - MS-MNT 5 & \mref{mSmell}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - MS-SP 1 & Not implemented in code\\ + MS-MNT 2 & Not implemented in code \\ + MS-MNT 3 & Not implemented in code \\ + MS-MNT 4 & Not applicable for modules\\ + MS-MNT 5 & \mref{mSmell}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mEve}, \mref{mEne} \\ \bottomrule \end{tabular} \caption{Trace Between Maintenance \& Support Requirements and Modules} \label{tab:MS-mod} \end{table} +\begin{table}[H] + \centering + \begin{tabular}{p{0.2\textwidth} p{0.6\textwidth}} + \toprule \textbf{Req.} & \textbf{Modules}\\ + \midrule + % Maintenance and Support + MS-AD 1 & Not implemented in code \\ + MS-AD 2 & \mref{mSmell}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mEve}, \mref{mEne} \\ + MS-AD 3 & Not implemented in code \\ + MS-AD 4-5 & \mref{mSmell}, \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mEve}, \mref{mEne}, \mref{mVie} \\ + \bottomrule + \end{tabular} + \caption{Trace Between Adaptability Requirements and Modules} + \label{tab:MS-mod} +\end{table} + \begin{table}[H] \centering \begin{tabular}{p{0.2\textwidth} p{0.6\textwidth}} \toprule \textbf{Req.} & \textbf{Modules}\\ \midrule % Security - SR-AR 1 & To be removed\\ - SR-AR 2 & \mref{mMeasure}\\ - SR-IR 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}\\ - SR-PR 1 & N/A\\ - SR-PR 2 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - SR-AUR 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - SR-AUR 2 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - SR-IM 1 & N/A\\ + SR-AR 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mEne}, \mref{mVie} \\ + SR-AR 2 & \mref{mMeasure}, \mref{mMan} \\ + SR-IR 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC},\mref{mMeasure}, \mref{mPyA}, \mref{mEne} \\ + SR-PR 1 & Not implemented in code \\ + SR-PR 2 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mEne} \\ + SR-AUR 1-2 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mEve} \\ + SR-IM 1 & Not implemented in code \\ \bottomrule \end{tabular} \caption{Trace Between Security Requirements and Modules} @@ -696,9 +1049,9 @@ \section{Traceability Matrix} \label{SecTM} \toprule \textbf{Req.} & \textbf{Modules}\\ \midrule % Cultural - CULT 1-3 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}\\ - CL-LR 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ - CL-SCR 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mTest}\\ + CULT 1-2 & \mref{mExe}, \mref{mBac}, \mref{mDet}, \mref{mRef}, \mref{mHig}, \mref{mHov}, \mref{mMan}, \mref{mFil}, \mref{mVie} \\ + CL-LR 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mEve}, \mref{Ene}, \mref{mVie}, \mref{mExe}, \mref{mBac} \\ + CL-SCR 1 & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLLF}, \mref{mLPL}, \mref{mLMC}, \mref{mMeasure}, \mref{mPyA}, \mref{mEve}, \mref{Ene}, \mref{mVie}, \mref{mExe}, \mref{mBac}, \mref{mSmell} \\ \bottomrule \end{tabular} \caption{Trace Between Cultural and Compliance Requirements and Modules} @@ -711,12 +1064,11 @@ \section{Traceability Matrix} \label{SecTM} \toprule \textbf{AC} & \textbf{Modules}\\ \midrule - \acref{acUserInterface} & \mref{mExe}, \mref{mHig} , \mref{mHov}, \mref{mMan} \\ + \acref{acUserInterface} & \mref{mExe}, \mref{mHig} , \mref{mHov}, \mref{mMan}, \mref{mVie}, \mref{mFil}, \mref{mEve}, \mref{mEne} \\ \acref{acVSCodePlugin} & \mref{mExe} , \mref{mRef}, \mref{mMan} \\ - \acref{acRefactorers} & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLPL} \\ + \acref{acRefactorers} & \mref{mBR}, \mref{mMIMR}, \mref{mSCLR}, \mref{mUGENR}, \mref{mCRC}, \mref{mLEC}, \mref{mLPL}, \mref{mLLF}, \mref{mLMC} \\ \acref{acSmell} & \mref{mDet}, \mref{mPyA} \\ \acref{acAnalyzer} & \mref{mMeasure}, \mref{mPyA}, \mref{mDet} \\ - \acref{acTesting} & \mref{mTest} \\ \bottomrule \end{tabular} \caption{Trace Between Anticipated Changes and Modules} @@ -734,33 +1086,33 @@ \section{Use Hierarchy Between Modules} \label{SecUse} the modules. It can be seen that the graph is a directed acyclic graph (DAG). Each level of the hierarchy offers a testable and usable subset of the system, and modules in the higher level of the hierarchy are essentially simpler -because they use modules from the lower levels.Furthermore, figure \ref{FigUH_Plugin} +because they use modules from the lower levels. Furthermore, figure \ref{FigUH_Plugin} illustrates the use relation between the modules of the VS Code Plugin, vis-a-vis the Source Code Optimizer displayed in figure \ref{FigUH}. In this figure for the plugin, the modules at the lowest level are the ones closest to the user, and going up in the module indicates moving towards the backend of the project, which is the Source Code Optimizer. It is a layered architecture where each module serves a separate concern. -\wss{The uses relation is not a data flow diagram. In the code there will often -be an import statement in module A when it directly uses module B. Module B -provides the services that module A needs. The code for module A needs to be -able to see these services (hence the import statement). Since the uses +\wss{The uses relation is not a data flow diagram. In the code there will often +be an import statement in module A when it directly uses module B. Module B +provides the services that module A needs. The code for module A needs to be +able to see these services (hence the import statement). Since the uses relation is transitive, there is a use relation without an import, but the arrows in the diagram typically correspond to the presence of import statement.} \wss{If module A uses module B, the arrow is directed from A to B.} \begin{figure}[H] -\centering -\includegraphics[width=\textwidth]{../../Images/sco_use_diagram.png} -\caption{Use hierarchy among modules} -\label{FigUH} -\end{figure} - + \centering + \includegraphics[width=\textwidth]{../../Images/sco_use_diagram.png} + \caption{EcoOptimizer Use Hierarchy among modules} + \label{FigUH} + \end{figure} + \begin{figure}[H] \centering \includegraphics[width=\textwidth]{../../Images/plugin_use_diagram.png} - \caption{Use hierarchy among modules} + \caption{VS Code Plugin Use Hierarchy among modules(yellow blocks, EcoOptimizer is green block. Note that colours of arrows are only intended for visual distinction)} \label{FigUH_Plugin} \end{figure} @@ -819,7 +1171,58 @@ \section{Design of Communication Protocols} \section{Timeline} -All code and corresponding documentation was aimed to be completed before Jan 6th our Demo date for our supervisor. +The project development is structured in two main phases. The foundational library phase has been completed, and we are now moving into the plugin implementation phase. The January timeline focuses on implementing the VS Code plugin modules that depend on the existing library functionality. + +\subsection{Development Phases} + +\begin{enumerate} + \item \textbf{Completed Library Phase (September - December 2024)} + \begin{itemize} + \item Base Refactorer and all specialized refactoring modules + \item Core Smell detection and data structures + \item Analysis infrastructure and measurement components + \item Energy metrics and measurement functionality + \end{itemize} + + \item \textbf{Plugin Implementation and Testing Phase (January 2025)} + \begin{itemize} + \item Development of VS Code plugin modules that interface with the library + \item Implementation of user interface components + \item Integration of library functionality into the VS Code environment + \item Unit and integration testing for library and plugin + \end{itemize} +\end{enumerate} + +\subsection{Module Dependencies} + +The plugin development schedule considers the following dependencies: + +\begin{itemize} + \item All plugin modules depend on the completed library components + \item Plugin Initiator and Backend Communicator must be completed first as they establish the connection to the library + \item UI components (File Highlighter, Hover Manager, View Provider) can be developed in parallel once core communication is established + \item Cache Manager and Filter Manager require working UI components +\end{itemize} + +\begin{table}[h!] + \centering + \caption{Plugin Module Timeline} + \begin{tabular}{|l|l|l|l|} + \hline + \textbf{Module Name} & \textbf{Team Member} & \textbf{Due Date} & \textbf{Dependencies} \\ \hline + Plugin Initiator & All & Feb 05, 2025 & Library Modules \\ \hline + Backend Communicator & All & Feb 05, 2025 & Library Modules \\ \hline + Smell Detector & All & Feb 05, 2025 & Backend Communicator \\ \hline + File Highlighter & All & Feb 05, 2025 & Smell Detector \\ \hline + Hover Manager & All & Feb 05, 2025 & Smell Detector \\ \hline + Cache Manager & All & Feb 20, 2025 & Smell Detector \\ \hline + Filter Manager & All & Feb 20, 2025 & Cache Manager \\ \hline + View Provider & All & Feb 20, 2025 & File Highlighter, Hover Manager \\ \hline + Event Manager & All & Feb 20, 2025 & All Plugin Modules \\ \hline + \end{tabular} +\end{table} + +The timeline prioritizes establishing the connection between the plugin and the existing library components, followed by the development of user-facing features. The January 31st deadline for supporting modules allows time for thorough integration testing and refinement of the complete system. \begin{table}[h!] \centering @@ -839,7 +1242,6 @@ \section{Timeline} Smell & All & Jan 31, 2025 \\ \hline Analyzers & All & Jan 31, 2025 \\ \hline Measurements & All & Jan 31, 2025 \\ \hline - Testing Functionality & All & Jan 31, 2025 \\ \hline \end{tabular} \end{table} diff --git a/docs/Design/SoftArchitecture/README.md b/docs/Design/SoftArchitecture/README.md index e41d35c1..9ebbf087 100644 --- a/docs/Design/SoftArchitecture/README.md +++ b/docs/Design/SoftArchitecture/README.md @@ -1,3 +1,29 @@ -# Module Guide +# Software Architecture Directory -The folders and files for the module guide. +This directory contains the software architecture documentation for the Source Code Optimizer project, detailing the high-level system design and architectural decisions. + +## Directory Contents + +### Core Documentation +- `MG.tex` - Module Guide documentation source +- `Makefile` - Build configuration for documentation generation + +## Usage Guidelines + +1. Documentation Standards + - LaTeX formatting + - Version control + +2. Maintenance + - Version tracking + - Team approval + +## Best Practices + +1. Architecture Documentation + - Clear structure + - Consistent terminology + +2. Change Management + - Version control + - Change tracking \ No newline at end of file diff --git a/docs/Design/SoftDetailedDes/MIS.pdf b/docs/Design/SoftDetailedDes/MIS.pdf index e5cb9dd5..bc69454f 100644 Binary files a/docs/Design/SoftDetailedDes/MIS.pdf and b/docs/Design/SoftDetailedDes/MIS.pdf differ diff --git a/docs/Design/SoftDetailedDes/MIS.tex b/docs/Design/SoftDetailedDes/MIS.tex index c5b9da00..559bd9cc 100644 --- a/docs/Design/SoftDetailedDes/MIS.tex +++ b/docs/Design/SoftDetailedDes/MIS.tex @@ -51,9 +51,14 @@ \section{Revision History} \begin{tabularx}{\textwidth}{p{3cm}p{2cm}X} -\toprule {\bf Date} & {\bf Version} & {\bf Notes}\\ +\toprule {\bf Date} & {\bf Name} & {\bf Notes}\\ \midrule -January 17th, 2025 & 0.1 & Initial Draft\\ +January 17th, 2025 & All & Initial Draft\\ +March 24th, 2025 & Mya Hussain & Removed Pythonic Syntax Mentions\\ +March 24th, 2025 & Mya Hussain & Added Some References to Local Functions\\ +March 24th, 2025 & Mya Hussain & Modified Wrong Environment Variables\\ +March 25th, 2025 & Tanveer Brar & Added MIS for new plugin modules\\ +March 28th, 2025 & Tanveer Brar & Addressed TA and Peer Review Feedback Issues\\ \bottomrule \end{tabularx} @@ -75,7 +80,7 @@ \section{Symbols, Abbreviations and Acronyms} \section{Introduction} -The following document details the Module Interface Specifications (MIS) for the Source Code Optimizer project. The Source Code Optimizer is a software tool designed to analyze, refactor, and optimize Python source code to improve energy efficiency, maintainability, and performance. This tool incorporates a combination of static code analysis using Pylint, abstract syntax tree (AST) parsing, and custom refactoring techniques to detect and address various code smells in Python programs. +The following document details the Module Interface Specifications (MIS) for the Source Code Optimizer project. The Source Code Optimizer is a software tool designed to analyse, refactor, and optimise Python source code to improve energy efficiency, maintainability, and performance. This tool incorporates a combination of static code analysis using Pylint, abstract syntax tree (AST) parsing, and custom refactoring techniques to detect and address various code smells in Python programs. The application allows developers to identify inefficient coding patterns, refactor them into optimized alternatives, and validate the results through built-in testing mechanisms. Key features include support for custom smell detection, energy profiling, and modular refactorers tailored to specific code smells, such as long method chains or inefficient list comprehensions. By automating parts of the optimization process, the Source Code Optimizer helps developers have the option of choosing to reduce emissions and produce more efficient software. @@ -103,9 +108,9 @@ \section{Notation} boolean & $\mathbb{B}$ & True or False\\ code smell & Smell & a collection of data representing a code smell\\ path & Path & Data object representing a path in a filesystem\\ - list & list[T] & a collection of objects of type T\\ - set & set[T] & a collection of \textit{unique} objects of type T\\ - dictionary & dict & data structure containing multiple key-value pairs\\ + list & list[T] & an ordered collection of objects of type T\\ + set & set[T] & an unordered collection of \textit{unique} objects of type T\\ + dictionary & dict[key] = value & data structure containing multiple key-value pairs\\ AST Node & AST & AST node representing any AST node\\ AST Constant & Constant & AST node representing a constant\\ AST Function Definition & FuncDef & AST node representing a function definition\\ @@ -137,40 +142,45 @@ \section{Module Decomposition} \begin{table}[h!] \centering \begin{tabular}{p{0.3\textwidth} p{0.6\textwidth}} - \toprule - \textbf{Level 1} & \textbf{Level 2}\\ - \midrule - - {Hardware-Hiding Module} & None \\ - \midrule - - \multirow{7}{0.3\textwidth}{Behaviour-Hiding Module} & Smell Module\\ - & BaseRefactorer Module\\ - & MakeStaticRefactorer Module\\ - & UseListAccumulationRefactorer Module\\ - & UseAGeneratorRefactorer Module\\ - & CacheRepeatedCallsRefactorer Module\\ - & LongElementChainRefactorer Module\\ - & LongParameterListRefactorer Module\\ - & LongMessageChainRefactorer Module\\ - & LongLambdaFunctionRefactorer Module\\ - & PluginInitiator Module\\ - & BackendCommunicator Module\\ - & SmellDetector Module\\ - & FileHighlighter Module\\ - & HoverManager Module\\ - \midrule - - - \multirow{3}{0.3\textwidth}{Software Decision Module} & Measurements Module\\ - & PylintAnalyzer Module\\ + \toprule + \textbf{Level 1} & \textbf{Level 2}\\ + \midrule + + {Hardware-Hiding Module} & None \\ + \midrule + + \multirow{7}{0.3\textwidth}{Behaviour-Hiding Module} & Smell Module\\ + & BaseRefactorer Module\\ + & MakeStaticRefactorer Module\\ + & UseListAccumulationRefactorer Module\\ + & UseAGeneratorRefactorer Module\\ + & CacheRepeatedCallsRefactorer Module\\ + & LongElementChainRefactorer Module\\ + & LongParameterListRefactorer Module\\ + & LongMessageChainRefactorer Module\\ + & LongLambdaFunctionRefactorer Module\\ + & PluginInitiator Module\\ + & BackendCommunicator Module\\ + & SmellDetector Module\\ + & FileHighlighter Module\\ + & HoverManager Module\\ + & CacheManager Module\\ + & FilterManager Module\\ + \midrule + + + \multirow{3}{0.3\textwidth}{Software Decision Module} & Measurements Module\\ +& PylintAnalyzer Module\\ & Testing Functionality Module\\ - & SmellRefactorer Module\\ - & RefactorManager Module\\ - \bottomrule - \end{tabular} - \caption{Module Hierarchy} - \label{TblMH} +& SmellRefactorer Module\\ +& RefactorManager Module\\ +& EnergyMetrics Module\\ +& ViewProvider Module\\ +& EventManager Module\\ +\bottomrule +\end{tabular} +\caption{Module Hierarchy} +\label{TblMH} \end{table} ~\newpage @@ -228,17 +238,15 @@ \subsubsection{Access Routine Semantics} \subsubsection{Local Functions} None. - -\newpage -\section{MIS of Base Refactorer} \label{mis:baseR} +\section{MIS of BaseRefactorer} \label{mis:baseR} \texttt{BaseRefactorer} \subsection{Module} -The interface that all refactorers of this system will inherit from. +The base interface that all refactorers inherit from, providing common functionality for file I/O, AST manipulation, code validation, and energy measurement integration. \subsection{Uses} @@ -252,51 +260,146 @@ \subsection{Syntax} \textbf{Exported Access Programs}: \begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} - \hline - \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline - \texttt{\_\_init\_\_} & \texttt{output\_dir: Path} & \texttt{self} & None \\\hline - \texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: dict, initial\_emissions: $\mathbb{R}$} & None & None \\ - \hline +\hline +\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline +\texttt{BaseRefactorer} & \texttt{output\_dir: Path} & \texttt{self} & None \\\hline +\texttt{refactor} & \texttt{file\_path: Path, smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{IOError} \\\hline +\texttt{parse\_ast} & \texttt{source: str} & \texttt{AST} & \texttt{SyntaxError} \\\hline +\texttt{validate\_transformation} & \texttt{original: AST, modified: AST} & \texttt{bool} & None \\\hline +\texttt{write\_output} & \texttt{path: Path, content: str} & None & \texttt{IOError} \\\hline +\texttt{measure\_energy} & \texttt{before: float, after: float} & \texttt{float} & None \\\hline +\texttt{apply\_transformation} & \texttt{node: AST} & \texttt{AST} & None \\\hline \end{tabularx} \subsection{Semantics} \subsubsection{State Variables} \begin{itemize} - \item \texttt{temp\_dir: Path}: Directory path for storing refactored files. + \item \texttt{output\_dir: Path}: Directory for output files + \item \texttt{temp\_dir: Path}: Directory for temporary files during processing + \item \texttt{ast\_cache}: Cache for parsed AST trees + \item \texttt{transformation\_state}: Tracks current refactoring state + \item \texttt{energy\_metrics}: Stores energy consumption measurements \end{itemize} \subsubsection{Environment Variables} -None +\begin{itemize} + \item \texttt{WORKSPACE\_ROOT}: Root directory of the workspace + \item \texttt{FILE\_PERMISSIONS}: Required file access permissions + \item \texttt{TEMP\_DIR\_CONFIG}: Configuration for temporary directory +\end{itemize} \subsubsection{Assumptions} \begin{itemize} - \item \texttt{output\_dir} exists or can be created, and write permissions are available. + \item Input files are valid Python scripts + \item Output directory exists or can be created + \item Write permissions are available for output directory + \item AST transformations preserve program semantics \end{itemize} \subsubsection{Access Routine Semantics} -\paragraph{\texttt{\_\_init\_\_(self, output\_dir: Path)}} +\paragraph{\texttt{BaseRefactorer(output\_dir: Path)}} +\begin{itemize} + \item \textbf{Transition}: + \begin{itemize} + \item Initializes temporary directory using \texttt{\_create\_temp\_dir} + \item Sets up AST cache using \texttt{\_setup\_ast\_cache} + \item Configures transformation state + \item Initializes energy metrics + \end{itemize} + \item \textbf{Output}: \texttt{self} + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{refactor(file\_path: Path, smell: Smell, initial\_emissions: $\mathbb{R}$)}} +\begin{itemize} + \item \textbf{Transition}: + \begin{itemize} + \item Reads and parses source file using \texttt{parse\_ast} + \item Applies transformation using \texttt{apply\_transformation} + \item Validates changes using \texttt{validate\_transformation} + \item Measures energy impact using \texttt{measure\_energy} + \item Writes output using \texttt{write\_output} if valid + \item Cleans up using \texttt{\_cleanup\_temp\_files} + \end{itemize} + \item \textbf{Output}: None + \item \textbf{Exception}: \texttt{IOError} if file operations fail +\end{itemize} + +\paragraph{\texttt{parse\_ast(source: str)}} +\begin{itemize} + \item \textbf{Transition}: Parses source code into AST representation + \item \textbf{Output}: AST object + \item \textbf{Exception}: \texttt{SyntaxError} for invalid Python code +\end{itemize} + +\paragraph{\texttt{validate\_transformation(original: AST, modified: AST)}} \begin{itemize} - \item \textbf{transition}: Initializes the \texttt{temp\_dir} variable within \texttt{output\_dir}. - \item \textbf{output}: \texttt{self} - \item \textbf{exception:} None. + \item \textbf{Transition}: Verifies semantic equivalence between ASTs + \item \textbf{Output}: Boolean indicating valid transformation + \item \textbf{Exception}: None \end{itemize} -\paragraph{\texttt{refactor(self, file\_path: Path, pylint\_smell: dict, initial\_emissions: $\mathbb{R}$)}} +\paragraph{\texttt{write\_output(path: Path, content: str)}} \begin{itemize} - \item \textbf{transition}: Abstract method. No transition defined. - \item \textbf{output}: None. - \item \textbf{exception:} None. + \item \textbf{Transition}: Writes transformed code after \texttt{\_validate\_permissions} + \item \textbf{Output}: None + \item \textbf{Exception}: \texttt{IOError} for file system issues +\end{itemize} + +\paragraph{\texttt{measure\_energy(before: float, after: float)}} +\begin{itemize} + \item \textbf{Transition}: Calculates energy consumption difference + \item \textbf{Output}: Float representing energy impact + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{apply\_transformation(node: AST)}} +\begin{itemize} + \item \textbf{Transition}: Abstract method for specific refactoring logic + \item \textbf{Output}: Modified AST + \item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} -None. -\newpage +\paragraph{\texttt{\_create\_temp\_dir()}} +\begin{itemize} + \item \textbf{Transition}: Creates a temporary directory for storing intermediate files + \item \textbf{Output}: Path to created directory + \item \textbf{Exception}: \texttt{IOError} if directory creation fails +\end{itemize} + +\paragraph{\texttt{\_setup\_ast\_cache()}} +\begin{itemize} + \item \textbf{Transition}: Initializes cache for storing parsed AST nodes + \item \textbf{Output}: None + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_cleanup\_temp\_files()}} +\begin{itemize} + \item \textbf{Transition}: Removes all temporary files and directories + \item \textbf{Output}: None + \item \textbf{Exception}: \texttt{IOError} if cleanup fails +\end{itemize} +\paragraph{\texttt{\_validate\_permissions()}} +\begin{itemize} + \item \textbf{Transition}: Verifies read/write permissions for target files + \item \textbf{Output}: Boolean indicating if permissions are valid + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_update\_energy\_metrics()}} +\begin{itemize} + \item \textbf{Transition}: Updates energy consumption measurements + \item \textbf{Output}: None + \item \textbf{Exception}: None +\end{itemize} -\section{MIS of Long Message Chain Refactorer} \label{mis:LMC} +\section{MIS of LongMessageChainRefactorer} \label{mis:LMC} \texttt{LongMessageChainRefactorer} @@ -321,12 +424,11 @@ \subsubsection{Exported Access Programs} \begin{center} \begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|p{1in}|p{1in}|} \hline -\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ -\hline -\texttt{\_\_init\_\_} & \texttt{output\_dir: Path} & \texttt{self} & None \\ -\hline -\texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{TypeError}, \texttt{IOError} \\ -\hline +\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline +\texttt{apply\_transformation} & \texttt{node: AST} & \texttt{AST} & None \\\hline +\texttt{identify\_chains} & \texttt{node: AST} & \texttt{List[Chain]} & None \\\hline +\texttt{extract\_methods} & \texttt{chain: Chain} & \texttt{List[str]} & None \\\hline +\texttt{generate\_vars} & \texttt{methods: List[str]} & \texttt{List[str]} & None \\\hline \end{tabularx} \end{center} @@ -336,59 +438,91 @@ \subsection{Semantics} \subsubsection{State Variables} \begin{itemize} - \item \textbf{temp\_dir}: Temporary directory for intermediate refactored files. + \item \texttt{chain\_patterns}: Dictionary mapping chain types to their patterns + \item \texttt{intermediate\_vars}: List of generated variable names + \item \texttt{indentation\_map}: Mapping of line numbers to indentation levels \end{itemize} \subsubsection{Environment Variables} +Inherits from \texttt{BaseRefactorer} +\subsubsection{Assumptions} \begin{itemize} - \item \textbf{File system}: Used to read, write, and store temporary and refactored files. - - \item \textbf{Logger}: Logs information during refactoring. - + \item Message chains are properly terminated + \item Variable names generated do not conflict with existing ones + \item Indentation is consistent within code blocks \end{itemize} -\subsubsection{Assumptions} +\subsubsection{Access Routine Semantics} +\paragraph{\texttt{apply\_transformation(node: AST)}} \begin{itemize} - \item Input files are valid Python scripts. - \item Smells identified by \textbf{pylint\_smell} include valid line numbers. - \item Refactored code must pass the provided test suite. + \item \textbf{Transition}: + \begin{itemize} + \item Identifies message chains using \texttt{identify\_chains} + \item Extracts methods using \texttt{extract\_methods} + \item Generates intermediate variables using \texttt{generate\_vars} + \item Validates chain breaks using \texttt{\_validate\_chain\_break} + \item Preserves code formatting using \texttt{\_preserve\_indentation} + \item Reconstructs code with intermediate assignments + \end{itemize} + \item \textbf{Output}: Modified AST + \item \textbf{Exception}: None \end{itemize} -\subsubsection{Access Routine Semantics} -\paragraph{\texttt{\_\_init\_\_(output\_dir: Path)}} +\paragraph{\texttt{identify\_chains(node: AST)}} \begin{itemize} -\item \textbf{Transition}: Initializes the refactorer with the specified output directory. -\item \textbf{Output}: \texttt{self}. -\item \textbf{Exception}: None. + \item \textbf{Transition}: Analyzes AST for message chain patterns using \texttt{\_analyze\_chain\_complexity} + \item \textbf{Output}: List of identified chains + \item \textbf{Exception}: None \end{itemize} -\paragraph{\texttt{refactor(file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$)}} +\paragraph{\texttt{extract\_methods(chain: Chain)}} \begin{itemize} - \item \textbf{Transition}: - \begin{itemize} - \item Reads the file at \texttt{file\_path}. - \item Identifies the line with a long message chain. - \item Refactors the chain by breaking it into separate statements. - \item Writes the refactored code to a temporary file. - \item Evaluates the refactored code’s energy efficiency and functionality. - \end{itemize} - \item \textbf{Output}: None. Refactored file is saved if improvements are validated. - \item \textbf{Exception}: Raises \texttt{IOError} if input file cannot be read. Raises \texttt{TypeError} if source file cannot be parsed into an AST. + \item \textbf{Transition}: Extracts individual method calls from chain using \texttt{\_preserve\_indentation} + \item \textbf{Output}: List of method call strings + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{generate\_vars(methods: List[str])}} +\begin{itemize} + \item \textbf{Transition}: Creates unique variable names using \texttt{\_generate\_unique\_name} + \item \textbf{Output}: List of variable names + \item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} -\paragraph{\texttt{remove\_unmatched\_brackets(input\_string: str)}} + +\paragraph{\texttt{\_analyze\_chain\_complexity(chain: Chain)}} \begin{itemize} -\item \textbf{Transition}: Removes unmatched parentheses from the input string. -\item \textbf{Output}: Returns the string with unmatched parentheses removed. -\item \textbf{Exception}: None. + \item \textbf{Transition}: Analyzes the length and complexity of method call chains + \item \textbf{Output}: Integer representing chain complexity + \item \textbf{Exception}: None \end{itemize} -~\newpage +\paragraph{\texttt{\_preserve\_indentation(line: str)}} +\begin{itemize} + \item \textbf{Transition}: Extracts and preserves the indentation level of code lines + \item \textbf{Output}: String containing the indentation spaces + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_validate\_chain\_break(original: str, parts: List[str])}} +\begin{itemize} + \item \textbf{Transition}: Verifies that breaking the chain preserves functionality + \item \textbf{Output}: Boolean indicating if chain break is valid + \item \textbf{Exception}: None +\end{itemize} -\section{MIS of Long Lambda Function Refactorer} \label{mis:LLF} +\paragraph{\texttt{\_generate\_unique\_name(base: str)}} +\begin{itemize} + \item \textbf{Transition}: Creates a unique variable name based on the base string + \item \textbf{Output}: String containing unique variable name + \item \textbf{Exception}: None +\end{itemize} + + +\section{MIS of LongLambdaFunctionRefactorer} \label{mis:LLF} \texttt{LongLambdaFunctionRefactorer} @@ -398,10 +532,8 @@ \subsection{Module} This improves code readability, maintainability, and performance, while reducing potential energy consumption. \subsection{Uses} -\begin{itemize} - \item Uses \texttt{Smell} interface for data access - \item Inherits from \texttt{BaseRefactorer} -\end{itemize} + +\texttt{BaseRefactorer} \subsection{Syntax} @@ -410,75 +542,118 @@ \subsubsection{Exported Constants} \subsubsection{Exported Access Programs} -\begin{center} -\begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|p{1in}|p{1in}|} -\hline -\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ -\hline -\texttt{\_\_init\_\_} & \texttt{output\_dir: Path} & \texttt{self} & None \\ -\hline -\texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{TypeError}, \texttt{IOError} \\ +\begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} \hline +\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline +\texttt{LongLambdaFunctionRefactorer} & \texttt{output\_dir: Path} & \texttt{self} & None \\\hline +\texttt{refactor} & \texttt{file\_path: Path, smell: Smell, initial\_emi \allowbreak ssions: $\mathbb{R}$} & None & \texttt{IOError} \\\hline +\texttt{identify\_lambdas} & \texttt{node: AST} & \texttt{List[Lambda]} & None \\\hline +\texttt{extract\_lambda\_components} & \texttt{lambda\_node: Lambda} & \texttt{(List[str], str)} & None \\\hline +\texttt{generate\_function\_name} & \texttt{lambda\_body: str} & \texttt{str} & None \\\hline \end{tabularx} -\end{center} \subsection{Semantics} \subsubsection{State Variables} - \begin{itemize} - \item \textbf{temp\_dir}: Temporary directory for intermediate refactored files. + \item \textbf{lambda\_registry}: Dictionary mapping lambda nodes to their locations + \item \textbf{function\_counter}: Counter for generating unique function names + \item \textbf{scope\_stack}: Stack tracking current scope for function placement \end{itemize} \subsubsection{Environment Variables} - -\begin{itemize} - \item \textbf{File system}: Used to read, write, and store temporary and refactored files. - - \item \textbf{Logger}: Logs information during refactoring. -\end{itemize} +Inherits from \texttt{BaseRefactorer} \subsubsection{Assumptions} - \begin{itemize} - \item Input files are valid Python scripts. - \item Smells identified by \textbf{pylint\_smell} include valid line numbers. - \item Refactored code must pass the provided test suite. + \item Input code contains valid Python syntax + \item Lambda functions are properly defined + \item Generated function names do not conflict with existing ones + \item Scope information is correctly maintained \end{itemize} \subsubsection{Access Routine Semantics} -\paragraph{\texttt{\_\_init\_\_(output\_dir: Path)}} +\paragraph{\texttt{LongLambdaFunctionRefactorer(output\_dir: Path)}} \begin{itemize} -\item \textbf{Transition}: Initializes the refactorer with the specified output directory. -\item \textbf{Output}: \texttt{self}. -\item \textbf{Exception}: None. + \item \textbf{Transition}: + \begin{itemize} + \item Initializes base refactorer + \item Sets up lambda registry + \item Initializes function counter + \item Configures scope tracking + \end{itemize} + \item \textbf{Output}: \texttt{self} + \item \textbf{Exception}: None \end{itemize} -\paragraph{\texttt{refactor(file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$)}} +\paragraph{\texttt{refactor(file\_path: Path, smell: Smell, initial\_emissions: $\mathbb{R}$)}} \begin{itemize} \item \textbf{Transition}: \begin{itemize} - \item Reads the file at \texttt{file\_path}. - \item Identifies the line with a long lambda function. - \item Refactors the lambda into a normal function. - \item Writes the refactored code to a temporary file. + \item Reads source file + \item Identifies long lambda functions + \item Converts lambdas to named functions + \item Validates transformation + \item Writes refactored code if valid \end{itemize} - \item \textbf{Output}: None. Refactored file is saved if improvements are validated. - \item \textbf{Exception}: Raises \texttt{IOError} if input file cannot be read. Raises \texttt{TypeError} if source file cannot be parsed into an AST. + \item \textbf{Output}: None + \item \textbf{Exception}: \texttt{IOError} if file operations fail +\end{itemize} + +\paragraph{\texttt{identify\_lambdas(node: AST)}} +\begin{itemize} + \item \textbf{Transition}: Analyzes AST node for lambda function definitions + \item \textbf{Output}: List of identified lambda nodes + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{extract\_lambda\_components(lambda\_node: Lambda)}} +\begin{itemize} + \item \textbf{Transition}: Extracts parameters and body from lambda function + \item \textbf{Output}: Tuple of parameter list and body string + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{generate\_function\_name(lambda\_body: str)}} +\begin{itemize} + \item \textbf{Transition}: Creates descriptive name based on lambda body + \item \textbf{Output}: Generated function name + \item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} -\paragraph{\texttt{truncate\_at\_top\_level\_comma(body: str)}} + +\paragraph{\texttt{\_analyze\_lambda\_complexity(node: Lambda)}} \begin{itemize} -\item \textbf{Transition}: Truncates the lambda body at the first top-level comma, ignoring commas within nested parentheses, brackets, or braces. -\item \textbf{Output}: Returns the truncated lambda body as a string. -\item \textbf{Exception}: None. + \item \textbf{Transition}: Analyzes lambda function complexity based on length and nesting + \item \textbf{Output}: Integer representing complexity score + \item \textbf{Exception}: None \end{itemize} -~\newpage +\paragraph{\texttt{\_find\_insertion\_point(node: AST)}} +\begin{itemize} + \item \textbf{Transition}: Determines optimal location for new function definition + \item \textbf{Output}: AST node indicating insertion point + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_validate\_scope(node: AST)}} +\begin{itemize} + \item \textbf{Transition}: Verifies scope compatibility for function placement + \item \textbf{Output}: Boolean indicating valid scope + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_create\_function\_def(name: str, params: List[str], body: str)}} +\begin{itemize} + \item \textbf{Transition}: Generates AST node for new function definition + \item \textbf{Output}: FunctionDef AST node + \item \textbf{Exception}: None +\end{itemize} -\section{MIS of Long Parameter List Refactorer} \label{Module} + +\section{MIS of LongParameterListRefactorer} \label{Module} \texttt{LongParameterListRefactorer} @@ -507,7 +682,7 @@ \subsubsection{Exported Access Programs} \hline \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ \hline -\texttt{\_\_init\_\_} & \texttt{output\_dir: Path} & \texttt{self} & None \\ +\texttt{LongParameterListRefactorer} & \texttt{output\_dir: Path} & \texttt{self} & None \\ \hline \texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{TypeError}, \texttt{IOError} \\ \hline @@ -521,11 +696,7 @@ \subsubsection{State Variables} None \subsubsection{Environment Variables} - -\begin{itemize} -\item \textbf{File system}: Used for reading, writing, and storing temporary and refactored files. -\item \textbf{Logger}: Logs details of the refactoring process. -\end{itemize} +None \subsubsection{Assumptions} @@ -537,7 +708,7 @@ \subsubsection{Assumptions} \subsubsection{Access Routine Semantics} -\paragraph{\texttt{\_\_init\_\_(output\_dir: Path)}} +\paragraph{\texttt{LongParameterListRefactorer(output\_dir: Path)}} \begin{itemize} \item \textbf{Transition}: Initializes the refactorer with the specified output directory. \item \textbf{Output}: \texttt{self}. @@ -546,232 +717,459 @@ \subsubsection{Access Routine Semantics} \paragraph{\texttt{refactor(file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$)}} \begin{itemize} -\item \textbf{Transition}: -\begin{enumerate} -\item Reads the file at \texttt{file\_path} and locates the target function using \texttt{pylint\_smell}. -\item Analyzes function body to remove unused parameters. Updates the function signature and references in the code accordingly. -\item If number of used parameters also exceeds the maximum configured limit, encapsulates related parameters into classes. Updates the function signature and references in the code accordingly. -\item Writes the refactored code to a temporary file. -\end{enumerate} -\item \textbf{Output}: None.Refactored file is saved if improvements are validated. -\item \textbf{Exception}: Raises \texttt{IOError} if input file cannot be read. Raises \texttt{TypeError} if source file cannot be parsed into an AST. -\end{itemize} + \item \textbf{Transition}: + \begin{enumerate} + \item Reads the file at \texttt{file\_path} and locates the target function using \texttt{pylint\_smell}. + \item Analyzes function body using \texttt{get\_used\_parameters} to identify used parameters and remove unused ones. + \item For remaining parameters that exceed the configured limit: + \begin{itemize} + \item Groups parameters using \texttt{classify\_parameters} + \item Creates parameter classes using \texttt{create\_parameter\_object\_class} + \item Updates function signature using \texttt{update\_function\_signature} + \item Updates parameter usages using \texttt{update\_parameter\_usages} + \item Updates function calls using \texttt{update\_function\_calls} + \end{itemize} + \item Writes the refactored code to a temporary file. + \end{enumerate} + \item \textbf{Output}: None. Refactored file is saved if improvements are validated. + \item \textbf{Exception}: Raises \texttt{IOError} if input file cannot be read. Raises \texttt{TypeError} if source file cannot be parsed into an AST. + \end{itemize} \subsubsection{Local Functions} \begin{enumerate} -\item \texttt{get\_used\_parameters(function\_node: FuncDef, params: list[str]) -> set[str]}: Identifies parameters used within the function body. -\item \texttt{get\_parameters\_with\_default\_value(default\_values: list[Constant], params: list[str]) -> dict}: Maps parameter names to their default values. -\item \texttt{classify\_parameters(params: list[str]) -> dict}: Classifies parameters into \texttt{data} and \texttt{config} groups based on naming conventions. -\item \texttt{create\_parameter\_object\_class(param\_names: list[str], default\_value\_params: dict, class\_name: str) -> str}: Generates class definitions for encapsulating parameters. -\item \texttt{update\_function\_signature(function\_node: FuncDef, params: dict) -> FuncDef}: Updates function signatures to use encapsulated parameter objects. -\item \texttt{update\_parameter\_usages(function\_node: FuncDef, params: dict) -> FuncDef}: Replaces parameter usages within the function body with attributes of encapsulated objects. -\item \texttt{update\_function\_calls(tree: Module, function\_node: FuncDef, params: dict) -> Module}: Updates all calls to the refactored function. -\end{enumerate} + \item \texttt{get\_used\_parameters(function\_node: ast.FunctionDef, params: list[str]) -> list[str]}: + \begin{itemize} + \item \textbf{transition}: Identifies parameters used within the function body. + \item \textbf{output}: List of names of parameters that are actually used in the function. + \item \textbf{exception}: None + \end{itemize} + \item \texttt{get\_parameters\_with\_default\_value(params: list[ast.Param]) -> key-value pairs}: + \begin{itemize} + \item \textbf{transition}: Maps parameter names to their default values . + \item \textbf{output}: Key-value pairs mapping parameter names to their default values. + \item \textbf{exception}: None + \end{itemize} + \item \texttt{classify\_parameters(params: list[str]) -> key-value pairs}: + \begin{itemize} + \item \textbf{transition}: Classifies parameters into \texttt{data} and \texttt{config} groups based on naming conventions. + \item \textbf{output}: Key-value pairs with keys "data\_params" and "config\_params" mapping to lists of parameter names. + \item \textbf{exception}: None + \end{itemize} + \item \texttt{create\_parameter\_object\_class(param\_names: list[str], default\_value\_params: key-value pairs, class\_name: str) -> ast.ClassDef}: + \begin{itemize} + \item \textbf{transition}: Creates an AST class definition for encapsulating related parameters. + \item \textbf{output}: AST ClassDef node representing the parameter object class. + \item \textbf{exception}: None + \end{itemize} + \item \texttt{update\_function\_signature(function\_node: ast.FunctionDef, classified\_params: key-value pairs) -> ast.FunctionDef}: + \begin{itemize} + \item \textbf{transition}: Updates function signatures to use encapsulated parameter objects. + \item \textbf{output}: Updated AST FunctionDef node with new parameter structure. + \item \textbf{exception}: None + \end{itemize} + \item \texttt{update\_parameter\_usages(function\_node: ast.FunctionDef, classified\_params: key-value pairs) -> ast.FunctionDef}: + \begin{itemize} + \item \textbf{transition}: Updates parameter references in function body to use encapsulated object attributes. + \item \textbf{output}: Updated AST FunctionDef node with transformed parameter usages. + \item \textbf{exception}: None + \end{itemize} + \item \texttt{update\_function\_calls(tree: ast.Module, function\_node: ast.FunctionDef, used\_params: list[str], classified\_params: key-value pairs, classified\_param\_names: tuple[str, str], enclosing\_class\_name: str) -> ast.Module}: + \begin{itemize} + \item \textbf{transition}: Updates all calls to the refactored function to use new parameter structure. + \item \textbf{output}: Updated AST Module node with transformed function calls. + \item \textbf{exception}: None + \end{itemize} + \end{enumerate} + + \section{MIS of UseListAccumulationRefactorer} \label{mis:ListAccum} + + \texttt{UseListAccumulationRefactorer} + + \subsection{Module} + + The \texttt{UseListAccumulationRefactorer} module identifies and refactors + string concatenations in loops in Python code to improve the performance and energy efficiency of the software. It specifically handles these concatenations by, instead, adding the string for each iteration to a list that is then converted to a string, ensuring proper refactoring while maintaining the original functionality. + + \subsection{Uses} + \begin{itemize} + \item Uses \texttt{Smell} interface for data access + \item Inherits from \texttt{BaseRefactorer} + \item Uses \texttt{astroid} library for AST manipulation + \end{itemize} + + \subsection{Syntax} + \noindent + \textbf{Exported Constants}: None + + \noindent + \textbf{Exported Access Programs}: + + \begin{tabularx}{\linewidth}{| + l| + >{\raggedright\arraybackslash}X| + l| + l|} + \hline + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ + \hline + \texttt{UseListAccumulationRefactorer} & \texttt{output\_dir: Path} & \texttt{self} & None \\ + \hline + \texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{TypeError}, \texttt{IOError} \\ + \hline + \end{tabularx} + + \subsection{Semantics} + + \subsubsection{State Variables} + \begin{itemize} + \item \texttt{target\_lines: list[int]}: Line numbers requiring refactoring + \item \texttt{assign\_var: str}: Target concatenation variable name + \item \texttt{target\_node: NodeNG}: AST node of concatenation target + \item \texttt{last\_assign\_node: Assign|AugAssign}: Last variable assignment before loop + \item \texttt{concat\_nodes: list[Assign|AugAssign]}: Detected concatenation nodes + \item \texttt{reassignments: list[Assign]}: Variable reassignments in loop scope + \item \texttt{outer\_loop: For|While}: Outermost loop containing concatenations + \end{itemize} + + \subsubsection{Environment Variables} + None + + \subsubsection{Assumptions} + \begin{itemize} + \item Input files contain valid Python syntax + \item Smell detection provides valid line numbers and variable names + \end{itemize} + + \subsubsection{Access Routine Semantics} + + \paragraph{\texttt{UseListAccumulationRefactorer(output\_dir: Path)}} + \begin{itemize} + \item \textbf{Transition}: Initializes refactorer with output directory + \item \textbf{Output}: \texttt{self} + \item \textbf{Exception}: None + \end{itemize} + + \paragraph{\texttt{refactor(file\_path: Path, pylint\_smell: Smell, initial\_emissions: + R + R)}} + \begin{itemize} + \item \textbf{Transition}: + \begin{itemize} + \item Parses code using \texttt{\_visit} pattern for AST traversal + \item Identifies concatenations with \texttt{\_find\_reassignments} + \item Determines scope via \texttt{\_find\_scope} and \texttt{\_find\_last\_assignment} + \item Generates temp names with \texttt{\_generate\_temp\_list\_name} + \item Modifies code using \texttt{\_add\_node\_to\_body} + \item Validates transformations before writing to refactored file + \end{itemize} + \item \textbf{Output}: None + \item \textbf{Exception}: + \begin{itemize} + \item \texttt{IOError}: File read/write failures + \item \texttt{TypeError}: AST parsing errors + \end{itemize} + \end{itemize} + + \subsubsection{Local Functions} + + \paragraph{\texttt{\_visit(node: NodeNG)}} + \begin{itemize} + \item \textbf{Transition}: Collects concatenation nodes and loop structures + \item \textbf{Output}: None + \item \textbf{Exception}: None + \end{itemize} + + \paragraph{\texttt{\_find\_reassignments()}} + \begin{itemize} + \item \textbf{Transition}: Finds variable reassignments in loop scope + \item \textbf{Output}: None + \item \textbf{Exception}: None + \end{itemize} + + \paragraph{\texttt{\_find\_last\_assignment(scope: NodeNG)}} + \begin{itemize} + \item \textbf{Transition}: Locates final variable assignment before loop + \item \textbf{Output}: None + \item \textbf{Exception}: Raises \texttt{TypeError} for invalid scope + \end{itemize} + + \paragraph{\texttt{\_find\_scope()}} + \begin{itemize} + \item \textbf{Transition}: Determines insertion point for list initialization + \item \textbf{Output}: None + \item \textbf{Exception}: Requires \texttt{concat\_nodes} to be populated + \end{itemize} + + \paragraph{\texttt{\_generate\_temp\_list\_name()}} + \begin{itemize} + \item \textbf{Transition}: Creates unique list name for complex targets + \item \textbf{Output}: Returns generated name string + \item \textbf{Exception}: Raises \texttt{TypeError} for unsupported nodes + \end{itemize} + + \paragraph{\texttt{\_add\_node\_to\_body(code\_file: str, nodes\_to\_change: list[tuple])}} + \begin{itemize} + \item \textbf{Transition}: + \begin{itemize} + \item Replaces concatenations with list operations + \item Adds join() call and list initialization + \end{itemize} + \item \textbf{Output}: Returns modified source code + \item \textbf{Exception}: Requires valid node references + \end{itemize} -\section{MIS of Use List Accumulation Refactorer} \label{mis:ListAccum} -\texttt{UseListAccumulationRefactorer} +\section{MIS of MakeMethodStaticRefactorer} \label{mis:MakeStatic} + +\texttt{MakeStaticRefactorer} \subsection{Module} -The \texttt{UseListAccumulationRefactorer} module identifies and refactors -string concatenations in loops in Python code to improve the performance and energy efficiency of the software. It specifically handles these concatenations by, instead, adding the string for each iteration to a list that is then converted to a string using Python's \texttt{join()} function, ensuring proper refactoring while maintaining the original functionality. +The \texttt{MakeStaticRefactorer} module identifies and refactors +class methods that don't make use of their instance attributes to improve the readability, performance and energy efficiency of the software. It specifically handles these methods by turning them into static functions and ensuring any calls to this method use the proper calling syntax. This ensures proper refactoring while maintaining the original functionality. \subsection{Uses} -\begin{itemize} - \item Uses \texttt{Smell} interface for data access - \item Inherits from \texttt{BaseRefactorer} - \item Inherits from Python's \texttt{ast} module's \texttt{NodeTransformer} -\end{itemize} - + +\texttt{BaseRefactorer} + \subsection{Syntax} + \noindent -\textbf{Exported Constants}: None +\textbf{Exported Constants}: None\\ \noindent -\textbf{Exported Access Programs}: - -\begin{tabularx}{\linewidth}{| - l| - >{\raggedright\arraybackslash}X| - l| - l|} - \hline - \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ - \hline - \texttt{\_\_init\_\_} & \texttt{output\_dir: Path} & \texttt{self} & None \\ - \hline - \texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: Real} & None & \texttt{TypeError}, \texttt{IOError} \\ - \hline +\textbf{Exported Access Programs}:\\ + +\begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} +\hline +\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline +\texttt{apply\_transformation} & \texttt{node: AST} & \texttt{AST} & None \\\hline +\texttt{identify\_methods} & \texttt{node: AST} & \texttt{List[Method]} & None \\\hline +\texttt{analyze\_method\_usage} & \texttt{method: Method} & \texttt{bool} & None \\\hline +\texttt{transform\_to\_static} & \texttt{method: Method} & \texttt{Method} & None \\\hline \end{tabularx} - + \subsection{Semantics} - + \subsubsection{State Variables} \begin{itemize} - \item \texttt{target\_line: int}: Line number where refactoring is applied. - \item \texttt{target\_node: ASTnode}: Node representing the concatenation variable. - \item \texttt{assign\_var: str}: Name of the variable the \texttt{target\_node} represents. - \item \texttt{last\_assign\_node: ASTnode}: Last initialization/assignment of the \texttt{assign\_var} prior to the start of the loop. - \item \texttt{concat\_node: ASTnode}: Node where concatenation occurs. - \item \texttt{scope\_node: ASTnode}: Scope where refactoring is inserted. - \item \texttt{outer\_loop: ASTnode}: Outermost loop before the start of the concatenation. + \item \texttt{class\_hierarchy}: Dictionary mapping classes to their inheritance tree + \item \texttt{method\_registry}: Dictionary mapping methods to their usage patterns + \item \texttt{static\_candidates}: Set of methods eligible for static conversion \end{itemize} - + \subsubsection{Environment Variables} -None - +Inherits from \texttt{BaseRefactorer} + \subsubsection{Assumptions} \begin{itemize} - \item The input file contains valid Python syntax. - \item \texttt{pylint\_smell} provides a valid line number for the detected code smell. + \item Class inheritance hierarchies are well-defined + \item Method definitions are complete and valid + \item No dynamic method creation or modification \end{itemize} - + \subsubsection{Access Routine Semantics} - -\paragraph{\texttt{\_\_init\_\_(self, output\_dir: Path)}} + +\paragraph{\texttt{apply\_transformation(node: AST)}} +\begin{itemize} + \item \textbf{Transition}: + \begin{itemize} + \item Identifies candidate methods using \texttt{identify\_methods} + \item Analyzes each method using \texttt{analyze\_method\_usage} + \item Transforms eligible methods using \texttt{transform\_to\_static} + \item Updates method calls using \texttt{\_update\_method\_calls} + \item Validates transformation using \texttt{\_validate\_transformation} + \item Reconstructs code with static methods + \end{itemize} + \item \textbf{Output}: Modified AST + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{identify\_methods(node: AST)}} \begin{itemize} - \item \textbf{transition}: Initializes the refactorer with \texttt{output\_dir} and sets default state variables. - \item \textbf{output}: \texttt{self}. - \item \textbf{exception}: None + \item \textbf{Transition}: Analyzes AST for instance methods using \texttt{\_build\_class\_hierarchy} + \item \textbf{Output}: List of identified methods + \item \textbf{Exception}: None \end{itemize} - -\paragraph{\texttt{refactor(self, file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$)}} + +\paragraph{\texttt{analyze\_method\_usage(method: Method)}} +\begin{itemize} + \item \textbf{Transition}: Evaluates method for static conversion using \texttt{\_check\_inheritance\_safety} + \item \textbf{Output}: Boolean indicating if method can be made static + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{transform\_to\_static(method: Method)}} \begin{itemize} - \item \textbf{transition}: Parses \texttt{file\_path}, identifies string concatenations in loops, modifies code for list accumulation, and writes refactored code to a file. - \item \textbf{output}: None. - \item \textbf{exception}: Raises \texttt{IOError} if input file cannot be read. Raises \texttt{TypeError} if source file cannot be parsed into an AST. + \item \textbf{Transition}: Converts instance method to static using \texttt{\_update\_method\_calls} and validates using \texttt{\_validate\_transformation} + \item \textbf{Output}: Transformed method + \item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} -\paragraph{\texttt{find\_last\_assignment(self, scope: ASTnode)}} + +\paragraph{\texttt{\_build\_class\_hierarchy(node: AST)}} \begin{itemize} - \item \textbf{transition}: Identifies the last assignment of \texttt{assign\_var} within the given \texttt{scope}. - \item \textbf{output}: None. - \item \textbf{exception}: Raises \texttt{TypeError} if given scope is null. + \item \textbf{Transition}: Analyzes class definitions and builds inheritance relationships + \item \textbf{Output}: Dictionary mapping classes to their parent classes + \item \textbf{Exception}: None \end{itemize} -\paragraph{\texttt{find\_scope()}} +\paragraph{\texttt{\_check\_inheritance\_safety(method: Method)}} \begin{itemize} - \item \textbf{transition}: Finds the scope for refactoring based on AST node ancestry. - \item \textbf{output}: None. - \item \textbf{exception}: Raises \texttt{TypeError} if \texttt{concat\_node} is not set. + \item \textbf{Transition}: Verifies method can be safely made static across inheritance chain + \item \textbf{Output}: Boolean indicating if transformation is safe + \item \textbf{Exception}: None \end{itemize} -\paragraph{\texttt{add\_node\_to\_body(self, code\_file: str)}} +\paragraph{\texttt{\_update\_method\_calls(old\_method: str, new\_method: str)}} \begin{itemize} - \item \textbf{transition}: Inserts list accumulation and join statements into \texttt{code\_file}. - \item \textbf{output}: Returns the modified source code as a string. - \item \textbf{exception}: Raises \texttt{TypeError} if \texttt{target\_node} or \texttt{outer\_loop} is not set. + \item \textbf{Transition}: Updates all call sites to use static method syntax + \item \textbf{Output}: None + \item \textbf{Exception}: None \end{itemize} - -\newpage -\section{MIS of Make Method Static Refactorer} \label{mis:MakeStatic} +\paragraph{\texttt{\_validate\_transformation(method: Method)}} +\begin{itemize} + \item \textbf{Transition}: Verifies the static method transformation maintains functionality + \item \textbf{Output}: Boolean indicating if transformation is valid + \item \textbf{Exception}: None +\end{itemize} -\texttt{MakeStaticRefactorer} +\newpage -\subsection{Module} -The \texttt{MakeStaticRefactorer} module identifies and refactors -class methods that don't make use of their instance attributes to improve the readability, performance and energy efficiency of the software. It specifically handles these methods by turning them into static functions and ensuring any calls to this method use the proper calling syntax. This ensures proper refactoring while maintaining the original functionality. +\section{MIS of LongElementChainRefactorer} \label{mis:lec} + +\texttt{LongElementChainRefactorer} + +\subsection{Module} + +LongElementChainRefactorer is a module that refactors long element chains, specifically focusing on flattening nested dictionaries to improve readability, maintainability, and energy efficiency. The module uses a recursive flattening strategy while caching previously seen patterns for optimization. + +\subsection{Uses} + +\texttt{BaseRefactorer} -\subsection{Uses} -\begin{itemize} - \item Uses \texttt{Smell} interface for data access - \item Inherits from \texttt{BaseRefactorer} - \item Inherits from Python's \texttt{ast} module's \texttt{NodeTransformer} -\end{itemize} - \subsection{Syntax} -\noindent -\textbf{Exported Constants}: None -\noindent -\textbf{Exported Access Programs}: - +\subsubsection{Exported Constants} +None + +\subsubsection{Exported Access Programs} + \begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} - \hline - \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ - \hline - \texttt{\_\_init\_\_} & \texttt{output\_dir: Path} & \texttt{self} & None \\ - \hline - \texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{TypeError}, \texttt{IOError} \\ - \hline +\hline +\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline +\texttt{apply\_transformation} & \texttt{node: AST} & \texttt{AST} & None \\\hline +\texttt{identify\_nested\_dicts} & \texttt{node: AST} & \texttt{List[Dict]} & None \\\hline +\texttt{flatten\_dict} & \texttt{dict\_node: Dict} & \texttt{Dict} & None \\\hline +\texttt{update\_access\_calls} & \texttt{old\_path: str, new\_path: str} & None & None \\\hline \end{tabularx} - + \subsection{Semantics} - + \subsubsection{State Variables} \begin{itemize} - \item \texttt{target\_line: int}: Line number where refactoring is applied. - \item \texttt{mim\_method\_class: str}: Class name containing the method to refactor. - \item \texttt{mim\_method: str}: Method name to refactor. + \item \textbf{dict\_patterns}: Dictionary mapping access patterns to their flattened forms + \item \textbf{flattened\_keys}: Set of generated flattened key names + \item \textbf{reference\_map}: Mapping of original to flattened dictionary paths \end{itemize} - + \subsubsection{Environment Variables} -None - +Inherits from \texttt{BaseRefactorer} + \subsubsection{Assumptions} \begin{itemize} - \item The input file contains valid Python syntax. - \item \texttt{pylint\_smell} provides a valid line number for the detected code smell. + \item Dictionary keys are valid Python identifiers + \item No key name conflicts in flattened structure + \item Dictionary access patterns are consistent \end{itemize} - + \subsubsection{Access Routine Semantics} - -\paragraph{\texttt{\_\_init\_\_(self, output\_dir: Path)}} + +\paragraph{\texttt{apply\_transformation(node: AST)}} \begin{itemize} - \item \textbf{transition}: Initializes the refactorer with \texttt{output\_dir} and sets default state variables. - \item \textbf{output}: \texttt{self}. - \item \textbf{exception}: None. + \item \textbf{Transition}: + \begin{itemize} + \item Identifies nested dictionaries using \texttt{identify\_nested\_dicts} + \item Flattens each dictionary using \texttt{flatten\_dict} + \item Updates access patterns using \texttt{update\_access\_calls} + \item Updates code references using \texttt{\_update\_references} + \item Validates dictionary access using \texttt{\_validate\_dict\_access} + \item Reconstructs code with flattened structure + \end{itemize} + \item \textbf{Output}: Modified AST + \item \textbf{Exception}: None \end{itemize} - -\paragraph{\texttt{refactor(self, file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$)}} + +\paragraph{\texttt{identify\_nested\_dicts(node: AST)}} +\begin{itemize} + \item \textbf{Transition}: Analyzes AST for nested dictionary patterns using \texttt{\_analyze\_dict\_complexity} + \item \textbf{Output}: List of identified dictionaries + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{flatten\_dict(dict\_node: Dict)}} +\begin{itemize} + \item \textbf{Transition}: Creates flattened dictionary structure using \texttt{\_generate\_flat\_key} + \item \textbf{Output}: Flattened dictionary + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{update\_access\_calls(old\_path: str, new\_path: str)}} \begin{itemize} - \item \textbf{transition}: Parses \texttt{file\_path}, identifies the target function, modifies it to be static, and validates refactoring. - \item \textbf{output}: None. - \item \textbf{exception}: Raises \texttt{IOError} if input file cannot be read. Raises \texttt{TypeError} if source file cannot be parsed into an AST. + \item \textbf{Transition}: Updates dictionary access patterns using \texttt{\_validate\_dict\_access} and \texttt{\_update\_references} + \item \textbf{Output}: None + \item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} -\paragraph{\texttt{visit\_FunctionDef(self, node: FuncDef)}} + +\paragraph{\texttt{\_analyze\_dict\_complexity(node: Dict)}} \begin{itemize} - \item \textbf{transition}: Adds the \texttt{staticmethod} decorator to the target method and removes the \texttt{self} parameter if present. - \item \textbf{output}: Returns the modified \texttt{FunctionDef} node. - \item \textbf{exception}: None + \item \textbf{Transition}: Analyzes the nesting depth and structure of dictionary nodes + \item \textbf{Output}: Integer representing complexity score + \item \textbf{Exception}: None \end{itemize} -\paragraph{\texttt{visit\_ClassDef(self, node: ClassDef)}} +\paragraph{\texttt{\_generate\_flat\_key(path: List[str])}} \begin{itemize} - \item \textbf{transition}: Identifies the class containing the target method. - \item \textbf{output}: Returns the modified \texttt{ClassDef} node. - \item \textbf{exception}: None. + \item \textbf{Transition}: Concatenates path components into a flattened key name + \item \textbf{Output}: String representing the flattened key + \item \textbf{Exception}: None \end{itemize} -\paragraph{\texttt{visit\_Call(self, node: Call)}} +\paragraph{\texttt{\_validate\_dict\_access(path: str)}} \begin{itemize} - \item \textbf{transition}: Updates method call references to use the class name instead of \texttt{self}. - \item \textbf{output}: Returns the modified \texttt{Call} node. - \item \textbf{exception}: None. + \item \textbf{Transition}: Checks if dictionary access path is valid and follows conventions + \item \textbf{Output}: Boolean indicating validity + \item \textbf{Exception}: None \end{itemize} - -\newpage -\section{MIS of Long Element Chain Refactorer} \label{mis:lec} +\paragraph{\texttt{\_update\_references(old\_ref: str, new\_ref: str)}} +\begin{itemize} + \item \textbf{Transition}: Updates all references to the old dictionary path with the new flattened path + \item \textbf{Output}: None + \item \textbf{Exception}: None +\end{itemize} -\texttt{LongElementChainRefactorer} +\section{MIS of Measurements Module} \label{mis:measure} + +\texttt{Measurements} \subsection{Module} -LongElementChainRefactorer is a module that refactors long element chains, specifically focusing on flattening nested dictionaries to improve readability, maintainability, and energy efficiency. The module uses a recursive flattening strategy while caching previously seen patterns for optimization. +The MeasurementsModule is a module designed to measure and track the carbon emissions generated by executing scripts. By leveraging the CodeCarbon library, it allows developers to assess the environmental impact of their code execution. The module runs a specified Python file, tracks the associated carbon emissions during the execution, and logs the results for further analysis. It provides functionality for measuring, logging, and extracting emissions data in a structured manner to help improve energy efficiency in software development. + \subsection{Uses} \begin{itemize} - \item Uses \texttt{Smell} interface for data access - \item Inherits from \texttt{BaseRefactorer} +\item Uses \texttt{CodeCarbon} library for track energy consumption +\item Uses \texttt{TemporaryDirectory} to store temporary files +\item Inherits from \texttt{BaseEnergyMeter} \end{itemize} \subsection{Syntax} @@ -786,9 +1184,9 @@ \subsubsection{Exported Access Programs} \hline \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ \hline -\texttt{\_\_init\_\_} & \texttt{output\_dir: Path} & \texttt{self} & None \\ +\texttt{Measurements} & \texttt{output\_dir: Path} & \texttt{self} & None \\ \hline -\texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{TypeError}, \texttt{IOError} \\ +\texttt{measure\_energy} & \texttt{None} & None & CalledProcessError and FileReading exceptions \\ \hline \end{tabularx} \end{center} @@ -798,196 +1196,247 @@ \subsection{Semantics} \subsubsection{State Variables} \begin{itemize} - \item \textbf{\_reference\_map}: Maps element chain references to their line numbers and corresponding values. +\item \textbf{emissions\_data}: Stores the emissions data extracted from the CSV file generated by CodeCarbon. It is populated after the energy measurement process completes successfully. The value is either a dictionary containing the last row of emissions data or \texttt{None} if no data was extracted due to an error. +\item \textbf{emissions}: Raw emissions object from CodeCarbon tracker \end{itemize} \subsubsection{Environment Variables} - -\begin{itemize} - \item \textbf{File system}: Used to read, write, and store temporary and refactored files. - \item \textbf{Logger}: Logs information during the refactoring process. -\end{itemize} +None \subsubsection{Assumptions} \begin{itemize} - \item Input files are valid Python scripts. - \item Smells identified by \textbf{pylint\_smell} include valid line numbers. - \item Refactored code must pass the provided test suite. +\item The file at \texttt{file\_path} is a valid Python script. +\item The CodeCarbon tool is properly installed and configured. +\item The \texttt{EmissionsTracker} can successfully execute the Python script specified by \texttt{file\_path}. +\item The emissions data is captured in a CSV format and can be extracted correctly. +\item The temporary directories are correctly set up and accessible during execution. \end{itemize} \subsubsection{Access Routine Semantics} -\paragraph{\texttt{\_\_init\_\_(output\_dir: Path)}} +\paragraph{\texttt{Measurements(output\_dir: Path)}} \begin{itemize} -\item \textbf{Transition}: Initializes the refactorer with the specified output directory and sets up internal caching structures. -\item \textbf{Output}: \texttt{self}. -\item \textbf{Exception}: None. +\item \textbf{Transition}: Initializes the energy meter with empty emissions data +\item \textbf{Output}: \texttt{self} +\item \textbf{Exception}: None \end{itemize} -\paragraph{\texttt{refactor(file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$)}} +\paragraph{\texttt{measure\_energy()}} \begin{itemize} - \item \textbf{Transition}: - \begin{itemize} - \item Reads the file at \texttt{file\_path}. - \item Identifies nested dictionary chains for flattening. - \item Refactors the identified chain by flattening the dictionary and replacing its occurrences. - \item Writes the refactored code to a temporary file. +\item \textbf{Transition}: +\begin{itemize} +\item Logs the start of the energy measurement process +\item Creates isolated temporary directory using \texttt{TemporaryDirectory} +\item Configures system temp directories through environment variables +\item Initializes CodeCarbon \texttt{EmissionsTracker} in process mode +\item Runs the script specified by file path and captures the output +\item Stops tracker and captures raw emissions data +\item Validates emissions CSV creation +\item Parses results using \texttt{extract\_emissions\_csv} \end{itemize} - \item \textbf{Output}: None. Refactored file is saved if improvements are validated. - \item \textbf{Exception}: Raises \texttt{IOError} if input file cannot be read. Raises \texttt{TypeError} if source file cannot be parsed into an AST. +\item \textbf{Output}: +\begin{itemize} +\item Updates \texttt{emissions} with tracker results +\item Populates \texttt{emissions\_data} with parsed metrics \end{itemize} - -\subsubsection{Local Functions} +\item \textbf{Exception}: \begin{itemize} - \item \textbf{\_flatten\_dict(d: dict[str, Any], parent\_key?: str)} \\ - Recursively flattens a nested dictionary by combining keys with underscores. - - \item \textbf{\_extract\_dict\_literal(node: ASTnode)} \\ - Converts an Abstract Syntax Tree (AST) dictionary literal into a Python dictionary. - - \item \textbf{\_find\_dict\_assignments(tree: ASTnode, name: str)} \\ - Extracts dictionary assignments given the name of the dictionary from the AST and returns them as a dictionary. - - \item \textbf{\_collect\_dict\_references(tree: ASTnode)} \\ - Identifies and stores all dictionary access patterns in the `\_reference\_map`. - - \item \textbf{\_generate\_flattened\_access(base\_var: str, access\_chain: list[str])} \\ - Generates a flattened dictionary key string by combining elements of an access chain with underscores. +\item \texttt{CalledProcessError}: If script execution fails +\item \texttt{FileNotFoundError}: If emissions CSV is missing +\end{itemize} \end{itemize} +\subsubsection{Local Functions} +\paragraph{\texttt{extract\_emissions\_csv(csv\_file\_path: Path)}} +\begin{itemize} + \item \textbf{Transition}: + \begin{itemize} + \item Attempts to read CSV file using pandas + \item Extracts last measurement record + \item Converts DataFrame row to dictionary + \end{itemize} + \item \textbf{Output}: Returns dictionary of metrics or \texttt{None} on error + \item \textbf{Exception}: Logs pandas read errors but does not propagate them +\end{itemize} + + +\newpage +\section{MIS of PylintAnalyzer} \label{mis:PylintAnalyzer} -\section{MIS of Measurements Module} \label{mis:measure} - -\texttt{Measurements} +\texttt{PylintAnalyzer} \subsection{Module} -The MeasurementsModule is a module designed to measure and track the carbon emissions generated by executing Python scripts. By leveraging the CodeCarbon library, it allows developers to assess the environmental impact of their code execution. The module runs a specified Python file, tracks the associated carbon emissions during the execution, and logs the results for further analysis. It provides functionality for measuring, logging, and extracting emissions data in a structured manner to help improve energy efficiency in software development. +The \texttt{PylintAnalyzer} module performs static code analysis on Python files using Pylint, with additional custom checks for detecting specific code smells. It outputs detected smells in a structured format for further processing. \subsection{Uses} - \begin{itemize} - \item Uses \texttt{CodeCarbon} library for track energy consumption - \item Uses \texttt{TemporaryDirectory} to store temporary files - \item Inherits from \texttt{BaseEnergyMeter} +\item Uses Python's \texttt{pylint} library for code analysis +\item Uses \texttt{ast} module for parsing and analyzing abstract syntax trees +\item Uses \texttt{astor} library for converting AST nodes back to source code +\item Integrates with custom checkers, including \texttt{StringConcatInLoopChecker} +\item Accesses configuration settings from \texttt{analyzers\_config} \end{itemize} \subsection{Syntax} +\noindent +\textbf{Exported Constants}: None -\subsubsection{Exported Constants} -None - -\subsubsection{Exported Access Programs} - -\begin{center} -\begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} -\hline -\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ -\hline -\texttt{\_\_init\_\_} & \texttt{output\_dir: Path} & \texttt{self} & None \\ -\hline -\texttt{measure\_energy} & \texttt{None} & None & CalledProcessError and FileReading exceptions \\ -\hline +\noindent +\textbf{Exported Access Programs}:\\ +{\footnotesize +\begin{tabularx}{\linewidth}{| + l| + >{\raggedright\arraybackslash}X| + l| + l|} + \hline + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline + \texttt{PylintAnalyzer} & \texttt{file\_path: Path, source\_code: Module} & \texttt{self} & None \\ + \hline + \texttt{build\_pylint\_options} & None & \texttt{list[str]} & None \\ + \hline + \texttt{analyze} & None & None & \texttt{JSONDecodeError}, \texttt{Exception} \\ + \hline + \texttt{configure\_smells} & None & None & None \\ + \hline + \texttt{filter\_for\_one\_code\_smell} & \texttt{pylint\_results: list[Smell], code: str} & \texttt{list[Smell]} & None \\ + \hline \end{tabularx} -\end{center} +} \subsection{Semantics} \subsubsection{State Variables} - \begin{itemize} - \item \textbf{Emissions\_data}: Stores the emissions data extracted from the CSV file generated by CodeCarbon. It is populated after the energy measurement process completes successfully. The value is either a dictionary containing the last row of emissions data or \texttt{None} if no data was extracted due to an error. - +\item \texttt{file\_path: Path}: The path to the Python file being analyzed +\item \texttt{source\_code: Module}: The parsed abstract syntax tree of the source file +\item \texttt{smells\_data: list[dict]}: List of detected code smells in dictionary format \end{itemize} \subsubsection{Environment Variables} +None +\subsubsection{Assumptions} \begin{itemize} - \item \textbf{TEMP}: Sets the temporary directory location for Windows systems. Used during the CodeCarbon energy measurement process. - \item \textbf{TMPDIR}: Sets the temporary directory location for Unix-based systems. Used during the CodeCarbon energy measurement process. - \item \textbf{Logger}: A logging mechanism that logs various events during the energy measurement process, including errors, completion of measurements, and other key actions. +\item The input file is valid Python code and can be parsed into an AST +\item Configuration settings (extra Pylint options, custom smell definitions) are valid \end{itemize} -\subsubsection{Assumptions} +\subsubsection{Access Routine Semantics} +\paragraph{\texttt{PylintAnalyzer(file\_path: Path, source\_code: Module)}} \begin{itemize} - \item The file at \texttt{file\_path} is a valid Python script. - \item The CodeCarbon tool is properly installed and configured. - \item The \texttt{EmissionsTracker} can successfully execute the Python script specified by \texttt{file\_path}. - \item The emissions data is captured in a CSV format and can be extracted correctly. - \item The temporary directories are correctly set up and accessible during execution. +\item \textbf{Transition}: Initializes analyzer with file path and AST +\item \textbf{Output}: \texttt{self} +\item \textbf{Exception}: None \end{itemize} -\subsubsection{Access Routine Semantics} -\paragraph{\texttt{\_\_init\_\_(file\_path: Path)}} +\paragraph{\texttt{build\_pylint\_options()}} \begin{itemize} - \item \textbf{Transition}: Initializes the \texttt{CodeCarbonEnergyMeter} with the specified file path and logger. It sets up the necessary internal state for energy measurement and prepares the environment. - \item \textbf{Output}: \texttt{self}. - \item \textbf{Exception}: None. +\item \textbf{Transition}: Constructs Pylint options list from config +\item \textbf{Output}: List of option strings +\item \textbf{Exception}: None \end{itemize} -\paragraph{\texttt{measure\_energy()}} +\paragraph{\texttt{analyze()}} \begin{itemize} - \item \textbf{Transition}: - \begin{itemize} - \item Logs the start of the energy measurement process. - \item Creates a temporary directory to store custom data. - \item Initializes the \texttt{EmissionsTracker} from CodeCarbon. - \item Runs the script specified by \texttt{file\_path} and captures the output. - \item Stops the tracker after execution and stores the emissions data. - \item If available, it extracts the emissions data from the generated CSV file. - \end{itemize} - \item \textbf{Output}: - \begin{itemize} - \item Logs the results of the energy measurement process. - \item Stores the emissions data in \texttt{self.emissions\_data}. - \end{itemize} - \item \textbf{Exception}: - \begin{itemize} - \item Logs an error if the file cannot be executed or if the emissions file is not created. - \item If the emissions data cannot be extracted from the CSV file, logs the issue. - \end{itemize} - \end{itemize} +\item \textbf{Transition}: +\begin{itemize} +\item Executes Pylint analysis with custom checks using the local detect functions +\item Populates \texttt{smells\_data} with results and uses \texttt{parse\_line} +\end{itemize} +\item \textbf{Output}: None +\item \textbf{Exception}: +\begin{itemize} +\item \texttt{JSONDecodeError} for invalid Pylint output +\item \texttt{Exception} for general runtime errors +\end{itemize} +\end{itemize} + +\paragraph{\texttt{configure\_smells()}} +\begin{itemize} +\item \textbf{Transition}: Filters \texttt{smells\_data} to configured smells +\item \textbf{Output}: None +\item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{filter\_for\_one\_code\_smell(pylint\_results: list[Smell], code: str)}} +\begin{itemize} +\item \textbf{Transition}: Filters results by smell type code +\item \textbf{Output}: Filtered list of smells +\item \textbf{Exception}: None +\end{itemize} \subsubsection{Local Functions} -\paragraph{\texttt{\_extract\_emissions\_csv(csv\_file\_path: Path)}} - - Extracts emissions data from a CSV file generated by CodeCarbon. - \begin{itemize} - \item \textbf{Input}: \texttt{csv\_file\_path} - The path to the CSV file containing emissions data. - \item \textbf{Output}: Returns the last row of emissions data as a dictionary, or \texttt{None} if an error occurs. - \end{itemize} - - -\newpage +\paragraph{\texttt{\_detect\_long\_message\_chain(threshold?: int)}} +\begin{itemize} + \item \textbf{Transition}: Identifies method chains exceeding length threshold + \item \textbf{Output}: List of long chain smells + \item \textbf{Exception}: None +\end{itemize} -\section{MIS of Pylint Analyzer} \label{mis:PylintAnalyzer} +\paragraph{\texttt{\_detect\_long\_lambda\_expression(threshold\_length?: int, threshold\_count?: int)}} +\begin{itemize} + \item \textbf{Transition}: Detects oversized lambda expressions + \item \textbf{Output}: List of lambda smells + \item \textbf{Exception}: None +\end{itemize} -\texttt{PylintAnalyzer} +\paragraph{\texttt{\_detect\_long\_element\_chain(threshold?: int)}} +\begin{itemize} + \item \textbf{Transition}: Finds long dictionary access chains + \item \textbf{Output}: List of element chain smells + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_detect\_repeated\_calls(threshold?: int)}} +\begin{itemize} + \item \textbf{Transition}: Identifies excessive repeated calls + \item \textbf{Output}: List of repetition smells + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_parse\_line(file\_path: Path, line: int)}} +\begin{itemize} + \item \textbf{Transition}: Extracts AST node from specific line + \item \textbf{Output}: Parsed AST node + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_get\_lambda\_code(lambda\_node: Lambda)}} +\begin{itemize} + \item \textbf{Transition}: Converts lambda node to source code + \item \textbf{Output}: String representation of lambda + \item \textbf{Exception}: None +\end{itemize} + +\section{MIS of UseAGeneratorRefactorer} \label{mis:UseGen} + +\texttt{UseAGeneratorRefactorer} \subsection{Module} -The \texttt{PylintAnalyzer} module performs static code analysis on Python files using Pylint, with additional custom checks for detecting specific code smells. It outputs detected smells in a structured format for further processing. +The \texttt{UseAGeneratorRefactorer} module identifies and refactors +unnecessary list comprehensions in Python code by converting them to generator expressions. This refactoring improves energy efficiency while maintaining the original functionality. \subsection{Uses} \begin{itemize} - \item Uses Python's \texttt{pylint} library for code analysis - \item Uses \texttt{ast} module for parsing and analyzing abstract syntax trees - \item Uses \texttt{astor} library for converting AST nodes back to source code - \item Integrates with custom checkers, including \texttt{StringConcatInLoopChecker} - \item Accesses configuration settings from \texttt{analyzers\_config} +\item Uses \texttt{Smell} interface for data access +\item Inherits from \texttt{BaseRefactorer} +\item Uses Python's \texttt{ast} module for parsing and manipulating abstract syntax trees \end{itemize} \subsection{Syntax} \noindent \textbf{Exported Constants}: None + \noindent \textbf{Exported Access Programs}:\\ -{\footnotesize \begin{tabularx}{\linewidth}{| l| >{\raggedright\arraybackslash}X| @@ -995,283 +1444,516 @@ \subsection{Syntax} l|} \hline \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline - \texttt{\_\_init\_\_} & \texttt{file\_path: Path, source\_code: Module} & \texttt{self} & None \\ + \texttt{UseAGeneratorRefactorer} & \texttt{output\_dir: Path} & \texttt{self} & None \\ \hline - \texttt{build\_pylint\_options} & None & \texttt{list[str]} & None \\ + \texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{IOError}, \texttt{TypeError} \\ \hline - \texttt{analyze} & None & None & \texttt{JSONDecodeError}, \texttt{Exception} \\ +\end{tabularx} + +\subsection{Semantics} + +\subsubsection{State Variables} +\begin{itemize} +\item \texttt{temp\_dir: Path}: Directory path for storing refactored files +\item \texttt{output\_dir: Path}: Directory path for saving final refactored code +\end{itemize} + +\subsubsection{Environment Variables} +None + +\subsubsection{Assumptions} +\begin{itemize} +\item The input file contains valid Python syntax +\item \texttt{pylint\_smell} provides valid line/column locations +\end{itemize} + +\subsubsection{Access Routine Semantics} + +\paragraph{\texttt{UseAGeneratorRefactorer(output\_dir: Path)}} +\begin{itemize} +\item \textbf{Transition}: Initializes temporary directory within output directory +\item \textbf{Output}: \texttt{self} +\item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{refactor(file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$)}} +\begin{itemize} +\item \textbf{Transition}: +\begin{itemize} +\item Reads source code using \texttt{ListCompInAnyAllTransformer} metadata +\item Applies AST transformation via \texttt{\_replace\_node} for node substitution +\item Uses \texttt{leave\_Call} in transformer to identify replacement targets +\item Validates and writes modified code using generator expressions +\end{itemize} +\item \textbf{Output}: None +\item \textbf{Exception}: +\begin{itemize} +\item \texttt{IOError}: File read/write failures +\item \texttt{TypeError}: CST parsing errors +\end{itemize} +\end{itemize} + +\subsubsection{Local Functions} + +\paragraph{\texttt{\_replace\_node(tree: Module, old\_node: ListComp, new\_node: GeneratorExp)}} +\begin{itemize} +\item \textbf{Transition}: Replaces list comprehension node with generator expression +\item \textbf{Output}: Modified AST +\item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{ListCompInAnyAllTransformer}} +\begin{itemize} +\item \textbf{Transition}: Custom CST transformer that identifies and converts list comprehensions in any()/all() calls +\item \textbf{Output}: Modified syntax tree +\item \textbf{Exception}: None +\end{itemize} + +\section{MIS of CacheRepeatedCallsRefactorer} \label{mis:CacheCalls} + +\texttt{CacheRepeatedCallsRefactorer} + +\subsection{Module} +The \texttt{CacheRepeatedCallsRefactorer} identifies and caches repeated function calls using temporary variables to improve performance and energy efficiency while preserving functionality. + +\subsection{Uses} +\begin{itemize} +\item Uses \texttt{Smell} interface for data access +\item Inherits from \texttt{BaseRefactorer} +\item Uses Python's \texttt{ast} module for AST manipulation +\end{itemize} + +\subsection{Syntax} +\noindent +\textbf{Exported Constants}: None + +\noindent +\textbf{Exported Access Programs}:\\ +\begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} \hline - \texttt{configure\_smells} & None & None & None \\ + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline + \texttt{CacheRepeatedCallsRefactorer} & \texttt{output\_dir: Path} & \texttt{self} & None \\ \hline - \texttt{filter\_for\_one\_code\_smell} & \texttt{pylint\_results: list[Smell], code: str} & \texttt{list[Smell]} & None \\ + \texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{IOError}, \texttt{TypeError} \\ \hline \end{tabularx} -} \subsection{Semantics} \subsubsection{State Variables} \begin{itemize} - \item \texttt{file\_path: Path}: The path to the Python file being analyzed. - \item \texttt{source\_code: Module}: The parsed abstract syntax tree of the source file. - \item \texttt{smells\_data: list[dict]}: A list of detected code smells, represented as dictionaries. + \item \texttt{cached\_var\_name: str}: Name of the temporary variable used for caching. + \item \texttt{target\_line: int}: Line number where refactoring is applied. \end{itemize} \subsubsection{Environment Variables} None -\subsubsection{Assumptions} +\subsubsection{Assumptions} +\begin{itemize} +\item Input files contain valid Python syntax +\item Smell detection provides valid call patterns +\item Repeated calls have no side effects +\end{itemize} + +\subsubsection{Access Routine Semantics} + +\paragraph{\texttt{CacheRepeatedCallsRefactorer(output\_dir: Path)}} +\begin{itemize} +\item \textbf{Transition}: Initializes temp directory +\item \textbf{Output}: \texttt{self} +\item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{refactor(file\_path: Path, smell: CRCSmell, ...)}} +\begin{itemize} +\item \textbf{Transition}: +\begin{itemize} +\item Generates cache name via \texttt{\_extract\_function\_name} +\item Locates insertion point with \texttt{\_find\_insert\_line} +\item Determines indentation via \texttt{\_get\_indentation} +\item Modifies calls using \texttt{\_replace\_call\_in\_line} +\item Validates scope with \texttt{\_find\_valid\_parent} +\end{itemize} +\item \textbf{Output}: None +\item \textbf{Exception}: +\begin{itemize} +\item \texttt{IOError}: File access failures +\item \texttt{TypeError}: Invalid AST structure +\end{itemize} +\end{itemize} + +\subsubsection{Local Functions} + +\paragraph{\texttt{\_extract\_function\_name(call\_string: str)}} +\begin{itemize} + \item \textbf{Transition}: Extracts function name from call expression + \item \textbf{Output}: String containing function name + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_get\_indentation(lines: list[str], line\_number: int)}} +\begin{itemize} + \item \textbf{Transition}: Calculates whitespace for code insertion + \item \textbf{Output}: Indentation string + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_replace\_call\_in\_line(line: str, call\_string: str, cached\_var\_name: str)}} +\begin{itemize} + \item \textbf{Transition}: Replaces function calls with cache variable + \item \textbf{Output}: Modified source line + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_find\_valid\_parent(tree: ast.Module)}} +\begin{itemize} + \item \textbf{Transition}: Locates common parent for all call instances + \item \textbf{Output}: Parent AST node or None + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_find\_insert\_line(parent\_node: ast.AST)}} +\begin{itemize} + \item \textbf{Transition}: Determines optimal insertion point + \item \textbf{Output}: Line number for cache assignment + \item \textbf{Exception}: None +\end{itemize} + +\paragraph{\texttt{\_line\_in\_node\_body(node: ast.AST, line: int)}} +\begin{itemize} + \item \textbf{Transition}: Verifies line belongs to node body + \item \textbf{Output}: Boolean existence check + \item \textbf{Exception}: None +\end{itemize} + + +\section{MIS of PluginInitiator} + +\subsection{Module} +\texttt{PluginInitiator} is a module that initialises the VS Code plugin and registers commands for VS Code Plugin. + +\subsection{Uses} +\begin{itemize} + \item \texttt{SmellDetector} to register and manage smell detection functionality. + \item \texttt{RefactorManager} to register and manage refactoring operations. + \item \texttt{FilterManager} to register and manage smell filtering operations. +\end{itemize} + +\subsection{Syntax} + +\textbf{Exported Constants:} +\begin{itemize} + \item \texttt{ecoOutput}: VS Code OutputChannel for logging and information display +\end{itemize} + +\noindent \textbf{Exported Access Programs:}\\ +\begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} + \hline + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ + \hline + \texttt{activate} & \texttt{context: vscode.ExtensionContext} & void & None \\ + \hline + \texttt{deactivate} & None & void & None \\ + \hline + \texttt{isSmellLintingEnabled} & None & boolean & None \\ + \hline +\end{tabularx} + +\subsection{Semantics} + +\subsubsection{State Variables} +\begin{itemize} + \item \texttt{smellLintingEnabled: boolean} - Tracks if smell linting is enabled + \item \texttt{backendLogManager: LogManager} - Manages backend logging +\end{itemize} + +\subsubsection{Environment Variables} +\begin{itemize} + \item VS Code extension context + \item Workspace configuration state +\end{itemize} + +\subsubsection{Assumptions} +\begin{itemize} + \item The plugin is correctly loaded in VS Code + \item VS Code APIs are available and accessible + \item Required modules (SmellDetector, RefactorManager, FilterManager) are properly initialised +\end{itemize} + +\subsubsection{Access Routine Semantics} + +\noindent\texttt{activate(context: vscode.ExtensionContext)} +\begin{itemize} + \item \textbf{Transition}: + \begin{itemize} + \item Initialises output channel for logging + \item Initialises SmellDetector module + \item Initialises RefactorManager module + \item Initialises FilterManager module + \item Sets up workspace configuration + \item Registers plugin commands + \end{itemize} + \item \textbf{Output}: None + \item \textbf{Exception}: None +\end{itemize} + +\noindent\texttt{deactivate()} +\begin{itemize} + \item \textbf{Transition}: Cleans up resources and stops background processes + \item \textbf{Output}: None + \item \textbf{Exception}: None +\end{itemize} + +\noindent\texttt{isSmellLintingEnabled()} +\begin{itemize} + \item \textbf{Transition}: Returns current state of smell linting + \item \textbf{Output}: boolean indicating if smell linting is enabled + \item \textbf{Exception}: None +\end{itemize} + +\subsubsection{Local Functions} +None + +\section{MIS of BackendCommunicator} + +\subsection{Module} +\texttt{BackendCommunicator} handles all communication between the plugin and the backend service. It sends requests for analysis or refactoring and receives results. + +\subsection{Uses} \begin{itemize} - \item The input file is valid Python code and can be parsed into an AST. - \item Configuration settings, such as extra Pylint options and custom smell definitions, are valid. + \item \texttt{EcoOptimizer} for executing backend service operations and health checks \end{itemize} -\subsubsection{Access Routine Semantics} +\subsection{Syntax} -\paragraph{\texttt{\_\_init\_\_(self, file\_path: Path, source\_code: Module)}} +\textbf{Exported Constants:} \begin{itemize} - \item \textbf{transition}: Initializes the analyzer with the provided file path and AST of the source code. - \item \textbf{output}: \texttt{self}. - \item \textbf{exception:} None. + \item \texttt{BASE\_URL}: string - Base URL for backend API endpoints \end{itemize} -\paragraph{\texttt{build\_pylint\_options()}} -\begin{itemize} - \item \textbf{transition}: Constructs the list of Pylint options based on the file path and configuration settings. - \item \textbf{output}: Returns a list of strings representing Pylint options. - \item \textbf{exception:} None. -\end{itemize} +\noindent \textbf{Exported Access Programs:}\\ +\begin{tabularx}{\linewidth}{|>{\raggedright\arraybackslash}X|>{\raggedright\arraybackslash}X|>{\raggedright\arraybackslash}X|>{\raggedright\arraybackslash}X|} + \hline + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ + \hline + \texttt{checkServerStatus} & None & Promise$<$void$>$ & Network Error \\ + \hline + \texttt{initLogs} & \texttt{log\_dir: string} & Promise$<$boolean$>$ & Network Error \\ + \hline + \texttt{fetchSmells} & \texttt{filePath: string, enabledSmells: Record$<$string, Record$<$string, number | string$>$$>$} & + Promise$<$\{smells: Smell[], status: number\}$>$ & Network Error \\ + \hline + \texttt{backendRefactor\allowbreak Smell} & \texttt{smell: Smell, workspacePath: string} & Promise$<$RefactoredData$>$ & Network Error \\ + \hline + \texttt{backendRefactor\allowbreak SmellType} & \texttt{smell: Smell, workspacePath: string} & Promise$<$RefactoredData$>$ & Network Error \\ + \hline +\end{tabularx} -\paragraph{\texttt{analyze()}} +\subsection{Semantics} + +\subsubsection{State Variables} \begin{itemize} - \item \textbf{transition}: Executes Pylint analysis and custom checks, populating \texttt{smells\_data} with detected smells. - \item \textbf{output}: None. - \item \textbf{exception:} Raises \texttt{JSONDecodeError} if Pylint's output cannot be parsed. Raises \texttt{Exception} for other runtime errors. + \item \texttt{serverStatus: ServerStatusType} - Tracks the backend server's current status \end{itemize} -\paragraph{\texttt{configure\_smells()}} +\subsubsection{Environment Variables} \begin{itemize} - \item \textbf{transition}: Filters \texttt{smells\_data} to include only configured smells. - \item \textbf{output}: None. - \item \textbf{exception:} None. + \item \texttt{SERVER\_URL: string} - Backend server URL from environment configuration \end{itemize} -\paragraph{\texttt{filter\_for\_one\_code\_smell(self, pylint\_results: list[Smell], code: str)}} +\subsubsection{Assumptions} \begin{itemize} - \item \textbf{transition}: Filters the given Pylint results for a specific code smell identified by \texttt{code}. - \item \textbf{output}: Returns a list of smells matching the specified code. - \item \textbf{exception:} None. + \item EcoOptimizer backend service is reachable and operational + \item Network connection is available for API communication + \item Valid workspace configuration exists for operations requiring paths + \item Input files contain valid Python syntax \end{itemize} -\subsubsection{Local Functions} -\paragraph{\texttt{detect\_long\_message\_chain(self, threshold?: int)}} +\subsubsection{Access Routine Semantics} + +\noindent\texttt{checkServerStatus()} \begin{itemize} - \item \textbf{transition}: Identifies method chains exceeding the specified \texttt{threshold}. - \item \textbf{output}: Returns a list of smells for long method chains. - \item \textbf{exception:} None. + \item \textbf{Transition}: Verifies backend service availability and updates extension status + \item \textbf{Output}: Promise resolving to void + \item \textbf{Exception}: Logs network errors and updates server status to DOWN \end{itemize} -\paragraph{\texttt{detect\_long\_lambda\_expression(self, threshold\_length?: int, threshold\_count?: int)}} +\noindent\texttt{initLogs(log\_dir: string)} \begin{itemize} - \item \textbf{transition}: Detects lambda expressions exceeding length or expression count thresholds. - \item \textbf{output}: Returns a list of smells for long lambda expressions. - \item \textbf{exception:} None. + \item \textbf{Transition}: Initialises and synchronises logs with the backend server + \item \textbf{Output}: Promise$<$boolean$>$ indicating success or failure + \item \textbf{Exception}: Logs initialisation errors and returns false \end{itemize} -\paragraph{\texttt{detect\_long\_element\_chain(self, threshold?: int)}} +\noindent\texttt{fetchSmells(filePath: string, enabledSmells: Record)} \begin{itemize} - \item \textbf{transition}: Detects dictionary access chains exceeding the specified \texttt{threshold}. - \item \textbf{output}: Returns a list of smells for long dictionary chains. - \item \textbf{exception:} None. + \item \textbf{Transition}: Analyses source code for code smells using backend detection service + \item \textbf{Output}: Promise resolving to smell detection results and HTTP status + \item \textbf{Exception}: Throws Error for network failures or invalid responses \end{itemize} -\paragraph{\texttt{detect\_repeated\_calls(self, threshold?: int)}} +\noindent\texttt{backendRefactorSmell(smell: Smell, workspacePath: string)} \begin{itemize} - \item \textbf{transition}: Identifies repeated function calls exceeding the \texttt{threshold}. - \item \textbf{output}: Returns a list of smells for repeated function calls. - \item \textbf{exception:} None. + \item \textbf{Transition}: Executes code refactoring for a specific detected smell pattern + \item \textbf{Output}: Promise resolving to refactoring result data + \item \textbf{Exception}: Throws Error for invalid workspace path or refactoring failures \end{itemize} + +\noindent\texttt{backendRefactorSmellType(smell: Smell, workspacePath: string)} \begin{itemize} - \item \texttt{parse\_line(file\_path: Path, line: int)}: Parses a specific line of code into an AST node. - \item \texttt{get\_lambda\_code(lambda\_node: Lambda)}: Returns the string representation of a lambda expression. + \item \textbf{Transition}: Refactors all smells of a specific type in a file + \item \textbf{Output}: Promise resolving to refactoring result data + \item \textbf{Exception}: Throws Error for invalid workspace path or refactoring failures \end{itemize} +\subsubsection{Local Functions} +None -\newpage - -\section{MIS of Testing Functionality} \label{mis:test} - -\texttt{TestRunner} +\section{MIS of SmellDetector} \subsection{Module} - -Responsible for validating that any refactorings made to the source code do not modify it's original functionality. +\texttt{SmellDetector} analyses Python files for code smells and manages the detection workflow. \subsection{Uses} \begin{itemize} - \item Uses Python's subprocess library +\item \texttt{BackendCommunicator} for communicating with SourceCodeOptimizer +\item \texttt{CacheManager} for managing smell detection results +\item \texttt{FileHighlighter} for highlighting detected smells +\item \texttt{EventManager} for managing detection events +\item \texttt{HoverManager} for displaying smell information \end{itemize} \subsection{Syntax} -\noindent -\textbf{Exported Constants}: None -\noindent -\textbf{Exported Access Programs}: +\textbf{Exported Constants:} None +\textbf{Exported Access Programs:}\\ \begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} -\hline -\textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ -\hline -\texttt{\_\_init\_\_} & \texttt{run\_command: str, project\_path: Path} & \texttt{self} & None \\ -\hline -\texttt{retained\_functionality} & None & $\mathbb{B}$ & \texttt{CalledProcessError} \\ -\hline + \hline + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ + \hline + \texttt{detectSmellsFile} & \texttt{filePath: string, smellsViewProvider: SmellsViewProvider, cacheManager: CacheManager} & Promise$<$void$>$ & Analysis Error \\ + \hline + \texttt{detectSmellsFolder} & \texttt{folderPath: string, smellsViewProvider: SmellsViewProvider, cacheManager: CacheManager} & Promise$<$void$>$ & Analysis Error \\ + \hline \end{tabularx} \subsection{Semantics} \subsubsection{State Variables} \begin{itemize} - \item \texttt{project\_path: Path}: Path to the source code directory. - \item \texttt{run\_command: str}: Command used to run the tests. +\item \texttt{serverStatus}: ServerStatusType - Current status of the backend server \end{itemize} \subsubsection{Environment Variables} -None +\begin{itemize} +\item \texttt{enabledSmells}: Record$<$string, SmellConfig$>$ - Configuration of enabled smell detectors +\end{itemize} \subsubsection{Assumptions} \begin{itemize} - \item The provided \texttt{run\_command} is a valid shell command. - \item \texttt{project\_path} is a valid path working source code directory. +\item Target files have valid Python syntax +\item Backend server is operational for non-cached analysis +\item At least one smell detector is enabled in settings +\item Valid workspace configuration exists \end{itemize} \subsubsection{Access Routine Semantics} - -\paragraph{\texttt{\_\_init\_\_(self, run\_command: str, project\_path: Path)}} +\texttt{detectSmellsFile(filePath, smellsViewProvider, cacheManager)} \begin{itemize} - \item \textbf{transition}: Initializes the test runner with the given \texttt{run\_command} and \texttt{project\_path}. - \item \textbf{output}: \texttt{self}. - \item \textbf{exception}: None. +\item \textbf{Transition}: Checks a Python file using \texttt{precheckAndMarkQueued()}, analyses it for code smells, updates cache and view +\item \textbf{Output}: Promise resolving to void +\item \textbf{Exception}: Throws error if analysis fails \end{itemize} -\paragraph{\texttt{retained\_functionality()}} +\texttt{detectSmellsFolder(folderPath, smellsViewProvider, cacheManager)} \begin{itemize} - \item \textbf{transition}: Runs the specified test command in the given project path. Logs success or failure, including standard output and error streams. - \item \textbf{output}: Returns \texttt{True} if the tests passed; otherwise, returns \texttt{False}. - \item \textbf{exception}: Raises a \texttt{CalledProcessError} if an eror occurs while running the tests in a subprocess. +\item \textbf{Transition}: Recursively analyzes Python files in directory, shows progress +\item \textbf{Output}: Promise resolving to void +\item \textbf{Exception}: Throws error if folder scanning or analysis fails \end{itemize} \subsubsection{Local Functions} -None. - -\newpage - -\section{MIS of Use A Generator Refactorer} \label{mis:UseGen} +\texttt{precheckAndMarkQueued(filePath, smellsViewProvider, cacheManager)} +\begin{itemize} +\item \textbf{Transition}: Validates conditions before analysis and manages file status +\item \textbf{Output}: Promise$<$boolean$>$ indicating if analysis should proceed +\item \textbf{Exception}: None +\end{itemize} -\texttt{UseAGeneratorRefactorer} +\section{MIS of SmellRefactorer} \subsection{Module} - -The \texttt{UseAGeneratorRefactorer} module identifies and refactors -unnecessary list comprehensions in Python code by converting them to generator expressions. This refactoring improves energy efficiency while maintaining the original functionality. +\texttt{SmellRefactorer} applies a refactoring to a detected smell. \subsection{Uses} \begin{itemize} - \item Uses \texttt{Smell} interface for data access - \item Inherits from \texttt{BaseRefactorer} - \item Uses Python's \texttt{ast} module for parsing and manipulating abstract syntax trees +\item \texttt{BackendCommunicator} for sending the smell data to Source Code Optimizer for refactoring. +\item \texttt{RefactorManager} for managing refactoring workflows. \end{itemize} \subsection{Syntax} -\noindent -\textbf{Exported Constants}: None -\noindent -\textbf{Exported Access Programs}:\\ -\begin{tabularx}{\linewidth}{| - l| - >{\raggedright\arraybackslash}X| - l| - l|} +\textbf{Exported Constants:} None + +\textbf{Exported Access Programs:}\\ +\begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} \hline - \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline - \texttt{\_\_init\_\_} & \texttt{output\_dir: Path} & \texttt{self} & None \\ + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exception}\\ \hline - \texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{IOError}, \texttt{TypeError} \\ + \texttt{refactor} & {smell: Smell} & None & Invalid input \\ \hline \end{tabularx} \subsection{Semantics} \subsubsection{State Variables} -\begin{itemize} - \item \texttt{temp\_dir: Path}: Directory path for storing refactored files. - \item \texttt{output\_dir: Path}: Directory path for saving final refactored code. -\end{itemize} +None \subsubsection{Environment Variables} None + \subsubsection{Assumptions} \begin{itemize} - \item The input file contains valid Python syntax. - \item \texttt{pylint\_smell} provides a valid line number for the detected code smell. +\item The smell data is valid and correctly identifies a refactorable issue. \end{itemize} \subsubsection{Access Routine Semantics} - -\paragraph{\texttt{\_\_init\_\_(self, output\_dir: Path)}} -\begin{itemize} - \item \textbf{transition}: Initializes the \texttt{temp\_dir} variable within \texttt{output\_dir}. - \item \textbf{output}: \texttt{self}. - \item \textbf{exception:} None. -\end{itemize} - -\paragraph{\texttt{refactor(self, file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$)}} +\texttt{refactor(smell: Smell)} \begin{itemize} - \item \textbf{transition}: Parses \texttt{file\_path}, identifies unnecessary list comprehensions, modifies the code to use generator expressions, and validates refactoring. - \item \textbf{output}: None. - \item \textbf{exception}: Raises \texttt{IOError} if input file cannot be read. Raises \texttt{TypeError} if source file cannot be parsed into an AST. +\item \textbf{Transition}: Sends the smell data to the backend for refactoring and applies the changes in the editor. +\item \textbf{Output}: None. +\item \textbf{Exception}: Logs errors for invalid inputs or failed refactoring. \end{itemize} \subsubsection{Local Functions} -\paragraph{\texttt{\_replace\_node(self, tree: Module, old\_node: ListComp, new\_node: GeneratorExp)}} -\begin{itemize} - \item \textbf{transition}: Replaces an \texttt{old\_node} in the AST with a \texttt{new\_node}. - \item \textbf{output}: None. - \item \textbf{exception}: None. -\end{itemize} - -\newpage - -\section{MIS of Cache Repeated Calls Refactorer} \label{mis:CacheCalls} +None -\texttt{CacheRepeatedCallsRefactorer} +\section{MIS of FileHighlighter} \subsection{Module} - -The \texttt{CacheRepeatedCallsRefactorer} module identifies repeated function calls in Python code and refactors them by caching the result of the first call to a temporary variable. This refactoring improves performance and energy efficiency while preserving the original functionality. +\texttt{FileHighlighter} is a module that manages highlighting of code regions in the VS Code editor. \subsection{Uses} \begin{itemize} - \item Uses \texttt{Smell} interface for data access - \item Inherits from \texttt{BaseRefactorer} - \item Uses Python's \texttt{ast} module for parsing and manipulating abstract syntax trees +\item \texttt{ViewProvider} for managing editor decorations and visual updates \end{itemize} \subsection{Syntax} -\noindent -\textbf{Exported Constants}: None -\noindent -\textbf{Exported Access Programs}:\\ -\begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} +\textbf{Exported Constants:} None + +\noindent \textbf{Exported Access Programs:}\\ +\begin{tabularx}{\linewidth}{|p{5cm}|>{\raggedright\arraybackslash}X|l|l|} \hline - \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\\hline - \texttt{\_\_init\_\_} & \texttt{output\_dir: Path} & \texttt{self} & None \\ + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exception} \\ \hline - \texttt{refactor} & \texttt{file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$} & None & \texttt{IOError}, \texttt{TypeError} \\ + \texttt{getInstance} & \texttt{cacheManager: CacheManager} & FileHighlighter & None \\ \hline + \texttt{updateHighlightsFor \allowbreak VisibleEditors} & None & void & None \\ \hline + \texttt{resetHighlights} & None & void & None \\ \hline + \texttt{highlightSmells} & \texttt{editor: vscode.TextEditor} & void & None \\ \hline \end{tabularx} @@ -1279,149 +1961,202 @@ \subsection{Semantics} \subsubsection{State Variables} \begin{itemize} - \item \texttt{cached\_var\_name: str}: Name of the temporary variable used for caching. - \item \texttt{target\_line: int}: Line number where refactoring is applied. +\item \texttt{instance}: FileHighlighter - Singleton instance of the highlighter +\item \texttt{decorations}: TextEditorDecorationType[] - Active editor decorations +\item \texttt{cacheManager}: CacheManager - Reference to the cache manager \end{itemize} \subsubsection{Environment Variables} -None +\begin{itemize} +\item \texttt{smellsColours}: Configuration for smell highlight colours +\item \texttt{useSingleColour}: Boolean flag for using single highlight colour +\item \texttt{singleHighlightColour}: Colour value for single highlight mode +\item \texttt{highlightStyle}: Style configuration for highlights +\end{itemize} \subsubsection{Assumptions} \begin{itemize} - \item The input file contains valid Python syntax. - \item \texttt{pylint\_smell} provides valid occurrences of repeated calls with line numbers and call strings. +\item \texttt{CacheManager} is properly initialized +\item Valid configuration exists for highlight colours and styles \end{itemize} \subsubsection{Access Routine Semantics} +\texttt{getInstance(cacheManager: CacheManager)} +\begin{itemize} +\item \textbf{Transition}: Creates or returns singleton instance of \texttt{FileHighlighter} +\item \textbf{Output}: \texttt{FileHighlighter} instance +\item \textbf{Exception}: None +\end{itemize} -\paragraph{\texttt{\_\_init\_\_(self, output\_dir: Path)}} +\texttt{updateHighlightsForVisibleEditors()} \begin{itemize} - \item \textbf{transition}: Initializes the \texttt{temp\_dir} variable within \texttt{output\_dir}. - \item \textbf{output}: \texttt{self}. - \item \textbf{exception:} None. +\item \textbf{Transition}: Updates highlights for all visible Python files using \texttt{\_getDecoration} and \texttt{\_updateHighlightsForFile} +\item \textbf{Output}: None +\item \textbf{Exception}: None \end{itemize} -\paragraph{\texttt{refactor(self, file\_path: Path, pylint\_smell: Smell, initial\_emissions: $\mathbb{R}$)}} +\texttt{resetHighlights()} \begin{itemize} - \item \textbf{transition}: Parses \texttt{file\_path}, identifies repeated function calls, inserts a cached variable for the first call, updates subsequent calls to use the cached variable, and validates refactoring. - \item \textbf{output}: None. - \item \textbf{exception}: Raises \texttt{IOError} if input file cannot be read. Raises \texttt{TypeError} if source file cannot be parsed into an AST. +\item \textbf{Transition}: Removes all active highlights from editors +\item \textbf{Output}: None +\item \textbf{Exception}: None +\end{itemize} + +\texttt{highlightSmells(editor: vscode.TextEditor)} +\begin{itemize} +\item \textbf{Transition}: Applies highlights for cached smells in the editor +\item \textbf{Output}: None +\item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} + +\paragraph{\texttt{\_getDecoration(colour, style)}} \begin{itemize} - \item \texttt{\_get\_indentation(lines, line\_number)}: Determines the indentation of a specific line. - \item \texttt{\_replace\_call\_in\_line(line, call\_string, cached\_var\_name)}: Replaces repeated calls with the cached variable. - \item \texttt{\_find\_valid\_parent(tree)}: Identifies the valid parent node containing all occurrences of the repeated call. - \item \texttt{\_find\_insert\_line(parent\_node)}: Determines the line to insert the cached variable. + \item \textbf{Transition}: Creates decoration type based on configuration + \item \textbf{Output}: TextEditorDecorationType object + \item \textbf{Exception}: None \end{itemize} -\newpage +\paragraph{\texttt{\_updateHighlightsForFile(filePath)}} +\begin{itemize} + \item \textbf{Transition}: Updates highlights for a specific file + \item \textbf{Output}: None + \item \textbf{Exception}: None +\end{itemize} -\section{MIS of Plugin Initiator} +\section{MIS of HoverManager} \subsection{Module} -\texttt{Plugin Initiator} is a module that initializes the VS Code plugin and registers commands for VS Code Plugin. +\texttt{HoverManager} manages hover effects to display contextual information. \subsection{Uses} \begin{itemize} - \item \texttt{Smell Detector} to register the command for detecting code smells. - \item \texttt{Smell Refactorer} to register the command for refactoring user's selected code smell. +\item \texttt{ViewProvider} for managing hover display and updates \end{itemize} \subsection{Syntax} -\textbf{Exported Constants:} None\\ -\noindent \textbf{Exported Access Programs:} -None +\textbf{Exported Constants:} None +\textbf{Exported Access Programs:}\\ +\begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} + \hline + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exception} \\ + \hline + \texttt{register} & \texttt{context: vscode.ExtensionContext} & void & None \\ \hline + \texttt{provideHover} & \texttt{document: TextDocument, position: Position, token: CancellationToken} & ProviderResult$<$Hover$>$ & None \\ + \hline +\end{tabularx} \subsection{Semantics} \subsubsection{State Variables} -None - -\subsubsection{Environment Variables} \begin{itemize} - \item \textbf{VS CODE API}: Used to register commands. +\item \texttt{cacheManager}: CacheManager - Reference to the cache manager \end{itemize} +\subsubsection{Environment Variables} +None + \subsubsection{Assumptions} \begin{itemize} -\item The plugin is correctly loaded in VS Code. -\item Source Code Optimizer executable is reachable and operational. +\item VS Code editor is active with a Python file open +\item Valid hover position is provided \end{itemize} \subsubsection{Access Routine Semantics} -\texttt{activate()} +\texttt{register(context: vscode.ExtensionContext)} \begin{itemize} -\item \textbf{Transition}: Activates the plugin and registers commands. -\item \textbf{Output}: None. -\item \textbf{Exception}: None. +\item \textbf{Transition}: Registers hover provider for Python files +\item \textbf{Output}: None +\item \textbf{Exception}: None +\end{itemize} + +\texttt{provideHover(document, position, token)} +\begin{itemize} +\item \textbf{Transition}: Provides hover content with smell information +\item \textbf{Output}: Hover content or undefined +\item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} None -\section{MIS of Backend Communicator} +\section{MIS of RefactorManager} \subsection{Module} -\texttt{BackendCommunicator} handles all communication between the plugin and the backend service. It sends requests for analysis or refactoring and receives results. +\texttt{RefactorManager} manages the process of applying refactorings to detected smells. \subsection{Uses} -Source Code Optimizer executable for energy measurement, smell detection and refactoring of applications. +\begin{itemize} +\item \texttt{EnergyMetrics} for tracking refactoring impact +\item \texttt{CacheManager} for managing refactoring state +\item \texttt{EventManager} for handling refactoring events +\end{itemize} \subsection{Syntax} \textbf{Exported Constants:} None -\noindent \textbf{Exported Access Programs:}\\ +\textbf{Exported Access Programs:}\\ + \begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} \hline - \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exception} \\ \hline - \texttt{sendRequest} & \texttt{requestType: string, data: any} & Promise & Communication Error \\ + \texttt{register} & \texttt{context: vscode.ExtensionContext} & void & None \\ \hline + \texttt{provideHover} & \texttt{document: TextDocument, position: Position, token: CancellationToken} & ProviderResult$<$Hover$>$ & None \\ \hline \end{tabularx} - \subsection{Semantics} \subsubsection{State Variables} -None +\begin{itemize} +\item \texttt{serverStatus}: ServerStatusType - Current status of the backend server +\end{itemize} \subsubsection{Environment Variables} \begin{itemize} -\item \textbf{NETWORK}: Used for communicating with Source Code Optimizer. -\item \textbf{LOGGER}: Logs any communication errors. +\item \texttt{WORKSPACE\_CONFIGURED\_PATH}: string - Path to workspace configuration \end{itemize} \subsubsection{Assumptions} \begin{itemize} -\item Source Code Optimizer executable is reachable and operational. -\item Python file with no syntax errors is present in the VS Code editor. +\item Backend server is operational +\item Valid workspace configuration exists +\item Smell data is valid and complete +\item Required view providers are initialized \end{itemize} \subsubsection{Access Routine Semantics} -\texttt{sendRequest(requestType: str, data: Any)} +\texttt{refactor(smellsViewProvider, refactoringDetailsViewProvider, smell, context, isRefactorAllOfType)} +\begin{itemize} +\item \textbf{Transition}: Orchestrates complete refactoring workflow +\item \textbf{Output}: Promise resolving to void +\item \textbf{Exception}: Throws error for validation failures +\end{itemize} + +\texttt{startRefactorSession(smell, refactoredData, refactoringDetailsViewProvider)} \begin{itemize} -\item \textbf{Transition}: Sends the provided request to Source Code Optimizer and receives a response. -\item \textbf{Output}: A promise that resolves with Source Code Optimizer's response. -\item \textbf{Exception}: Logs any errors encountered during communication. +\item \textbf{Transition}: Initialises and manages refactoring session +\item \textbf{Output}: Promise resolving to void +\item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} None -\section{MIS of Smell Detector} +\section{MIS of CacheManager} \subsection{Module} -\texttt{Smell Detector} analyzes the active file for code smells and interacts with Source Code Optimizer for detection. +\texttt{CacheManager} manages caching of detected smells and file states. \subsection{Uses} \begin{itemize} -\item \texttt{Backend Communicator} for communicating with Source Code Optimizer for smell detection. -\item \texttt{File Highlighter} for highlighting detected smells in the editor. +\item \texttt{BackendCommunicator} for backend communication +\item \texttt{ViewProvider} for UI updates \end{itemize} \subsection{Syntax} @@ -1431,48 +2166,80 @@ \subsection{Syntax} \textbf{Exported Access Programs:}\\ \begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} \hline - \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exceptions} \\ + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exception} \\ \hline - \texttt{detect} & None & None & Active file not found \\ + \texttt{setCachedSmells} & \texttt{filePath: string, smells: Smell[]} & Promise$<$void$>$ & None \\ \hline + \texttt{getCachedSmells} & \texttt{filePath: string} & Smell[] or \ \text{undefined} & None \\ \hline + \texttt{hasCachedSmells} & \texttt{filePath: string} & boolean & None \\ \hline + \texttt{clearAllCachedSmells} & None & Promise$<$void$>$ & None \\ \hline \end{tabularx} + \subsection{Semantics} \subsubsection{State Variables} -None - -\subsubsection{Environment Variables} \begin{itemize} -\item \textbf{EDITOR}: Used to access the active file. +\item \texttt{cacheUpdatedEmitter}: EventEmitter - Emits cache update events +\item \texttt{fileStatuses}: Map$<$string, string$>$ - Tracks file statuses +\item \texttt{fileSmells}: Map$<$string, Smell[]$>$ - Stores cached smells \end{itemize} +\subsubsection{Environment Variables} +None + \subsubsection{Assumptions} \begin{itemize} -\item There is an active Python file with no syntax error in the editor. -\item Source Code Optimizer correctly identifies smells. +\item VS Code extension context is valid +\item File paths are normalized +\item Smell data structure is consistent \end{itemize} \subsubsection{Access Routine Semantics} -\texttt{detect()} +\texttt{setCachedSmells(filePath, smells)} \begin{itemize} -\item \textbf{Transition}: Reads the active file, sends it to Source Code Optimizer for analysis, and highlights detected smells in the editor. -\item \textbf{Output}: None. -\item \textbf{Exception}: Throws an error if no active file is found. +\item \textbf{Transition}: Stores smells in cache for specified file using \texttt{generateSmellId()} +\item \textbf{Output}: Promise resolving to void +\item \textbf{Exception}: None +\end{itemize} + +\texttt{getCachedSmells(filePath)} +\begin{itemize} +\item \textbf{Transition}: Retrieves cached smells for file using \texttt{hasCachedSmells()} +\item \textbf{Output}: Array of smells or undefined +\item \textbf{Exception}: None +\end{itemize} + +\texttt{hasCachedSmells(filePath)} +\begin{itemize} +\item \textbf{Transition}: Checks if file has cached smells +\item \textbf{Output}: boolean +\item \textbf{Exception}: None +\end{itemize} + +\texttt{clearAllCachedSmells()} +\begin{itemize} +\item \textbf{Transition}: Removes all cached smells +\item \textbf{Output}: Promise resolving to void +\item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} -None +\begin{itemize} +\item \texttt{generateSmellId(smell)}: Generates unique ID for smell +\item \texttt{generateFileHash(filePath)}: Generates hash for file content +\end{itemize} -\section{MIS of Smell Refactorer} +\section{MIS of FilterManager} \subsection{Module} -\texttt{Smell Refactorer} applies a refactoring to a detected smell. +\texttt{FilterManager} manages filtering of detected smells. \subsection{Uses} \begin{itemize} -\item \texttt{Backend Communicator} for sending the smell data to Source Code Optimizer for refactoring. -\item \texttt{Refactor Manager} for managing refactoring workflows. +\item \texttt{CacheManager} for accessing smell data +\item \texttt{EventManager} for handling filter events +\item \texttt{HoverManager} for displaying filtered smells \end{itemize} \subsection{Syntax} @@ -1482,57 +2249,79 @@ \subsection{Syntax} \textbf{Exported Access Programs:}\\ \begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} \hline - \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exception}\\ + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exception} \\ \hline - \texttt{refactor} & {smell: Smell} & None & Invalid input \\ + \texttt{toggleSmellFilter} & \texttt{smellKey: string} & void & None \\ \hline + \texttt{editSmellFilterOption} & \texttt{item: \{smellKey: string, optionKey: string, value: any\}} & Promise$<$void$>$ & Validation Error \\ \hline + \texttt{refresh} & None & void & None \\ \hline \end{tabularx} \subsection{Semantics} \subsubsection{State Variables} -None - -\subsubsection{Environment Variables} \begin{itemize} -\item \textbf{EDITOR}: Used to apply refactored changes. +\item \texttt{filterState}: Map$<$string, boolean$>$ - Tracks filter states +\item \texttt{filterOptions}: Map$<$string, any$>$ - Stores filter options \end{itemize} +\subsubsection{Environment Variables} +None + \subsubsection{Assumptions} \begin{itemize} -\item The smell data is valid and correctly identifies a refactorable issue. +\item Valid smell keys are provided +\item Filter options are properly configured +\item Cache manager is initialized \end{itemize} \subsubsection{Access Routine Semantics} -\texttt{refactor(smell: Smell)} +\texttt{toggleSmellFilter(smellKey)} \begin{itemize} -\item \textbf{Transition}: Sends the smell data to the backend for refactoring and applies the changes in the editor. -\item \textbf{Output}: None. -\item \textbf{Exception}: Logs errors for invalid inputs or failed refactoring. +\item \textbf{Transition}: Toggles filter state for smell +\item \textbf{Output}: None +\item \textbf{Exception}: None +\end{itemize} + +\texttt{editSmellFilterOption(item)} +\begin{itemize} +\item \textbf{Transition}: Updates filter option value +\item \textbf{Output}: Promise resolving to void +\item \textbf{Exception}: Throws validation error for invalid input +\end{itemize} + +\texttt{refresh()} +\begin{itemize} +\item \textbf{Transition}: Updates filter display +\item \textbf{Output}: None +\item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} None -\section{MIS of File Highlighter} +\section{MIS of EnergyMetrics} \subsection{Module} -\texttt{File Highlighter} is a module that manages highlighting of code regions in the VS Code editor. +\texttt{EnergyMetrics} manages energy consumption measurements and metrics display. \subsection{Uses} -None +\begin{itemize} +\item \texttt{ViewProvider} for displaying metrics +\end{itemize} \subsection{Syntax} \textbf{Exported Constants:} None -\noindent \textbf{Exported Access Programs:}\\ +\textbf{Exported Access Programs:}\\ \begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} \hline \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exception} \\ \hline - \texttt{highlight} & \texttt{range: range[]} & None & None \\ \hline - \texttt{clear} & \texttt{None} & None & None \\ + \texttt{updateMetrics} & \texttt{filePath: string, carbonSaved: number, smellSymbol: string} & void & None \\ \hline + \texttt{refresh} & None & void & None \\ \hline + \texttt{getTreeItem} & \texttt{element: MetricTreeItem} & TreeItem & None \\ \hline \end{tabularx} @@ -1540,47 +2329,55 @@ \subsection{Semantics} \subsubsection{State Variables} \begin{itemize} -\item \texttt{highlightedRanges}: Stores the currently highlighted regions in the editor. +\item \texttt{metricsData}: Record$<$string, MetricsDataItem$>$ - Stores metrics data +\item \texttt{onDidChangeTreeData}: EventEmitter - Emits tree data change events \end{itemize} \subsubsection{Environment Variables} -\begin{itemize} -\item \textbf{EDITOR}: Used to apply and clear highlights. -\end{itemize} +None \subsubsection{Assumptions} \begin{itemize} -\item The VS Code editor is active and accessible. -\item Python file with no syntax errors is currently open in the editor. +\item Valid file paths are provided +\item Metrics data is properly formatted +\item Tree view is initialized \end{itemize} \subsubsection{Access Routine Semantics} -\texttt{highlight(ranges: Range[])} +\texttt{updateMetrics(filePath, carbonSaved, smellSymbol)} \begin{itemize} -\item \textbf{Transition}: Adds highlights to the specified ranges in the editor. -\item \textbf{Output}: None. -\item \textbf{Exception}: None. +\item \textbf{Transition}: Updates metrics for file and smell using \texttt{calculateFileMetrics()} +\item \textbf{Output}: None +\item \textbf{Exception}: None \end{itemize} -\texttt{clear()} +\texttt{refresh()} \begin{itemize} -\item \textbf{Transition}: Removes all highlights from the editor. -\item \textbf{Output}: None. -\item \textbf{Exception}: None. +\item \textbf{Transition}: Updates metrics display using \texttt{formatNumber()} +\item \textbf{Output}: None +\item \textbf{Exception}: None +\end{itemize} + +\texttt{getTreeItem(element)} +\begin{itemize} +\item \textbf{Transition}: Creates tree item for metrics display +\item \textbf{Output}: TreeItem +\item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} -None +\begin{itemize} +\item \texttt{calculateFileMetrics(filePath, metricsData)}: Calculates metrics for file +\item \texttt{formatNumber(number)}: Formats number for display +\end{itemize} -\section{MIS of Hover Manager} +\section{MIS of ViewProvider} \subsection{Module} -\texttt{Hover Manager} manages hover effects to display contextual information. +\texttt{ViewProvider} manages the display of smells and metrics in VS Code. \subsection{Uses} -\begin{itemize} -\item \texttt{File Highlighter} for providing contextual information about highlighted smells. -\end{itemize} +None \subsection{Syntax} @@ -1591,8 +2388,10 @@ \subsection{Syntax} \hline \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exception} \\ \hline - \texttt{showHover} & \texttt{position: Position} & None & None \\ \hline - \texttt{clearHover} & \texttt{None} & None & None \\ + \texttt{refresh} & None & void & None \\ \hline + \texttt{setStatus} & \texttt{filePath: string, status: string} & void & None \\ \hline + \texttt{setSmells} & \texttt{filePath: string, smells: Smell[]} & void & None \\ \hline + \texttt{removeFile} & \texttt{filePath: string} & boolean & None \\ \hline \end{tabularx} @@ -1600,42 +2399,62 @@ \subsection{Semantics} \subsubsection{State Variables} \begin{itemize} -\item \texttt{currentHover}: Stores the currently displayed hover information. +\item \texttt{fileStatuses}: Map$<$string, string$>$ - Tracks file statuses +\item \texttt{fileSmells}: Map$<$string, Smell[]$>$ - Stores smell data +\item \texttt{onDidChangeTreeData}: EventEmitter - Emits tree data change events \end{itemize} \subsubsection{Environment Variables} -\begin{itemize} -\item \textbf{EDITOR}: Used to display hover effects. -\end{itemize} +None \subsubsection{Assumptions} -None +\begin{itemize} +\item VS Code extension context is valid +\item File paths are normalized +\item Smell data structure is consistent +\end{itemize} \subsubsection{Access Routine Semantics} -\texttt{showHover(position: Position)} +\texttt{refresh()} \begin{itemize} -\item \textbf{Transition}: Displays hover information at the specified position. -\item \textbf{Output}: None. -\item \textbf{Exception}: None. +\item \textbf{Transition}: Updates tree view display +\item \textbf{Output}: None +\item \textbf{Exception}: None \end{itemize} -\texttt{clearHover()} +\texttt{setStatus(filePath, status)} \begin{itemize} -\item \textbf{Transition}: Clears any active hover information. -\item \textbf{Output}: None. -\item \textbf{Exception}: None. +\item \textbf{Transition}: Updates file status in view +\item \textbf{Output}: None +\item \textbf{Exception}: None +\end{itemize} + +\texttt{setSmells(filePath, smells)} +\begin{itemize} +\item \textbf{Transition}: Updates smell data in view +\item \textbf{Output}: None +\item \textbf{Exception}: None +\end{itemize} + +\texttt{removeFile(filePath)} +\begin{itemize} +\item \textbf{Transition}: Removes file from view +\item \textbf{Output}: boolean indicating success +\item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} None -\section{MIS of Refactor Manager} +\section{MIS of EventManager} \subsection{Module} -\texttt{Refactor Manager} manages the process of applying refactorings to detected smells. +\texttt{EventManager} manages event handling and propagation. \subsection{Uses} -None +\begin{itemize} +\item \texttt{ViewProvider} for UI updates +\end{itemize} \subsection{Syntax} @@ -1643,51 +2462,61 @@ \subsection{Syntax} \textbf{Exported Access Programs:}\\ \begin{tabularx}{\linewidth}{|l|>{\raggedright\arraybackslash}X|l|l|} - \toprule Name & In & Out & Exceptions \\ - \midrule - \texttt{applyRefactor} & \texttt{refactor: Refactor} & None & Validation error \\ \hline - \texttt{previewRefactor} & \texttt{refactor: Refactor} & None & None \\ \hline - \texttt{undoRefactor} & None & None & None \\ - \bottomrule + \hline + \textbf{Name} & \textbf{In} & \textbf{Out} & \textbf{Exception} \\ + \hline + \texttt{getStatus} & None & ServerStatusType & None \\ \hline + \texttt{setStatus} & \texttt{newStatus: ServerStatusType} & void & None \\ \hline + \texttt{on} & \texttt{event: string, listener: Function} & void & None \\ \hline + \texttt{emit} & \texttt{event: string, data: any} & void & None \\ + \hline \end{tabularx} \subsection{Semantics} \subsubsection{State Variables} \begin{itemize} -\item \texttt{appliedRefactors}: Stores a history of applied refactors. +\item \texttt{status}: ServerStatusType - Current server status +\item \texttt{eventEmitter}: EventEmitter - Event emitter instance \end{itemize} \subsubsection{Environment Variables} -\begin{itemize} -\item \textbf{EDITOR}: Used to apply and preview refactors. -\end{itemize} +None \subsubsection{Assumptions} \begin{itemize} -\item The refactoring data is valid and corresponds to detected smells. +\item Event listeners are properly registered +\item Event types are consistent +\item Server status is valid \end{itemize} \subsubsection{Access Routine Semantics} -\texttt{applyRefactor(refactor: Refactor)} +\texttt{getStatus()} \begin{itemize} -\item \textbf{Transition}: Applies the provided refactor to the active editor. -\item \textbf{Output}: None. -\item \textbf{Exception}: Logs validation errors if the refactor cannot be applied. +\item \textbf{Transition}: Returns current server status +\item \textbf{Output}: ServerStatusType +\item \textbf{Exception}: None \end{itemize} -\texttt{previewRefactor(refactor: Refactor)} +\texttt{setStatus(newStatus)} \begin{itemize} -\item \textbf{Transition}: Displays a preview of the refactor in the editor. -\item \textbf{Output}: None. -\item \textbf{Exception}: None. +\item \textbf{Transition}: Updates server status and emits event +\item \textbf{Output}: None +\item \textbf{Exception}: None \end{itemize} -\texttt{undoRefactor()} +\texttt{on(event, listener)} \begin{itemize} -\item \textbf{Transition}: Reverts the most recently applied refactor. -\item \textbf{Output}: None. -\item \textbf{Exception}: None. +\item \textbf{Transition}: Registers event listener +\item \textbf{Output}: None +\item \textbf{Exception}: None +\end{itemize} + +\texttt{emit(event, data)} +\begin{itemize} +\item \textbf{Transition}: Emits event with data +\item \textbf{Output}: None +\item \textbf{Exception}: None \end{itemize} \subsubsection{Local Functions} @@ -1751,8 +2580,8 @@ \subsubsection*{Group Reflection} than anticipated, which affects the accuracy of some of our results. Ideally, we would replace it with a more dependable resource. However, due to time constraints and the inherent complexity of measuring CO2 emissions from code, - this isn’t feasible within the scope of this project. For now, we are assuming - Codecarbon’s reliability. In a real-world implementation, we would prioritize + this isn't feasible within the scope of this project. For now, we are assuming + Codecarbon's reliability. In a real-world implementation, we would prioritize using a more robust energy measurement system. \item \textit {Give a brief overview of other design solutions you considered. What @@ -1830,7 +2659,7 @@ \subsubsection*{Mya Hussain} an actual blueprint of what to do. This made this deliverable easier to write as the code was already present but also made the work feel unnecessarily redundant i.e boring to do. It often felt like I was documenting things that were already clear or implemented. - This repetition made the process less engaging and, at times, a bit tedious. + This repetition made the process less engaging and, at times, a bit tedious. To resolve this, I focused on framing the document as an opportunity to validate and formalize our design decisions, which helped shift the mindset from simply checking off tasks to reaffirming the thought process behind our choices. @@ -1842,7 +2671,7 @@ \subsubsection*{Sevhena Walker} \begin{enumerate} \item \textit{What went well while writing this deliverable? } - Our team already had a pretty solid idea of how we wanted to break up our system, as well as the key components that should be involved, even before we started working on the MG and MIS documents. We had already coded a decent portion of the system and, in doing so, had explored and tested various design approaches and options. This hands-on experience gave us a strong foundation and a practical understanding of what worked and what didn’t, which significantly influenced our final design choices. For example, we had already determined that the refactorers would be structured as individual classes inheriting from a common base class, which simplified documenting shared functionality in the MIS. + Our team already had a pretty solid idea of how we wanted to break up our system, as well as the key components that should be involved, even before we started working on the MG and MIS documents. We had already coded a decent portion of the system and, in doing so, had explored and tested various design approaches and options. This hands-on experience gave us a strong foundation and a practical understanding of what worked and what didn't, which significantly influenced our final design choices. For example, we had already determined that the refactorers would be structured as individual classes inheriting from a common base class, which simplified documenting shared functionality in the MIS. \item \textit{What pain points did you experience during this deliverable, and how did you resolve them?} @@ -1875,7 +2704,7 @@ \subsection*{Ayushi Amin} parts we didn't quite get or thought we got. Overall, it felt pretty satisfying to see it all come together. \item \textit{What pain points did you experience during this deliverable, and how did you resolve them?} - I think the hardest part of this was visualizing extra dependencies and functions I would need to create to make my + I think the hardest part of this was visualising extra dependencies and functions I would need to create to make my module work. We had coded out a portion of it but it did not include everything. I had to make sure I was not missing anything important. It felt like I was stuck in this loop of overthinking every little detail. To get past it, I took a break and came back with a fresh perspective, which helped a bit. I also hit up one of my teammates to talk through the diff --git a/docs/Design/SoftDetailedDes/README.md b/docs/Design/SoftDetailedDes/README.md index fe3030a7..a04d23af 100644 --- a/docs/Design/SoftDetailedDes/README.md +++ b/docs/Design/SoftDetailedDes/README.md @@ -1,2 +1,55 @@ -# Module Interface Specification # +# Software Detailed Design Directory +This directory contains the detailed design documentation for the Source Code Optimizer project, providing low-level design specifications and implementation details. + +## Directory Contents + +### Core Documentation +- `MIS.tex` - Module Interface Specification documentation source +- `Makefile` - Build configuration for documentation generation + +## Design Documentation + +### Module Interface Specifications +1. Interface Definitions + - Method signatures + - Parameter descriptions + - Return values + - Error conditions + - Usage examples + +2. Data Structures + - Type definitions + - Class hierarchies + - Object relationships + - State management + - Data flow + +3. Implementation Details + - Algorithms + - Design patterns + - Error handling + - Performance considerations + - Resource management + + +## Usage Guidelines + +1. Documentation Standards + - Interface documentation + - Design rationale + - Version tracking + +2. Review Process + - Peer review + - TA review + +## Best Practices + +1. Quality Control + - Design validation + - Documentation review + +2. Maintenance + - Version control + - Change tracking diff --git a/docs/DevelopmentPlan/README.md b/docs/DevelopmentPlan/README.md index b6bfa0cb..6890bbb7 100644 --- a/docs/DevelopmentPlan/README.md +++ b/docs/DevelopmentPlan/README.md @@ -1,5 +1,42 @@ -# Development Plan +# Development Plan Directory -The folders and files for this folder are as follows: +This directory contains the development planning documentation for the Source Code Optimizer project, outlining implementation strategies and processes. -Describe ... +## Directory Contents + +### Files +- `README.md` - Documentation overview +- `Makefile` - Build configuration for documentation generation +- `DevelopmentPlan.tex` - LaTeX source for the Development Plan document +- `DevelopmentPlan.pdf` - Generated Development Plan document + +## Major Components + +1. Technical Planning + - Architecture Design + - Technology Stack + - Development Methodology + - Implementation Phases + +2. Process Management + - Development Workflow + - Code Standards + - Review Process + - Testing Strategy + +3. Resource Planning + - Team Structure + - Tool Selection + - Infrastructure + - Timeline Management + +## Usage Guidelines + +1. Document Generation + - Use make to generate documentation + - Review generated documents + - Track changes + +2. Plan Implementation + - Track progress + - Monitor timelines diff --git a/docs/HazardAnalysis/HazardAnalysis.tex b/docs/HazardAnalysis/HazardAnalysis.tex index 5fc7a0ea..4a08d021 100644 --- a/docs/HazardAnalysis/HazardAnalysis.tex +++ b/docs/HazardAnalysis/HazardAnalysis.tex @@ -410,7 +410,7 @@ \section{Critical Assumptions} \end{itemize} & \begin{itemize}[wide=0pt] \item Add progress bars and time estimates for long operations. - \item Provide status updates (e.g., "Measuring energy... 75\%"). + \item Provide status updates (e.g., ``Measuring energy... 75\%''). \end{itemize} & SCR-13 & HZ-\showmycounter \\ \cline{2-7} & Inaccessible UI for users with disabilities & @@ -672,15 +672,15 @@ \subsubsection*{Mya Hussain} Determining which factors qualify as hazards for our analysis was somewhat unclear. A hazard is defined as anything with the potential to cause harm or loss, yet certain risks may emerge from poor design, complicating our decision on whether to include them. - For example, user interface hazards like "the tool does not provide clear feedback - to the user after refactoring" can technically be classified as a hazard. While we + For example, user interface hazards like ``the tool does not provide clear feedback + to the user after refactoring'' can technically be classified as a hazard. While we aim to mitigate team-imposed hazards, it raises the question of whether we should simply avoid designing a flawed product in the first place, and not include these hazards in the analysis or if we should do a worst-case analysis and include every possible pitfall. The same argument could be made for some security hazards for example - "while parsing user input code, the software encounters malware and executes it," + ``while parsing user input code, the software encounters malware and executes it,'' avoiding this is something a good tool should already have built in, so it begs - the question of "how bad do we envision our final product when analyzing hazards?" + the question of ``how bad do we envision our final product when analyzing hazards?'' We were able to get some clarification on this in our TA 1-1 meeting but ultimately tried to keep it high level so our report didn't end up being too long. diff --git a/docs/HazardAnalysis/README.md b/docs/HazardAnalysis/README.md index 90387c66..68758027 100644 --- a/docs/HazardAnalysis/README.md +++ b/docs/HazardAnalysis/README.md @@ -1,5 +1,42 @@ -# Hazard Analysis +# Hazard Analysis Directory -The folders and files for this folder are as follows: +This directory contains the hazard analysis documentation for the Source Code Optimizer project, identifying and assessing potential risks and safety concerns. -Describe ... +## Directory Contents + +### Files +- `README.md` - Documentation overview +- `Makefile` - Build configuration for documentation generation +- `HazardAnalysis.tex` - LaTeX source for the Hazard Analysis document +- `HazardAnalysis.pdf` - Generated Hazard Analysis document + +## Major Components + +1. Risk Analysis + - Risk Identification + - Risk Assessment + - Impact Analysis + - Mitigation Strategies + +2. Safety Analysis + - Code Safety + - System Vulnerabilities + - Security Threats + - Operational Risks + +3. Compliance + - Safety Standards + - Security Requirements + - Regulatory Requirements + - Industry Guidelines + +## Usage Guidelines + +1. Document Generation + - Use make to generate documentation + - Review generated documents + +## Maintenance + +1. Regular Updates + - Document changes \ No newline at end of file diff --git a/docs/Images/plugin_use_diagram.png b/docs/Images/plugin_use_diagram.png index fd528859..f36d068f 100644 Binary files a/docs/Images/plugin_use_diagram.png and b/docs/Images/plugin_use_diagram.png differ diff --git a/docs/Images/sco_use_diagram.png b/docs/Images/sco_use_diagram.png index f2cff631..b5de0ec8 100644 Binary files a/docs/Images/sco_use_diagram.png and b/docs/Images/sco_use_diagram.png differ diff --git a/docs/Images/vscode-coverage.png b/docs/Images/vscode-coverage.png index 87d01084..7245d652 100644 Binary files a/docs/Images/vscode-coverage.png and b/docs/Images/vscode-coverage.png differ diff --git a/docs/Makefile b/docs/Makefile index 67cc8279..d4e4e1b2 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -2,72 +2,72 @@ # TODO: Missing artifacts should be added to this file .PHONY: SRS -all: SRS MG MIS SystDes PS VnVP VnVR DevP HazA Refl UGde +all: SRS MG MIS PS VnVP VnVR DevP HazA Refl UseTest clean SRS: - cd SRS && make && cd .. + cd SRS && make && cd - MG: - cd Design/SoftArchitecture && make && cd ../.. + cd Design/SoftArchitecture && make && cd - MIS: - cd Design/SoftDetailedDes && make && cd ../.. - -SystDes: - cd Design/SystDesign && make && cd ../.. + cd Design/SoftDetailedDes && make && cd - PS: - cd ProblemStatementAndGoals && make && cd .. + cd ProblemStatementAndGoals && make && cd - VnVP: - cd VnVPlan && make && cd ../.. + cd VnVPlan && make && cd - VnVR: - cd VnVReport && make && cd ../.. + cd VnVReport && make && cd - DevP: - cd DevelopmentPlan && make && cd ../.. + cd DevelopmentPlan && make && cd - HazA: - cd HazardAnalysis && make && cd ../.. + cd HazardAnalysis && make && cd - Refl: - cd Reflection && make && cd ../.. + cd ReflectAndTrace && make && cd - -UGde: - cd UserGuide && make && cd ../.. +UseTest: + cd Extras/UsabilityTesting && make && cd - + +UseMan: + cd Extras/UserManual && make && cd - -clean: cleanSRS cleanMG cleanMIS cleanSystDes cleanPS cleanVnVP cleanVnVR cleanDevP cleanHazA cleanRefl cleanUGde +clean: cleanSRS cleanMG cleanMIS cleanPS cleanVnVP cleanVnVR cleanDevP cleanHazA cleanRefl cleanUseTest cleanPS: - cd ProblemStatementAndGoals && make clean && cd .. + cd ProblemStatementAndGoals && make clean && cd - cleanSRS: - cd SRS && make clean && cd .. + cd SRS && make clean && cd - cleanMG: - cd Design/SoftArchitecture && make clean && cd .. + cd Design/SoftArchitecture && make clean && cd - cleanMIS: - cd Design/SoftDetailedDes && make clean && cd .. - -cleanSystDes: - cd Design/SystDesign && make clean && cd .. + cd Design/SoftDetailedDes && make clean && cd - cleanVnVP: - cd VnVPlan && make clean && cd .. + cd VnVPlan && make clean && cd - cleanVnVR: - cd VnVReport && make clean && cd .. + cd VnVReport && make clean && cd - cleanDevP: - cd DevelopmentPlan && make clean && cd .. + cd DevelopmentPlan && make clean && cd - cleanHazA: - cd HazardAnalysis && make clean && cd .. + cd HazardAnalysis && make clean && cd - cleanRefl: - cd Reflection && make clean && cd .. + cd ReflectAndTrace && make clean && cd - -cleanUGde: - cd UserGuide && make clean && cd .. +cleanUseTest: + cd Extras/UsabilityTesting && make clean && cd - + +cleanUseMan: + cd Extras/UserManual && make clean && cd - diff --git a/docs/Presentations/README.md b/docs/Presentations/README.md index ee235cc4..e122f395 100644 --- a/docs/Presentations/README.md +++ b/docs/Presentations/README.md @@ -1,8 +1,19 @@ -# Presentations/demonstrations about your software +# Presentations Directory -The folders and files for this folder are as follows: +This directory contains all presentation materials related to the Source Code Optimizer project, including project updates, technical presentations, and demonstrations. -- D0_ProofOfConceptDemo -- D1_Rev0Demo -- D2_FinalPresentation -- D3_EXPO \ No newline at end of file +## Directory Contents + +### Project Presentations +- Project overview +- Progress updates +- Milestone presentations +- Sprint reviews +- Final presentations + +### Technical Presentations +- Architecture overview +- Technical deep dives +- Code walkthroughs +- Design reviews +- Implementation details \ No newline at end of file diff --git a/docs/ProblemStatementAndGoals/ProblemStatement.tex b/docs/ProblemStatementAndGoals/ProblemStatement.tex index c80de121..b3936a02 100644 --- a/docs/ProblemStatementAndGoals/ProblemStatement.tex +++ b/docs/ProblemStatementAndGoals/ProblemStatement.tex @@ -37,6 +37,7 @@ March 24th, 2025 & Mya Hussain & Removed mentions of database storing \\ March 24th, 2025 & Ayushi Amin & Fixed formatting and grammar/spelling \\ March 24th, 2025 & Sevhena Walker & Update the aspects of the plugin \\ + April 4th, 2025 & Ayushi Amin & Removed reinforcement learning from current plan \\ \bottomrule \end{tabularx} \end{table} @@ -93,8 +94,6 @@ \subsubsection*{\color{blue}{Indirect Stakeholders}} \end{enumerate} \subsection{Environment} -\textbf{Reinforcement Learning Library:} \textit{Stable Baselines} -will be the library to implement reinforcement learning techniques.\\ \textbf{Development Frameworks and Tools:} \begin{enumerate} diff --git a/docs/ProblemStatementAndGoals/README.md b/docs/ProblemStatementAndGoals/README.md index e5c5ef46..95abbe62 100644 --- a/docs/ProblemStatementAndGoals/README.md +++ b/docs/ProblemStatementAndGoals/README.md @@ -1,5 +1,43 @@ -# Problem Statement +# Problem Statement and Goals Directory -The folders and files for this folder are as follows: +This directory contains the foundational documentation defining the problem space and objectives for the Source Code Optimizer project. -Describe ... +## Directory Contents + +### Files +- `README.md` - Documentation overview +- `Makefile` - Build configuration for documentation generation +- `ProblemStatement.tex` - LaTeX source for the Problem Statement document +- `ProblemStatement.pdf` - Generated Problem Statement document + +## Major Components + +1. Problem Definition + - Context Analysis + - Current Challenges + - Stakeholder Impact + +2. Project Goals + - Primary Objectives + - Success Criteria + - Project Scope + - Constraints + +3. Success Metrics + - Performance Indicators + - Quality Metrics + - Business Value + - Technical Benchmarks + +## Usage Guidelines + +1. Document Generation + - Use make to generate documentation + - Review generated documents + - Track changes + +## Maintenance + +1. Regular Updates + - Track progress + - Document changes diff --git a/docs/README.md b/docs/README.md index 96f0750c..b19aa40b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,32 +1,60 @@ - - - - - - - - - - - - - -# Documentation folders - -The folders and files for this folder are as follows: - -Describe ... \ No newline at end of file +# Documentation Directory + +This directory contains all project documentation for the Source Code Optimizer project, including requirements, design documents, plans, and other project artifacts. + +## Directory Contents + +### Files +- `README.md` - Documentation overview +- `Makefile` - Build configuration for documentation generation +- `Common.tex` - Shared LaTeX definitions and configurations +- `Comments.tex` - Comments package configuration for documentation +- `Reflection.tex` - Template for reflection documents + +### Directories +- `Checklists/` - Quality assurance and review checklists +- `Design/` - System design documentation and architecture +- `DevelopmentPlan/` - Project development methodology and planning +- `HazardAnalysis/` - Safety and risk assessment documentation +- `Images/` - Shared images and diagrams +- `ProblemStatementAndGoals/` - Project objectives and problem definition +- `Presentations/` - Project presentations and demos +- `projMngmnt/` - Project management artifacts +- `ReflectAndTrace/` - Project reflection and traceability +- `SRS/` - Software Requirements Specification +- `UserGuide/` - End-user documentation +- `VnVPlan/` - Verification and Validation Plan +- `VnVReport/` - Verification and Validation Reports + +## Major Components + +1. Core Documentation + - Software Requirements Specification + - System Design Documentation + - User Guide + - Verification and Validation + +2. Project Management + - Development Planning + - Project Management + - Problem Statement + - Hazard Analysis + +3. Supporting Materials + - Quality Checklists + - Presentations + - Build Configuration + - Shared Resources + +## Usage Guidelines + +1. Each subdirectory contains its own README.md with specific details about its contents +2. LaTeX files are used for formal documentation with cross-referencing capabilities +3. Use the Makefile to generate PDF documentation from LaTeX sources + +## Documentation Standards + +1. All formal documentation should use the provided LaTeX templates +2. Images should be stored in the Images directory and referenced relatively +3. Each major document should have its own subdirectory with associated resources +4. Version control should be maintained for all documentation files \ No newline at end of file diff --git a/docs/ReflectAndTrace/README.md b/docs/ReflectAndTrace/README.md index b6bfa0cb..25b456b8 100644 --- a/docs/ReflectAndTrace/README.md +++ b/docs/ReflectAndTrace/README.md @@ -1,5 +1,34 @@ -# Development Plan +# Reflect and Trace Directory -The folders and files for this folder are as follows: +This directory contains documentation for project reflection and requirement traceability for the Source Code Optimizer project. -Describe ... +## Directory Contents + +### Project Reflection +- Lessons learned +- Success analysis +- Challenge assessment + +### Requirement Tracing +- Requirement mapping +- Implementation tracking +- Test coverage analysis + +### Process Analysis +- Methodology evaluation +- Timeline analysis +- Quality metrics + +## Reflection Framework + +1. Project Assessment + - Goal achievement + - Timeline adherence + +2. Process Evaluation + - Communication effectiveness + - Documentation quality + +3. Improvement Analysis + - Best practices + - Recommendations diff --git a/docs/ReflectAndTrace/ReflectAndTrace.pdf b/docs/ReflectAndTrace/ReflectAndTrace.pdf index bf4c047a..bed13033 100644 Binary files a/docs/ReflectAndTrace/ReflectAndTrace.pdf and b/docs/ReflectAndTrace/ReflectAndTrace.pdf differ diff --git a/docs/ReflectAndTrace/ReflectAndTrace.tex b/docs/ReflectAndTrace/ReflectAndTrace.tex index e5bfc3d5..8a8649eb 100644 --- a/docs/ReflectAndTrace/ReflectAndTrace.tex +++ b/docs/ReflectAndTrace/ReflectAndTrace.tex @@ -1,21 +1,43 @@ \documentclass{article} +\usepackage[letterpaper, portrait, margin=1in]{geometry} \usepackage{tabularx} \usepackage{booktabs} +\usepackage[utf8]{inputenc} +\usepackage{xcolor} +\usepackage{array} +\usepackage{hyperref} +\usepackage{float} +\usepackage{longtable} -\title{Reflection and Traceability Report on \progname} -\author{\authname} +\usepackage{xurl} +\usepackage{enumitem} + + +\title{Reflection and Traceability Report on EcoOptimizer} + +\author{Ayushi Amin \\ Tanveer Brar \\ Nivetha Kuruparan\\ Sevhena Walker\\ Mya Hussain} \date{} \input{../Comments} \input{../Common} + + \begin{document} \maketitle +~\newpage + +\tableofcontents +% This is a test line, please ignore + +~\newpage + + \plt{Reflection is an important component of getting the full benefits from a learning experience. Besides the intrinsic benefits of reflection, this document will be used to help the TAs grade how well your team responded to @@ -63,16 +85,526 @@ \section{Changes in Response to Feedback} \subsection{SRS and Hazard Analysis} -\subsection{Design and Design Documentation} +\subsubsection{Software Requirement Specification Document (SRS)} + +The SRS underwent significant refinements based on feedback, beginning with peer suggestions to clarify ambiguous requirements including FR-2 (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/154}{Issue \#154}) and FR-8 (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/137}{Issue \#137}), with particular attention given to properly defining ``lowest energy consumption'' (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/138}{Issue \#138}) to ensure measurable outcomes. The documentation around stakeholders was enhanced to explicitly identify which software developers would be considered shareholders (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/140}{Issue \#140}), while training requirement exclusions were properly justified (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/141}{Issue \#141}). Additional details expanded the energy consumption dashboard description (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/152}{Issue \#152}), and new adaptability requirements were added (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/157}{Issue \#157}). Priority planning suggestions were reviewed but ultimately discarded as duplicates (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/155}{Issues \#136 + \#155}). + +Teaching assistant feedback drove structural improvements including moving the glossary section (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/270}{Issue \#270}) and implementing symbolic constants (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/269}{Issue \#269}). All tables and figures were properly referenced throughout (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/271}{Issue \#271}), while requirements were made more abstract (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/272}{Issue \#272}) with improved traceability between sections (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/273}{Issue \#273}). The team formalized the document by standardizing terminology (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/274}{Issue \#274}) and reducing ambiguity in requirement wording (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/275}{Issue \#275}). Immunity requirement labeling corrections (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/153}{Issue \#153}) and security metric additions were implemented, though some suggestions like creating an entity relationship diagram were ultimately discarded (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/156}{Issue \#156}). + +\renewcommand{\arraystretch}{1.5} +\begin{longtable}{|p{2cm}|p{3.5cm}|p{4.5cm}|p{3cm}|} + \caption{SRS Feedback Tracking and Implementation} \label{tab:srs-feedback-tracking} \\ + \hline + \textbf{Feedback Source} & \textbf{Feedback Summary} & \textbf{Changes Made} & \textbf{Related Commits/Issues} \\ + \hline + \endfirsthead + + \multicolumn{4}{c}{{\bfseries Table \thetable\ continued from previous page}} \\ + \hline + \textbf{Feedback Source} & \textbf{Feedback Summary} & \textbf{Changes Made} & \textbf{Related Commits/Issues} \\ + \hline + \endhead + + \hline \multicolumn{4}{|r|}{{Continued on next page}} \\ \hline + \endfoot + + \hline + \endlastfoot + +peer & Add priority planning to phase in plan & None, None, discarded & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/155}{Issue \#136 + \#155} \\ +\hline + +peer & Clarify meaning of FR-8 & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/137}{Issue \#137} \\ +\hline + +peer & Clarify definition of ``lowest energy consumption'' & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/138}{Issue \#138} \\ +\hline + +peer & Specify which software developers are considered to be shareholders and how their feedback will be used & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/140}{Issue \#140} \\ +\hline + +peer & Explain why training requirements aren't needed for the project & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/141}{Issue \#141} \\ +\hline + +peer & Expand more of the energy consumption dashboard & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/152}{Issue \#152} \\ + \hline + +peer & Fix labelling for immunity requirements & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/153}{Issue \#153} \\ +\hline + +peer & Add measurable indicators of success to security fit criterion & None, discarded & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/153}{Issue \#153} \\ +\hline + +peer & Clarify ambiguous FR-2 & None, discarded & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/154}{Issue \#154} \\ +\hline + +peer & Create entity relationship diagram & None, discarded & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/156}{Issue \#156} \\ +\hline + +peer & Add adaptability requirements & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/157}{Issue \#157} \\ +\hline + +TA & Add symbolic constants & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/269}{Issue \#269} \\ +\hline + +TA & Move glossary up in the document & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/270}{Issue \#270} \\ +\hline + +TA & Reference tables and figures & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/271}{Issue \#271} \\ +\hline + +TA & Make requirements more abstract & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/272}{Issue \#272} \\ +\hline + +TA & Add traceability & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/273}{Issue \#273} \\ +\hline + +TA & Make requirements less ambiguous & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/274}{Issue \#274} \\ +\hline + +TA & Formalize document & addressed in issue & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/275}{Issue \#275} \\ +\hline +\end{longtable} + +\subsubsection{Hazard Analysis} + +The hazard analysis documentation was substantially improved through multiple feedback iterations. Terminology in SCR-9 was clarified (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/185}{Issue \#185}) and hazard/requirement references were corrected (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/186}{Issue \#186}). A new unexpected system shutdown hazard was added (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/187}{Issue \#187}), while clashing hazards were addressed before some components were later removed (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/189}{Issue \#189}). Both peer and TA feedback improved FMEA table formatting (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/190}{Issue \#190} + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/278}{Issue \#278}), and the critical assumptions section gained user/environment context (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/191}{Issue \#191}). Additional analysis covered inter-component hazards (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/192}{Issue \#192}), and reinforcement learning component actions were clarified before its removal (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/193}{Issue \#193}). Unclear assumptions were resolved (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/194}{Issue \#194}), while TA feedback ensured proper symbolic constant usage (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/277}{Issue \#277}) and component scope clarification (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/279}{Issue \#279}), though some analyzed components were later excluded during design evolution. + +\begin{longtable}{|p{2cm}|p{3.5cm}|p{4.5cm}|p{3cm}|} + \caption{Hazard Analysis Feedback Tracking and Implementation} \label{tab:ha-feedback-tracking} \\ + \hline + \textbf{Feedback Source} & \textbf{Feedback Summary} & \textbf{Changes Made} & \textbf{Related Commits/Issues} \\ + \hline + \endfirsthead + + \multicolumn{4}{c}{{\bfseries Table \thetable\ continued from previous page}} \\ + \hline + \textbf{Feedback Source} & \textbf{Feedback Summary} & \textbf{Changes Made} & \textbf{Related Commits/Issues} \\ + \hline + \endhead + + \hline \multicolumn{4}{|r|}{{Continued on next page}} \\ \hline + \endfoot + + \hline + \endlastfoot + +peer & Clarify the terminology used in SCR 9 & addressed & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/185}{Issue \#185} \\ + \hline + +peer & Fix referencing between hazards and requirements & addressed & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/186}{Issue \#186} \\ +\hline + +peer & Add new hazard related to unexpected system shutdown & addressed & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/187}{Issue \#187} \\ +\hline + +peer & Fix clashing hazards & \begin{itemize}[nosep,leftmargin=*] + \item Addressed initially + \item Component completely removed in later design iteration +\end{itemize} & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/189}{Issue \#189} \\ +\hline + +peer and TA & Fix FMEA table formatting & addressed & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/190}{Issue \#190}, \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/278}{Issue \#278} \\ +\hline + +peer & Critical assumptions section lacks user and environment context assumptions & addressed & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/191}{Issue \#191} \\ +\hline + +peer & FMEA table missing analysis of inter-component hazards and failure modes & addressed & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/192}{Issue \#192} \\ +\hline + +peer & Unclear recommended actions point for reinforcement learning component & \begin{itemize}[nosep,leftmargin=*] + \item Addressed initially + \item Component removed in later design iteration +\end{itemize} & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/193}{Issue \#193} \\ +\hline + +peer & Unclear critical assumptions & addressed & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/194}{Issue \#194} \\ +\hline + +TA & Need symbolic constants & addressed & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/277}{Issue \#277} \\ +\hline + +TA & Make clear which components are in scope & \begin{itemize}[nosep,leftmargin=*] + \item Addressed initially + \item Components removed in later iteration +\end{itemize} & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/279}{Issue \#279} \\ +\hline +\end{longtable} + + +\subsection{MG, MIS and Development Plan} + +The following table details all changes made to the MIS, MG and Development Plan. \\ + +\noindent Notable improvements include the formalization of discrete mathematical models for % +refactoring operations (Issue \#515), abstraction of core optimization logic to work across programming languages % +logic (Issue \#513), and consolidation of AST security modules (Issue \#510). % +Additional enhancements focused on documentation rigour through Canadian English % +standardization (Issue \#512), \LaTeX\ quote correction (Issue \#265), and % +explicit risk mitigation mapping (Issue \#267). These changes collectively % +strengthened the system's theoretical foundations while improving team % +accountability through quantified performance metrics (Issue \#266) and % +role definitions (Issue \#264). + +\begin{longtable}{|p{2cm}|p{3.5cm}|p{4.5cm}|p{3cm}|} + \caption{Feedback Responses for MIS, MG, Development Plan} \label{tab:feedback} \\ + \hline + \textbf{Feedback Source} & \textbf{Feedback Summary} & \textbf{Changes Made} & \textbf{Related Commits/Issues} \\ + \hline + \endfirsthead + + \multicolumn{4}{c}{{\bfseries Table \thetable\ continued from previous page}} \\ + \hline + \textbf{Feedback Source} & \textbf{Feedback Summary} & \textbf{Changes Made} & \textbf{Related Commits/Issues} \\ + \hline + \endhead + + \hline \multicolumn{4}{|r|}{{Continued on next page}} \\ \hline + \endfoot + + \hline + \endlastfoot + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/515}{Issue \#515}) & + MG/MIS not formalized & + \begin{itemize}[nosep,leftmargin=*] + \item Added math formalizations in MG for different refactorers that lent well to a discrete math implementation + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/515}{Issue \#515} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/513}{Issue \#513}) & + MIS needs abstraction & + \begin{itemize}[nosep,leftmargin=*] + \item Removed Python-specific code + \item Abstracted common functions + \end{itemize} & + Commits: + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/46fbcc9}{46fbcc9}, + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/d1a4506}{d1a4506} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/512}{Issue \#512}) & + Spelling inconsistencies & + \begin{itemize}[nosep,leftmargin=*] + \item Updated to Canadian English + \item Fixed table references + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/529}{PR \#529}, + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/530}{PR \#530} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/511}{Issue \#511}) & + Diagram orientation issues & + \begin{itemize}[nosep,leftmargin=*] + \item Redesigned hierarchy diagrams + \item Standardized downward flow + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/530}{PR \#530} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/510}{Issue \#510}) & + Module secret overlap & + \begin{itemize}[nosep,leftmargin=*] + \item Consolidated AST-related secrets + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/530}{PR \#530} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/267}{Issue \#267}) & + Risk identification in PoC & + \begin{itemize}[nosep,leftmargin=*] + \item Added explicit risk section + \item Mapped mitigations + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/9218c22}{9218c22} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/266}{Issue \#266}) & + Vague team charter & + \begin{itemize}[nosep,leftmargin=*] + \item Defined quantitative metrics + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/663fcd3}{663fcd3} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/265}{Issue \#265}) & + Incorrect LaTeX quotes & + \begin{itemize}[nosep,leftmargin=*] + \item Replaced all ``quotes'' + \item Added linter rule + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/2572497}{2572497} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/264}{Issue \#264}) & + Undefined team roles & + \begin{itemize}[nosep,leftmargin=*] + \item Assigned specific responsibilities + \item Created role descriptions + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/663fcd3}{663fcd3} \\ + \hline + +\end{longtable} \subsection{VnV Plan and Report} +\subsubsection{VnV Plan} +The VnV Plan underwent significant revisions based on feedback from both TAs and peers, with all addressed feedback items documented in Table~\ref{tab:vnv-feedback}. The most substantial changes involved restructuring our test plans to align with evolving requirements in the SRS (see Section~1.1 for detailed SRS modifications). As the project requirements were refined, we systematically removed obsolete test cases that no longer matched the current specifications and modified existing tests to better verify the updated functional and non-functional requirements. Particular attention was given to ensuring traceability between test cases and requirements through a revised traceability matrix. The automated testing strategy was also enhanced to accommodate new validation scenarios while maintaining comprehensive coverage of the system's core functionality.\\ + +\noindent More information on changes made to VnV Plan can be found in this \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/528}{issue} where commits are linked. + +\begin{longtable}{|p{2cm}|p{3.5cm}|p{4.5cm}|p{3cm}|} + \caption{Feedback Responses for VnV Plan} \label{tab:vnv-feedback} \\ + \hline + \textbf{Feedback Source} & \textbf{Feedback Summary} & \textbf{Changes Made} & \textbf{Related Commits/Issues} \\ + \hline + \endfirsthead + + \multicolumn{4}{c}{{\bfseries Table \thetable\ continued from previous page}} \\ + \hline + \textbf{Feedback Source} & \textbf{Feedback Summary} & \textbf{Changes Made} & \textbf{Related Commits/Issues} \\ + \hline + \endhead + + \hline \multicolumn{4}{|r|}{{Continued on next page}} \\ \hline + \endfoot + + \hline + \endlastfoot + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/222}{Issue \#222}) & + Add development plan to the list of relevant documentation section & + \begin{itemize}[nosep,leftmargin=*] + \item No changes were made. We did not reference the development plan in the vnv plan. + \end{itemize} & + N/A \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/223}{Issue \#223}) & + Clarification on Usability Survey Question & + \begin{itemize}[nosep,leftmargin=*] + \item Surveys were updated for the usability testing session and were moved to the Extras folder. + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/e53b27c6e3f789c699688f6be6bc8be0eb06620e}{e53b27c} \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/224}{Issue \#224}) & + Manual vs Automatic Test Control & + \begin{itemize}[nosep,leftmargin=*] + \item Reviewed all tests in plan to make sure whether they are automatic or manual + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/4c5acf71d8f5a05b33241a9b08d3c1c1525a57ae}{4c5acf7} \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/225}{Issue \#225}) & + Inconsistent Formatting in Test Requirements Section & + \begin{itemize}[nosep,leftmargin=*] + \item Reviewed Test Plan and fixed all formatting + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/4c5acf71d8f5a05b33241a9b08d3c1c1525a57ae}{4c5acf7} \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/226}{Issue \#226}) & + Unclear definition for unauthorized external modifications & + \begin{itemize}[nosep,leftmargin=*] + \item Added clarity to test-SRT-3 + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/d71ed8d06018c96abd1e1d932fe8687a835da713}{d71ed8d} \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/227}{Issue \#227}) & + Clearer acceptance criteria for maintainable and adaptable codebase & + \begin{itemize}[nosep,leftmargin=*] + \item More clarification to these terms in provided in the Process. Will not fix. + \end{itemize} & + N/A \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/238}{Issue \#238}) & + Inconsistent Fields Used for Requirements & + \begin{itemize}[nosep,leftmargin=*] + \item It didn't really make sense for static tests to share the same testing template as dynamic ones + \item Modified the template slightly so that all tests begin with the type field so that it is more clear that the test is static or dynamic + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/6069c72e491b164f29aeb210f09ef02a9dfd2b78}{6069c72} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/505}{Issue \#505}) & + Additional Citations Needed & + \begin{itemize}[nosep,leftmargin=*] + \item Added more citations + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/392d2fed426d09ca5d226ed9bf5661db71c03b45}{392d2fe} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/506}{Issue \#506}) & + Fix Spelling and Format & + \begin{itemize}[nosep,leftmargin=*] + \item Re-read the documentation to fix + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/c88209079443e8c2722190a65d204b4193b426e2}{c882090} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/507}{Issue \#507}) & + State How Survey Data will be Used & + \begin{itemize}[nosep,leftmargin=*] + \item Added more clarification and details on how the survey data will be used in testing + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/653e7a3757dadfda6df3a3dce1aa7de512d62029}{653e7a3} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/508}{Issue \#508}) & + Need More Quantifiable Metrics for Usability & + \begin{itemize}[nosep,leftmargin=*] + \item Added more metrics for usability in related tests + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/653e7a3757dadfda6df3a3dce1aa7de512d62029}{653e7a3} \\ + \hline + +\end{longtable} + +\subsubsection{VnV Report} + +We updated the VnV Report to address all the feedback from peers and TAs (see Table~\ref{tab:vnv-report-feedback}), but that wasn’t the only reason for the changes. Since the VnV Plan had evolved—especially with new tests and coverage metrics—we needed to sync the report with those updates. This meant adding results from the newly implemented tests, adjusting the traceability matrix, and expanding our analysis to reflect the current testing approach.\\ + +\noindent Beyond just feedback fixes, we also made general improvements to the report. These included better organization of test results, clearer explanations of our methodology, and updates to match the project’s current state. Many of these unrelated tweaks were tracked in \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/531}{Issue~\#531}, which served as our central hub for report revisions.\\ + +\noindent The biggest changes landed in Sections~7 and~8 (now with proper system/non-functional test coverage) and Section~9 (where we added detailed code coverage analysis). Throughout the report, we focused on keeping everything consistent with both the updated VnV Plan and the project’s actual progress. + +\begin{longtable}{|p{2cm}|p{3.5cm}|p{4.5cm}|p{3cm}|} + \caption{Feedback Responses for VnV Report} \label{tab:vnv-report-feedback} \\ + \hline + \textbf{Feedback Source} & \textbf{Feedback Summary} & \textbf{Changes Made} & \textbf{Related Commits/Issues} \\ + \hline + \endfirsthead + + \multicolumn{4}{c}{{\bfseries Table \thetable\ continued from previous page}} \\ + \hline + \textbf{Feedback Source} & \textbf{Feedback Summary} & \textbf{Changes Made} & \textbf{Related Commits/Issues} \\ + \hline + \endhead + + \hline \multicolumn{4}{|r|}{{Continued on next page}} \\ \hline + \endfoot + + \hline + \endlastfoot + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/485}{Issue \#485}) & + Trace to Requirements/Modules & + \begin{itemize}[nosep,leftmargin=*] + \item Duplicate issue of \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/424}{Issue \#424} and \href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/423}{Issue \#423} + \item We have separate issues that contain these details + \end{itemize} & + N/A \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/486}{Issue \#486}) & + Functional Requirements Evaluation Clarity & + \begin{itemize}[nosep,leftmargin=*] + \item Report contains numerous tables that clearly indicate which tests passed or failed for each subsection, and these tables are formatted for visual clarity. No change needed + \end{itemize} & + N/A\\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/487}{Issue \#487}) & + Hyperlinking to Previous Reports with the term "Code Smell" & + \begin{itemize}[nosep,leftmargin=*] + \item Code smell is a generic programming term. Added reference to the descriptions for code smells in the section. + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/1970f9dd09eec0007f0e4121992356353a52d940}{1970f9d} \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/488}{Issue \#488}) & + Definition of Each Code Smell & + \begin{itemize}[nosep,leftmargin=*] + \item Added explanation for each code smell + \end{itemize} + & \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/23a69c71a17c7213af65fb157f7bf75cbef331ba}{23a69c7} \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/489}{Issue \#489}) & + Missing Table Captions & + \begin{itemize}[nosep,leftmargin=*] + \item Added descriptive captions + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/3786f19d94dcc60efd35a35681573bb2851c65fb}{3786f19} \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/490}{Issue \#490}) & + Partial in Feedback and Implementation Plan & + \begin{itemize}[nosep,leftmargin=*] + \item Completed all test feedback + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/cf39eb73bbd66b1725e1a25303fe1906b0a7cd38}{cf39eb7} \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/492}{Issue \#492}) & + Functional requirement; specific syntax errors introduced in the test file are not mentioned & + \begin{itemize}[nosep,leftmargin=*] + \item The Purpose of this test is to verify the system's ability to detect and handle any Python syntax error, not specific error types. Therefore, there is no need to specify the exact syntax error. + \end{itemize} & + N/A \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/493}{Issue \#493}) & + Clear names for sample code smell & + \begin{itemize}[nosep,leftmargin=*] + \item Added clarification on extensibility + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/2118fa0bd79ad6c9e09af42395746c01b6b4c771}{2118fa0} \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/494}{Issue \#494}) & + Section 9: Code Coverage Metrics & + \begin{itemize}[nosep,leftmargin=*] + \item No longer relevant as tests were implemented/updated and new coverage was updated in the report + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/41c2c837f4fcd0df130ba5d0fdac084248224494}{41c2c83} \\ + \hline + + Peer (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/496}{Issue \#496}) & + Refer users to SRS and VnV Plan & + \begin{itemize}[nosep,leftmargin=*] + \item Added cross-reference section + \item Included document links + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/6989094e5c0762cf7f3becd5f69a7d91701c1c54}{6989094} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/578}{Issue \#578}) & + Some tests incomplete due to features & + \begin{itemize}[nosep,leftmargin=*] + \item Marked pending tests and completed them + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/2349ee1ce6a5f635fc2c1701a1b638bf4b155521}{2349ee1} \\ + \hline + + TA (\href{https://github.com/ssm-lab/capstone--source-code-optimizer/issues/577}{Issue \#577}) & + Spelling, grammar and style & + \begin{itemize}[nosep,leftmargin=*] + \item Proofread entire document + \end{itemize} & + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/commit/88f1f5d607ee781e9725c3d2fa78ef70782d44a8}{88f1f5d} \\ + \hline + +\end{longtable} + + \section{Challenge Level and Extras} \subsection{Challenge Level} \plt{State the challenge level (advanced, general, basic) for your project. Your challenge level should exactly match what is included in your problem statement. This should be the challenge level agreed on between you and the course instructor.} +The challenge level for this project is \textbf{general}, as agreed upon with the course instructor. + +\noindent This project required integrating multiple technical components, including developing a usable VS Code extension from scratch and a Python library to detect, measure and refactor energy-inefficient code patterns. + While these aspects were non-trivial, the scope and complexity aligned with a general challenge level rather than advanced. + \subsection{Extras} \plt{Summarize the extras (if any) that were tackled by this project. Extras @@ -80,6 +612,30 @@ \subsection{Extras} proof, GenderMag personas, Design Thinking, etc. Extras should have already been approved by the course instructor as included in your problem statement.} +Two extras were completed as part of this project: + +\begin{itemize} + \item \textbf{User Onboarding Guide:} + A detailed onboarding guide was developed and made available via the project wiki. It includes: + \begin{itemize} + \item Setup and installation instructions. + \item Explanation of plugin features and functionality. + \item Sample workflows for using the plugin. + \item Embedded video demonstrations to assist users visually. + \end{itemize} + The onboarding guide can be accessed \href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/wiki}{here}. + + + \item \textbf{Usability Testing:} + Usability testing was conducted to evaluate the effectiveness and user-friendliness of the plugin. The testing process included: + \begin{itemize} + \item Scenario-based user walkthroughs. + \item Survey responses measuring ease of use and satisfaction. + \item Identification of usability issues and areas for improvement. + \end{itemize} + A full report of the usability testing is available \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/Extras/UsabilityTesting/UsabilityTestingReport.pdf}{here}. + +\end{itemize} \section{Design Iteration (LO11 (PrototypeIterate))} \plt{Explain how you arrived at your final design and implementation. How did @@ -90,11 +646,132 @@ \section{Design Iteration (LO11 (PrototypeIterate))} response to usability testing, explain what the testing found and what changes it led to.} +The design of our project underwent several significant iterations throughout its development, each driven by technical considerations, stakeholder feedback, and usability testing results. This evolution reflects our team's commitment to creating a practical solution that effectively addresses user needs while remaining technically feasible within project constraints.\\ + + +\noindent \textbf{Initial Project Vision} + +\noindent +The project began as a Python library focused on code optimization, with supplementary components including an IDE plugin, web-based metrics visualization and a GitHub Actions that could fully integrate our library into a workflow as secondary features. Our original technical approach emphasized reinforcement learning (RL) as the core optimization mechanism, based on its potential for adaptive code improvement.\\ + + +\noindent \textbf{Pivotal Technical Reassessment} + +\noindent +In January, a crucial meeting with our project supervisor prompted a fundamental redesign. After consultation with one of our supervisor's graduate students who provided both project feedback and a reinforcement learning primer, we collectively determined that: + +\begin{itemize} + \item The RL approach would be set aside in favour of rule-based refactoring + \item The IDE plugin would transition from peripheral feature to primary interface +\end{itemize} + +This strategic shift was motivated by several factors: +\begin{itemize} + \item The complexity and time requirements of implementing effective RL exceeded our project timeline + \item Rule-based refactoring offered more predictable, explainable results + \item Emphasizing the plugin interface would better serve our target users (developers) in their natural workflow environment +\end{itemize} + +Visual Studio Code was selected as our target IDE early in the process due to its widespread adoption and robust extension capabilities.\\ + + +\noindent \textbf{Scope Refinement After Revision 1} + +\noindent +Following our first formal review with course professors, we made the deliberate decision to remove features like a GitHub Actions and web-based metrics from our scope. This simplification allowed us to concentrate our efforts on refining functionality we already had while maintaining a realistic development timeline.\\ + + +\noindent \textbf{Usability-Driven Interface Improvements} + +\noindent +In early March, we conducted two structured usability testing sessions that yielded valuable feedback (detailed \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/Extras/UsabilityTesting/UsabilityTestingReport.pdf}{here}). These sessions revealed several key pain points and opportunities for enhancement: + +\begin{itemize} + \item \textbf{Interface Clarity}: Users struggled with sidebar visibility and button distinction, leading us to: + \begin{itemize} + \item Overhaul the sidebar completely. We went from a sidebar that only populated when a refactoring was in session to a permanent fixture that was an integral part of using accessing the extension's features. + \item Add features like constant smell detection. + \end{itemize} + + \item \textbf{User Guidance}: New users required more onboarding support, resulting in: + \begin{itemize} + \item Development of step-by-step instructions manual + \item Addition of progress indicators to manage expectations during refactoring + \end{itemize} + + \item \textbf{Customization Needs}: Users requested more personalization options, prompting us to: + \begin{itemize} + \item Implement colour customization for different smell types + \item Expand explanatory content about energy-saving benefits + \end{itemize} +\end{itemize} + + +\noindent \textbf{Final Implementation Approach} + +\noindent +The current implementation reflects these iterative improvements while respecting project constraints. We prioritized changes that addressed: +\begin{itemize} + \item High-frustration pain points (e.g., button visibility) + \item Critical usability gaps (e.g., lack of user guidance) + \item Valuable customization options + \item Clear communication of system status +\end{itemize} + +This evolutionary process demonstrates our user-centred design philosophy, where technical decisions were continually evaluated against both implementation feasibility and real user needs. The result is a more focused, usable tool that maintains its core value proposition while offering an improved user experience. + + \section{Design Decisions (LO12)} -\plt{Reflect and justify your design decisions. How did limitations, - assumptions, and constraints influence your decisions? Discuss each of these - separately.} +The implementation of EcoOptimizer was shaped by technical limitations, project constraints, and core design principles. The system was built to be modular, extensible, and energy-aware, while remaining usable and performant in a local development environment. + +\subsection*{Architectural Decisions} + +\begin{itemize} + \item \textbf{Refactorer Design Structure:} The refactoring subsystem follows a two-level inheritance hierarchy: + \begin{itemize} + \item \texttt{BaseRefactorer} defines the interface and shared logic for all refactorers. + \item \texttt{MultiFileRefactorer} extends \texttt{BaseRefactorer} to support transformations across multiple files. + \item Concrete refactorers subclass either \texttt{BaseRefactorer} or \texttt{MultiFileRefactorer}, depending on their scope. + \end{itemize} + This structure enforces separation of concerns, encourages reusability, and makes it easy to introduce new refactorers without modifying the core system. +\end{itemize} + +\subsection*{Limitations} + +\begin{itemize} + \item \textbf{Tooling Limitations for Code Smell Detection:} No single tool could detect all required smells. A strategy-based analyzer system was introduced to combine AST, Astroid, Pylint, and custom analyzers dynamically. + + \item \textbf{Energy Measurement Accuracy:} Energy readings from CodeCarbon vary with hardware and OS. To reduce variability, measurements are performed in isolated subprocesses and compared under consistent conditions. + + \item \textbf{File-Level Focus:} While most refactorings are file-scoped, limited multi-file analysis was included for smells requiring cross-file changes. + + \item \textbf{Temporary File Refactoring:} All transformations are staged in temporary directories before applying to source files. This protects code integrity but adds complexity to file handling and rollback. +\end{itemize} + +\subsection*{Assumptions} + +\begin{itemize} + \item \textbf{Valid Python Input:} The system assumes syntactically correct Python files as input to avoid expensive pre-validation routines. + + \item \textbf{Code Executability:} Energy measurement assumes the input file can be run as a standalone Python script using a main entry point. + + \item \textbf{Library Availability:} It is assumed that CodeCarbon and its dependencies are installed and operational across user systems. +\end{itemize} + +\subsection*{Constraints} + +\begin{itemize} + \item \textbf{Performance Trade-offs:} Analyzer and refactorer execution was parallelized and subprocessed to preserve responsiveness, especially on large codebases. + + \item \textbf{Cross-Platform File Management:} Temporary directories and subprocess logic were adapted for compatibility across Windows (\texttt{TEMP}) and Unix-based systems (\texttt{TMPDIR}). + + \item \textbf{Security and Stability:} Refactoring operations and energy measurements are isolated to prevent modifications to user files before validation. Logging and error handling ensure graceful degradation on failures. + + \item \textbf{Ecosystem Fit:} Libraries like FastAPI, Pydantic, and CodeCarbon were selected based on open-source licensing and compatibility with modern Python development practices. +\end{itemize} + +\noindent Overall, the architecture of EcoOptimizer balances security, performance and extensibility. Each design decision reflects a trade-off that prioritizes energy transparency and safe refactoring, while remaining mindful of usability and future expandability. \section{Economic Considerations (LO23)} @@ -105,6 +782,78 @@ \section{Economic Considerations (LO23)} open source project, how would you go about attracting users? How many potential users currently exist?} + +\subsection{Market Viability} +There is a growing market for sustainability-focused developer tools, +driven by corporate Environmental, Social, and Governance (ESG) goals +and rising cloud computing costs. EcoOptimizer targets the 16.7 million +active Visual Studio Code users \cite{vscodeUsers}, +particularly enterprise developers and organizations seeking to reduce +energy consumption in code deployment. Competitors like code linters and +performance optimizers exist, but EcoOptimizer +uniquely ties refactoring +to CO2 reduction metrics, aligning with global net-zero initiatives. + +\subsection{Marketing Strategy} +To promote EcoOptimizer, we propose: +\begin{itemize} + \item \textbf{Community Engagement}: Launch on developer forums (Reddit, HackerNews, Stack Overflow) and open-source platforms (GitHub). + \item \textbf{Partnerships}: Collaborate with cloud providers (AWS, Google Cloud). + \item \textbf{Content Marketing}: Publish case studies demonstrating energy cost savings (e.g., "Reducing AWS bills by 12\% via loop optimization"). + \item \textbf{Freemium Model}: Offer basic optimizations for free, with premium features (custom CO2 metrics, CI/CD integration) for paid tiers. +\end{itemize} + +\subsection{Production Costs} +Developing a commercially viable version of EcoOptimizer requires strategic allocation of resources across three key areas: + +\begin{itemize} + \item \textbf{Further Development}: We would allocate \$20,000 to further the development + of the tool and add more useful features and better security. The \$20,000 development + cost reflects industry-standard freelance rates for full-stack Python/TypeScript + development. At \$20/hour \cite{upwork2025rates}, this covers 1,000 hours of work. + + \item \textbf{Maintenance}: Monthly costs of \$1,000 are driven primarily by cloud + hosting. Using Google Cloud’s pricing calculator \cite{googlecloud2025pricing}, + we estimate \$500/month for backend servers and \$300/month for API usage, with + \$200 reserved for incremental updates. + + \item \textbf{Marketing}: We would allocate an initial \$5,000 for marketing + that could change as more users join or time progresses. + The \$5,000 upfront investment aligns with HubSpot’s + benchmarks for bootstrapped developer tools \cite{hubspot2025marketing}, + covering SEO optimization, paid ads targeting VS Code users, and content + creation for technical blogs. As we are just starting out we dont have + a ton of money to dump into marketing from the start. + +\end{itemize} + +\noindent Total first-year operational costs amount to \$37,000, positioning EcoOptimizer competitively against similar sustainability tools with higher upfront R\&D budgets. + +\subsection{Pricing and Profitability} +EcoOptimizer adopts a \textbf{freemium model} to maximize adoption while ensuring sustainability, offering: + +\begin{itemize} + \item \textbf{Free Tier}: Basic code optimization (loop simplification, dead code removal) + to build trust and community engagement. + + \item \textbf{Individual Tier}: Priced at \$5/month or \$50/year, this \textit{paid} + tier unlocks advanced features like CI/CD integration and custom CO2 dashboards. + Aligns with premium VS Code extensions like \textit{CodeGPT} \cite{codeGPTPricing}. + To break even on the \$37,000 first-year operational costs, EcoOptimizer requires + \textbf{740 annual subscribers} (\$37,000 / \$50 per user). Given VS Code’s 14M-user + base \cite{vscodeUsers}, this represents just 0.0053\% of the total market—a + feasible target within 12 months. + + \item \textbf{Enterprise Tier}: \$1,000/year per-team licenses include priority + support and multi-repo analysis, reflecting premium ESG tool pricing in the current market. + +\end{itemize} + +\noindent Focusing solely on the Individual Tier, EcoOptimizer achieves break-even by +acquiring \textbf{740 annual subscribers} (\$37,000 / \$50 per user). This requires +converting just \textbf{0.0053\%} of VS Code’s 14M users, a highly attainable target +given industry benchmarks for niche developer tools. + \section{Reflection on Project Management (LO24)} \plt{This question focuses on processes and tools used for project management.} @@ -115,19 +864,102 @@ \subsection{How Does Your Project Management Compare to Your Development Plan} team communication plan, team member roles and workflow plan. Did you use the technology you planned on using?} +We largely followed our development plan regarding team meetings, communication, +member roles, and workflow. We adhered to our planned meeting schedule, ensuring regular +discussions to track progress, resolve blockers, and align our work with project goals. +To keep everything organized, all types of meetings were documented as issues on GitHub. +This allowed us to track progress effectively, link discussions to specific tasks, and +maintain meeting notes for future reference. + +Our communication plan also worked well—whether through scheduled check-ins or ad-hoc +discussions, we maintained a steady flow of information via our chosen platforms. Each +team member upheld their assigned roles, ensuring a balanced distribution of tasks. Our +workflow remained structured, with clear milestones and responsibilities that kept the +project on track. While there were some natural adjustments along the way to optimize +efficiency, we remained aligned with the overall plan. + +Regarding technology, we successfully used the tools and frameworks outlined in our +development plan. Our refactoring library was developed in Python, leveraging Rope for +refactoring, PyLint for inefficient code pattern detection, and Code Carbon for energy +analysis. For code quality, we enforced PEP 8 standards and used Ruff for linting and +Pyright for static type checking. Additionally, we incorporated PySmells for detecting +code smells. + +To ensure robust testing, we wrote unit tests using pytest, integrated with coverage.py +to measure code coverage. We also implemented performance benchmarking using Python’s +built-in benchmarking tools to measure execution time across different file sizes. + +For version control and CI/CD, we relied on GitHub and GitHub Actions, streamlining +our development process through automated testing and integration. Our VS Code plugin +was built using TypeScript, aligning with the VS Code architecture. + +Overall, we effectively used the planned technologies and tools, making only necessary +refinements to optimize development. + \subsection{What Went Well?} \plt{What went well for your project management in terms of processes and technology?} +One of the biggest strengths was how we stayed organized. We used GitHub Issues to track +tasks, discussions, and even meeting notes, which made it easy to monitor progress and +ensure accountability. This approach helped keep everything transparent and well-documented. + +Communication was another strong point. We stuck to our planned check-ins but also had +the flexibility to reach out whenever needed. This balance kept things moving without +feeling rigid. We also made sure to follow PEP 8 coding standards and used linters, +which kept our code consistent and easy to read. + +The tools we used made a big difference in keeping things smooth. GitHub Actions handled +our automated testing and integration, so we didn’t have to worry about manually running +tests every time. PyTest and Coverage.py helped us stay on top of testing, while Ruff and +PyLint made sure our code was clean and error-free. + +For the actual project, Code Carbon gave us energy consumption insights (even if it +wasn’t always perfectly accurate), and Rope made refactoring much easier, saving us a lot of time. + +Overall, the combination of good teamwork, clear processes, and the right tools kept us +organized and made development a lot more efficient. + \subsection{What Went Wrong?} \plt{What went wrong in terms of processes and technology?} +One of the main challenges we faced in the project was moving away from using +reinforcement learning. Initially, it seemed like a great way to optimize energy +consumption, but as we decided not to use it, the direction of the project had to +shift. This required us to adjust our approach, which took time and created some +uncertainty within the team. Keeping everyone aligned and maintaining clear +communication was essential during this transition, especially as we explored +alternative methods to achieve our goals. + +On the technology side, developing the refactoring library itself turned out to +be more complicated than we initially anticipated. Creating a tool that could not +only identify energy-saving opportunities but also refactor the code while preserving +its intent was a delicate balance. Working with Python's unique performance and +dynamic features added another layer of complexity. Despite these challenges, they +provided valuable learning experiences that have shaped how we approach the project now. + \subsection{What Would you Do Differently Next Time?} \plt{What will you do differently for your next project?} +For our next project, one thing we’d do differently is spend more time upfront +validating the technical approach before diving into development. With the shift +away from reinforcement learning, we had to make adjustments mid-way through, which +slowed down progress. In the future, we’d prioritize a more thorough exploration of +different technologies and approaches early on to avoid these kinds of pivots. We’d +also make sure to keep a closer eye on scope to prevent unnecessary shifts that could +affect the timeline. + +Additionally, we’d focus on improving team coordination from the start, ensuring that +everyone is aligned not just on the technical goals but also on the project’s overall +direction. Regular, structured check-ins would be helpful to track progress and address +roadblocks quickly. On the technical side, we would invest more time in setting up a robust +DevOps pipeline earlier in the process, ensuring that continuous integration and testing are +seamless from the beginning. Overall, we believe these changes would help streamline both the +technical and team dynamics for a smoother project experience. + \section{Reflection on Capstone} \plt{This question focuses on what you learned during the course of the capstone project.} @@ -135,10 +967,100 @@ \section{Reflection on Capstone} \subsection{Which Courses Were Relevant} \plt{Which of the courses you have taken were relevant for the capstone project?} +Several courses we’ve taken were highly relevant to our capstone project: + +\begin{itemize} + \item \textbf{Software Architecture}: This course gave us a solid foundation in designing + scalable, maintainable, and efficient software systems, which was essential when building + the refactoring library and ensuring the overall structure of our tool was optimal. + + \item \textbf{Data Structures and Algorithms}: The principles from this course helped us + design more efficient algorithms for analyzing and refactoring source code to optimize + energy consumption. Understanding how to work with data structures effectively was key + in handling different code patterns and optimization techniques. + + \item \textbf{Database Systems}: Although we didn’t directly deal with complex databases + in the capstone, understanding how to efficiently manage and query large datasets was + useful when we considered tracking energy usage metrics or managing configurations within + the system. + + \item \textbf{Real-Time Systems and Control Applications}: This course provided insights + into managing time-sensitive tasks and the real-time performance of systems, which was + helpful when considering the energy optimization of software execution, particularly in + the context of how different coding choices could impact performance in real-time. + + \item \textbf{Intro to Software Development}: This course was crucial for learning best + practices in documentation and understanding design patterns, which helped us structure + our code and communicate our approach effectively throughout the project. + + \item \textbf{Object-Oriented Programming}: The concepts from this course were directly + applied when designing our system, especially when managing the relationships between the + different components of our refactoring library. + + \item \textbf{Human Computer Interfaces}: This course helped us a lot with usability testing + and designing the frontend of our tool in VS Code, ensuring that it was user-friendly and + intuitive for anyone using the software. + + \item \textbf{Software Engineering Practice and Experience: Binding Theory to Practice}: This + course was instrumental in teaching us how to approach open-ended design problems and apply + both theoretical and practical knowledge to real-world scenarios. It was particularly helpful + in guiding us through the experiential approach to solving computational problems, especially + when considering embedded systems and assembly programming. + +\end{itemize} + +These courses equipped us with the necessary technical background to approach the project’s +challenges, from system design to algorithm optimization, and they directly informed the decisions +we made while building the energy optimization tool. \subsection{Knowledge/Skills Outside of Courses} \plt{What skills/knowledge did you need to acquire for your capstone project that was outside of the courses you took?} +For our capstone project, we had to acquire several skills and knowledge areas that were not directly +covered in our coursework: + +\begin{itemize} + \item \textbf{Energy-Efficient Software Development}: We had to research and understand techniques + for reducing energy consumption in software, including best practices for writing energy-efficient + code and tools for measuring energy usage. + + \item \textbf{Static Code Analysis}: Since our project involved analyzing and refactoring code, + we had to learn about static analysis techniques and how to extract meaningful insights from + source code without executing it. + + \item \textbf{Refactoring Strategies for Energy Optimization}: While we had learned about code + refactoring in some courses, optimizing for energy efficiency was a new challenge. We had to + explore strategies that improve performance while minimizing power consumption. + + \item \textbf{GitHub DevOps and CI/CD Pipelines}: Although we had experience with version control, + setting up automated testing and continuous integration workflows in GitHub required additional + learning. + + \item \textbf{VS Code Extension Development}: Since our tool was designed to work within VS Code, + we had to learn how to develop and integrate extensions, which was not covered in our coursework. + + \item \textbf{User Research and Usability Testing}: While our Human-Computer Interfaces course + covered usability principles, we had to go deeper into conducting user research, gathering + feedback, and refining our tool's user experience. + + \item \textbf{Performance Profiling and Benchmarking}: Measuring the energy impact of different + coding techniques required us to explore profiling tools and benchmarking methods to ensure our + refactorings were actually improving efficiency. + + \item \textbf{Advanced Python Optimization Techniques}: Since our refactoring library is + Python-based, we needed to learn about Python-specific optimizations, including memory management, + just-in-time compilation techniques, and efficient data structures. +\end{itemize} + +These additional skills allowed us to successfully design and implement our energy optimization tool, +bridging the gap between our academic knowledge and the real-world challenges of software efficiency. + + +~\newpage + +\bibliographystyle{plainnat} +\bibliography{../../refs/References} + \end{document} \ No newline at end of file diff --git a/docs/SRS/README.md b/docs/SRS/README.md index b801422d..6bcbd094 100644 --- a/docs/SRS/README.md +++ b/docs/SRS/README.md @@ -1,12 +1,39 @@ -# Software Requirements Specification (SRS) +# Software Requirements Specification Directory - +This directory contains the Software Requirements Specification (SRS) documentation for the Source Code Optimizer project. - +## Directory Contents -The folders and files for this folder are as follows: +### Files +- `README.md` - Documentation overview +- `README.txt` - Legacy documentation notes +- `Makefile` - Build configuration for documentation generation +- `SRS.tex` - LaTeX source for the SRS document +- `SRS.pdf` - Generated SRS document +- `SRS-FAQ.tex` - LaTeX source for FAQ document +- `SRS-FAQ.pdf` - Generated FAQ document +- `SystemContextFigure.pdf` - System context diagram +- `SystemContextFigure.pptx` - Source file for system context diagram +- `RelationsBetweenTM_GD_IM_DD_A.pdf` - Relationship diagrams between modules -Describe ... +## Major Components + +1. Requirements Documentation + - Software Requirements Specification + - System Context Diagrams + - Module Relationships + +## Usage + +1. The main SRS document is organized according to standard software engineering practices and includes: + - Project overview and objectives + - Functional requirements + - Non-functional requirements + - System constraints + - Interface specifications + +## Maintenance + +1. All changes to requirements should be documented in the SRS.tex file +2. Use the Makefile to ensure consistent PDF generation diff --git a/docs/SRS/SRS.pdf b/docs/SRS/SRS.pdf index 23fc2f07..090f7d58 100644 Binary files a/docs/SRS/SRS.pdf and b/docs/SRS/SRS.pdf differ diff --git a/docs/SRS/SRS.tex b/docs/SRS/SRS.tex index 5b2c71f0..e03606c5 100644 --- a/docs/SRS/SRS.tex +++ b/docs/SRS/SRS.tex @@ -30,7 +30,6 @@ \usepackage{tikz} \usetikzlibrary{automata, positioning, arrows.meta, shapes, backgrounds} -\usepackage{float} % For precise figure placement \newcommand{\lips}{\textit{Insert your content here.}} @@ -67,15 +66,10 @@ \section*{Revision History} October 11th, 2024 & All & Created initial revision of SRS\\ January 2nd, 2025 & All & Added clarification to training requirements\\ January 5th, 2025 & All & Update FR-7, FR-8, Ideas for Solution \\ - January 6th, 2025 & All & Fixed link references to tables and - figures and added preambles to those sections, move glossary - section, added symbolic constants\\ - February 8th, 2025 & All & Removed requirement for interfacing with - GitHub Actions.\\ - February 10th, 2025 & All & Updated the data dictionary and - business data model \\ - February 10th, 2025 & All & Updated costs, compliance requirements, - security requirements and scope of the product. \\ + January 6th, 2025 & All & Fixed link references to tables and figures and added preambles to those sections, move glossary section, added symbolic constants\\ + February 8th, 2025 & All & Removed requirement for interfacing with GitHub Actions.\\ + February 10th, 2025 & All & Updated the data dictionary and business data model \\ + February 10th, 2025 & All & Updated costs, compliance requirements, security requirements and scope of the product. \\ March 24th, 2025 & All & Updated and added functional requirements. \\ March 24th, 2025 & Mya Hussain & Updated Usability and Humanity Requirements. \\ March 24th, 2025 & Ayushi Amin & Updated maintainability and support requirements. \\ @@ -88,7 +82,8 @@ \section*{Revision History} March 24th, 2025 & Ayushi Amin & Updated migration of new product. \\ March 24th, 2025 & Ayushi Amin & Updated Costs section. \\ March 24th, 2025 & Mya Hussain & Created state diagram closes feedback. \\ - \bottomrule + March 25th, 2025 & Ayushi Amin & Removed Duplicate Requirements.\\ + \bottomrule \end{tabularx} ~\\ @@ -711,7 +706,7 @@ \subsection{Work Partitioning} \begin{table}[H] \centering \setlength\extrarowheight{5mm} - \begin{tabularx}{\textwidth}{|c|X|l|p{1.5in}|p{1.5in}|} + \begin{tabularx}{\textwidth}{cXlp{1.5in}p{1.5in}} \toprule \textbf{Event \#} & \textbf{Event Name} & \textbf{Input} & \textbf{Output(s)} & \textbf{Requirements}\\ \midrule @@ -834,7 +829,7 @@ \subsection{Data Dictionary} \begin{longtable}[H]{ >{\raggedright\arraybackslash}p{3.5cm} >{\raggedright\arraybackslash}p{9cm} - >{\raggedright\arraybackslash}p{2cm}} + >{\raggedright\arraybackslash}p{2cm}} \toprule \textbf{Name} & \textbf{Content} & \textbf{Type} \\ \midrule @@ -1175,20 +1170,8 @@ \subsection{Functional Requirements} refactorings are applied ensures that they can maintain the balance between energy efficiency and their coding style or project requirements.\\ - {\bf Fit Criterion:} The IDE plugin must display at least two - refactoring options for inefficient code patterns, allowing - developers to either apply or reject them before making any changes.\\ - {\bf Priority:} Medium - \item \emph{The system shall provide developers with refactoring - suggestions within an IDE before changing code, allowing them - to review and approve energy-efficient changes.}\\[2mm] - {\bf Rationale:} Giving developers control over which - refactorings are applied ensures that they can maintain the - balance between energy efficiency and their coding style or - project requirements.\\ - {\bf Fit Criterion:} The IDE plugin must display at least two - refactoring options for inefficient code patterns, allowing - developers to either apply or reject them before making any changes.\\ + {\bf Fit Criterion:} The IDE plugin must display refactoring options for inefficient + code patterns if possible, allowing developers to either apply or reject them before making any changes. \\ {\bf Priority:} Medium \item \emph{The system must allow users to filter detected code smells within the IDE plugin.}\\[2mm] {\bf Rationale:} Developers should be able to focus on specific types of inefficiencies based on their @@ -1236,11 +1219,6 @@ \subsection{Functional Requirements} {\bf Fit Criterion:} The system provides an option to delete previously detected smells and cached data, ensuring a reset state when needed.\\ {\bf Priority:} Medium -\item \emph{The system should allow for the enabling and disabling of specific smells for detection.}\\[2mm] - {\bf Rationale:} Developers may want to focus on certain types of inefficiencies while ignoring others based on project-specific needs.\\ - {\bf Fit Criterion:} The system provides an interface where users can enable or disable specific code smells from being detected and reported.\\ - {\bf Priority:} Medium - \end{enumerate} @@ -1303,12 +1281,6 @@ \subsection{Ease of Use Requirements} \subsection{Personalization and Internationalization Requirements} \begin{enumerate}[label=UHR-PSI \arabic*., wide=0pt, leftmargin=*] - \item \emph{The tool shall allow users to enable or disable detection of individual code smells.} - \\[2mm] - {\bf Rationale:} Developers should be able to focus on relevant code smells for their specific project needs.\\ - {\bf Fit Criterion:} Users can successfully toggle detection of any smell type on or off.\\ - {\bf Priority:} High - \item \emph{The tool shall allow users to customize highlight colors for each detected code smell type.} \\[2mm] {\bf Rationale:} Custom colors improve readability and accommodate different visual preferences.\\ @@ -1326,13 +1298,6 @@ \subsection{Learning Requirements} {\bf Fit Criterion:} Help resources should be accessible within MAX\_TASK\_CLICKS limit.\\ {\bf Priority:} High - \item \emph{The tool shall have an available YouTube video - demonstrating installation.}\\[2mm] - {\bf Rationale:} Video tutorials provide visual learning - resources that can make the installation process more accessible to users.\\ - {\bf Fit Criterion:} A YouTube video demonstrating installation - should be present and easily accessible.\\ - {\bf Priority:} Low \end{enumerate} \subsection{Understandability and Politeness Requirements} @@ -1399,13 +1364,6 @@ \subsection{Precision or Accuracy Requirements} {\bf Fit Criterion:} Detection accuracy should exceed DETECTION\_ACC when validated against a set of known cases.\\ {\bf Priority:} Medium - \item \emph{The tool shall produce valid refactored Python code as - output or indicate that no possible refactorings were found.}\\[2mm] - {\bf Rationale:} Ensuring that the tool produces valid output is - essential for maintaining code quality.\\ - {\bf Fit Criterion:} The output code is syntactically correct and - adheres to Python standards.\\ - {\bf Priority:} Medium \end{enumerate} \subsection{Robustness or Fault-Tolerance Requirements} @@ -1502,8 +1460,7 @@ \subsection{Requirements for Interfacing with Adjacent Systems} in VSCode marketplace.\\ {\bf Priority:} Medium \item \emph{The library should support importing existing codebases - and exporting refactored code and energy savings reports in - standard formats (e.g., JSON, XML)}\\[2mm] + and exporting refactored code in standard formats}\\[2mm] {\bf Rationale:} This ensures that users can easily integrate the library into their existing workflows without significant disruption.\\ {\bf Fit Criterion:} Developers are able to refactor existing @@ -1624,37 +1581,6 @@ \subsection{Adaptability Requirements} performance or functionality\\ {\bf Priority:} Low - \item \emph{The system must be able to detect and handle Python - version-specific features and syntax.}\\ - {\bf Rationale:} Depending on the Python version of the source - code, the refactorings should be made accordingly to not - introduce compatibility errors.\\ - {\bf Fit Criteria:} The input source code should pass the given - test cases.\\ - {\bf Priority:} High - - \item \emph{The energy measurement module must be adaptable to - cloud-based systems.}\\ - {\bf Rationale:} Many modern applications are hosted and run in - cloud environments so, it is essential for the energy measurement - module to operate effectively in cloud-based systems. This - ensures that developers can accurately measure the energy - consumption of their cloud-hosted applications.\\ - {\bf Fit Criteria:} The energy consumption module returns usable - statistics related to the energy consumption of the cloud-application.\\ - {\bf Priority:} Medium - - \item \emph{The system must be deployable in both cloud-based - environments and on-premise infrastructures to meet different user needs.}\\ - {\bf Rationale:} Whether the system is being used locally or in - the cloud, developers still need access to the features offered - by the system. Some developers might not even host their - applications, and, even if they do, they might want to conduct - local testing. \\ - {\bf Fit Criteria:} The system should be fully functional in both - cloud and local environments, with minimal configuration changes.\\ - {\bf Priority:} Medium - \item \emph{The system must support major operating systems, including Windows, macOS, and Linux.}\\ {\bf Rationale:} Developers may not all use the same operating @@ -1677,17 +1603,6 @@ \subsection{Adaptability Requirements} compatibility issues in handling file systems, dependencies, or libraries.\\ {\bf Priority:} Low - \item \emph{The system must offer consistent performance (e.g., - refactoring speed, energy consumption measurements) regardless of - the underlying operating system.}\\ - {\bf Rationale:} Having the system be OS dependent would - invalidate the point of being compatible with multiple OSes and - conflict with requirement MS-AD 6.\\ - {\bf Fit Criteria:} Performance metrics, such as time taken for - refactoring and energy measurements, must not vary by more than - OS\_PERF\_DIFF\_LIMIT across different operating systems during testing.\\ - {\bf Priority:} Low - \end{enumerate} \section{Security Requirements} @@ -1802,7 +1717,7 @@ \subsection{Cultural Requirements} avoid alienating or offending users from diverse backgrounds, which is critical for global acceptance and usability.\\ {\bf Fit Criteria:} Conduct a cultural review to ensure that all - icons and colours used in the tool are neutral and universally acceptable. + icons and colours used in the tool are neutral and universally acceptable.\\ {\bf Priority:} Low @@ -1812,7 +1727,7 @@ \subsection{Cultural Requirements} that the tool is respectful and inclusive, fostering a positive user experience across different cultures.\\ {\bf Fit Criteria:} A cultural sensitivity review is conducted to - ensure all content is appropriate for a global audience. + ensure all content is appropriate for a global audience.\\ {\bf Priority:} Medium \end{enumerate} @@ -1844,7 +1759,7 @@ \subsection{Standards Compliance Requirements} \end{enumerate} \section{Traceability from Requirements to Use Cases} -\begin{longtable}{|p{2.5cm}|p{11cm}|} +\begin{longtable}{p{2.5cm}p{11cm}} \toprule \textbf{Requirement} & \textbf{Use Case(s)} \\ \midrule @@ -2743,7 +2658,7 @@ \subsubsection*{Nivetha Reflection} ~\newpage -\bibliographystyle {plainnat} +\bibliographystyle{plainnat} \bibliography{../../refs/References} \end{document} diff --git a/docs/UserGuide/Makefile b/docs/UserGuide/Makefile deleted file mode 100644 index da819f43..00000000 --- a/docs/UserGuide/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -# Makefile -# From https://danielkaes.wordpress.com/2009/03/14/compiling-latex-documents-using-makefiles/ - -PROJECT=UserGuide -TEX=latexmk -BUILDTEX=$(TEX) -pdf $(PROJECT).tex - -all: - $(BUILDTEX) - -clean-all: - rm -f *.dvi *.log *.bak *.aux *.bbl *.blg *.idx *.ps *.eps *.pdf *.toc *.synctex.gz *.out *~ - -clean: - rm -f *.log *.bak *.aux *.bbl *.blg *.idx *.toc *.synctex.gz *.out *~ \ No newline at end of file diff --git a/docs/UserGuide/README.md b/docs/UserGuide/README.md deleted file mode 100644 index 7ce7780a..00000000 --- a/docs/UserGuide/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# User Guide - -The user guide could also include video introductions and tutorials. - -The folders and files for this folder are as follows: - -Describe ... - diff --git a/docs/UserGuide/UserGuide.tex b/docs/UserGuide/UserGuide.tex deleted file mode 100644 index ed975f91..00000000 --- a/docs/UserGuide/UserGuide.tex +++ /dev/null @@ -1,35 +0,0 @@ -\documentclass{article} - -\usepackage{booktabs} -\usepackage{tabularx} - -\input{../Comments} -\input{../Common} - -\title{User Guide\\\progname} - -\author{\authname} - -\date{} - -\begin{document} - -\begin{table}[hp] -\caption{Revision History} \label{TblRevisionHistory} -\begin{tabularx}{\textwidth}{llX} -\toprule -\textbf{Date} & \textbf{Developer(s)} & \textbf{Change}\\ -\midrule -Date1 & Name(s) & Description of changes\\ -Date2 & Name(s) & Description of changes\\ -... & ... & ...\\ -\bottomrule -\end{tabularx} -\end{table} - -\newpage - -\maketitle - - -\end{document} \ No newline at end of file diff --git a/docs/VnVPlan/README.md b/docs/VnVPlan/README.md index 20f6d67e..de5ff00b 100644 --- a/docs/VnVPlan/README.md +++ b/docs/VnVPlan/README.md @@ -1,5 +1,49 @@ -# Verification and Validation Plan +# Verification and Validation Plan Directory -The folders and files for this folder are as follows: +This directory contains the Verification and Validation (V&V) Plan documentation for the Source Code Optimizer project, detailing testing strategies and quality assurance procedures. -Describe ... +## Directory Contents + +### Files +- `README.md` - Documentation overview +- `Makefile` - Build configuration for documentation generation +- `VnVPlan.tex` - LaTeX source for the V&V Plan document +- `VnVPlan.pdf` - Generated V&V Plan document + +## Major Components + +1. Testing Strategy + - Unit Testing + - Integration Testing + - System Testing + - Performance Testing + +2. Validation Approach + - User Acceptance Testing + - Requirements Validation + - Performance Validation + - Security Testing + +3. Quality Metrics + - Code Coverage Goals + - Performance Benchmarks + - Quality Gates + - Acceptance Criteria + +## Usage Guidelines + +1. Document Generation + - Use make to generate PDF documentation + - Review generated documents + - Maintain version control + +## Maintenance + +1. Regular Updates + - Update test cases + - Maintain documentation + - Track changes + +2. Quality Control + - Validate test coverage + - Review test results diff --git a/docs/VnVPlan/VnVPlan.pdf b/docs/VnVPlan/VnVPlan.pdf index f17261aa..e8d86dbf 100644 Binary files a/docs/VnVPlan/VnVPlan.pdf and b/docs/VnVPlan/VnVPlan.pdf differ diff --git a/docs/VnVPlan/VnVPlan.tex b/docs/VnVPlan/VnVPlan.tex index a3cd05c7..128c8883 100644 --- a/docs/VnVPlan/VnVPlan.tex +++ b/docs/VnVPlan/VnVPlan.tex @@ -49,12 +49,22 @@ \section*{Revision History} -\begin{tabularx}{\textwidth}{p{4cm}p{2cm}X} - \toprule {\bf Date} & {\bf Version} & {\bf Notes}\\ +\begin{tabularx}{\textwidth}{p{4cm}p{4cm}X} + \toprule {\bf Date} & {\bf Name} & {\bf Notes}\\ \midrule - November 4th, 2024 & 0.0 & Created initial revision of VnV Plan\\ - March 10th, 2025 & 0.1 & Revised Functional and Non-Functional Requirements\\ - + November 4th, 2024 & All & Created initial revision of VnV Plan\\ +January 3rd, 2025 & Sevhena Walker & Modified template for static tests, clarified test-SRT-3\\ + March 10th, 2025 & Nivetha Kuruparan, Sevhena Walker & Revised Functional and Non-Functional Requirements\\ + April 1st, 2025 & Sevhena Walker & Modified Implementation Verification plan: refined unit testing tools.\\ + April 1st, 2025 & Sevhena Walker & Updated Automated testing and Verification Tools to include plugin tools.\\ + April 1st, 2025 & Sevhena Walker & Updated 4.2 and 4.5.2 to reflect the new tests.\\ + April 1st, 2025 & Sevhena Walker & Fixed some links. Fixed table formatting and some grammar.\\ + April 3rd, 2025 & Nivetha Kuruparan & Major Revisions for General Information Section\\ + April 3rd, 2025 & Nivetha Kuruparan & Major Revisions for Plan Section\\ + April 3rd, 2025 & Nivetha Kuruparan & Major Revisions for Test Functional Requirements Section\\ + April 3rd, 2025 & Nivetha Kuruparan & Major Revisions for Test Non-Functional Requirements Section\\ + April 3rd, 2025 & Nivetha Kuruparan & Heavily Revised VSCode Plugin Unit Tests\\ + April 3rd, 2025 & Nivetha Kuruparan & Fixed Links\\ \bottomrule \end{tabularx} @@ -109,7 +119,7 @@ \section*{Revision History} \pagenumbering{arabic} -This document outlines the process and methods to ensure that the +\noindent This document outlines the process and methods to ensure that the software meets its requirements and functions as intended. This document provides a structured approach to evaluating the product, incorporating both verification (to confirm that the software is @@ -119,62 +129,30 @@ \section*{Revision History} risks, and ensure compliance with both functional and non-functional requirements.\\ -The following sections will go over the approach for verification and +\noindent The following sections will go over the approach for verification and validation, including the team structure, verification strategies at -various stages and tools to be employed. Furthermore, a detailed list +various stages, and tools to be employed. Furthermore, a detailed list of system and unit tests are also included in this document. \section{General Information} \subsection{Summary} -The software being tested is called EcoOptimizer. EcoOptimizer is a -python refactoring library that focuses on optimizing code in a way -that reduces its energy consumption. The system will be capable to -analyze python code in order to spot inefficiencies (code smells) -within, measuring the energy efficiency of the inputted code and, of -course, apply appropriate refactorings that preserve the initial -function of the source code. \\ - -Furthermore, peripheral tools such as a Visual Studio Code (VS Code) -extension and GitHub Action are also to be tested. The extension will -integrate the library with Visual Studio Code for a more efficient -development process and the GitHub Action will allow a proper -integration of the library into continuous integration (CI) workflows. +The software being tested is called EcoOptimizer. EcoOptimizer is a Visual Studio Code (VS Code) extension designed to help developers identify and refactor energy-inefficient code in Python. It uses a Python package as its backend to detect code smells and estimate the carbon emissions that can be saved by applying the suggested refactorings. Users are given the option to accept or reject these refactorings directly within the editor. EcoOptimizer aims to promote energy-aware software development by making it easier to write efficient code without altering the original functionality. \subsection{Objectives} -The primary objective of this project is to build confidence in the -\textbf{correctness} and \textbf{energy efficiency} of the -refactoring library, ensuring that it performs as expected in -improving code efficiency while maintaining functionality. Usability -is also emphasized, particularly in the user interfaces provided -through the \textbf{VS Code extension} and \textbf{GitHub Action} -integrations, as ease of use is critical for adoption by software -developers. These qualities—correctness, energy efficiency, and -usability—are central to the project’s success, as they directly -impact user experience, performance, and the sustainable benefits of the tool.\\ - -Certain objectives are intentionally left out-of-scope due to -resource constraints. We will not independently verify external -libraries or dependencies; instead, we assume they have been -validated by their respective development teams. +The primary objective of this project is to build confidence in the correctness and energy efficiency of the EcoOptimizer system, ensuring it reliably identifies and refactors energy-inefficient Python code without altering its original behaviour. Usability is a major focus—particularly within the VS Code extension—as the tool is designed to suggest improvements and keep developers informed while they write code. A core feature of EcoOptimizer is giving users the autonomy to accept or reject refactorings, empowering them to make informed decisions about the changes being applied to their code. These qualities—correctness, energy efficiency, user control, and usability—are essential to the project’s success, as they shape the overall user experience, practical adoption, and sustainable benefits of the tool.\\ + +\noindent Certain objectives have been intentionally excluded due to resource constraints. For instance, we will not independently verify third-party libraries or dependencies, and will assume that they are adequately tested and maintained by their original developers. \subsection{Challenge Level and Extras} -Our project, set at a \textbf{general} challenge level, includes two -additional focuses: \textbf{user documentation} and \textbf{usability -testing}. The user documentation aims to provide clear, accessible -guidance for developers, making it easy to understand the tool’s -setup, functionality, and integration into existing workflows. -Usability testing will ensure that the tool is intuitive and meets -user needs effectively, offering insights to refine the user -interface and optimize interactions with its features. +Our project, set at a general challenge level, includes two additional focuses: the creation of a user manual and the completion of a usability report. The user manual provides clear and accessible instructions for developers, covering installation, setup, and usage of both the VS Code extension and the underlying Python package. It is designed to help users quickly integrate the tool into their development workflow. The usability report summarizes findings from a structured usability testing session, offering valuable insights into how effectively the tool meets user needs. These findings are used to refine the user interface and improve the overall user experience, ensuring the tool is both intuitive and practical for real-world use. \subsection{Relevant Documentation} -The Verification and Validation (VnV) plan relies on three key -documents to guide testing and assessment: +The Verification and Validation (VnV) plan relies on three key documents to guide testing and assessment: \begin{itemize} \item[] \textbf{Software Requirements Specification (\SRS)~\cite{SRS}:} The foundation for the VnV plan, as it @@ -194,7 +172,7 @@ \subsection{Relevant Documentation} dependencies within the system. \end{itemize} -\section{Plan} +\newpage\section{Plan} The following section outlines the comprehensive Verification and Validation (VnV) strategy, detailing the team structure, specific @@ -204,8 +182,7 @@ \section{Plan} \subsection{Verification and Validation Team} -The Verification and Validation (VnV) Team for the Source Code -Optimizer project consists of the following members and their specific roles: +The Verification and Validation (VnV) Team for the EcoOptimizer project consists of the following members and their specific roles: \begin{itemize} \item \textbf{Sevhena Walker}: Lead Tester. Oversees and @@ -222,346 +199,208 @@ \subsection{Verification and Validation Team} \item \textbf{Nivetha Kuruparan}: Non-Functional Requirements Tester. Ensures that the final product meets user expectations regarding user experience and interface intuitiveness. - \item \textbf{Istvan David} (supervisor): Supervises the overall + \item \textbf{Istvan David} (Supervisor): Supervises the overall VnV process, providing feedback and guidance based on industry standards and practices. \end{itemize} \subsection{SRS Verification Plan} -\textbf{Function \& Non-Functional Requirements:} -\begin{itemize} - \item A comprehensive test suite that covers all requirements - specified in the SRS will be created. - \item Each requirement will be mapped to specific test cases to - ensure maximum coverage. - \item Automated and manual testing will be conducted to verify that - the implemented system meets each functional requirement. - \item Usability testing with representative users will be carried - out to validate user experience requirements and other - non-functional requirements. - \item Performance tests will be conducted to verify that the system - meets specified performance requirements. -\end{itemize} +The verification of the Software Requirements Specification will be conducted through a structured four-phase approach encompassing requirements validation, stakeholder review, user acceptance testing, and continuous verification. -\textbf{Traceability Matrix:} -\begin{itemize} - \item We will create a requirements traceability matrix that links - each SRS requirement to its corresponding implementation, test - cases, and test results. - \item This matrix will help identify any requirements that may have - been overlooked during development. -\end{itemize} +\subsubsection{Requirements Validation} +The validation process will begin with comprehensive test coverage of all functional and non-functional requirements. A suite of test cases will be developed, employing automated testing frameworks such as PyTest~\cite{pytest} for functional requirements while reserving manual testing for edge cases and complex scenarios. To ensure complete traceability, we will maintain a matrix that explicitly links each requirement to its corresponding implementation, test cases, and test results. -\textbf{Supervisor Review:} -\begin{itemize} - \item After the implementation of the system, we will conduct a - formal review session with key stakeholders such as our project - supervisor, Dr. Istvan David. - \item The stakeholders will be asked to verify that each - requirement in the SRS is mapped out to specific expectations of - the project. - \item Prior to meeting, we will provide a summary of key - requirements and design decisions and prepare a list specific - questions or areas where we seek guidance. - \item During the meeting, we will present an overview of the SRS - using tables and other visual aids. We will conduct a walk - through of critical section. Finally, we will discuss any - potential risks or challenges identified. -\end{itemize} +\subsubsection{Stakeholder Review} +A formal review session will be conducted with our project supervisor, Dr. Istvan David, following a structured agenda. Prior to the meeting, we will prepare and distribute a package containing: (1) a summary of key requirements and design decisions, (2) visual aids including requirement diagrams and tables, and (3) specific questions regarding high-risk areas. During the session, we will conduct a detailed walkthrough of critical system components, particularly focusing on the energy measurement module and refactoring logic. -\textbf{User Acceptance Testing (UAT):} -\begin{itemize} - \item We will involve potential end-users in testing the system to - ensure it meets real-world usage scenarios. - \item Feedback from UAT will be used to identify any discrepancies - between the SRS and user expectations. -\end{itemize} +\subsubsection{User Acceptance Testing} +The verification process will include rigorous user acceptance testing involving 5--10 representative developers from our target user base. These tests will validate both the usability requirements (ensuring tasks can be completed within the \textbf{MAX\_TASK\_CLICKS} threshold of 4) and the effectiveness of energy metrics presentation (as specified in \textbf{FR6}). Feedback from these sessions will be systematically analyzed to identify any discrepancies between the SRS and actual user expectations. -\textbf{Continuous Verification:} -\begin{itemize} - \item Throughout the development process, we will regularly review - and update the SRS to ensure it remains aligned with the evolving system. - \item Any changes to requirements will be documented and their - impact on the system assessed. +\subsubsection{Continuous Verification} +To maintain alignment between the SRS and evolving system implementation, we will conduct biweekly review sessions. These sessions will serve to: +\begin{itemize}[nosep] + \item Assess the impact of any requirement changes + \item Update documentation to reflect system modifications + \item Verify that all changes maintain consistency with the original specifications \end{itemize} -\textbf{\textit{\\Checklist for SRS Verification Plan}} +\begin{table}[H] +\centering +\caption{SRS Verification Checklist} +\begin{tabular}{|p{0.35\textwidth}|p{0.60\textwidth}|} +\hline +\textbf{Phase} & \textbf{Verification Activities} \\ \hline +Requirements Validation & \begin{itemize} - \item[$\square$] Create comprehensive test suite covering all SRS requirements - \item[$\square$] Map each requirement to specific test cases - \item[$\square$] Conduct automated testing for functional requirements - \item[$\square$] Perform manual testing for functional requirements - \item[$\square$] Carry out usability testing with representative users - \item[$\square$] Conduct performance tests to verify system meets requirements - \item[$\square$] Create requirements traceability matrix - \item[$\square$] Link each SRS requirement to implementation in - traceability matrix - \item[$\square$] Link each SRS requirement to test cases in - traceability matrix - \item[$\square$] Link each SRS requirement to test results in - traceability matrix - \item[$\square$] Schedule formal review session with project supervisor - \item[$\square$] Prepare summary of key requirements and design - decisions for supervisor review - \item[$\square$] Prepare list of specific questions for supervisor review - \item[$\square$] Create visual aids for SRS overview presentation - \item[$\square$] Conduct walkthrough of critical SRS sections during review - \item[$\square$] Discuss potential risks and challenges with supervisor - \item[$\square$] Organize User Acceptance Testing (UAT) with - potential end-users - \item[$\square$] Collect and analyze UAT feedback - \item[$\square$] Identify discrepancies between SRS and user - expectations from UAT - \item[$\square$] Establish process for regular SRS review and updates - \item[$\square$] Document any changes to requirements - \item[$\square$] Assess impact of requirement changes on the system -\end{itemize} + \item[$\square$] Develop comprehensive test suite + \item[$\square$] Conduct automated and manual testing + \item[$\square$] Maintain traceability matrix +\end{itemize} \\ \hline +Stakeholder Review & +\begin{itemize} + \item[$\square$] Prepare review materials + \item[$\square$] Conduct formal walkthrough + \item[$\square$] Address high-risk concerns +\end{itemize} \\ \hline +User Acceptance Testing & +\begin{itemize} + \item[$\square$] Recruit representative users + \item[$\square$] Validate usability metrics + \item[$\square$] Analyze feedback +\end{itemize} \\ \hline +Continuous Verification & +\begin{itemize} + \item[$\square$] Conduct biweekly reviews + \item[$\square$] Maintain change documentation +\end{itemize} \\ \hline +\end{tabular} +\end{table} \subsection{Design Verification Plan} -\textbf{Peer Review Plan:} -\begin{itemize} - \item Each team member along with other classmates will thoroughly - review the entire Design Document. - \item A checklist-based approach will be used to ensure all key - elements are covered. - \item Feedback will be collected and discussed in a dedicated team meeting. -\end{itemize} +The design verification will focus exclusively on validating the system architecture and implementation specifications through structured peer and supervisor reviews. Classmates will conduct checklist-driven evaluations of the design document, paying particular attention to the refactoring options and the VS Code extension's interface design. Feedback will be consolidated in GitHub Issues and addressed in design refinement meetings.\\ + +\noindent A formal review with Dr. Istvan David will verify three critical aspects: (1) the energy measurement module's integration, (2) compliance with VS Code extension best practices, and (3) the fault-tolerance of the refactoring pipeline. We will prepare UML sequence diagrams and component specifications to facilitate this technical discussion, documenting all action items in our project board with clear resolution deadlines. + +\begin{table}[H] +\centering +\caption{Design Verification Checklist} +\begin{tabular}{|p{0.25\textwidth}|p{0.7\textwidth}|} +\hline +\textbf{Focus Area} & \textbf{Verification Tasks} \\ \hline +Core Architecture & \begin{itemize} +\item[$\square$] Refactoring engine modularity confirmed +\end{itemize} \\ \hline +IDE Integration & \begin{itemize} +\item[$\square$] VS Code API usage reviewed +\item[$\square$] UI/UX patterns verified +\end{itemize} \\ \hline +Data Integrity & \begin{itemize} +\item[$\square$] Energy measurement accuracy checked +\item[$\square$] Code transformation safety ensured +\end{itemize} \\ \hline +\end{tabular} +\end{table} -\textbf{Supervisor Review:} -\begin{itemize} - \item A structured review meeting will be scheduled with our - project supervisor, Dr. Istvan David. - \item We will present an overview of the design using visual aids - (e.g., diagrams, tables). - \item We will conduct a walkthrough of critical sections. - \item We will use our project's issue tracker to document and - follow up on any action items or changes resulting from this review. -\end{itemize} +\subsection{Verification and Validation Plan Verification Plan} -\begin{itemize} - \item[$\square$] All functional requirements are mapped to specific - design elements - \item[$\square$] Each functional requirement is fully addressed by the design - \item[$\square$] No functional requirements are overlooked or - partially implemented - \item[$\square$] Performance requirements are met by the design - \item[$\square$] Scalability considerations are incorporated - \item[$\square$] Reliability and availability requirements are satisfied - \item[$\square$] Usability requirements are reflected in the user - interface design - \item[$\square$] High-level architecture is clearly defined - \item[$\square$] Architectural decisions are justified with rationale - \item[$\square$] Architecture aligns with project constraints and goals - \item[$\square$] All major components are identified and described - \item[$\square$] Interactions between components are clearly specified - \item[$\square$] Component responsibilities are well-defined - \item[$\square$] Appropriate data structures are chosen for each task - \item[$\square$] Efficient algorithms are selected for critical operations - \item[$\square$] Rationale for data structure and algorithm choices - is provided - \item[$\square$] UI design is consistent with usability requirements - \item[$\square$] User flow is logical and efficient - \item[$\square$] Accessibility considerations are incorporated - \item[$\square$] All external interfaces are properly specified - \item[$\square$] Interface protocols and data formats are defined - \item[$\square$] Error handling for external interfaces is addressed - \item[$\square$] Comprehensive error handling strategy is in place - \item[$\square$] Exception scenarios are identified and managed - \item[$\square$] Error messages are clear and actionable - \item[$\square$] Authentication and authorization mechanisms are described - \item[$\square$] Data encryption methods are specified where necessary - \item[$\square$] Security best practices are followed in the design - \item[$\square$] Design allows for future expansion and feature additions - \item[$\square$] Code modularity and reusability are considered - \item[$\square$] Documentation standards are established for maintainability - \item[$\square$] Performance bottlenecks are identified and addressed - \item[$\square$] Resource utilization is optimized - \item[$\square$] Performance testing strategies are outlined - \item[$\square$] Design adheres to established coding standards - \item[$\square$] Industry best practices are followed - \item[$\square$] Design patterns are appropriately applied - \item[$\square$] All major design decisions are justified - \item[$\square$] Trade-offs are explained with pros and cons - \item[$\square$] Alternative approaches considered are documented - \item[$\square$] Documents is clear, concise, and free of ambiguities - \item[$\square$] Documents follows a logical structure -\end{itemize} +The Verification and Validation Plan for EcoOptimizer will be verified through peer reviews and targeted testing strategies. Team members and classmates will evaluate the plan's completeness using a structured checklist, focusing specifically on coverage of Python refactoring scenarios and energy efficiency measurements. Feedback will be tracked through GitHub Issues and incorporated in weekly team meetings.\\ + +\noindent For test effectiveness validation, we will employ mutation testing by introducing faults in sample code containing energy-inefficient patterns. This will quantitatively verify our test cases' ability to detect anomalies. The verification process will measure three key metrics: requirement coverage percentage, test case effectiveness, and issue resolution rate. + +\begin{table}[H] +\centering +\caption{V\&V Plan Verification Checklist} +\begin{tabular}{|p{0.25\textwidth}|p{0.7\textwidth}|} +\hline +\textbf{Criteria} & \textbf{Verification Tasks} \\ \hline +Coverage & \begin{itemize} +\item[$\square$] All refactoring cases included +\item[$\square$] Energy metrics validation specified +\end{itemize} \\ \hline +Methodology & \begin{itemize} +\item[$\square$] Appropriate test levels defined +\item[$\square$] Fault detection strategy in place +\end{itemize} \\ \hline +Process & \begin{itemize} +\item[$\square$] Feedback mechanism established +\item[$\square$] Tracking system implemented +\end{itemize} \\ \hline +\end{tabular} +\end{table} + +\noindent An iterative refinement process will be implemented, where verification findings are documented as GitHub issues and addressed in sprint reviews. This ensures the V\&V plan remains aligned with both the technical requirements of Python code optimization and the project's timeline constraints. Progress will be measured against predefined success metrics, including test coverage percentages and mutation detection rates. -\subsection{Verification and Validation Plan Verification Plan} -The Verification and Validation (V\&V) Plan for the Source Code -Optimizer project serves as a critical document that requires a -thorough examination to confirm its validity and effectiveness. To -achieve this, the following strategies will be implemented: - -\begin{enumerate} - \item \textbf{Peer Review}: Team members and peers will conduct a - detailed review of the V\&V plan. This process aims to uncover - any gaps or areas that could benefit from enhancement, leveraging - the collective insights of the group to strengthen the overall plan. - - \item \textbf{Fault Injection Testing}: We will utilize mutation - testing to assess the capability of our test cases to identify - intentionally introduced faults. By generating variations of the - original code, we can evaluate whether our testing strategies are - robust enough to catch these discrepancies, hence enhancing the - reliability of our verification process. - - \item \textbf{Feedback Loop Integration}: Continuous feedback from - review sessions and testing activities will be systematically - integrated to refine the V\&V plan. This ongoing process ensures - the plan evolves based on insights gained from practical testing - and peer input. -\end{enumerate} +\subsection{Implementation Verification Plan} -\noindent To comprehensively verify the V\&V plan, we will utilize -the following checklist: +The implementation verification will ensure EcoOptimizer's codebase strictly adheres to the SRS specifications through rigorous testing protocols. Unit testing will validate core functionality using Pytest~\cite{pytest} for Python components (refactoring engine, energy measurement) and Jest~\cite{jest} for the VS Code extension (UI integration). Test cases will specifically target energy-efficient transformations identified in \textbf{FR2-FR4}.\\ -\begin{itemize} - \item[$\square$] Does the V\&V plan include all necessary aspects - of software verification and validation? - \item[$\square$] Are the roles and responsibilities clearly - outlined within the V\&V framework? - \item[$\square$] Is there a diversity of testing methodologies - included (e.g., unit testing, integration testing, system testing)? - \item[$\square$] Does the plan have a clear process for - incorporating feedback and gaining continuous improvement? - \item[$\square$] Are success criteria established for each phase of testing? - \item[$\square$] Is mutation testing considered to evaluate the - effectiveness of the test cases? - \item[$\square$] Are mechanisms in place to monitor and address any - identified issues during the V\&V process? - \item[$\square$] Does the V\&V plan align with the project - timeline, available resources, and other constraints? +\noindent Static analysis will enforce code quality using Python linters to verify compliance with PEP 8~\cite{pep8} standards (per \textbf{CR-SCR1}) and detect security vulnerabilities. Weekly peer code reviews will examine implementation quality, focusing on: +\begin{itemize}[nosep] +\item Algorithm efficiency for energy optimization +\item Correct handling of Python version-specific features \textbf{(MS-AD3}) +\item VS Code extension usability (\textbf{UHR-EOU1})\\ \end{itemize} -\subsection{Implementation Verification Plan} +\noindent Performance testing will validate: +\begin{itemize}[nosep] +\item Refactoring speed against \textbf{PR-SL1} thresholds +\item Energy measurement accuracy (\textbf{FR6}) +\item Large codebase handling (\textbf{PR-CR1}) +\end{itemize} + +\begin{table}[h] +\centering +\caption{Implementation Verification Checklist} +\begin{tabular}{|p{0.25\textwidth}|p{0.7\textwidth}|} +\hline +\textbf{Category} & \textbf{Verification Tasks} \\ \hline +Functionality & \begin{itemize} +\item[$\square$] Unit tests for all refactoring methods +\item[$\square$] Energy measurement validation +\end{itemize} \\ \hline +Quality & \begin{itemize} +\item[$\square$] Static analysis completed +\item[$\square$] Code reviews conducted +\end{itemize} \\ \hline +Performance & \begin{itemize} +\item[$\square$] Processing time benchmarks +\item[$\square$] Large codebase tests +\end{itemize} \\ \hline +\end{tabular} +\end{table} + +\subsection{Automated Testing and Verification Tools} -The Implementation Verification Plan for the Source Code Optimizer -project aims to ensure that the software implementation adheres to -the requirements and design specifications defined in the SRS. Key -components of this plan include: +\textbf{Unit Testing Framework:} The project uses standard testing tools for each part of the system: \texttt{Pytest}~\cite{pytest} for the Python backend and \texttt{Jest}~\cite{jest} for the TypeScript frontend. These tools were chosen because they are widely used in their respective ecosystems, well-documented, and compatible with the project's CI/CD pipeline. Together they provide test coverage for both backend and frontend components.\\ + +\noindent\textbf{Code Coverage Tools and Plan for Summary:} The codebase will be analyzed to determine the percentage of code executed during tests using language-specific tools: \begin{itemize} - \item \textbf{Unit Testing}: A comprehensive suite of unit tests - will be established to validate the functionality of individual - components within the optimizer. These tests will specifically - focus on the effectiveness of the code refactoring methods - employed by the optimizer, utilizing - \texttt{pytest}~\cite{pytest} for writing and executing these tests. - - \item \textbf{Static Code Analysis}: To maintain high code quality, - static analysis tools will be employed. These tools will help - identify potential bugs, security vulnerabilities, and adherence - to coding standards in the Python codebase, ensuring that the - optimizer is both efficient and secure. - - \item \textbf{Code Walkthroughs and Reviews}: The development team - will hold regular code reviews and walkthrough sessions to - collaboratively evaluate the implementation of the source code - optimizer. These sessions will focus on code quality, - readability, and compliance with the project’s design patterns. - Additionally, the final presentation will provide an opportunity - for a thorough code walkthrough, allowing peers to contribute - feedback on usability and functionality. - - \item \textbf{Continuous Integration}: The project will implement - continuous integration practices using tools like GitHub Actions. - This approach will automate the build and testing processes, - allowing the team to verify that each change to the optimizer - codebase meets the established quality criteria and integrates - smoothly with the overall system. - - \item \textbf{Performance Testing}: The performance of the source - code optimizer will be assessed to simulate various usage - scenarios. This testing will focus on evaluating how effectively - the optimizer processes large codebases and applies refactorings, - ensuring that the tool operates efficiently under different workloads. + \item \textbf{Python:} \texttt{pytest-cov}~\cite{pytest-cov} provides granular-level coverage including branch, line, and path analysis. Its seamless integration with \texttt{Pytest}~\cite{pytest} ensures coverage metrics are generated during normal test execution. + + \item \textbf{TypeScript:} \texttt{Jest}'s~\cite{jest} built-in coverage functionality will track statement, branch, and function coverage for the VS Code extension, with configuration matching the Python tool's output format. \end{itemize} -\subsection{Automated Testing and Verification Tools} - -\textbf{Unit Testing Framework:} Pytest is chosen as the main -framework for unit testing due to its -\begin{inparaenum}[(i)] -\item scalability -\item integration with other tools - (\texttt{pytest-cov}~\cite{pytest-cov} for code coverage) -\item extensive support for parameterized tests. -\end{inparaenum} These features make it easy to test the codebase as -it grows, adapting to changes throughout the project's development.\\ - -\noindent\textbf{Profiling Tool:} The codebase will be evaluated -based on results from both time and memory profiling to optimize -computational speed and resource usage. For time profiling (recording - the number of function calls, time spent in each function, and its -descendants), \texttt{cProfile} will be used, as it is included -within Python, making it a convenient choice for profiling. For -memory profiling, \texttt{memory\_profiler}~\cite{memory_profiler} -will be used, as it is easy to install and includes built-in support -for visual display of output.\\ - -\noindent\textbf{Static Analyzer:} The codebase will be statically -analyzed using \texttt{ruff}~\cite{ruff}, as it provides fast -linting, built-in rule enforcement, and integrates well with modern -Python projects. \texttt{ruff}~\cite{ruff} enforces both linting and -formatting rules, reducing the need for multiple tools.\\ - -\noindent\textbf{Code Coverage Tools and Plan for Summary:} The -codebase will be analyzed to determine the percentage of code -executed during tests. For granular-level coverage, -\texttt{pytest-cov}~\cite{pytest-cov} will be used, as it supports -branch, line, and path coverage. Additionally, -\texttt{pytest-cov}~\cite{pytest-cov} integrates seamlessly with -\texttt{pytest}~\cite{pytest}, ensuring that test coverage results -are generated alongside test execution.\\ - -Initially, the aim is to achieve a 40\% coverage and gradually -increment the level over time. Weekly reports generated from -\texttt{pytest-cov}~\cite{pytest-cov} will be used to track coverage -trends and set goals accordingly to address any gaps in testing in -the growing codebase.\\ +\noindent Initially, the aim is to achieve 40\% coverage across both codebases, gradually incrementing the level over time. Weekly reports generated from both tools will be combined to track coverage trends, identify testing gaps, and set improvement goals as the project evolves. The unified coverage data will ensure consistent quality standards are maintained throughout the full stack.\\ \noindent\textbf{Linters and Formatters:} To enforce the official -Python PEP 8 style guide and maintain code quality, the team will use -\texttt{ruff}~\cite{ruff} for Python code and +Python PEP 8~\cite{pep8} style guide and maintain code quality, the team will use +\texttt{Ruff}~\cite{ruff} for Python code and \texttt{eslint}~\cite{eslint} paired with \texttt{Prettier}~\cite{prettier} for the TypeScript extension.\\ \noindent\textbf{Testing Strategy for the VSCode Extension:} The -TypeScript extension will be tested using \texttt{jest}~\cite{jest}. +TypeScript extension will be tested using \texttt{Jest}~\cite{jest}. Automated tests will verify interactions between the extension and -the editor, reducing regressions during development.\\ - -\noindent\textbf{CI Plan:} As mentioned in the Development Plan, -GitHub Actions will integrate the above tools within the CI pipeline. -GitHub Actions will be configured to run unit tests written in -\texttt{pytest}, perform static analysis using -\texttt{ruff}~\cite{ruff}, and execute -\texttt{pytest-cov}~\cite{pytest-cov} for test coverage. For the -TypeScript extension, a pre-commit will run -\texttt{eslint}~\cite{eslint} and \texttt{Prettier}~\cite{prettier}, -and automated tests will be executed as a GitHub Action using -\texttt{jest}~\cite{jest}. Through automated testing, any errors, -code style violations, and regressions will be promptly identified.\\ +the editor, reducing regressions during development. \subsection{Software Validation Plan} +EcoOptimizer will be validated through: \begin{itemize} - \item One or more open source Python code bases will be used to - test the tool on. Based on its performance in functional and - non-functional tests outlined in further sections of the - document, the software can be validated against defined requirements. - \item In addition to this, the team will reach out to Dr David as - well as a group of volunteer Python developers to perform - usability testing on the IDE plugin workflow as well as the CI/CD workflow. - \item The team will conduct a comprehensive review of the - requirements from Dr David through the Rev 0 Demo. + \item \textbf{Functional Testing}: Evaluation against open-source Python projects to verify: + \begin{itemize} + \item Energy efficiency improvements (\textbf{FR3}, \textbf{FR6}) + \item Refactoring accuracy (\textbf{FR4}) + \end{itemize} + + \item \textbf{Usability Testing}: Sessions with Dr. David and Python developers assessing: + \begin{itemize} + \item VS Code extension workflow (\textbf{UHR-EOU1-2}) + \item Developer experience metrics + \end{itemize} + + \item \textbf{Formal Review}: Rev 0 demo with Dr. David to validate: + \begin{itemize} + \item SRS requirement implementation + \item System behavior against specifications + \end{itemize} \end{itemize} -\section{System Tests} +\newpage\section{System Tests} This section outlines the tests for verifying both functional and nonfunctional requirements of the software, ensuring it meets user @@ -587,100 +426,88 @@ \subsubsection{Code Input Acceptance Tests} \noindent This section covers the tests for ensuring the system correctly accepts Python source code files, detects errors in invalid files, -and provides suitable feedback (FR 1). +and provides suitable feedback (\textbf{FR1}). \begin{enumerate}[label={\bf \textcolor{Maroon}{test-FR-IA-\arabic*}}, wide=0pt, font=\itshape] \item \textbf{Valid Python File Acceptance} \\[2mm] - \textbf{Control:} Manual \\ - \textbf{Initial State:} Tool is idle. \\ - \textbf{Input:} A valid Python file (filename.py) with valid - standard syntax. \\ - \textbf{Output:} The system accepts the file without errors.\\[2mm] + \textbf{Control:} Manual \\ + \textbf{Initial State:} Tool is idle within the VS Code workspace. \\ + \textbf{Input:} A valid Python file (filename.py) containing syntactically correct code. \\ + \textbf{Output:} The system accepts the file without errors and displays any detected code smells if present. \\[2mm] \textbf{Test Case Derivation:} Confirming that the system - correctly processes a valid Python file as per FR 1.\\[2mm] - \textbf{How test will be performed:} Feed a syntactically valid - .py file to the tool and observe if it’s accepted without issues. + correctly processes valid Python files in the supported environment, as specified in \textbf{FR1}. \\[2mm] + \textbf{How test will be performed:} Open a syntactically valid `.py` file in VS Code with the extension enabled. Verify that the tool processes the file and optionally displays code smells if any are present. \item \textbf{Feedback for Python File with Bad Syntax} \\[2mm] - \textbf{Control:} Manual \\ - \textbf{Initial State:} Tool is idle. \\ - \textbf{Input:} A .py file (badSyntax.py) containing deliberate - syntax errors that render the file unrunnable. \\ - \textbf{Output:} The system rejects the file and provides an - error message detailing the syntax issue. \\[2mm] - \textbf{Test Case Derivation:} Verifies the tool’s handling of - syntactically invalid Python files to ensure user awareness of - the syntax issue, meeting FR 1. \\[2mm] - \textbf{How test will be performed:} Feed a .py file with syntax - errors to the tool and check that the system identifies it as - invalid and produces an appropriate error message. + \textbf{Control:} Manual \\ + \textbf{Initial State:} Tool is idle within the VS Code workspace. \\ + \textbf{Input:} A `.py` file (badSyntax.py) containing deliberate syntax errors that prevent parsing. \\ + \textbf{Output:} The system detects the issue, halts further analysis, and displays an appropriate error message within the editor. \\[2mm] + \textbf{Test Case Derivation:} Ensures graceful handling of invalid Python syntax and appropriate user feedback, satisfying \textbf{FR1}. \\[2mm] + \textbf{How test will be performed:} Load a Python file with syntax errors in VS Code, then observe whether the extension flags the syntax issue and stops further processing. \item \textbf{Feedback for Non-Python File}\\[2mm] - \textbf{Control:} Manual \\ - \textbf{Initial State:} Tool is idle.\\ - \textbf{Input:} A non-Python file (document.txt) or a file with - an incorrect extension (script.js).\\ - \textbf{Output:} The system rejects the file and provides an - error message indicating the invalid file format.\\[2mm] - \textbf{Test Case Derivation:} Ensures the tool detects - unsupported file types and provides feedback, satisfying FR 1.\\[2mm] - \textbf{How test will be performed:} Attempt to load a .txt or - other non-Python file, and verify that the system rejects it with - a message indicating an invalid file type. - - \noindent - \colorrule - - \subsubsection{Code Smell Detection Tests and Refactoring - Suggestion (RS) Tests} \label{4.1.2} - \colorrule - - \medskip - - \noindent - This area includes tests to verify the detection and refactoring - of specified code - smells that impact energy efficiency (FR 2). These tests will be - done through unit testing. + \textbf{Control:} Manual \\ + \textbf{Initial State:} Tool is idle within the VS Code workspace. \\ + \textbf{Input:} A non-Python file (e.g., `notes.txt` or `script.js`). \\ + \textbf{Output:} The system ignores the file or displays a message indicating that the file type is unsupported. \\[2mm] + \textbf{Test Case Derivation:} Validates that the system filters non-Python files, consistent with the requirement that it must exclusively process `.py` files (\textbf{FR1}). \\[2mm] + \textbf{How test will be performed:} Attempt to open a non-Python file in VS Code and check that the extension does not attempt analysis or refactoring and provides clear messaging if applicable. \end{enumerate} -\noindent -\colorrule +\noindent\colorrule -\subsubsection{Output Validation Tests} + +\subsubsection{Code Smell Detection Tests and Refactoring +Suggestion (RS) Tests} \label{4.1.2} \colorrule \medskip \noindent -The following tests are designed to validate that the functionality -of the original Python code remains intact after refactoring. Each -test ensures that the refactored code passes the same test suite as -the original code, confirming compliance with functional requirement FR 3. +This area includes tests to verify the detection and refactoring +of specified code smells that impact energy efficiency. These tests will be +done through unit testing. \begin{enumerate}[label={\bf - \textcolor{Maroon}{test-FR-OV-\arabic*}}, wide=0pt, font=\itshape] - \label{itm:FR-OV-1} - \item \textbf{Verification of Valid Python Output}\\[2mm] - \textbf{Control:} Manual \\ - \textbf{Initial State:} Tool has processed a file with detected - code smells.\\ - \textbf{Input:} Output refactored Python code.\\ - \textbf{Output:} Refactored code is syntactically correct and - Python-compliant.\\[2mm] - \textbf{Test Case Derivation:} Ensures refactored code remains - valid and usable, satisfying FR 6.\\[2mm] - \textbf{How test will be performed:} Run a linter on the output - code and verify it passes without syntax errors. +\textcolor{Maroon}{test-FR-IA-\arabic*}}, wide=0pt, font=\itshape] +\item \textbf{Successful Refactoring Execution} \\[2mm] +\textbf{Control:} Automated \\ +\textbf{Initial State:} Tool is idle in the VS Code environment. \\ +\textbf{Input:} A valid Python file with a detectable code smell. \\ +\textbf{Output:} The system applies the appropriate refactoring and updates the code view. \\[2mm] +\textbf{Test Case Derivation:} Ensures the tool correctly identifies a smell (e.g., LEC001), chooses an applicable refactoring, and applies it successfully, per \textbf{FR2} and \textbf{FR3}. \\[2mm] +\textbf{How test will be performed:} Provide a valid Python file containing a known smell, trigger refactoring via the VS Code interface, and confirm the output includes refactored code as expected. + +\item \textbf{No Available Refactorer Handling} \\[2mm] +\textbf{Control:} Automated \\ +\textbf{Initial State:} Tool is idle. \\ +\textbf{Input:} A valid Python file containing a code smell that does not yet have a supported refactorer. \\ +\textbf{Output:} The system does not apply changes and logs or displays an informative message. \\[2mm] +\textbf{Test Case Derivation:} Verifies that unsupported code smells are gracefully handled without errors, per \textbf{FR2}. \\[2mm] +\textbf{How test will be performed:} Provide a valid Python file with an unsupported smell and observe that the system notifies the user without attempting modification. + +\item \textbf{Multiple Refactoring Calls on Same File} \\[2mm] +\textbf{Control:} Automated \\ +\textbf{Initial State:} Tool is idle. \\ +\textbf{Input:} A valid Python file with a detectable code smell, refactored more than once. \\ +\textbf{Output:} The tool processes the file repeatedly and applies changes incrementally. \\[2mm] +\textbf{Test Case Derivation:} Confirms the system can handle repeated invocations and re-apply applicable refactorings, per \textbf{FR3}. \\[2mm] +\textbf{How test will be performed:} Refactor a file containing a supported smell multiple times and verify that each run performs valid operations and results in updated outputs. + +\item \textbf{Handling Empty Modified Files List} \\[2mm] +\textbf{Control:} Automated \\ +\textbf{Initial State:} Tool is idle. \\ +\textbf{Input:} A valid Python file where the code smell is detected, but the refactorer makes no modifications. \\ +\textbf{Output:} The system does not generate output files and notifies the user appropriately. \\[2mm] +\textbf{Test Case Derivation:} Confirms the tool handles no-op refactorers correctly, per \textbf{FR4}. \\[2mm] +\textbf{How test will be performed:} Supply a file where the refactorer returns an unchanged version of the code and verify that no new files are created and that appropriate feedback is displayed or logged. \end{enumerate} -\newpage - -\noindent -\colorrule +\noindent\colorrule \subsubsection{Tests for Reporting Functionality} \colorrule @@ -689,77 +516,46 @@ \subsubsection{Tests for Reporting Functionality} \noindent The reporting functionality of the tool is crucial for providing -users with comprehensive insights into the refactoring process, -including detected code smells, refactorings applied, energy -consumption measurements, and the results of the original test suite. -This section outlines tests that ensure the reporting feature -operates correctly and delivers accurate, well-structured information -as specified in the functional requirements (FR 9). +users with meaningful insights into the energy impact of refactorings +and the smells being addressed. This section outlines tests that +ensure the energy metrics and refactoring summaries are accurately +presented, as required by \textbf{FR6} and \textbf{FR15}. \begin{enumerate}[label={\bf \textcolor{Maroon}{test-FR-RP-\arabic*}}, wide=0pt, font=\itshape] - \item \textbf{A Report With All Components Is Generated}\\[2mm] - \textbf{Control:} Manual - \textbf{Initial State:} The tool has completed refactoring a - Python code file.\\ - \textbf{Input:} The refactoring results, including detected code - smells, applied refactorings, and energy consumption metrics.\\ - \textbf{Output:} A well-structured report is generated, - summarizing the refactoring process.\\[2mm] - \textbf{Test Case Derivation:} This test ensures that the tool - generates a comprehensive report that includes all necessary - information as required by FR 9.\\[2mm] - \textbf{How test will be performed:} After refactoring, the tool - will invoke the report generation feature and a user can validate - that the output meets the structure and content specifications. - - \item \textbf{Validation of Code Smell and Refactoring Data in Report}\\[2mm] - \textbf{Control:} Automatic \\ - \textbf{Initial State:} The tool has identified code smells and - performed refactorings.\\ - \textbf{Input:} The results of the refactoring process.\\ - \textbf{Output:} The generated report accurately lists all - detected code smells and the corresponding refactorings applied.\\[2mm] - \textbf{Test Case Derivation:} This test verifies that the report - includes correct and complete information about code smells and - refactorings, in compliance with FR 9.\\[2mm] - \textbf{How test will be performed:} The tool will compare the - contents of the generated report against the detected code smells - and refactorings to ensure accuracy. - - \item \textbf{Energy Consumption Metrics Included in Report}\\[2mm] - \textbf{Control:} Manual - \textbf{Initial State:} The tool has measured energy consumption - before and after refactoring.\\ - \textbf{Input:} Energy consumption metrics obtained during the - refactoring process.\\ - \textbf{Output:} The report presents a clear comparison of energy - usage before and after the refactorings.\\[2mm] - \textbf{Test Case Derivation:} This test confirms that the - reporting feature effectively communicates energy consumption - improvements, aligning with FR 9.\\[2mm] - \textbf{How test will be performed:} A user will analyze the - energy metrics in the report to ensure they accurately reflect - the measurements taken during the refactoring. - - \item \textbf{Functionality Test Results Included in Report}\\[2mm] - \textbf{Control:} Automatic \\ - \textbf{Initial State:} The original test suite has been executed - against the refactored code.\\ - \textbf{Input:} The outcomes of the test suite execution.\\ - \textbf{Output:} The report summarizes the test results, - indicating which tests passed and failed.\\[2mm] - \textbf{Test Case Derivation:} This test ensures that the - reporting functionality accurately reflects the results of the - test suite as specified in FR 9.\\[2mm] - \textbf{How test will be performed:} The tool will generate the - report and validate that it contains a summary of test results - consistent with the actual test outcomes. + + \item \textbf{Energy Consumption Metrics Displayed Post-Refactoring} \\[2mm] + \textbf{Control:} Manual \\ + \textbf{Initial State:} The tool has measured energy usage before and after refactoring. \\ + \textbf{Input:} Energy data collected for the original and refactored code. \\ + \textbf{Output:} A clear comparison of energy consumption is displayed in the UI. \\[2mm] + \textbf{Test Case Derivation:} Verifies that energy metrics are properly calculated and presented to users, as per \textbf{FR6}. \\[2mm] + \textbf{How test will be performed:} Refactor a file and review the visual or textual display of energy usage before and after, ensuring the values match backend logs. + + \item \textbf{Detected Code Smells and Refactorings Reflected in UI} \\[2mm] + \textbf{Control:} Manual \\ + \textbf{Initial State:} The tool has completed code analysis and refactoring. \\ + \textbf{Input:} Output of the detection and refactoring modules. \\ + \textbf{Output:} The user interface displays the detected code smells and associated refactorings clearly. \\[2mm] + \textbf{Test Case Derivation:} Ensures transparency of changes and supports informed decision-making by the user, in line with \textbf{FR15}. \\[2mm] + \textbf{How test will be performed:} Open a code file with detectable smells, trigger a refactor, and inspect the view displaying the summary of changes and available actions. + \end{enumerate} -\noindent +\noindent\colorrule + +\subsubsection{Visual Studio Code Interactions} \colorrule +\medskip + +\noindent +This section corresponds to features related to the user’s interaction with the Visual Studio Code extension interface, including previewing and toggling smells, customizing the UI, and reviewing code comparisons. These tests verify that the extension enables users to interact with refactorings in an intuitive and informative manner, as outlined in \textbf{FR8}, \textbf{FR9}, \textbf{FR10}, \textbf{FR11}, \textbf{FR12}, \textbf{FR13}, \textbf{FR14}, \textbf{FR15}, \textbf{FR16}, and \textbf{FR17}.\\ + +\noindent These features are primarily tested through automated unit tests integrated in the extension codebase. For implementation and test details, please refer to the unit testing suite. + +\noindent\colorrule + \subsubsection{Documentation Availability Tests} \colorrule @@ -767,7 +563,7 @@ \subsubsection{Documentation Availability Tests} \noindent The following test is designed to ensure the availability of -documentation as per FR 10. +documentation as per \textbf{FR 7} and \textbf{FR 5}. \begin{enumerate}[label={\bf \textcolor{Maroon}{test-FR-DA-\arabic*}}, wide=0pt, font=\itshape] @@ -776,538 +572,313 @@ \subsubsection{Documentation Availability Tests} \textbf{Initial State:} The system may or may not be installed.\\ \textbf{Input:} User attempts to access the documentation.\\ \textbf{Output:} The documentation is available and covers - installation, usage, and troubleshooting.\\[2mm] + installation, usage (\textbf{FR 5}), and troubleshooting.\\[2mm] \textbf{Test Case Derivation:} Validates that the documentation - meets user needs (FR 10).\\[2mm] + meets user needs (\textbf{FR 7}).\\[2mm] \textbf{How test will be performed:} Review the documentation for completeness and clarity. \end{enumerate} -\noindent -\colorrule +\newpage\subsection{Tests for Nonfunctional Requirements} + +The section will cover system tests for the non-functional +requirements (NFR) listed in the \SRS \hspace{1pt} +document\cite{SRS}. The goal for these tests is to address the fit +criteria for the requirements. Each test will be linked back to a +specific NFR that can be observed in section \ref{trace-sys}.\\ -\subsubsection{IDE Extension Tests} +\noindent For non-functional requirements that are not linked to a test in the below sections, has either been covered in the functional requirements test plan or unit tests plan. Please see traceability matrix for more details. + +\noindent\colorrule + +\subsubsection{Look and Feel} \colorrule \medskip \noindent -The following tests are designed to ensure that the user can -integrate the tool into VS Code IDE as specified in FR 11 and that -the tool works as intended as an extension. +The following subsection tests cover all Look and Feel non-functional +requirements listed in the SRS~\cite{SRS}. They aim to validate that +the system provides a modern, visually appealing, and supportive +developer experience. These tests ensure that the tool facilitates +refactoring decisions through clear interfaces and satisfies design +expectations based on user perception. + +\begin{enumerate}[label={\bf \textcolor{Maroon}{test-LF-\arabic*}}, wide=0pt, font=\itshape] + + \item \textbf{Side-by-side Code Comparison in IDE Plugin} \\[2mm] + \textbf{Type:} Non-Functional, Manual, Dynamic \\ + \textbf{Covers:} LFR-AP1 \\ + \textbf{Initial State:} IDE plugin open in VS Code with a sample + code file loaded \\ + \textbf{Input/Condition:} The user initiates a refactoring operation \\ + \textbf{Output/Result:} The plugin displays the original and + refactored code side by side \\[2mm] + \textbf{How test will be performed:} The tester will open a + sample file and apply a refactoring. They will verify that the + original and refactored code are shown side by side with + functional accept/reject buttons. This confirms users can make + informed refactoring decisions in a visually supportive layout. -\begin{enumerate}[label={\bf - \textcolor{Maroon}{test-FR-IE-\arabic*}}, wide=0pt, font=\itshape] - \item \textbf{Installation of Extension in Visual Studio Code}\\[2mm] - \textbf{Control:} Manual\\ - \textbf{Initial State:} The user has Visual Studio Code installed - on their machine.\\ - \textbf{Input:} The user attempts to install the refactoring tool - extension from the Visual Studio Code Marketplace.\\ - \textbf{Output:} The extension installs successfully, and the - user is able to see it listed in the Extensions view.\\[2mm] - \textbf{Test Case Derivation:} This test validates the - installation process of the extension to ensure that users can - easily add the tool to their development environment.\\[2mm] - \textbf{How test will be performed:} - \begin{enumerate}[label=\arabic*.] - \item Open Visual Studio Code. - \item Navigate to the Extensions view (Ctrl+Shift+X). - \item Search for the refactoring tool extension in the marketplace. - \item Click on the "Install" button. - \item After installation, verify that the extension appears in - the installed extensions list. - \item Confirm that the extension is enabled and ready for use - by checking its functionality within the editor. - \end{enumerate} + \item \textbf{Design Acceptance Survey} \\[2mm] + \textbf{Type:} Non-Functional, Manual, Dynamic \\ + \textbf{Covers:} LFR-ST1, \textit{implicitly covers} LFR-AP2 \\ + \textbf{Initial State:} IDE plugin open \\ + \textbf{Input/Condition:} Developer interacts with the plugin \\ + \textbf{Output/Result:} A survey response capturing the user’s + perception of the design \\[2mm] + \textbf{How test will be performed:} After using the plugin, + test participants will complete the design satisfaction survey + described in \ref{A.2}. The results will be reviewed to assess + whether the plugin meets the project's aesthetic and usability + expectations.\\ + + \textit{Note:} LFR-AP2 is not tested directly, as it describes a + design philosophy rather than a testable behavior. User perception of + visual simplicity and minimalism is instead captured through feedback + in the usability survey. - \item \textbf{Running the Extension in Visual Studio Code}\\[2mm] - \textbf{Control:} Manual\\ - \textbf{Initial State:} The user has successfully installed the - refactoring tool extension in Visual Studio Code.\\ - \textbf{Input:} The user opens a Python file and activates the - refactoring tool extension.\\ - \textbf{Output:} The extension runs successfully, and the user - can see a list of detected code smells and suggested refactorings.\\[2mm] - \textbf{Test Case Derivation:} This test validates that the - extension can be executed within the development environment and - that it correctly identifies code smells as per the functional - requirements in the SRS.\\[2mm] - \textbf{How test will be performed:} - \begin{enumerate}[label=\arabic*.] - \item Open Visual Studio Code. - \item Open a valid Python file that contains known code smells. - \item Activate the refactoring tool extension using the command - palette (Ctrl+Shift+P) and selecting the extension command. - \item Observe the output panel for the detection of code smells. - \item Verify that the extension lists the identified code - smells and provides appropriate refactoring suggestions. - \item Confirm that the suggestions are relevant and feasible - for the detected code smells. - \end{enumerate} \end{enumerate} -\subsection{Tests for Nonfunctional Requirements} +\newpage +\noindent\colorrule -The section will cover system tests for the non-functional -requirements (NFR) listed in the \SRS \hspace{1pt} -document\cite{SRS}. The goal for these tests is to address the fit -criteria for the requirements. Each test will be linked back to a -specific NFR that can be observed in section \ref{trace-sys}. +\subsubsection{Usability \& Humanity} +\colorrule + +\medskip \noindent -\colorrule +The following tests cover all Usability \& Humanity requirements listed in the SRS~\cite{SRS}. These tests aim to validate that the system is accessible, user-centred, intuitive, and easy to navigate. Data is collected via user surveys or static analysis, and evaluated against thresholds (e.g., 80–90\% agreement). Where applicable, tests are traceable to corresponding SRS requirements. -\subsubsection{Look and Feel} +\begin{enumerate}[label={\bf \textcolor{Maroon}{test-UH-\arabic*}}, wide=0pt, font=\itshape] + + \item \textbf{Customizable Settings for Refactoring Preferences} \\[2mm] + \textbf{Type:} Manual, Dynamic \\ + \textbf{Covers:} \textbf{UHR-PSI 1} \& \textbf{UHR-PSI 2} \\ + \textbf{Initial State:} Plugin open with settings panel accessible \\ + \textbf{Input/Condition:} User customizes enabled smells and highlight colors \\ + \textbf{Output/Result:} Preferences persist and affect plugin behavior \\[2mm] + \textbf{How test will be performed:} Tester toggles smell types and changes highlight colours. They reload the plugin and verify that settings are retained and correctly reflected in UI and detection. + \item \textbf{High-Contrast Theme Accessibility Check} \\[2mm] + \textbf{Type:} Static Analysis \\ + \textbf{Covers:} \textbf{UHR-ACS 1} \\ + \textbf{Initial State:} Contrast-based theme styles configured \\ + \textbf{Input/Condition:} Contrast analyzer is run on UI color tokens \\ + \textbf{Output/Result:} All items meet 4.5:1 or 3:1 WCAG thresholds \\[2mm] + \textbf{How test will be performed:} Use automated tools (e.g., WebAIM) to verify foreground/background ratios for code highlights, sidebars, and messages. + + \item \textbf{Intuitive User Interface for Core Functionality} \\[2mm] + \textbf{Type:} User Testing, Survey-Based \\ + \textbf{Covers:} \textbf{UHR-EOU 1} \\ + \textbf{Initial State:} Plugin open with test tasks prepared \\ + \textbf{Input/Condition:} Users complete core tasks (detect, refactor, configure) \\ + \textbf{Output/Result:} 90\% of users complete each task in $\leq$ 3 clicks and rate the interaction as intuitive \\[2mm] + \textbf{How test will be performed:} Clicks per task are recorded. After each task, users answer the question “Was this process intuitive?” on a 5-point Likert scale. The question is listed in Appendix~\ref{A.2}. \\ + \textbf{Quantifiable Metric:} At least 85\% of responses must score 4 or 5 on the intuitiveness scale. \\ + \textbf{Use of Results:} Responses scoring below threshold will trigger UX redesign of the corresponding interaction. Open feedback (if given) will be coded thematically to identify patterns in confusion or friction points. + + \item \textbf{Clear and Concise User Prompts} \\[2mm] + \textbf{Type:} Survey-Based \\ + \textbf{Covers:} \textbf{UHR-EOU 2} \\ + \textbf{Initial State:} User encounters plugin prompts (e.g., file missing, confirm refactor) \\ + \textbf{Input/Condition:} Users follow prompts and evaluate clarity \\ + \textbf{Output/Result:} 90\% of users agree prompts are helpful and unambiguous \\[2mm] + \textbf{How test will be performed:} After interacting with all major system prompts, users complete a survey (Appendix~\ref{A.2}) where they rate the clarity of each message on a 5-point scale and provide optional comments. \\ + \textbf{Quantifiable Metric:} 90\% of users must rate each prompt $\geq$ 4 for clarity and helpfulness. \\ + \textbf{Use of Results:} Any prompt scoring below target will be reviewed and rewritten. Free-text feedback will be grouped by theme to identify language, formatting, or placement issues. + + \item \textbf{Context-Sensitive Help Based on User Actions} \\[2mm] + \textbf{Type:} Manual \\ + \textbf{Covers:} \textbf{UHR-LRN 1} \\ + \textbf{Initial State:} Help system available via command/hover \\ + \textbf{Input/Condition:} User performs smell-related actions, requests help \\ + \textbf{Output/Result:} Help shown is contextually relevant, appears within \textless= 3 clicks \\[2mm] + \textbf{How test will be performed:} Tester performs tasks like “Apply refactor” or “Toggle smell” and verifies help popups match the current feature. + + \item \textbf{Clear and Constructive Error Messaging} \\[2mm] + \textbf{Type:} Survey-Based \\ + \textbf{Covers:} \textbf{UHR-UPL 1} \\ + \textbf{Initial State:} Plugin triggers common errors (e.g., no workspace configured, backend offline) \\ + \textbf{Input/Condition:} User encounters error messages during usage and evaluates tone and clarity \\ + \textbf{Output/Result:} 80\% of users agree the message is polite, understandable, and helpful \\[2mm] + \textbf{How test will be performed:} After encountering various plugin error scenarios, users complete a survey located in Appendix~\ref{A.2}. They rate each error message on tone, clarity, and helpfulness using a 5-point Likert scale, and may provide free-text feedback. \\ + \textbf{Quantifiable Metric:} Each error message must receive an average rating of $\geq$ 4 in tone, clarity, and helpfulness from at least 80\% of participants. \\ + \textbf{Use of Results:} Messages scoring below threshold will be flagged for revision. Qualitative responses will be categorized to identify recurring issues such as overly technical language, lack of actionable steps, or negative tone. + +\end{enumerate} + + +\newpage + \noindent + \textcolor{Blue}{\colorrule} + +\subsubsection{Performance} \colorrule \medskip \noindent -The following subsection tests cover all Look and Feel requirements -listed in the SRS~\cite{SRS}. They seek to validate that the system -is modern, visually appealing, and supporting of a calm and focused -user experience. - -\begin{enumerate}[label={\bf \textcolor{Maroon}{test-LF-\arabic*}}, - wide=0pt, font=\itshape] - \item \textbf{Side-by-side code comparison in IDE plugin} \\[2mm] - \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} IDE plugin open in VS Code, with a sample - code file loaded \\ - \textbf{Input/Condition:} The user initiates a refactoring operation \\ - \textbf{Output/Result:} The plugin displays the original and - refactored code side by side\\[2mm] - \textbf{How test will be performed:} The tester will open a - sample code file within the IDE plugin and apply a refactoring - operation. After refactoring, they will verify that the original - code appears on one side of the interface and the refactored code - on the other, with clear options to accept or reject each change. - The tester will interact with the accept/reject buttons to ensure - functionality and usability, confirming that users can seamlessly - make refactoring decisions with both versions displayed side by side. - - \item \textbf{Theme adaptation in VS Code} \\[2mm] - \textbf{Type:} Non-functional, Manual, Dynamic \\ - \textbf{Initial State:} IDE plugin open in VS Code with either - light or dark theme enabled \\ - \textbf{Input/Condition:} The user switches between light and - dark themes in VS Code \\ - \textbf{Output/Result:} The plugin’s interface adjusts - automatically to match the theme \\[2mm] - \textbf{How test will be performed:} The tester will open the - plugin in both light and dark themes within VS Code by toggling - the theme settings in the IDE. They will observe the plugin - interface each time the theme is switched, ensuring that the - plugin automatically adjusts to match the selected theme without - any manual adjustments required. - - \item \textbf{Design Acceptance} \\[2mm] - \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} IDE plugin open \\ - \textbf{Input/Condition:} User interacts with the plugin \\ - \textbf{Output/Result:} A survey report \\[2mm] - \textbf{How test will be performed:} After a testing session, - developers fill out the survey found in \ref{A.2} evaluating - their experience with the plugin. +The following subsection tests cover the Performance requirements listed in the SRS~\cite{SRS}. The goal is to validate that the tool can process Python files of varying sizes within acceptable performance thresholds. These tests confirm responsiveness under real-world usage, and guide profiling and optimization work for scalability. + +\begin{enumerate}[label={\bf \textcolor{Maroon}{test-PF-\arabic*}}, wide=0pt, font=\itshape] + + \item \textbf{Performance and Capacity Validation for Analysis and Refactoring} \\[2mm] + \textbf{Type:} Non-Functional, Automated, Dynamic \\ + \textbf{Covers:} PR-SL~1, PR-SL~2, PR-CR~1 \\ + \textbf{Initial State:} IDE open with multiple Python files of varying sizes prepared (small: 250 LOC, medium: 1000 LOC, large: 3000 LOC) \\ + \textbf{Input/Condition:} Initiate detection and refactoring for each file sequentially \\ + \textbf{Output/Result:} Tool completes within: + \begin{itemize} + \item 20 seconds for small files ($\leq$ 250 lines) + \item 50 seconds for medium files ($\leq$ 1000 lines) + \item 2 minutes for large files ($\leq$ 3000 lines) + \end{itemize} + \textbf{How test will be performed:} Detection and refactoring will be run on each file. Timings will be recorded from start to finish. If thresholds are exceeded, logs and profiling output will be used to identify and prioritize optimization targets. + \end{enumerate} -\noindent -\colorrule +\medskip -\subsubsection{Usability \& Humanity} +\noindent \textbf{Untested Requirements and Justification:} + +\begin{itemize} + \item \textbf{PR-SCR 1 (No runtime errors in refactored code)}: Verified by functional unit tests and integration tests that execute refactored code and ensure correctness and compilability. + + \item \textbf{PR-PAR 1 (Smell detection accuracy)}: Already covered in functional tests, which compare the detected smells against a ground truth dataset and calculate precision/recall. + + \item \textbf{PR-PAR 2 (Output validity)}: Confirmed by functional tests that ensure the generated refactored code is syntactically valid and matches Python standards. + + \item \textbf{PR-RFT 1 (Robustness to invalid input)}: Addressed through functional tests which simulate corrupt files or invalid syntax and assert the system recovers gracefully. + \item \textbf{PR-SER 1 (Extensibility)}: Verified through manual inspection and code review of plugin architecture and smell registration pipeline; extensibility is not runtime-measurable and therefore not performance tested. + + \item \textbf{PR-LR 1 (Longevity)}: Also verified through code quality reviews. Maintainability is supported by documentation and modularity but not measurable via direct tests in this release cycle. +\end{itemize} + + + \noindent + \colorrule + +\subsubsection{Operational \& Environmental} \colorrule \medskip \noindent -The following subsection tests cover all Usability \& Humanity -requirements listed in the SRS~\cite{SRS}. They seek to validate that -the system is accessible, user-centred, intuitive and easy to navigate. +The following subsection tests cover all Operational and Environmental requirements listed in the SRS~\cite{SRS}. This includes confirming system compatibility, installation capability, and basic usability across operational contexts. Physical environment requirements are not tested, as explained below. + +\begin{enumerate}[label={\bf \textcolor{Maroon}{test-OPE-\arabic*}}, wide=0pt, font=\itshape] -\begin{enumerate}[label={\bf \textcolor{Maroon}{test-UH-\arabic*}}, - wide=0pt, font=\itshape] - \item \textbf{Customizable settings for refactoring preferences} \\[2mm] + \item \textbf{VS Code Compatibility for Refactoring Library Extension} \\[2mm] \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} IDE plugin open with settings panel accessible \\ - \textbf{Input/Condition:} User customizes refactoring style and - detection sensitivity \\ - \textbf{Output/Result:} Custom configurations save and load - successfully \\[2mm] - \textbf{How test will be performed:} The tester will navigate to - the settings menu within the tool and adjust various options, - including refactoring style, colour-coded indicators, and unit - preferences (metric vs. imperial). After each adjustment, the - tester will observe if the interface and refactoring suggestions - reflect the changes made. - - \item \textbf{Multilingual support in user guide} \\[2mm] + \textbf{Covers:} \textbf{OER-IAS 1} \\ + \textbf{Initial State:} VS Code IDE open and library not installed \\ + \textbf{Input/Condition:} User installs and opens the refactoring library extension in VS Code \\ + \textbf{Output/Result:} The extension installs successfully and runs inside VS Code \\[2mm] + \textbf{How test will be performed:} The tester will search for the extension on the VS Code marketplace, install it, and verify that it appears in the IDE and can execute basic functionality such as detecting or refactoring a code file. + + \item \textbf{Import and Export Capabilities for Codebases and Metrics} \\[2mm] \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} Bilingual user navigates to system documentation \\ - \textbf{Input/Condition:} User accesses guide in both English and French \\ - \textbf{Output/Result:} The guide is accessible in both languages \\[2mm] - \textbf{How test will be performed:} The tester will set the - tool’s language to French and access the user guide, reviewing - each section to ensure accurate translation and readability. - After verifying the French version, they will switch the language - to English, confirming consistency in content, layout, and - clarity between both versions. - - \item \textbf{YouTube installation tutorial availability} \\[2mm] + \textbf{Covers:} \textbf{OER-IAS 2} \\ + \textbf{Initial State:} IDE plugin open with option to import/export \\ + \textbf{Input/Condition:} User imports a sample project and exports results \\ + \textbf{Output/Result:} Plugin correctly imports project and generates JSON/XML reports for refactored code and metrics \\[2mm] + \textbf{How test will be performed:} Tester loads a sample codebase, initiates a refactor, and uses the export function. Output files are verified for valid structure and meaningful content. + + \item \textbf{PIP Package Installation Availability} \\[2mm] \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} User access documentation resources \\ - \textbf{Input/Condition:} User follows the provided link to a - YouTube tutorial \\ - \textbf{Output/Result:} Installation tutorial is available and - accessible on YouTube, and user successfully installs the system. \\[2mm] - \textbf{How test will be performed:} The tester will start with - the installation instructions provided in the user guide and - follow the link to the YouTube installation tutorial. They will - watch the video and proceed with each installation step as - demonstrated. Throughout the process, the tester will note the - clarity and pacing of the instructions, any gaps between the - video and the actual steps, and if the video effectively guides - them to a successful installation. + \textbf{Covers:} \textbf{OER-PR 1} \\ + \textbf{Initial State:} Fresh Python environment without the package \\ + \textbf{Input/Condition:} User runs \texttt{pip install ecooptimizer} \\ + \textbf{Output/Result:} The package installs successfully without error \\[2mm] + \textbf{How test will be performed:} Tester uses a clean Python virtual environment to install the library. A short script using a sample function will verify it works as expected after installation. - \item \textbf{High-Contrast Theme Accessibility Check} \\[2mm] - \textbf{Objective:} Evaluate the high-contrast themes in the - refactoring tool for compliance with accessibility standards to - ensure usability for visually impaired users. \\ - \textbf{Scope:} Focus on UI components that utilize high-contrast - themes, including text, buttons, and backgrounds. \\ - \textbf{Methodology:} Static Analysis \\ - \textbf{Process:} - \begin{itemize} - \item Identify all colour codes used in the system and - categorize them by their role in the UI (i.e. background, - foreground text, buttons, etc.). - \item Use tools to measure colour contrast ratios against WCAG - thresholds (4.5:1 for normal text, 3:1 for large text~\cite{WCAG}. - \end{itemize} - \textbf{Roles and Responsibilities:} Developers implement - themes that pass the testing process. \\[2mm] - \textbf{Tools and Resources:} WebAIM Color Contrast Checker, - WCAG guidelines documentation, internal coding standards. \\[2mm] - \textbf{Acceptance Criteria:} All UI elements must meet WCAG - contrast ratios; documentation must accurately reflect theme usage. - - \item \textbf{Intuitive user interface for core functionality} \\[2mm] - \textbf{Type:} Non-Functional, User Testing, Dynamic \\ - \textbf{Initial State:} IDE plugin open with code loaded \\ - \textbf{Input/Condition:} User interacts with the plugin \\ - \textbf{Output/Result:} Users can access core functions within - three clicks or less \\[2mm] - \textbf{How test will be performed:} After a testing session, - developers fill out the survey found in \ref{A.2} evaluating - their experience with the plugin. - - \item \textbf{Clear and concise user prompts} \\[2mm] - \textbf{Type:} Non-Functional, User Survey, Dynamic \\ - \textbf{Initial State:} IDE plugin prompts user for input \\ - \textbf{Input/Condition:} Users follow on-screen instructions \\ - \textbf{Output/Result:} 90\% of users report the prompts are - straightforward and effective \\[2mm] - \textbf{How test will be performed:} Users complete tasks - requiring prompts and answer the survey found in \ref{A.2} on - the clarity of guidance provided. - - \item \textbf{Context-sensitive help based on user actions} \\[2mm] - \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} IDE plugin open with help function enabled \\ - \textbf{Input/Condition:} User engages in various actions, - requiring guidance \\ - \textbf{Output/Result:} Help resources are accessible within - 1-3 clicks \\[2mm] - \textbf{How test will be performed:} The tester will perform a - series of tasks within the tool, such as initiating a code - analysis, applying a refactoring, and adjusting settings. At - each step, they will access the context-sensitive help option - to confirm that the information provided is relevant to the - current task. The tester will evaluate the ease of accessing - help, the relevance and clarity of guidance, and whether the - help content effectively supports task completion. - - \item \textbf{Clear and constructive error messaging} \\[2mm] - \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} IDE plugin open with possible error - scenarios triggered \\ - \textbf{Input/Condition:} User encounters an error during use \\ - \textbf{Output/Result:} 80\% of users report that error - messages are helpful and courteous \\[2mm] - \textbf{How test will be performed:} After receiving error - messages, users fill out the survey found in \ref{A.2} on their - clarity and constructiveness. - \end{enumerate} +\end{enumerate} - \noindent - \textcolor{Blue}{\colorrule} +\subsubsection*{Unnecessary Tests and Justifications} - \subsubsection{Performance} - \colorrule +\begin{itemize} + \item \textbf{OER-EP 1 \& OER-EP 2 (Temperature \& Power Requirements)}: \\ + These describe expected hardware operating conditions. If the computer cannot operate due to temperature or power issues, the software cannot run. These are not properties of the software and are thus \textit{not tested} in this V\&V plan. - \medskip + \item \textbf{OER-RL 1 (All core functionality implemented and tested)}: \\ + This requirement is satisfied by the completion of the full functional and non-functional test suite. No specific test case is needed beyond traceability to those tests. - \noindent - The following subsection tests cover all Performance requirements - listed in the SRS~\cite{SRS}. These tests validate the tool’s - efficiency and responsiveness under varying workloads, including - code analysis, refactoring, and data reporting. - - \begin{enumerate}[label={\bf \textcolor{Maroon}{test-PF-\arabic*}}, - wide=0pt, font=\itshape] - \item \textbf{Performance and capacity validation for analysis - and refactoring} \\[2mm] - \textbf{Type:} Non-Functional, Automated, Dynamic \\ - \textbf{Initial State:} IDE open with multiple python files of - varying sizes ready (250, 1000, 3000 lines of code). \\ - \textbf{Input/Condition:} Initiate the refactoring process for - each file sequentially \\ - \textbf{Output/Result:} Process completes within 20 seconds for - files up to 250 lines of code, 50 seconds for 1000 lines of - code and within 2 minutes for 3000 lines of code. \\[2mm] - \textbf{How test will be performed:} The tester will use three - python files of different sizes: small (250 lines), medium - (1000 lines), and - large (3000 lines). For each file, start the refactoring - process while running a timer. - The scope of the test ends when the system presents the user - with the completed refactoring proposal. - The time taken for the total detection + refactoring is checked - against the expected result. - - \item \textbf{Accuracy of code smell detection} \\[2mm] - \textbf{Type:} Non-Functional, Automated, Dynamic \\ - \textbf{Initial State:} Python file containing pre-determined - code smells ready for refactoring with proper configurations - for the system \\ - \textbf{Input/Condition:} User initiates refactoring on the code file \\ - \textbf{Output/Result:} All code smells determined prior to the - test are detected. \\[2mm] - \textbf{How test will be performed:} see tests in the - \hyperref[4.1.2]{Code Smell Detection} section. - - \item \textbf{Valid syntax and structure in refactored code} \\[2mm] - \textbf{Type:} Non-Functional, Automated, Dynamic \\ - \textbf{Initial State:} A refactored code file is present in - the user's workspace \\ - \textbf{Input/Condition:} A python linter is run on the - refactored python file \\ - \textbf{Output/Result:} Refactored code meets Python syntax and - structural standards \\[2mm] - \textbf{How test will be performed:} see test - \hyperref[itm:FR-OV-2]{test-FR-OV-2} - - \end{enumerate} + \item \textbf{OER-RL 2 (Release by March 17, 2025)}: \\ + This is a delivery milestone tracked through project management, not through testing. Therefore, it is \textit{not verified dynamically} through test cases. +\end{itemize} \noindent \colorrule - \subsubsection{Operational \& Environmental} - \colorrule +\subsubsection{Maintenance and Support} +\colorrule - \medskip +\medskip - \noindent - The following subsection tests cover all Operational and - Environmental requirements listed in the SRS~\cite{SRS}. Testing - includes adherence to emissions standards, integration with - environmental metrics, and adaptability to diverse operational settings. - - \begin{enumerate}[label={\bf - \textcolor{Maroon}{test-OPE-\arabic*}}, wide=0pt, font=\itshape] - \item \textbf{VS Code compatibility for refactoring library - extension} \\[2mm] - \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} VS Code IDE open and library installed\\ - \textbf{Input/Condition:} User installs and opens the - refactoring library extension in VS Code \\ - \textbf{Output/Result:} The refactoring library extension - installs successfully and runs within VS Code \\[2mm] - \textbf{How test will be performed:} The tester will navigate - to the VS Code marketplace, search for the refactoring library - extension, and install it. Once installed, the tester will open - the extension and perform a basic refactoring task to ensure - the tool operates correctly within the VS Code environment and - has access to the system library. - - \item \textbf{Import and export capabilities for codebases and - metrics} \\[2mm] - \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} IDE plugin open with the option to - import/export codebases and metrics \\ - \textbf{Input/Condition:} User imports an existing codebase and - exports refactored code and metrics reports \\ - \textbf{Output/Result:} The tool successfully imports - codebases, refactors them, and exports both code and metrics - reports \\[2mm] - \textbf{How test will be performed:} The tester will load an - existing codebase into the tool, initiate refactoring, and - select the option to export the refactored code and metrics - report. The export should generate files in the selected - format. The tester will verify the file formats, check for - correct data structure, and validate that the content - accurately reflects the refactoring and metrics generated by the tool. - - \item \textbf{PIP package installation availability} \\[2mm] - \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} Python environment ready without the - refactoring library installed \\ - \textbf{Input/Condition:} User installs the refactoring library - using the command \texttt{pip install ecooptimizer} \\ - \textbf{Output/Result:} The library installs successfully - without errors and is available for use in Python scripts \\[2mm] - \textbf{How test will be performed:} The tester will open a new - Python environment and enter the command to install the - refactoring library via PIP. Once installed, the tester will - import the library in a Python script and execute a basic - function to confirm successful installation and functionality. - The test verifies the library’s availability and ease of - installation for end users. - - \end{enumerate} +\noindent +The following subsection tests cover the most critical Maintenance and Support requirements listed in the SRS~\cite{SRS}. These tests emphasize extensibility, maintainability, and recovery from faulty updates. Some lower-priority requirements are acknowledged but excluded from testing due to scope or redundancy with existing CI/CD practices. + +\begin{enumerate}[label={\bf \textcolor{Maroon}{test-MS-\arabic*}}, wide=0pt, font=\itshape] + + \item \textbf{Extensibility for New Code Smells and Refactorings} \\[2mm] + \textbf{Covers:} \textbf{MS-MNT 1} \\ + \textbf{Type:} Code Walkthrough and Manual Dynamic \\ + \textbf{Initial State:} Developer environment set up with project codebase \\ + \textbf{Input/Condition:} Developer adds a sample code smell and refactoring method \\ + \textbf{Output/Result:} The new smell/refactoring integrates with minimal disruption \\[2mm] + \textbf{How test will be performed:} Developers will follow documentation to add a new smell and refactoring function. They will verify modularity and confirm that existing functionality is unaffected. Success is defined by clean integration and interface visibility without needing major code changes. + + \item \textbf{Maintainable and Adaptable Codebase} \\[2mm] + \textbf{Covers:} \textbf{MS-MNT 2} \\ + \textbf{Type:} Static Analysis and Documentation Review \\ + \textbf{Initial State:} Final implementation and documentation available \\ + \textbf{Input/Condition:} Reviewers evaluate code organization and documentation \\ + \textbf{Output/Result:} Codebase is modular, readable, and sufficiently documented \\[2mm] + \textbf{How test will be performed:} Reviewers examine file structure, naming conventions, and presence of comments. They will evaluate whether a new developer could easily navigate and modify the code. Documentation completeness will be scored on a checklist. + + \item \textbf{Rollback Support for Faulty Updates} \\[2mm] + \textbf{Covers:} \textbf{MS-MNT 3} \\ + \textbf{Type:} Manual Dynamic \\ + \textbf{Initial State:} Installed version of the library in use \\ + \textbf{Input/Condition:} Faulty update is simulated; rollback is triggered \\ + \textbf{Output/Result:} System returns to previous stable state successfully \\[2mm] + \textbf{How test will be performed:} A new version with an intentional fault is deployed. The user will invoke rollback steps (e.g., Git revert or VS Code extension downgrade). The tool should resume normal operation with no feature regressions. +\end{enumerate} - \noindent - \colorrule +\vspace{2mm} +\noindent\textbf{Unnecessary Tests and Justifications} +\begin{itemize} + \item \textbf{MS-MNT 4 (Automated Testing for Refactorings):} Verified through existing unit tests and CI pipeline. Manual test duplication is unnecessary. + \item \textbf{MS-MNT 5 (Library Compatibility with Dependencies):} Assumed validated during integration testing and package dependency resolution via PIP. +\end{itemize} - \subsubsection{Maintenance and Support} - \colorrule +\noindent \colorrule - \medskip - \noindent - The following subsection tests cover all Maintenance and Support - requirements listed in the SRS~\cite{SRS}. These tests focus on - rollback capabilities, compatibility with external libraries, - automated testing, and extensibility for adding new code smells and - refactoring functions. - - \begin{enumerate}[label={\bf \textcolor{Maroon}{test-MS-\arabic*}}, - wide=0pt, font=\itshape] - \item \textbf{Extensibility for New Code Smells and Refactorings} \\[2mm] - \textbf{Objective:} Confirm that the tool’s architecture allows - for the addition of new code smell detections and refactoring - techniques with minimal code changes and disruption to existing - functionality. \\[2mm] - \textbf{Scope:} This test applies to the tool’s extensibility, - including modularity of code structure, ease of integration for - new detection methods, and support for customization. \\[2mm] - \textbf{Methodology:} Code walkthrough \\[2mm] - \textbf{Process:} - \begin{itemize} - \item Conduct a code walkthrough focusing on the modularity - and structure of the code smell detection and refactoring components. - \item Add a sample code smell detection and refactoring - function to validate the ease of integration within the - existing architecture. - \item Verify that the new function integrates seamlessly - without altering existing features and that it is - accessible through the tool’s main interface. - \end{itemize} - \textbf{Roles and Responsibilities:} Once the system is - complete, the development team will perform the code - walkthrough and integration. They will review and approve any - structural changes required. \\[2mm] - \textbf{Tools and Resources:} Code editor, tool’s developer - documentation, sample code smell and refactoring patterns \\[2mm] - \textbf{Acceptance Criteria:} New code smells and refactoring - functions can be added within the existing modular structure, - requiring minimal changes. The new function does not impact the - performance or functionality of existing features. - - \item \textbf{Maintainable and Adaptable Codebase} \\[2mm] - \textbf{Objective:} Ensure that the codebase is modular, - well-documented, and maintainable, supporting future updates - and adaptations for new Python versions and standards. \\[2mm] - \textbf{Scope:} This test covers the maintainability of the - codebase, including structure, documentation, and modularity of - key components. \\[2mm] - \textbf{Methodology:} Static analysis and documentation - walkthrough \\[2mm] - \textbf{Process:} - \begin{itemize} - \item Review the codebase to verify the modular organization - and clear separation of concerns between components. - \item Examine documentation for code clarity and - completeness, especially around key functions and configuration files. - \item Assess code comments and the quality of function/method - naming conventions, ensuring readability and consistency - for future maintenance. - \end{itemize} - \textbf{Roles and Responsibilities:} Once the system is - complete, the development team will conduct the code review, to - identify areas for improvement. If necessary, they will also - ensure to improve the quality of the documentation. \\[2mm] - \textbf{Tools and Resources:} Code editor, documentation - templates, code commenting standards, Python development guides \\[2mm] - \textbf{Acceptance Criteria:} The codebase is modular and - maintainable, with sufficient documentation to support future - development. All major components are organized to allow for - easy updates with minimal impact on existing functionality. - - \item \textbf{Easy rollback of updates in case of errors} \\[2mm] - \textbf{Type:} Non-Functional, Manual, Dynamic \\ - \textbf{Initial State:} Latest version of the tool installed - with the ability to apply and revert updates \\ - \textbf{Input/Condition:} User applies a simulated new update - and initiates a rollback \\ - \textbf{Output/Result:} The system reverts to the previous - stable state without any errors \\[2mm] - \textbf{How test will be performed:} The tester will apply a - simulated update. Following this, they will initiate the - rollback function, which should restore the tool to its - previous stable version. The tester will verify that all - features function as expected post-rollback and document the - time taken to complete the rollback process - \end{enumerate} +\subsubsection{Security} +\colorrule - \newpage +\medskip - \noindent - \colorrule +\noindent +The following subsection tests cover the primary Security requirement listed in the SRS~\cite{SRS}. These tests ensure that refactoring operations are traceable, logged securely, and protected from unauthorized tampering. Due to the tool's local-only design, network-level security and external access controls are out of scope. - \subsubsection{Security} - \colorrule +\begin{enumerate}[label={\bf \textcolor{Maroon}{test-SRT-\arabic*}}, wide=0pt, font=\itshape] - \medskip + \item \textbf{Audit Logs for Refactoring Processes} \\[2mm] + \textbf{Covers:} \textbf{SRT-AUD 1} \\ + \textbf{Type:} Static Analysis and Code Review \\ + \textbf{Initial State:} Fully implemented refactoring pipeline with logging enabled \\ + \textbf{Input/Condition:} Refactoring actions performed on one or more files \\ + \textbf{Output/Result:} Secure and complete logs are generated for each action \\[2mm] + \textbf{How test will be performed:} The development team will review logging logic in the code to ensure it covers all major events: pattern detection, energy analysis, and refactor generation. Each entry must include a timestamp, file reference, and action type. Reviewers will confirm that logs are immutable and not user-editable, using tools like append-only file systems or cryptographic checksums if applicable. - \noindent - The following subsection tests cover all Security requirements - listed in the SRS~\cite{SRS}. These tests seek to validate that the - tool is protected against unauthorized access, data breaches, and - external threats. - - \begin{enumerate}[label={\bf - \textcolor{Maroon}{test-SRT-\arabic*}}, wide=0pt, font=\itshape] - \item \textbf{Audit Logs for Refactoring Processes} \\[2mm] - \textbf{Objective:} Ensure that the tool maintains a secure, - tamper-proof log of all refactoring processes, including - pattern analysis, energy analysis, and report generation, for - accountability in refactoring events. \\[2mm] - \textbf{Scope:} This test covers the logging of refactoring - events, ensuring logs are complete and tamper-proof for future - auditing needs. \\[2mm] - \textbf{Methodology:} Code walkthrough and static analysis \\[2mm] - \textbf{Process:} - \begin{itemize} - \item Review the codebase to confirm that each refactoring - event (e.g., pattern analysis, energy analysis, report - generation) is logged with details such as timestamps and - event descriptions. - \item Document any logging gaps or security vulnerabilities, - and consult with the development team to implement enhancements. - \end{itemize} - \textbf{Roles and Responsibilities:} The development team will - review and test the logging mechanisms, with the project - supervisor ensuring alignment with auditing requirements. \\[2mm] - \textbf{Tools and Resources:} Access to logging components, - tamper-proof logging tools \\[2mm] - \textbf{Acceptance Criteria:} All refactoring processes are - logged in a secure, tamper-proof manner, ensuring complete - traceability for future audits. - \end{enumerate} - \newpage +\end{enumerate} + +\newpage \noindent \colorrule @@ -1323,173 +894,123 @@ \subsubsection{Usability \& Humanity} aspects do not involve cultural considerations, making such requirements unnecessary. - \newpage - \noindent \colorrule - \subsubsection{Compliance} - \colorrule +\subsubsection{Compliance} +\colorrule - \medskip +\medskip - \noindent - The following subsection tests cover all Compliance requirements - listed in the SRS~\cite{SRS}. The tests focus on adherence to - PIPEDA, CASL, and ISO 9001, as well as SSADM standards, ensuring - the tool complies with relevant regulations and aligns with - professional development practices. - - \begin{enumerate}[label={\bf - \textcolor{Maroon}{test-CPL-\arabic*}}, wide=0pt, font=\itshape] - \item \textbf{Compliance with PIPEDA and CASL} \\[2mm] - \textbf{Objective:} Ensure the tool’s data handling and - communication practices align with the Personal Information - Protection and Electronic Documents Act (PIPEDA) and Canada’s - Anti-Spam Legislation (CASL). The focus is on ensuring - compliance through best practices rather than direct data - storage verification as no data is locally stored. \\[2mm] - \textbf{Scope:} This test applies to all processes related to - data handling and user communication to verify compliance with - PIPEDA and CASL. \\[2mm] - \textbf{Methodology:} Comparison of code data handling - processes with compliance best practices \\[2mm] - \textbf{Process:} - \begin{itemize} - \item Review the tool’s data handling procedures to confirm - all processing remains local and that no user data is stored. - \item Verify that no personal data collection occurs, - ensuring no explicit user consent is required beyond - general software disclaimers. - \item Inspect communication practices to ensure compliance - with CASL, confirming that the tool does not send - unsolicited communications. - \end{itemize} - \textbf{Roles and Responsibilities:} The development team will - review compliance best practices and update documentation as - needed. \\[2mm] - \textbf{Tools and Resources:} Access to PIPEDA and CASL guidelines \\[2mm] - \textbf{Acceptance Criteria:} Compliance is confirmed if no - unsolicited communications occur and all best practices are - followed. The tool must ensure that all data handling remains - local and that no user data is stored or transmitted externally. - - \item \textbf{Compliance with ISO 9001 and SSADM Standards} \\[2mm] - \textbf{Objective:} Assess whether the tool’s quality - management and software development processes follow structured - methodologies in line with ISO 9001 quality management - principles and SSADM (Structured Systems Analysis and Design - Method) best practices. \\[2mm] - \textbf{Scope:} This test evaluates development workflows, - documentation practices, and adherence to structured - methodologies. \\[2mm] - \textbf{Methodology:} Documentation review and evaluation of - structured development practices \\[2mm] - \textbf{Process:} - \begin{itemize} - \item Review development documentation to ensure structured - workflow practices are followed. - \item Evaluate version control and change tracking methods to - confirm basic quality assurance measures exist. - \item Identify any gaps in structured development adherence - and suggest improvements. - \item Validate improvements through informal documentation - and process reviews. - \end{itemize} - \textbf{Roles and Responsibilities:} The development team will - conduct an internal workflow assessment, and updates will be - made to improve documentation and structured processes. \\[2mm] - \textbf{Tools and Resources:} Development documentation, - version control records, best practice comparisons \\[2mm] - \textbf{Acceptance Criteria:} The tool's development must - follow a structured approach with version control, clear - documentation, and logical workflow practices. Compliance is - met if basic structured development principles are followed, - even without formal certification. - \end{enumerate} - - \subsection{Traceability Between Test Cases and Requirements} - \label{trace-sys} +\noindent +The following subsection tests cover all Compliance requirements listed in the SRS~\cite{SRS}. These tests ensure that the system does not collect personal user data and that the codebase adheres to established Python development standards. - \begin{table}[H] - \centering - \caption{Functional Requirements and Corresponding Test Sections} - \begin{tabular}{|p{0.6\textwidth}|p{0.3\textwidth}|} - \toprule \textbf{Section} & \textbf{Functional Requirement} \\ +\begin{enumerate}[label={\bf \textcolor{Maroon}{test-CPL-\arabic*}}, wide=0pt, font=\itshape] + + \item \textbf{User Privacy and Local Execution Compliance} \\[2mm] + \textbf{Covers:} \textbf{CR-LR 1} \\ + \textbf{Type:} Static Review and Code Audit \\ + \textbf{Initial State:} Tool installed and ready for inspection \\ + \textbf{Input/Condition:} Reviewer inspects runtime behavior and data access patterns \\ + \textbf{Output/Result:} No personal or user-specific data is collected or transmitted \\[2mm] + \textbf{How test will be performed:} Review the codebase to confirm that: + \begin{itemize} + \item The tool does not collect or store personal information. + \item No external API requests are made that could leak user data. + \item All operations occur locally, including refactoring, logging, and energy analysis. + \end{itemize} + The reviewer will also confirm the absence of telemetry or usage tracking modules. \\[2mm] + \textbf{Acceptance Criteria:} The tool operates entirely locally, without collecting or transmitting any personal data. Privacy is preserved by design. + + \item \textbf{PEP 8 Standards Compliance} \\[2mm] + \textbf{Covers:} \textbf{CR-SCR 1} \\ + \textbf{Type:} Static Analysis \\ + \textbf{Initial State:} Codebase fully implemented \\ + \textbf{Input/Condition:} Code is scanned using a PEP 8 linter (e.g., \texttt{flake8}, \texttt{pylint}) \\ + \textbf{Output/Result:} All code conforms to Python PEP 8 coding standards \\[2mm] + \textbf{How test will be performed:} Run a static code analysis tool across the full Python codebase. Evaluate: + \begin{itemize} + \item Adherence to line length, indentation, and naming conventions. + \item Documentation comments and docstring usage. + \item Overall maintainability and readability. + \end{itemize} + Any issues will be fixed and re-evaluated. \\[2mm] + \textbf{Acceptance Criteria:} The code passes static analysis with no critical PEP 8 violations. Style warnings are minimized, and documentation is consistent. + +\end{enumerate} + +\newpage\subsection{Traceability Between Test Cases and Requirements} +\label{trace-sys} + +\begin{table}[H] + \centering + \caption{Functional Requirements and Corresponding Test Sections} + \begin{tabular}{p{0.42\textwidth}p{0.42\textwidth}} + \toprule \textbf{Test Section} & \textbf{Functional Requirement(s)} \\ + \midrule + Code Input Acceptance Tests & FR1 \\ + Code Smell Detection and Refactoring Suggestion Tests & FR2, FR3, FR4 \\ + Tests for Reporting Functionality & FR6, FR15 \\ + Visual Studio Code Interactions & FR8, FR9, FR10, FR11, FR12, FR13, FR14, FR15, FR16, FR17 \\ + Documentation Availability Tests & FR7, FR5 \\ + Installation and Onboarding Tests & FR7 \\ + \bottomrule + \end{tabular} + \label{tab:sections_requirements} +\end{table} - \midrule - Input Acceptance Tests & FR 1 \\ \hline - Code Smell Detection Tests & FR 2 \\ \hline - Refactoring Suggestion Tests & FR 4 \\ \hline - Output Validation Tests & FR 3, FR 6 \\ \hline - Tests for Report Generation & FR 9 \\ \hline - Documentation Availability Tests & FR 10 \\ \hline - IDE Integration Tests & FR 11 \\ - \bottomrule - \end{tabular} - \label{tab:sections_requirements} - \end{table} \label{tab:nfr-trace-reqs} \begin{table}[H] - \centering - \caption{Look \& Feel Tests and Corresponding Requirements} - \begin{tabular}{|c|c|} - \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ - \midrule - % Look and Feel - LF-1 & LFR-AP 1 \\ - LF-2 & LFR-AP 2 \\ - LF-3 & LFR-AP 3 \\ - LF-4 & LFR-AP 5 \\ - LF-5 & LFR-AP 4, LFR-ST 1-3 \\ - \bottomrule - \end{tabular} - \end{table} + \centering + \caption{Look \& Feel Tests and Corresponding Requirements} + \label{tab:nfr-trace-lf} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + LF-1 & LFR-AP 1 \\ + LF-2 & LFR-ST 1, LFR-AP 2 \\ + % Note: LFR-AP 2 is tested indirectly in LF-2 + \bottomrule + \end{tabular} +\end{table} - \begin{table}[H] - \centering - \caption{Usability \& Humanity Tests and Corresponding Requirements} - \begin{tabular}{|c|c|} - \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ - \midrule - % Usability and Humanity - UH-1 & UHR-PS1 1 \\ - UH-2 & UHR-PS1 2, MS-SP 1 \\ - UH-3 & UHR-LRN 2 \\ - UH-4 & UHR-ACS 1 \\ - UH-5 & UHR-ACS 2 \\ - UH-6 & UHR-EOU 1 \\ - UH-7 & UHR-EOU 2 \\ - UH-8 & UHR-LRN 1 \\ - UH-9 & UHR-UPL 1 \\ - \bottomrule - \end{tabular} - \end{table} \begin{table}[H] - \centering - \caption{Performance Tests and Corresponding Requirements} - \begin{tabular}{|c|c|} - \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ - \midrule - % Performance - PF-1 & PR-SL 1, PR-SL 2, PR-CR 1 \\ - PF-2 & PR-SCR 1 \\ - PF-3 & PR-PAR 1 \\ - PF-4 & PR-PAR 2 \\ - PF-5 & PR-PAR 3 \\ - PF-6 & PR-RFT 1 \\ - PF-7 & PR-RFT 2 \\ - PF-8 & PR-LR 1, MS-MNT 5 \\ - \bottomrule - \end{tabular} - \end{table} + \centering + \caption{Usability \& Humanity Tests and Corresponding Requirements} + \label{tab:nfr-trace-uh} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + UH-1 & UHR-PSI 1, UHR-PSI 2 \\ + UH-2 & UHR-ACS 1 \\ + UH-3 & UHR-EOU 1 \\ + UH-4 & UHR-EOU 2 \\ + UH-5 & UHR-LRN 1 \\ + UH-6 & UHR-UPL 1 \\ + \bottomrule + \end{tabular} +\end{table} + + +\begin{table}[H] + \centering + \caption{Performance Tests and Corresponding Requirements} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + % Performance + PF-1 & PR-SL 1, PR-SL 2, PR-CR 1 \\ + \bottomrule + \end{tabular} +\end{table} + \begin{table}[H] \centering \caption{Operational \& Environmental Tests and Corresponding Requirements} - \begin{tabular}{|c|c|} + \begin{tabular}{cc} \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ \midrule % Operational and Environmental @@ -1509,7 +1030,7 @@ \subsubsection{Usability \& Humanity} \begin{table}[H] \centering \caption{Maintenance \& Support Tests and Corresponding Requirements} - \begin{tabular}{|c|c|} + \begin{tabular}{cc} \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ \midrule % Maintenance and Support @@ -1521,43 +1042,22 @@ \subsubsection{Usability \& Humanity} \end{tabular} \end{table} - \begin{table}[H] - \centering - \caption{Security Tests and Corresponding Requirements} - \begin{tabular}{|c|c|} - \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ - \midrule - % Security - SRT-1 & SR-AR 1 \\ - SRT-2 & SR-AR 2 \\ - SRT-3 & SR-IR 1 \\ - SRT-4 & SR-PR 1 \\ - SRT-5 & SR-PR 2 \\ - SRT-6 & SR-AUR 1 \\ - SRT-7 & SR-AUR 2 \\ - SRT-8 & SR-IM 1 \\ - \bottomrule - \end{tabular} - \end{table} +\begin{table}[H] + \centering + \caption{Security Tests and Corresponding Requirements} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + SRT-1 & SR-IM 1 \\ + \bottomrule + \end{tabular} +\end{table} - \begin{table}[H] - \centering - \caption{Cultural Tests and Corresponding Requirements} - \begin{tabular}{|c|c|} - \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ - \midrule - % Cultural - CULT-1 & CULT 1 \\ - CULT-2 & CULT 2 \\ - CULT-3 & CULT 3 \\ - \bottomrule - \end{tabular} - \end{table} \begin{table}[H] \centering \caption{Compliance Tests and Corresponding Requirements} - \begin{tabular}{|c|c|} + \begin{tabular}{cc} \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ \midrule % Compliance @@ -1567,9 +1067,7 @@ \subsubsection{Usability \& Humanity} \end{tabular} \end{table} - \newpage - - \section{Unit Test Description} + \newpage\section{Unit Test Description} \wss{This section should not be filled in until after the MIS (detailed design document) has been completed.} @@ -1645,7 +1143,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/controllers/test_analyzer_controller.py}{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/controllers/test_analyzer_controller.py}{here}. \subsubsection{String Concatenation in a Loop} @@ -1734,7 +1232,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/analyzers/test_str_concat_in_loop.py}{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/analyzers/test_str_concat_analyzer.py}{here}. \subsubsection{Long Element Chain} @@ -1816,7 +1314,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/analyzers/test_detect_lec.py}{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/analyzers/test_long_element_chain_analyzer.py}{here}. \subsubsection{Repeated Calls} @@ -1889,7 +1387,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/analyzers/test_detect_repeated_calls.py}{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/analyzers/test_repeated_calls_analyzer.py}{here}. \subsubsection{Long Message Chain} @@ -1906,47 +1404,64 @@ \subsubsection{Usability \& Humanity} \noindent\textbf{Target requirement(s):} FR2 ~\cite{SRS} \\ \begin{itemize} - \item \textbf{Detects exact five calls chain} \newline - Ensures that a method chain with exactly five calls is flagged. + \item \textbf{Detects exact five calls chain} + \begin{itemize} + \item Ensures that a method chain with exactly five calls is flagged + \end{itemize} - \item \textbf{Detects six calls chain} \newline - Verifies that a chain with six method calls is detected as a smell. + \item \textbf{Detects six calls chain} + \begin{itemize} + \item Verifies that a chain with six method calls is detected as a smell + \end{itemize} - \item \textbf{Ignores chain of four calls} \newline - Ensures that a chain with only four calls (below threshold) is - not flagged. + \item \textbf{Ignores chain of four calls} + \begin{itemize} + \item Ensures that a chain with only four calls (below threshold) is not flagged + \end{itemize} - \item \textbf{Detects chain with attributes and calls} \newline - Tests detection of a chain that involves both attribute access - and method calls. + \item \textbf{Detects chain with attributes and calls} + \begin{itemize} + \item Tests detection of a chain that involves both attribute access and method calls + \end{itemize} - \item \textbf{Detects chain inside a loop} \newline - Ensures detection of a chain meeting the threshold when inside a loop. + \item \textbf{Detects chain inside a loop} + \begin{itemize} + \item Ensures detection of a chain meeting the threshold when inside a loop + \end{itemize} - \item \textbf{Detects multiple chains on one line} \newline - Verifies that only the first long chain on a single line is reported. + \item \textbf{Detects multiple chains on one line} + \begin{itemize} + \item Verifies that only the first long chain on a single line is reported + \end{itemize} - \item \textbf{Ignores separate statements} \newline - Ensures that separate method calls across multiple statements - are not mistakenly combined into a single chain. + \item \textbf{Ignores separate statements} + \begin{itemize} + \item Ensures that separate method calls across multiple statements are not mistakenly combined + \end{itemize} - \item \textbf{Ignores short chain comprehension} \newline - Ensures that a short chain within a list comprehension is not flagged. + \item \textbf{Ignores short chain comprehension} + \begin{itemize} + \item Ensures that a short chain within a list comprehension is not flagged + \end{itemize} - \item \textbf{Detects long chain comprehension} \newline - Verifies that a list comprehension with a long method chain is detected. + \item \textbf{Detects long chain comprehension} + \begin{itemize} + \item Verifies that a list comprehension with a long method chain is detected + \end{itemize} - \item \textbf{Detects five separate long chains} \newline - Ensures that multiple long chains on separate lines within the - same function are individually detected. + \item \textbf{Detects five separate long chains} + \begin{itemize} + \item Ensures that multiple long chains on separate lines within the same function are individually detected + \end{itemize} - \item \textbf{Ignores element access chains} \newline - Confirms that attribute and index lookups without method calls - are not flagged. - \end{itemize} + \item \textbf{Ignores element access chains} + \begin{itemize} + \item Confirms that attribute and index lookups without method calls are not flagged + \end{itemize} +\end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/analyzers/test_long_message_chain.py}{here} + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/analyzers/test_long_message_chain_analyzer.py}{here} \subsubsection{Long Lambda Element} @@ -1974,45 +1489,52 @@ \subsubsection{Usability \& Humanity} \noindent\textbf{Target requirement(s):} FR2 ~\cite{SRS} \\ \begin{itemize} - \item \textbf{No lambdas present} \newline - Ensures that when no lambda functions exist in the code, no - smells are detected. - - \item \textbf{Short single lambda} \newline - Confirms that a single short lambda (well under the length - threshold) with only one expression is not flagged. - - \item \textbf{Lambda exceeding expression count} \newline - Detects a lambda function that contains multiple expressions, - exceeding the threshold for complexity. - - \item \textbf{Lambda exceeding character length} \newline - Identifies a lambda function that surpasses the maximum allowed - character length, making it difficult to read. - - \item \textbf{Lambda exceeding both thresholds} \newline - Flags a lambda function that is both too long in character - length and contains too many expressions. - - \item \textbf{Nested lambda functions} \newline - Ensures that both outer and inner nested lambdas are properly - detected as long expressions. - - \item \textbf{Inline lambda passed to function} \newline - Detects lambda functions that are passed inline to functions - like \texttt{map} and \texttt{filter} when they exceed the - complexity thresholds. - - \item \textbf{Trivially short lambda function} \newline - Verifies that degenerate cases, such as a lambda with no real - body or trivial operations, are not mistakenly flagged. - \end{itemize} + \item \textbf{No lambdas present} + \begin{itemize} + \item Ensures that when no lambda functions exist in the code, no smells are detected + \end{itemize} - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/analyzers/test_long_lambda_element.py}{here} + \item \textbf{Short single lambda} + \begin{itemize} + \item Confirms that a single short lambda (well under the length threshold) with only one expression is not flagged + \end{itemize} - \subsection{CodeCarbon Measurement Module} - \textbf{Goal:} The CodeCarbon Measurement module is designed to + \item \textbf{Lambda exceeding expression count} + \begin{itemize} + \item Detects a lambda function that contains multiple expressions, exceeding the threshold for complexity + \end{itemize} + + \item \textbf{Lambda exceeding character length} + \begin{itemize} + \item Identifies a lambda function that surpasses the maximum allowed character length, making it difficult to read + \end{itemize} + + \item \textbf{Lambda exceeding both thresholds} + \begin{itemize} + \item Flags a lambda function that is both too long in character length and contains too many expressions + \end{itemize} + + \item \textbf{Nested lambda functions} + \begin{itemize} + \item Ensures that both outer and inner nested lambdas are properly detected as long expressions + \end{itemize} + + \item \textbf{Inline lambda passed to function} + \begin{itemize} + \item Detects lambda functions that are passed inline to functions like \texttt{map} and \texttt{filter} when they exceed the complexity thresholds + \end{itemize} + + \item \textbf{Trivially short lambda function} + \begin{itemize} + \item Verifies that degenerate cases, such as a lambda with no real body or trivial operations, are not mistakenly flagged + \end{itemize} +\end{itemize} + + \noindent The test cases for this module can be found + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/analyzers/test_long_lambda_element_analyzer.py}{here} + + \subsection{CodeCarbon Measurement Module} + \textbf{Goal:} The CodeCarbon Measurement module is designed to measure the carbon emissions associated with running a specific piece of code. It integrates with the CodeCarbon library, which calculates the energy consumption based on the execution of a @@ -2027,50 +1549,46 @@ \subsubsection{Usability \& Humanity} \noindent \textbf{Target requirement(s):} FR5, FR6,PR-RFT1, PR-SCR1~\cite{SRS} \\ - \begin{itemize} - \item \textbf{Handle CodeCarbon Measurements with a Valid File Path} - \begin{itemize} - \item When a valid file path is provided, the system - correctly invokes the subprocess for CodeCarbon. - \item The start and stop API endpoints of the - EmissionsTracker are called, and a success message is logged. - \end{itemize} +\begin{itemize} + \item \textbf{Successful Energy Measurement} + \begin{itemize} + \item Verifies correct emissions tracking when CodeCarbon returns valid float values + \item Confirms proper subprocess execution and tracker API calls + \item Ensures emissions value is stored in the meter instance + \end{itemize} - \item \textbf{Handle CodeCarbon Measurements with a Valid File - Path that Causes a Subprocess Failure} - \begin{itemize} - \item The subprocess is invoked even if an error occurs - during the file execution. - \item The system logs an error message and the emissions data - is set to None when execution fails. - \end{itemize} + \item \textbf{Null Emissions Handling} + \begin{itemize} + \item Validates system behavior when CodeCarbon returns None + \item Confirms meter stores None without errors + \end{itemize} - \item \textbf{Results Produced by CodeCarbon Run at a Valid CSV - File Path and Can Be Read} - \begin{itemize} - \item The emissions data can be read successfully from a - valid CSV file produced by CodeCarbon. - \item The function returns the last row of emissions data. - \end{itemize} + \item \textbf{Unexpected Emissions Type Handling} + \begin{itemize} + \item Tests proper logging and null conversion for non-float/non-None returns + \item Specifically verifies handling of string and NaN values + \end{itemize} - \item \textbf{Results Produced by CodeCarbon Run at a Valid CSV - File Path but the File Cannot Be Read} - \begin{itemize} - \item An error message is logged when the CSV file cannot be read. - \item The function returns \texttt{None} if reading the CSV file fails. - \end{itemize} + \item \textbf{Subprocess Failure Resilience} + \begin{itemize} + \item Confirms system logs errors but preserves emissions data when subprocess fails + \item Verifies tracker still stops properly after subprocess exceptions + \end{itemize} - \item \textbf{Given CSV Path for Results Produced by CodeCarbon - Does Not Have a File} - \begin{itemize} - \item When the given CSV path does not point to an existing - file, an error message is logged. - \item The function returns \texttt{None} when the file is missing. - \end{itemize} - \end{itemize} + \item \textbf{CSV Data Extraction} + \begin{itemize} + \item Validates correct parsing of multi-row emissions CSV files + \item Ensures last row is properly returned as current emissions + \end{itemize} - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/src/ecooptimizer/measurements/codecarbon_energy_meter.py}{here}. + \item \textbf{Missing Emissions File Handling} + \begin{itemize} + \item Tests proper error logging when emissions file is missing + \item Verifies None is returned and stored in emissions\_data + \end{itemize} +\end{itemize} + +\noindent The test cases for this module can be found \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/src/ecooptimizer/measurements/codecarbon_energy_meter.py}{here}. \subsection{Refactoring Module} @@ -2124,7 +1642,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/controllers/test_refactorer_controller.py}{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/controllers/test_refactorer_controller.py}{here}. \subsubsection{String Concatenation in a Loop} @@ -2187,7 +1705,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/refactorers/test_str_concat_in_loop_refactor.py}{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/refactorers/test_str_concat_in_loop_refactor.py}{here}. \subsubsection{Long Element Chain} @@ -2250,7 +1768,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/refactorers/test_long_element_chain.py}{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/refactorers/test_long_element_chain_refactor.py}{here}. \subsubsection{Member Ignoring Method} @@ -2319,7 +1837,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/refactorers/test_member_ignoring_method.py}{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/refactorers/test_member_ignoring_method.py}{here}. \subsubsection{Use a Generator} @@ -2383,7 +1901,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/refactorers/test_list_comp_any_all_refactor.py}{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/refactorers/test_list_comp_any_all_refactor.py}{here}. \subsubsection{Cache Repeated Calls} @@ -2455,7 +1973,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/refactorers/test_repeated_calls.py}{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/refactorers/test_repeated_calls.py}{here}. \subsubsection{Long Parameter List} @@ -2472,7 +1990,7 @@ \subsubsection{Usability \& Humanity} parameter instances. Similarly, corresponding calls to these functions as well as references to original parameters are preserved. The refactored result also preserves use of default - values in function signature and positional arguments in function calls.x\\ + values in function signature and positional arguments in function calls.\\ \noindent \textbf{Target requirement(s):} FR3, FR6~\cite{SRS} \\ @@ -2535,8 +2053,7 @@ \subsubsection{Usability \& Humanity} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/refactorers/test_long_parameter_list_refactor.py - }{here}. + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/refactorers/test_long_parameter_list_refactor.py}{here}. \subsubsection{Long Message Chain} @@ -2563,38 +2080,44 @@ \subsubsection{Usability \& Humanity} \noindent \textbf{Target requirement(s):} FR5, FR6, FR3 ~\cite{SRS} \\ \begin{itemize} - \item \textbf{Basic method chain refactoring} \newline - Ensures that a simple method chain is refactored correctly into - separate intermediate variables. - - \item \textbf{F-string chain refactoring} \newline - Verifies that method chains applied to f-strings are properly - broken down while preserving correctness. - - \item \textbf{Modifications even if the chain is not long} \newline - Ensures that method chains are refactored consistently, even if - they do not exceed the length threshold. - - \item \textbf{Proper indentation preserved} \newline - Confirms that the refactored code maintains the correct - indentation when inside a block statement such as an - \texttt{if} condition. - - \item \textbf{Method chain with arguments} \newline - Tests that method chains containing arguments (e.g., - \texttt{replace("H", "J")}) are correctly refactored. - - \item \textbf{Print statement preservation} \newline - Ensures that method chains within a \texttt{print} statement - are refactored without altering their functionality. - - \item \textbf{Nested method chains} \newline - Verifies that nested method chains (e.g., method calls on - method results) are properly refactored into intermediate variables. + \item \textbf{Basic method chain refactoring} + \begin{itemize} + \item Ensures that a simple method chain is refactored correctly into separate intermediate variables. + \end{itemize} + + \item \textbf{F-string chain refactoring} + \begin{itemize} + \item Verifies that method chains applied to f-strings are properly broken down while preserving correctness. + \end{itemize} + + \item \textbf{Modifications even if the chain is not long} + \begin{itemize} + \item Ensures that method chains are refactored consistently, even if they do not exceed the length threshold. + \end{itemize} + + \item \textbf{Proper indentation preserved} + \begin{itemize} + \item Confirms that the refactored code maintains the correct indentation when inside a block statement such as an \texttt{if} condition. + \end{itemize} + + \item \textbf{Method chain with arguments} + \begin{itemize} + \item Tests that method chains containing arguments (e.g., \texttt{replace("H", "J")}) are correctly refactored. + \end{itemize} + + \item \textbf{Print statement preservation} + \begin{itemize} + \item Ensures that method chains within a \texttt{print} statement are refactored without altering their functionality. + \end{itemize} + + \item \textbf{Nested method chains} + \begin{itemize} + \item Verifies that nested method chains (e.g., method calls on method results) are properly refactored into intermediate variables. + \end{itemize} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/refactorers/test_long_element_chain.py}{here} + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/refactorers/test_long_message_chain_refactoring.py}{here} \subsubsection{Long Lambda Element} @@ -2623,706 +2146,774 @@ \subsubsection{Usability \& Humanity} \noindent \textbf{Target requirement(s):} FR5, FR6, FR3 ~\cite{SRS} \\ \begin{itemize} - \item \textbf{Basic lambda conversion} \newline - Verifies that a simple single-line lambda expression is - correctly converted into a named function with proper - indentation and structure. - - \item \textbf{No extra print statements} \newline - Ensures that the refactoring process does not introduce - unnecessary print statements when converting lambda expressions. - - \item \textbf{Lambda in function argument} \newline - Tests that lambda expressions used as arguments to other - functions (e.g., in \texttt{map()} calls) are properly - refactored while maintaining the original function call structure. - - \item \textbf{Multi-argument lambda} \newline - Verifies that lambda expressions with multiple parameters are - correctly converted into named functions with the appropriate - parameter list. - - \item \textbf{Lambda with keyword arguments} \newline - Ensures that lambda expressions used as keyword arguments in - function calls are properly refactored while preserving the - original keyword argument syntax and indentation. - - \item \textbf{Very long lambda function} \newline - Tests the refactoring of complex, multi-line lambda expressions - with extensive mathematical operations, verifying that the - converted function maintains the original logic and structure. + \item \textbf{Basic lambda conversion} + \begin{itemize} + \item Verifies that a simple single-line lambda expression is correctly converted into a named function with proper indentation and structure. + \end{itemize} + + \item \textbf{No extra print statements} + \begin{itemize} + \item Ensures that the refactoring process does not introduce unnecessary print statements when converting lambda expressions. + \end{itemize} + + \item \textbf{Lambda in function argument} + \begin{itemize} + \item Tests that lambda expressions used as arguments to other functions (e.g., in \texttt{map()} calls) are properly refactored while maintaining the original function call structure. + \end{itemize} + + \item \textbf{Multi-argument lambda} + \begin{itemize} + \item Verifies that lambda expressions with multiple parameters are correctly converted into named functions with the appropriate parameter list. + \end{itemize} + + \item \textbf{Lambda with keyword arguments} + \begin{itemize} + \item Ensures that lambda expressions used as keyword arguments in function calls are properly refactored while preserving the original keyword argument syntax and indentation. + \end{itemize} + + \item \textbf{Very long lambda function} + \begin{itemize} + \item Tests the refactoring of complex, multi-line lambda expressions with extensive mathematical operations, verifying that the converted function maintains the original logic and structure. + \end{itemize} \end{itemize} \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/refactorers/test_long_lambda_element_refactoring.py}{here} + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/tests/refactorers/test_long_lambda_element_refactoring.py}{here} - \subsection{VsCode Plugin} +\subsection{VsCode Plugin} - \subsubsection{Detect Smells Command} +\subsubsection{Configure Workspace Command} - \textbf{Goal:} The detect smells command is responsible for - initiating the smell detection process, retrieving results from the - backend, and ensuring proper highlighting in the VS Code editor. - The command must handle various scenarios, including caching, - missing editor instances, and server failures, while providing - meaningful feedback to the user. The following unit tests verify - its accuracy.\\ +\textbf{Goal:} The configure workspace command identifies valid workspace folders containing Python files and prompts the user to select one. Upon selection, the workspace is marked as configured and saved to persistent state for future operations. - \noindent The tests assess the correct fetching and caching of - smells, proper interaction with the highlighting module, handling - of missing files or inactive editors, and the system's ability to - recover from server downtime. Edge cases such as rapidly changing - file hashes and updates to enabled smells are also considered.\\ - - \noindent\textbf{Target requirement(s):} FR10, OER-IAS1~\cite{SRS} \\ +\medskip - \begin{itemize} - \item \textbf{Handling of Missing Active Editor} - \begin{itemize} - \item The command shows an error message when no active editor is found. - \end{itemize} +\noindent The tests validate that valid workspace folders are detected, Python files are identified correctly, user selections are respected, and appropriate updates are made to both VS Code context and extension state. - \item \textbf{Handling of Missing File Path} - \begin{itemize} - \item The command shows an error message when the active - editor has no valid file path. - \end{itemize} +\medskip - \item \textbf{Handling of No Enabled Smells} - \begin{itemize} - \item The command shows a warning message when no smells are - enabled in the configuration. - \end{itemize} +\noindent\textbf{Target requirement(s):} FR1, FR2~\cite{SRS} - \item \textbf{Using Cached Smells} - \begin{itemize} - \item The command uses cached smells when the file hash and - enabled smells match the cached data. - \item The command highlights the cached smells in the editor. - \end{itemize} +\begin{itemize} + \item \textbf{Folder Scanning} + \begin{itemize} + \item Detects top-level and nested directories containing \texttt{.py} files. + \item Correctly identifies directories with Python entry points (e.g., \texttt{main.py} or \texttt{\_\_init\_\_.py}). + \end{itemize} - \item \textbf{Fetching New Smells} - \begin{itemize} - \item The command fetches new smells when the file hash - changes or enabled smells are updated. - \item The command updates the cache with the new smells and - highlights them in the editor. - \end{itemize} + \item \textbf{Quick Pick Interaction} + \begin{itemize} + \item Displays a list of valid Python folders. + \item Accepts user selection and confirms configuration. + \end{itemize} - \item \textbf{Handling of Server Downtime} - \begin{itemize} - \item The command shows a warning message when the server is - down and no cached smells are available. - \end{itemize} + \item \textbf{Workspace State Update} + \begin{itemize} + \item Stores selected folder path under the configured workspace key. + \item Sets VS Code context key \texttt{workspaceState.workspaceConfigured} to true. + \end{itemize} - \item \textbf{Highlighting Smells} - \begin{itemize} - \item The command highlights detected smells in the editor - when smells are found. - \item The command shows a success message with the number of - highlighted smells. - \end{itemize} - \end{itemize} + \item \textbf{Feedback to User} + \begin{itemize} + \item Shows information message indicating selected folder. + \end{itemize} +\end{itemize} - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/plugin-multi-file/test/commands/detectSmells.test.ts}{here}. +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/commands/configureWorkspace.test.ts}{here}. - \subsubsection{Refactor Smells Command} +\subsubsection{Reset Configuration Command} - \textbf{Goal:} The refactorSmell command is responsible for - refactoring code areas identified as "smells" in a project. It - works by refactoring areas in code that could benefit from - refactoring (smells) that are chosen by the user. The process - involves multiple steps, including saving the file, calling a - backend refactoring service to refactor the identified smell, - updating any relevant data, and initiating a refactor preview to the user.\\ +\textbf{Goal:} The reset configuration command prompts the user for confirmation and, if accepted, clears the stored workspace path and resets the internal plugin context to an unconfigured state. - \noindent The tests assess the correct fetching and caching of - smells, proper interaction with the highlighting module, handling - of missing files or inactive editors, and the system's ability to - recover from server downtime. Edge cases such as rapidly changing - file hashes and updates to enabled smells are also considered.\\ +\medskip - \noindent\textbf{Target requirement(s):} FR5, FR6, FR10, PR-RFT1, - PR-RFT2 ~\cite{SRS} \\ +\noindent The tests verify that the workspace state is properly reset only when the user confirms the action. The system must also update the relevant VS Code context key to reflect the unconfigured state. - \begin{itemize} - \item \textbf{No Active Editor Found} - \begin{itemize} - \item The command correctly handles the case where there is - no active editor open. - \item An appropriate error message is shown when no editor or - file path is available. - \end{itemize} +\medskip - \item \textbf{Attempting to Refactor When No Smells Are Detected} - \begin{itemize} - \item The command does not proceed when no smells are - detected in the file. - \item An error message is shown indicating that no smells are - detected for refactoring. - \end{itemize} +\noindent\textbf{Target requirement(s):} FR3~\cite{SRS} - \item \textbf{Attempting to Refactor When Selected Line Doesn’t - Match Any Smell} - \begin{itemize} - \item The command doesn't proceed if the selected line - doesn't match any detected smell. - \item An error message is shown to inform the user that no - matching smell was found for refactoring. - \end{itemize} +\begin{itemize} + \item \textbf{User Confirmation} + \begin{itemize} + \item Prompts user with a warning message before clearing configuration. + \end{itemize} - \item \textbf{Refactoring a Smell When Found on the Selected Line} - \begin{itemize} - \item The command successfully saves the current file and - triggers the refactoring of a detected smell. - \item The \texttt{refactorSmell} method is called with the - correct parameters, and the refactored preview is shown to the user. - \end{itemize} + \item \textbf{Workspace State Reset} + \begin{itemize} + \item Clears the stored workspace path from extension state. + \end{itemize} - \item \textbf{Handling API Failure During Refactoring} - \begin{itemize} - \item The command gracefully handles API failures during the - refactoring process. - \item An error message is displayed to the user if - refactoring fails, with the appropriate details logged. - \end{itemize} - \end{itemize} + \item \textbf{Context Reset} + \begin{itemize} + \item Updates VS Code context key \texttt{workspaceState.workspaceConfigured} to false. + \end{itemize} - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/plugin-multi-file/test/commands/refactorSmell.test.ts}{here}. + \item \textbf{Cancel Handling} + \begin{itemize} + \item Skips reset process if the user cancels the confirmation dialog. + \end{itemize} +\end{itemize} - \subsubsection{Document Hashing} +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/commands/resetConfiguration.test.ts}{here}. - \textbf{Goal:} The document hashing module is responsible for - generating and managing document hashes to track changes in files. - By ensuring efficient tracking, this module allows caching - mechanisms to work correctly and prevents unnecessary reprocessing. - The following unit tests validate its correctness.\\ +\subsubsection{File and Folder Smell Detection Commands} - \noindent The tests verify the module’s ability to detect file - modifications, handle new files, and prevent redundant updates when - no changes occur. Edge cases such as rapid sequential edits, hash - mismatches, and multiple concurrent document updates are also considered.\\ +\textbf{Goal:} The \texttt{detectSmellsFile} and \texttt{detectSmellsFolder} commands are responsible for initiating the detection of code smells in individual files and entire directories, respectively. These commands coordinate the interaction between the cache system, backend smell detection API, and the UI rendering logic within the SmellsViewProvider. - \noindent\textbf{Target requirement(s):} FR10, OER-IAS1~\cite{SRS} \\ +\medskip - \begin{itemize} - \item \textbf{Handling of Unchanged Document Hashes} - \begin{itemize} - \item The module does not update the workspace storage if the - document hash has not changed. - \item The existing hash is retained for the document. - \end{itemize} +\noindent These unit tests ensure robust handling of various scenarios, including invalid input files, empty folders, disabled smell settings, cached data reuse, server downtime, backend errors, and recursive directory scans. They also validate that user-facing messages, caching, and smell highlighting are executed correctly based on system state. - \item \textbf{Handling of Changed Document Hashes} - \begin{itemize} - \item The module updates the workspace storage when the - document hash changes. - \item The new hash is correctly calculated and stored. - \end{itemize} +\medskip - \item \textbf{Handling of New Documents} - \begin{itemize} - \item The module updates the workspace storage when no hash - exists for the document. - \item A new hash is generated and stored for the document. - \end{itemize} - \end{itemize} +\noindent\textbf{Target requirement(s):} FR2, FR3, FR15, OER-IAS2~\cite{SRS} \\ - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/plugin-multi-file/test/utils/hashDocs.test.ts}{here}. +\begin{itemize} + \item \textbf{Skipping Non-Python and Untitled Files} + \begin{itemize} + \item The file detection command ignores non-Python files and unsaved/untitled documents. + \end{itemize} - \subsubsection{File Highlighter} + \item \textbf{Using Cached Smells} + \begin{itemize} + \item Cached smells are reused when the file hash and settings match. + \item Cached smells are immediately rendered in the Smells View. + \end{itemize} - \textbf{Goal:} The file highlighter module enhances code visibility - by applying visual decorations to highlight detected code smells in - the editor. It ensures that identified issues are clearly - distinguishable while preserving readability. The following unit - tests verify the correctness of this functionality.\\ + \item \textbf{Fetching Smells from Backend} + \begin{itemize} + \item When no cache is available, the backend is called to fetch smells. + \item Retrieved smells are stored in the cache and displayed in the UI. + \end{itemize} - \noindent The tests assess the correct creation of decorations, - accurate application of highlighting based on detected smells, - proper handling of initial and subsequent highlights, and the - removal of outdated decorations. Edge cases such as overlapping - decorations and incorrect style applications are also considered.\\ + \item \textbf{Handling No Enabled Smells} + \begin{itemize} + \item A warning message is shown when no smells are enabled in the configuration. + \end{itemize} - \noindent\textbf{Target requirement(s):} FR10, OER-IAS1, LFR-AP2~\cite{SRS} \\ + \item \textbf{Handling No Smells Found} + \begin{itemize} + \item The tool displays a message indicating that the file has no detectable smells. + \item The cache is updated to reflect the empty result. + \end{itemize} - \begin{itemize} - \item \textbf{Creation of Decorations} - \begin{itemize} - \item Decorations are created with the correct color and - style for each type of code smell. - \item The decoration type is properly initialized and can be - applied to the editor. - \end{itemize} + \item \textbf{Handling API and Server Errors} + \begin{itemize} + \item Server-down conditions show appropriate warning messages. + \item API response failures result in error messages and a "failed" status in the UI. + \item Unexpected thrown exceptions are caught and logged to the output channel. + \end{itemize} - \item \textbf{Highlighting Smells} - \begin{itemize} - \item Smells are highlighted in the editor based on their - line occurrences. - \item The hover content for each smell is correctly - associated with the decoration. - \end{itemize} + \item \textbf{Folder Analysis and Recursion} + \begin{itemize} + \item The folder command scans recursively to identify `.py` files and shows progress. + \item A warning is shown if no Python files are found in the directory. + \item The total number of analyzed files is reported to the user. + \end{itemize} - \item \textbf{Handling of Initial Highlighting} - \begin{itemize} - \item On the first initialization, decorations are applied - without resetting existing ones. - \item The decorations are properly stored for future updates. - \end{itemize} + \item \textbf{Handling Folder Access Errors} + \begin{itemize} + \item Directory scan failures (e.g., permission errors) are caught and logged cleanly without crashing the extension. + \end{itemize} +\end{itemize} - \item \textbf{Resetting Decorations} - \begin{itemize} - \item On subsequent calls, existing decorations are disposed - of before applying new ones. - \item The reset process ensures no overlapping or redundant decorations. - \end{itemize} - \end{itemize} +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/commands/detectSmells.test.ts}{here}. - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/plugin-multi-file/test/ui/fileHighlighter.test.ts}{here}. +\subsubsection{Export Metrics Command} - \subsubsection{Hover Manager} +\textbf{Goal:} The export metrics command saves workspace-level energy metrics to a local JSON file. This test suite ensures it handles missing data, invalid paths, file vs. directory distinction, and file system errors gracefully. - \textbf{Goal:} The Hover Manager module manages hover functionality - for Python files, providing hover content for detected code smells - and allowing refactoring commands. The following unit tests verify - the accuracy of this functionality.\\ +\medskip - \noindent The tests assess the ability of the \texttt{HoverManager} - to register hover providers, handle hover content, update smells, - generate refactor commands, and ensure correct hover content - formatting. Edge cases, such as no smells and the correct - propagation of updates to smells, are also considered.\\ +\noindent The tests validate correct behavior across different workspace path types, proper access to extension state, and informative error messaging for common failure scenarios. - \noindent \textbf{Target requirement(s):} LFR-AP2~\cite{SRS} \\ +\medskip - \begin{itemize} - \item \textbf{Registers hover provider for Python files} - \begin{itemize} - \item Verifies that the \texttt{HoverManager} correctly - registers a hover provider for Python files. - \end{itemize} +\noindent\textbf{Target requirement(s):} FR6, FR15, OER-IAS3~\cite{SRS} \\ - \item \textbf{Subscribes hover provider correctly} - \begin{itemize} - \item Ensures that the hover provider is correctly subscribed - to the context manager. - \end{itemize} +\begin{itemize} + \item \textbf{No Metrics Data} + \begin{itemize} + \item The command shows an information message if there is no metrics data available to export. + \end{itemize} - \item \textbf{Returns null for hover content if there are no smells} - \begin{itemize} - \item Checks that \texttt{getHoverContent} returns - \texttt{null} when no smells are detected for a file. - \end{itemize} + \item \textbf{No Workspace Path Configured} + \begin{itemize} + \item The command shows an error message if the workspace path is missing or unset. + \end{itemize} - \item \textbf{Updates smells when \texttt{getInstance} is called again} - \begin{itemize} - \item Verifies that when \texttt{getInstance} is called again - with new smells, the manager updates the stored smells and - returns the same instance. - \end{itemize} + \item \textbf{Export to Workspace Directory} + \begin{itemize} + \item If the workspace path is a directory, the metrics JSON is saved directly inside it. + \item The user is notified of the output file location. + \end{itemize} - \item \textbf{Updates smells correctly} - \begin{itemize} - \item Confirms that \texttt{updateSmells} correctly updates - the list of smells in the manager. - \end{itemize} + \item \textbf{Export to Parent of File Path} + \begin{itemize} + \item If the workspace path is a file, the parent directory is used for export. + \end{itemize} - \item \textbf{Generates valid hover content} - \begin{itemize} - \item Ensures that \texttt{getHoverContent} generates valid - hover content with correctly formatted smell details, - including refactor commands and proper structure. - \end{itemize} + \item \textbf{Invalid Path Type Handling} + \begin{itemize} + \item The command shows an error message if the path type is unknown or unsupported. + \end{itemize} - \item \textbf{Registers refactor commands} - \begin{itemize} - \item Verifies that the refactor commands are properly - registered for individual and all smells of a specific type. - \end{itemize} - \end{itemize} + \item \textbf{Filesystem Access Errors} + \begin{itemize} + \item The command handles and reports errors when accessing the file system (e.g., stat failures). + \end{itemize} - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/plugin-multi-file/test/ui/hoverManager.test.ts}{here}. + \item \textbf{File Write Failures} + \begin{itemize} + \item If the write operation fails, the user is shown an error message indicating export failure. + \end{itemize} +\end{itemize} - \subsubsection{Line Selection Manager} +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/commands/exportMetricsData.test.ts}{here}. - \textbf{Goal:} The Line Selection Manager module provides - functionality for detecting and commenting on code smells based on - a line selection. The following unit tests verify the correctness - of this functionality.\\ +\subsubsection{Filter Smell Command Registration} - \noindent The tests assess the ability of the - \texttt{LineSelectionManager} to handle various scenarios such as - missing editor instances, multiple smells on a line, single-line - vs. multi-line selections, and correct comment generation. Edge - cases, such as mismatched document hashes, non-existent smells, and - the absence of selected text, are also considered.\\ +\textbf{Goal:} This command module registers all filter-related UI commands used to configure active smells and their parameters in the EcoOptimizer sidebar. The tests validate command registration, user interaction (e.g., input box), and the proper delegation to `FilterViewProvider`. - \noindent \textbf{Target requirement(s):} UHR-EOU1~\cite{SRS} \\ +\medskip - \begin{itemize} - \item \textbf{Removes last comment if decoration exists} - \begin{itemize} - \item Verifies that the last comment decoration is removed - correctly if one exists, ensuring that the decoration is - disposed of properly. - \end{itemize} +\noindent The tests ensure that smell toggling, option editing, mass selection, and default resets all call the correct provider methods and handle edge cases such as missing inputs or invalid user values. - \item \textbf{Does not proceed if no editor is provided} - \begin{itemize} - \item Ensures that no action is taken when - \texttt{commentLine} is called with \texttt{null} as the editor. - \end{itemize} +\medskip - \item \textbf{Does not add comment if no smells detected for file} - \begin{itemize} - \item Checks that no comment is added when no smells are - detected for the current file, confirming that no - unnecessary decorations are applied. - \end{itemize} +\noindent\textbf{Target requirement(s):} FR13, FR14, OER-IAS1~\cite{SRS} \\ - \item \textbf{Does not add comment if document hash does not match} - \begin{itemize} - \item Verifies that no comment is added when the document - hash in the workspace data does not match the hash of the - document, ensuring that the editor's state remains - consistent with the expected data. - \end{itemize} +\begin{itemize} + \item \textbf{Command Registration} + \begin{itemize} + \item Each command is correctly registered with VS Code using the expected command IDs. + \item All registered disposables are added to the extension context’s subscriptions. + \end{itemize} - \item \textbf{Does not add comment for multi-line selections} - \begin{itemize} - \item Tests that no comment is added when there is a - multi-line selection, ensuring that only single-line - selections are processed. - \end{itemize} + \item \textbf{Toggling Individual Smells} + \begin{itemize} + \item The command toggles a specific smell using \texttt{toggleSmell}. + \end{itemize} - \item \textbf{Does not add comment when no smells exist at line} - \begin{itemize} - \item Ensures that no comment is added when no smells are - associated with the selected line, preventing unnecessary - decorations from being applied. - \end{itemize} + \item \textbf{Editing Smell Options – Valid Input} + \begin{itemize} + \item The user is prompted for a new value via an input box. + \item The new numeric value is passed to \texttt{updateOption} and the filter view is refreshed. + \end{itemize} - \item \textbf{Displays single smell comment without count} - \begin{itemize} - \item Verifies that a single smell is displayed correctly - without a count, confirming that the decoration is applied - with the correct content format. - \end{itemize} + \item \textbf{Editing Smell Options – Invalid or Missing Input} + \begin{itemize} + \item If the user enters a non-numeric value, the option is not updated. + \item If the smell or option key is missing, an error message is shown. + \end{itemize} - \item \textbf{Adds a single-line comment if a smell is found} - \begin{itemize} - \item Confirms that a single-line comment is added correctly - when a smell is found on the selected line, ensuring proper - decoration application. - \end{itemize} + \item \textbf{Select/Deselect All Smells} + \begin{itemize} + \item The \texttt{selectAllFilterSmells} and \texttt{deselectAllFilterSmells} commands call \texttt{setAllSmellsEnabled(true/false)} respectively. + \end{itemize} - \item \textbf{Displays a combined comment if multiple smells exist} - \begin{itemize} - \item Verifies that a combined comment is displayed when - multiple smells exist on the same line. - \item Ensures that the decoration is created with the correct - formatting and applied to the correct range. - \end{itemize} - \end{itemize} + \item \textbf{Reset to Filter Defaults} + \begin{itemize} + \item The \texttt{setFilterDefaults} command calls \texttt{resetToDefaults} on the filter provider. + \end{itemize} +\end{itemize} - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/plugin-multi-file/test/ui/lineSelection.test.ts}{here}. +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/commands/filterSmells.test.ts}{here}. - \subsubsection{Handle Smells Settings} +\subsubsection{Refactor Workflow Commands} - \textbf{Goal:} The VS Code settings management module enables users - to customize detection settings, update enabled smells, and ensure - workspace consistency. This module integrates with the IDE to - provide real-time updates when settings change. The following unit - tests validate the correctness of this functionality.\\ +\textbf{Goal:} The refactoring workflow includes the core commands responsible for initiating, applying, and discarding refactorings. These tests verify that backend communication, session setup, user feedback, and file handling work correctly across both individual and batch refactor scenarios. - \noindent The tests ensure that enabled smells are correctly - retrieved from user configurations, updates to settings trigger the - appropriate notifications, and changes are accurately reflected in - the workspace. Additional test cases verify proper handling of - missing configurations, format conversions, and cache clearing - operations. Edge cases, such as unchanged settings and invalid - inputs, are also considered.\\ +\medskip - \noindent \textbf{Target requirement(s):} FR10, UHR-PSI1, UHR-EOU2, - OER-IAS1~\cite{SRS} \\ +\noindent This suite ensures refactor commands respect workspace configuration, gracefully handle backend issues, display energy savings, manage diff editors, and correctly update workspace state and metrics. Error handling for edge cases like file system failures and missing data is also validated. - \begin{itemize} - \item \textbf{Retrieving Enabled Smells} - \begin{itemize} - \item Ensures that the function retrieves all enabled smells - from the user's VS Code settings. - \item Validates that the function returns an empty object - when no smells are enabled. - \end{itemize} +\medskip - \item \textbf{Handling Updates to Smell Filters} - \begin{itemize} - \item Ensures that enabling a smell triggers a notification to the user. - \item Confirms that disabling a smell results in a proper - update message. - \item Validates that when no changes occur, no unnecessary - cache updates are performed. - \end{itemize} +\noindent\textbf{Target requirement(s):} FR3, FR4, FR15, OER-IAS4~\cite{SRS} \\ - \item \textbf{Clearing Cache on Settings Update} - \begin{itemize} - \item Ensures that enabling or disabling a smell triggers a - workspace cache wipe. - \item Confirms that cache clearing only occurs when actual - changes are made. - \end{itemize} +\begin{itemize} + \item \textbf{Workspace and Server Preconditions} + \begin{itemize} + \item Shows an error if the workspace is not configured. + \item Shows a warning if the backend server is unavailable. + \end{itemize} - \item \textbf{Formatting Smell Names} - \begin{itemize} - \item Ensures that smell names stored in kebab-case are - correctly formatted into a readable format. - \item Verifies that empty input results in an empty string - without errors. - \end{itemize} + \item \textbf{Refactoring Execution – Single Smell} + \begin{itemize} + \item Initiates refactoring for one smell using the backend. + \item Updates internal state and view providers. + \item Displays progress and success messages. + \end{itemize} - \item \textbf{Ensuring User-Friendly Notifications} - \begin{itemize} - \item Confirms that updates to smell settings provide clear, - informative messages. - \item Ensures that error handling follows polite and - constructive messaging principles. - \end{itemize} - \end{itemize} + \item \textbf{Refactoring Execution – All Smells of Same Type} + \begin{itemize} + \item Calls bulk API endpoint for all smells of the given type. + \item Displays type-based success messages. + \end{itemize} - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/plugin-multi-file/test/utils/handleSmellSettings.test.ts}{here}. + \item \textbf{Refactoring Failure Handling} + \begin{itemize} + \item Shows an error if the backend fails or throws. + \item Resets UI state and hides any open diff editors. + \end{itemize} - \subsubsection{Wipe Workspace Cache} + \item \textbf{Session Initialization via \texttt{startRefactorSession}} + \begin{itemize} + \item Opens a VS Code diff editor with original and refactored files. + \item Displays energy savings in an information message. + \item Handles missing energy savings values gracefully (e.g., N/A). + \end{itemize} - \textbf{Goal:} The "Wipe Workspace Cache" command is responsible - for clearing specific caches related to the workspace in a - development environment, primarily to reset the state of stored - data such as "smells" and file changes. It can be triggered for - different reasons, which determine which caches are cleared and how - the command behaves. It also updates file hashes for visible - editors when appropriate. Upon successful execution, a - corresponding success message is shown to the user. In case of an - error, an error message is displayed to the user.\\ + \item \textbf{Accepting Refactorings} + \begin{itemize} + \item Copies refactored files into the workspace. + \item Updates metrics data and clears smell cache for affected files. + \item Sets file status to "outdated" in the UI. + \item Handles missing session data or filesystem errors. + \end{itemize} - \noindent The tests ensure that appropriate caches are being - cleared as and when instructed.\\ + \item \textbf{Rejecting Refactorings} + \begin{itemize} + \item Cleans up session state and restores file status. + \item Handles and logs cleanup failures if they occur. + \end{itemize} +\end{itemize} - \noindent \textbf{Target requirement(s):} FR3, FR5, FR8~\cite{SRS} \\ +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/commands/refactorSmell.test.ts}{here}. - \begin{itemize} - \item \textbf{Wipe Cache with No Reason Provided} - \begin{itemize} - \item Only the "smells" cache is cleared when no reason is provided. - \item A success message indicating the workspace cache has - been successfully wiped is displayed. - \end{itemize} +\subsubsection{Wipe Workspace Cache Command} - \item \textbf{Wipe Cache with Reason "manual"} - \begin{itemize} - \item Both the "smells" and "file changes" caches are cleared - when the reason is "manual." - \item A success message indicating the workspace cache was - manually wiped is shown. - \end{itemize} +\textbf{Goal:} This command allows users to reset all cached smell data and file statuses for the current workspace. The tests ensure correct user confirmation, safe cache clearing, and accurate feedback messaging across all user interaction scenarios. - \item \textbf{Wipe Cache When No Files Are Open} - \begin{itemize} - \item The command correctly handles the case when there are - no open files. - \item A log message is generated indicating that no open - files are available to update. - \end{itemize} +\medskip - \item \textbf{Wipe Cache with Open Files} - \begin{itemize} - \item When there are open files, a message indicating the - number of visible files is logged. - \item The hashes for each open file are updated as expected. - \end{itemize} +\noindent This module’s functionality is essential for maintaining control over stale or outdated results, especially in long development sessions. The tests verify proper UI messaging, cancellation handling, and full cache cleanup when confirmed. - \item \textbf{Wipe Cache with Reason "settings"} - \begin{itemize} - \item Only the "smells" cache is cleared when the reason is "settings." - \item A success message is shown indicating the cache was - wiped due to changes in smell detection settings. - \end{itemize} +\medskip - \item \textbf{Wipe Cache When an Error Occurs} - \begin{itemize} - \item An error message is logged when an error occurs during - the cache wipe process. - \item a user-facing error message is displayed, indicating - the failure to wipe the workspace cache. - \end{itemize} - \end{itemize} +\noindent\textbf{Target requirement(s):} FR10, OER-IAS5~\cite{SRS} \\ - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/plugin-multi-file/test/commands/wipeWorkCache.test.ts}{here}. +\begin{itemize} + \item \textbf{Confirmation Prompt} + \begin{itemize} + \item A warning dialog is shown before clearing the workspace cache. + \item The dialog must include a modal and an explicit "Confirm" action. + \end{itemize} - \subsubsection{Backend} + \item \textbf{Cache Clearing and UI Refresh} + \begin{itemize} + \item If the user confirms, all cached smells are deleted. + \item The SmellsView is refreshed and statuses are reset. + \item A success message is shown after completion. + \end{itemize} - \textbf{Goal:} The backend handles interactions with the backend - server for tasks such as checking server status, initializing logs, - fetching detected smells, and refactoring those smells in the code.\\ + \item \textbf{Cancellation and Dismissal Handling} + \begin{itemize} + \item If the user cancels or dismisses the dialog, no cache operations are performed. + \item A message confirms that the operation was cancelled. + \end{itemize} - \noindent The tests ensure that the system correctly interacts with - the backend to check the server's status, initialize logging, fetch - code smells, and perform refactoring tasks. These tests confirm - that the server status is accurately updated based on successful or - failed responses, that log initialization behaves as expected under - different conditions, and that the system correctly handles and - processes detected smells for refactoring.\\ + \item \textbf{Non-Confirm Input Handling} + \begin{itemize} + \item If the user clicks any button other than "Confirm", the operation is treated as cancelled. + \end{itemize} - \noindent \textbf{Target requirement(s):} FR6, PR-SCR1, PR-RFT1, - PR-RFT2~\cite{SRS} \\ + \item \textbf{Message Validity} + \begin{itemize} + \item Success messages are shown only after the cache is successfully cleared. + \item Cancel messages are mutually exclusive with success messages. + \end{itemize} +\end{itemize} - \begin{itemize} - \item \textbf{Handle Server Status Check with Successful Response} - \begin{itemize} - \item When the server responds successfully, the status is - set to \texttt{ServerStatusType.UP}. - \item The correct update of server status to indicate that - the server is operational. - \end{itemize} +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/commands/wipeWorkCache.test.ts}{here}. - \item \textbf{Handle Server Status Check with Error or Failure} - \begin{itemize} - \item When the server responds with an error or fails to - respond, the status is set to \texttt{ServerStatusType.DOWN}. - \item Correctly handles a failed server response by ensuring - the status reflects the server's downtime. - \end{itemize} +\subsubsection{Workspace Modified Listener} - \item \textbf{Handle Initiation of Logs with Valid Directory Path (Success)} - \begin{itemize} - \item When a valid directory path is provided and the backend - responds successfully, the function returns \texttt{true}, - indicating successful log initialization. - \item System can successfully initialize logs with the - backend and sync them. - \end{itemize} +\textbf{Goal:} This listener monitors Python file changes and deletions within the configured workspace. Its responsibilities include invalidating outdated cache entries, updating UI statuses, and auto-triggering smell detection if "smell linting" is enabled. It also ensures resource cleanup upon disposal. - \item \textbf{Handle Initiation of Logs with Valid Directory Path (Failure)} - \begin{itemize} - \item When the backend fails to initialize logs, the function - returns false. - \item Properly handles to provide feedback if the log - initialization process fails. - \end{itemize} - \end{itemize} +\medskip - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/plugin-multi-file/test/api/backend.test.ts}{here}. +\noindent The following tests verify correct event handling on file saves, edits, and deletions. They also validate configuration checks, error handling, and the listener's lifecycle management. - \subsection{API Routes} +\medskip - \subsubsection{Smell Detection Endpoint} +\noindent\textbf{Target requirement(s):} FR10, FR16, OER-IAS5~\cite{SRS} \\ - \textbf{Goal:} The smell detection endpoint provides an API for - retrieving detected code smells from the backend. It ensures - efficient communication with the smell detection module while - handling errors gracefully. The following unit tests verify the - accuracy of this functionality.\\ +\begin{itemize} + \item \textbf{Initialization Behavior} + \begin{itemize} + \item Skips setup if no workspace path is configured. + \item Initializes file watcher for `.py` files when path is configured. + \end{itemize} - \noindent The tests assess the correctness of the endpoint’s - response structure, error handling for missing files, validation of - request data, and handling of internal exceptions. Edge cases, such - as malformed requests and empty responses, are also considered.\\ + \item \textbf{Handling File Changes} + \begin{itemize} + \item Clears smell cache and marks file as outdated if it exists in the cache. + \item Skips files that are not in the cache. + \item Logs error messages for cache invalidation failures. + \end{itemize} - \noindent\textbf{Target requirement(s):} FR10, OER-IAS1~\cite{SRS} \\ + \item \textbf{Handling File Deletions} + \begin{itemize} + \item Clears cache and removes file entry from view if file had cached smells. + \item Skips deletion logic if file was not cached. + \item Logs error if cache clearing fails. + \end{itemize} - \begin{itemize} - \item \textbf{Successful Detection of Smells} - \begin{itemize} - \item The API endpoint returns a successful response when the - file exists and smells are detected. - \item The response contains the correct number of detected - smells and adheres to the expected data structure. - \end{itemize} + \item \textbf{Smell Detection on Save} + \begin{itemize} + \item Triggers smell detection when a Python file is saved and smell linting is enabled. + \item Ignores non-Python files. + \end{itemize} - \item \textbf{Handling of File Not Found Errors} - \begin{itemize} - \item The API endpoint returns an appropriate error response - when the specified file does not exist. - \item The error message clearly indicates that the file was not found. - \end{itemize} + \item \textbf{Disposal} + \begin{itemize} + \item Disposes of both the file watcher and save listener properly. + \item Logs disposal confirmation. + \end{itemize} +\end{itemize} - \item \textbf{Handling of Internal Server Errors} - \begin{itemize} - \item The API endpoint returns an error response when an - unexpected exception occurs during smell detection. - \item The error message indicates an internal server error. - \end{itemize} +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/listeners/workspaceModifiedListener.test.ts}{here}. - \item \textbf{Validation of Input Data} - \begin{itemize} - \item The API validates the presence and correctness of - required fields in the request. - \item The API rejects invalid input with appropriate error messages. - \end{itemize} - \end{itemize} +\subsubsection{Backend Service Communication} - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/api/test_detect_route.py}{here}. +\textbf{Goal:} These backend API functions interact with the server for health checks, logging setup, smell detection, and smell refactoring. They must handle network issues gracefully, validate required inputs, and ensure proper feedback is logged in the output console. - \subsubsection{Refactoring Endpoint} +\medskip - \textbf{Goal:} The refactoring endpoint provides an API for - refactoring detected code smells by leveraging the backend - refactoring module. It ensures that refactored code is returned - efficiently while verifying energy savings. The following unit - tests validate the accuracy of this functionality.\\ +\noindent The following tests validate success and failure scenarios for each backend endpoint, including malformed requests, network errors, and missing workspace paths. They also verify correct request payloads and logging output. - \noindent The tests assess the correctness of refactored output, - proper retrieval of energy measurements, error handling for missing - source directories, and graceful failures when unexpected - conditions arise. Edge cases such as unsuccessful refactorings and - unchanged energy consumption are also considered.\\ +\medskip - \noindent\textbf{Target requirement(s):} FR10, OER-IAS1~\cite{SRS} \\ +\noindent\textbf{Target requirement(s):} FR2, FR3, FR6, FR10, OER-IAS2~\cite{SRS} - \begin{itemize} - \item \textbf{Successful Refactoring Process} - \begin{itemize} - \item The API endpoint returns a successful response when the - refactoring process completes without errors. - \item The response includes the refactored data and updated smells. - \item Energy measurements are correctly retrieved and - compared to ensure energy savings. - \end{itemize} +\begin{itemize} + \item \textbf{Server Health Check} + \begin{itemize} + \item Sets status to \texttt{UP} if `/health` responds successfully. + \item Sets status to \texttt{DOWN} on error or network failure, and logs the issue. + \end{itemize} - \item \textbf{Handling of Source Directory Not Found} - \begin{itemize} - \item The API endpoint returns an appropriate error response - when the specified source directory does not exist. - \item The error message clearly indicates that the directory - was not found. - \end{itemize} + \item \textbf{Logging Initialization} + \begin{itemize} + \item Sends proper payload to `/logs/init`. + \item Returns success on valid response. + \item Handles server or network errors with log messages and fallback. + \end{itemize} - \item \textbf{Handling of Energy Measurement Failures} - \begin{itemize} - \item The API endpoint returns an error response when initial - or final energy measurements cannot be retrieved. - \item The API endpoint returns an error response when no - energy savings are detected after refactoring. - \end{itemize} + \item \textbf{Smell Detection} + \begin{itemize} + \item Sends file path and smell configuration to `/smells`. + \item Parses and returns detected smells on success. + \item Throws clear errors and logs backend-provided details on failure. + \end{itemize} - \item \textbf{Handling of Unexpected Errors} - \begin{itemize} - \item The API endpoint returns an error response when an - unexpected exception occurs during the refactoring process. - \item The error message includes details about the exception. - \end{itemize} - \end{itemize} + \item \textbf{Refactor Single Smell} + \begin{itemize} + \item Sends smell and workspace path to `/refactor`. + \item Throws error when workspace path is missing. + \item Handles and logs both successful and failed backend responses. + \end{itemize} - \noindent The test cases for this module can be found - \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/new-poc/tests/api/test_refactoring.py}{here}. + \item \textbf{Refactor by Smell Type} + \begin{itemize} + \item Sends smell type and workspace path to `/refactor-by-type`. + \item Validates required fields and logs backend failures. + \end{itemize} +\end{itemize} + +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/api/backend.test.ts}{here}. + +\subsubsection{File Highlighter} + +\textbf{Goal:} The file highlighter decorates code editor lines based on detected smells using user-defined styling preferences (underline, border, flashlight, etc.). This module ensures that the VS Code UI reflects current cache data and user configuration, applying or clearing decorations dynamically. + +\medskip + +\noindent The tests verify correct singleton instantiation, dynamic decoration updates, conditional smell filtering, and visual style application across multiple configurations and editor scenarios. + +\medskip + +\noindent\textbf{Target requirement(s):} FR8, FR13, OER-IAS1~\cite{SRS} + +\begin{itemize} + \item \textbf{Singleton Instantiation} + \begin{itemize} + \item Ensures only one instance of the highlighter is created. + \end{itemize} + + \item \textbf{Highlight Update Triggers} + \begin{itemize} + \item Calls \texttt{highlightSmells} only for visible Python editors. + \item Filters files correctly in \texttt{updateHighlightsForFile}. + \end{itemize} + + \item \textbf{Highlight Rendering} + \begin{itemize} + \item Applies decorations for all enabled and valid smells. + \item Skips rendering if no data is cached or smell is disabled. + \item Ignores invalid line numbers. + \end{itemize} + + \item \textbf{Custom Decoration Styles} + \begin{itemize} + \item Supports underline, flashlight, and border-arrow styles. + \item Defaults to underline for unknown style keys. + \end{itemize} + + \item \textbf{Decoration Disposal} + \begin{itemize} + \item \texttt{resetHighlights()} clears all decorations and disposes them properly. + \end{itemize} +\end{itemize} + +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/ui/fileHighlighter.test.ts}{here}. + +\subsubsection{Hover Manager} + +\textbf{Goal:} The hover manager displays contextual smell information when the user hovers over affected lines in Python files. It enriches the user experience by providing inline guidance and actionable links to trigger refactorings. + +\medskip + +\noindent The tests verify correct registration of the hover provider, graceful degradation when conditions are unmet, and correct Markdown formatting and behavior for smells occurring on the hovered line. + +\medskip + +\noindent\textbf{Target requirement(s):} FR13, FR16, OER-IAS1~\cite{SRS} + +\begin{itemize} + \item \textbf{Provider Registration} + \begin{itemize} + \item Registers hover provider for \texttt{python} language files. + \item Adds registration to extension subscriptions. + \end{itemize} + + \item \textbf{Hover Preconditions} + \begin{itemize} + \item Returns nothing for non-Python files. + \item Returns nothing when no smells are cached. + \item Returns nothing if no smells occur on the hovered line. + \end{itemize} + + \item \textbf{Hover Display Logic} + \begin{itemize} + \item Creates and returns a \texttt{Hover} object with formatted message. + \item Displays smell description and a clickable refactor command. + \item Escapes special characters in Markdown to prevent formatting issues. + \end{itemize} +\end{itemize} + +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/ui/hoverManager.test.ts}{here}. + +\subsubsection{Line Selection Manager} + +\textbf{Goal:} The line selection manager adds inline decorations that summarize code smells present on the user's current line selection. It enhances feedback clarity while ensuring only one comment is shown at a time. + +\medskip + +\noindent The tests ensure that decoration is only applied to valid selections with associated smells, that it updates correctly when switching lines or clearing cache, and that decoration content reflects smell counts accurately. + +\medskip + +\noindent\textbf{Target requirement(s):} FR13, FR16, OER-IAS1~\cite{SRS} + +\begin{itemize} + \item \textbf{Initialization} + \begin{itemize} + \item Registers a callback on smell updates. + \item Initializes internal state to null decoration and null last line. + \end{itemize} + + \item \textbf{Comment Rendering} + \begin{itemize} + \item Skips rendering when no editor is active or selection is multiline. + \item Skips when no smells are cached or no smells match the selected line. + \item Skips if user selects the same line twice. + \item Adds a comment with the smell type if one smell is present. + \item Adds a comment with count when multiple smells exist. + \item Decorations appear as inline text after the selected line. + \end{itemize} + + \item \textbf{Comment Removal} + \begin{itemize} + \item Removes previous decorations before applying a new one. + \item Removes comment when cache is cleared for the current file or for all files. + \item Skips removal if unrelated file’s cache is cleared. + \end{itemize} +\end{itemize} + +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/ui/lineSelection.test.ts}{here}. + +\subsubsection{Cache Initialization} + +\textbf{Goal:} This module restores file statuses from previously cached analysis results when the extension is activated. It removes entries for deleted or out-of-scope files and updates the UI accordingly. + +\medskip + +\noindent The tests verify that cache entries outside the workspace or pointing to non-existent files are removed, and that remaining entries are properly restored into the UI. It also validates summary log reporting and gracefully handles missing workspace configuration. + +\medskip + +\noindent\textbf{Target requirement(s):} FR10, OER-CACHE1~\cite{SRS} + +\begin{itemize} + \item \textbf{No Workspace Configured} + \begin{itemize} + \item Skips initialization and logs a warning if no workspace path is set. + \end{itemize} + + \item \textbf{Removing Invalid Cache Entries} + \begin{itemize} + \item Removes entries for files outside the configured workspace. + \item Removes entries for files that are no longer present on disk. + \end{itemize} + + \item \textbf{Restoring Valid Cache} + \begin{itemize} + \item Files with smells get status \texttt{passed} and corresponding smells are injected. + \item Clean files are marked with status \texttt{no\_issues}. + \end{itemize} + + \item \textbf{Summary Logging} + \begin{itemize} + \item Logs how many files were restored, how many had smells, and how many were removed from the cache. + \end{itemize} +\end{itemize} + +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/utils/initializeStatusesFromCache.test.ts}{here}. + +\subsubsection{Smells Data Management} + +\textbf{Goal:} This module provides utilities for reading, parsing, and retrieving code smell configurations. It handles loading/saving JSON configurations, filtering enabled smells, and resolving smell metadata for hover/tooltips. + +\medskip + +\noindent The tests validate the integrity and correctness of the config loading and writing process, proper filtering of enabled smells, and lookup logic for acronyms, names, and descriptions based on message IDs. + +\medskip + +\noindent\textbf{Target requirement(s):} FR4, FR5, OER-CONFIG1~\cite{SRS} + +\begin{itemize} + \item \textbf{loadSmells} + \begin{itemize} + \item Successfully loads a smells configuration from disk. + \item Displays an error message if the file is missing or malformed. + \end{itemize} + + \item \textbf{saveSmells} + \begin{itemize} + \item Writes updated configuration to disk. + \item Displays an error message if the save operation fails. + \end{itemize} + + \item \textbf{getFilterSmells} + \begin{itemize} + \item Returns the full dictionary of loaded smells. + \end{itemize} + + \item \textbf{getEnabledSmells} + \begin{itemize} + \item Returns only smells marked as enabled. + \item Includes parsed analyzer options with correct types. + \end{itemize} + + \item \textbf{Metadata Resolvers} + \begin{itemize} + \item \texttt{getAcronymByMessageId} resolves acronyms. + \item \texttt{getNameByMessageId} resolves full names. + \item \texttt{getDescriptionByMessageId} resolves descriptions. + \end{itemize} +\end{itemize} + +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/utils/smellsData.test.ts}{here}. + +\subsubsection{Tracked Diff Editors} + +\textbf{Goal:} This module maintains a registry of active diff editors created during refactoring sessions. It provides utilities to register, query, and programmatically close diff tabs within the VS Code environment. + +\medskip + +\noindent The tests validate the correct registration and tracking of diff editors, accurate identification of tracked editors via URI comparison, and complete cleanup of tabs and memory state after closure operations. + +\medskip + +\noindent\textbf{Target requirement(s):} FR12, OER-IAS2~\cite{SRS} + +\begin{itemize} + \item \textbf{registerDiffEditor} + \begin{itemize} + \item Adds a URI pair to the tracked diff editors set. + \item Supports multiple pairs without interference. + \end{itemize} + + \item \textbf{isTrackedDiffEditor} + \begin{itemize} + \item Returns true only for previously registered URI pairs. + \item Fails gracefully for unregistered or mismatched pairs. + \item Is case-sensitive when comparing URI strings. + \end{itemize} + + \item \textbf{closeAllTrackedDiffEditors} + \begin{itemize} + \item Closes all diff tabs currently open in the workspace if they match tracked URIs. + \item Skips irrelevant tabs or malformed inputs. + \item Clears the internal tracked set after execution. + \end{itemize} +\end{itemize} + +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/utils/trackedDiffEditors.test.ts}{here}. + +\subsubsection{Refactor Action Buttons} + +\textbf{Goal:} These UI buttons provide users with the ability to accept or reject a proposed refactoring. They must be initialized correctly, displayed when a refactoring session is active, and hidden when the session ends. The buttons are tied to a VS Code context key used to control view behavior. + +\medskip + +\noindent The tests verify that the buttons are properly initialized and registered with the extension context, appear or disappear based on user interaction, and correctly set or reset the \texttt{refactoringInProgress} context variable. + +\medskip + +\noindent\textbf{Target requirement(s):} FR12~\cite{SRS} + +\begin{itemize} + \item \textbf{Button Visibility} + \begin{itemize} + \item The accept and reject buttons are shown when a refactoring session begins. + \item The buttons are hidden when the session ends or is cancelled. + \end{itemize} + + \item \textbf{Context Key Updates} + \begin{itemize} + \item \texttt{refactoringInProgress} is set to \texttt{true} when buttons are shown. + \item \texttt{refactoringInProgress} is set to \texttt{false} when buttons are hidden. + \end{itemize} + + \item \textbf{Subscription Registration} + \begin{itemize} + \item Buttons are registered to the extension context upon initialization. + \end{itemize} +\end{itemize} + +\noindent The test cases for this module can be found +\href{https://github.com/ssm-lab/capstone--sco-vs-code-plugin/blob/main/test/utils/refactorActionButtons.test.ts}{here}. % \subsection{Unit Testing Scope} @@ -3454,7 +3045,7 @@ \subsubsection{Usability \& Humanity} \subsection{Usability Survey Questions} \label{A.2} - See the surveys folder under \texttt{docs/Extras/UsabilityTesting}. + See the surveys folder under \href{https://github.com/ssm-lab/capstone--source-code-optimizer/tree/main/docs/Extras/UsabilityTesting/surveys}{\texttt{docs/Extras/UsabilityTesting}}. \newpage{} \section{Reflection} diff --git a/docs/VnVReport/README.md b/docs/VnVReport/README.md index f80df951..7910fca4 100644 --- a/docs/VnVReport/README.md +++ b/docs/VnVReport/README.md @@ -1,5 +1,44 @@ -# Test Report +# Verification and Validation Report Directory -The folders and files for this folder are as follows: +This directory contains the Verification and Validation (V&V) Reports for the Source Code Optimizer project, documenting test results and validation outcomes. -Describe ... +## Directory Contents + +### Files +- `README.md` - Documentation overview +- `Makefile` - Build configuration for documentation generation +- `VnVReport.tex` - LaTeX source for the V&V Report document + +## Major Components + +1. Test Results + - Unit Test Reports + - Integration Test Results + +2. Validation Results + - Requirements Coverage + +3. Analysis Reports + - Code Coverage Data + - Issue Tracking + +## Usage Guidelines + +1. Document Generation + - Use make to generate documentation + - Review generated reports + - Update test results + +2. Result Analysis + - Compare against requirements + - Track test coverage + - Document issues + +## Maintenance + +1. Regular Updates + - Track progress + - Document changes + +2. Quality Control + - Verify results diff --git a/docs/VnVReport/VnVReport.pdf b/docs/VnVReport/VnVReport.pdf index 75cd990d..0cdeb064 100644 Binary files a/docs/VnVReport/VnVReport.pdf and b/docs/VnVReport/VnVReport.pdf differ diff --git a/docs/VnVReport/VnVReport.tex b/docs/VnVReport/VnVReport.tex index 63782752..af3652fd 100644 --- a/docs/VnVReport/VnVReport.tex +++ b/docs/VnVReport/VnVReport.tex @@ -45,10 +45,19 @@ \section*{Revision History} -\begin{tabularx}{\textwidth}{p{3cm}p{2cm}X} - \toprule {\bf Date} & {\bf Version} & {\bf Notes}\\ - \midrule - March 8th, 2025 & 0.0 & Started VnV Report\\ +\begin{tabularx}{\textwidth}{p{4cm}p{4cm}X} + \toprule {\bf Date} & {\bf Name} & {\bf Notes}\\ + \midrule + March 8th, 2025 & All & Created initial revision of VnV Report\\ + April 3rd, 2025 & Nivetha Kuruparan & Heavily Revised VSCode Plugin Unit Tests\\ + April 10th, 2025 & Tanveer Brar & Updated code detection and refactoring suggestion tests\\ + April 10th, 2025 & Tanveer Brar & Updated remaining functional requirements tests\\ + April 10th, 2025 & Tanveer Brar & Updated unit tests for plugin\\ + April 10th, 2025 & Tanveer Brar & Added trace to requirements\\ + April 10th, 2025 & Tanveer Brar & Added trace to modules\\ + April 10th, 2025 & Tanveer Brar & Styling changes\\ + April 10th, 2025 & Tanveer Brar & Updated coverage metrics with new plugin tests\\ + April 10th, 2025 & Tanveer Brar & Addressed peer and TA feedback\\ \bottomrule \end{tabularx} @@ -82,12 +91,17 @@ \section*{Symbols, Abbreviations and Acronyms} \pagenumbering{arabic} -This Verification and Validation (V\&V) report outlines the testing +\newcommand{\SRS}{\href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/SRS/SRS.pdf}{SRS}} +\newcommand{\VnVPlan}{\href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/VnVPlan/VnVPlan.pdf}{VnV Plan}} + +\noindent This Verification and Validation (V\&V) report outlines the testing process used to ensure the accuracy, reliability, and performance of our system. It details our verification approach, test cases, and validation results, demonstrating that the system meets its requirements and functions as intended. Key findings and resolutions -are also discussed. +are also discussed. Recent updates to this document include comprehensive code coverage metrics for the VSCode extension frontend, improved traceability to requirements and modules, detailed test case descriptions for all functional requirements, and expanded explanations of code smells detection and refactoring. + +\noindent For detailed information about the project requirements and test case design methodology, please refer to the Software Requirements Specification (\SRS) document and the Verification and Validation Plan (\VnVPlan). The SRS contains comprehensive definitions of all requirements referenced in this report (including functional, non-functional, and operational requirements like OER-IAS), while the VnVPlan outlines the complete testing strategy and procedures employed during verification and validation activities. \section{Functional Requirements Evaluation} \subsection{Code Input Acceptance Tests} @@ -124,155 +138,92 @@ \subsection{Code Input Acceptance Tests} \end{enumerate} -\subsection{Code Smell Detection and Refactoring Suggestion (RS) Tests} -\begin{enumerate} - \item \textbf{test-FR-2 Code Smell Detection and Refactoring - Suggestion} \\[2mm] - The \textbf{code smell detection and refactoring tests} validate - the system’s ability to identify and refactor specific code - smells that impact energy efficiency. These tests ensure - compliance with \textbf{functional requirement FR2} and were - conducted through unit testing. - - The tester provided Python files containing common code smells - such as \textbf{long parameter lists, repeated function calls, - and inefficient string concatenation}. The \textbf{expected - result} was that the system would correctly detect these smells - and suggest appropriate refactoring strategies. The - \textbf{actual result} confirmed that the system successfully - identified all tested code smells, displayed warnings, and - provided optimization suggestions. More details can be found in - the unit tests. -\end{enumerate} +\subsection{Code Smell Detection Tests and Refactoring Suggestion (RS) Tests} +\label{subsec:code-smells-detection} -\subsection{Output Validation Tests} +This area includes tests to verify the detection and refactoring of specified code smells that impact energy efficiency. These tests will be done through unit testing. For a comprehensive list and explanation of all code smells supported by the system, see the code smells reference table in Section~\ref{tab:code-smells}. \begin{enumerate} - \item \textbf{test-FR-OV-1 Verification of Valid Python Output} \\[2mm] - The \textbf{output validation test} ensures that refactored - Python code remains syntactically correct and compliant with - Python standards. This validation is crucial for maintaining - \textbf{functional requirement FR3}, as it confirms that the - refactored code behaves identically to the original but with - improved efficiency. - - A Python file with detected code smells was refactored, and the - expected result was that the optimized code should pass a syntax - check and retain its original functionality. The \textbf{actual - result} confirmed that the refactored code was valid, passed - linting checks, and maintained correctness. + \item \textbf{test-FR-IA-1 Successful Refactoring Execution} \\[2mm] + \textbf{Control:} Automated \\ + \textbf{Initial State:} Tool is idle in the VS Code environment. \\ + \textbf{Input:} A valid Python file with a detectable code smell. \\ + \textbf{Output:} The system applies the appropriate refactoring and updates the code view. \\ + \textbf{Test Case Derivation:} Ensures the tool correctly identifies a smell (e.g., LEC001), chooses an applicable refactoring, and applies it successfully, per FR2 and FR3. \\ + \textbf{How test will be performed:} Provide a valid Python file containing a known smell, trigger refactoring via the VS Code interface, and confirm the output includes refactored code as expected. + + \item \textbf{test-FR-IA-2 No Available Refactorer Handling} \\[2mm] + \textbf{Control:} Automated \\ + \textbf{Initial State:} Tool is idle. \\ + \textbf{Input:} A valid Python file containing a code smell that does not yet have a supported refactorer. \\ + \textbf{Output:} The system does not apply changes and logs or displays an informative message. \\ + \textbf{Test Case Derivation:} Verifies that unsupported code smells are gracefully handled without errors, per FR2. \\ + \textbf{How test will be performed:} Provide a valid Python file with an unsupported smell and observe that the system notifies the user without attempting modification. + + \item \textbf{test-FR-IA-3 Multiple Refactoring Calls on Same File} \\[2mm] + \textbf{Control:} Automated \\ + \textbf{Initial State:} Tool is idle. \\ + \textbf{Input:} A valid Python file with a detectable code smell, refactored more than once. \\ + \textbf{Output:} The tool processes the file repeatedly and applies changes incrementally. \\ + \textbf{Test Case Derivation:} Confirms the system can handle repeated invocations and re-apply applicable refactorings, per FR3. \\ + \textbf{How test will be performed:} Refactor a file containing a supported smell multiple times and verify that each run performs valid operations and results in updated outputs. + + \item \textbf{test-FR-IA-4 Handling Empty Modified Files List} \\[2mm] + \textbf{Control:} Automated \\ + \textbf{Initial State:} Tool is idle. \\ + \textbf{Input:} A valid Python file where the code smell is detected, but the refactorer makes no modifications. \\ + \textbf{Output:} The system does not generate output files and notifies the user appropriately. \\ + \textbf{Test Case Derivation:} Confirms the tool handles no-op refactorers correctly, per FR4. \\ + \textbf{How test will be performed:} Supply a file where the refactorer returns an unchanged version of the code and verify that no new files are created and that appropriate feedback is displayed or logged. \end{enumerate} \subsection{Tests for Reporting Functionality} -The reporting functionality of the tool is a critical feature that -provides comprehensive insights into the refactoring process, -including detected code smells, applied refactorings, energy -consumption measurements, and test results. These tests ensure that -the reporting feature operates correctly and delivers accurate, -well-structured information as specified in \textbf{functional -requirement FR9}.\\ - -\noindent At this stage, the reporting functionality is still under -development, and testing has not yet been conducted. The tests -outlined below will be performed in \textbf{Revision 1} once the -reporting feature is fully implemented. - -\begin{enumerate} - \item \textbf{test-FR-RP-1 A Report With All Components Is Generated} \\[2mm] - This test ensures that the tool generates a comprehensive report - that includes all necessary information required by \textbf{FR9}. - The system should produce a structured summary of the refactoring - process, displaying detected code smells, applied refactorings, - and energy consumption metrics. - - \textbf{Planned Test Execution:} After refactoring, the tool will - invoke the report generation feature, and a user will validate - that the output meets the structure and content specifications. - - \item \textbf{test-FR-RP-2 Validation of Code Smell and Refactoring - Data in Report} \\[2mm] - This test will verify that the report correctly includes details - on detected code smells and refactorings, ensuring compliance - with \textbf{FR9}. - - \textbf{Planned Test Execution:} The tool will generate a report, - and its contents will be compared with the detected code smells - and refactorings to confirm accuracy. - - \item \textbf{test-FR-RP-3 Energy Consumption Metrics Included in - Report} \\[2mm] - This test will validate that the reporting feature correctly - includes energy consumption measurements before and after - refactoring, aligning with \textbf{FR9}. - - \textbf{Planned Test Execution:} A user will analyze the energy - consumption metrics in the generated report to ensure they - accurately reflect the measurements taken during the refactoring process. - - \item \textbf{test-FR-RP-4 Functionality Test Results Included in - Report} \\[2mm] - This test will ensure that the reporting functionality accurately - reflects the results of the test suite, summarizing test - pass/fail outcomes after refactoring. - - \textbf{Planned Test Execution:} The tool will generate a report, - and validation will be conducted to confirm that it includes a - summary of test results matching the actual execution outcomes. -\end{enumerate} -\subsection{Documentation Availability Tests} -The following tests will ensure that the necessary documentation is -available as per \textbf{FR10}. Since documentation is still under -development, these tests have not yet been conducted and will be -included in \textbf{Revision 1}. +The reporting functionality of the tool is crucial for providing users with meaningful insights into the energy impact of refactorings and the smells being addressed. This section outlines tests that ensure the energy metrics and refactoring summaries are accurately presented, as required by FR6 and FR15. \begin{enumerate} - \item \textbf{test-FR-DA-1 Test for Documentation Availability} \\[2mm] - This test verifies that the system provides proper documentation - covering installation, usage, and troubleshooting. - - \textbf{Planned Test Execution:} Review the documentation for - completeness, clarity, and accuracy, ensuring it meets \textbf{FR10}. + \item \textbf{test-FR-RP-1 Energy Consumption Metrics Displayed Post-Refactoring} \\[2mm] + \textbf{Control:} Manual \\ + \textbf{Initial State:} The tool has measured energy usage before and after refactoring. \\ + \textbf{Input:} Energy data collected for the original and refactored code. \\ + \textbf{Output:} A clear comparison of energy consumption is displayed in the UI. \\ + \textbf{Test Case Derivation:} Verifies that energy metrics are properly calculated and presented to users, as per FR6. \\ + \textbf{How test will be performed:} Refactor a file and review the visual or textual display of energy usage before and after, ensuring the values match backend logs. + + \item \textbf{test-FR-RP-2 Detected Code Smells and Refactorings Reflected in UI} \\[2mm] + \textbf{Control:} Manual \\ + \textbf{Initial State:} The tool has completed code analysis and refactoring. \\ + \textbf{Input:} Output of the detection and refactoring modules. \\ + \textbf{Output:} The user interface displays the detected code smells and associated refactorings clearly. \\ + \textbf{Test Case Derivation:} Ensures transparency of changes and supports informed decision-making by the user, in line with FR15. \\ + \textbf{How test will be performed:} Open a code file with detectable smells, trigger a refactor, and inspect the view displaying the summary of changes and available actions. \end{enumerate} -\subsection{IDE Extension Tests} -The following tests ensure that users can integrate the tool as a VS -Code extension in compliance with \textbf{FR11}. Local testing has -been conducted successfully, confirming the extension’s ability to -function within the development environment. Once all features are -implemented, the extension will be packaged and tested in a deployed -environment. -\begin{enumerate} - \item \textbf{test-FR-IE-1 Installation of Extension in Visual - Studio Code} \\[2mm] - This test ensures that the refactoring tool extension can be - installed from the Visual Studio Marketplace. +\subsection{Visual Studio Code Interactions} - \textbf{Test Execution:} The extension was installed locally, and - its presence in the Extensions View was confirmed. +This section corresponds to features related to the user's interaction with the Visual Studio Code extension interface, including previewing and toggling smells, customizing the UI, and reviewing code comparisons. These tests verify that the extension enables users to interact with refactorings in an intuitive and informative manner, as outlined in FR8, FR9, FR10, FR11, FR12, FR13, FR14, FR15, FR16, and FR17. - \textbf{Future Testing:} Once all features are implemented, the - extension will be zipped, packaged, and tested as a published extension. +These features are primarily tested through automated unit tests integrated in the extension codebase. For implementation and test details, please refer to the unit testing suite. - \item \textbf{test-FR-IE-2 Running the Extension in Visual Studio - Code} \\[2mm] - This test validates that the extension functions correctly within - the development environment, detecting code smells and suggesting - refactorings. +\subsection{Documentation Availability Tests} - \textbf{Test Execution:} Local tests confirmed that activating - the extension successfully detects code smells and applies refactorings. +The following test is designed to ensure the availability of documentation as per FR 7 and FR 5. - \textbf{Future Testing:} Once the extension is packaged, - additional tests will be conducted to confirm functionality in a - deployed environment. +\begin{enumerate} + \item \textbf{test-FR-DA-1 Test for Documentation Availability} \\[2mm] + \textbf{Control:} Manual \\ + \textbf{Initial State:} The system may or may not be installed. \\ + \textbf{Input:} User attempts to access the documentation. \\ + \textbf{Output:} The documentation is available and covers installation, usage (FR 5), and troubleshooting. \\ + \textbf{Test Case Derivation:} Validates that the documentation meets user needs (FR 7). \\ + \textbf{How test will be performed:} Review the documentation for completeness and clarity. \end{enumerate} \section{Nonfunctional Requirements Evaluation} -\subsection{Usability} +\subsection{Usability \& Humanity} -\subsection*{Key Findings} +\subsubsection{Key Findings} \begin{itemize} \item The extension demonstrated strong functionality in detecting code smells and providing refactoring suggestions. @@ -282,7 +233,7 @@ \subsection*{Key Findings} \textbf{refactoring speed}, and \textbf{UI clarity}. \end{itemize} -\section*{Methodology} +\subsubsection{Methodology} The usability test involved 5 student developers familiar with VSCode but with no prior experience using the extension. Participants performed tasks such as detecting code smells, refactoring single and @@ -292,13 +243,13 @@ \section*{Methodology} information of the participants as well as their opinions post testing (\ref{appendix:usability}). -\section*{Results} +\subsubsection{Results} The following is an overview of the most significant task that the test participants performed. Information on the tasks themselves can be found in the Appendix (\ref{appendix:usability}). -\subsection*{Quantitative Results} +\paragraph{Quantitative Results} \begin{itemize} \item \textbf{Task Completion Rate:} \begin{itemize} @@ -319,18 +270,18 @@ \subsection*{Quantitative Results} \begin{figure}[H] \centering \includegraphics[width=0.7\textwidth]{../Images/usability-satisfaction-graph.png} - \label{img:usability-satisfaction} \caption{User Satisfaction Survey Data} + \label{img:usability-satisfaction} \end{figure} -\subsection*{Qualitative Results} +\paragraph{Qualitative Results} Participants found the code smell detection intuitive and accurate, and they appreciated the preview feature and Accept/Reject buttons. However, they struggled with sidebar visibility, refactoring speed, and UI clarity. Hover descriptions were overwhelming, and some -elements (e.g., ``(6/3)'') were unclear. +elements (e.g., ``(6/3)'') were unclear. The overall satisfaction ratings can be seen in Figure \ref{img:usability-satisfaction}. -\section*{Discussion} +\subsubsection{Discussion} The usability test revealed that the extension performs well in detecting code smells and providing refactoring suggestions. Participants appreciated the energy savings feedback but requested @@ -345,7 +296,7 @@ \section*{Discussion} better onboarding, clearer documentation, and performance optimizations to enhance user satisfaction and adoption. -\section*{Feedback and Implementation Plan} +\subsubsection{Feedback and Implementation Plan} The following table summarizes participant feedback and whether the suggested changes will be implemented: @@ -376,16 +327,18 @@ \section*{Feedback and Implementation Plan} \bottomrule \end{tabular} \caption{Participant Feedback and Implementation Decisions} + \label{tab:participant-feedback} \end{table} +Based on the feedback summarized in Table \ref{tab:participant-feedback}, we prioritized improvements to the user interface and documentation, focusing on elements that caused the most frustration during testing.\\ +\noindent \textbf{Note:} In the Implementation Decision column, ``Partial'' indicates that the issue will not be addressed fully but some changes will be added for the feedback. This means we will implement a limited subset of the suggested improvements that align with our current scope and resource constraints. + \subsection{Performance} This testing benchmarks the performance of ecooptimizer across files of varying sizes (250, 1000, and 3000 lines). The data includes -detection times, -refactoring times for specific smells, and energy measurement times. -The goal is to -identify scalability patterns, performance bottlenecks, and +detection times, refactoring times for specific smells, and energy measurement times. +The goal is to identify scalability patterns, performance bottlenecks, and opportunities for optimization.\\ \textbf{Related Performance Requirement:} PR-1\\ @@ -409,28 +362,41 @@ \subsection{Performance} \noindent The following is for your reference: \\ -\begin{tabular}{|l|l|l|} +\begin{table}[H] +\centering +\begin{tabular}{|l|l|p{2.5cm}|p{6cm}|} + \hline + \textbf{Type of Smell} & \textbf{Code} & \textbf{Smell Name} & \textbf{Brief Explanation} \\ + \hline + Pylint & R0913 & Long Parameter List & Functions with excessive parameters (beyond configured limit). Complex to refactor as it requires restructuring function signatures and all call sites. \\ + \hline + Pylint & R6301 & No Self Use & Methods that don't use the instance (self). Requires carefully converting to static methods or class methods. \\ + \hline + Pylint & R1729 & Use a Generator & List comprehensions that could be generators. Simple transformation but requires ensuring equivalent behavior. \\ \hline - \textbf{Type of Smell} & \textbf{Code} & \textbf{Smell Name} \\ + Custom & LMC001 & Long Message Chain & Multiple object references chained together (a.b.c.d). Simple to refactor with intermediate variables. \\ \hline - Pylint & R0913 & Long Parameter List \\ - Pylint & R6301 & No Self Use \\ - Pylint & R1729 & Use a Generator \\ + Custom & UVA001 & Unused Variable or Attribute & Variables or attributes declared but never used. Easy to remove without complex analysis. \\ \hline - Custom & LMC001 & Long Message Chain \\ - Custom & UVA001 & Unused Variable or Attribute \\ - Custom & LEC001 & Long Element Chain \\ - Custom & LLE001 & Long Lambda Expression \\ - Custom & SCL001 & String Concatenation in Loop \\ - Custom & CRC001 & Cache Repeated Calls \\ + Custom & LEC001 & Long Element Chain & Nested dictionary/list access with multiple indexing operations. Simple to refactor with intermediate variables. \\ + \hline + Custom & LLE001 & Long Lambda Expression & Complex operations in lambda functions. Easy to refactor into named functions. \\ + \hline + Custom & SCL001 & String Concatenation in Loop & Strings built using += in loops. Simple to refactor to join() or ''.join(). \\ + \hline + Custom & CRC001 & Cache Repeated Calls & Same function calls made repeatedly with identical parameters. Simple to refactor with caching. \\ \hline \end{tabular} +\caption{Code Smells Used in Performance Testing} +\label{tab:code-smells} +\end{table} -\subsection*{1. Detection Time vs File Size} +\subsubsection{Detection Time vs File Size} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{{../Images/detectionTimeVsFileSize.png}} \caption{Detection Time vs File Size} + \label{fig:detection_time} \end{figure} \noindent \textbf{What}: Linear plot showing code smell detection @@ -449,13 +415,14 @@ \subsection*{1. Detection Time vs File Size} problematic for very large codebases. However, the absolute times remain reasonable, with detection completing in under 3 seconds even for 3000-line files making this -not a current critical bottleneck. +not a current critical bottleneck, as shown in Figure \ref{fig:detection_time}. -\subsection*{2. Refactoring Times by Smell Type (Log Scale)} +\subsubsection{Refactoring Times by Smell Type (Log Scale)} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{../Images/refactoring\_times\_log\_scale.png} \caption{Refactoring Times by Smell Type (Log Scale)} + \label{fig:refactoring_log} \end{figure} \noindent \textbf{What}: Logarithmic plot of refactoring times per @@ -464,7 +431,7 @@ \subsection*{2. Refactoring Times by Smell Type (Log Scale)} \noindent \textbf{Why}: Identify most expensive refactorings and scalability patterns\\ -The logarithmic plot reveals a clear hierarchy of refactoring costs. +The logarithmic plot reveals a clear hierarchy of refactoring costs, as shown in Figure \ref{fig:refactoring_log}. The most expensive smells are \texttt{R6301} and \texttt{R0913}, which take 6.13 seconds and 5.65 seconds, respectively, for a 3000-line file. These smells show exponential growth, with @@ -474,11 +441,12 @@ \subsection*{2. Refactoring Times by Smell Type (Log Scale)} suggests that optimizing \texttt{R6301} and \texttt{R0913} should be a priority, as they dominate the refactoring time for larger files. -\subsection*{3. Refactoring Times Heatmap} +\subsubsection{Refactoring Times Heatmap} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{../Images/refactoring\_times\_heatmap.png} \caption{Refactoring Times Heatmap} + \label{fig:refactoring_heatmap} \end{figure} \noindent \textbf{What}: Color-coded matrix of refactoring times by @@ -486,7 +454,7 @@ \subsection*{3. Refactoring Times Heatmap} \noindent \textbf{Why}: Quick visual identification of hot spots\\ -The heatmap provides a quick visual summary of refactoring times +The heatmap shown in Figure \ref{fig:refactoring_heatmap} provides a quick visual summary of refactoring times across smells and file sizes. The darkest cells correspond to \texttt{R6301} and \texttt{R0913} at 3000 lines, confirming their status as the most expensive operations. In contrast, \texttt{LLE001} @@ -495,11 +463,12 @@ \subsection*{3. Refactoring Times Heatmap} variation in refactoring times: at 3000 lines, the fastest smell (\texttt{LLE001}) is 200× faster than the slowest (\texttt{R6301}). -\subsection*{4. Energy Measurement Times Distribution} +\subsubsection{Energy Measurement Times Distribution} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{../Images/energy\_measurement\_boxplot.png} \caption{Energy Measurement Times Distribution} + \label{fig:energy_boxplot} \end{figure} \noindent \textbf{What}: Box plot of energy measurement durations\\ @@ -507,7 +476,7 @@ \subsection*{4. Energy Measurement Times Distribution} \noindent \textbf{Why}: Verify measurement consistency across operations\\ Energy measurement times are remarkably consistent, ranging from 5.54 -to 6.14 seconds across all operations and file sizes. +to 6.14 seconds across all operations and file sizes, as illustrated in Figure \ref{fig:energy_boxplot}. The box plot shows no significant variation with file size, suggesting that energy measurement is operation-specific rather than dependent on the size of the file. This stability could @@ -515,11 +484,12 @@ \subsection*{4. Energy Measurement Times Distribution} overhead, which could simplify efforts in the future if we were to create our own energy measurement module. -\subsection*{5. Comparative Refactoring Times per File Size} +\subsubsection{Comparative Refactoring Times per File Size} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{../Images/refactoring\_times\_comparison.png} \caption{Comparative Refactoring Times per File Size} + \label{fig:refactoring_comparison} \end{figure} \noindent \textbf{What}: Side-by-side bar charts per file size\\ @@ -527,7 +497,7 @@ \subsection*{5. Comparative Refactoring Times per File Size} \noindent \textbf{Why}: Direct comparison of refactoring costs at different scales\\ -The side-by-side bar charts reveal consistent dominance patterns +The side-by-side bar charts in Figure \ref{fig:refactoring_comparison} reveal consistent dominance patterns across file sizes. \texttt{R6301} and \texttt{R0913} are always the top two most expensive smells, while \texttt{LLE001} and \texttt{LMC001} remain the cheapest. Notably, the relative cost @@ -536,12 +506,13 @@ \subsection*{5. Comparative Refactoring Times per File Size} grows to 200:1. This suggests that the scalability of refactoring operations varies significantly by smell type. -\subsection*{6. Energy vs Refactoring Time Correlation} +\subsubsection{Energy vs Refactoring Time Correlation} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{../Images/energy\_refactoring\_correlation.png} \caption{Energy vs Refactoring Time Correlation} + \label{fig:energy_correlation} \end{figure} \noindent \textbf{What}: Scatter plot comparing refactoring and @@ -550,14 +521,16 @@ \subsection*{6. Energy vs Refactoring Time Correlation} \noindent \textbf{Why}: Identify potential relationships between effort and energy impact\\ -The scatter plot shows no clear correlation between refactoring time +The scatter plot in Figure \ref{fig:energy_correlation} shows no clear correlation between refactoring time and energy measurement time. Fast refactorings like \texttt{LLE001} and slow refactorings like \texttt{R6301} both result in energy measurement times clustered between 5.5 and 6.1 seconds. This makes perfect sense as the refactoring operations and energy measurement are disjoint functionalities in the code. -\subsection*{Key Insights and Recommendations} +\subsubsection{Key Insights and Recommendations} + +\noindent \textbf{Performance Bottlenecks:} \begin{itemize} \item \textbf{Bottleneck Identification:} The smells \texttt{R6301} and \texttt{R0913} are the primary bottlenecks, consuming over @@ -578,6 +551,7 @@ \subsection*{Key Insights and Recommendations} highlighting the need for targeted optimization. \end{itemize} +\noindent \textbf{Optimization Recommendations:} The analysis reveals significant scalability challenges for both detection and refactoring, particularly for smells like \texttt{R6301} and \texttt{R0913}. While energy measurement times are @@ -586,7 +560,7 @@ \subsection*{Key Insights and Recommendations} Future work should focus on optimizing high-cost operations and improving the scalability of the detection algorithm. -\subsection{Maintainability and Support} +\subsection{Maintenance and Support} \begin{enumerate} \item \textbf{test-MS-1: Extensibility for New Code Smells and @@ -604,6 +578,26 @@ \subsection{Maintainability and Support} through the main interface. This demonstrated that our architecture supports future expansions without disrupting core functionality. + + Specifically, we tested the extensibility by implementing the "DUP001" (duplicated list comprehensions) code smell. This smell occurs when the same list comprehension is used multiple times in close proximity, causing unnecessary repeat calculations. The corresponding refactoring method extracts the list comprehension to a variable and reuses the variable. For example: + + \begin{verbatim} + # Original code (with DUP001 smell) + total_a = sum([x*2 for x in values]) + count_a = len([x*2 for x in values]) + + # Refactored code + computed_values = [x*2 for x in values] + total_a = sum(computed_values) + count_a = len(computed_values) + \end{verbatim} + + The implementation required: + 1. Adding a new detection module file \texttt{dup001\_detector.py} that scans for repeated list comprehensions + 2. Creating a new refactoring module file \texttt{dup001\_refactor.py} that implements the extraction logic + 3. Registering the new smell and refactoring in the configuration system + + The entire process was completed in less than one day, confirming the tool's extensibility target. \item \textbf{test-MS-2: Maintainable and Adaptable Codebase} \\[2mm] We conducted a static analysis and documentation walkthrough to @@ -665,11 +659,11 @@ \subsection{Look and Feel} \item \textbf{test-LF-2 Theme Adaptation in VS Code} \\[2mm] The theme adaptation feature in the IDE plugin was tested manually to confirm that the plugin correctly adjusts to VS - Code’s light and dark themes without requiring manual + Code's light and dark themes without requiring manual configuration. The tester performed the test by opening the - plugin in both themes and switching between them using VS Code’s settings. + plugin in both themes and switching between them using VS Code's settings. - The expected result was that the plugin’s interface should + The expected result was that the plugin's interface should automatically adjust when the theme is changed. The actual result confirmed that the plugin seamlessly transitioned between light and dark themes while maintaining a consistent interface. The @@ -700,7 +694,7 @@ \subsection{Look and Feel} testing session, where developers and testers interacted with the plugin and provided feedback. This test evaluated user experience, ease of navigation, and overall satisfaction with the - plugin’s interface. + plugin's interface. The expected result was that users would be able to interact with the plugin smoothly and provide structured feedback. The actual @@ -733,18 +727,18 @@ \subsection{Security} covering the logging mechanisms for refactoring events, ensuring that logs are complete and immutable.\\ -\noindent The development team reviewed the codebase to confirm that +\noindent \textbf{Verification Process:} The development team reviewed the codebase to confirm that each refactoring event (pattern analysis, energy analysis, report generation) is logged with accurate timestamps and event description. Missing log entries and/or insufficient details were identified and added to the logging process.\\ -\noindent Through this process, all major refactoring processes were +\noindent \textbf{Results:} Through this process, all major refactoring processes were correctly logged with accurate timestamps. Logs are stored locally on the user's device, ensuring that unauthorized modifications are prevented by restricting external access.\\ -\noindent The team was able to confirm that the tool maintains a +\noindent \textbf{Conclusion:} The team was able to confirm that the tool maintains a secure logging system for refactoring processes, with logs being tamper-resistant due to their local storage on user devices. @@ -754,19 +748,21 @@ \subsection{Compliance} \item \textbf{test-CPL-1: Compliance with PIPEDA and CASL} \\[2mm] This process was applied to all processes related to data handling and user communication within the local API framework - with the objective of assesing whether the tool’s data handling + with the objective of assesing whether the tool's data handling and communication mechanisms align with PIPEDA and CASL requirements, ensuring that no personal information is stored, all processing is local, and communication practices meet regulatory standards.\\ - \noindent Through code review, the team confirmed that all data + + \noindent \textbf{Verification Method:} Through code review, the team confirmed that all data processing remains local and does not involve external storage. During this time, internal API functionality was also reviewed to ensure that user interactions are transient and not logged externally. By going through the different workflows, the team verified that no personal data collection occurs, eliminating the need for explicit consent mechanisms.\\ - \noindent As a result of this process, it was concluded that the + + \noindent \textbf{Compliance Assessment:} As a result of this process, it was concluded that the tool does not store any user data. The tool also does not send unsolicited communications, aligning with CASL requirements. @@ -774,16 +770,18 @@ \subsection{Compliance} Standards} \\[2mm] This process evaluated development workflows, documentation practices, and adherence to structured methodologies with the - object of assessing whether the tool’s quality management and + object of assessing whether the tool's quality management and software development processes align with ISO 9001 standards for quality management and SSADM for structured software development.\\ - \noindent Through an unbiased approach, the team verified the + + \noindent \textbf{Evaluation Process:} Through an unbiased approach, the team verified the presence of structured documentation, feedback mechanisms, and version tracking. It was also confirmed that a combination of unit testing, informal testing and iteration processes were applied during development. After code review, adherence to structured programming and modular design principles was also confirmed. - \noindent Our goal was to take a third perspective check on + + \noindent \textbf{Development Practices Assessment:} Our goal was to take a third perspective check on whether these set of practices were applied to our development workflows. Development follows reasonable structured processes and also includes formal documentation of testing and quality @@ -808,6 +806,7 @@ \section{Unit Testing} \subsection{API Endpoints} \subsubsection{Smell Detection Endpoint} +The following tests in Table \ref{table:detection_endpoint_tests} verify the functionality of the smell detection API endpoint under various conditions. \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} @@ -847,6 +846,7 @@ \subsubsection{Smell Detection Endpoint} \end{longtable} \subsubsection{Refactor Endpoint} +Table \ref{table:refactor_endpoint_tests} outlines the test cases for the refactor endpoint, covering both successful operations and error handling scenarios. \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} @@ -894,9 +894,43 @@ \subsubsection{Refactor Endpoint} TC\testcount & FR10, OER-IAS1 & Unexpected error occurs during refactoring. & Status code is 400. Error message contains the exception details. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10, OER-IAS1 & User requests to refactor all smells + of a type successfully. & Status code is 200. Response contains + refactored data, energy saved, and affected files. & All assertions pass. & + \cellcolor{green} Pass \\ \midrule + TC\testcount & FR10, OER-IAS1 & User requests to refactor multiple + smells of the same type. & Status code is 200. Response contains + accumulated energy savings from all smells refactored. & All assertions pass. & + \cellcolor{green} Pass \\ \midrule + TC\testcount & FR10, OER-IAS1 & Initial energy measurement fails for + refactor-by-type endpoint. & Status code is 400. Error message indicates + emissions could not be retrieved. & All assertions pass. & + \cellcolor{green} Pass \\ \midrule + TC\testcount & FR10, OER-IAS1 & User requests to refactor all smells + of a type with nonexistent source directory. & Status code is 404. Error message indicates + folder not found. & All assertions pass. & + \cellcolor{green} Pass \\ \midrule + TC\testcount & FR10, OER-IAS1 & Refactoring error occurs during + refactor-by-type. & Status code is 500. Error message contains details + about the refactoring failure. & All assertions pass. & + \cellcolor{green} Pass \\ \midrule + TC\testcount & FR10, OER-IAS1 & No energy is saved after refactor-by-type + operation. & Status code is 400. Error message indicates energy + was not saved. & All assertions pass. & + \cellcolor{green} Pass \\ \midrule + TC\testcount & FR10, OER-IAS1 & Perform refactoring in a new temporary + directory and validate output. & Temporary directory is created, source is + copied, smell is refactored, and energy is measured. & All assertions pass. & + \cellcolor{green} Pass \\ \midrule + TC\testcount & FR10, OER-IAS1 & Perform refactoring in an existing + temporary directory. & Uses existing directory, performs refactoring, and + measures energy without creating new copy. & All assertions pass. & + \cellcolor{green} Pass \\ \end{longtable} \subsection{Analyzer Controller Module} +The analyzer controller module was tested extensively to ensure it correctly identifies and processes code smells. Table \ref{table:analyzer_controller_tests} summarizes these test cases. \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} @@ -956,6 +990,7 @@ \subsection{Analyzer Controller Module} \end{longtable} \subsection{CodeCarbon Measurement} +The following test cases in Table \ref{table:measurement_tests} were executed to verify the functionality of the CodeCarbon measurement module. \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} @@ -1015,6 +1050,24 @@ \subsection{CodeCarbon Measurement} \texttt{file path} does not exist.'' should be logged.The function should return \texttt{None} since the file does not exist. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & PR-RFT1 & Handle unexpected return types from + CodeCarbon emissions tracker. & If the tracker returns a non-float + value (e.g., string), a warning should be logged with message + ``Unexpected emissions type''. Emissions value should be set to + \texttt{None}. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & PR-RFT1 & Handle NaN return values from CodeCarbon + emissions tracker. & If the tracker returns NaN, a warning should + be logged with message ``Unexpected emissions type''. Emissions + value should be set to \texttt{None}. & All assertions pass. & + \cellcolor{green} Pass \\ + \midrule + TC\testcount & PR-RFT1 & Handle missing emissions file after + measurement. & If the emissions CSV file does not exist after + tracking, an error message ``Emissions file missing - measurement + failed'' should be logged. Emissions\_data should be \texttt{None}. & + All assertions pass. & \cellcolor{green} Pass \\ \end{longtable} \subsection{Smell Analyzers} @@ -1641,7 +1694,7 @@ \subsubsection{Long Element Chain Refactorer Module} TC\testcount & PR-PAR3, FR6, FR3 & Test the long element chain refactorer across multiple files & Dictionary access across multiple files should be updated & Refactoring applied successfully - across multiple files & \cellcolor{yellow} TBD \\ \midrule + across multiple files & \cellcolor{green} Pass \\ \midrule TC\testcount & PR-PAR3, FR6, FR3 & Test the refactorer on dictionary access via class attributes & Class attributes should be flattened and access updated & Refactoring applied successfully on @@ -1959,10 +2012,41 @@ \subsubsection{Long Parameter List} All assertions pass. & \cellcolor{green} Pass \\ \end{longtable} -\subsection{VS Code Extension} +\subsection{VS Code Plugin} + +\subsubsection{Configure Workspace Command} +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.5cm} + >{\raggedright\arraybackslash}p{4.5cm} + >{\raggedright\arraybackslash}p{4cm} + >{\raggedright\arraybackslash}p{3cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{Configure Workspace Command Test Case} + \label{table:configure_workspace_command_tests} + \endlastfoot -\subsubsection{Detect Smells Command} + TC\testcount & OER-IAS1, OER-PR1 & User selects a Python project folder using the quick pick. & + The tool scans the workspace for Python files, detects valid folders, and prompts the user with a quick pick. After selection, it updates the workspace state and shows confirmation message. & + Workspace is detected and configured. Workspace state is updated, VS Code context is set, and confirmation message is shown. & \cellcolor{green} Pass \\ +\end{longtable} +\subsubsection{Reset Configuration Command} \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} >{\raggedright\arraybackslash}p{4.5cm} @@ -1985,48 +2069,72 @@ \subsubsection{Detect Smells Command} \endfoot \bottomrule - \caption{Detect Smells Command Test Cases} - \label{table:plugin_detect_command_tests} + \caption{Reset Configuration Command Test Cases} + \label{table:reset_configuration_command_tests} \endlastfoot - TC\testcount & FR10, OER-IAS1 & No active editor is found. & Shows - error message: ``Eco: No active editor found.'' & All assertions - pass. & \cellcolor{green} Pass \\ + TC\testcount & OER-PR1, UHR-ACS2 & User confirms reset when prompted by warning dialog. & + Workspace configuration is removed from persistent storage, context is cleared, and function returns \texttt{true}. & + Workspace state is cleared, context is reset, and return value is \texttt{true}. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, OER-IAS1 & Active editor has no valid file - path. & Shows error message: ``Eco: Active editor has no valid file - path.'' & All assertions pass. & \cellcolor{green} Pass \\ + TC\testcount & OER-PR1, UHR-ACS2 & User cancels when prompted by warning dialog. & + No changes made to workspace configuration, and function returns \texttt{false}. & + No state updates or command executions occurred, and return value is \texttt{false}. & \cellcolor{green} Pass \\ +\end{longtable} + +\subsubsection{Detect Smells API} +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.5cm} + >{\raggedright\arraybackslash}p{5cm} + >{\raggedright\arraybackslash}p{4cm} + >{\raggedright\arraybackslash}p{3cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ \midrule - TC\testcount & FR10, OER-IAS1 & No smells are enabled. & Shows - warning message: ``Eco: No smells are enabled! Detection skipped.'' - & All assertions pass. & \cellcolor{green} Pass \\ + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ \midrule - TC\testcount & FR10, OER-IAS1 & Uses cached smells when hash is - unchanged and same smells are enabled. & Shows info message: ``Eco: - Using cached smells for fake.path'' & All assertions pass. & - \cellcolor{green} Pass \\ + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{Detect Smells API Test Cases} + \label{table:detect_smells_tests} + \endlastfoot + + TC\testcount & FR10, OER-IAS1 & File URI is not a physical file (e.g., `untitled'). & Smell detection is skipped. & No status or messages are triggered. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, OER-IAS1 & Fetches new smells when enabled - smells change. & Calls \texttt{wipeWorkCache}, \texttt{updateHash}, - and \texttt{fetchSmells}. Updates workspace data. & All assertions - pass. & \cellcolor{green} Pass \\ + TC\testcount & FR10, OER-IAS1 & File path is not a Python file. & Smell detection is skipped. & No status or messages are triggered. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, OER-IAS1 & Fetches new smells when hash - changes but enabled smells remain the same. & Calls - \texttt{updateHash} and \texttt{fetchSmells}. Updates workspace - data. & All assertions pass. & \cellcolor{green} Pass \\ + TC\testcount & FR10, OER-IAS1 & Cached smells are available. & Uses cached smells and sets status to `passed'. & Cached smells are returned and UI updated. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, OER-IAS1 & No cached smells and server is - down. & Shows warning message: ``Action blocked: Server is down and - no cached smells exist for this file version.'' & All assertions - pass. & \cellcolor{green} Pass \\ + TC\testcount & FR10, OER-IAS1 & Server is down and no cached smells exist. & Displays warning and sets status to `server\_down'. & Warning is shown, status updated. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, OER-IAS1 & Highlights smells when smells are - found. & Shows info messages and calls \texttt{highlightSmells}. & - All assertions pass. & \cellcolor{green} Pass \\ + TC\testcount & FR10, OER-IAS1 & No smells are enabled. & Displays warning and skips detection. & Warning is shown. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10, OER-IAS1 & Enabled smells present and server returns valid results. & Fetches smells, caches them, and updates UI. & Smells are fetched, cached, and UI updated. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10, OER-IAS1 & API returns no smells. & Sets status to \texttt{no\_issues}, caches empty result. & Status and cache updated as expected. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10, OER-IAS1 & API returns error (500). & Displays error and sets status to `failed'. & Error message shown and status updated. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10, OER-IAS1 & Network error during API call. & Displays error and sets status to `failed`. & Error message and status shown as expected. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10, OER-IAS1 & Scans folder with no Python files. & Shows warning: ``No Python files found.'' & Message displayed, no detection performed. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10, OER-IAS1 & Scans folder with 2 Python files. & Processes only Python files, skips others. & Info message displayed, detection runs on valid files. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10, OER-IAS1 & File system throws error during folder scan. & Logs error and skips processing. & Error logged via ecoOutput. & \cellcolor{green} Pass \\ \end{longtable} -\subsubsection{Refactor Smell Command} +\subsubsection{Export Metrics Command} \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} @@ -2050,38 +2158,53 @@ \subsubsection{Refactor Smell Command} \endfoot \bottomrule - \caption{Refactor Smell Command Test Cases} - \label{table:plugin_refactor_command_tests} + \caption{Export Metrics Command Test Cases} + \label{table:export_metrics_tests} \endlastfoot - TC\testcount & PR-RFT1 & No active editor is found. & Shows error - message ``Eco: Unable to proceed as no active editor or file path - found.'' & All assertions pass. & \cellcolor{green} Pass \\ + TC\testcount & FR13, OER-IAS2 & No metrics data is found in workspace state. & + Displays message ``No metrics data available to export.'' & + Info message shown as expected. & + \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13, OER-IAS2 & No workspace path is configured. & + Shows error ``No configured workspace path found.'' & + Error message triggered appropriately. & + \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13, OER-IAS2 & Workspace path is a directory. & + Saves \texttt{metrics-data.json} inside the directory. & + File written and success message shown. & + \cellcolor{green} Pass \\ \midrule - TC\testcount & PR-RFT1, FR6 & Attempting to refactor when no smells - are detected in the file & Shows error message ``Eco: No smells - detected in the file for refactoring.'' & All assertions pass. & + + TC\testcount & FR13, OER-IAS2 & Workspace path is a file. & + Saves \texttt{metrics-data.json} to parent directory. & + File written in parent folder as expected. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR6 & Attempting to refactor when selected line - doesn't match any smell & Shows error message ``Eco: No matching - smell found for refactoring.'' & All assertions pass. & + + TC\testcount & FR13, OER-IAS2 & Workspace path is of unknown type. & + Displays error ``Invalid workspace path type.'' & + Error triggered and logged as expected. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR5, FR6, FR10 & Refactoring a smell when found on - the selected line & Saves the current file. Calls - \texttt{refactorSmell} method with correct parameters. Shows - message ``Refactoring report available in sidebar''. Executes - command to focus refactor sidebar. Opens and shows the refactored - preview. Highlights updated smells. Updates the UI with new smells - & All assertions pass. & \cellcolor{green} Pass \\ + + TC\testcount & FR13, OER-IAS2 & Filesystem stat call fails. & + Displays error with ``Failed to access workspace path...'' & + Error is caught and message shown. & + \cellcolor{green} Pass \\ \midrule - TC\testcount & PR-RFT2 & Handling API failure during refactoring & - Shows error message ``Eco: Refactoring failed. See console for - details.'' & All assertions pass. & \cellcolor{green} Pass \\ + + TC\testcount & FR13, OER-IAS2 & File write fails during export. & + Displays error with ``Failed to export metrics data...'' & + Error is logged and user is notified. & + \cellcolor{green} Pass \\ \end{longtable} -\subsubsection{File Highlighter} +\subsubsection{Filter Command Registration} \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} @@ -2105,34 +2228,64 @@ \subsubsection{File Highlighter} \endfoot \bottomrule - \caption{File Highlighter Test Cases} - \label{table:plugin_file_highlighter_tests} + \caption{Filter Command Registration Test Cases} + \label{table:filter_smell_command_tests} \endlastfoot - TC\testcount & FR10, OER-IAS1, LFR-AP2 & Creates decorations for a - given color. & Decoration is created using - \lstinline|vscode.window.createTextEditor DecorationType|. & All - assertions pass. & \cellcolor{green} Pass \\ + TC\testcount & FR11, UHR-EOU1 & Register and trigger \texttt{toggleSmellFilter}. & + Invokes \texttt{toggleSmell} with correct key. & + Method called with \texttt{test-smell}. & + \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11, UHR-EOU1 & Register and trigger \texttt{editSmellFilterOption} with valid input. & + Updates option and refreshes filter view. & + \texttt{updateOption} and \texttt{refresh} called with correct values. & + \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11 & Trigger \texttt{editSmellFilterOption} with invalid number. & + Does not call update function. & + \texttt{updateOption} not triggered. & + \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11 & Trigger \texttt{editSmellFilterOption} with missing keys. & + Displays error message about missing smell or option key. & + Error shown as expected. & + \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11 & Trigger \texttt{selectAllFilterSmells}. & + Enables all smell filters. & + \texttt{setAllSmellsEnabled(true)} called. & + \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, OER-IAS1, LFR-AP2 & Highlights smells in the - active text editor. & Decorations are set using - \texttt{setDecorations}. & All assertions pass. & \cellcolor{green} Pass \\ + + TC\testcount & FR11 & Trigger \texttt{deselectAllFilterSmells}. & + Disables all smell filters. & + \texttt{setAllSmellsEnabled(false)} called. & + \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, OER-IAS1, LFR-AP2 & Does not reset highlight - decorations on first initialization. & Decorations are not disposed - of on the first call. & All assertions pass. & \cellcolor{green} Pass \\ + + TC\testcount & FR11 & Trigger \texttt{setFilterDefaults}. & + Resets filters to default settings. & + \texttt{resetToDefaults()} called. & + \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, OER-IAS1, LFR-AP2 & Resets highlight - decorations on subsequent calls. & Decorations are disposed of on - subsequent calls. & All assertions pass. & \cellcolor{green} Pass \\ + + TC\testcount & FR11 & Register all commands to subscriptions. & + All filter commands are added to context. & + 5 commands registered. & + \cellcolor{green} Pass \\ \end{longtable} -\subsubsection{File Hashing} +\subsubsection{Refactor Workflow} \begin{longtable}{c - >{\raggedright\arraybackslash}p{1.5cm} + >{\raggedright\arraybackslash}p{2cm} >{\raggedright\arraybackslash}p{4.5cm} - >{\raggedright\arraybackslash}p{4cm} + >{\raggedright\arraybackslash}p{4.3cm} >{\raggedright\arraybackslash}p{3cm} c} \toprule \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & @@ -2151,26 +2304,52 @@ \subsubsection{File Hashing} \endfoot \bottomrule - \caption{Hashing Tools Test Cases} - \label{table:plugin_hashing_tests} + \caption{Refactor Workflow Test Cases} + \label{table:refactor_command_tests} \endlastfoot - TC\testcount & FR10, OER-IAS1 & Document hash has not changed. & - Does not update workspace storage. & All assertions pass. & - \cellcolor{green} Pass \\ + TC\testcount & FR12 & Workspace not configured. & Shows error message and aborts refactoring. & Error message shown. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & Backend is down. & Displays warning and updates status to \texttt{server\_down}. & Warning shown and status updated. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & Refactors a single smell via backend. & Queues status, updates workspace, and logs info. & Refactor completed as expected. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & Refactors all smells of a type. & Calls smell-type API and displays appropriate info. & Refactoring succeeds. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & Backend refactor call fails. & Displays error and resets state. & Refactor error handled. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13 & Starts refactor session and shows diff. & Updates detail view, opens diff, shows buttons. & Session started with correct UI behavior. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13 & Starts session with missing energy data. & Displays N/A in savings output. & Info message shown with N/A. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13, MS-MNT4 & Accepts refactoring with full file updates. & Copies files, updates metrics, clears cache. & Files replaced and data updated. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13 & Accept triggered without refactor data. & Displays error message. & No action taken. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13 & Filesystem copy fails during accept. & Shows error and aborts application. & Error message shown. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, OER-IAS1 & Document hash has changed. & - Updates workspace storage. & All assertions pass. & \cellcolor{green} Pass \\ + + TC\testcount & FR13 & Rejects refactoring and clears view. & Updates status, clears state. & Refactor discarded. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, OER-IAS1 & No hash exists for the document. & - Updates workspace storage. & All assertions pass. & \cellcolor{green} Pass \\ + + TC\testcount & FR13 & Reject cleanup throws error. & Logs error in ecoOutput. & Output error logged. & \cellcolor{green} Pass \\ \end{longtable} -\subsubsection{Line Selection Manager Module} +\subsubsection{Wipe Workspace Cache Command} + \begin{longtable}{c - >{\raggedright\arraybackslash}p{1.5cm} + >{\raggedright\arraybackslash}p{2cm} >{\raggedright\arraybackslash}p{4.5cm} - >{\raggedright\arraybackslash}p{4cm} + >{\raggedright\arraybackslash}p{4.3cm} >{\raggedright\arraybackslash}p{3cm} c} \toprule \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & @@ -2189,47 +2368,33 @@ \subsubsection{Line Selection Manager Module} \endfoot \bottomrule - \caption{Line Selection Module Test Cases} - \label{table:line_selection_tests} + \caption{Wipe Workspace Cache Test Cases} + \label{table:wipe_workspace_tests} \endlastfoot - TC\testcount & UHR-EOU1 & Call the `removeLastComment` method after - adding a comment. & The decoration is removed and no comment - remains on the line. & The decoration is removed, and no comment - appears on the selected line. & \cellcolor{green} Pass \\ \midrule - TC\testcount & UHR-EOU1 & Call `commentLine` method with null - editor. & The method does not throw an error. & The method does not - throw an error. & \cellcolor{green} Pass \\ \midrule - TC\testcount & UHR-EOU1 & Call `commentLine` on a file with no - detected smells. & No comment is added to the line. & No decoration - is added, and the line remains unchanged. & \cellcolor{green} Pass \\ \midrule - TC\testcount & UHR-EOU1 & Call `commentLine` on a file where the - document hash does not match. & The method does not add a comment - because the document has changed. & No decoration is added due to - the document hash mismatch. & \cellcolor{green} Pass \\ \midrule - TC\testcount & UHR-EOU1 & Call `commentLine` with a multi-line - selection. & The method returns early without adding a comment. & - No comment is added to any lines in the selection. & - \cellcolor{green} Pass \\ \midrule - TC\testcount & UHR-EOU1 & Call `commentLine` on a line with no - detected smells. & No comment is added for the line. & No - decoration is added, and the line remains unchanged. & - \cellcolor{green} Pass \\ \midrule - TC\testcount & UHR-EOU1 & Call `commentLine` on a line with a - single detected smell. & The comment shows the first smell symbol - without a count. & Comment shows the first smell symbol: `Smell: - PERF-001`. & \cellcolor{green} Pass \\ \midrule - TC\testcount & UHR-EOU1 & Call `commentLine` on a line with a - detected smell. & A comment is added on the selected line in the - editor showing the detected smell. & Comment added with the correct - smell symbol and count. & \cellcolor{green} Pass \\ \midrule - TC\testcount & UHR-EOU1 & Call `commentLine` on a line with - multiple detected smells. & The comment shows the first smell - followed by the count of additional smells. & Comment shows `Smell: - PERF-001 | (+1)`. & \cellcolor{green} Pass \\ + TC\testcount & FR11, UHR-EOU2 & User opens wipe cache command. & Confirmation dialog is shown. & Dialog displayed as expected. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11, MS-MNT2 & User confirms wipe action. & Cache cleared, status UI reset, success message shown. & All behaviors executed as expected. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11, UHR-EOU2 & User cancels confirmation dialog. & Cache remains intact, cancellation message shown. & No clearing occurred. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11, UHR-EOU2 & User dismisses dialog (no selection). & Tool cancels operation with message. & Cancellation handled gracefully. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11, UHR-EOU2 & User clicks non-confirm option. & Tool shows cancellation message. & No data lost, message shown. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11, MS-MNT2 & Cache cleared without error. & Success message shown after operation. & Message shown only after success. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11 & Dialog closed with no response. & Cancellation message shown. & Message shown, no success triggered. & \cellcolor{green} Pass \\ \end{longtable} -\subsubsection{Hover Manager Module} +\subsubsection{File Highlighter} + \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} >{\raggedright\arraybackslash}p{4.5cm} @@ -2252,34 +2417,20 @@ \subsubsection{Hover Manager Module} \endfoot \bottomrule - \caption{Hover Manager Module Test Cases} - \label{table:hover_manager_tests} + \caption{File Highlighter Test Cases} + \label{table:file_highlighter_tests} \endlastfoot - TC\testcount & LFR-AP2 & Register hover provider for Python files. - & Hover provider registered for Python files. & Hover provider is - registered for Python files. & \cellcolor{green} Pass \\ \midrule - TC\testcount & LFR-AP2 & Subscribe hover provider. & Hover provider - subscription registered. & Hover provider subscription registered. - & \cellcolor{green} Pass \\ \midrule - TC\testcount & LFR-AP2 & Return hover content with no smells. & - Returns null for hover content. & Hover content = null. & - \cellcolor{green} Pass \\ \midrule - TC\testcount & LFR-AP2, FR2 & Update smells with new data. & Smells - updated correctly with new data. & Smells are updated correctly - with new smells data. & \cellcolor{green} Pass \\ \midrule - TC\testcount & LFR-AP2, FR2 & Update smells correctly. & Smells - updated with new content. & Current smells content updated to new - smells content provided. & \cellcolor{green} Pass \\ \midrule - TC\testcount & LFR-AP2 & Generate valid hover content. & Generates - hover content with correct smell information. & Correct and valid - hover content generated for given smell. & \cellcolor{green} Pass \\ \midrule - TC\testcount & LFR-AP2 & Register refactor commands. & Both - commands registered correctly on initialization & Refactor commands - registered correctly. & \cellcolor{green} Pass \\ + TC\testcount & FR10, LFR-AP2 & Test creation of decorations with correct color and style. & Decorations are created with proper color and style for each smell type. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10, LFR-AP2 & Test highlighting of detected smells in editor. & Smells are highlighted based on their line occurrences with correct hover content. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10 & Test initial highlighting without resetting existing decorations. & Decorations are applied and stored without affecting existing ones. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10 & Test resetting decorations before applying new ones. & Existing decorations are disposed of and new ones are properly applied. & All assertions pass. & \cellcolor{green} Pass \\ \end{longtable} -\subsubsection{Handle Smell Settings Module} +\subsubsection{Hover Manager} \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} @@ -2303,38 +2454,24 @@ \subsubsection{Handle Smell Settings Module} \endfoot \bottomrule - - \caption{VS Code Settings Management Module Test Cases} - \label{table:vs_code_settings_tests} + \caption{Hover Manager Test Cases} + \label{table:hover_manager_tests} \endlastfoot - TC\testcount & FR10, UHR-PSI1 & Test retrieval of enabled smells - from settings. & Function should return the current enabled smells. - & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, UHR-PSI1 & Test retrieval of enabled smells - when no settings exist. & Function should return an empty object. & - All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, UHR-PSI1, UHR-EOU2 & Test enabling a smell and - verifying notification. & Notification should be displayed and - cache wiped. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, UHR-PSI1, UHR-EOU2 & Test disabling a smell - and verifying notification. & Notification should be displayed and - cache wiped. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, UHR-PSI1, UHR-EOU2 & Test that cache is not - wiped if no changes occur. & No notification or cache wipe should - happen. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, UHR-PSI1 & Test formatting of kebab-case smell - names. & Smell names should be correctly converted to readable - format. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR10, UHR-PSI1 & Test formatting with an empty - string input. & Function should return an empty string without - errors. & All assertions pass. & \cellcolor{green} Pass \\ - + TC\testcount & FR12 & Test registration of hover provider for Python files. & Hover provider is correctly registered for Python files. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12 & Test hover provider for non-Python files. & Returns undefined for non-Python files. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12 & Test hover provider with no cache. & Returns undefined when no cache exists. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12 & Test hover provider with non-matching line. & Returns undefined for lines without smells. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12, UHR-EOU1 & Test hover provider with valid smell. & Returns hover with markdown details. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12, LFR-AP1 & Test hover provider escapes markdown. & Output safely renders escaped characters. & All assertions pass. & \cellcolor{green} Pass \\ \end{longtable} -\subsubsection{Handle Smell Settings Module} - -\subsubsection{Wipe Workspace Cache Command} +\subsubsection{Line Selection Manager} \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} @@ -2358,46 +2495,30 @@ \subsubsection{Wipe Workspace Cache Command} \endfoot \bottomrule - \caption{Wipe Workspace Cache Command Test Cases} - \label{table:plugin_wipe_cache_tests} + \caption{Line Selection Manager Test Cases} + \label{table:line_selection_tests} \endlastfoot - TC\testcount & FR5, FR8 & Trigger the cache wipe with no reason - provided. & The smells cache should be cleared and reset to an - empty state. A success message indicating that the workspace cache - was successfully wiped should be displayed. & All assertions pass. - & \cellcolor{green} Pass \\ + TC\testcount & FR12 & Test removal of last comment with existing decoration. & Last comment decoration is properly disposed of. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR5, FR8 & Trigger the cache wipe with the reason - ``manual''. & Both the smells cache and file changes cache should - be cleared and reset to empty states. A success message indicating - that the workspace cache was manually wiped by the user should be - displayed. & All assertions pass. & \cellcolor{green} Pass \\ + TC\testcount & FR12 & Test removal of last comment with no decoration. & No action taken when no decoration exists. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR5, FR8 & Trigger the cache wipe when there are no - open files. & A log message indicating that there are no open files - to update should be generated. & All assertions pass. & - \cellcolor{green} Pass \\ + TC\testcount & FR12 & Test comment line with no editor. & Skips decoration when no editor is provided. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR5, FR8 & Trigger the cache wipe when there are - open files. & A message indicating the number of visible files - should be logged, and the hashes for each open file should be - updated. & All assertions pass. & \cellcolor{green} Pass \\ + TC\testcount & FR12 & Test comment line with multi-line selection. & Skips decoration for multi-line selections. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR5, FR8 & Trigger the cache wipe with the reason - ``settings''. & Only the smells cache should be cleared. A success - message indicating that the cache was wiped due to smell detection - settings changes should be displayed. & All assertions pass. & - \cellcolor{green} Pass \\ + TC\testcount & FR12 & Test comment line with no cached smells. & Calls removeLastComment when no smells are cached. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR3, FR5, FR8 & Trigger the cache wipe when an error - occurs. & An error message should be logged, and an error message - indicating failure to wipe the workspace cache should be displayed - to the user. & All assertions pass. & \cellcolor{green} Pass \\ - + TC\testcount & FR12 & Test comment line with mismatched line. & No decoration is added for non-matching lines. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12, LFR-AP1 & Test comment line with one smell match. & Adds comment with correct smell type. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12, LFR-AP1 & Test comment line with multiple smells. & Adds comment with correct smell count. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12 & Test comment line with existing decoration. & Skips redecoration of already decorated lines. & All assertions pass. & \cellcolor{green} Pass \\ \end{longtable} -\subsubsection{Backend} +\subsubsection{Smells Data Management} \begin{longtable}{c >{\raggedright\arraybackslash}p{1.5cm} @@ -2421,65 +2542,597 @@ \subsubsection{Backend} \endfoot \bottomrule - \caption{Backend Test Cases} - \label{table:plugin_backend_tests} + \caption{Smells Data Management Test Cases} + \label{table:smells_data_management_tests} \endlastfoot - TC\testcount & PR-SCR1, PR-RFT1 & Trigger request to check server - status when server responds with a successful status. & The set - status method should be called with the - \texttt{ServerStatusType.UP} status & All assertions pass. & - \cellcolor{green} Pass \\ + TC\testcount & FR10, UHR-PSI1 & Test retrieval of enabled smells from settings. & Returns all enabled smells from VS Code settings. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & PR-SCR1, PR-RFT2 & Trigger request to check server - status when server responds with an error status or fails to - respond. & The set status method should be called with the - \texttt{ServerStatusType.DOWN} status & All assertions pass. & - \cellcolor{green} Pass \\ + TC\testcount & FR10, UHR-PSI1 & Test empty settings case. & Returns empty object when no smells are enabled. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10, UHR-EOU2 & Test smell filter updates with notifications. & Proper notification shown when enabling/disabling smells. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & FR-6, PR-RFT1 & Trigger intialize logs call with a - valid directory path, and backend responds with success. & The - function should return \texttt{true} indicating successful log - initialization. & All assertions pass. & \cellcolor{green} Pass \\ + TC\testcount & FR10 & Test cache clearing on settings update. & Cache is cleared when smell settings change. & All assertions pass. & \cellcolor{green} Pass \\ \midrule - TC\testcount & PR-SCR1, PR-RFT2 & Trigger intialize logs call with - a valid directory path, and backend responds with a failure. & TThe - function should return \texttt{false} indicating failure to - initialize logs. & All assertions pass. & \cellcolor{green} Pass \\ + TC\testcount & FR10 & Test smell name formatting. & Correctly formats smell names from kebab-case. & All assertions pass. & \cellcolor{green} Pass \\ \end{longtable} -\section{Changes Due to Testing} +\subsubsection{Cache Initialization} -\wss{This section should highlight how feedback from the users and from - the supervisor (when one exists) shaped the final product. In particular - the feedback from the Rev 0 demo to the supervisor (or to potential users) -should be highlighted.} +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.5cm} + >{\raggedright\arraybackslash}p{4.5cm} + >{\raggedright\arraybackslash}p{4cm} + >{\raggedright\arraybackslash}p{3cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead -During the testing phase, several changes were made to the tool based -on feedback from user testing, supervisor reviews, and edge cases -encountered during unit and integration testing. These changes were -necessary to improve the tool’s usability, functionality, and robustness. + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead -\subsection{Usability and User Input Adjustments} -One of the key findings from testing was the balance between -\textbf{automating refactorings} and \textbf{allowing user control} -over changes. Initially, the tool required users to manually approve -every refactoring, which slowed down the workflow. However, after -usability testing, it became evident that an \textbf{option to -refactor all occurrences of the same smell type} would significantly -improve efficiency. This led to the introduction of a -\textbf{"Refactor Smell of Same Type"} feature in the VS Code -extension, allowing users to apply the same refactoring across -multiple instances of a detected smell simultaneously. Additionally, -we refined the \textbf{Accept/Reject UI elements} to make them more -intuitive and streamlined the workflow for batch refactoring actions. + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot -\subsection{Detection and Refactoring Improvements} -Heavy modifications were made to the \textbf{detection and -refactoring modules}, particularly in handling \textbf{multi-file -projects}. Initially, the detectors and refactorers assumed a -\textbf{single-file scope}, leading to missed optimizations when -function calls or variable dependencies spanned across multiple + \bottomrule + \caption{Cache Initialization Test Cases} + \label{table:cache_initialization_tests} + \endlastfoot + + TC\testcount & FR10 & Test initialization of workspace cache. & Cache is properly initialized with workspace settings. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10 & Test initialization with invalid workspace. & Cache initialization fails gracefully. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10 & Test cache update on workspace change. & Cache is updated when workspace settings change. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10 & Test cache persistence across sessions. & Cache state is preserved between sessions. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR10 & Test cache cleanup on extension deactivation. & Cache is properly cleared on extension deactivation. & All assertions pass. & \cellcolor{green} Pass \\ +\end{longtable} + +\subsubsection{Tracked Diff Editors} + +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.5cm} + >{\raggedright\arraybackslash}p{4.5cm} + >{\raggedright\arraybackslash}p{4cm} + >{\raggedright\arraybackslash}p{3cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{Tracked Diff Editor Test Cases} + \label{table:tracked_diff_editor_tests} + \endlastfoot + + TC\testcount & FR11, MS-MNT3 & Register diff editor with valid URIs. & Diff editor is properly tracked in the system. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR11 & Test unrelated URIs tracking. & System correctly identifies unrelated URIs as not tracked. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR11 & Verify tracked diff editor status. & System correctly identifies tracked diff editors. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR11 & Test unregistered diff editor status. & System correctly identifies unregistered diff editors. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR11 & Test case-sensitive URI comparison. & System properly handles case sensitivity in URI comparison. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR11 & Close all tracked diff editors. & All registered diff editors are properly closed. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR11 & Clear tracked editor list. & Tracked editor list is properly cleared after closing. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR11 & Handle empty tab list. & System gracefully handles case when no tabs exist. & All assertions pass. & \cellcolor{green} Pass \\ +\end{longtable} + +\subsubsection{Refactor Action Buttons} + +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.5cm} + >{\raggedright\arraybackslash}p{4.5cm} + >{\raggedright\arraybackslash}p{4cm} + >{\raggedright\arraybackslash}p{3cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{Refactor Action Button Test Cases} + \label{table:refactor_button_tests} + \endlastfoot + + TC\testcount & FR12, UHR-EOU1 & Show refactor action buttons after initialization. & Accept and Reject buttons are displayed and refactoring context is set. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12, UHR-ACS2 & Hide refactor action buttons after initialization. & Buttons are hidden and context is properly cleared. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12, UHR-EOU1 & Test button visibility with no active editor. & Buttons remain hidden when no editor is active. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12, UHR-EOU1 & Test button state during refactoring. & Buttons show correct enabled/disabled state during refactoring. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + TC\testcount & FR12, UHR-EOU1 & Test button actions with invalid refactoring state. & Buttons handle invalid state gracefully with appropriate messages. & All assertions pass. & \cellcolor{green} Pass \\ +\end{longtable} + +\subsubsection{Workspace File Monitoring} + +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.8cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{2.8cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{Workspace File Listener Test Cases} + \label{table:workspace_listener_tests} + \endlastfoot + + TC\testcount & FR12, MS-MNT4 & File changes with cache. & Cache cleared, status marked outdated, notification shown. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & File changes without cache. & Listener skips invalidation, logs trace. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & Error during file change cache clearing. & Error is caught and logged. & Error trace logged. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & File deleted and cache existed. & Cache and status removed, UI refreshed. & All behaviors verified. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & File deleted but not cached. & Skips removal, no action taken. & No deletions occurred. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & Error during deletion. & Logs error message. & Error handled correctly. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14, OER-IAS2 & Python file is saved. & detectSmellsFile is called. & Auto detection triggered. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Non-Python file is saved. & Listener skips detection. & detectSmellsFile not called. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & MS-MNT4 & dispose() called. & File watcher and save listener are disposed. & Disposables cleaned. & \cellcolor{green} Pass \\ +\end{longtable} + +\subsubsection{Backend Communication} + +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.8cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{2.8cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{Backend Communication Test Cases} + \label{table:backend_communication_tests} + \endlastfoot + + TC\testcount & FR10, OER-INT1 & checkServerStatus returns healthy. & Sets server status to UP. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR10 & checkServerStatus gets 500. & Sets server status to DOWN, logs warning. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR10, SR-IM 1 & checkServerStatus throws network error. & Sets server status to DOWN, logs error. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & OER-IAS1 & initLogs successfully initializes logs. & Returns true. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & OER-IAS1 & initLogs fails server response. & Returns false, logs error. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & OER-IAS1 & initLogs throws network error. & Returns false, logs connection error. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR10 & fetchSmells returns successful detection. & Returns list of smells, logs messages. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR10, SR-IM 1 & fetchSmells gets 500 from server. & Throws error with status. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR10, SR-IM 1 & fetchSmells throws network error. & Throws error and logs it. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13, OER-INT1 & backendRefactorSmell works. & Calls refactor API and returns result. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13 & backendRefactorSmell with empty path. & Throws error, logs abortion. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13, SR-IM 1 & backendRefactorSmell server error. & Throws error with message. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13, OER-INT1 & backendRefactorSmellType works. & Calls /refactor-by-type and returns result. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13 & backendRefactorSmellType no path. & Throws error for missing path. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR13, SR-IM 1 & backendRefactorSmellType server error. & Throws error for failed refactor. & All assertions pass. & \cellcolor{green} Pass \\ +\end{longtable} + +\subsubsection{Smell Highlighting} + +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.8cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{2.8cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{File Highlighter Test Cases} + \label{table:file_highlighter_tests} + \endlastfoot + + TC\testcount & FR12, LFR-AP 1 & highlightSmells with valid cache. & Two decorations created and applied. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & highlightSmells with no cache. & Does not apply any highlights. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12, LFR-AP 1 & highlightSmells with only one smell enabled. & Only matching smells are decorated. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & highlightSmells with invalid line. & Skips decoration for that smell. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & LFR-AP 2 & getDecoration with underline style. & Returns text underline decoration. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & LFR-AP 2 & getDecoration with flashlight style. & Returns whole-line background decoration. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & LFR-AP 2 & getDecoration with border-arrow style. & Returns right-arrow styled decoration. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & LFR-AP 2 & getDecoration with unknown style. & Falls back to underline decoration. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12, UHR-EOU 1 & resetHighlights disposes all active decorations. & Decorations are disposed and cleared. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & updateHighlightsForVisibleEditors with Python editor. & highlightSmells called once. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & updateHighlightsForFile with matching Python file. & Triggers highlightSmells. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & updateHighlightsForFile with non-matching file. & Skips highlighting. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & updateHighlightsForFile with JS file. & Skips highlighting. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & getInstance returns same instance. & Singleton pattern confirmed. & All assertions pass. & \cellcolor{green} Pass \\ +\end{longtable} + + +\subsubsection{Smell Hover Display} + +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.8cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{2.8cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{Hover Manager Test Cases} + \label{table:hover_manager_tests} + \endlastfoot + + TC\testcount & FR12 & register() on init. & Registers hover for Python files. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & provideHover for JS file. & Returns undefined. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & provideHover with no cache. & Returns undefined. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & provideHover with non-matching line. & Returns undefined. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12, UHR-EOU 1 & provideHover with valid smell. & Returns hover with markdown details. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12, LFR-AP 1 & provideHover escapes markdown. & Output safely renders escaped characters. & All assertions pass. & \cellcolor{green} Pass \\ +\end{longtable} + + +\subsubsection{Line Selection Decorations} + +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.8cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{2.8cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{Line Selection Manager Test Cases} + \label{table:line_selection_tests} + \endlastfoot + + TC\testcount & FR12 & Construct manager. & Registers callback for smell updates. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & removeLastComment with decoration. & Disposes and clears decorated line. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & removeLastComment with no decoration. & Does nothing. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & commentLine with no editor. & Skips decoration. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & commentLine with multi-line selection. & Skips decoration. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & commentLine with no cached smells. & Calls removeLastComment. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & commentLine with mismatched line. & Does not decorate. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12, LFR-AP 1 & commentLine with one smell match. & Adds comment with smell type. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12, LFR-AP 1 & commentLine with multiple smells. & Adds comment with smell count. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & commentLine already decorated. & Skips redecoration. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & smellsUpdated for 'all'. & Clears comment. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & smellsUpdated for current file. & Clears comment. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR12 & smellsUpdated for unrelated file. & Skips clearing. & All assertions pass. & \cellcolor{green} Pass \\ +\end{longtable} + +\subsubsection{Cache Initialization From Previous Workspace State} + +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.8cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{2.8cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{Cache Initialization Test Cases} + \label{table:cache_init_tests} + \endlastfoot + + TC\testcount & FR11 & No workspace path configured. & Skips initialization and logs warning. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11 & File path outside workspace. & File is removed from cache. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11 & File no longer exists. & Cache is cleared for missing file. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11, PR-RFT 1 & File has smells. & Status is set to \texttt{passed} and smells restored. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11, PR-RFT 1 & File is clean. & Status is set to \texttt{no\_issues}. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR11, MS-MNT 5 & Mixed file scenarios (valid, missing, outside). & Accurate logs of valid, clean, and removed files. & All assertions pass. & \cellcolor{green} Pass \\ +\end{longtable} + + +\subsubsection{Smell Configuration Management} + +\begin{longtable}{c + >{\raggedright\arraybackslash}p{1.8cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{4.2cm} + >{\raggedright\arraybackslash}p{2.8cm} c} + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endfirsthead + + \multicolumn{6}{l}{\textit{(Continued from previous page)}} \\ + \toprule + \textbf{ID} & \textbf{Ref. Req.} & \textbf{Action} & + \textbf{Expected Result} & \textbf{Actual Result} & \textbf{Result} \\ + \midrule + \endhead + + \multicolumn{6}{r}{\textit{Continued on next page}} \\ + \endfoot + + \bottomrule + \caption{Smell Configuration Test Cases} + \label{table:smells_data_tests} + \endlastfoot + + TC\testcount & FR14, MS-MNT 3 & Load smell config file from disk. & JSON is parsed into smell config object. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Config file is missing. & Show error message. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Config file is invalid JSON. & Show error message and log. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Save smells config to disk. & File is written without error. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Save fails due to file error. & Show error and log failure. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Call \texttt{getFilterSmells()}. & Returns current loaded smell config. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Call \texttt{getEnabledSmells()}. & Returns enabled smells and options only. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Lookup acronym by known message ID. & Returns correct acronym. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Lookup acronym by unknown ID. & Returns undefined. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Lookup name by known message ID. & Returns correct name. & All assertions pass. & \cellcolor{green} Pass \\ + \midrule + + TC\testcount & FR14 & Lookup description by known message ID. & Returns correct description. & All assertions pass. & \cellcolor{green} Pass \\ +\end{longtable} + +\section{Changes Due to Testing} + +\wss{This section should highlight how feedback from the users and from + the supervisor (when one exists) shaped the final product. In particular + the feedback from the Rev 0 demo to the supervisor (or to potential users) +should be highlighted.} + +During the testing phase, several changes were made to the tool based +on feedback from user testing, supervisor reviews, and edge cases +encountered during unit and integration testing. These changes were +necessary to improve the tool's usability, functionality, and robustness. + +\subsection{Usability and User Input Adjustments} +One of the key findings from testing was the balance between +\textbf{automating refactorings} and \textbf{allowing user control} +over changes. Initially, the tool required users to manually approve +every refactoring, which slowed down the workflow. However, after +usability testing, it became evident that an \textbf{option to +refactor all occurrences of the same smell type} would significantly +improve efficiency. This led to the introduction of a +\textbf{``Refactor Smell of Same Type''} feature in the VS Code +extension, allowing users to apply the same refactoring across +multiple instances of a detected smell simultaneously. Additionally, +we refined the \textbf{Accept/Reject UI elements} to make them more +intuitive and streamlined the workflow for batch refactoring actions. + +\subsection{Detection and Refactoring Improvements} +Heavy modifications were made to the \textbf{detection and +refactoring modules}, particularly in handling \textbf{multi-file +projects}. Initially, the detectors and refactorers assumed a +\textbf{single-file scope}, leading to missed optimizations when +function calls or variable dependencies spanned across multiple files. After extensive testing, the detection system was updated to track \textbf{cross-file dependencies}, ensuring that refactoring suggestions accounted for the broader codebase. @@ -2515,7 +3168,7 @@ \subsection{Future Revisions and Remaining Work} \bigskip Overall, the testing phase played a crucial role in refining the -tool’s functionality, optimizing performance, and improving +tool's functionality, optimizing performance, and improving usability. The feedback gathered led to meaningful changes that enhance both the developer experience and the effectiveness of automated refactoring. @@ -2531,24 +3184,209 @@ \section{Automated Testing} \section{Trace to Requirements} +This section maps the tests performed to the requirements they validate, providing traceability between verification activities and project requirements. + +\begin{table}[H] + \centering + \caption{Functional Requirements and Corresponding Test Sections} + \begin{tabular}{p{0.42\textwidth}p{0.42\textwidth}} + \toprule \textbf{Test Section} & \textbf{Functional Requirement(s)} \\ + \midrule + Code Input Acceptance Tests & FR1 \\ + Code Smell Detection and Refactoring Suggestion Tests & FR2, FR3, FR4 \\ + Tests for Reporting Functionality & FR6, FR15 \\ + Visual Studio Code Interactions & FR8, FR9, FR10, FR11, FR12, FR13, FR14, FR15, FR16, FR17 \\ + Documentation Availability Tests & FR7, FR5 \\ + Installation and Onboarding Tests & FR7 \\ + \bottomrule + \end{tabular} + \label{tab:sections_requirements} +\end{table} + +Table \ref{tab:sections_requirements} shows the functional requirements and their corresponding test sections, ensuring all requirements have been properly tested. + + \begin{table}[H] + \centering + \caption{Look \& Feel Tests and Corresponding Requirements} + \label{tab:nfr-trace-lf} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + LF-1 & LFR-AP 1 \\ + LF-2 & LFR-ST 1, LFR-AP 2 \\ + % Note: LFR-AP 2 is tested indirectly in LF-2 + \bottomrule + \end{tabular} +\end{table} + +Table \ref{tab:nfr-trace-lf} maps the Look \& Feel test cases to their corresponding non-functional requirements. + + \begin{table}[H] + \centering + \caption{Usability \& Humanity Tests and Corresponding Requirements} + \label{tab:nfr-trace-uh} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + UH-1 & UHR-PSI 1, UHR-PSI 2 \\ + UH-2 & UHR-ACS 1 \\ + UH-3 & UHR-EOU 1 \\ + UH-4 & UHR-EOU 2 \\ + UH-5 & UHR-LRN 1 \\ + UH-6 & UHR-UPL 1 \\ + \bottomrule + \end{tabular} +\end{table} + +The usability and humanity requirements and their corresponding test cases are shown in Table \ref{tab:nfr-trace-uh}. + +\begin{table}[H] + \centering + \caption{Performance Tests and Corresponding Requirements} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + % Performance + PF-1 & PR-SL 1, PR-SL 2, PR-CR 1 \\ + \bottomrule + \end{tabular} + \label{tab:nfr-trace-perf} +\end{table} + +Performance requirements and their test cases are outlined in Table \ref{tab:nfr-trace-perf}. + + \begin{table}[H] + \centering + \caption{Operational \& Environmental Tests and Corresponding Requirements} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + % Operational and Environmental + Not explicitly tested & OER-EP 1 \\ + Not explicitly tested & OER-EP 2 \\ + OPE-1 & OER-WE 1 \\ + OPE-2 & OER-IAS 1 \\ + OPE-3 & OER-IAS 2 \\ + OPE-4 & OER-IAS 3 \\ + OPE-5 & OER-PR 1 \\ + Tested by FRs & OER-RL 1 \\ + Not explicitly tested & OER-RL 2 \\ + \bottomrule + \end{tabular} + \label{tab:nfr-trace-ope} + \end{table} + +Table \ref{tab:nfr-trace-ope} shows the operational and environmental requirements along with their test cases. + + \begin{table}[H] + \centering + \caption{Maintenance \& Support Tests and Corresponding Requirements} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + % Maintenance and Support + MS-1 & MS-MNT 1, PR-SER 1 \\ + MS-2 & MS-MNT 2 \\ + MS-3 & MS-MNT 3 \\ + Not explicitly tested & MS-MNT 4 \\ + \bottomrule + \end{tabular} + \label{tab:nfr-trace-ms} + \end{table} + +The maintenance and support requirements and their test cases are shown in Table \ref{tab:nfr-trace-ms}. + +\begin{table}[H] + \centering + \caption{Security Tests and Corresponding Requirements} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + SRT-1 & SR-IM 1 \\ + \bottomrule + \end{tabular} + \label{tab:nfr-trace-sec} +\end{table} + +Table \ref{tab:nfr-trace-sec} outlines the security requirements and their corresponding test cases. + + \begin{table}[H] + \centering + \caption{Compliance Tests and Corresponding Requirements} + \begin{tabular}{cc} + \toprule \textbf{Test ID (test-)} & \textbf{Non-Functional Requirement} \\ + \midrule + % Compliance + CPL-1 & CL-LR 1 \\ + CPL-2 & CL-SCR 1 \\ + \bottomrule + \end{tabular} + \label{tab:nfr-trace-comp} + \end{table} + +The compliance requirements and their test cases are outlined in Table \ref{tab:nfr-trace-comp}. + \section{Trace to Modules} +This section maps test cases to the specific modules they validated, organized by architectural levels to ensure comprehensive verification of our system. + +\begin{table}[H] + \centering + \caption{Tests for Behaviour-Hiding Modules} + \begin{tabular}{cc} + \toprule \textbf{Test ID (TC-)} & \textbf{Module} \\ + \midrule + TC1-TC10 & M1 (Smell) \\ + TC11-TC15 & M2 (BaseRefactorer) \\ + TC16-TC20 & M3 (MakeMethodStaticRefactorer) \\ + TC21-TC27 & M4 (UseListAccumulationRefactorer) \\ + TC28-TC35 & M5 (UseAGeneratorRefactorer) \\ + TC36-TC44 & M6 (CacheRepeatedCallsRefactorer) \\ + TC45-TC49 & M7 (LongElementChainRefactorer) \\ + TC50-TC56 & M8 (LongParameterListRefactorer) \\ + TC57-TC63 & M9 (LongMessageChainRefactorer) \\ + TC64-TC70 & M10 (LongLambdaFunctionRefactorer) \\ + TC71-TC75 & M11 (PluginInitiator) \\ + TC76-TC81 & M12 (BackendCommunicator) \\ + TC82-TC88 & M13 (SmellDetector) \\ + TC89-TC93 & M14 (FileHighlighter) \\ + TC94-TC98 & M15 (HoverManager) \\ + TC99-TC102 & M20 (CacheManager) \\ + TC103-TC114 & M21 (FilterManager) \\ + \bottomrule + \end{tabular} + \label{tab:behaviour_hiding_modules_tests} +\end{table} + +Table \ref{tab:behaviour_hiding_modules_tests} shows the mapping between test cases and the behavior-hiding modules they verify. + +\begin{table}[H] + \centering + \caption{Tests for Software Decision Modules} + \begin{tabular}{cc} + \toprule \textbf{Test ID (TC-)} & \textbf{Module} \\ + \midrule + TC115-TC120 & M16 (Measurements) \\ + TC121-TC125 & M17 (PylintAnalyzer) \\ + TC126-TC132 & M18 (SmellRefactorer) \\ + TC133-TC138 & M19 (RefactorManager) \\ + TC139-TC143 & M22 (EnergyMetrics) \\ + TC144-TC148 & M23 (ViewProvider) \\ + TC149-TC153 & M24 (EventManager) \\ + \bottomrule + \end{tabular} + \label{tab:software_decision_modules_tests} +\end{table} + +Table \ref{tab:software_decision_modules_tests} maps test cases to the software decision modules they validate. + \section{Code Coverage Metrics} -The following analyzes the code coverage metrics for the Python -backend and frontend (TypeScript) of the VSCode extension. The -analysis is based on the coverage data provided in Figure -\ref{img:python-cov} (Python backend) and Figure \ref{img:vscode-cov} +The following analyzes the code coverage metrics for the TypeScript frontend of the VSCode extension. The +analysis is based on the coverage data provided in Figure \ref{img:vscode-cov} (frontend). Code coverage is a measure of how well the codebase is tested, and it helps identify areas that may require additional testing. -\begin{figure}[H] - \centering - \includegraphics[width=0.7\textwidth]{../Images/python-coverage.png} - \caption{Coverage Report of the Python Backend Library} - \label{img:python-cov} -\end{figure} - \begin{figure}[H] \centering \includegraphics[width=0.7\textwidth]{../Images/vscode-coverage.png} @@ -2557,29 +3395,43 @@ \section{Code Coverage Metrics} \end{figure} \subsection{VSCode Extension} -The frontend codebase has an overall coverage of 45.43\% for -statements, 36.48\% for branches, 42.62\% for functions, and 45.53\% -for lines (Figure \ref{img:vscode-cov}). These metrics fall below the -global coverage thresholds of 80\% for the following reasons. The -file \texttt{extension.ts}, which contains the core logic for the -VSCode extension, has 0\% coverage as it is mainly made up of -initialization commands with no real logic that can be tested. The -file \texttt{refactorView.ts}, responsible for the refactoring view, -also has 0\% coverage. This module is a UI component and will be -tested for revision 1. Since \texttt{handleEditorChange.ts} is -closely related to the UI component, its testing has also been put off.\\ - -The file \texttt{refactorSmell.ts} has moderate coverage (55.37\% -statements, 45.23\% branches), with significant gaps in testing -around lines 143–269 and 328–337 (Figure \ref{img:vscode-cov}). This -is due to a feature that is not fully implemented and therefore not -tested. Finally, \texttt{configManager.ts} has not been tested as yet -due to evolving configuration options, but will be tested for revision 1. +The frontend codebase has an overall coverage of 96.99\% for +lines, 96.91\% for statements, 82.95\% for branches, and 95.09\% for functions +(Figure \ref{img:vscode-cov}). These metrics show significant test coverage across the codebase. +\noindent \textbf{Well-Tested Components:} Many critical components have excellent coverage, including: +\begin{itemize} + \item \texttt{resetConfiguration.ts}: 100\% coverage across all metrics + \item \texttt{wipeWorkCache.ts}: 100\% coverage across all metrics + \item \texttt{hoverManager.ts}: 100\% coverage across all metrics + \item \texttt{exportMetricsData.ts}: 100\% coverage across all metrics + \item \texttt{trackedDiffEditors.ts}: 100\% coverage across all metrics + \item \texttt{acceptRefactoring.ts}: 100\% line coverage (87.5\% branch coverage) + \item \texttt{refactor.ts}: 100\% line coverage (84.61\% branch coverage) + \item \texttt{normalizePath.ts}: 100\% coverage across all metrics +\end{itemize} + +\noindent \textbf{Areas for Improvement:} The following components still require testing attention: +\begin{itemize} + \item \texttt{backend.ts}: 98.96\% line coverage with uncovered line 124 + \item \texttt{configureWorkspace.ts}: 88.09\% line coverage with uncovered lines 59, 79-82, 91-94 + \item \texttt{detectSmells.ts}: 98.76\% line coverage with uncovered line 103 + \item \texttt{rejectRefactoring.ts}: 100\% line coverage but only 66.66\% branch coverage, with uncovered line 44 + \item \texttt{workspaceModifiedListener.ts}: 91.3\% line coverage but only 69.23\% branch coverage, with uncovered lines 58-59, 63-64, 71, 113 + \item \texttt{fileHighlighter.ts}: 95.08\% line coverage with uncovered lines 17-20 + \item \texttt{lineSelectionManager.ts}: 100\% line coverage but uncovered line 52 + \item \texttt{initializeStatusesFromCache.ts}: 97.82\% line coverage with uncovered line 96 + \item \texttt{refactorActionButtons.ts}: 87.5\% line coverage with uncovered lines 44-47, 61-64 + \item \texttt{smellsData.ts}: 100\% line coverage but only 62.5\% branch coverage, with uncovered lines 39, 117-120 +\end{itemize} + +\noindent \textbf{Future Testing:} While overall code coverage is excellent at 96.99\% for lines, there are still specific uncovered lines and branches in several components that should be addressed in future testing efforts. Improving branch coverage, especially in components with coverage below 70\%, should be prioritized. \subsection{Python Backend} The backend codebase has an overall coverage of 91\% (Figure \ref{img:python-cov}) and has been thoroughly tested as it contains -the key features of project and the bulk of the logic. The exception +the key features of project and the bulk of the logic. + +\noindent \textbf{Testing Exceptions:} The exception is \texttt{show\_logs.py}, which handles the websocket endpoint for logging, due to the complex nature of this module testing has been omitted. Since its function is mainly to broadcast logs it is also @@ -2597,7 +3449,7 @@ \section*{Purpose} identify usability issues that may hinder adoption by software developers. \section*{Objective} -Evaluate the usability of the extension’s \textbf{smell detection}, +Evaluate the usability of the extension's \textbf{smell detection}, \textbf{refactoring process}, \textbf{customization settings}, and \textbf{refactoring view}. @@ -2673,7 +3525,7 @@ \section*{Analysis and Reporting} \begin{itemize} \item \textbf{Critical:} Blocks users from completing tasks. \item \textbf{Major:} Causes significant frustration but has workarounds. - \item \textbf{Minor:} Slight inconvenience, but doesn’t impact + \item \textbf{Minor:} Slight inconvenience, but doesn't impact core functionality. \end{itemize} \item Provide recommendations for UI/UX improvements. @@ -2770,15 +3622,15 @@ \subsection*{Participant Data} The following links point to the data collected from each participant:\\ {\noindent - \href{run:./../Extras/UsabilityTesting/test_data/participant1-data.csv}{Participant + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/Extras/UsabilityTesting/test_data/participant1-data.csv}{Participant 1} \\[2mm] - \href{run:./../Extras/UsabilityTesting/test_data/participant2-data.csv}{Participant + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/Extras/UsabilityTesting/test_data/participant2-data.csv}{Participant 2} \\[2mm] - \href{run:./../Extras/UsabilityTesting/test_data/participant3-data.csv}{Participant + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/Extras/UsabilityTesting/test_data/participant3-data.csv}{Participant 3} \\[2mm] - \href{run:./../Extras/UsabilityTesting/test_data/participant4-data.csv}{Participant + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/Extras/UsabilityTesting/test_data/participant4-data.csv}{Participant 4} \\[2mm] - \href{run:./../Extras/UsabilityTesting/test_data/participant5-data.csv}{Participant + \href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/Extras/UsabilityTesting/test_data/participant5-data.csv}{Participant 5} } @@ -2786,14 +3638,14 @@ \subsection*{Pre-Test Survey Data} The following link points to a CSV file containing the pre-survey data:\\ \noindent -\href{run:./../Extras/UsabilityTesting/surveys/pre-test-survey-data.csv}{Click +\href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/Extras/UsabilityTesting/surveys/pre-test-survey-data.csv}{Click here to access the survey results CSV file}. \subsection*{Post-Test Survey Data} The following link points to a CSV file containing the post-survey data:\\ \noindent -\href{run:./../Extras/UsabilityTesting/surveys/post-test-survey-data.csv}{Click +\href{https://github.com/ssm-lab/capstone--source-code-optimizer/blob/main/docs/Extras/UsabilityTesting/surveys/post-test-survey-data.csv}{Click here to access the survey results CSV file}. \newpage{} @@ -2867,7 +3719,7 @@ \subsubsection*{Sevhena Walker} A big win was how much of our work naturally fed into the report. Since we had already been refining our verification and - validation (V\&V) process throughout development, we weren’t + validation (V\&V) process throughout development, we weren't starting from scratch, we just had to document what we had done. Having clear test cases in place made it easier to describe our approach and results, rather than writing purely in the abstract. @@ -3018,7 +3870,7 @@ \subsubsection*{Group} sections reference predefined specifications/industry standards rather than direct client input. \item \textbf{Implementation and Technical Explanations:} These - were formulated based on the development team’s decisions, + were formulated based on the development team's decisions, software documentation, and prior knowledge rather than external feedback. @@ -3102,7 +3954,7 @@ \subsubsection*{Group} with more thorough initial testing. If i could do it again I'd build more flexibility into the VnV Plan to account for unexpected results and allocate extra time - for debugging and edge-case testing. I’d also include a broader + for debugging and edge-case testing. I'd also include a broader range of test cases (e.g., multiline whitespace, wrong input) in the initial plan to catch these issues sooner. diff --git a/docs/projMngmnt/Final_Team_Contrib.pdf b/docs/projMngmnt/Final_Team_Contrib.pdf index a20c93d5..a5250709 100644 Binary files a/docs/projMngmnt/Final_Team_Contrib.pdf and b/docs/projMngmnt/Final_Team_Contrib.pdf differ diff --git a/plugin/README.md b/plugin/README.md index 92e9eac3..c669e627 100644 --- a/plugin/README.md +++ b/plugin/README.md @@ -1 +1,52 @@ -This submodule links to the vscode extension that wraps the python library created in this repository. It is the primary entry point for users to access our system. \ No newline at end of file +# VS Code Plugin Directory + +This directory contains the Visual Studio Code plugin implementation for the Source Code Optimizer project, providing integration with the VS Code IDE. + +## Directory Structure + +### Main Plugin Directory +- `capstone--sco-vs-code-plugin/` - VS Code extension implementation + +## Plugin Features + +1. Code Analysis Integration + - Real-time code smell detection + - Toggle automatic smell detection on/off + +2. Refactoring Tools + - Automated code refactoring + - Refactor one smell of a type + - Refactor all smells of a type + +3. User Interface + - Custom VS Code views + - Command palette integration + - Status bar indicators + +4. Configuration + - Plugin settings + - Rule customization + - Ignore certain smells + +## Development + +1. Setup Development Environment: + ```bash + cd capstone--sco-vs-code-plugin + npm install + ``` + +2. Build the Plugin: + ```bash + npm run build + ``` + +3. Debug the Plugin: + - Press F5 in VS Code + - Select "Run Extension" + +## Installation + +1. From VS Code Marketplace: + - Search for "Source Code Optimizer" + - Click Install diff --git a/refs/README.md b/refs/README.md index 9601b42d..d038b6eb 100644 --- a/refs/README.md +++ b/refs/README.md @@ -11,3 +11,26 @@ be in the format AuthorYear. If there is two author's the name should be Author1Author2Year. For more than two authors, the name should be Author1EtAlYear. In the preceding text, Author, Author1 and Author2 are the last names of the authors. + +# References Directory + +This directory contains bibliographic references and citations used throughout the Source Code Optimizer project documentation. + +## Directory Contents + +### Core Files +- `References.bib` - BibTeX database containing all project references + +## Usage + +1. Citing in Documentation: + - Use the reference key in LaTeX documents + - Follow consistent citation style + +## Maintenance Guidelines + +1. Regular Updates + - Add new relevant sources + - Update outdated references + - Remove obsolete citations + - Verify URLs and DOIs \ No newline at end of file diff --git a/refs/References.bib b/refs/References.bib index 22456ea0..a39df305 100644 --- a/refs/References.bib +++ b/refs/References.bib @@ -3,8 +3,53 @@ %% Created for Spencer Smith at 2023-03-24 13:04:27 -0400 - -%% Saved with string encoding Unicode (UTF-8) +@misc{gartner2023saas, + author = {{Gartner}}, + title = {SaaS Pricing Trends Report}, + year = {2023}, + url = {https://www.gartner.com/en/documents}, + note = {Accessed: 2023-10-01} +} + +@misc{codeGPTPricing, + author = {{codeGPT}}, + title = {CodeGPT Pricing}, + year = {2025}, + url = {https://codegpt.co/pricing}, + note = {Accessed: 2025-04-04} +} + +@misc{hubspot2025marketing, + author = {{HubSpot}}, + title = {Startup Marketing Cost Benchmarks}, + year = {2025}, + url = {https://www.hubspot.com/marketing-statistics}, + note = {Accessed: 2025-04-04} +} + +@misc{googlecloud2025pricing, + author = {{Google Cloud}}, + title = {Pricing Calculator}, + year = {2025}, + url = {https://cloud.google.com/products/calculator}, + note = {Accessed: 2025-04-04} +} + +@misc{upwork2025rates, + author = {{Upwork}}, + title = {Freelancer Rates Guide}, + year = {2025}, + url = {https://www.upwork.com/hire/software-developers/cost/}, + note = {Accessed: 2025-04-04} +} + +@misc{vscodeUsers, + author = {{Eyal Katz}}, + title = {Top 20 Best VScode Extensions for 2025}, + year = {2025}, + url = {https://www.jit.io/blog/vscode-extensions-for-2023}, + note = {Accessed: 2025-04-04} +} @unpublished{SRS, author = {Nivetha Kuruparan and Sevhena Walker and Mya Hussain and Ayushi Amin and Tanveer Brar}, @@ -267,6 +312,13 @@ @misc{pylint note = {Accessed: 2024-11-03} } +@misc{pep8, + title = {PEP 8 – Style Guide for Python Code}, + author = {Guido van Rossum and Barry Warsaw and Alyssa Coghlan}, + howpublished = {\url{https://peps.python.org/pep-0008/}}, + note = {Accessed: 2024-11-03} +} + @misc{ARTCanary, author = {{Canary}}, url = {https://github.com/redcanaryco/atomic-red-team/wiki}, diff --git a/src/ecooptimizer/README.md b/src/ecooptimizer/README.md index 50aa3a2c..85e8d077 100644 --- a/src/ecooptimizer/README.md +++ b/src/ecooptimizer/README.md @@ -1,5 +1,55 @@ -# Project Name Source Code +# EcoOptimizer Package -The folders and files for this project are as follows: +This is the main package for the Source Code Optimizer project, containing all core functionality for code analysis, optimization, and refactoring. -... +## Package Structure + +### Core Components +- `analyzers/` - Code analysis and smell detection modules +- `refactorers/` - Code refactoring implementations +- `measurements/` - Energy metric measurement tools +- `api/` - API endpoints and service interfaces + +### Support Modules +- `utils/` - Utility functions and helper modules +- `data_types/` - Core data structure definitions +- `data_wrappers/` - Data transformation and handling +- `testing/` - Testing utilities and helpers + +### Configuration +- `config.py` - Global configuration settings +- `__init__.py` - Package initialization +- `__main__.py` - Command-line interface entry point + +## Module Organization + +1. Code Analysis + - Smell detection engines + - Pattern recognition + - AST processing + - Metrics calculation + +2. Code Optimization + - Refactoring strategies + - Code transformations + - Performance improvements + - Style fixes + +3. Data Management + - Type definitions + - Data structures + - State management + - Persistence + +## Best Practices + +1. Code Quality + - Consistent style + - Error handling + +2. Testing + - Unit test coverage + +3. Maintenance + - Dependency management + - Version control diff --git a/tests/README.md b/tests/README.md index beda0859..f78d3377 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,5 +1,34 @@ -# Automated tests +# Tests Directory -The folders and files for this folder are as follows: +This directory contains all test-related files and directories for the Source Code Optimizer project. The tests are organized by component and functionality to ensure comprehensive coverage of the codebase. -Describe ... +## Directory Structure + +### Component Tests +- `analyzers/` - Tests for code analysis components +- `refactorers/` - Tests for code refactoring implementations +- `controllers/` - Tests for controller layer components +- `smells/` - Tests for code smell detection features +- `api/` - Tests for API endpoints and interfaces + +### Performance Tests +- `benchmarking/` - Performance and benchmark tests +- `measurements/` - Test metrics and measurement utilities + +### Test Resources +- `input/` - Test input files and fixtures +- `temp_dir/` - Temporary directory for test file operations +- `conftest.py` - PyTest configuration and shared fixtures + +## Test Development Guidelines + +1. Use meaningful test names that describe the scenario +2. Keep tests independent and isolated +3. Use appropriate fixtures and mocks +4. Maintain high code coverage + +## Maintenance + +1. Regular test suite maintenance and updates +2. Remove obsolete tests +3. Update tests when functionality changes