Unit Testing (Part - 1): Introduction


  • Generally, we all think that testing means it is part of testers or QA team, but it is wrong assumption.
  • Testing which is done at developer level is called Unit Testing.
  • Generally testing is divided into two type
    • Unit Testing
    • Integration Testing
  • Unit Testing: 
    • The process of testing, whether a  particular unit is working properly or not.
    • Developer level testing
    • white box testing
  • Integration Testing: 
    • The process of testing total application (ie., end to end testing) 
    • QA/testing Team level testing
    • Black Box testing


Django: if the column is there in database and fields are not there in model.py then how to remove the column from database

command used
==============

python manage.py schemamigration common --auto
python manage.py migrate common --fake
python manage.py migrate common --list
python manage.py migrate common

============
add the fields in model
================

(cpi) user1@BLRPROFLOWD01:~/projects/cpi/code/cpi_mrppython manage.py schemamigration common --auto
 + Added field slt_estimated_time on common.Process
Created 0214_auto__add_field_process_slt_estimated_time.py. You can now apply this migration with: ./manage.py migrate common

-----------------

(cpi) user1@BLRPROFLOWD01:~/projects/cpi/code/cpi_mrp$ python manage.py migrate common --fake
Running migrations for common:
 - Migrating forwards to 0214_auto__add_field_process_slt_estimated_time.
 > common:0214_auto__add_field_process_slt_estimated_time
   (faked)
Installing /home/user1/projects/cpi/code/cpi_mrp/apps/common/customsql/alive_orders.postgresql.sql
Installing /home/user1/projects/cpi/code/cpi_mrp/apps/common/customsql/working_time.postgresql.sql
Installing /home/user1/projects/cpi/code/cpi_mrp/apps/common/customsql/workingorder.postgresql.sql

-------------------

