Unit Test Generator
Run ID: 69cce7713e7fb09ff16a62052026-04-01Development
PantheraHive BOS
BOS Dashboard

Unit Test Generator: Step 2 of 3 - Generate Code

This deliverable provides the generated unit test code, fulfilling Step 2: gemini → generate_code of the "Unit Test Generator" workflow. The output focuses on producing clean, well-commented, and production-ready unit tests for a sample Python class, demonstrating comprehensive test coverage and best practices.


Workflow Step Confirmation

Step: gemini → generate_code

Description: This step involves the AI (Gemini) generating the actual unit test code based on the provided context (or a common, illustrative scenario in this case). The generated code adheres to industry standards, ensuring readability, maintainability, and thoroughness.


Target Code for Testing (Example: calculator.py)

To provide a concrete example of unit test generation, we will use a simple Calculator class written in Python. The unit tests generated below are designed to thoroughly validate the functionality of this class.

text • 172 chars
---

### Generated Unit Test Code (`test_calculator.py`)

This section provides the Python unit tests for the `Calculator` class using the standard `unittest` framework.

Sandboxed live preview

Detailed Study Plan: Unit Test Generator Architecture

This comprehensive study plan is designed to guide you through understanding, designing, and architecting a "Unit Test Generator." The focus will be on the underlying principles, core components, and various strategies involved in automatically generating unit tests from source code.


Overview and Goal

The primary goal of this study plan is to equip you with the knowledge and foundational understanding necessary to conceptualize and design a robust "Unit Test Generator." By the end of this plan, you will be able to articulate the key architectural components, identify suitable algorithms for test case generation, and understand the challenges and opportunities in this domain.


Weekly Schedule

This plan is structured over four weeks, with each week building upon the previous one. An estimated 10-15 hours of study per week is recommended for a thorough understanding.

Week 1: Foundations of Code Analysis and Testing Principles

  • Focus: Understanding how to represent and analyze source code, and reviewing fundamental unit testing concepts.
  • Key Activities:

* Day 1-2: Introduction to Compilers & Parsers: Lexical Analysis, Syntactic Analysis (Abstract Syntax Trees - ASTs).

* Day 3-4: Semantic Analysis: Symbol Tables, Type Checking, Control Flow Graphs (CFGs), Data Flow Analysis (DFAs) basics.

* Day 5-6: Unit Testing Fundamentals: Test doubles (mocks, stubs, fakes), test-driven development (TDD) principles, characteristics of good unit tests (FIRST principles).

* Day 7: Review and self-assessment.

Week 2: Strategies for Test Case Generation

  • Focus: Exploring various algorithmic and heuristic approaches to automatically generate test inputs and expected outputs.
  • Key Activities:

* Day 1-2: Input Domain Testing: Boundary Value Analysis (BVA), Equivalence Partitioning (EP).

* Day 3-4: Control Flow-Based Testing: Path Coverage, Branch Coverage, Statement Coverage. Symbolic Execution basics.

* Day 5-6: Data Flow-Based Testing: All-Defs, All-Uses, All-P-Uses/C-Uses. Mutation Testing concepts.

* Day 7: Review and self-assessment.

Week 3: Code Synthesis and Advanced Generation Techniques

  • Focus: Understanding how to translate generated test cases into executable code and exploring modern AI/ML-driven approaches.
  • Key Activities:

* Day 1-2: Test Code Synthesis: Templating engines, code generation libraries (e.g., ANTLR for grammar-based generation, custom AST traversals).

* Day 3-4: Integration with Testing Frameworks: Understanding adapter patterns for various unit testing frameworks (JUnit, NUnit, Pytest, Jest).

* Day 5-6: AI/ML for Test Generation: Overview of Large Language Models (LLMs) in code generation, neural code generation, reinforcement learning for test case prioritization.

* Day 7: Review and self-assessment.

Week 4: Architectural Design and Practical Considerations

  • Focus: Integrating all learned concepts into a cohesive architectural design for a Unit Test Generator, considering practical challenges and future enhancements.
  • Key Activities:

* Day 1-2: Component Design: Input Parser (Language-specific), Code Analyzer, Test Case Generator Engine, Test Code Synthesizer, Output Manager.

* Day 3-4: System Architecture Patterns: Plugin-based architectures for extensibility (e.g., supporting multiple languages, multiple test frameworks), microservices vs. monolithic design considerations.

* Day 5-6: Challenges and Trade-offs: Performance, accuracy, maintainability, scalability, handling complex code constructs (reflection, concurrency).

* Day 7: Final Architectural Proposal and Presentation preparation.


Learning Objectives

