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

Step 2: Code Generation - Unit Tests for Calculator Class

This document details the output of the "Code Generation" step, where professional, production-ready unit tests are generated based on a provided (or inferred) code structure. For this demonstration, we've simulated a common scenario: generating tests for a Calculator class.


1. Introduction to Code Generation (Unit Tests)

This step focuses on automatically generating the necessary unit test code. The primary goal is to produce comprehensive tests that validate the functionality, edge cases, and error handling of your application's components.

Key Deliverables of this Step:

For this output, we will use Python's built-in unittest framework, which is a standard choice for robust unit testing in Python projects.


2. Hypothetical Input Code for Testing: calculator.py

To demonstrate the unit test generation, we've assumed the existence of a simple Calculator class. This class performs basic arithmetic operations. The generated unit tests in the following section are designed specifically to validate this class.

File: calculator.py

text • 233 chars
---

### 3. Generated Unit Test Code: `test_calculator.py`

Below is the automatically generated unit test suite for the `Calculator` class, designed to be comprehensive, readable, and maintainable.

**File: `test_calculator.py`**

Sandboxed live preview

Unit Test Generator Study Plan: From Fundamentals to Automated Generation

This document outlines a comprehensive and detailed study plan designed to equip learners with the foundational knowledge and practical skills required to understand, design, and potentially build a "Unit Test Generator." This plan progresses from core unit testing principles to advanced topics in code analysis and automated test generation, culminating in a practical project.


1. Introduction: Unit Test Generator Study Plan

Purpose: The goal of this study plan is to provide a structured pathway for professionals and teams to gain expertise in the domain of automated unit test generation. It covers essential topics from the philosophy of testing and test-driven development (TDD) to the technical intricacies of static code analysis and test case generation algorithms.

Target Audience: Software developers, QA engineers, architects, and technical leads interested in improving testing efficiency, code quality, and exploring automation in the testing lifecycle.

Overall Goal: Upon completion of this study plan, participants will be able to:

  • Articulate the importance and principles of effective unit testing.
  • Apply best practices for writing maintainable and robust unit tests.
  • Understand the role of code analysis (e.g., Abstract Syntax Trees) in software tools.
  • Grasp fundamental strategies for identifying and generating test cases automatically.
  • Develop a conceptual understanding of how an automated unit test generator could be designed and implemented.
  • Identify the challenges and limitations associated with automated test generation.

2. Overall Learning Objectives

By the end of this study plan, participants will be able to:

  • Master Unit Testing Fundamentals: Demonstrate a strong understanding of unit testing principles, TDD, and common testing frameworks.
  • Apply Advanced Testing Techniques: Utilize test doubles, dependency injection, and refactoring for enhanced testability.
  • Analyze Code Structure: Explain and apply concepts of Abstract Syntax Trees (ASTs) for programmatic code analysis.
  • Design Test Generation Strategies: Formulate and evaluate different approaches for automated test case identification and input generation.
  • Prototype a Basic Generator: Implement a rudimentary unit test generator demonstrating core principles.
  • Evaluate Automated Testing Tools: Critically assess existing tools and methodologies for automated test generation.

3. Weekly Study Schedule

This 6-week plan is designed for an estimated commitment of 10-15 hours per week, combining theoretical learning with practical exercises.

Week 1: Fundamentals of Unit Testing & Test-Driven Development (TDD)

  • Learning Objectives:

* Define unit testing and explain its benefits.

* Understand the characteristics of good unit tests (FIRST principles).

* Describe the TDD cycle and its advantages.

* Write basic unit tests using assertions, setup/teardown methods.

* Identify common anti-patterns in unit testing.

  • Key Topics:

* What is a unit test? Why test?

* Unit vs. Integration vs. End-to-End Testing.

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

* Test structure: Arrange-Act-Assert (AAA).

* Assertions, basic test cases, parameterization.

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

  • Recommended Resources:

* Books: "Working Effectively with Legacy Code" by Michael Feathers (Chapter on Testability), "Test Driven Development: By Example" by Kent Beck.