(cpi) user1@BLRPROFLOWD01:~/projects/cpi/code/cpi_mrp$ python manage.py migrate common --list

 common
  (*) 0001_initial
  (*) 0002_fake_to_pospone_initial_data_load
  (*) 0003_auto__add_field_customer_priority
  (*) 0004_add_set_customer_priority_permission
  (*) 0005_auto__add_field_workingorder_priority
  (*) 0006_can_change_wo_priority
  (*) 0007_auto__add_field_part_cached_raw_area__add_field_part_cached_units_of_c
  (*) 0008_set_part_cached_area_and_units_of_capacity
  (*) 0009_auto__add_field_prime_priority
  (*) 0010_Add_set_prime_priority_permission
  (*) 0011_auto__add_field_process_capacity
  (*) 0012_process_capacity_perm
  (*) 0013_auto__add_field_workingorder_critical_ratio
  (*) 0014_rename_wo_priority_to_cs_priority
  (*) 0015_auto__chg_field_workingorder_critical_ratio
  (*) 0016_add_change_wo_notes_permission
  (*) 0017_auto__chg_field_cert_msword_version__chg_field_workingorder_msword_ver
  (*) 0018_auto__chg_field_historylog_user
  (*) 0019_auto__add_field_process_is_packing
  (*) 0020_auto__add_field_sequencenode_estimated_time
  (*) 0021_add_can_unhold_order_permission
  (*) 0022_copy_process_lead_time_to_node
  (*) 0023_auto__chg_field_sequencenode_estimated_time
  (*) 0024_auto__add_field_workingorder_release_date
  (*) 0025_auto__add_estimatedtime__add_unique_estimatedtime_part_process
  (*) 0026_add_can_set_expected_date
  (*) 0027_auto__del_field_workingorder_release_date__add_field_workingorder_crit
  (*) 0028_part_cached_uoc_not_null
  (*) 0029_auto__chg_field_part_cached_units_of_capacity
  (*) 0030_auto__add_field_customer_is_out_of_town_shipment
  (*) 0031_out_of_town_shipment
  (*) 0032_auto__add_field_sequencenode_do_not_cert
  (*) 0033_add_can_set_no_cert_to_process_permission
  (*) 0034_auto__add_cspriority
  (*) 0035_create_cspriority_instances
  (*) 0036_auto__chg_field_workingorder_cs_priority__chg_field_cspriority_value
  (*) 0037_auto__add_restrictreason__add_field_specification_restrict_reason
  (*) 0038_auto__add_field_specification_print_reason_in_cert__del_field_restrict
  (*) 0039_add_working_order_in_containment_field
  (*) 0040_add_continment_permissions
  (*) 0041_fix_perm_typo
  (*) 0042_rename_parts_unit_of_capacity_to_units_of_load
  (*) 0043_auto__add_field_invoice_date_sent
  (*) 0044_add_edit_sent_status_permission
  (*) 0045_auto__chg_field_rfqfile_file
  (*) 0046_auto__chg_field_workingorder_cs_priority
  (*) 0047_auto__chg_field_cspriority_value
  (*) 0048_auto__add_field_estimatedtime_locked
  (*) 0049_auto__chg_field_customer_phone_number__chg_field_customer_fax_number__
  (*) 0050_auto__add_field_workingorder_invoice_as_exception
  (*) 0051_add_change_invoice_as_exception_permission
  (*) 0052_auto__add_field_workingorder_tracking_number
  (*) 0053_add_can_set_tracking_number_permission
  (*) 0054_auto__add_field_restrictreason_time_before_next
  (*) 0055_fix_typo_in_history_log
  (*) 0056_auto__add_field_customer_responsable
  (*) 0057_add_permission_customer_responsables
  (*) 0058_auto__add_field_workingorder_is_internal_rework
  (*) 0059_create_can_change_is_internal_rework_permission
  (*) 0060_rename_permission
  (*) 0061_rename_field_customer_responsible
  (*) 0062_auto__add_field_userprofile_itar_unrestricted
  (*) 0063_itar_unrestricted_default
  (*) 0064_auto__add_field_pai_revision_number
  (*) 0065_auto__del_configvariable__del_field_sequencenode_pds_version_id
  (*) 0066_auto__del_configimagevariable
  (*) 0067_auto__add_plant
  (*) 0068_auto__add_field_process_facility_plant
  (*) 0069_auto__add_popaccount__add_smtpaccount
  (*) 0070_auto__add_facility
  (*) 0071_auto__del_field_facility_rfq_email__add_field_facility_rfq_account
  (*) 0072_auto__add_field_customerrequest_is_taxes_required
  (*) 0073_auto__add_field_specification_spec_title
  (*) 0074_add_permission_to_change_is_taxes_required
  (*) 0075_auto__add_field_facility_short_name
  (*) 0076_auto__add_field_facility_invoice_report_recipients
  (*) 0077_auto__del_field_facility_short_name
  (*) 0078_auto__add_field_facility_wo_archive_url
  (*) 0079_auto__chg_field_userprofile_user
  (*) 0080_auto__chg_field_rfq_from_email_address
  (*) 0081_auto__add_field_process_is_frozen
  (*) 0082_auto__chg_field_contact_email
  (*) 0083_auto__chg_field_line_guide_plan__add_field_facility_invoice_email_body
  (*) 0084_auto__chg_field_line_guide_plan__add_field_processdatasheet_is_frozen_
  (*) 0085_auto__add_field_pai_app_temperature_min__add_field_pai_app_temperature
  (*) 0086_auto__add_field_pai_description
  (*) 0087_auto__add_field_pai_induction_time_min__add_field_pai_induction_time_m
  (*) 0088_induction_time_to_induction_time_min_and_max
  (*) 0089_auto__del_field_pai_induction_time
  (*) 0090_auto__del_field_pai_drying_time__add_field_pai_drying_time_min__add_fi
  (*) 0091_fill_pai_drying_time_max
  (*) 0092_auto__add_field_pai_show_notes
  (*) 0093_create_can_change_order_freeze_status_permission
  (*) 0094_auto__chg_field_line_guide_plan__add_field_cert_facility_plant__chg_fi
  (*) 0095_add_facility_plant_to_certs
  (*) 0096_auto__add_field_guideplan_requested_freeze_user__add_field_guideplan_r
  (*) 0097_auto__del_field_guideplan_freeze_name__add_field_guideplan_frozen_plan
  (*) 0098_auto__add_field_process_statement__add_field_process_show_statement
  (*) 0099_auto__add_partattachedfile
  (*) 0100_auto__add_field_part_lock_attachments
  (*) 0101_auto__add_field_process_show_on_cert
  (*) 0102_auto__add_field_processstep_notes_on_pds
  (*) 0103_auto__add_field_specification_limited_approval
  (*) 0104_permission_edit_gp_in_bulk
  (*) 0105_add_permission_to_unship
  (*) 0106_auto__add_field_processnote_spec
  (*) 0107_auto__add_woattachment
  (*) 0108_auto__add_field_productcode_stock
  (*) 0109_add_show_jump_to_free_form_button_perm
  (*) 0110_auto__add_processcategory__add_field_process_category
  (*) 0111_auto__add_creditterm__add_unique_creditterm_name_days_to_pay__chg_fiel
  (*) 0112_create_default_credit_terms
  (*) 0113_auto__add_field_invoice_id_code
  (*) 0114_migrate_PAI_stock_to_ProductCode_stock
  (*) 0115_auto__del_field_pai_not_stocked
  (*) 0116_auto__add_field_processnote_show_on_wo
  (*) 0117_auto__add_measureunit
  (*) 0118_auto__del_field_processnote_show_on_wo
  (*) 0119_auto__add_processnotecertparameter
  (*) 0120_auto__add_field_cert_rejections
  (*) 0121_auto__add_field_measureunit_is_for_conductivity__add_field_measureunit
  (*) 0122_auto__add_certparameterdetail__add_field_certprocessdetail_part_hardne
  (*) 0123_auto__add_field_processdatasheet_statement
  (*) 0124_auto__add_field_process_is_hardness__add_field_process_is_conductivity
  (*) 0125_auto__add_field_facility_invoice_display_default
  (*) 0126_auto__add_field_customer_invoice_display_mode
  (*) 0127_auto__add_field_workingorder_shop_status
  (*) 0128_auto__add_field_invoice_min_lot_charge
  (*) 0129_auto__add_field_customer_cert_notes__add_field_customer_include_cert_n
  (*) 0130_add_can_enable_cert_notes_permission
  (*) 0131_auto__add_field_processnotecertparameter_plain_parameter
  (*) 0132_auto__chg_field_pai_thickness_min__chg_field_pai_thickness_max
  (*) 0133_auto__chg_field_invoice_min_lot_charge
  (*) 0134_auto__add_field_invoice_price_method
  (*) 0135_add_permission_to_select_material_condition_on_wo_lines
  (*) 0136_auto__add_field_creditnote_notes
  (*) 0137_auto__add_field_sequencenode_editable
  (*) 0138_set_editable_value_on_sequencenodes
  (*) 0139_auto__add_field_pai_show_notes_on_cert
  (*) 0140_auto__add_field_process_lockheed_process_code__add_field_customer_lock
  (*) 0141_add_can_view_lockheed_report_perm
  (*) 0142_add_permission_to_move_from_needs_leave_time_to_needs_plan
  (*) 0143_auto__add_field_certparameterdetail_sequence_node
  (*) 0144_remove_view_late_jobs_permission
  (*) 0145_auto__add_field_pai_active
  (*) 0146_add_activate_or_inactivate_permission_for_PAIs
  (*) 0147_auto__chg_field_specificationrevision_status
  (*) 0148_add_change_parts_dimensions_permission
  (*) 0149_auto__add_field_specification_is_active
  (*) 0150_data_migration_delete_customer_comments
  (*) 0151_auto__del_field_customer_comments
  (*) 0152_auto__add_field_specificationrevision_effective_date__add_field_specif
  (*) 0153_auto__add_field_historylog_process_group
  (*) 0154_remove_change_wo_material_permission
  (*) 0155_auto__add_field_task_state
  (*) 0156_existing_tasks_state
  (*) 0157_permission_add_change_estimated_time_and_target_date_of_wo
  (*) 0158_auto__add_taskcategory
  (*) 0159_load_internal_task_categories
  (*) 0160_auto__chg_field_task_category__add_index_task_category
  (*) 0161_auto__add_field_workingorder_original_target_date
  (*) 0162_data_migration_original_target_date
  (*) 0163_add_permissions_for_tasks_to_csm
  (*) 0164_create_task_category_for_leadtime_change
  (*) 0165_auto__add_field_pai_oven_number
  (*) 0166_auto__add_field_guideplannode_heat_treatment_range
  (*) 0167_auto__add_field_process_time_track
  (*) 0168_permission_to_set_process_time_track
  (*) 0169_auto__del_unique_customer_lockheed_supplier_code
  (*) 0170_auto__add_field_specification_lockheed_code
  (*) 0171_auto__del_field_process_lockheed_process_code
  (*) 0172_auto__add_field_process_suggested_estimated_time
  (*) 0173_initial_estimated_times
  (*) 0174_permission_for_restricted_settings
  (*) 0175_auto__add_unique_process_facility_plant_name
  (*) 0176_auto__add_unique_specification_name
  (*) 0177_auto__add_unique_materialtype_name
  (*) 0178_auto__add_unique_materialgroup_name
  (*) 0179_auto__add_unique_materialkind_name
  (*) 0180_migrate_permission_from_pex_to_shopstatus
  (*) 0181_auto__chg_field_userprofile_signature
  (*) 0182_auto__chg_field_task_creation_date
  (*) 0183_auto__chg_field_certstampperseqnode_seq_node__add_unique_certstamppers
  (*) 0184_auto__add_field_customer_email_confirmation_mode
  (*) 0185_auto__add_field_contact_active
  (*) 0186_auto__add_field_workingorder_email_confirmation_date
  (*) 0187_auto__add_field_facility_wo_confirmation_account
  (*) 0188_auto__add_field_facility_needs_quote_default
  (*) 0189_auto__add_field_facility_address
  (*) 0190_auto__del_field_facility_address
  (*) 0191_auto__add_field_workingorder_original_customer_expected_date
  (*) 0192_auto__add_field_customer_quote_display_mode
  (*) 0193_auto__del_field_workingorder_original_customer_expected_date
  (*) 0194_auto__add_field_workingorder_original_customer_expected_date
  (*) 0195_auto__add_field_contact_email_per_invoice
  (*) 0199_auto__add_field_contact_email_per_invoice
  (*) 0204_auto__add_field_guideplannode_pds
  (*) 0207_auto__del_field_guideplannode_pds
  (*) 0208_auto__add_slthistory
  (*) 0209_auto__add_field_slthistory_creation_date__add_field_slthistory_descrip
  (*) 0210_auto__chg_field_slthistory_creation_date
  (*) 0211_auto__add_sltcategory
  (*) 0213_auto__add_field_contact_delete_button
  (*) 0214_auto__add_field_process_slt_estimated_time