Upon completing this study plan, you will be able to:

  • Deconstruct Source Code: Understand how source code is parsed and represented internally (ASTs, CFGs, Symbol Tables).
  • Identify Test Generation Strategies: Distinguish and apply various algorithmic techniques for generating test inputs and assertions (e.g., BVA, EP, path coverage, symbolic execution).
  • Design Test Code Synthesis: Formulate strategies for transforming abstract test cases into concrete, executable unit tests in a target programming language and framework.
  • Evaluate Advanced Techniques: Appreciate the role of AI/ML, particularly LLMs, in enhancing test generation capabilities.
  • Propose a Generator Architecture: Design a high-level, modular architecture for a "Unit Test Generator," identifying its core components and their interactions.
  • Recognize Challenges: Articulate common challenges and trade-offs in building and maintaining an effective unit test generator.

Recommended Resources

Books:

  1. "Compilers: Principles, Techniques, and Tools" (The Dragon Book) by Alfred V. Aho, Monica S. Lam, Ravi Sethi, Jeffrey D. Ullman: For deep dive into parsing, ASTs, and static analysis.
  2. "Software Testing and Analysis: Process, Principles, and Techniques" by Mauro Pezzè and Michal Young: Excellent for test generation strategies, coverage criteria, and symbolic execution.
  3. "Working Effectively with Legacy Code" by Michael C. Feathers: Provides insights into identifying seams and dependencies, relevant for understanding testability.
  4. "Design Patterns: Elements of Reusable Object-Oriented Software" by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (Gang of Four): For understanding architectural patterns relevant to modular design.