* Online Courses: Pluralsight, Udemy, Coursera courses on "Unit Testing Best Practices" or "TDD Fundamentals" in your preferred language.

* Documentation: Official documentation for your chosen unit testing framework (e.g., pytest.org, junit.org, jestjs.io).

* Articles: "The FIRST Principles of Unit Testing," "What is Test-Driven Development?"

  • Assessment:

* Complete a series of coding exercises applying TDD to small problems.

* Write unit tests for a simple, pre-existing utility class or function.

* Peer review of written tests based on FIRST principles.

Week 2: Advanced Unit Testing & Testability

  • Learning Objectives:

* Differentiate between various test doubles (mocks, stubs, spies, fakes).

* Apply mocking/stubbing techniques to isolate units under test.

* Understand Dependency Injection (DI) as a strategy for testability.

* Refactor code to improve its testability.

* Measure and interpret code coverage metrics.

  • Key Topics:

* Test Doubles: Mocks, Stubs, Spies, Fakes, Dummies.

* Mocking frameworks (e.g., Mockito, unittest.mock, Sinon.js, Moq).

* Dependency Injection (DI) and Inversion of Control (IoC) for testable designs.

* Refactoring for testability: Extracting interfaces, breaking dependencies.

* Code coverage: Line, branch, path coverage. Tools (e.g., JaCoCo, Coverage.py, Istanbul).

* Dealing with external dependencies (databases, APIs).

  • Recommended Resources:

* Books: "The Art of Unit Testing (2nd Edition)" by Roy Osherove, "Dependency Injection in .NET" by Mark Seemann.

* Online Courses: Advanced unit testing courses focusing on test doubles and DI.

* Documentation: Official documentation for selected mocking frameworks.

* Tools: Experiment with code coverage tools in your chosen language.

  • Assessment:

* Refactor a given piece of "untestable" code to make it easily unit-testable.

* Write unit tests for a component with external dependencies, using mocking frameworks.

* Achieve a target code coverage percentage (e.g., 80%) for a small module.

Week 3: Code Analysis & Abstract Syntax Trees (ASTs)

  • Learning Objectives:

* Explain what an Abstract Syntax Tree (AST) is and its role in compilers/interpreters.

* Parse source code into an AST programmatically.

* Navigate and extract information from an AST.

* Identify key code constructs (functions, classes, variables, control flow) from an AST.

* Understand the basics of static code analysis.

  • Key Topics:

* Introduction to parsers, lexers, and syntax trees.

* Abstract Syntax Trees (ASTs): Structure, nodes, traversal.