====================
Remove the field from model.py
===================

(cpi) user1@BLRPROFLOWD01:~/projects/cpi/code/cpi_mrp$ python manage.py schemamigration common --auto
 - Deleted field slt_estimated_time on common.Process
Created 0215_auto__del_field_process_slt_estimated_time.py. You can now apply this migration with: ./manage.py migrate common

----------

(cpi) user1@BLRPROFLOWD01:~/projects/cpi/code/cpi_mrp$ python manage.py migrate common
Running migrations for common:
 - Migrating forwards to 0215_auto__del_field_process_slt_estimated_time.
 > common:0215_auto__del_field_process_slt_estimated_time
 - Loading initial data for common.
Installed 50 object(s) from 1 fixture(s)
Installing /home/user1/projects/cpi/code/cpi_mrp/apps/common/customsql/alive_orders.postgresql.sql
Installing /home/user1/projects/cpi/code/cpi_mrp/apps/common/customsql/working_time.postgresql.sql
Installing /home/user1/projects/cpi/code/cpi_mrp/apps/common/customsql/workingorder.postgresql.sql


Angularjs is not provide for configuration blocks

This post explains why services aren't available in configuration blocks.
AngularJS has a concept of $injector which has a function called invoke().
AngularJS has two injectors. They are:
  • instanceInjector
  • providerInjector

