diff --git a/.github/trafico.yml b/.github/trafico.yml index 418eef238..a296513ef 100644 --- a/.github/trafico.yml +++ b/.github/trafico.yml @@ -37,4 +37,4 @@ labels: name: "status: closed" color: "#0E8A16" description: "Pull Request is complete and integrated or closed for anther reason." - ignore: true + ignore: false diff --git a/.github/workflows/do_release.yml b/.github/workflows/do_release.yml index af736511b..bcc42f12d 100644 --- a/.github/workflows/do_release.yml +++ b/.github/workflows/do_release.yml @@ -84,6 +84,7 @@ jobs: repository_url: https://test.pypi.org/legacy/ - name: Test install from Test PyPI + if: ${{ env.build_ok == 1 }} run: | sudo apt-get update sudo apt-get install -y --no-install-recommends apt-utils git libgirepository1.0-dev gir1.2-gtk-3.0 python3-gi python3-gi-cairo python3-pytest libenchant1c2a libenchant-dev python3-numpy python3-scipy xauth xvfb diff --git a/.github/workflows/dont-static-checks.yml b/.github/workflows/dont-static-checks.yml new file mode 100644 index 000000000..a0e4f9d5c --- /dev/null +++ b/.github/workflows/dont-static-checks.yml @@ -0,0 +1,53 @@ +# This is a dummy workflow that will run when the conditions of the +# do-static-checks workflow aren't met. This allows PRs to be merged when the +# conditions aren't met for a protected branch. See +# https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/defining-the-mergeability-of-pull-requests/troubleshooting-required-status-checks +name: Perform Static Checks on RAMSTK Code Base + +on: + push: + paths-ignore: + - "**.py" + pull_request: + paths-ignore: + - "**.py" + types: + - "opened" + - "reopened" + - "synchronize" + +jobs: + bandit: + name: Check for Security Vulnerabilities + runs-on: ubuntu-latest + steps: + - run: + echo "No security check required." + + format-check: + name: Check Code Formatting + runs-on: ubuntu-latest + steps: + - run: + echo "No files to be formatted." + + style-check: + name: Check Code Styling + runs-on: ubuntu-latest + steps: + - run: + echo "No files to be style checked." + + type-check: + name: Check Code Type Hinting + runs-on: ubuntu-latest + steps: + - run: + echo "No files to be type checked." + + lint-check: + name: Check Code Lint + runs-on: ubuntu-latest + steps: + - run: + echo "No files to be linted." diff --git a/.github/workflows/dont-test-suite.yml b/.github/workflows/dont-test-suite.yml new file mode 100644 index 000000000..f31d33167 --- /dev/null +++ b/.github/workflows/dont-test-suite.yml @@ -0,0 +1,33 @@ +# This is a dummy workflow that will run when the conditions of the +# do-test-suite workflow aren't met. This allows PRs to be merged when the +# conditions aren't met for a protected branch. See +# https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/defining-the-mergeability-of-pull-requests/troubleshooting-required-status-checks +name: Execute RAMSTK Test Suite with Coverage + +on: + push: + paths-ignore: + - "**.py" + pull_request: + paths-ignore: + - "**.py" + types: + - "opened" + - "reopened" + - "synchronize" + +jobs: + test_suite: + name: Run Test Suite + runs-on: ubuntu-latest + steps: + - run: | + echo "Test suite not required." + + upload_coveralls: + name: Upload Results to Coveralls + needs: test_suite + runs-on: ubuntu-latest + steps: + - run: | + echo "No test suite required; no coverage report generated." diff --git a/.github/workflows/on-pr-close.yml b/.github/workflows/on-pr-close.yml index dc7de54c4..677699dc7 100644 --- a/.github/workflows/on-pr-close.yml +++ b/.github/workflows/on-pr-close.yml @@ -1,9 +1,6 @@ # This workflow runs when a pull request is closed. # # - Job 1: -# - Remove 'status: inprogress' label. -# - Add 'status: closed' label. -# - Job 2: # - Gets list of PR labels. # - Get current version from VERSION. # - Determine next Semantic version. @@ -21,16 +18,6 @@ on: - closed jobs: - label-pr-closed: - name: Add Closed Label - runs-on: ubuntu-latest - steps: - - name: Add label - uses: andymckay/labeler@master - with: - add-labels: "status: closed" - remove-labels: "status: inprogress" - tag-version: name: Push Version Tag runs-on: ubuntu-latest diff --git a/.github/workflows/on-pr-merge.yml b/.github/workflows/on-pr-merge.yml index c30e7e5ee..63c6f13e8 100644 --- a/.github/workflows/on-pr-merge.yml +++ b/.github/workflows/on-pr-merge.yml @@ -64,12 +64,6 @@ jobs: make html cd .. - - name: Build pdf documentation - run: | - cd docs - make latexpdf LATEXMKOPTS="-silent -f" - cd .. - - name: Import GPG key id: import_gpg uses: crazy-max/ghaction-import-gpg@v4 @@ -96,3 +90,9 @@ jobs: branch: gh-pages directory: gh-pages github_token: ${{ secrets.GITHUB_TOKEN }} + + - name: Build pdf documentation + run: | + cd docs + make latexpdf LATEXMKOPTS="-silent -f" + cd .. diff --git a/pyproject.toml b/pyproject.toml index 8a1d99121..4311e41cd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -216,7 +216,8 @@ disable = [ 'fixme', 'anomalous-unicode-escape-in-string', 'import-error', - 'no-member' + 'no-member', + 'no-else-return' ] [tool.pylint.reports] diff --git a/src/ramstk/analyses/allocation.py b/src/ramstk/analyses/allocation.py index 9873301cc..f80abbdb4 100644 --- a/src/ramstk/analyses/allocation.py +++ b/src/ramstk/analyses/allocation.py @@ -390,9 +390,8 @@ def get_allocation_goal(**attributes: Dict[str, Any]) -> Dict[str, Any]: :raise: KeyError if the passed attributes dict doesn't contain the allocation_method_id, hazard_rate_goal, and/or reliability_goal key. """ - if attributes["allocation_method_id"] in [2, 4]: # ARINC or FOO. - _goal = attributes["hazard_rate_goal"] - else: - _goal = attributes["reliability_goal"] - - return _goal + return ( + attributes["hazard_rate_goal"] + if attributes["allocation_method_id"] in [2, 4] + else attributes["reliability_goal"] + ) diff --git a/src/ramstk/analyses/criticality.py b/src/ramstk/analyses/criticality.py index 0245626a9..ff179b5c4 100644 --- a/src/ramstk/analyses/criticality.py +++ b/src/ramstk/analyses/criticality.py @@ -40,14 +40,12 @@ def calculate_rpn(sod): if not 0 < sod["rpn_detection"] < 11: raise OutOfRangeError(("RPN detection is outside the range [1, 10].")) - _rpn = ( + return ( int(sod["rpn_severity"]) * int(sod["rpn_occurrence"]) * int(sod["rpn_detection"]) ) - return _rpn - def calculate_mode_hazard_rate(item_hr, mode_ratio): """Calculate the failure mode hazard rate. diff --git a/src/ramstk/analyses/fha.py b/src/ramstk/analyses/fha.py index 5dd21cd98..7f40df8dc 100644 --- a/src/ramstk/analyses/fha.py +++ b/src/ramstk/analyses/fha.py @@ -216,10 +216,9 @@ def set_user_defined_functions( for _idx in [6, 7, 8, 9, 10]: try: _key = list(fha.keys())[_idx] - if str(functions[_idx - 6]) == "": - fha[_key] = "0.0" - else: - fha[_key] = str(functions[_idx - 6]) + fha[_key] = ( + "0.0" if not str(functions[_idx - 6]) else str(functions[_idx - 6]) + ) except IndexError: fha[_key] = "0.0" diff --git a/src/ramstk/analyses/milhdbk217f/milhdbk217f.py b/src/ramstk/analyses/milhdbk217f/milhdbk217f.py index d713fb7ca..fde3cb379 100644 --- a/src/ramstk/analyses/milhdbk217f/milhdbk217f.py +++ b/src/ramstk/analyses/milhdbk217f/milhdbk217f.py @@ -230,18 +230,14 @@ def _get_environment_factor( 10: {1: crystal.PI_E, 2: efilter.PI_E, 3: fuse.PI_E, 4: lamp.PI_E}, } - if category_id == 8 and subcategory_id in [1, 2]: - _pi_e = _pi_e_lists[category_id][subcategory_id][quality_id][ + if category_id == 8 and subcategory_id in {1, 2}: + return _pi_e_lists[category_id][subcategory_id][quality_id][ environment_active_id - 1 ] - elif category_id in [2, 3, 5, 7, 9, 10] or ( - category_id == 8 and subcategory_id not in [1, 2] - ): - _pi_e = _pi_e_lists[category_id][subcategory_id][environment_active_id - 1] + elif category_id in {2, 3, 5, 7, 9, 10, 8}: + return _pi_e_lists[category_id][subcategory_id][environment_active_id - 1] else: - _pi_e = _pi_e_lists[category_id][environment_active_id - 1] - - return _pi_e + return _pi_e_lists[category_id][environment_active_id - 1] def _get_part_count_quality_factor( @@ -276,18 +272,17 @@ def _get_part_count_quality_factor( 10: {1: crystal.PART_COUNT_PI_Q, 2: efilter.PI_Q}, } - if category_id in [6, 7, 9]: - _pi_q = _pi_q_lists[category_id][subcategory_id][quality_id - 1] - elif category_id == 10 and subcategory_id in [1, 2]: - _pi_q = _pi_q_lists[category_id][subcategory_id][quality_id - 1] - elif category_id == 10 and subcategory_id in [3, 4]: - _pi_q = 1.0 + if category_id in {6, 7, 9}: + return _pi_q_lists[category_id][subcategory_id][quality_id - 1] + elif category_id == 10 and subcategory_id in {1, 2}: + return _pi_q_lists[category_id][subcategory_id][quality_id - 1] + elif category_id == 10 and subcategory_id in {3, 4}: + return 1.0 else: - _pi_q = _pi_q_lists[category_id][quality_id - 1] - - return _pi_q + return _pi_q_lists[category_id][quality_id - 1] +# pylint: disable=too-many-return-statements def _get_part_stress_quality_factor( category_id: int, subcategory_id: int, quality_id: int ) -> float: @@ -315,20 +310,20 @@ def _get_part_stress_quality_factor( } if category_id == 1: - _pi_q = _pi_q_lists[category_id][quality_id - 1] - elif (category_id == 8 and subcategory_id in [4, 5]) or ( - category_id == 7 and subcategory_id == 5 + return _pi_q_lists[category_id][quality_id - 1] + elif ( + category_id == 8 + and subcategory_id in {4, 5} + or (category_id == 7 and subcategory_id == 5) ): - _pi_q = _pi_q_lists[category_id][subcategory_id][quality_id - 1] - elif category_id == 7 and subcategory_id != 5: - _pi_q = 0.0 - elif category_id == 8 and subcategory_id not in [4, 5]: - _pi_q = 0.0 + return _pi_q_lists[category_id][subcategory_id][quality_id - 1] + elif category_id == 7: + return 0.0 + elif category_id == 8: + return 0.0 elif category_id == 9 and subcategory_id == 1: - _pi_q = 0.0 - elif category_id == 10 and subcategory_id in [3, 4]: - _pi_q = 0.0 + return 0.0 + elif category_id == 10 and subcategory_id in {3, 4}: + return 0.0 else: - _pi_q = _pi_q_lists[category_id][subcategory_id][quality_id - 1] - - return _pi_q + return _pi_q_lists[category_id][subcategory_id][quality_id - 1] diff --git a/src/ramstk/analyses/milhdbk217f/models/capacitor.py b/src/ramstk/analyses/milhdbk217f/models/capacitor.py index 12e0428ba..85240ddd6 100644 --- a/src/ramstk/analyses/milhdbk217f/models/capacitor.py +++ b/src/ramstk/analyses/milhdbk217f/models/capacitor.py @@ -420,9 +420,7 @@ def calculate_capacitance_factor(subcategory_id: int, capacitance: float) -> flo } _f0 = _dic_factors[subcategory_id][0] _f1 = _dic_factors[subcategory_id][1] - _pi_cv = _f0 * capacitance ** _f1 - - return _pi_cv + return _f0 * capacitance ** _f1 def calculate_part_count(**attributes: Dict[str, Any]) -> float: @@ -549,14 +547,12 @@ def calculate_part_stress_lambda_b( _f2 = _dic_factors[subcategory_id][2] _f3 = _dic_factors[subcategory_id][3] _f4 = _dic_factors[subcategory_id][4] - _lambda_b = ( + return ( _f0 * ((voltage_ratio / _f1) ** _f2 + 1.0) * exp(_f3 * ((temperature_active + 273.0) / _ref_temp) ** _f4) ) - return _lambda_b - def calculate_series_resistance_factor( resistance: float, voltage_dc_operating: float, voltage_ac_operating: float @@ -576,19 +572,17 @@ def calculate_series_resistance_factor( _ckt_resistance = resistance / (voltage_dc_operating + voltage_ac_operating) if 0 < _ckt_resistance <= 0.1: - _pi_sr = 0.33 + return 0.33 elif 0.1 < _ckt_resistance <= 0.2: - _pi_sr = 0.27 + return 0.27 elif 0.2 < _ckt_resistance <= 0.4: - _pi_sr = 0.2 + return 0.2 elif 0.4 < _ckt_resistance <= 0.6: - _pi_sr = 0.13 + return 0.13 elif 0.6 < _ckt_resistance <= 0.8: - _pi_sr = 0.1 + return 0.1 else: - _pi_sr = 0.066 - - return _pi_sr + return 0.066 def get_configuration_factor(configuration_id: int) -> float: @@ -696,13 +690,12 @@ def get_part_count_lambda_b( :rtype: float :raise: KeyError if passed an unknown subcategory ID or specification ID. """ - if subcategory_id == 1: - _base_hr = PART_COUNT_LAMBDA_B[subcategory_id][ # type: ignore - specification_id - ][environment_active_id - 1] - else: - _base_hr = PART_COUNT_LAMBDA_B[subcategory_id][ # type: ignore + return ( + PART_COUNT_LAMBDA_B[subcategory_id][specification_id][ # type: ignore environment_active_id - 1 ] - - return _base_hr + if subcategory_id == 1 + else PART_COUNT_LAMBDA_B[subcategory_id][ # type: ignore + environment_active_id - 1 + ] + ) diff --git a/src/ramstk/analyses/milhdbk217f/models/connection.py b/src/ramstk/analyses/milhdbk217f/models/connection.py index 487010300..8197ebb85 100644 --- a/src/ramstk/analyses/milhdbk217f/models/connection.py +++ b/src/ramstk/analyses/milhdbk217f/models/connection.py @@ -354,12 +354,7 @@ def calculate_complexity_factor(n_circuit_planes: int) -> float: :return: _pi_c; the calculated value of the complexity factor. :rtype: float """ - if n_circuit_planes > 2: - _pi_c = 0.65 * n_circuit_planes ** 0.63 - else: - _pi_c = 1.0 - - return _pi_c + return 0.65 * n_circuit_planes**0.63 if n_circuit_planes > 2 else 1.0 def calculate_insert_temperature(contact_gauge: int, current_operating: float) -> float: @@ -395,9 +390,7 @@ def calculate_insert_temperature(contact_gauge: int, current_operating: float) - _dic_factors = {12: 0.1, 16: 0.274, 20: 0.64, 22: 0.989, 26: 2.1} _fo = _dic_factors[contact_gauge] - _temperature_rise = _fo * current_operating ** 1.85 - - return _temperature_rise + return _fo * current_operating**1.85 def calculate_part_count(**attributes: Dict[str, Any]) -> float: @@ -503,33 +496,31 @@ def calculate_part_stress_lambda_b( :raise: IndexError if passed an unknown type ID. :raise: ZeroDivisionError if passed contact temperature = 0.0. """ - # Factors are used to calculate base hazard rate for circular/rack and - # panel connectors. Key is from dictionary above (1 - 4) or contact - # gauge (22 - 12). - _dic_factors = { - 1: [0.2, -1592.0, 5.36], - 2: [0.431, -2073.6, 4.66], - 3: [0.19, -1298.0, 4.25], - 4: [0.77, -1528.8, 4.72], - 5: [0.216, -2073.6, 4.66], - } - _ref_temp = REF_TEMPS[factor_key] - _f0 = _dic_factors[factor_key][0] - _f1 = _dic_factors[factor_key][1] - _f2 = _dic_factors[factor_key][2] - - if subcategory_id in [4, 5]: - _lambda_b = PART_STRESS_LAMBDA_B[subcategory_id][type_id - 1] + if subcategory_id in {4, 5}: + return PART_STRESS_LAMBDA_B[subcategory_id][type_id - 1] elif subcategory_id == 3: - _lambda_b = 0.00042 + return 0.00042 else: - _lambda_b = _f0 * exp( + # Factors are used to calculate base hazard rate for circular/rack and + # panel connectors. Key is from dictionary above (1 - 4) or contact + # gauge (22 - 12). + _dic_factors = { + 1: [0.2, -1592.0, 5.36], + 2: [0.431, -2073.6, 4.66], + 3: [0.19, -1298.0, 4.25], + 4: [0.77, -1528.8, 4.72], + 5: [0.216, -2073.6, 4.66], + } + + _f0 = _dic_factors[factor_key][0] + _f1 = _dic_factors[factor_key][1] + _f2 = _dic_factors[factor_key][2] + + return _f0 * exp( (_f1 / contact_temperature) + (contact_temperature / _ref_temp) ** _f2 ) - return _lambda_b - def get_factor_key(type_id: int, specification_id: int, insert_id: int) -> int: """Retrieve the reference temperature key for the connection. @@ -589,17 +580,15 @@ def get_mate_unmate_factor(n_cycles: float) -> float: :rtype: float """ if n_cycles <= 0.05: - _pi_k = PI_K[0] + return PI_K[0] elif 0.05 < n_cycles <= 0.5: - _pi_k = PI_K[1] + return PI_K[1] elif 0.5 < n_cycles <= 5.0: - _pi_k = PI_K[2] + return PI_K[2] elif 5.0 < n_cycles <= 50.0: - _pi_k = PI_K[3] + return PI_K[3] else: - _pi_k = PI_K[4] - - return _pi_k + return PI_K[4] def get_part_count_lambda_b(**kwargs: Dict[str, int]) -> float: @@ -644,11 +633,8 @@ def get_part_count_lambda_b(**kwargs: Dict[str, int]) -> float: _type_id = kwargs.get("type_id", 0) _environment_active_id = kwargs.get("environment_active_id", 0) - if _subcategory_id in [1, 5]: - _base_hr = PART_COUNT_LAMBDA_B[_subcategory_id][_type_id][ - _environment_active_id - 1 - ] - else: - _base_hr = PART_COUNT_LAMBDA_B[_subcategory_id][_environment_active_id - 1] - - return _base_hr + return ( + PART_COUNT_LAMBDA_B[_subcategory_id][_type_id][_environment_active_id - 1] + if _subcategory_id in [1, 5] + else PART_COUNT_LAMBDA_B[_subcategory_id][_environment_active_id - 1] + ) diff --git a/src/ramstk/analyses/milhdbk217f/models/integratedcircuit.py b/src/ramstk/analyses/milhdbk217f/models/integratedcircuit.py index b80e007f8..44786ad03 100644 --- a/src/ramstk/analyses/milhdbk217f/models/integratedcircuit.py +++ b/src/ramstk/analyses/milhdbk217f/models/integratedcircuit.py @@ -1097,11 +1097,7 @@ def calculate_lambda_cyclic_factors( ) _b_2 = 0.0 elif construction_id == 2: - if 300000 < n_cycles <= 400000: - _a_2 = 1.1 - else: - _a_2 = 2.3 - + _a_2 = 1.1 if 300000 < n_cycles <= 400000 else 2.3 _b_1 = ((n_elements / 64000.0) ** 0.25) * ( exp( (0.1 / 8.63e-5) @@ -1182,7 +1178,7 @@ def calculate_package_factor(package_id: int, n_active_pins: int) -> float: :result: _c2; the calculated package factor. :rtype: float """ - if package_id in [1, 2, 3]: + if package_id in {1, 2, 3}: _package = 1 elif package_id == 4: _package = 2 @@ -1196,7 +1192,7 @@ def calculate_package_factor(package_id: int, n_active_pins: int) -> float: _f0 = C2[_package][0] _f1 = C2[_package][1] - return _f0 * (n_active_pins ** _f1) + return _f0 * (n_active_pins**_f1) def calculate_part_count(**attributes: Dict[str, Any]) -> float: @@ -1397,7 +1393,7 @@ def get_die_complexity_factor( if subcategory_id == 2 and technology_id == 11: _technology = 2 - elif subcategory_id == 2 and technology_id != 11: + elif subcategory_id == 2: _technology = 1 else: _technology = technology_id @@ -1423,12 +1419,7 @@ def get_die_base_hazard_rate(type_id: int) -> float: :return: _lambda_bd; the base die hazard rate. :rtype: float """ - if type_id == 1: - _lambda_bd = 0.16 - else: - _lambda_bd = 0.24 - - return _lambda_bd + return 0.16 if type_id == 1 else 0.24 def get_error_correction_factor(type_id: int) -> float: @@ -1449,12 +1440,7 @@ def get_manufacturing_process_factor(manufacturing_id: int) -> float: :return: _pi_mfg; the manufacturing process correction factor. :rtype: float """ - if manufacturing_id == 1: - _pi_mfg = 0.55 - else: - _pi_mfg = 2.0 - - return _pi_mfg + return 0.55 if manufacturing_id == 1 else 2.0 def get_package_type_correction_factor(package_id: int) -> float: @@ -1555,13 +1541,12 @@ def get_part_count_lambda_b(n_elements: int, id_keys: Dict[str, int]) -> float: + 1 ) - if id_keys["subcategory_id"] == 1: - _base_hr = PART_COUNT_LAMBDA_B[id_keys["subcategory_id"]][_index][ + return ( + PART_COUNT_LAMBDA_B[id_keys["subcategory_id"]][_index][ id_keys["environment_active_id"] - 1 ] - else: - _base_hr = PART_COUNT_LAMBDA_B[id_keys["subcategory_id"]][ - id_keys["technology_id"] - ][_index][id_keys["environment_active_id"] - 1] - - return _base_hr + if id_keys["subcategory_id"] == 1 + else PART_COUNT_LAMBDA_B[id_keys["subcategory_id"]][id_keys["technology_id"]][ + _index + ][id_keys["environment_active_id"] - 1] + ) diff --git a/src/ramstk/analyses/milhdbk217f/models/meter.py b/src/ramstk/analyses/milhdbk217f/models/meter.py index 9db7e9684..435dea015 100644 --- a/src/ramstk/analyses/milhdbk217f/models/meter.py +++ b/src/ramstk/analyses/milhdbk217f/models/meter.py @@ -246,13 +246,11 @@ def get_part_stress_lambda_b(subcategory_id: int, type_id: int) -> float: :raise: IndexError when passed an unknown type ID. """ if subcategory_id == 1: - _lambda_b = PART_STRESS_LAMBDA_B[1][type_id - 1] + return PART_STRESS_LAMBDA_B[1][type_id - 1] elif subcategory_id == 2: - _lambda_b = PART_STRESS_LAMBDA_B[2] + return PART_STRESS_LAMBDA_B[2] else: - _lambda_b = 0.0 - - return _lambda_b + return 0.0 def get_temperature_stress_factor( diff --git a/src/ramstk/analyses/milhdbk217f/models/relay.py b/src/ramstk/analyses/milhdbk217f/models/relay.py index 15b31bb8f..5fb9116a1 100644 --- a/src/ramstk/analyses/milhdbk217f/models/relay.py +++ b/src/ramstk/analyses/milhdbk217f/models/relay.py @@ -251,16 +251,14 @@ def calculate_cycling_factor(quality_id: int, n_cycles: float) -> float: :return: _pi_cyc; the calculate cycling factor. :rtype: float """ - if quality_id in [1, 2, 3, 4, 5, 6] and n_cycles < 1.0: - _pi_cyc = 0.1 + if quality_id in {1, 2, 3, 4, 5, 6} and n_cycles < 1.0: + return 0.1 elif quality_id == 7 and n_cycles > 1000.0: - _pi_cyc = (n_cycles / 100.0) ** 2.0 + return (n_cycles / 100.0) ** 2.0 elif quality_id == 7 and 10.0 < n_cycles < 1000.0: - _pi_cyc = n_cycles / 10.0 + return n_cycles / 10.0 else: - _pi_cyc = 0.0 - - return _pi_cyc + return 0.0 def calculate_load_stress_factor(technology_id: int, current_ratio: float) -> float: @@ -274,15 +272,13 @@ def calculate_load_stress_factor(technology_id: int, current_ratio: float) -> fl :rtype: float """ if technology_id == 1: - _pi_l = (current_ratio / 0.8) ** 2.0 + return (current_ratio / 0.8) ** 2.0 elif technology_id == 2: - _pi_l = (current_ratio / 0.4) ** 2.0 + return (current_ratio / 0.4) ** 2.0 elif technology_id == 3: - _pi_l = (current_ratio / 0.2) ** 2.0 + return (current_ratio / 0.2) ** 2.0 else: - _pi_l = 0.0 - - return _pi_l + return 0.0 def calculate_part_count(**attributes: Dict[str, Any]) -> float: @@ -402,11 +398,7 @@ def get_application_construction_factor( :raise: KeyError if passed an unknown contact rating ID, construction ID, or application ID. """ - if quality_id in [1, 2, 3, 4, 5, 6]: - _quality = 1 - else: - _quality = 2 - + _quality = 1 if quality_id in {1, 2, 3, 4, 5, 6} else 2 return PI_F[contact_rating_id][application_id][construction_id][_quality - 1] @@ -423,17 +415,12 @@ def get_environment_factor( :raise: IndexError if passed an unknown active environment ID. :raise: KeyError if passed an unknown subcategory ID. """ - if quality_id in [1, 2, 3, 4, 5, 6]: - _quality = 1 - else: - _quality = 2 - - if subcategory_id == 1: - _pi_e = PI_E[subcategory_id][_quality][environment_active_id - 1] - else: - _pi_e = PI_E[subcategory_id][environment_active_id - 1] - - return _pi_e + _quality = 1 if quality_id in {1, 2, 3, 4, 5, 6} else 2 + return ( + PI_E[subcategory_id][_quality][environment_active_id - 1] + if subcategory_id == 1 + else PI_E[subcategory_id][environment_active_id - 1] + ) def get_part_count_lambda_b(**kwargs: Dict[str, int]) -> float: diff --git a/src/ramstk/analyses/milhdbk217f/models/resistor.py b/src/ramstk/analyses/milhdbk217f/models/resistor.py index 1de99d8d9..3f089f637 100644 --- a/src/ramstk/analyses/milhdbk217f/models/resistor.py +++ b/src/ramstk/analyses/milhdbk217f/models/resistor.py @@ -999,7 +999,7 @@ def get_resistance_factor(attributes: Dict[str, Any]) -> Dict[str, Any]: _pi_r = PI_R[_subcategory_id][_specification_id - 1][_family_id - 1][ _index + 1 ] - elif _subcategory_id not in [4, 8]: + else: _pi_r = PI_R[_subcategory_id][_index + 1] attributes["piR"] = _pi_r @@ -1022,9 +1022,9 @@ def get_voltage_factor(attributes: Dict[str, Any]) -> Dict[str, Any]: _index = -1 _breaks = [0.0] - if _subcategory_id in [9, 10, 11, 12]: + if _subcategory_id in {9, 10, 11, 12}: _breaks = [0.1, 0.2, 0.6, 0.7, 0.8, 0.9] - elif _subcategory_id in [13, 14, 15]: + elif _subcategory_id in {13, 14, 15}: _breaks = [0.8, 0.9] for _index, _value in enumerate(_breaks): diff --git a/src/ramstk/analyses/milhdbk217f/models/switch.py b/src/ramstk/analyses/milhdbk217f/models/switch.py index 7cad564ff..efbbf3da0 100644 --- a/src/ramstk/analyses/milhdbk217f/models/switch.py +++ b/src/ramstk/analyses/milhdbk217f/models/switch.py @@ -390,11 +390,8 @@ def get_part_count_lambda_b(attributes: Dict[str, Any]) -> float: _environment_active_id: Any = attributes["environment_active_id"] _subcategory_id: Any = attributes["subcategory_id"] - if _subcategory_id == 5: - _base_hr: float = PART_COUNT_LAMBDA_B_BREAKER[_construction_id][ - _environment_active_id - 1 - ] - else: - _base_hr = PART_COUNT_LAMBDA_B[_subcategory_id][_environment_active_id - 1] - - return _base_hr + return ( + PART_COUNT_LAMBDA_B_BREAKER[_construction_id][_environment_active_id - 1] + if _subcategory_id == 5 + else PART_COUNT_LAMBDA_B[_subcategory_id][_environment_active_id - 1] + ) diff --git a/src/ramstk/analyses/statistics/bounds.py b/src/ramstk/analyses/statistics/bounds.py index 8716bc9b4..d9d50badf 100644 --- a/src/ramstk/analyses/statistics/bounds.py +++ b/src/ramstk/analyses/statistics/bounds.py @@ -91,6 +91,4 @@ def do_calculate_fisher_information( for _record in data ] - _fisher = 1.0 / noise ** 2 * np.einsum("mk, nk", _D, _D) - - return _fisher + return 1.0 / noise ** 2 * np.einsum("mk, nk", _D, _D) diff --git a/src/ramstk/analyses/statistics/exponential.py b/src/ramstk/analyses/statistics/exponential.py index 86e1c9663..6e6a70ff8 100644 --- a/src/ramstk/analyses/statistics/exponential.py +++ b/src/ramstk/analyses/statistics/exponential.py @@ -32,13 +32,11 @@ def get_hazard_rate(scale: float, location: float = 0.0) -> float: :return: _hazard_rate; the hazard rate. :rtype: float """ - _hazard_rate = 1.0 / expon.mean( + return 1.0 / expon.mean( loc=location, scale=scale, ) - return _hazard_rate - def get_mtbf(rate: float, location: float = 0.0) -> float: """Calculate the MTBF (scale) given a hazard rate (lambda) and location parameter. diff --git a/src/ramstk/analyses/statistics/lognormal.py b/src/ramstk/analyses/statistics/lognormal.py index 7b2c8ee67..b556661be 100644 --- a/src/ramstk/analyses/statistics/lognormal.py +++ b/src/ramstk/analyses/statistics/lognormal.py @@ -46,14 +46,12 @@ def get_hazard_rate( :return: _hazard_rate; the hazard rate. :rtype: float """ - if time <= 0.0: - _hazard_rate = 0.0 - else: - _hazard_rate = lognorm.pdf( - time, shape, loc=location, scale=scale - ) / lognorm.cdf(time, shape, loc=location, scale=scale) - - return _hazard_rate + return ( + 0.0 + if time <= 0.0 + else lognorm.pdf(time, shape, loc=location, scale=scale) + / lognorm.cdf(time, shape, loc=location, scale=scale) + ) def get_mtbf(shape: float, location: float = 0.0, scale: float = 1.0) -> float: diff --git a/src/ramstk/analyses/statistics/normal.py b/src/ramstk/analyses/statistics/normal.py index 71c2a19aa..1dec95edc 100644 --- a/src/ramstk/analyses/statistics/normal.py +++ b/src/ramstk/analyses/statistics/normal.py @@ -36,14 +36,12 @@ def get_hazard_rate(location: float, scale: float, time: float) -> float: :return: _hazard_rate; the hazard rate. :rtype: float """ - _hazard_rate = norm.pdf(time, loc=location, scale=scale,) / norm.sf( + return norm.pdf(time, loc=location, scale=scale,) / norm.sf( time, loc=location, scale=scale, ) - return _hazard_rate - def get_mtbf(location: float, scale: float) -> float: """Calculate the MTBF given a shape (sigma) and scale (mu) parameter. diff --git a/src/ramstk/analyses/statistics/weibull.py b/src/ramstk/analyses/statistics/weibull.py index 41f8309e5..7c00dd748 100644 --- a/src/ramstk/analyses/statistics/weibull.py +++ b/src/ramstk/analyses/statistics/weibull.py @@ -50,14 +50,12 @@ def get_hazard_rate( :return: _hazard_rate; the hazard rate. :rtype: float """ - if time <= 0.0: - _hazard_rate = 0.0 - else: - _hazard_rate = weibull_min.pdf( - time, shape, loc=location, scale=scale - ) / weibull_min.cdf(time, shape, loc=location, scale=scale) - - return _hazard_rate + return ( + 0.0 + if time <= 0.0 + else weibull_min.pdf(time, shape, loc=location, scale=scale) + / weibull_min.cdf(time, shape, loc=location, scale=scale) + ) def get_mtbf(shape: float, scale: float, location: float = 0.0) -> float: diff --git a/src/ramstk/db/base.py b/src/ramstk/db/base.py index 5973361f5..c4b8664ec 100644 --- a/src/ramstk/db/base.py +++ b/src/ramstk/db/base.py @@ -347,11 +347,7 @@ def do_select_all(self, table, **kwargs) -> query.Query: else: _results = _results.order_by(_order) - if _all: - _results = _results.all() - else: - _results = _results.first() - + _results = _results.all() if _all else _results.first() return _results def do_update(self, record: object = None) -> None: @@ -440,7 +436,7 @@ def get_last_id(self, table: str, id_column: str) -> Any: """ # This ensures the column name is prefixed with fld_ in case the # table's attribute name was passed instead. - if id_column[0:4] != "fld_": + if id_column[:4] != "fld_": id_column = "fld_" + id_column _sql_statement = ( diff --git a/src/ramstk/exim/imports.py b/src/ramstk/exim/imports.py index 18eafbbc6..8d59d474c 100644 --- a/src/ramstk/exim/imports.py +++ b/src/ramstk/exim/imports.py @@ -921,10 +921,7 @@ def _do_read_db_fields(self, module: str) -> None: :return: None :rtype: None """ - _db_fields = [] - for _field in self._dic_field_map[module]: - _db_fields.append(_field) - + _db_fields = list(self._dic_field_map[module]) pub.sendMessage( "succeed_read_db_fields", db_fields=_db_fields, diff --git a/src/ramstk/models/__init__.py b/src/ramstk/models/__init__.py index c3d371391..8f5059357 100644 --- a/src/ramstk/models/__init__.py +++ b/src/ramstk/models/__init__.py @@ -22,6 +22,7 @@ from .commondb.failure_mode.record import RAMSTKFailureModeRecord # isort:skip from .commondb.group.record import RAMSTKGroupRecord # isort:skip from .commondb.hazards.record import RAMSTKHazardsRecord # isort:skip +from .commondb.load_history.record import RAMSTKLoadHistoryRecord # isort:skip from .commondb.site_info.record import RAMSTKSiteInfoRecord # isort:skip from .commondb.subcategory.record import RAMSTKSubCategoryRecord # isort:skip from .commondb.category.table import RAMSTKCategoryTable # isort:skip @@ -32,6 +33,7 @@ from .commondb.failure_mode.table import RAMSTKFailureModeTable from .commondb.group.table import RAMSTKGroupTable from .commondb.hazards.table import RAMSTKHazardsTable +from .commondb.load_history.table import RAMSTKLoadHistoryTable from .commondb.site_info.table import RAMSTKSiteInfoTable from .commondb.subcategory.table import RAMSTKSubCategoryTable from .programdb.action.record import RAMSTKActionRecord diff --git a/src/ramstk/models/commondb/__init__.py b/src/ramstk/models/commondb/__init__.py index b531da8f3..b81b6c894 100644 --- a/src/ramstk/models/commondb/__init__.py +++ b/src/ramstk/models/commondb/__init__.py @@ -8,7 +8,6 @@ """The RAMSTK common database models package.""" # RAMSTK Local Imports -from .ramstkloadhistory import RAMSTKLoadHistory from .ramstkmanufacturer import RAMSTKManufacturer from .ramstkmeasurement import RAMSTKMeasurement from .ramstkmethod import RAMSTKMethod diff --git a/src/ramstk/models/commondb/database.py b/src/ramstk/models/commondb/database.py index 4fea28517..014a00964 100644 --- a/src/ramstk/models/commondb/database.py +++ b/src/ramstk/models/commondb/database.py @@ -22,12 +22,12 @@ RAMSTKFailureModeRecord, RAMSTKGroupRecord, RAMSTKHazardsRecord, + RAMSTKLoadHistoryRecord, RAMSTKSiteInfoRecord, RAMSTKSubCategoryRecord, ) from ramstk.models.commondb import ( RAMSTKRPN, - RAMSTKLoadHistory, RAMSTKManufacturer, RAMSTKMeasurement, RAMSTKMethod, @@ -559,7 +559,7 @@ def _do_load_load_history( :return: user_configuration :rtype: RAMSTKUserConfiguration """ - for _record in self.common_dao.session.query(RAMSTKLoadHistory).all(): + for _record in self.common_dao.session.query(RAMSTKLoadHistoryRecord).all(): _attributes = _record.get_attributes() user_configuration.RAMSTK_LOAD_HISTORY[_record.history_id] = _attributes[ "description" diff --git a/src/ramstk/models/commondb/database.pyi b/src/ramstk/models/commondb/database.pyi index 987d7f361..87aae2840 100644 --- a/src/ramstk/models/commondb/database.pyi +++ b/src/ramstk/models/commondb/database.pyi @@ -11,10 +11,10 @@ from ramstk.models import RAMSTKCategoryRecord as RAMSTKCategoryRecord from ramstk.models import RAMSTKFailureModeRecord as RAMSTKFailureModeRecord from ramstk.models import RAMSTKGroupRecord as RAMSTKGroupRecord from ramstk.models import RAMSTKHazardsRecord as RAMSTKHazardsRecord +from ramstk.models import RAMSTKLoadHistoryRecord as RAMSTKLoadHistoryRecord from ramstk.models import RAMSTKSiteInfoRecord as RAMSTKSiteInfoRecord from ramstk.models import RAMSTKSubCategoryRecord as RAMSTKSubCategoryRecord from ramstk.models.commondb import RAMSTKRPN as RAMSTKRPN -from ramstk.models.commondb import RAMSTKLoadHistory as RAMSTKLoadHistory from ramstk.models.commondb import RAMSTKManufacturer as RAMSTKManufacturer from ramstk.models.commondb import RAMSTKMeasurement as RAMSTKMeasurement from ramstk.models.commondb import RAMSTKMethod as RAMSTKMethod diff --git a/src/ramstk/models/commondb/load_history/__init__.py b/src/ramstk/models/commondb/load_history/__init__.py new file mode 100644 index 000000000..4040aa41a --- /dev/null +++ b/src/ramstk/models/commondb/load_history/__init__.py @@ -0,0 +1,8 @@ +# pylint: disable=unused-import +# -*- coding: utf-8 -*- +# +# ramstk.models.commondb.load_history.__init__.py is part of The RAMSTK Project +# +# All rights reserved. +# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland reliaqual com +"""The RAMSTK Load History model package.""" diff --git a/src/ramstk/models/commondb/ramstkloadhistory.py b/src/ramstk/models/commondb/load_history/record.py similarity index 72% rename from src/ramstk/models/commondb/ramstkloadhistory.py rename to src/ramstk/models/commondb/load_history/record.py index 72f458d98..c62d0946f 100644 --- a/src/ramstk/models/commondb/ramstkloadhistory.py +++ b/src/ramstk/models/commondb/load_history/record.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- # -# ramstk.models.commondb.RAMSTKLoadHistory.py is part of The RAMSTK +# ramstk.models.commondb.load_history.record.py is part of The RAMSTK # Project # # All rights reserved. -# Copyright 2007 - 2017 Doyle Rowland doyle.rowland reliaqual com -"""RAMSTKLoadHistory Table.""" +# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland reliaqual com +"""Load History Table Model.""" # Third Party Imports from sqlalchemy import Column, Integer, String @@ -15,10 +15,12 @@ from ramstk.models import RAMSTKBaseRecord -class RAMSTKLoadHistory(RAMSTK_BASE, RAMSTKBaseRecord): +class RAMSTKLoadHistoryRecord(RAMSTK_BASE, RAMSTKBaseRecord): """Class to represent the table ramstk_load_history.""" - __defaults__ = {"description": "Load History Description"} + __defaults__ = { + "description": "Load History Description", + } __tablename__ = "ramstk_load_history" __table_args__ = {"extend_existing": True} @@ -39,9 +41,7 @@ def get_attributes(self): :return: {load_history_id, description} pairs :rtype: dict """ - _values = { + return { "history_id": self.history_id, "description": self.description, } - - return _values diff --git a/src/ramstk/models/commondb/load_history/table.py b/src/ramstk/models/commondb/load_history/table.py new file mode 100644 index 000000000..7257805e9 --- /dev/null +++ b/src/ramstk/models/commondb/load_history/table.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# +# ramstk.models.commondb.load_history.table.py is part of The RAMSTK Project +# +# All rights reserved. +# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland reliaqual com +"""Load History Table Model.""" + +# Standard Library Imports +from typing import Type + +# RAMSTK Package Imports +from ramstk.models import RAMSTKBaseTable, RAMSTKLoadHistoryRecord + + +class RAMSTKLoadHistoryTable(RAMSTKBaseTable): + """Contain the attributes and methods of the Load History table model.""" + + # Define private dict class attributes. + + # Define private list class attributes. + + # Define private scalar class attributes. + _db_id_colname = "fld_history_id" + _db_tablename = "ramstk_load_history" + _deprecated = False + _select_msg = "request_get_load_history" + _tag = "load_history" + + # Define public dict class attributes. + + # Define public list class attributes. + + # Define public scalar class attributes. + + def __init__(self, **kwargs) -> None: + """Initialize a Options data manager instance.""" + RAMSTKBaseTable.__init__(self, **kwargs) + + # Initialize private dictionary attributes. + + # Initialize private list attributes. + self._lst_id_columns = [ + "history_id", + ] + + # Initialize private scalar attributes. + self._record: Type[RAMSTKLoadHistoryRecord] = RAMSTKLoadHistoryRecord + + # Initialize public dictionary attributes. + + # Initialize public list attributes. + + # Initialize public scalar attributes. + self.pkey = "history_id" + + # Subscribe to PyPubSub messages. diff --git a/src/ramstk/models/commondb/ramstkmanufacturer.py b/src/ramstk/models/commondb/ramstkmanufacturer.py index 0eed5619f..e764f9815 100644 --- a/src/ramstk/models/commondb/ramstkmanufacturer.py +++ b/src/ramstk/models/commondb/ramstkmanufacturer.py @@ -45,11 +45,9 @@ def get_attributes(self): :return: {manufacturer_id, description, location, cage_code} pairs :rtype: dict """ - _attributes = { + return { "manufacturer_id": self.manufacturer_id, "description": self.description, "location": self.location, "cage_code": self.cage_code, } - - return _attributes diff --git a/src/ramstk/models/commondb/ramstkmeasurement.py b/src/ramstk/models/commondb/ramstkmeasurement.py index ed6749a68..47658be49 100644 --- a/src/ramstk/models/commondb/ramstkmeasurement.py +++ b/src/ramstk/models/commondb/ramstkmeasurement.py @@ -47,11 +47,9 @@ def get_attributes(self): :return: {measurement_id, description} pairs. :rtype: dict """ - _attributes = { + return { "measurement_id": self.measurement_id, "code": self.code, "description": self.description, "measurement_type": self.measurement_type, } - - return _attributes diff --git a/src/ramstk/models/commondb/ramstkmethod.py b/src/ramstk/models/commondb/ramstkmethod.py index 54676d390..6bdb2afae 100644 --- a/src/ramstk/models/commondb/ramstkmethod.py +++ b/src/ramstk/models/commondb/ramstkmethod.py @@ -46,11 +46,9 @@ def get_attributes(self): :return: {method_id, name, description, method_type} pairs. :rtype: dict """ - _attributes = { + return { "method_id": self.method_id, "name": self.name, "description": self.description, "method_type": self.method_type, } - - return _attributes diff --git a/src/ramstk/models/commondb/ramstkmodel.py b/src/ramstk/models/commondb/ramstkmodel.py index 635493969..7b4a5db74 100644 --- a/src/ramstk/models/commondb/ramstkmodel.py +++ b/src/ramstk/models/commondb/ramstkmodel.py @@ -42,10 +42,8 @@ def get_attributes(self) -> Dict[str, object]: :return: {model_id, description, model_type} pairs. :rtype: dict """ - _attributes = { + return { "model_id": self.model_id, "description": self.description, "model_type": self.model_type, } - - return _attributes diff --git a/src/ramstk/models/commondb/ramstkrpn.py b/src/ramstk/models/commondb/ramstkrpn.py index 7b9bc8120..fc228562b 100644 --- a/src/ramstk/models/commondb/ramstkrpn.py +++ b/src/ramstk/models/commondb/ramstkrpn.py @@ -46,12 +46,10 @@ def get_attributes(self): :return: {}rpn_id, name, description, rpn_type, value} key:value pairs :rtype: dict """ - _values = { + return { "rpn_id": self.rpn_id, "name": self.name, "description": self.description, "rpn_type": self.rpn_type, "value": self.value, } - - return _values diff --git a/src/ramstk/models/commondb/ramstkstakeholders.py b/src/ramstk/models/commondb/ramstkstakeholders.py index 6dd499cc7..0ecd7bb2b 100644 --- a/src/ramstk/models/commondb/ramstkstakeholders.py +++ b/src/ramstk/models/commondb/ramstkstakeholders.py @@ -39,9 +39,7 @@ def get_attributes(self): :return: {stakeholders_id, stakeholder} pairs. :rtype: dict """ - _attributes = { + return { "stakeholders_id": self.stakeholders_id, "stakeholder": self.stakeholder, } - - return _attributes diff --git a/src/ramstk/models/commondb/ramstkstatus.py b/src/ramstk/models/commondb/ramstkstatus.py index 8f2a83263..9ebe0a881 100644 --- a/src/ramstk/models/commondb/ramstkstatus.py +++ b/src/ramstk/models/commondb/ramstkstatus.py @@ -46,11 +46,9 @@ def get_attributes(self): :return: {status_id, name, description, status_type} pairs. :rtype: dict """ - _attributes = { + return { "status_id": self.status_id, "name": self.name, "description": self.description, "status_type": self.status_type, } - - return _attributes diff --git a/src/ramstk/models/commondb/ramstktype.py b/src/ramstk/models/commondb/ramstktype.py index 425feeeb1..8ae2821e7 100644 --- a/src/ramstk/models/commondb/ramstktype.py +++ b/src/ramstk/models/commondb/ramstktype.py @@ -44,11 +44,9 @@ def get_attributes(self): :return: {type_id, description, type_type} pairs. :rtype: dict """ - _attributes = { + return { "type_id": self.type_id, "code": self.code, "description": self.description, "type_type": self.type_type, } - - return _attributes diff --git a/src/ramstk/models/commondb/ramstkuser.py b/src/ramstk/models/commondb/ramstkuser.py index d2301f2bb..84e503a0d 100644 --- a/src/ramstk/models/commondb/ramstkuser.py +++ b/src/ramstk/models/commondb/ramstkuser.py @@ -60,7 +60,7 @@ def get_attributes(self): user_group_id} pairs. :rtype: dict """ - _attributes = { + return { "user_id": self.user_id, "user_lname": self.user_lname, "user_fname": self.user_fname, @@ -68,5 +68,3 @@ def get_attributes(self): "user_phone": self.user_phone, "user_group_id": self.user_group_id, } - - return _attributes diff --git a/src/ramstk/models/commondb/site_info/record.py b/src/ramstk/models/commondb/site_info/record.py index b8bb34a3e..8e6ddd9d5 100644 --- a/src/ramstk/models/commondb/site_info/record.py +++ b/src/ramstk/models/commondb/site_info/record.py @@ -135,7 +135,7 @@ def get_attributes(self): requirement_enabled, vandv_enabled, fmea_enabled} pairs. :rtype: dict """ - _attributes = { + return { "site_id": self.site_id, "site_name": self.site_name, "product_key": self.product_key, @@ -158,5 +158,3 @@ def get_attributes(self): "rbd_enabled": self.rbd_enabled, "fta_enabled": self.fta_enabled, } - - return _attributes diff --git a/src/ramstk/models/programdb/action/record.py b/src/ramstk/models/programdb/action/record.py index a28308e3a..9cdbb7dfb 100644 --- a/src/ramstk/models/programdb/action/record.py +++ b/src/ramstk/models/programdb/action/record.py @@ -137,7 +137,7 @@ def get_attributes(self): action_closed_date} pairs. :rtype: dict """ - _attributes = { + return { "cause_id": self.cause_id, "action_id": self.action_id, "action_recommended": self.action_recommended, @@ -151,5 +151,3 @@ def get_attributes(self): "action_closed": self.action_closed, "action_close_date": self.action_close_date, } - - return _attributes diff --git a/src/ramstk/models/programdb/allocation/record.py b/src/ramstk/models/programdb/allocation/record.py index 25b9c167d..dae05799f 100644 --- a/src/ramstk/models/programdb/allocation/record.py +++ b/src/ramstk/models/programdb/allocation/record.py @@ -133,7 +133,7 @@ def get_attributes(self): soa_factor, weight_factor} pairs. :rtype: dict """ - _attributes = { + return { "revision_id": self.revision_id, "hardware_id": self.hardware_id, "availability_alloc": self.availability_alloc, @@ -158,5 +158,3 @@ def get_attributes(self): "soa_factor": self.soa_factor, "weight_factor": self.weight_factor, } - - return _attributes diff --git a/src/ramstk/models/programdb/cause/record.py b/src/ramstk/models/programdb/cause/record.py index 5300e9550..b7b9d6e46 100644 --- a/src/ramstk/models/programdb/cause/record.py +++ b/src/ramstk/models/programdb/cause/record.py @@ -122,7 +122,7 @@ def get_attributes(self): rpn_new} :rtype: tuple """ - _attributes = { + return { "mode_id": self.mode_id, "mechanism_id": self.mechanism_id, "cause_id": self.cause_id, @@ -134,5 +134,3 @@ def get_attributes(self): "rpn_occurrence": self.rpn_occurrence, "rpn_occurrence_new": self.rpn_occurrence_new, } - - return _attributes diff --git a/src/ramstk/models/programdb/control/record.py b/src/ramstk/models/programdb/control/record.py index 4ef80b69c..1175d5b0e 100644 --- a/src/ramstk/models/programdb/control/record.py +++ b/src/ramstk/models/programdb/control/record.py @@ -85,11 +85,9 @@ def get_attributes(self): :return: {cause_id, control_id, description, type_id} pairs. :rtype: dict """ - _attributes = { + return { "cause_id": self.cause_id, "control_id": self.control_id, "description": self.description, "type_id": self.type_id, } - - return _attributes diff --git a/src/ramstk/models/programdb/design_mechanic/record.py b/src/ramstk/models/programdb/design_mechanic/record.py index f6d5d9808..ba2de5ec7 100644 --- a/src/ramstk/models/programdb/design_mechanic/record.py +++ b/src/ramstk/models/programdb/design_mechanic/record.py @@ -248,7 +248,7 @@ def get_attributes(self): viscosity_dynamic, water_per_cent, width_minimum} pairs. :rtype: dict """ - _attributes = { + return { "hardware_id": self.hardware_id, "altitude_operating": self.altitude_operating, "application_id": self.application_id, @@ -303,5 +303,3 @@ def get_attributes(self): "water_per_cent": self.water_per_cent, "width_minimum": self.width_minimum, } - - return _attributes diff --git a/src/ramstk/models/programdb/fmea/view.py b/src/ramstk/models/programdb/fmea/view.py index 83cab2cb1..d40cff8ee 100644 --- a/src/ramstk/models/programdb/fmea/view.py +++ b/src/ramstk/models/programdb/fmea/view.py @@ -151,6 +151,8 @@ def _do_load_causes(self, mechanism_id: int, parent_id: str) -> None: _cause = _node.data["cause"] if _cause.mechanism_id == mechanism_id: + _node_id = f"{parent_id}.{_cause.cause_id}" + self.tree.create_node( tag="cause", identifier=f"{parent_id}.{_cause.cause_id}", @@ -182,6 +184,8 @@ def _do_load_controls(self, cause_id: int, parent_id: str) -> None: _control = _node.data["control"] if _control.cause_id == cause_id: + _node_id = f"{parent_id}.{_control.control_id}c" + self.tree.create_node( tag="control", identifier=f"{parent_id}.{_control.control_id}c", @@ -201,6 +205,8 @@ def _do_load_actions(self, cause_id: int, parent_id: str) -> None: _action = _node.data["action"] if _action.cause_id == cause_id: + _node_id = f"{parent_id}.{_action.action_id}a" + self.tree.create_node( tag="action", identifier=f"{parent_id}.{_action.action_id}a", diff --git a/src/ramstk/models/programdb/function/record.py b/src/ramstk/models/programdb/function/record.py index 565afb0f5..7b6b6ab86 100644 --- a/src/ramstk/models/programdb/function/record.py +++ b/src/ramstk/models/programdb/function/record.py @@ -135,7 +135,7 @@ def get_attributes(self): type_id} pairs. :rtype: tuple """ - _values = { + return { "revision_id": self.revision_id, "function_id": self.function_id, "availability_logistics": self.availability_logistics, @@ -159,5 +159,3 @@ def get_attributes(self): "total_part_count": self.total_part_count, "type_id": self.type_id, } - - return _values diff --git a/src/ramstk/models/programdb/hardware/record.py b/src/ramstk/models/programdb/hardware/record.py index b4ed2bc9d..ed7842a6f 100644 --- a/src/ramstk/models/programdb/hardware/record.py +++ b/src/ramstk/models/programdb/hardware/record.py @@ -230,7 +230,7 @@ def get_attributes(self) -> Dict[str, Union[float, int, str]]: total_power_dissipation, year_of_manufacture} pairs. :rtype: dict """ - _attributes = { + return { "revision_id": self.revision_id, "hardware_id": self.hardware_id, "alt_part_number": self.alt_part_number, @@ -268,8 +268,6 @@ def get_attributes(self) -> Dict[str, Union[float, int, str]]: "year_of_manufacture": self.year_of_manufacture, } - return _attributes - def do_calculate_total_cost(self) -> None: """Calculate the total cost of the hardware item.""" if self.cost_type_id == 1: diff --git a/src/ramstk/models/programdb/hardware/view.py b/src/ramstk/models/programdb/hardware/view.py index c1d0b76ed..3a0d6bbf0 100644 --- a/src/ramstk/models/programdb/hardware/view.py +++ b/src/ramstk/models/programdb/hardware/view.py @@ -249,6 +249,7 @@ def do_calculate_cost(self, node_id: int) -> None: for _node in self.tree.children(node_id): self.do_calculate_cost(_node.identifier) _total_cost += _node.data["hardware"].total_cost + _total_cost *= _record.quantity _record.set_attributes({"cost": _total_cost}) _record.set_attributes({"total_cost": _total_cost}) @@ -313,6 +314,7 @@ def do_calculate_part_count(self, node_id: int) -> None: for _node in self.tree.children(node_id): self.do_calculate_part_count(_node.identifier) _total_part_count += _node.data["hardware"].total_part_count + _total_part_count *= _record.quantity _record.set_attributes({"total_part_count": _total_part_count}) @@ -384,6 +386,7 @@ def do_calculate_power_dissipation(self, node_id: int) -> float: _total_power_dissipation += self.do_calculate_power_dissipation( _node_id ) + _total_power_dissipation *= _record.data["hardware"].quantity _record.data["design_electric"].set_attributes( {"power_operating": _total_power_dissipation} diff --git a/src/ramstk/models/programdb/hazard/record.py b/src/ramstk/models/programdb/hazard/record.py index 658f2e332..59a6d47b9 100644 --- a/src/ramstk/models/programdb/hazard/record.py +++ b/src/ramstk/models/programdb/hazard/record.py @@ -223,7 +223,7 @@ def get_attributes(self) -> Dict[str, Any]: user_int_2, user_int_3} pairs :rtype: dict """ - _attributes = { + return { "revision_id": self.revision_id, "function_id": self.function_id, "hazard_id": self.hazard_id, @@ -266,5 +266,3 @@ def get_attributes(self) -> Dict[str, Any]: "user_int_2": self.user_int_2, "user_int_3": self.user_int_3, } - - return _attributes diff --git a/src/ramstk/models/programdb/mechanism/record.py b/src/ramstk/models/programdb/mechanism/record.py index e31070dea..4666c82fe 100644 --- a/src/ramstk/models/programdb/mechanism/record.py +++ b/src/ramstk/models/programdb/mechanism/record.py @@ -123,7 +123,7 @@ def get_attributes(self): rpn_occurrence_new} pairs :rtype: dict """ - _attributes = { + return { "mode_id": self.mode_id, "mechanism_id": self.mechanism_id, "description": self.description, @@ -135,5 +135,3 @@ def get_attributes(self): "rpn_occurrence": self.rpn_occurrence, "rpn_occurrence_new": self.rpn_occurrence_new, } - - return _attributes diff --git a/src/ramstk/models/programdb/milhdbk217f/record.py b/src/ramstk/models/programdb/milhdbk217f/record.py index 844f350a0..33536217d 100644 --- a/src/ramstk/models/programdb/milhdbk217f/record.py +++ b/src/ramstk/models/programdb/milhdbk217f/record.py @@ -122,7 +122,7 @@ def get_attributes(self): piPT, piQ, piR, piS, piT, piTAPS, piU, piV} pairs. :rtype: dict """ - _attributes = { + return { "hardware_id": self.hardware_id, "A1": self.A1, "A2": self.A2, @@ -160,5 +160,3 @@ def get_attributes(self): "piU": self.piU, "piV": self.piV, } - - return _attributes diff --git a/src/ramstk/models/programdb/mode/record.py b/src/ramstk/models/programdb/mode/record.py index 9745102cd..824af04f5 100644 --- a/src/ramstk/models/programdb/mode/record.py +++ b/src/ramstk/models/programdb/mode/record.py @@ -196,7 +196,7 @@ def get_attributes(self): severity_class, single_point, type_id} pairs. :rtype: dict """ - _attributes = { + return { "revision_id": self.revision_id, "hardware_id": self.hardware_id, "mode_id": self.mode_id, @@ -226,5 +226,3 @@ def get_attributes(self): "single_point": self.single_point, "type_id": self.type_id, } - - return _attributes diff --git a/src/ramstk/models/programdb/nswc/record.py b/src/ramstk/models/programdb/nswc/record.py index f3bfb903a..a4c913b61 100644 --- a/src/ramstk/models/programdb/nswc/record.py +++ b/src/ramstk/models/programdb/nswc/record.py @@ -167,7 +167,7 @@ def get_attributes(self): Csv, Csw, Csz, Ct, Cv, Cw, Cy} pairs. :rtype: dict """ - _attributes = { + return { "hardware_id": self.hardware_id, "Cac": self.Cac, "Calt": self.Calt, @@ -227,5 +227,3 @@ def get_attributes(self): "Cw": self.Cw, "Cy": self.Cy, } - - return _attributes diff --git a/src/ramstk/models/programdb/program_info/record.py b/src/ramstk/models/programdb/program_info/record.py index 22a1b1021..1cc3fde1f 100644 --- a/src/ramstk/models/programdb/program_info/record.py +++ b/src/ramstk/models/programdb/program_info/record.py @@ -128,7 +128,7 @@ def get_attributes(self): last_saved_by, method} pairs. :rtype: dict """ - _attributes = { + return { "revision_id": self.revision_id, "function_active": self.function_active, "requirement_active": self.requirement_active, @@ -152,5 +152,3 @@ def get_attributes(self): "last_saved": self.last_saved, "last_saved_by": self.last_saved_by, } - - return _attributes diff --git a/src/ramstk/models/programdb/program_status/record.py b/src/ramstk/models/programdb/program_status/record.py index a99fe244b..54bd688cb 100644 --- a/src/ramstk/models/programdb/program_status/record.py +++ b/src/ramstk/models/programdb/program_status/record.py @@ -59,12 +59,10 @@ def get_attributes(self): pairs. :rtype: dict """ - _attributes = { + return { "revision_id": self.revision_id, "status_id": self.status_id, "cost_remaining": self.cost_remaining, "date_status": self.date_status, "time_remaining": self.time_remaining, } - - return _attributes diff --git a/src/ramstk/models/programdb/requirement/record.py b/src/ramstk/models/programdb/requirement/record.py index 17f22314a..d4edd1974 100644 --- a/src/ramstk/models/programdb/requirement/record.py +++ b/src/ramstk/models/programdb/requirement/record.py @@ -231,7 +231,7 @@ def get_attributes(self): q_verifiable_3, q_verifiable_4, q_verifiable_5} pairs. :rtype: dict """ - _attributes = { + return { "revision_id": self.revision_id, "requirement_id": self.requirement_id, "derived": self.derived, @@ -282,8 +282,6 @@ def get_attributes(self): "q_verifiable_5": self.q_verifiable_5, } - return _attributes - def create_code(self, prefix: str) -> None: """Create Requirement code based on the requirement type and it's ID. diff --git a/src/ramstk/models/programdb/revision/record.py b/src/ramstk/models/programdb/revision/record.py index b2fa32869..b454a7e00 100644 --- a/src/ramstk/models/programdb/revision/record.py +++ b/src/ramstk/models/programdb/revision/record.py @@ -256,7 +256,7 @@ def get_attributes(self): program_cost_se} pairs. :rtype: dict """ - _attributes = { + return { "revision_id": self.revision_id, "availability_logistics": self.availability_logistics, "availability_mission": self.availability_mission, @@ -285,5 +285,3 @@ def get_attributes(self): "program_cost": self.program_cost, "program_cost_sd": self.program_cost_sd, } - - return _attributes diff --git a/src/ramstk/models/programdb/similar_item/record.py b/src/ramstk/models/programdb/similar_item/record.py index 56bbfa3c5..eee8d1f8c 100644 --- a/src/ramstk/models/programdb/similar_item/record.py +++ b/src/ramstk/models/programdb/similar_item/record.py @@ -273,7 +273,7 @@ def get_attributes(self): user_int_5} :rtype: tuple """ - _attributes = { + return { "hardware_id": self.hardware_id, "change_description_1": self.change_description_1, "change_description_2": self.change_description_2, @@ -329,5 +329,3 @@ def get_attributes(self): "user_int_4": self.user_int_4, "user_int_5": self.user_int_5, } - - return _attributes diff --git a/src/ramstk/models/programdb/stakeholder/record.py b/src/ramstk/models/programdb/stakeholder/record.py index e08ddbea6..4122b4974 100644 --- a/src/ramstk/models/programdb/stakeholder/record.py +++ b/src/ramstk/models/programdb/stakeholder/record.py @@ -100,7 +100,7 @@ def get_attributes(self): user_float_3, user_float_4, user_float_5} pairs. :rtype: tuple """ - _attributes = { + return { "revision_id": self.revision_id, "stakeholder_id": self.stakeholder_id, "customer_rank": self.customer_rank, @@ -118,5 +118,3 @@ def get_attributes(self): "user_float_4": self.user_float_4, "user_float_5": self.user_float_5, } - - return _attributes diff --git a/src/ramstk/models/programdb/validation/table.py b/src/ramstk/models/programdb/validation/table.py index 50ab54681..dc0e514ba 100644 --- a/src/ramstk/models/programdb/validation/table.py +++ b/src/ramstk/models/programdb/validation/table.py @@ -98,7 +98,6 @@ def do_calculate_plan(self) -> None: :return: _planned; the pandas DataFrame() containing the planned burndown hours for the entire validation effort. """ - _dic_plan = {} _dic_planned = {} # type: ignore _time_ll = 0.0 _time_mean = 0.0 diff --git a/src/ramstk/views/gtk3/allocation/panel.py b/src/ramstk/views/gtk3/allocation/panel.py index 28469ce71..47407a661 100644 --- a/src/ramstk/views/gtk3/allocation/panel.py +++ b/src/ramstk/views/gtk3/allocation/panel.py @@ -930,7 +930,7 @@ def __do_load_allocation(self, node: Any = "", row: Gtk.TreeIter = None) -> None """ _entity = node.data["allocation"] - if not _entity.parent_id == 0: + if _entity.parent_id != 0: _attributes = [ _entity.revision_id, _entity.hardware_id, @@ -964,11 +964,12 @@ def __do_load_allocation(self, node: Any = "", row: Gtk.TreeIter = None) -> None except (AttributeError, TypeError, ValueError): _message = _( f"An error occurred when loading allocation record " - f"{str(node.identifier)} into the allocation list. This might " - f"indicate it was missing it's data package, some of the data in " - f"the package was missing, or some of the data was the wrong " - f"type. Row data was: {_attributes}" + f"{node.identifier} into the allocation list. This might indicate " + f"it was missing it's data package, some of the data in the " + f"package was missing, or some of the data was the wrong type. " + f"Row data was: {_attributes}" ) + pub.sendMessage( "do_log_warning_msg", logger_name="WARNING", diff --git a/src/ramstk/views/gtk3/assistants/imports.py b/src/ramstk/views/gtk3/assistants/imports.py index 977b254f4..19e0a7bc5 100644 --- a/src/ramstk/views/gtk3/assistants/imports.py +++ b/src/ramstk/views/gtk3/assistants/imports.py @@ -126,7 +126,7 @@ def _do_load_import_fields(self, import_fields: List[str]) -> None: _cellmodel.append([""]) # pylint: disable=unused-variable - for __, _field in enumerate(import_fields): + for _field in import_fields: _cellmodel.append([_field]) def _do_quit(self, __widget: Gtk.Widget) -> None: diff --git a/src/ramstk/views/gtk3/stakeholder/panel.py b/src/ramstk/views/gtk3/stakeholder/panel.py index 7e125f3fb..bccdf5cfb 100644 --- a/src/ramstk/views/gtk3/stakeholder/panel.py +++ b/src/ramstk/views/gtk3/stakeholder/panel.py @@ -352,8 +352,7 @@ def do_load_affinity_groups(self, affinities: Dict[int, Tuple[str, str]]) -> Non _cellmodel.append([""]) # pylint: disable=unused-variable - for __, _key in enumerate(affinities): - _group = affinities[_key] + for _key, _group in affinities.items(): _cellmodel.append([_group[0]]) def do_load_stakeholders(self, stakeholders: Dict[int, str]) -> None: @@ -371,8 +370,7 @@ def do_load_stakeholders(self, stakeholders: Dict[int, str]) -> None: _cellmodel.append([""]) # pylint: disable=unused-variable - for __, _key in enumerate(stakeholders): - _group = stakeholders[_key] + for _key, _group in stakeholders.items(): _cellmodel.append([_group]) def _do_load_requirements(self, tree: treelib.Tree) -> None: diff --git a/src/ramstk/views/gtk3/widgets/button.py b/src/ramstk/views/gtk3/widgets/button.py index 2cd767977..699f3f0b0 100644 --- a/src/ramstk/views/gtk3/widgets/button.py +++ b/src/ramstk/views/gtk3/widgets/button.py @@ -120,7 +120,7 @@ def do_set_properties(self, **kwargs: Any) -> None: super().do_set_properties(**kwargs) self.set_property("always_show_image", True) - _icon = kwargs.get("icon", None) + _icon = kwargs.get("icon") if _icon is not None: self.set_label("") @@ -224,7 +224,7 @@ def do_set_properties(self, **kwargs: Any) -> None: """ super().do_set_properties(**kwargs) - _select_action = kwargs.get("select-action", None) + _select_action = kwargs.get("select-action") self.set_action(_select_action) diff --git a/src/ramstk/views/gtk3/widgets/combo.py b/src/ramstk/views/gtk3/widgets/combo.py index d43d079fa..4a58db1c9 100644 --- a/src/ramstk/views/gtk3/widgets/combo.py +++ b/src/ramstk/views/gtk3/widgets/combo.py @@ -42,6 +42,7 @@ def __init__(self, index: int = 0, simple: bool = True) -> None: # Initialize private scalar attributes. self._index: int = index + _list = Gtk.ListStore() # Initialize public dictionary attributes. # Initialize public list attributes. @@ -49,12 +50,10 @@ def __init__(self, index: int = 0, simple: bool = True) -> None: # Initialize public scalar attributes. if not simple: - _list = Gtk.ListStore() _list.set_column_types( [GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING] ) else: - _list = Gtk.ListStore() _list.set_column_types([GObject.TYPE_STRING]) self.set_model(_list) @@ -122,12 +121,12 @@ def do_load_combo( if not simple: _model.append(["", "", ""]) # pylint: disable=unused-variable - for __, _entry in enumerate(entries): + for _entry in entries: _model.append(list(_entry)) else: _model.append([""]) # pylint: disable=unused-variable - for __, _entry in enumerate(entries): + for _entry in entries: _model.append([_entry[self._index]]) if _handler_id > 0: @@ -163,6 +162,4 @@ def get_value(self, index: int = 0) -> str: _model = self.get_model() _row = self.get_active_iter() - _value: str = _model.get_value(_row, index) - - return _value + return _model.get_value(_row, index) diff --git a/src/ramstk/views/gtk3/widgets/label.py b/src/ramstk/views/gtk3/widgets/label.py index 30fd0032c..1b599989c 100644 --- a/src/ramstk/views/gtk3/widgets/label.py +++ b/src/ramstk/views/gtk3/widgets/label.py @@ -77,14 +77,11 @@ def do_set_properties(self, **kwargs: Any) -> None: self.set_property("justify", _justify) if _justify == Gtk.Justification.CENTER: self.set_xalign(0.5) - self.set_yalign(0.5) elif _justify == Gtk.Justification.LEFT: self.set_xalign(0.05) - self.set_yalign(0.5) else: self.set_xalign(0.99) - self.set_yalign(0.5) - + self.set_yalign(0.5) if _bold: _text = self.get_property("label") _text = "" + _text + "" @@ -128,10 +125,10 @@ def do_make_label_group( _lst_labels = [] _max_x = 0 - _char_width = max([len(_label_text) for _label_text in text]) + _char_width = max(len(_label_text) for _label_text in text) # pylint: disable=unused-variable - for __, _label_text in enumerate(text): + for _label_text in text: _label = RAMSTKLabel(_label_text) _label.do_set_properties( bold=_bold, height=-1, justify=_justify, width=-1, wrap=_wrap diff --git a/src/ramstk/views/gtk3/widgets/plot.py b/src/ramstk/views/gtk3/widgets/plot.py index be6af6a35..5cbfcdd3c 100644 --- a/src/ramstk/views/gtk3/widgets/plot.py +++ b/src/ramstk/views/gtk3/widgets/plot.py @@ -201,10 +201,8 @@ def do_make_labels(self, label: str, **kwargs: Any) -> matplotlib.text.Text: _x_pos = kwargs.get("x_pos", 0) _y_pos = kwargs.get("y_pos", 0) - _label = None - if _set_x: - _label = self.axis.set_xlabel( + return self.axis.set_xlabel( label, { "fontsize": _fontsize, @@ -216,7 +214,7 @@ def do_make_labels(self, label: str, **kwargs: Any) -> matplotlib.text.Text: }, ) else: - _label = self.axis.set_ylabel( + return self.axis.set_ylabel( label, { "fontsize": _fontsize, @@ -227,8 +225,6 @@ def do_make_labels(self, label: str, **kwargs: Any) -> matplotlib.text.Text: }, ) - return _label - # pylint: disable=too-many-arguments def do_make_legend(self, text: List[str], **kwargs: Any) -> None: """Make a legend on the RAMSTKPlot. diff --git a/tests/analyses/milhdbk217f/models/test_connection.py b/tests/analyses/milhdbk217f/models/test_connection.py index ffdf19ba5..e98d1a665 100644 --- a/tests/analyses/milhdbk217f/models/test_connection.py +++ b/tests/analyses/milhdbk217f/models/test_connection.py @@ -177,10 +177,7 @@ def test_get_mate_unmate_factor(n_cycles): @pytest.mark.parametrize("subcategory_id", [1, 3, 5]) def test_calculate_part_stress_lambda_b(subcategory_id): """calculate_part_stress_lamba_b() should return a float value for the part stress base hazard rate on success.""" - if subcategory_id == 1: - _factor_key = 2 - else: - _factor_key = 5 + _factor_key = 2 if subcategory_id == 1 else 5 _lambda_b = connection.calculate_part_stress_lambda_b( subcategory_id, 4, 325, _factor_key ) diff --git a/tests/analyses/statistics/distributions/_test_mcf.py b/tests/analyses/statistics/distributions/_test_mcf.py index a49eba457..593db58cb 100644 --- a/tests/analyses/statistics/distributions/_test_mcf.py +++ b/tests/analyses/statistics/distributions/_test_mcf.py @@ -115,7 +115,7 @@ def test_mcf_build_d_matrix_no_censoring(self): _data = {1: [5, 8], 3: [1, 8, 16]} _times = reduce(lambda x, y: x + y, _data.values()) - _times = set([float(f) for f in _times if isinstance(f, int)]) + _times = {float(f) for f in _times if isinstance(f, int)} _times = sorted(list(_times)) _d_matrix = d_matrix(_data, _times) @@ -148,7 +148,7 @@ def test_delta_matrix_no_censoring(self): _data = {1: [5, 8], 3: [1, 8, 16]} _times = reduce(lambda x, y: x + y, _data.values()) - _times = set([float(f) for f in _times if isinstance(f, int)]) + _times = {float(f) for f in _times if isinstance(f, int)} _times = sorted(list(_times)) _delta_matrix = delta_matrix(_data, _times) @@ -166,7 +166,7 @@ def test_mcf_variance(self): _data = {1: [5, 8, "12+"], 2: ["16+"], 3: [1, 8, 16, "20+"]} _times = reduce(lambda x, y: x + y, _data.values()) - _times = set([float(f) for f in _times if isinstance(f, int)]) + _times = {float(f) for f in _times if isinstance(f, int)} _times = sorted(list(_times)) _d_matrix = d_matrix(_data, _times) diff --git a/tests/conftest.py b/tests/conftest.py index 8ca709b75..3b338a15d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -31,10 +31,7 @@ from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT # RAMSTK Package Imports -from ramstk.configuration import ( - RAMSTKSiteConfiguration, - RAMSTKUserConfiguration, -) +from ramstk.configuration import RAMSTKSiteConfiguration, RAMSTKUserConfiguration from ramstk.db.base import BaseDatabase _ = gettext.gettext @@ -424,9 +421,7 @@ def setup_test_db(db_config) -> None: ) ) cursor.execute( - sql.SQL("CREATE DATABASE {}").format( - sql.Identifier(db_config["database"]) - ) + sql.SQL("CREATE DATABASE {}").format(sql.Identifier(db_config["database"])) ) cursor.close() conn.close() @@ -579,9 +574,7 @@ def test_common_dao(): """Create a test DAO object for testing against an RAMSTK Common DB.""" # Create a random name for the test database. This ensures each test class uses # a unique, clean database to test against. - db_name = "".join( - random.choices(string.ascii_uppercase + string.digits, k=10) - ) + db_name = "".join(random.choices(string.ascii_uppercase + string.digits, k=10)) # This will create a RAMSTK Common database using the # test_common_db.sql file in ./data for each group of tests collected in a @@ -620,9 +613,7 @@ def test_program_dao(): """Create a test DAO object for testing against a RAMSTK Program DB.""" # Create a random name for the test database. This ensures each test class uses # a unique, clean database to test against. - db_name = "".join( - random.choices(string.ascii_uppercase + string.digits, k=10) - ) + db_name = "".join(random.choices(string.ascii_uppercase + string.digits, k=10)) # This will create a RAMSTK Program database using the # test_program_db.sql file in tests/__data for each group of tests collected in a @@ -661,9 +652,7 @@ def test_simple_database(): """Create a simple test database using postgres.""" # Create a random name for the test database. This ensures each test class uses # a unique, clean database to test against. - db_name = "".join( - random.choices(string.ascii_uppercase + string.digits, k=10) - ) + db_name = "".join(random.choices(string.ascii_uppercase + string.digits, k=10)) # This temporary database has two tables (RAMSTKRevision and # RAMSTKSiteInfo) and is used primarily to test the connection, insert, @@ -701,9 +690,7 @@ def test_simple_program_database(): """Create a simple test database using postgres.""" # Create a random name for the test database. This ensures each test class uses # a unique, clean database to test against. - db_name = "".join( - random.choices(string.ascii_uppercase + string.digits, k=10) - ) + db_name = "".join(random.choices(string.ascii_uppercase + string.digits, k=10)) # This temporary database has two tables (RAMSTKRevision and # RAMSTKSiteInfo) and is used primarily to test the connection, insert, @@ -736,30 +723,28 @@ def test_simple_program_database(): def test_license_file(): """Create a license key file for testing.""" _cwd = os.getcwd() - _license_file = open(_cwd + "/license.key", "w") - _license_file.write("0\n") - _license_file.write("apowdigfb3rh9214839qu\n") - _license_file.write("2019-08-07\n") - _license_file.write("1\n") - _license_file.write("1\n") - _license_file.write("1\n") - _license_file.write("0\n") - _license_file.write("0\n") - _license_file.write("0\n") - _license_file.write("0\n") - _license_file.write("0\n") - _license_file.write("1\n") - _license_file.write("1\n") - _license_file.write("1\n") - _license_file.write("1\n") - _license_file.write("1\n") - _license_file.write("1\n") - _license_file.write("1\n") - _license_file.write("0\n") - _license_file.write("0\n") - _license_file.write("ReliaQual Test Site") - _license_file.close() - + with open(_cwd + "/license.key", "w") as _license_file: + _license_file.write("0\n") + _license_file.write("apowdigfb3rh9214839qu\n") + _license_file.write("2019-08-07\n") + _license_file.write("1\n") + _license_file.write("1\n") + _license_file.write("1\n") + _license_file.write("0\n") + _license_file.write("0\n") + _license_file.write("0\n") + _license_file.write("0\n") + _license_file.write("0\n") + _license_file.write("1\n") + _license_file.write("1\n") + _license_file.write("1\n") + _license_file.write("1\n") + _license_file.write("1\n") + _license_file.write("1\n") + _license_file.write("1\n") + _license_file.write("0\n") + _license_file.write("0\n") + _license_file.write("ReliaQual Test Site") yield _license_file os.remove(_cwd + "/license.key") @@ -782,9 +767,7 @@ def test_toml_site_configuration(test_config_dir): }, } - toml.dump( - _dic_site_configuration, open(_site_config.RAMSTK_SITE_CONF, "w") - ) + toml.dump(_dic_site_configuration, open(_site_config.RAMSTK_SITE_CONF, "w")) yield _site_config @@ -796,9 +779,7 @@ def test_toml_user_configuration(make_home_config_dir): _user_config._INSTALL_PREFIX = VIRTUAL_ENV _user_config.RAMSTK_HOME_DIR = VIRTUAL_ENV + "/tmp" _user_config.RAMSTK_CONF_DIR = VIRTUAL_ENV + "/tmp/.config/RAMSTK" - _user_config.RAMSTK_PROG_CONF = ( - _user_config.RAMSTK_CONF_DIR + "/RAMSTK.toml" - ) + _user_config.RAMSTK_PROG_CONF = _user_config.RAMSTK_CONF_DIR + "/RAMSTK.toml" _user_config.RAMSTK_DATA_DIR = _user_config.RAMSTK_CONF_DIR + "/layouts" _user_config.RAMSTK_ICON_DIR = _user_config.RAMSTK_CONF_DIR + "/icons" _user_config.RAMSTK_LOG_DIR = _user_config.RAMSTK_CONF_DIR + "/logs" @@ -952,9 +933,7 @@ def test_toml_user_configuration(make_home_config_dir): }, } - toml.dump( - _dic_user_configuration, open(_user_config.RAMSTK_PROG_CONF, "w") - ) + toml.dump(_dic_user_configuration, open(_user_config.RAMSTK_PROG_CONF, "w")) _user_config.get_user_configuration() yield _user_config @@ -1045,19 +1024,13 @@ def test_excel_file(): _book = xlwt.Workbook() _sheet = _book.add_sheet("Sheet 1", cell_overwrite_ok=True) - _col_num = 1 - for _header in HEADERS["Function"]: + for _col_num, _header in enumerate(HEADERS["Function"], start=1): _sheet.write(0, _col_num, _header) - _col_num += 1 - - _row_num = 1 - for _row in ROW_DATA[:2]: + for _row_num, _row in enumerate(ROW_DATA[:2], start=1): _col_num = 1 for _data in enumerate(_row): _sheet.write(_row_num, _col_num, _data[1]) _col_num += 1 - _row_num += 1 - _book.save(_test_file) yield _test_file diff --git a/tests/mocks/MockDAO.py b/tests/mocks/MockDAO.py index 6ef9da73e..b65ad37e0 100644 --- a/tests/mocks/MockDAO.py +++ b/tests/mocks/MockDAO.py @@ -29,13 +29,7 @@ def do_select_all(self, table, **kwargs: Dict[str, Any]) -> List[object]: _order: Any = kwargs.get("order", None) _all: bool = kwargs.get("_all", True) - if _all: - _records: List[object] = self.table - else: - # noinspection PyTypeChecker - _records = self.table[0] - - return _records + return self.table if _all else self.table[0] def do_select(self, node_id: int, table: str) -> object: """Mock the do_select() method. diff --git a/tests/models/commondb/load_history/conftest.py b/tests/models/commondb/load_history/conftest.py new file mode 100644 index 000000000..a1d86e462 --- /dev/null +++ b/tests/models/commondb/load_history/conftest.py @@ -0,0 +1,42 @@ +# Standard Library Imports +from datetime import date, timedelta + +# Third Party Imports +import pytest +from mocks import MockDAO + +# RAMSTK Package Imports +from ramstk.models import RAMSTKLoadHistoryRecord + + +@pytest.fixture +def mock_common_dao(monkeypatch): + _history_1 = RAMSTKLoadHistoryRecord() + _history_1.history_id = 1 + _history_1.description = "Histogram" + + DAO = MockDAO() + DAO.table = [ + _history_1, + ] + + yield DAO + + +@pytest.fixture(scope="function") +def test_attributes(): + yield { + "history_id": 1, + "description": "Histogram", + } + + +@pytest.fixture(scope="function") +def test_recordmodel(mock_common_dao): + """Get a record model instance for each test function.""" + dut = mock_common_dao.do_select_all(RAMSTKLoadHistoryRecord, _all=False) + + yield dut + + # Delete the device under test. + del dut diff --git a/tests/models/commondb/load_history/load_history_integration_test.py b/tests/models/commondb/load_history/load_history_integration_test.py new file mode 100644 index 000000000..a3fea96ba --- /dev/null +++ b/tests/models/commondb/load_history/load_history_integration_test.py @@ -0,0 +1,252 @@ +# pylint: skip-file +# type: ignore +# -*- coding: utf-8 -*- +# +# tests.models.commondb.load_history.load_history_integration_test.py is part of +# The RAMSTK Project +# +# All rights reserved. +# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland reliaqual com +"""Test class for testing LoadHistory module integrations.""" + +# Third Party Imports +import pytest +from pubsub import pub +from treelib import Tree + +# RAMSTK Package Imports +from ramstk.models import RAMSTKLoadHistoryRecord, RAMSTKLoadHistoryTable + + +@pytest.fixture(scope="class") +def test_tablemodel(test_common_dao): + """Get a data manager instance for each test class.""" + # Create the device under test (dut) and connect to the database. + dut = RAMSTKLoadHistoryTable() + dut.do_connect(test_common_dao) + dut.do_select_all({"history_id": 1}) + + yield dut + + # Unsubscribe from pypubsub topics. + pub.unsubscribe(dut.do_get_attributes, "request_get_load_history_attributes") + pub.unsubscribe(dut.do_set_attributes, "request_set_load_history_attributes") + pub.unsubscribe(dut.do_update, "request_update_load_history") + pub.unsubscribe(dut.do_get_tree, "request_get_load_history_tree") + pub.unsubscribe(dut.do_select_all, "request_get_load_history_attributes") + + # Delete the device under test. + del dut + + +@pytest.mark.usefixtures("test_tablemodel") +class TestSelectMethods: + """Class for testing data manager select_all() and select() methods.""" + + def on_succeed_select_all(self, tree): + assert isinstance(tree, Tree) + assert isinstance( + tree.get_node(1).data["load_history"], RAMSTKLoadHistoryRecord + ) + # There should be a root node with no data package and a node with + # the one RAMSTKLoadHistoryRecord record. + assert len(tree.all_nodes()) == 2 + print("\033[36m\nsucceed_retrieve_load_history topic was broadcast.") + + @pytest.mark.integration + def test_do_select_all_populated_tree(self, test_tablemodel): + """do_select_all() should clear nodes from an existing LoadHistory tree.""" + pub.subscribe(self.on_succeed_select_all, "succeed_retrieve_load_history") + + test_tablemodel.do_select_all({"history_id": 1}) + + pub.unsubscribe(self.on_succeed_select_all, "succeed_retrieve_load_history") + + +@pytest.mark.usefixtures("test_tablemodel") +class TestUpdateMethods: + """Class for testing update() and update_all() methods.""" + + def on_succeed_update(self, tree): + assert isinstance(tree, Tree) + assert tree.get_node(1).data["load_history"].description == "New Load History" + print("\033[36m\nsucceed_update_load_history topic was broadcast") + + def on_succeed_update_all(self): + print("\033[36m\nsucceed_update_all topic was broadcast") + + def on_fail_update_wrong_data_type(self, error_message): + assert error_message == ( + "do_update: The value for one or more attributes for load_history ID 1 was " + "the wrong type." + ) + print("\033[35m\nfail_update_load_history topic was broadcast on wrong type.") + + def on_fail_update_root_node_wrong_data_type(self, error_message): + assert error_message == ("do_update: Attempting to update the root node 0.") + print("\033[35m\nfail_update_load_history topic was broadcast on root node.") + + def on_fail_update_non_existent_id(self, error_message): + assert error_message == ( + "do_update: Attempted to save non-existent load history with " + "load history ID skullduggery." + ) + print( + "\033[35m\nfail_update_load_history topic was broadcast on non-existent ID." + ) + + def on_fail_update_no_data_package(self, error_message): + assert error_message == ( + "do_update: No data package found for load history ID 1." + ) + print( + "\033[35m\nfail_update_load_history topic was broadcast on no data package." + ) + + @pytest.mark.integration + def test_do_update(self, test_tablemodel): + """do_update() should return a zero error code on success.""" + pub.subscribe(self.on_succeed_update, "succeed_update_load_history") + + test_tablemodel.tree.get_node(1).data[ + "load_history" + ].description = "New Load History" + test_tablemodel.do_update(1) + + pub.unsubscribe(self.on_succeed_update, "succeed_update_load_history") + + assert ( + test_tablemodel.tree.get_node(1).data["load_history"].description + == "New Load History" + ) + + test_tablemodel.tree.get_node(1).data[ + "load_history" + ].description = "Integrated Circuit" + test_tablemodel.do_update(1) + + assert ( + test_tablemodel.tree.get_node(1).data["load_history"].description + == "Integrated Circuit" + ) + + @pytest.mark.integration + def test_do_update_all(self, test_tablemodel): + """do_update_all() should broadcast the succeed message on success.""" + pub.subscribe(self.on_succeed_update_all, "succeed_update_all") + + pub.sendMessage("request_update_all_load_history") + + pub.unsubscribe(self.on_succeed_update_all, "succeed_update_all") + + @pytest.mark.integration + def test_do_update_wrong_data_type(self, test_tablemodel): + """do_update() should return a zero error code on success.""" + pub.subscribe(self.on_fail_update_wrong_data_type, "fail_update_load_history") + + test_tablemodel.tree.get_node(1).data["load_history"].description = None + test_tablemodel.do_update(1) + + pub.unsubscribe(self.on_fail_update_wrong_data_type, "fail_update_load_history") + + @pytest.mark.integration + def test_do_update_root_node_wrong_data_type(self, test_tablemodel): + """do_update() should return a zero error code on success.""" + pub.subscribe( + self.on_fail_update_root_node_wrong_data_type, "fail_update_load_history" + ) + + test_tablemodel.tree.get_node(1).data["load_history"].description = None + test_tablemodel.do_update(0) + + pub.unsubscribe( + self.on_fail_update_root_node_wrong_data_type, "fail_update_load_history" + ) + + @pytest.mark.integration + def test_do_update_non_existent_id(self, test_tablemodel): + """do_update() should return a non-zero error code when passed a LoadHistory ID + that doesn't exist.""" + pub.subscribe(self.on_fail_update_non_existent_id, "fail_update_load_history") + + test_tablemodel.do_select_all({"history_id": 1}) + test_tablemodel.do_update("skullduggery") + + pub.unsubscribe(self.on_fail_update_non_existent_id, "fail_update_load_history") + + @pytest.mark.integration + def test_do_update_no_data_package(self, test_tablemodel): + """do_update() should return a non-zero error code when passed a LoadHistory ID + that doesn't exist.""" + pub.subscribe(self.on_fail_update_no_data_package, "fail_update_load_history") + + test_tablemodel.tree.get_node(1).data.pop("load_history") + test_tablemodel.do_update(1) + + pub.unsubscribe(self.on_fail_update_no_data_package, "fail_update_load_history") + + +@pytest.mark.usefixtures("test_tablemodel") +class TestGetterSetter: + """Class for testing methods that get or set.""" + + def on_succeed_get_attributes(self, attributes): + assert isinstance(attributes, dict) + assert _attributes["history_id"] == 1 + assert _attributes["description"] == "Integrated Circuit" + print("\033[36m\nsucceed_get_load_history_attributes topic was broadcast.") + + def on_succeed_get_data_manager_tree(self, tree): + assert isinstance(tree, Tree) + assert isinstance( + tree.get_node(1).data["load_history"], RAMSTKLoadHistoryRecord + ) + print("\033[36m\nsucceed_get_load_history_tree topic was broadcast") + + def on_succeed_set_attributes(self, tree): + assert isinstance(tree, Tree) + assert tree.get_node(1).data["load_history"].description == "Heavy melons" + print("\033[36m\nsucceed_get_load_history_tree topic was broadcast") + + @pytest.mark.integration + def test_do_get_attributes(self, test_tablemodel): + """do_get_attributes() should return a dict of site information attributes on + success.""" + pub.subscribe( + self.on_succeed_get_attributes, "succeed_get_load_history_attributes" + ) + + pub.sendMessage( + "request_get_load_history_attributes2", attributes={"history_id": 1} + ) + + pub.unsubscribe( + self.on_succeed_get_attributes, "succeed_get_load_history_attributes" + ) + + @pytest.mark.integration + def test_on_get_data_manager_tree(self, test_tablemodel): + """on_get_tree() should return the LoadHistory treelib Tree.""" + pub.subscribe( + self.on_succeed_get_data_manager_tree, "succeed_get_load_history_tree" + ) + + pub.sendMessage("request_get_load_history_tree") + + pub.unsubscribe( + self.on_succeed_get_data_manager_tree, "succeed_get_load_history_tree" + ) + + @pytest.mark.integration + def test_do_set_attributes(self, test_tablemodel): + """do_set_attributes() should return None when successfully setting site + information attributes.""" + pub.subscribe(self.on_succeed_set_attributes, "succeed_get_load_history_tree") + + pub.sendMessage( + "request_set_load_history_attributes", + node_id=1, + package={"description": "Heavy melons"}, + ) + + pub.unsubscribe(self.on_succeed_set_attributes, "succeed_get_load_history_tree") diff --git a/tests/models/commondb/load_history/load_history_unit_test.py b/tests/models/commondb/load_history/load_history_unit_test.py new file mode 100644 index 000000000..1fa4d5326 --- /dev/null +++ b/tests/models/commondb/load_history/load_history_unit_test.py @@ -0,0 +1,156 @@ +# pylint: skip-file +# type: ignore +# -*- coding: utf-8 -*- +# +# tests.models.commondb.load_history.load_history_unit_test.py is part of The +# RAMSTK +# Project +# +# All rights reserved. +# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland reliaqual com +"""Test class for testing Load History module algorithms and models.""" + +# Standard Library Imports +from datetime import date, timedelta + +# Third Party Imports +import pytest +from mocks import MockDAO +from pubsub import pub +from treelib import Tree + +# RAMSTK Package Imports +from ramstk.models import RAMSTKLoadHistoryRecord, RAMSTKLoadHistoryTable + + +@pytest.fixture(scope="function") +def test_tablemodel(mock_common_dao): + """Get a data manager instance for each test function.""" + # Create the device under test (dut) and connect to the database. + dut = RAMSTKLoadHistoryTable() + dut.do_connect(mock_common_dao) + + yield dut + + # Unsubscribe from pypubsub topics. + pub.unsubscribe(dut.do_get_attributes, "request_get_load_history_attributes") + pub.unsubscribe(dut.do_set_attributes, "request_set_load_history_attributes") + pub.unsubscribe(dut.do_update, "request_update_load_history") + pub.unsubscribe(dut.do_get_tree, "request_get_load_history_tree") + pub.unsubscribe(dut.do_select_all, "request_get_load_history_attributes") + + # Delete the device under test. + del dut + + +@pytest.mark.usefixtures("test_recordmodel", "test_tablemodel") +class TestCreateModels: + """Class for model initialization test suite.""" + + @pytest.mark.unit + def test_record_model_create(self, test_recordmodel): + """should return a record model instance.""" + assert isinstance(test_recordmodel, RAMSTKLoadHistoryRecord) + + # Verify class attributes are properly initialized. + assert test_recordmodel.__tablename__ == "ramstk_load_history" + assert test_recordmodel.history_id == 1 + assert test_recordmodel.description == "Histogram" + + @pytest.mark.unit + def test_table_model_create(self, test_tablemodel): + """__init__() should return a LoadHistory table model.""" + assert isinstance(test_tablemodel, RAMSTKLoadHistoryTable) + assert isinstance(test_tablemodel.tree, Tree) + assert isinstance(test_tablemodel.dao, MockDAO) + assert test_tablemodel._lst_id_columns == [ + "history_id", + ] + assert test_tablemodel._tag == "load_history" + assert test_tablemodel._root == 0 + + assert pub.isSubscribed( + test_tablemodel.do_get_attributes, "request_get_load_history_attributes" + ) + assert pub.isSubscribed( + test_tablemodel.do_get_tree, "request_get_load_history_tree" + ) + + +@pytest.mark.usefixtures("test_tablemodel") +class TestSelectMethods: + """Class for testing data manager select_all() and select() methods.""" + + @pytest.mark.unit + def test_do_select_all(self, test_tablemodel): + """do_select_all() should return a Tree() object populated with + RAMSTKProgramInfo and RAMSTKLoadHistoryRecord instances on success.""" + test_tablemodel.do_select_all({"history_id": 1}) + + assert isinstance(test_tablemodel.tree, Tree) + assert isinstance( + test_tablemodel.tree.get_node(1).data["load_history"], + RAMSTKLoadHistoryRecord, + ) + # There should be a root node with no data package and a node with + # the one RAMSTKLoadHistoryRecord record. + assert len(test_tablemodel.tree.all_nodes()) == 2 + + @pytest.mark.unit + def test_do_select(self, test_tablemodel): + """do_select() should return an instance of the RAMSTKLoadHistoryRecord on + success.""" + test_tablemodel.do_select_all({"history_id": 1}) + + _history = test_tablemodel.do_select(1) + + assert isinstance(_history, RAMSTKLoadHistoryRecord) + assert _history.history_id == 1 + assert _history.description == "Histogram" + + @pytest.mark.unit + def test_do_select_non_existent_id(self, test_tablemodel): + """do_select() should return None when a non-existent Options ID is + requested.""" + test_tablemodel.do_select_all({"history_id": 1}) + + assert test_tablemodel.do_select(100) is None + + +@pytest.mark.usefixtures("test_attributes", "test_recordmodel") +class TestGetterSetter: + """Class for testing methods that get or set.""" + + @pytest.mark.unit + def test_get_attributes(self, test_recordmodel): + """get_attributes() should return a tuple of attribute values.""" + _attributes = test_recordmodel.get_attributes() + assert _attributes["history_id"] == 1 + assert _attributes["description"] == "Histogram" + + @pytest.mark.unit + def test_set_attributes(self, test_attributes, test_recordmodel): + """set_attributes() should return a zero error code on success.""" + test_attributes.pop("history_id") + assert test_recordmodel.set_attributes(test_attributes) is None + + @pytest.mark.unit + def test_set_attributes_none_value(self, test_attributes, test_recordmodel): + """set_attributes() should set an attribute to it's default value when the + attribute is passed with a None value.""" + test_attributes["description"] = None + + test_attributes.pop("history_id") + assert test_recordmodel.set_attributes(test_attributes) is None + assert ( + test_recordmodel.get_attributes()["description"] + == "Load History Description" + ) + + @pytest.mark.unit + def test_set_attributes_unknown_attributes(self, test_attributes, test_recordmodel): + """set_attributes() should raise an AttributeError when passed an unknown + attribute.""" + test_attributes.pop("history_id") + with pytest.raises(AttributeError): + test_recordmodel.set_attributes({"shibboly-bibbly-boo": 0.9998}) diff --git a/tests/models/commondb/test_ramstkloadhistory.py b/tests/models/commondb/test_ramstkloadhistory.py deleted file mode 100644 index 0f0afb3f2..000000000 --- a/tests/models/commondb/test_ramstkloadhistory.py +++ /dev/null @@ -1,70 +0,0 @@ -# pylint: skip-file -# type: ignore -# -*- coding: utf-8 -*- -# -# tests.dao.commondb.test_ramstkloadhistory.py is part of The RAMSTK Project -# -# All rights reserved. -# Copyright 2007 - 2017 Doyle Rowland doyle.rowland reliaqual com -"""Test class for testing RAMSTKLoadHistory module algorithms and models.""" - -# Third Party Imports -import pytest - -# RAMSTK Package Imports -from ramstk.models.commondb import RAMSTKLoadHistory - -ATTRIBUTES = {"description": "Load History Description"} - - -@pytest.mark.usefixtures("test_common_dao") -class TestRAMSTKLoadHistory: - """Class for testing the RAMSTKLoadHistory model.""" - - @pytest.mark.integration - def test_ramstkloadhistory_create(self, test_common_dao): - """ __init__() should create an RAMSTKLoadHistory model.""" - DUT = test_common_dao.session.query(RAMSTKLoadHistory).first() - - assert isinstance(DUT, RAMSTKLoadHistory) - - # Verify class attributes are properly initialized. - assert DUT.__tablename__ == "ramstk_load_history" - assert DUT.history_id == 1 - assert DUT.description == "Cycle Counts" - - @pytest.mark.integration - def test_get_attributes(self, test_common_dao): - """ get_attributes() should return a dict of attribute:value pairs. """ - DUT = test_common_dao.session.query(RAMSTKLoadHistory).first() - - _attributes = DUT.get_attributes() - - assert isinstance(_attributes, dict) - assert _attributes["history_id"] == 1 - assert _attributes["description"] == "Cycle Counts" - - @pytest.mark.integration - def test_set_attributes(self, test_common_dao): - """ set_attributes() should return a zero error code on success. """ - DUT = test_common_dao.session.query(RAMSTKLoadHistory).first() - - assert DUT.set_attributes(ATTRIBUTES) is None - - @pytest.mark.integration - def test_set_attributes_none_value(self, test_common_dao): - """set_attributes() should set an attribute to it's default value when the attribute is passed with a None value.""" - DUT = test_common_dao.session.query(RAMSTKLoadHistory).first() - - ATTRIBUTES["description"] = None - - assert DUT.set_attributes(ATTRIBUTES) is None - assert DUT.get_attributes()["description"] == "Load History Description" - - @pytest.mark.integration - def test_set_attributes_unknown_attributes(self, test_common_dao): - """set_attributes() should raise an AttributeError when passed an unknown attribute.""" - DUT = test_common_dao.session.query(RAMSTKLoadHistory).first() - - with pytest.raises(AttributeError): - DUT.set_attributes({"shibboly-bibbly-boo": 0.9998}) diff --git a/tests/test_configuration.py b/tests/test_configuration.py index 1ba9f1664..f6ca946e9 100644 --- a/tests/test_configuration.py +++ b/tests/test_configuration.py @@ -7,6 +7,7 @@ # All rights reserved. """Test class for the Configuration module algorithms and models.""" + # Standard Library Imports import gettext import glob @@ -49,9 +50,9 @@ except IndexError: VIRTUAL_ENV = os.environ["VIRTUAL_ENV"] except KeyError: - if sys.platform == "Linux" or sys.platform == "linux": + if sys.platform in ["Linux", "linux"]: VIRTUAL_ENV = os.getenv("HOME") + "/.local" - elif sys.platform == "Windows" or sys.platform == "windows": + elif sys.platform in ["Windows", "windows"]: VIRTUAL_ENV = os.getenv("TEMP") else: print(("The {0:s} system platform is not " "supported.").format(sys.platform)) @@ -326,7 +327,7 @@ def test_initialize_site_configuration(self): # RAMSTK files will not be in the VIRTUAL_ENV, sys will not have the # real_prefix attribute. In this case, skip these tests. if hasattr(sys, "real_prefix"): - if sys.platform == "linux" or sys.platform == "linux2": + if sys.platform in ["linux", "linux2"]: assert DUT.RAMSTK_SITE_DIR == VIRTUAL_ENV + "/share/RAMSTK" elif sys.platform == "win32": assert DUT.RAMSTK_SITE_DIR == VIRTUAL_ENV + "/RAMSTK" @@ -378,7 +379,7 @@ def test_initialize_user_configuration(self): # won't be testing files installed in the VIRTUAL_ENV. Since the # RAMSTK files will not be in the VIRTUAL_ENV, sys will not have the # real_prefix attribute. In this case, skip these tests. - if sys.platform == "linux" or sys.platform == "linux2": + if sys.platform in ["linux", "linux2"]: assert DUT.RAMSTK_OS == "Linux" assert DUT.RAMSTK_HOME_DIR == os.environ["HOME"] if hasattr(sys, "real_prefix"):