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

Workflow Step Execution: Unit Test Generator - Step 2 of 3: Code Generation

This document details the successful execution of Step 2: Code Generation within the "Unit Test Generator" workflow. In this step, the AI (Gemini) has generated comprehensive, well-structured, and production-ready unit test code based on the implicit requirement for generating tests for a given (or hypothetical, in this demonstration) piece of software.


1. Objective of this Step

The primary objective of this "Code Generation" step is to produce high-quality unit tests that thoroughly validate the functionality of a specific code module or class. This involves:

For this demonstration, we will generate unit tests for a hypothetical Calculator class in Python, showcasing a practical application of this step.


2. Example Scenario: Calculator Class

To illustrate the unit test generation process, we will consider a simple Calculator class written in Python. This class will provide basic arithmetic operations: addition, subtraction, multiplication, and division.


3. Generated Source Code (Target for Testing)

Below is the example Calculator class for which the unit tests will be generated. This code is provided for context.

text • 197 chars
---

### 4. Generated Unit Test Code

Here is the comprehensive, detailed, and professional unit test code generated for the `Calculator` class, utilizing Python's built-in `unittest` framework.

Sandboxed live preview

Study Plan: Unit Test Generator - Foundations and Architectural Planning

This document outlines a comprehensive study plan designed to equip you with the foundational knowledge and advanced insights necessary to plan the architecture for a "Unit Test Generator." The plan progresses from core unit testing principles to advanced automated test generation techniques, culminating in a focus on AI-driven approaches and architectural considerations.


Overall Goal

To develop a deep understanding of unit testing principles, frameworks, and advanced techniques for generating unit tests, including AI-driven approaches, in order to inform and design the robust architecture of a "Unit Test Generator" system.


Weekly Schedule & Focus Areas

This 4-week study plan assumes approximately 10-15 hours of dedicated study per week, including reading, coding exercises, and conceptual design.

Week 1: Foundations of Unit Testing & Manual Test Writing

  • Focus: Establish a strong understanding of unit testing fundamentals, best practices, and hands-on experience with a chosen unit testing framework.
  • Key Topics:

* What is a unit test? Why is it important?

* Principles of good unit tests (FIRST: Fast, Independent, Repeatable, Self-validating, Timely).

* Anatomy of a unit test (Arrange-Act-Assert).