instanceInjector, or what we generally call $injector, can provide access to a service in either of the following ways:
  • instantiate the service. Once instantiated instanceInjector caches the service
  • get the service from cache if its alreay in cache
At low level, Controller or Service code is executed by $injector.invoke(). And this $injector knows a way to reach the services in one of the two ways mentioned above.
During configuration phase, i.e when configuration block is executed, $injector i.e instanceInjector isn't available. So instanceInjector cache isn't available too and so services aren't accessible in configuration blocks.
Try to access a service in configuration block and it will fail:
angular.module("core", []);
angular
    .module("core")
    .service("ProfileService", function () {
        var profile = {'name': 'hardcoded name'};
        return {
            'profile': profile;
        }
    });
Try to access this service in config block
angular
    .module("core")
    .config(["ProfileService", function (ProfileService) {
    }]);
This failed because $injector isn't available when config block executed.
Also there shouldn't be a need to access services in configuration blocks. Configuration blocks are meant to configure things, eg: to configure a constant which will be used throughout the angular app. And services are meant to keep business logic. There shouldn't be need to use business logic during configuration phase.

What is the difference between render and render-to-response

Render:

it will send the variable in context to the html page
Syntax-
return render(request,"x.html",response)


Render to response:it will also send the result like some validation
Syntax-
return render_to_response("x.html",context)