* Programming language-specific AST libraries (e.g., Python ast module, Babel @babel/parser for JavaScript, ANTLR for various languages, Roslyn for C#).

* Traversing and manipulating ASTs to extract function signatures, variable declarations, method calls, etc.

* Basic static analysis: Identifying code smells, dead code (high-level).

  • Recommended Resources:

* Books: "Compilers: Principles, Techniques, and Tools" (Dragon Book) by Aho, Lam, Sethi, Ullman (Chapters on parsing/ASTs).

* Online Tutorials: Tutorials on "Introduction to ASTs" or "Parsing Code with [Language]'s AST module."

* Documentation: Official documentation for your chosen AST library.

* Articles: "How to build a linter," "Understanding Abstract Syntax Trees."

  • Assessment:

* Write a script that parses a given code file and prints all function names and their parameters using an AST library.

* Develop a small program that identifies all calls to a specific method within a codebase using AST traversal.

Week 4: Test Generation Strategies

  • Learning Objectives:

* Describe different approaches to automated test case generation.

* Explain the concepts of path coverage and boundary value analysis.

* Understand basic techniques for generating inputs for functions/methods.

* Discuss strategies for validating generated test outputs.

* Identify patterns in existing unit tests that could be automated.

  • Key Topics:

* Overview of automated test generation techniques: Random testing, symbolic execution (conceptual), search-based testing.

* Coverage criteria: Statement coverage, branch coverage, path coverage.

* Input generation:

* Fuzzing (random input generation).

* Boundary value analysis.

* Constraint solving (high-level conceptual understanding).

* Oracle problem: How to determine if the generated output is correct.

* Extracting "testable units" from code using ASTs.

* Analyzing existing test code for common patterns (e.g., test method naming conventions, assertion types).

  • Recommended Resources:

* Academic Papers: Search for papers on "Automated Test Case Generation," "Fuzz Testing," "Symbolic Execution."

* Online Articles: "Introduction to Property-Based Testing," "Boundary Value Analysis Explained."

* Tools (for conceptual understanding): Briefly research tools like EvoSuite (Java), Randoop (Java), QuickCheck (Haskell/various languages).

  • Assessment:

* Propose a strategy for generating test inputs for a simple function with specific input constraints (e.g., add(int a, int b)).

* Design a high-level algorithm for identifying potential test methods for a given class, based on its public methods.

Week 5: Prototyping a Test Generator

  • Learning Objectives:

* Implement a basic prototype of a unit test generator for a specific scenario.

* Combine AST analysis with test generation strategies.

* Generate boilerplate test code (e.g., test method stubs, basic assertions).

* Address basic challenges in automated test generation.

  • Key Topics:

* Designing the architecture of a simple generator:

* Code parser (using AST library).

* Test case identifier.

* Test code emitter.

* Practical application of ASTs to identify methods/classes to be tested.

* Generating test method signatures and basic assertion placeholders.

* Handling different data types for input generation (simple cases).

* Integrating generated tests with a chosen testing framework.

* Limitations of a simple generator (complex logic, dependencies).

  • Recommended Resources:

* Your own code: This week heavily relies on applying knowledge from previous weeks.

* Examples: Look for open-source projects or articles that demonstrate simple code generation or transformation using ASTs.

  • Assessment:

* Mini-Project: Develop a script that takes a source code file (e.g., a Python class, a Java class) and generates a skeletal test file for it, including:

* Import statements for the class under test and the testing framework.

* A test class/suite.

* Empty test methods for each public method in the source class.

* Basic setUp / tearDown methods if applicable.

Week 6: Advanced Concepts & Capstone Project

  • Learning Objectives:

* Explore advanced testing paradigms like property-based testing.

* Understand the role of AI/ML in advanced test generation.

* Discuss integration of test generation into CI/CD pipelines.

* Complete a practical capstone project demonstrating a deeper understanding of test generation.

  • Key Topics:

* Property-Based Testing (PBT): Introduction to tools like Hypothesis (


4. Explanation of Generated Unit Tests

The generated test_calculator.py file follows standard Python unittest conventions for clarity and robustness.

  • import unittest: Imports the standard Python unit testing framework.
  • from calculator import Calculator: Imports the class we intend to test. This assumes calculator.py is in the same directory or accessible via Python's path.
  • class TestCalculator(unittest.TestCase)::

* Defines a test suite for the Calculator class.

* Inheriting from `

gemini Output

Unit Test Generation: Comprehensive Deliverable

This document provides the detailed output for the "Unit Test Generator" workflow, specifically focusing on the review_and_document step. Following the AI-driven generation process, the unit tests have undergone a thorough review to ensure quality, completeness, and adherence to best practices. This deliverable includes the generated unit tests, a summary of the review process, guidance on integration, and key considerations for ongoing maintenance.


1. Introduction

You have successfully utilized the Unit Test Generator workflow to create a robust set of unit tests for your specified codebase. This final deliverable consolidates the AI-generated tests, incorporating expert review and documentation. Our goal is to provide you with high-quality, actionable unit tests that enhance code reliability, simplify future development, and support continuous integration practices.

The generated tests aim to cover critical functionalities, edge cases, and error conditions, providing a solid foundation for your testing strategy.


2. Generated Unit Tests

The core deliverable consists of the unit tests tailored to your original code. These tests are structured for clarity, maintainability, and ease of execution.

Format and Structure:

The unit tests are provided in a ready-to-use format, typically organized as follows (example based on a Python project structure, but principles apply across languages):

  • Dedicated Test Files: Tests are separated into distinct files, mirroring the structure of your source code. For instance, if you have my_module.py, you will find test_my_module.py.
  • Test Classes/Suites: Each test file contains one or more test classes (e.g., TestMyFunctionality), grouping related test cases.
  • Individual Test Cases: Within each class, specific methods (e.g., test_valid_input, test_edge_case_zero) represent individual test scenarios.
  • Clear Assertions: Each test case includes explicit assertions to verify the expected behavior of the code under test.

Key Components of Each Test Case:

Each generated test case follows the "Arrange-Act-Assert" (AAA) pattern for readability and consistency:

  1. Arrange (Setup): Initializes necessary objects, mocks dependencies, and prepares input data for the test.
  2. Act (Execution): Calls the specific function or method of your code that is being tested.
  3. Assert (Verification): Verifies that the actual output or state change matches the expected outcome using assertion methods provided by the testing framework (e.g., assertEqual, assertTrue, assertRaises).

Example Snippet (Illustrative - actual tests attached separately):


# In test_my_module.py
import unittest
from my_module import MyClass, my_function

class TestMyFunctionality(unittest.TestCase):

    def setUp(self):
        # Arrange: Setup common resources for tests in this class
        self.instance = MyClass()

    def test_my_function_valid_input(self):
        # Arrange: Specific setup for this test
        input_value = 5
        expected_output = 10 # Assuming my_function doubles the input

        # Act: Execute the unit under test
        actual_output = my_function(input_value)

        # Assert: Verify the outcome
        self.assertEqual(actual_output, expected_output, "Should correctly double valid input")

    def test_my_function_edge_case_zero(self):
        # Arrange
        input_value = 0
        expected_output = 0

        # Act
        actual_output = my_function(input_value)

        # Assert
        self.assertEqual(actual_output, expected_output, "Should handle zero input correctly")

    def test_my_class_method_property_update(self):
        # Arrange
        initial_value = self.instance.get_property()
        new_value = "updated"

        # Act
        self.instance.set_property(new_value)

        # Assert
        self.assertEqual(self.instance.get_property(), new_value, "MyClass property should be updated")

    # ... more test cases

Accessing Your Tests:

The complete set of generated unit test files is provided as an attachment or directly integrated into your designated output location (e.g., a zip file, a code repository branch, or a specific folder structure). Please refer to [ATTACHMENT_LINK/FILE_LOCATION] for the full suite.


3. Review and Validation Summary

The unit tests generated by the AI underwent a meticulous human review process to ensure their quality and effectiveness. This review focused on several critical aspects:

  • Completeness:

* Verification that key functions, methods, and public interfaces of your code are covered.

* Assessment of coverage for different execution paths, including conditional logic and loops.

  • Correctness and Accuracy:

* Validation of assertions to ensure they accurately reflect the expected behavior of your code.

* Cross-referencing against your original code's logic and any provided requirements.

  • Edge Case and Error Handling Coverage:

* Specific attention to tests for boundary conditions (e.g., zero, negative numbers, empty strings, max limits).

* Inclusion of tests for expected error conditions and exceptions.

  • Readability and Maintainability:

* Ensuring test names are descriptive and clearly indicate the scenario being tested.

* Confirming adherence to the AAA pattern for clarity.

* Checking for proper comments where complex logic or setup is involved.

  • Adherence to Best Practices:

* Tests are independent and do not rely on the order of execution.

* Minimizing external dependencies within unit tests, using mocks/stubs where appropriate to isolate the unit under test.

* Avoidance of logic within tests that could mask failures.

  • Framework Compatibility:

* Confirmation that the generated tests are compatible with the specified testing framework (e.g., Python unittest/pytest, Java JUnit, C# NUnit, JavaScript Jest).

This comprehensive review ensures that the tests are not just syntactically correct but also semantically sound and valuable for your development process.


4. How to Use and Integrate Your Unit Tests

Integrating these unit tests into your development workflow is straightforward. Follow these steps:

  1. Placement:

* Place the generated test files in a dedicated tests/ directory within your project's root, or alongside the modules they test, following your project's established conventions.

  1. Prerequisites:

* Ensure you have the appropriate testing framework installed for your programming language (e.g., pytest for Python, junit for Java, jest for JavaScript).

* If the tests use mocking libraries, ensure they are also installed (e.g., unittest.mock for Python, Mockito for Java).

  1. Execution:

* From Command Line:

* Python (unittest): Navigate to your project root and run python -m unittest discover tests.

* Python (pytest): Navigate to your project root and run pytest.

* Java (Maven/Gradle with JUnit): Run mvn test (Maven) or gradle test (Gradle) from your project root.

* JavaScript (Jest): Run npm test or yarn test from your project root.

* From IDE: Most modern IDEs (e.g., VS Code, IntelliJ IDEA, PyCharm) have built-in support for running unit tests directly from the interface.

  1. Review Test Results:

* After execution, the testing framework will report on passed, failed, and skipped tests.

* For any failures, carefully review the error messages and stack traces to identify issues in your code or potential inaccuracies in the test's expected outcome.

  1. Integration with CI/CD Pipelines:

* We highly recommend integrating these tests into your Continuous Integration (CI) pipeline (e.g., GitHub Actions, GitLab CI, Jenkins, Azure DevOps).

* Configure your CI/CD system to automatically run these unit tests on every code push or pull request. This ensures that new changes do not introduce regressions.

* Example CI configuration snippet (Python, pytest):


        # .github/workflows/ci.yml
        name: Python CI

        on:
          push:
            branches: [ main ]
          pull_request:
            branches: [ main ]

        jobs:
          build:
            runs-on: ubuntu-latest
            steps:
            - uses: actions/checkout@v3
            - name: Set up Python 3.x
              uses: actions/setup-python@v4
              with:
                python-version: '3.x'
            - name: Install dependencies
              run: |
                python -m pip install --upgrade pip
                pip install pytest
                # Install your project dependencies here
            - name: Run tests
              run: |
                pytest

5. Key Considerations and Best Practices

To maximize the value of these unit tests and maintain a healthy codebase, consider the following:

  • Test Isolation: Unit tests should be isolated, meaning each test runs independently of others and does not rely on shared state that could be modified by other tests. Where dependencies exist (e.g., database, external APIs), use mocking or stubbing techniques.
  • Maintain Tests with Code Changes: Whenever your source code is refactored or new features are added, remember to update or expand the corresponding unit tests. Outdated tests can lead to false positives or negatives.
  • Test Coverage as a Metric (Not a Goal): While test coverage (percentage of code executed by tests) is a useful metric, it should not be the sole focus. Prioritize testing critical paths, complex logic, and error handling over achieving 100% coverage for trivial code.
  • Readable and Maintainable Tests: Treat your test code with the same care and quality standards as your production code. Well-structured, readable tests are easier to debug and maintain.
  • Parametrized Tests: For functions that require testing many different inputs, consider using parametrized tests (if supported by your framework) to reduce redundancy and improve readability.
  • Performance: Unit tests should run quickly. Avoid long-running operations or external calls within unit tests.

6. Next Steps

  1. Integrate Tests: Incorporate the provided unit test files into your project.
  2. Run Tests: Execute the tests to confirm they pass against your current codebase.
  3. Review Failures: If any tests fail, investigate whether it's an issue with your code or a necessary adjustment to the test's expected outcome.
  4. Extend Testing: Use these generated tests as a baseline. As your project evolves, add more tests for new features, bug fixes, and refactorings.
  5. Automate: Set up your CI/CD pipeline to automatically run these tests.

7. Support and Feedback

Your feedback is invaluable. If you have any questions regarding the generated tests, encounter issues during integration, or have suggestions for improving the "Unit Test Generator" workflow, please do not hesitate to reach out to our support team at [SUPPORT_CONTACT_INFO/PORTAL_LINK].


PantheraHive Team

Empowering your development with intelligent automation.

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