* Introduction to a specific unit testing framework (e.g., JUnit for Java, Pytest for Python, Jest for JavaScript, xUnit for C#).

* Writing basic unit tests for simple functions/classes.

* Introduction to test doubles (mocks, stubs, fakes, spies, dummies) – conceptual overview.

Week 2: Advanced Unit Testing & Test Design Patterns

  • Focus: Deepen understanding of test doubles, embrace Test-Driven Development (TDD), and explore techniques for comprehensive and maintainable tests.
  • Key Topics:

* Detailed usage of test doubles: when and how to use mocks, stubs, and spies effectively.

* Test-Driven Development (TDD) cycle: Red-Green-Refactor.

* Code Coverage: Metrics (line, branch, function) and tools (e.g., JaCoCo, Coverage.py, Istanbul/nyc).

* Refactoring tests: improving readability, maintainability, and performance of existing test suites.

* Testing challenging scenarios: private methods (consider alternatives), error handling, asynchronous operations.

* Introduction to property-based testing (e.g., Hypothesis for Python, QuickCheck for Haskell/others) – conceptual overview.

Week 3: Principles of Automated Test Generation (Non-AI Approaches)

  • Focus: Explore systematic and programmatic methods for generating unit tests, moving beyond manual test writing.
  • Key Topics:

* Static Analysis for Test Generation:

* Parsing Abstract Syntax Trees (ASTs) of code.

* Identifying functions, parameters, return types.

* Generating boilerplate tests (e.g., null checks, empty string checks, basic constructor tests).

* Exploring tools/libraries that perform static analysis (e.g., ANTLR, Python's ast module).

* Property-Based Testing in Practice:

* Using a property-based testing framework to generate diverse inputs and assert invariants.

* Designing properties for robust testing.

* Contract-Based Testing:

* Generating tests based on defined interfaces, APIs, or design contracts.

* Exploring tools that infer contracts or use formal specifications.

* Model-Based Testing (Conceptual):

* Understanding how models of system behavior can be used to generate test cases.

Week 4: AI/ML for Test Generation & Architectural Considerations

  • Focus: Dive into the cutting edge of test generation using AI and Machine Learning, and begin to formulate the architectural blueprint for a "Unit Test Generator" system.
  • Key Topics:

* Introduction to AI/ML for Code Generation:

* Overview of Large Language Models (LLMs) and their capabilities in code understanding and generation.

* Techniques for prompt engineering for test generation.

* Approaches to AI-Driven Test Generation:

* Generating tests from code context (function signatures, existing code logic).

* Generating tests from natural language requirements or documentation.

* Leveraging existing test suites to learn patterns and generate new tests.

* Challenges and limitations of AI-generated tests (correctness, relevance, completeness).

* Architectural Design Principles for a "Unit Test Generator":

* Input/Output formats (source code, ASTs, test code).

* Core components: Code Parser, Test Strategy Engine (static analysis, property generation, AI integration), Test Code Emitter.

* Integration points: IDEs, CI/CD pipelines.

* Scalability, extensibility, and configurability.

* Technology stack considerations (language for the generator, AI models/APIs).

* Ethical considerations and bias in AI-generated tests.


Learning Objectives

Upon completion of this study plan, you will be able to:

  • Master Core Unit Testing Concepts: Articulate the purpose, principles, and best practices of unit testing.
  • Proficiently Write Unit Tests: Independently write comprehensive and maintainable unit tests using a chosen framework, including effective use of test doubles and TDD.
  • Understand Automated Test Generation Techniques: Explain and apply various programmatic methods for generating tests, such as static analysis and property-based testing.
  • Evaluate AI/ML for Test Generation: Understand the potential and limitations of AI/LLMs in generating unit tests, and identify key considerations for their integration.
  • Design Generator Architecture: Outline a preliminary, high-level architectural design for a "Unit Test Generator" system, detailing its core components, inputs, outputs, and integration strategies.
  • Identify Key Challenges: Recognize and articulate the technical and practical challenges associated with building and deploying an automated unit test generator.

Recommended Resources

  • Books:

* "The Art of Unit Testing" by Roy Osherove

* "Working Effectively with Legacy Code" by Michael C. Feathers (Chapter on characterization tests)

* "Clean Code" by Robert C. Martin (Chapter on Unit Tests)

* "Test-Driven Development by Example" by Kent Beck

  • Online Courses/Platforms:

* Coursera, Udemy, Pluralsight: Search for "Unit Testing [Language]", "TDD", "Software Testing Automation".

* Specific framework tutorials (e.g., JUnit 5 documentation, Pytest documentation, Jest documentation).

  • Academic Papers & Research:

* Search for "Automated Test Generation," "AI for Code Testing," "Property-Based Testing."

* Key authors: John Hughes (QuickCheck), Michael O. Stepp (AI for testing).

  • Blogs & Articles:

* Martin Fowler's blog (especially on mocks vs. stubs, TDD).

* Articles on static analysis tools and their application to code.

* Recent publications on LLMs in software engineering (e.g., GitHub Copilot, AlphaCode research).

  • Tools & Frameworks (choose based on your primary language):

* Unit Testing: JUnit (Java), Pytest/unittest (Python), Jest/Mocha (JavaScript), xUnit/NUnit (C#), Go testing package (Go).

* Mocking: Mockito (Java), unittest.mock (Python), Jest's mocking features (JS).

* Code Coverage: JaCoCo (Java), Coverage.py (Python), Istanbul/nyc (JavaScript).

* Property-Based Testing: Hypothesis (Python), QuickCheck (Haskell, ports to other languages).

* Static Analysis: ANTLR (parser generator), Abstract Syntax Tree (AST) libraries for your language.

* AI/LLM APIs: OpenAI API, Google Gemini API, Hugging Face models.


Milestones

  • End of Week 1: Successfully write a comprehensive suite of unit tests for a small, well-defined module (e.g., a utility class, a simple data structure) using your chosen framework, adhering to FIRST principles.
  • End of Week 2: Implement a new feature using the TDD cycle, achieving high code coverage (e.g., >80% line coverage) and demonstrating effective use of test doubles. Refactor an existing, poorly tested code segment to improve its testability and test coverage.
  • End of Week 3: Develop a proof-of-concept script that uses static analysis (e.g., parsing an AST) to generate boilerplate unit tests (e.g., constructor tests, basic getter/setter tests, null checks) for a given class or function signature. Alternatively, successfully apply property-based testing to uncover edge cases in a small algorithm.
  • End of Week 4: Produce a preliminary architectural design document for the "Unit Test Generator" system, detailing its main components, proposed technologies, data flow, and key integration points. Include a section on how AI/LLMs would be incorporated and the challenges anticipated.

Assessment Strategies

  • Practical Coding Exercises: Implement unit tests for given codebases, refactor existing tests, and develop small test generation scripts.
  • Code Reviews: Peer or self-review of written tests and generated test code against best practices and design principles.
  • Design Document Submission: The preliminary architectural design for the "Unit Test Generator" will serve as a key deliverable, assessed for clarity, completeness, and technical soundness.
  • Concept Quizzes/Discussions: Short quizzes or facilitated discussions to test understanding of unit testing principles, TDD, and automated test generation techniques.
  • Presentation (Optional): Present the architectural design and key learnings to a small group for feedback and discussion.

This detailed study plan provides a structured pathway to master the necessary knowledge for designing a sophisticated "Unit Test Generator," moving from fundamental concepts to advanced architectural considerations.

python

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 focuses on a specific functionality or edge case

of the Calculator class.

"""

def setUp(self):

"""

Set up method to initialize a new Calculator instance before each test.

This ensures that tests are independent and start with a clean state.

"""

self.calculator = Calculator()

print(f"\nSetting up a new Calculator for test: {self._testMethodName}")

def tearDown(self):

"""

Tear down method to clean up resources after each test (if any are needed).

For this simple class, no specific cleanup is required.

"""

print(f"Tearing down Calculator after test: {self._testMethodName}")

del self.calculator # Explicitly delete the instance for clarity

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

def test_add_positive_numbers(self):

"""

Test case for adding two positive numbers.

Expected: Sum of the two numbers.

"""

result = self.calculator.add(5, 3)

self.assertEqual(result, 8, "Should correctly add two positive integers.")

def test_add_negative_numbers(self):

"""

Test case for adding two negative numbers.

Expected: Sum of the two negative numbers.

"""

result = self.calculator.add(-5, -3)

self.assertEqual(result, -8, "Should correctly add two negative integers.")

def test_add_positive_and_negative_numbers(self):

"""

Test case for adding a positive and a negative number.

Expected: The algebraic sum.

"""

result = self.calculator.add(5, -3)

self.assertEqual(result, 2, "Should correctly add positive and negative integers.")

result = self.calculator.add(-5, 3)

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

def test_add_zero(self):

"""

Test case for adding a number to zero.

Expected: The number itself.

"""

result = self.calculator.add(7, 0)

self.assertEqual(result, 7, "Should correctly add a number to zero.")

result = self.calculator.add(0, -7)

self.assertEqual(result, -7, "Should correctly add zero to a negative number.")

def test_add_float_numbers(self):

"""

Test case for adding floating-point numbers.

Expected: Sum with floating-point precision.

"""

result = self.calculator.add(2.5, 3.5)

self.assertEqual(result, 6.0, "Should correctly add floating point numbers.")

result = self.calculator.add(0.1, 0.2)

# Using assertAlmostEqual for floating point comparisons to avoid precision issues

self.assertAlmostEqual(result, 0.3, places=7, msg="Should handle float precision.")

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

def test_subtract_positive_numbers(self):

"""

Test case for subtracting two positive numbers.

Expected: Difference.

"""

result = self.calculator.subtract(10, 4)

self.assertEqual(result, 6, "Should correctly subtract two positive integers.")

def test_subtract_negative_numbers(self):

"""

Test case for subtracting two negative numbers.

Expected: Difference.

"""

result = self.calculator.subtract(-10, -4)

self.assertEqual(result, -6, "Should correctly subtract two negative integers.")

def test_subtract_mixed_numbers(self):

"""

Test case for subtracting a mix of positive and negative numbers.

Expected: Algebraic difference.

"""

result = self.calculator.subtract(10, -4)

self.assertEqual(result, 14, "Should correctly subtract a negative from a positive.")

result = self.calculator.subtract(-10, 4)

self.assertEqual(result, -14, "Should correctly subtract a positive from a negative.")

def test_subtract_zero(self):

"""

Test case for subtracting zero from a number, or a number from itself.

Expected: Number itself, or zero.

"""

result = self.calculator.subtract(8, 0)

self.assertEqual(result, 8, "Should correctly subtract zero from a number.")

result = self.calculator.subtract(5, 5)

self.assertEqual(result, 0, "Should return zero when subtracting a number from itself.")

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

def test_multiply_positive_numbers(self):

"""

Test case for multiplying two positive numbers.

Expected: Product.

"""

result = self.calculator.multiply(5, 3)

self.assertEqual(result, 15, "Should correctly multiply two positive integers.")

def test_multiply_negative_numbers(self):

"""

Test case for multiplying two negative numbers.

Expected: Positive product.

"""

result = self.calculator.multiply(-5, -3)

self.assertEqual(result, 15, "Should correctly multiply two negative integers.")

def test_multiply_mixed_numbers(self):

"""

Test case for multiplying a positive and a negative number.

Expected: Negative product.

"""

result = self.calculator.multiply(5, -3)

self.assertEqual(result, -15, "Should correctly multiply positive and negative integers.")

result = self.calculator.multiply(-5, 3)

self.assertEqual(result, -15, "Should correctly multiply negative and positive integers.")

def test_multiply_by_zero(self):

"""

Test case for multiplying any number by zero.

Expected: Zero.

"""

result = self.calculator.multiply(10, 0)

self.assertEqual(result, 0, "Should return zero when multiplying by zero.")

result = self.calculator.multiply(-10, 0)

self.assertEqual(result, 0, "Should return zero when multiplying a negative number by zero.")

def test_multiply_by_one(self):

"""

Test case for multiplying any number by one.

Expected: The number itself.

"""

result = self.calculator.multiply(10, 1)

self.assertEqual(result, 10, "Should return the number itself when multiplying by one.")

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

def test_divide_positive_numbers(self):

"""

Test case for dividing two positive numbers.

Expected: Quotient.

"""

result = self.calculator.divide(10, 2)

self.assertEqual(result, 5.0, "Should correctly divide two positive integers.")

def test_divide_negative_numbers(self):

"""

Test case for dividing two negative numbers.

Expected: Positive quotient.

"""

result = self.calculator.divide(-10, -2)

self.assertEqual(result, 5.0, "Should correctly divide two negative integers.")

def test_divide_mixed_numbers(self):

"""

Test case for dividing a positive by a negative, or vice versa.

Expected: Negative quotient.

"""

result = self.calculator.divide(10, -2)

self.assertEqual(result, -5.0, "Should correctly divide positive by negative.")

result = self.calculator.divide(-10, 2)

self.assertEqual(result, -5.0, "Should correctly divide negative by positive.")

def test_divide_by_one(self):

"""

Test case for dividing a number by one.

Expected: The number itself.

"""

result = self.calculator.divide(7, 1)

self.assertEqual(result, 7.0, "Should return the number itself when dividing by one.")

def test_divide_zero_by_number(self):

"""

Test case for dividing zero by any non-zero number.

Expected: Zero.

"""

result = self.calculator.divide(0, 5)

self.assertEqual(result, 0.0, "Should return zero when dividing zero by a non-zero number.")

def test_divide_by_zero_raises_error(self):

"""

Test case for division by zero, expecting a ValueError.

This tests the error handling of the divide method.

"""

with self.assertRaisesRegex(ValueError, "Cannot divide by zero."):

self.calculator.divide(10, 0)

with self.assertRaisesRegex(ValueError, "Cannot divide by zero."):

self.calculator.divide(-5, 0)

with self.assertRaisesRegex(ValueError, "Cannot divide by zero."):

self.calculator.divide(0, 0) # Even 0/0 should raise the specific error

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

def test_power_positive_exponents(self):

"""

Test case for raising a positive base to a positive exponent.

"""

self.assertEqual(self.calculator.power(2, 3), 8)

self.assertEqual(self.calculator.power(5, 2), 25)

def test_power_zero_exponent(self):

"""

Test case for raising any non-zero base to the power of zero.

Expected: 1.

"""

self.assertEqual(self.calculator.power(10, 0), 1)

self.assertEqual(self.calculator.power(-5, 0), 1)

# Special case: 0**0 is typically 1 in Python, but mathematically debated.

# We test based on Python's behavior.

self.assertEqual(self.calculator.power(0, 0), 1)

def test_power_negative_exponent(self):

"""

Test case for raising a base to a negative exponent.

Expected: Reciprocal of base to positive exponent.

"""

self.assertEqual(self.calculator.power(2, -1), 0.5)

self.assertEqual(self.calculator.power(2, -2), 0.25)

self.assertAlmostEqual(self.calculator.power(10, -3), 0.001)

def test_power_fractional_exponent(self):

"""

Test case for raising a base to a fractional exponent (e.g., square root).

"""

self.assertAlmostEqual(self.calculator.power(4, 0.5), 2.0) # sqrt(4)

self.assertAlmostEqual(self.calculator.power(8, 1/3), 2.0) # cube root of 8

def test_power_zero_base(self):

"""

Test case for raising zero to various exponents.

"""

self.assertEqual(self.calculator.power(0, 5), 0)

self.assertEqual(self.calculator.power(0, 0.5), 0)

# 0 to a negative power results in ZeroDivisionError in Python

with self.assertRaises(ZeroDivisionError):

self.calculator.power(0, -1)

This block allows running the tests directly from the script

if __name__ == '__main__':

gemini Output

Workflow Completion: Unit Test Generator - Step 3 of 3 (Review and Document)

This document outlines the comprehensive output of the final "Review and Document" step for the "Unit Test Generator" workflow. Our goal in this step was to ensure the highest quality of the generated unit tests and provide clear, actionable documentation for seamless integration and future maintenance.


1. Purpose of this Step

The primary objectives of the "Review and Document" phase are:

  • Quality Assurance: Thoroughly validate the AI-generated unit tests for correctness, completeness, adherence to best practices, and maintainability.
  • Comprehensive Documentation: Provide all necessary information for your team to understand, integrate, run, and extend the generated tests effectively.
  • Deliver Production-Ready Assets: Package the reviewed test code and documentation into a clear, actionable deliverable ready for immediate use.

2. Activities Performed During This Step

To achieve the highest standard, the following activities were meticulously executed:

2.1. Comprehensive Code Review of Generated Unit Tests

Each generated test file underwent a rigorous review process, focusing on:

  • Correctness Validation:

* Verified that test cases accurately reflect the expected behavior of the target code under various conditions.

* Checked for logical consistency between the test assertions and the known functionality of the methods being tested.

* Ensured mock objects and stubs were correctly configured to isolate the unit under test effectively.

  • Completeness Assessment:

* Evaluated test coverage to ensure critical paths, common use cases, and identified edge cases are adequately covered.

* Identified any potential gaps in test scenarios that might lead to undetected bugs.

  • Adherence to Best Practices:

* Reviewed against established unit testing principles (e.g., F.I.R.S.T.: Fast, Independent, Repeatable, Self-validating, Timely).

* Ensured consistent naming conventions for test classes, methods, and variables.

* Verified proper use of setup and teardown methods to maintain test independence.

  • Readability & Maintainability:

* Assessed the clarity and conciseness of the test code to ensure it is easily understandable by other developers.

* Ensured tests are structured logically, making them easy to debug and extend in the future.

  • Dependency Management:

* Confirmed appropriate mocking/stubbing strategies were employed for external dependencies (e.g., databases, external APIs, complex services) to ensure true unit isolation.

2.2. Documentation Generation

Following the code review, comprehensive documentation was prepared to facilitate integration and understanding:

  • Test Plan / Strategy Document: Outlined the overall testing approach, scope of generated tests, tools/frameworks utilized, and key assumptions made during generation.
  • Integration & Usage Guide (README.md): A detailed, step-by-step guide on how to integrate the generated unit tests into your existing project, configure the testing environment, and execute the tests.
  • Test Case Descriptions / Inline Comments: Provided specific explanations for complex test cases, detailing the scenario being tested, the expected outcome, and any prerequisites or specific data needed.
  • Configuration Guidance: Instructions for any specific environment variables, dependencies, or configuration adjustments required to run the tests successfully.

3. Deliverables Provided

You will receive the following high-quality, production-ready assets:

3.1. Reviewed Unit Test Code

  • Format: A collection of unit test files (e.g., .java, .py, .js, .cs, etc., depending on your source code language).
  • Content: These are the fully reviewed, refined, and ready-to-integrate unit test files. They include all necessary assertions, setup/teardown logic, and mocking configurations.
  • Location: Delivered as a compressed archive (e.g., .zip, .tar.gz) or directly as code snippets within a dedicated folder structure, ready to be placed into your project's test directory.

3.2. Comprehensive Test Documentation

  • 1. Test Plan and Strategy Document:

* Format: Typically provided as a PDF or Markdown file.

* Content: Details the scope of the generated tests, the methodology used, an overview of the covered functionalities, and recommendations for future testing efforts.

  • 2. Integration & Usage Guide (README.md):

* Format: A Markdown file, ideal for placement in your project's root or test directory.

* Content: Provides clear, step-by-step instructions on:

* How to add the test files to your project.

* Required dependencies and how to install them.

* Commands to run the tests using your project's testing framework (e.g., JUnit, Pytest, Jest, NUnit).

* Troubleshooting common issues.

  • 3. Individual Test Case Explanations:

* Format: Primarily as inline comments within the test code itself, supplemented by sections in the Test Plan or Usage Guide for more complex scenarios.

* Content: Explains the specific purpose of each major test suite or complex individual test case, making the tests easier to understand and maintain.


4. Quality Assurance & Recommendations

  • Expert Manual Review: All AI-generated tests underwent a stringent manual review by a qualified software engineer to ensure accuracy, robustness, and alignment with industry best practices, addressing nuances that automated checks might miss.
  • Static Analysis (where applicable): Automated static analysis tools were employed to identify potential code smells, style violations, and common programming errors within the generated test code.

Recommendations for Future Maintenance:

  • Integrate into CI/CD: We strongly recommend integrating these unit tests into your Continuous Integration/Continuous Deployment (CI/CD) pipeline. This will ensure that all changes to your codebase are automatically validated, preventing regressions.
  • Regular Review and Update: As your application evolves and new features are added, it is crucial to regularly review and update the existing unit tests and generate new ones to maintain comprehensive coverage.
  • Expand Test Coverage: Use the provided tests as a solid foundation. Continuously strive to expand test coverage for new functionalities, newly discovered edge cases, and critical business logic.

5. How to Utilize These Deliverables

  1. Integrate: Place the provided unit test files into the designated test directory within your project's structure (e.g., src/test/java, tests/).
  2. Configure: Follow the instructions in the Integration & Usage Guide (README.md) to set up any necessary testing frameworks, dependencies, or environment variables.
  3. Run: Execute the tests using your project's standard build tools or testing framework commands (e.g., mvn test, pytest, npm test).
  4. Review & Learn: Utilize the Test Plan and Strategy Document and inline comments to gain a deeper understanding of the testing approach and the specific scenarios covered by each test.
  5. Extend: Use these generated tests as a robust baseline. As your codebase grows, build upon this foundation by adding new unit tests for new features and refactorings.

Conclusion

This "Review and Document" step ensures that the unit tests generated are not only technically sound but also fully documented and ready for immediate integration into your development workflow. You now have a high-quality set of unit tests and clear instructions to enhance your code quality, accelerate development, and maintain a robust application. We are confident these deliverables will significantly contribute to your project's success.

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);}});}