How to set the button in admin page for django framework

  • Documentation version: development

Admin actions

The basic workflow of Django’s admin is, in a nutshell, “select an object, then change it.” This works well for a majority of use cases. However, if you need to make the same change to many objects at once, this workflow can be quite tedious.
In these cases, Django’s admin lets you write and register “actions” – simple functions that get called with a list of objects selected on the change list page.
If you look at any change list in the admin, you’ll see this feature in action; Django ships with a “delete selected objects” action available to all models. For example, here’s the user module from Django’s built-indjango.contrib.auth app:

Render and render to response in view django


Django “render” vs “render_to_response”


Summary: Always use render and not render_to_response
In Django you have more than one way to return a response, but many times I get confused between render and render_to_response, render_to_response seems shorter, so why not use it!
To explain let’s assume simple posts page:
def article_list(request, template_name='article/list.html'):
    posts = Post.objects.all()
    # DON'T USE
    return render_to_response(template_name, {'posts': posts})
In this example you will be able to access “posts” in your template, but unfortunately you will not have access to other important variables from other Middlewares, most importantly: user, csrf_token, and messages. To make “render_to_response” pass all these parameters you must send a “context_instance” like this:
return render_to_response(template_name, {'posts': posts}, context_instance=RequestContext(request))
Not so short after all, compare to “render” version:
# USE THIS :)
return render(request, template_name, {'posts': posts})
In fact “render” is always shorter than “render_to_response”, even without the “context_instance”:
return render(request, template_name, {'posts': posts})
... vs ...
return render_to_response(template_name, {'posts': posts})

How to create sample pdf file using Python and django?


Process :1

step 1: run this cmd:  pip install reportlab


step2: Create a file with below code.


from reportlab.pdfgen import canvas

c=canvas.Canvas("mypdf.pdf")
c.drawString(150,180,"This is sample pdf")
c.save()