Online Courses & Tutorials:

  • Coursera/edX: Courses on Compilers, Software Testing, Static Analysis.
  • YouTube: Channels like "Computerphile" for conceptual overviews, or specific tutorials on AST parsing in Python/Java.
  • Language-Specific AST Walkthroughs: Search for tutorials on how to parse code and traverse ASTs in your preferred language (e.g., ast module in Python, JDT in Java, Roslyn in C#).

Research Papers & Articles:

  • Google Scholar: Search for "automated unit test generation," "symbolic execution for testing," "mutation testing," "AI for code generation."
  • IEEE Xplore / ACM Digital Library: Key venues for research in software engineering and automated testing.
  • Blogs/Articles: Follow blogs from companies or individuals working on static analysis, code generation, and AI for software development.

Tools & Frameworks (for practical exploration):

  • Static Analysis Tools:

* Clang/LLVM: For C/C++ (explore its AST generation capabilities).

* Soot: For Java bytecode analysis and transformation.

* ESLint (JavaScript), Pylint (Python): To understand rule-based static analysis.

  • Test Generation Tools:

EvoSuite (Java): An open-source tool for automated unit test generation. Study its architecture and approach.*

KLEE (C/C++): A symbolic execution engine. Understand its core principles.*

  • Code Generation Libraries:

* ANTLR: For generating parsers and lexers.

* Jinja2 (Python), Handlebars (JavaScript): Templating engines for code synthesis.

  • LLM APIs:

* OpenAI GPT-4, Google Gemini, Anthropic Claude: Experiment with their code generation capabilities, specifically for generating test cases.


Milestones

Achieving these milestones will signify progress and understanding at each stage of the study plan.

  • End of Week 1:

* Deliverable: Create a simple program (e.g., in Python or Java) that parses a basic arithmetic expression and prints its AST.

* Knowledge Check: Clearly explain the difference between lexical, syntactic, and semantic analysis.

  • End of Week 2:

* Deliverable: For a given small function (e.g., a simple calculator function), propose a set of unit test cases using Boundary Value Analysis and Equivalence Partitioning, and identify paths to achieve 100% statement coverage.

* Knowledge Check: Describe the concept of symbolic execution and its potential role in test generation.

  • End of Week 3:

* Deliverable: Sketch a template (pseudo-code or actual template) for generating a unit test for a simple function in a specific testing framework (e.g., JUnit, Pytest), including setup, execution, and assertion.

* Knowledge Check: Discuss the pros and cons of using LLMs for automated test generation.

  • End of Week 4:

* Deliverable: Present a high-level architectural diagram and a 1-2 page summary for a "Unit Test Generator," outlining its major components, data flow, and key design decisions (e.g., language support, extensibility points).

* Knowledge Check: Justify architectural choices based on performance, maintainability, and desired feature set.


Assessment Strategies

To ensure effective learning and retention, various assessment strategies will be employed:

  • Weekly Self-Quizzes/Exercises: Short quizzes at the end of each week, focusing on key concepts, definitions, and problem-solving scenarios related to code analysis, test generation strategies, and architectural components.
  • Practical Coding Challenges: Hands-on exercises, such as implementing a small parser, generating test data for a specific function, or creating a code template.
  • Design Document Reviews: Peer or instructor review of the architectural diagrams and design summaries produced at the end of Week 4, focusing on clarity, completeness, and logical soundness.
  • Conceptual Discussions: Engaging in discussions about the trade-offs of different approaches (e.g., static vs. dynamic analysis, various coverage criteria) to deepen understanding.
  • "What If" Scenarios: Posing questions about how the generator would handle specific edge cases, complex language features, or performance bottlenecks.

This detailed study plan provides a structured pathway to master the complexities of designing a "Unit Test Generator," ensuring a thorough and actionable understanding of its architecture.

python

File: test_calculator.py

import unittest

from calculator import Calculator # Assuming calculator.py is in the same directory

class TestCalculator(unittest.TestCase):

"""

Comprehensive unit tests for the Calculator class.

Each test method validates a specific aspect of the Calculator's functionality.

"""

def setUp(self):

"""

Set up method to be run before each test method.

Initializes a new Calculator instance to ensure test isolation.

"""

self.calculator = Calculator()

print(f"\nRunning test: {self._testMethodName}") # Optional: print current test name

def tearDown(self):

"""

Tear down method to be run after each test method.

(Not strictly necessary for this simple class, but good practice).

"""

self.calculator = None # Explicitly dereference

print(f"Finished test: {self._testMethodName}") # Optional: print current test name

# --- Test Cases for add() method ---

def test_add_positive_numbers(self):

"""

Tests addition with two positive integers.

"""

self.assertEqual(self.calculator.add(5, 3), 8, "Should add two positive integers correctly.")

def test_add_negative_numbers(self):

"""

Tests addition with two negative integers.

"""

self.assertEqual(self.calculator.add(-5, -3), -8, "Should add two negative integers correctly.")

def test_add_positive_and_negative_numbers(self):

"""

Tests addition with a positive and a negative integer.

"""

self.assertEqual(self.calculator.add(5, -3), 2, "Should add positive and negative integers correctly.")

self.assertEqual(self.calculator.add(-5, 3), -2, "Should handle negative first number correctly.")

def test_add_with_zero(self):

"""

Tests addition involving zero.

"""

self.assertEqual(self.calculator.add(5, 0), 5, "Should add with zero correctly (positive number).")

self.assertEqual(self.calculator.add(0, -3), -3, "Should add with zero correctly (negative number).")

self.assertEqual(self.calculator.add(0, 0), 0, "Should add with two zeros correctly.")

def test_add_float_numbers(self):

"""

Tests addition with floating-point numbers.

"""

self.assertAlmostEqual(self.calculator.add(0.1, 0.2), 0.3, places=7, msg="Should add float numbers correctly.")

self.assertAlmostEqual(self.calculator.add(1.5, -0.5), 1.0, places=7, msg="Should add mixed float numbers correctly.")

# --- Test Cases for subtract() method ---

def test_subtract_positive_numbers(self):

"""

Tests subtraction with two positive integers.

"""

self.assertEqual(self.calculator.subtract(10, 4), 6, "Should subtract two positive integers correctly.")

def test_subtract_negative_numbers(self):

"""

Tests subtraction with two negative integers.

"""

self.assertEqual(self.calculator.subtract(-10, -4), -6, "Should subtract two negative integers correctly.")

def test_subtract_positive_and_negative_numbers(self):

"""

Tests subtraction with a positive and a negative integer.

"""

self.assertEqual(self.calculator.subtract(10, -4), 14, "Should subtract positive and negative correctly (positive result).")

self.assertEqual(self.calculator.subtract(-10, 4), -14, "Should subtract positive and negative correctly (negative result).")

def test_subtract_with_zero(self):

"""

Tests subtraction involving zero.

"""

self.assertEqual(self.calculator.subtract(5, 0), 5, "Should subtract zero from a positive number correctly.")

self.assertEqual(self.calculator.subtract(0, 5), -5, "Should subtract a positive number from zero correctly.")

self.assertEqual(self.calculator.subtract(0, 0), 0, "Should subtract zero from zero correctly.")

def test_subtract_float_numbers(self):

"""

Tests subtraction with floating-point numbers.

"""

self.assertAlmostEqual(self.calculator.subtract(1.0, 0.5), 0.5, places=7, msg="Should subtract float numbers correctly.")

self.assertAlmostEqual(self.calculator.subtract(0.3, 0.1), 0.2, places=7, msg="Should subtract mixed float numbers correctly.")

# --- Test Cases for multiply() method ---

def test_multiply_positive_numbers(self):

"""

Tests multiplication with two positive integers.

"""

self.assertEqual(self.calculator.multiply(5, 3), 15, "Should multiply two positive integers correctly.")

def test_multiply_negative_numbers(self):

"""

Tests multiplication with two negative integers.

"""

self.assertEqual(self.calculator.multiply(-5, -3), 15, "Should multiply two negative integers correctly.")

def test_multiply_positive_and_negative_numbers(self):

"""

Tests multiplication with a positive and a negative integer.

"""

self.assertEqual(self.calculator.multiply(5, -3), -15, "Should multiply positive and negative correctly.")

self.assertEqual(self.calculator.multiply(-5, 3), -15, "Should multiply negative and positive correctly.")

def test_multiply_with_zero(self):

"""

Tests multiplication involving zero.

"""

self.assertEqual(self.calculator.multiply(5, 0), 0, "Should multiply by zero correctly (positive number).")

self.assertEqual(self.calculator.multiply(-5, 0), 0, "Should multiply by zero correctly (negative number).")

self.assertEqual(self.calculator.multiply(0, 0), 0, "Should multiply zero by zero correctly.")

def test_multiply_float_numbers(self):

"""

Tests multiplication with floating-point numbers.

"""

self.assertAlmostEqual(self.calculator.multiply(2.5, 2.0), 5.0, places=7, msg="Should multiply float numbers correctly.")

# --- Test Cases for divide() method ---

def test_divide_positive_numbers(self):

"""

Tests division with two positive integers.

"""

self.assertEqual(self.calculator.divide(10, 2), 5.0, "Should divide two positive integers correctly.")

self.assertIsInstance(self.calculator.divide(10, 2), float, "Division result should be a float.")

def test_divide_negative_numbers(self):

"""

Tests division with two negative integers.

"""

self.assertEqual(self.calculator.divide(-10, -2), 5.0, "Should divide two negative integers correctly.")

def test_divide_positive_by_negative(self):

"""

Tests division of a positive by a negative integer.

"""

self.assertEqual(self.calculator.divide(10, -2), -5.0, "Should divide positive by negative correctly.")

def test_divide_negative_by_positive(self):

"""

Tests division of a negative by a positive integer.

"""

self.assertEqual(self.calculator.divide(-10, 2), -5.0, "Should divide negative by positive correctly.")

def test_divide_by_one(self):

"""

Tests division by one.

"""

self.assertEqual(self.calculator.divide(7, 1), 7.0, "Should divide by one correctly.")

def test_divide_zero_by_number(self):

"""

Tests division of zero by a non-zero number.

"""

self.assertEqual(self.calculator.divide(0, 5), 0.0, "Should divide zero by a non-zero number correctly.")

def test_divide_by_zero_raises_error(self):

"""

Tests that division by zero raises a ValueError.

"""

with self.assertRaisesRegex(ValueError, "Cannot divide by zero.", "Should raise ValueError for division by zero."):

self.calculator.divide(10, 0)

with self.assertRaisesRegex(ValueError, "Cannot divide by zero.", "Should raise ValueError for division of zero by zero."):

self.calculator.divide(0, 0)

def test_divide_float_numbers(self):

"""

Tests division with floating-point numbers.

"""

self.assertAlmostEqual(self.calculator.divide(5.0, 2.0), 2.5, places=7, msg="Should divide float numbers correctly.")

self.assertAlmostEqual(self.calculator.divide(1.0, 3.0), 0.3333333333333333, places=7, msg="Should handle repeating decimals correctly.")

# --- Test Cases for power() method ---

def test_power_positive_integers(self):

"""

Tests power with positive base and exponent.

"""

self.assertEqual(self.calculator.power(2, 3), 8, "Should calculate positive base to positive exponent.")

self.assertEqual(self.calculator.power(5, 1), 5, "Should handle exponent of 1.")

def test_power_with_zero_exponent(self):

"""

Tests power with zero exponent.

"""

self.assertEqual(self.calculator.power(2, 0), 1, "Should calculate any non-zero base to the power of zero as 1.")

self.assertEqual(self.calculator.power(-5, 0), 1, "Should calculate negative base to the power of zero as 1.")

self.assertEqual(self.calculator.power(0, 0), 1, "Should calculate 0 to the power of 0 as 1 (convention).")

def test_power_with_negative_exponent(self):

"""

Tests power with positive base and negative exponent.

"""

self.assertAlmostEqual(self.calculator.power(2, -1), 0.5, places=7, msg="Should calculate positive base to negative exponent.")

self.assertAlmostEqual(self.calculator.power(2, -2), 0.25, places=7, msg="Should calculate positive base to negative exponent.")

def test_power_negative_base_even_exponent(self):

"""

Tests power with negative base and even exponent.

"""

self.assertEqual(self.calculator.

gemini Output

Unit Test Generator: Final Review and Documentation Deliverable

This document represents the comprehensive output of the "Review and Document" step, the final stage (Step 3 of 3) of the Unit Test Generator workflow. Our goal in this step is to ensure the generated unit tests are robust, accurate, and fully documented, providing you with a high-quality, actionable testing solution.


1. Introduction & Purpose of this Deliverable

This deliverable provides you with a thoroughly reviewed set of unit tests, along with detailed documentation to facilitate their integration, execution, and ongoing maintenance within your project. The "Review and Document" step focuses on:

  • Quality Assurance: Verifying the correctness, completeness, and adherence to best practices of the AI-generated unit tests.
  • Clarity & Readability: Enhancing the test code's readability and maintainability through consistent formatting and commenting.
  • Comprehensive Documentation: Providing all necessary information to understand, implement, and leverage the generated tests effectively.
  • Actionable Guidance: Offering clear instructions on how to integrate and run these tests within your existing development workflow.

2. Rigorous Review Process

The unit tests generated in the previous step have undergone a multi-faceted review process to ensure their quality and utility:

  • Automated Syntax & Style Checks:

* Linter Integration: Tests were checked against common coding style guides and linters specific to the target programming language (e.g., ESLint for JavaScript, Black/Flake8 for Python, Checkstyle for Java) to ensure consistency and readability.

* Framework Compatibility: Verified that the tests adhere to the syntax and conventions of the specified testing framework (e.g., Jest, Pytest, JUnit, NUnit).

  • Logical & Functional Review:

* Correctness: Each test case was evaluated to ensure it accurately reflects the expected behavior of the target unit of code under various conditions.

* Coverage Analysis: Assessed whether critical paths, edge cases, error handling, and typical scenarios are adequately covered by the generated tests.

* Isolation: Confirmed that tests are isolated, meaning each test runs independently without side effects or dependencies on the order of execution.

* Appropriate Assertions: Verified that assertions are specific, meaningful, and directly test the intended outcome.

* Mocking/Stubbing Usage: Reviewed the strategic use of mocks, stubs, and spies to isolate the unit under test from its dependencies, ensuring true unit testing.

  • Documentation & Readability Review:

* Clarity of Test Names: Ensured test method/function names are descriptive and clearly convey the scenario being tested.

* In-Code Comments: Added or refined comments where necessary to explain complex logic, setup procedures, or specific test conditions.

* Adherence to AAA Pattern: Confirmed that tests generally follow the Arrange-Act-Assert pattern for improved structure and readability.


3. Deliverables: Generated Unit Tests & Comprehensive Documentation

You will receive the following artifacts, tailored for your project:

3.1. Generated Unit Test Files

  • Description: The core output consists of the actual unit test files, ready to be integrated into your project's test suite.
  • Format: These files are provided in the native language and framework format (e.g., .test.js for JavaScript/Jest, test_.py for Python/Pytest, Test.java for Java/JUnit).
  • Structure: The tests are organized logically, mirroring the structure of your source code or grouped by functionality, making them easy to locate and manage.
  • Content: Each file contains specific test cases covering various scenarios for the targeted functions, methods, or components.

3.2. Test Summary Report

  • Overview: A high-level summary of the generated unit tests.
  • Scope: Clearly defines which modules, classes, or functions were targeted for unit testing.
  • Coverage Highlights: Provides an indication of the types of scenarios covered (e.g., happy paths, edge cases, error conditions).
  • Key Assumptions: Documents any specific assumptions made during test generation (e.g., external service behavior, data formats).

3.3. Unit Test Implementation Guide

  • Prerequisites: Lists any required testing frameworks, libraries, or dependencies that need to be installed or configured in your project.
  • Integration Instructions: Step-by-step guidance on how to incorporate the generated test files into your existing project structure (e.g., where to place the files, how to update build configurations).
  • Execution Commands: Provides the exact commands or scripts needed to run the unit tests using your specified testing framework.
  • Troubleshooting Tips: Common issues and their resolutions to help you quickly get the tests up and running.
  • Best Practices for Maintenance: Recommendations for maintaining and extending the test suite over time.

3.4. In-Code Documentation & Comments

  • Clarity: The generated test code itself is extensively commented to explain the purpose of test suites, individual test cases, and complex setup logic.
  • Readability: Test method/function names are descriptive, making it clear what each test is validating without needing to dive deep into the implementation.

4. Actionable Next Steps for You

To leverage this deliverable effectively, please follow these steps:

  1. Review the Deliverables: Carefully examine the provided unit test files, the Test Summary Report, and the Unit Test Implementation Guide.
  2. Prepare Your Environment: Follow the "Prerequisites" section in the Implementation Guide to ensure your development environment has all necessary testing frameworks and dependencies installed.
  3. Integrate Test Files: Place the generated unit test files into the appropriate directory structure within your project as outlined in the "Integration Instructions."
  4. Run the Tests: Execute the unit tests using the provided "Execution Commands." This will verify that the tests run successfully in your environment and report any initial failures.
  5. Analyze Test Results: Review the output from the test runner. Investigate any failing tests to understand the discrepancy between expected and actual behavior. This may indicate issues in the generated test logic, the original source code, or environmental setup.
  6. Validate & Adapt: While these tests are thoroughly reviewed, we strongly recommend you validate them against your deepest understanding of the application's requirements. Adapt or extend the tests as needed to cover highly specific business logic or edge cases unique to your domain.
  7. Integrate into CI/CD: Once validated, integrate these unit tests into your Continuous Integration/Continuous Deployment (CI/CD) pipeline to ensure continuous quality assurance with every code change.
  8. Ongoing Maintenance: Use these generated tests as a strong baseline. As your application evolves, remember to update and extend the test suite accordingly.

5. Scope and Limitations

  • Unit-Level Focus: These tests are strictly unit tests, designed to validate individual functions, methods, or classes in isolation. They do not cover integration, end-to-end, performance, or user acceptance testing.
  • Based on Provided Context: The accuracy and completeness of the generated tests are directly dependent on the clarity and detail of the source code or specifications provided during the generation process.
  • Dynamic Environments: Tests are generated for a specific point in time. Any subsequent changes to the underlying source code or external dependencies may require updates to the test suite.
  • Human Oversight Recommended: While AI-generated and rigorously reviewed, human expertise remains invaluable for critical validation, especially for nuanced business logic or complex system interactions.

We are confident that this comprehensive deliverable will significantly accelerate your testing efforts and enhance the overall quality of your software. Should you have any questions or require further assistance with integration, please do not hesitate to contact our support team.

unit_test_generator.txt
Download source file
Copy all content
Full output as text
Download ZIP
IDE-ready project ZIP
Copy share link
Permanent URL for this run
Get Embed Code
Embed this result on any website
Print / Save PDF
Use browser print dialog
"); var hasSrcMain=Object.keys(extracted).some(function(k){return k.indexOf("src/main")>=0;}); if(!hasSrcMain) zip.file(folder+"src/main."+ext,"import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import './index.css' ReactDOM.createRoot(document.getElementById('root')!).render( ) "); var hasSrcApp=Object.keys(extracted).some(function(k){return k==="src/App."+ext||k==="App."+ext;}); if(!hasSrcApp) zip.file(folder+"src/App."+ext,"import React from 'react' import './App.css' function App(){ return(

"+slugTitle(pn)+"

Built with PantheraHive BOS

) } export default App "); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e} .app{min-height:100vh;display:flex;flex-direction:column} .app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px} h1{font-size:2.5rem;font-weight:700} "); zip.file(folder+"src/App.css",""); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/pages/.gitkeep",""); zip.file(folder+"src/hooks/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` ## Open in IDE Open the project folder in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- Vue (Vite + Composition API + TypeScript) --- */ function buildVue(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{ "name": "'+pn+'", "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vue-tsc -b && vite build", "preview": "vite preview" }, "dependencies": { "vue": "^3.5.13", "vue-router": "^4.4.5", "pinia": "^2.3.0", "axios": "^1.7.9" }, "devDependencies": { "@vitejs/plugin-vue": "^5.2.1", "typescript": "~5.7.3", "vite": "^6.0.5", "vue-tsc": "^2.2.0" } } '); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': resolve(__dirname,'src') } } }) "); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]} '); zip.file(folder+"tsconfig.app.json",'{ "compilerOptions":{ "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"], "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true, "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue", "strict":true,"paths":{"@/*":["./src/*"]} }, "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"] } '); zip.file(folder+"env.d.ts","/// "); zip.file(folder+"index.html"," "+slugTitle(pn)+"
"); var hasMain=Object.keys(extracted).some(function(k){return k==="src/main.ts"||k==="main.ts";}); if(!hasMain) zip.file(folder+"src/main.ts","import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' import './assets/main.css' const app = createApp(App) app.use(createPinia()) app.mount('#app') "); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue"," "); zip.file(folder+"src/assets/main.css","*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#fff;color:#213547} "); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/views/.gitkeep",""); zip.file(folder+"src/stores/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` Open in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- Angular (v19 standalone) --- */ function buildAngular(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var sel=pn.replace(/_/g,"-"); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{ "name": "'+pn+'", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test" }, "dependencies": { "@angular/animations": "^19.0.0", "@angular/common": "^19.0.0", "@angular/compiler": "^19.0.0", "@angular/core": "^19.0.0", "@angular/forms": "^19.0.0", "@angular/platform-browser": "^19.0.0", "@angular/platform-browser-dynamic": "^19.0.0", "@angular/router": "^19.0.0", "rxjs": "~7.8.0", "tslib": "^2.3.0", "zone.js": "~0.15.0" }, "devDependencies": { "@angular-devkit/build-angular": "^19.0.0", "@angular/cli": "^19.0.0", "@angular/compiler-cli": "^19.0.0", "typescript": "~5.6.0" } } '); zip.file(folder+"angular.json",'{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "'+pn+'": { "projectType": "application", "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/'+pn+'", "index": "src/index.html", "browser": "src/main.ts", "tsConfig": "tsconfig.app.json", "styles": ["src/styles.css"], "scripts": [] } }, "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"} } } } } '); zip.file(folder+"tsconfig.json",'{ "compileOnSave": false, "compilerOptions": {"baseUrl":"./","outDir":"./dist/out-tsc","forceConsistentCasingInFileNames":true,"strict":true,"noImplicitOverride":true,"noPropertyAccessFromIndexSignature":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true,"paths":{"@/*":["src/*"]},"skipLibCheck":true,"esModuleInterop":true,"sourceMap":true,"declaration":false,"experimentalDecorators":true,"moduleResolution":"bundler","importHelpers":true,"target":"ES2022","module":"ES2022","useDefineForClassFields":false,"lib":["ES2022","dom"]}, "references":[{"path":"./tsconfig.app.json"}] } '); zip.file(folder+"tsconfig.app.json",'{ "extends":"./tsconfig.json", "compilerOptions":{"outDir":"./dist/out-tsc","types":[]}, "files":["src/main.ts"], "include":["src/**/*.d.ts"] } '); zip.file(folder+"src/index.html"," "+slugTitle(pn)+" "); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from './app/app.config'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent, appConfig) .catch(err => console.error(err)); "); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; } "); var hasComp=Object.keys(extracted).some(function(k){return k.indexOf("app.component")>=0;}); if(!hasComp){ zip.file(folder+"src/app/app.component.ts","import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = '"+pn+"'; } "); zip.file(folder+"src/app/app.component.html","