Process :2

Python : 2.7
Django :1.11

1.pip install xhtml2pdf html5lib pypdf html5lib==1.0b8

2.create python file pdfgenerator.py

import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template,render_to_string
from django.template import Context
from django.http import HttpResponse
from cgi import escape
# from django.shortcuts import renderfrom django.shortcuts import render_to_response

def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(Context)
    html = template.render(context_dict)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

place the python in  pdfgenerator.py file

 3.Create method in views.py

Note:

from app.pdfgenerator import render_to_pdf 

def pdf_page(request,pk):

    print "pdf print...."
        context = {'pagesize':'A4','test':test}
        return render_to_pdf('mytemplate.html',context)


4.create mytemplate.html in templates directory.



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p> Html to PDF generator.....with python 2.7 and django 1.11</p>
</body>
</html>      
 

5. add the below url in url.py

url(r'^pdf_page/$', views.pdf_page,name='pdf_page'),


Done.......


Name and explain the three magic methods of Python that are used in the construction and initialization of custom Objects?

  • The 3 magic methods of Python that are used in the construction and initialization of custom Objects are:
    •  init__, 
    • new , and 
    • del__.
  • new – 
    • this method can be considered as a “constructor”. 
    • It is invoked to create an instance of a class with the statement say, 
      • myObj = MyClass()
  • init__ — 
    • It is an “initializer”/ “constructor” method. 
    • It is invoked whenever any arguments are passed at the time of creating an object. 
      • myObj = MyClass(‘Pizza’,25)
  • del- 
    • this method is a “destructor” of the class. 
    • Whenever an object is deleted,invocation of del__ takes place and it defines behaviour during the garbage collection. 
      • Note: new , del are rarely used explicitly.

What is Web Scraping? How do you achieve it in Python?


  • Web Scrapping is a way of extracting the large amounts of information which is available on the web sites and saving it onto the local machine or onto the database tables.
  • In order to scrap the web:load the web page which is interesting to you. 
  • To load the web page, use “requests” module.
  • parse HTML from the web page to find the interesting information.
  • Python has few modules for scraping the web. 
  • They are urllib2, scrapy, pyquery, BeautifulSoap, etc.

ajax syntax sample

$("button").click(
        function()
            {
                      $.ajax(
                {
                    url:"",
                                        success:function(result){
                                  $("#div").html(result);
                                  }
                }
            );
              }
        );

How to reverse the element in list without the reverse method

>>l = [1,2,3,4,5]
>>> l
[1, 2, 3, 4, 5]
>>> l[::-1]
[5, 4, 3, 2, 1]
>>>

Describe how to send mail from a Python script.

  • The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine.
  • A sample email is demonstrated below.
import smtplib
SERVER = smtplib.SMTP(‘smtp.server.domain’)
FROM = sender@mail.com
TO = ["user@mail.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."

# Main message
message = """
From: Sarah Naaz < sender@mail.com >
To: CarreerRide user@mail.com
Subject: SMTP email msg
This is a test email. Acknowledge the email by responding.
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

Explain how to overload constructors (or methods) in Python.

  • _init__ () is a first method defined in a class. 
  • when an instance of a class is created, python calls __init__() to initialize the attribute of the object.
Following example demonstrate further:

class Employee:

      def __init__(self, name, empCode,pay):
            self.name=name
            self.empCode=empCode
            self.pay=pay


e1 = Employee("Sarah",99,30000.00)
e2 = Employee("Asrar",100,60000.00)
print("Employee Details:")
print(" Name:",e1.name,"Code:", e1.empCode,"Pay:", e1.pay)
print(" Name:",e2.name,"Code:", e2.empCode,"Pay:", e2.pay)
---------------------------------------------------------------
Output
Employee Details:
(' Name:', 'Sarah', 'Code:', 99, 'Pay:', 30000.0)
(' Name:', 'Asrar', 'Code:', 100, 'Pay:', 60000.0)