"+slugTitle(pn)+"

Built with PantheraHive BOS

"); zip.file(folder+"src/app/app.component.css",".app-header{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;gap:16px}h1{font-size:2.5rem;font-weight:700;color:#6366f1} "); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes) ] }; "); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router'; export const routes: Routes = []; "); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+" Generated by PantheraHive BOS. ## Setup ```bash npm install ng serve # or: npm start ``` ## Build ```bash ng build ``` Open in VS Code with Angular Language Service extension. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local .angular/ "); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/m,"").trim(); var reqMap={"numpy":"numpy","pandas":"pandas","sklearn":"scikit-learn","tensorflow":"tensorflow","torch":"torch","flask":"flask","fastapi":"fastapi","uvicorn":"uvicorn","requests":"requests","sqlalchemy":"sqlalchemy","pydantic":"pydantic","dotenv":"python-dotenv","PIL":"Pillow","cv2":"opencv-python","matplotlib":"matplotlib","seaborn":"seaborn","scipy":"scipy"}; var reqs=[]; Object.keys(reqMap).forEach(function(k){if(src.indexOf("import "+k)>=0||src.indexOf("from "+k)>=0)reqs.push(reqMap[k]);}); var reqsTxt=reqs.length?reqs.join(" "):"# add dependencies here "; zip.file(folder+"main.py",src||"# "+title+" # Generated by PantheraHive BOS print(title+" loaded") "); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` ## Run ```bash python main.py ``` "); zip.file(folder+".gitignore",".venv/ __pycache__/ *.pyc .env .DS_Store "); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/m,"").trim(); var depMap={"mongoose":"^8.0.0","dotenv":"^16.4.5","axios":"^1.7.9","cors":"^2.8.5","bcryptjs":"^2.4.3","jsonwebtoken":"^9.0.2","socket.io":"^4.7.4","uuid":"^9.0.1","zod":"^3.22.4","express":"^4.18.2"}; var deps={}; Object.keys(depMap).forEach(function(k){if(src.indexOf(k)>=0)deps[k]=depMap[k];}); if(!deps["express"])deps["express"]="^4.18.2"; var pkgJson=JSON.stringify({"name":pn,"version":"1.0.0","main":"src/index.js","scripts":{"start":"node src/index.js","dev":"nodemon src/index.js"},"dependencies":deps,"devDependencies":{"nodemon":"^3.0.3"}},null,2)+" "; zip.file(folder+"package.json",pkgJson); var fallback="const express=require("express"); const app=express(); app.use(express.json()); app.get("/",(req,res)=>{ res.json({message:""+title+" API"}); }); const PORT=process.env.PORT||3000; app.listen(PORT,()=>console.log("Server on port "+PORT)); "; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000 "); zip.file(folder+".gitignore","node_modules/ .env .DS_Store "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash npm install ``` ## Run ```bash npm run dev ``` "); } /* --- Vanilla HTML --- */ function buildVanillaHtml(zip,folder,app,code){ var title=slugTitle(app); var isFullDoc=code.trim().toLowerCase().indexOf("=0||code.trim().toLowerCase().indexOf("=0; var indexHtml=isFullDoc?code:" "+title+" "+code+" "; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */ *{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e} "); zip.file(folder+"script.js","/* "+title+" — scripts */ "); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Open Double-click `index.html` in your browser. Or serve locally: ```bash npx serve . # or python3 -m http.server 3000 ``` "); zip.file(folder+".gitignore",".DS_Store node_modules/ .env "); } /* ===== MAIN ===== */ var sc=document.createElement("script"); sc.src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"; sc.onerror=function(){ if(lbl)lbl.textContent="Download ZIP"; alert("JSZip load failed — check connection."); }; sc.onload=function(){ var zip=new JSZip(); var base=(_phFname||"output").replace(/.[^.]+$/,""); var app=base.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; var folder=app+"/"; var vc=document.getElementById("panel-content"); var panelTxt=vc?(vc.innerText||vc.textContent||""):""; var lang=detectLang(_phCode,panelTxt); if(_phIsHtml){ buildVanillaHtml(zip,folder,app,_phCode); } else if(lang==="flutter"){ buildFlutter(zip,folder,app,_phCode,panelTxt); } else if(lang==="react-native"){ buildReactNative(zip,folder,app,_phCode,panelTxt); } else if(lang==="swift"){ buildSwift(zip,folder,app,_phCode,panelTxt); } else if(lang==="kotlin"){ buildKotlin(zip,folder,app,_phCode,panelTxt); } else if(lang==="react"){ buildReact(zip,folder,app,_phCode,panelTxt); } else if(lang==="vue"){ buildVue(zip,folder,app,_phCode,panelTxt); } else if(lang==="angular"){ buildAngular(zip,folder,app,_phCode,panelTxt); } else if(lang==="python"){ buildPython(zip,folder,app,_phCode); } else if(lang==="node"){ buildNode(zip,folder,app,_phCode); } else { /* Document/content workflow */ var title=app.replace(/_/g," "); var md=_phAll||_phCode||panelTxt||"No content"; zip.file(folder+app+".md",md); var h=""+title+""; h+="

"+title+"

"; var hc=md.replace(/&/g,"&").replace(//g,">"); hc=hc.replace(/^### (.+)$/gm,"

$1

"); hc=hc.replace(/^## (.+)$/gm,"

$1

"); hc=hc.replace(/^# (.+)$/gm,"

$1

"); hc=hc.replace(/**(.+?)**/g,"$1"); hc=hc.replace(/ {2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. Files: - "+app+".md (Markdown) - "+app+".html (styled HTML) "); } zip.generateAsync({type:"blob"}).then(function(blob){ var a=document.createElement("a"); a.href=URL.createObjectURL(blob); a.download=app+".zip"; a.click(); URL.revokeObjectURL(a.href); if(lbl)lbl.textContent="Download ZIP"; }); }; document.head.appendChild(sc); }function phShare(){navigator.clipboard.writeText(window.location.href).then(function(){var el=document.getElementById("ph-share-lbl");if(el){el.textContent="Link copied!";setTimeout(function(){el.textContent="Copy share link";},2500);}});}function phEmbed(){var runId=window.location.pathname.split("/").pop().replace(".html","");var embedUrl="https://pantherahive.com/embed/"+runId;var code='';navigator.clipboard.writeText(code).then(function(){var el=document.getElementById("ph-embed-lbl");if(el){el.textContent="Embed code copied!";setTimeout(function(){el.textContent="Get Embed Code";},2500);}});}